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

1.310   ! brouard     1: /* $Id: imach.c,v 1.309 2021/05/20 12:39:14 brouard Exp $
1.126     brouard     2:   $State: Exp $
1.163     brouard     3:   $Log: imach.c,v $
1.310   ! brouard     4:   Revision 1.309  2021/05/20 12:39:14  brouard
        !             5:   Summary: Version 0.99r24
        !             6: 
1.309     brouard     7:   Revision 1.308  2021/03/31 13:11:57  brouard
                      8:   Summary: Version 0.99r23
                      9: 
                     10: 
                     11:   * imach.c (Module): Still bugs in the result loop. Thank to Holly Benett
                     12: 
1.308     brouard    13:   Revision 1.307  2021/03/08 18:11:32  brouard
                     14:   Summary: 0.99r22 fixed bug on result:
                     15: 
1.307     brouard    16:   Revision 1.306  2021/02/20 15:44:02  brouard
                     17:   Summary: Version 0.99r21
                     18: 
                     19:   * imach.c (Module): Fix bug on quitting after result lines!
                     20:   (Module): Version 0.99r21
                     21: 
1.306     brouard    22:   Revision 1.305  2021/02/20 15:28:30  brouard
                     23:   * imach.c (Module): Fix bug on quitting after result lines!
                     24: 
1.305     brouard    25:   Revision 1.304  2021/02/12 11:34:20  brouard
                     26:   * imach.c (Module): The use of a Windows BOM (huge) file is now an error
                     27: 
1.304     brouard    28:   Revision 1.303  2021/02/11 19:50:15  brouard
                     29:   *  (Module): imach.c Someone entered 'results:' instead of 'result:'. Now it is an error which is printed.
                     30: 
1.303     brouard    31:   Revision 1.302  2020/02/22 21:00:05  brouard
                     32:   *  (Module): imach.c Update mle=-3 (for computing Life expectancy
                     33:   and life table from the data without any state)
                     34: 
1.302     brouard    35:   Revision 1.301  2019/06/04 13:51:20  brouard
                     36:   Summary: Error in 'r'parameter file backcast yearsbproj instead of yearsfproj
                     37: 
1.301     brouard    38:   Revision 1.300  2019/05/22 19:09:45  brouard
                     39:   Summary: version 0.99r19 of May 2019
                     40: 
1.300     brouard    41:   Revision 1.299  2019/05/22 18:37:08  brouard
                     42:   Summary: Cleaned 0.99r19
                     43: 
1.299     brouard    44:   Revision 1.298  2019/05/22 18:19:56  brouard
                     45:   *** empty log message ***
                     46: 
1.298     brouard    47:   Revision 1.297  2019/05/22 17:56:10  brouard
                     48:   Summary: Fix bug by moving date2dmy and nhstepm which gaefin=-1
                     49: 
1.297     brouard    50:   Revision 1.296  2019/05/20 13:03:18  brouard
                     51:   Summary: Projection syntax simplified
                     52: 
                     53: 
                     54:   We can now start projections, forward or backward, from the mean date
                     55:   of inteviews up to or down to a number of years of projection:
                     56:   prevforecast=1 yearsfproj=15.3 mobil_average=0
                     57:   or
                     58:   prevforecast=1 starting-proj-date=1/1/2007 final-proj-date=12/31/2017 mobil_average=0
                     59:   or
                     60:   prevbackcast=1 yearsbproj=12.3 mobil_average=1
                     61:   or
                     62:   prevbackcast=1 starting-back-date=1/10/1999 final-back-date=1/1/1985 mobil_average=1
                     63: 
1.296     brouard    64:   Revision 1.295  2019/05/18 09:52:50  brouard
                     65:   Summary: doxygen tex bug
                     66: 
1.295     brouard    67:   Revision 1.294  2019/05/16 14:54:33  brouard
                     68:   Summary: There was some wrong lines added
                     69: 
1.294     brouard    70:   Revision 1.293  2019/05/09 15:17:34  brouard
                     71:   *** empty log message ***
                     72: 
1.293     brouard    73:   Revision 1.292  2019/05/09 14:17:20  brouard
                     74:   Summary: Some updates
                     75: 
1.292     brouard    76:   Revision 1.291  2019/05/09 13:44:18  brouard
                     77:   Summary: Before ncovmax
                     78: 
1.291     brouard    79:   Revision 1.290  2019/05/09 13:39:37  brouard
                     80:   Summary: 0.99r18 unlimited number of individuals
                     81: 
                     82:   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.
                     83: 
1.290     brouard    84:   Revision 1.289  2018/12/13 09:16:26  brouard
                     85:   Summary: Bug for young ages (<-30) will be in r17
                     86: 
1.289     brouard    87:   Revision 1.288  2018/05/02 20:58:27  brouard
                     88:   Summary: Some bugs fixed
                     89: 
1.288     brouard    90:   Revision 1.287  2018/05/01 17:57:25  brouard
                     91:   Summary: Bug fixed by providing frequencies only for non missing covariates
                     92: 
1.287     brouard    93:   Revision 1.286  2018/04/27 14:27:04  brouard
                     94:   Summary: some minor bugs
                     95: 
1.286     brouard    96:   Revision 1.285  2018/04/21 21:02:16  brouard
                     97:   Summary: Some bugs fixed, valgrind tested
                     98: 
1.285     brouard    99:   Revision 1.284  2018/04/20 05:22:13  brouard
                    100:   Summary: Computing mean and stdeviation of fixed quantitative variables
                    101: 
1.284     brouard   102:   Revision 1.283  2018/04/19 14:49:16  brouard
                    103:   Summary: Some minor bugs fixed
                    104: 
1.283     brouard   105:   Revision 1.282  2018/02/27 22:50:02  brouard
                    106:   *** empty log message ***
                    107: 
1.282     brouard   108:   Revision 1.281  2018/02/27 19:25:23  brouard
                    109:   Summary: Adding second argument for quitting
                    110: 
1.281     brouard   111:   Revision 1.280  2018/02/21 07:58:13  brouard
                    112:   Summary: 0.99r15
                    113: 
                    114:   New Makefile with recent VirtualBox 5.26. Bug in sqrt negatve in imach.c
                    115: 
1.280     brouard   116:   Revision 1.279  2017/07/20 13:35:01  brouard
                    117:   Summary: temporary working
                    118: 
1.279     brouard   119:   Revision 1.278  2017/07/19 14:09:02  brouard
                    120:   Summary: Bug for mobil_average=0 and prevforecast fixed(?)
                    121: 
1.278     brouard   122:   Revision 1.277  2017/07/17 08:53:49  brouard
                    123:   Summary: BOM files can be read now
                    124: 
1.277     brouard   125:   Revision 1.276  2017/06/30 15:48:31  brouard
                    126:   Summary: Graphs improvements
                    127: 
1.276     brouard   128:   Revision 1.275  2017/06/30 13:39:33  brouard
                    129:   Summary: Saito's color
                    130: 
1.275     brouard   131:   Revision 1.274  2017/06/29 09:47:08  brouard
                    132:   Summary: Version 0.99r14
                    133: 
1.274     brouard   134:   Revision 1.273  2017/06/27 11:06:02  brouard
                    135:   Summary: More documentation on projections
                    136: 
1.273     brouard   137:   Revision 1.272  2017/06/27 10:22:40  brouard
                    138:   Summary: Color of backprojection changed from 6 to 5(yellow)
                    139: 
1.272     brouard   140:   Revision 1.271  2017/06/27 10:17:50  brouard
                    141:   Summary: Some bug with rint
                    142: 
1.271     brouard   143:   Revision 1.270  2017/05/24 05:45:29  brouard
                    144:   *** empty log message ***
                    145: 
1.270     brouard   146:   Revision 1.269  2017/05/23 08:39:25  brouard
                    147:   Summary: Code into subroutine, cleanings
                    148: 
1.269     brouard   149:   Revision 1.268  2017/05/18 20:09:32  brouard
                    150:   Summary: backprojection and confidence intervals of backprevalence
                    151: 
1.268     brouard   152:   Revision 1.267  2017/05/13 10:25:05  brouard
                    153:   Summary: temporary save for backprojection
                    154: 
1.267     brouard   155:   Revision 1.266  2017/05/13 07:26:12  brouard
                    156:   Summary: Version 0.99r13 (improvements and bugs fixed)
                    157: 
1.266     brouard   158:   Revision 1.265  2017/04/26 16:22:11  brouard
                    159:   Summary: imach 0.99r13 Some bugs fixed
                    160: 
1.265     brouard   161:   Revision 1.264  2017/04/26 06:01:29  brouard
                    162:   Summary: Labels in graphs
                    163: 
1.264     brouard   164:   Revision 1.263  2017/04/24 15:23:15  brouard
                    165:   Summary: to save
                    166: 
1.263     brouard   167:   Revision 1.262  2017/04/18 16:48:12  brouard
                    168:   *** empty log message ***
                    169: 
1.262     brouard   170:   Revision 1.261  2017/04/05 10:14:09  brouard
                    171:   Summary: Bug in E_ as well as in T_ fixed nres-1 vs k1-1
                    172: 
1.261     brouard   173:   Revision 1.260  2017/04/04 17:46:59  brouard
                    174:   Summary: Gnuplot indexations fixed (humm)
                    175: 
1.260     brouard   176:   Revision 1.259  2017/04/04 13:01:16  brouard
                    177:   Summary: Some errors to warnings only if date of death is unknown but status is death we could set to pi3
                    178: 
1.259     brouard   179:   Revision 1.258  2017/04/03 10:17:47  brouard
                    180:   Summary: Version 0.99r12
                    181: 
                    182:   Some cleanings, conformed with updated documentation.
                    183: 
1.258     brouard   184:   Revision 1.257  2017/03/29 16:53:30  brouard
                    185:   Summary: Temp
                    186: 
1.257     brouard   187:   Revision 1.256  2017/03/27 05:50:23  brouard
                    188:   Summary: Temporary
                    189: 
1.256     brouard   190:   Revision 1.255  2017/03/08 16:02:28  brouard
                    191:   Summary: IMaCh version 0.99r10 bugs in gnuplot fixed
                    192: 
1.255     brouard   193:   Revision 1.254  2017/03/08 07:13:00  brouard
                    194:   Summary: Fixing data parameter line
                    195: 
1.254     brouard   196:   Revision 1.253  2016/12/15 11:59:41  brouard
                    197:   Summary: 0.99 in progress
                    198: 
1.253     brouard   199:   Revision 1.252  2016/09/15 21:15:37  brouard
                    200:   *** empty log message ***
                    201: 
1.252     brouard   202:   Revision 1.251  2016/09/15 15:01:13  brouard
                    203:   Summary: not working
                    204: 
1.251     brouard   205:   Revision 1.250  2016/09/08 16:07:27  brouard
                    206:   Summary: continue
                    207: 
1.250     brouard   208:   Revision 1.249  2016/09/07 17:14:18  brouard
                    209:   Summary: Starting values from frequencies
                    210: 
1.249     brouard   211:   Revision 1.248  2016/09/07 14:10:18  brouard
                    212:   *** empty log message ***
                    213: 
1.248     brouard   214:   Revision 1.247  2016/09/02 11:11:21  brouard
                    215:   *** empty log message ***
                    216: 
1.247     brouard   217:   Revision 1.246  2016/09/02 08:49:22  brouard
                    218:   *** empty log message ***
                    219: 
1.246     brouard   220:   Revision 1.245  2016/09/02 07:25:01  brouard
                    221:   *** empty log message ***
                    222: 
1.245     brouard   223:   Revision 1.244  2016/09/02 07:17:34  brouard
                    224:   *** empty log message ***
                    225: 
1.244     brouard   226:   Revision 1.243  2016/09/02 06:45:35  brouard
                    227:   *** empty log message ***
                    228: 
1.243     brouard   229:   Revision 1.242  2016/08/30 15:01:20  brouard
                    230:   Summary: Fixing a lots
                    231: 
1.242     brouard   232:   Revision 1.241  2016/08/29 17:17:25  brouard
                    233:   Summary: gnuplot problem in Back projection to fix
                    234: 
1.241     brouard   235:   Revision 1.240  2016/08/29 07:53:18  brouard
                    236:   Summary: Better
                    237: 
1.240     brouard   238:   Revision 1.239  2016/08/26 15:51:03  brouard
                    239:   Summary: Improvement in Powell output in order to copy and paste
                    240: 
                    241:   Author:
                    242: 
1.239     brouard   243:   Revision 1.238  2016/08/26 14:23:35  brouard
                    244:   Summary: Starting tests of 0.99
                    245: 
1.238     brouard   246:   Revision 1.237  2016/08/26 09:20:19  brouard
                    247:   Summary: to valgrind
                    248: 
1.237     brouard   249:   Revision 1.236  2016/08/25 10:50:18  brouard
                    250:   *** empty log message ***
                    251: 
1.236     brouard   252:   Revision 1.235  2016/08/25 06:59:23  brouard
                    253:   *** empty log message ***
                    254: 
1.235     brouard   255:   Revision 1.234  2016/08/23 16:51:20  brouard
                    256:   *** empty log message ***
                    257: 
1.234     brouard   258:   Revision 1.233  2016/08/23 07:40:50  brouard
                    259:   Summary: not working
                    260: 
1.233     brouard   261:   Revision 1.232  2016/08/22 14:20:21  brouard
                    262:   Summary: not working
                    263: 
1.232     brouard   264:   Revision 1.231  2016/08/22 07:17:15  brouard
                    265:   Summary: not working
                    266: 
1.231     brouard   267:   Revision 1.230  2016/08/22 06:55:53  brouard
                    268:   Summary: Not working
                    269: 
1.230     brouard   270:   Revision 1.229  2016/07/23 09:45:53  brouard
                    271:   Summary: Completing for func too
                    272: 
1.229     brouard   273:   Revision 1.228  2016/07/22 17:45:30  brouard
                    274:   Summary: Fixing some arrays, still debugging
                    275: 
1.227     brouard   276:   Revision 1.226  2016/07/12 18:42:34  brouard
                    277:   Summary: temp
                    278: 
1.226     brouard   279:   Revision 1.225  2016/07/12 08:40:03  brouard
                    280:   Summary: saving but not running
                    281: 
1.225     brouard   282:   Revision 1.224  2016/07/01 13:16:01  brouard
                    283:   Summary: Fixes
                    284: 
1.224     brouard   285:   Revision 1.223  2016/02/19 09:23:35  brouard
                    286:   Summary: temporary
                    287: 
1.223     brouard   288:   Revision 1.222  2016/02/17 08:14:50  brouard
                    289:   Summary: Probably last 0.98 stable version 0.98r6
                    290: 
1.222     brouard   291:   Revision 1.221  2016/02/15 23:35:36  brouard
                    292:   Summary: minor bug
                    293: 
1.220     brouard   294:   Revision 1.219  2016/02/15 00:48:12  brouard
                    295:   *** empty log message ***
                    296: 
1.219     brouard   297:   Revision 1.218  2016/02/12 11:29:23  brouard
                    298:   Summary: 0.99 Back projections
                    299: 
1.218     brouard   300:   Revision 1.217  2015/12/23 17:18:31  brouard
                    301:   Summary: Experimental backcast
                    302: 
1.217     brouard   303:   Revision 1.216  2015/12/18 17:32:11  brouard
                    304:   Summary: 0.98r4 Warning and status=-2
                    305: 
                    306:   Version 0.98r4 is now:
                    307:    - displaying an error when status is -1, date of interview unknown and date of death known;
                    308:    - permitting a status -2 when the vital status is unknown at a known date of right truncation.
                    309:   Older changes concerning s=-2, dating from 2005 have been supersed.
                    310: 
1.216     brouard   311:   Revision 1.215  2015/12/16 08:52:24  brouard
                    312:   Summary: 0.98r4 working
                    313: 
1.215     brouard   314:   Revision 1.214  2015/12/16 06:57:54  brouard
                    315:   Summary: temporary not working
                    316: 
1.214     brouard   317:   Revision 1.213  2015/12/11 18:22:17  brouard
                    318:   Summary: 0.98r4
                    319: 
1.213     brouard   320:   Revision 1.212  2015/11/21 12:47:24  brouard
                    321:   Summary: minor typo
                    322: 
1.212     brouard   323:   Revision 1.211  2015/11/21 12:41:11  brouard
                    324:   Summary: 0.98r3 with some graph of projected cross-sectional
                    325: 
                    326:   Author: Nicolas Brouard
                    327: 
1.211     brouard   328:   Revision 1.210  2015/11/18 17:41:20  brouard
1.252     brouard   329:   Summary: Start working on projected prevalences  Revision 1.209  2015/11/17 22:12:03  brouard
1.210     brouard   330:   Summary: Adding ftolpl parameter
                    331:   Author: N Brouard
                    332: 
                    333:   We had difficulties to get smoothed confidence intervals. It was due
                    334:   to the period prevalence which wasn't computed accurately. The inner
                    335:   parameter ftolpl is now an outer parameter of the .imach parameter
                    336:   file after estepm. If ftolpl is small 1.e-4 and estepm too,
                    337:   computation are long.
                    338: 
1.209     brouard   339:   Revision 1.208  2015/11/17 14:31:57  brouard
                    340:   Summary: temporary
                    341: 
1.208     brouard   342:   Revision 1.207  2015/10/27 17:36:57  brouard
                    343:   *** empty log message ***
                    344: 
1.207     brouard   345:   Revision 1.206  2015/10/24 07:14:11  brouard
                    346:   *** empty log message ***
                    347: 
1.206     brouard   348:   Revision 1.205  2015/10/23 15:50:53  brouard
                    349:   Summary: 0.98r3 some clarification for graphs on likelihood contributions
                    350: 
1.205     brouard   351:   Revision 1.204  2015/10/01 16:20:26  brouard
                    352:   Summary: Some new graphs of contribution to likelihood
                    353: 
1.204     brouard   354:   Revision 1.203  2015/09/30 17:45:14  brouard
                    355:   Summary: looking at better estimation of the hessian
                    356: 
                    357:   Also a better criteria for convergence to the period prevalence And
                    358:   therefore adding the number of years needed to converge. (The
                    359:   prevalence in any alive state shold sum to one
                    360: 
1.203     brouard   361:   Revision 1.202  2015/09/22 19:45:16  brouard
                    362:   Summary: Adding some overall graph on contribution to likelihood. Might change
                    363: 
1.202     brouard   364:   Revision 1.201  2015/09/15 17:34:58  brouard
                    365:   Summary: 0.98r0
                    366: 
                    367:   - Some new graphs like suvival functions
                    368:   - Some bugs fixed like model=1+age+V2.
                    369: 
1.201     brouard   370:   Revision 1.200  2015/09/09 16:53:55  brouard
                    371:   Summary: Big bug thanks to Flavia
                    372: 
                    373:   Even model=1+age+V2. did not work anymore
                    374: 
1.200     brouard   375:   Revision 1.199  2015/09/07 14:09:23  brouard
                    376:   Summary: 0.98q6 changing default small png format for graph to vectorized svg.
                    377: 
1.199     brouard   378:   Revision 1.198  2015/09/03 07:14:39  brouard
                    379:   Summary: 0.98q5 Flavia
                    380: 
1.198     brouard   381:   Revision 1.197  2015/09/01 18:24:39  brouard
                    382:   *** empty log message ***
                    383: 
1.197     brouard   384:   Revision 1.196  2015/08/18 23:17:52  brouard
                    385:   Summary: 0.98q5
                    386: 
1.196     brouard   387:   Revision 1.195  2015/08/18 16:28:39  brouard
                    388:   Summary: Adding a hack for testing purpose
                    389: 
                    390:   After reading the title, ftol and model lines, if the comment line has
                    391:   a q, starting with #q, the answer at the end of the run is quit. It
                    392:   permits to run test files in batch with ctest. The former workaround was
                    393:   $ echo q | imach foo.imach
                    394: 
1.195     brouard   395:   Revision 1.194  2015/08/18 13:32:00  brouard
                    396:   Summary:  Adding error when the covariance matrix doesn't contain the exact number of lines required by the model line.
                    397: 
1.194     brouard   398:   Revision 1.193  2015/08/04 07:17:42  brouard
                    399:   Summary: 0.98q4
                    400: 
1.193     brouard   401:   Revision 1.192  2015/07/16 16:49:02  brouard
                    402:   Summary: Fixing some outputs
                    403: 
1.192     brouard   404:   Revision 1.191  2015/07/14 10:00:33  brouard
                    405:   Summary: Some fixes
                    406: 
1.191     brouard   407:   Revision 1.190  2015/05/05 08:51:13  brouard
                    408:   Summary: Adding digits in output parameters (7 digits instead of 6)
                    409: 
                    410:   Fix 1+age+.
                    411: 
1.190     brouard   412:   Revision 1.189  2015/04/30 14:45:16  brouard
                    413:   Summary: 0.98q2
                    414: 
1.189     brouard   415:   Revision 1.188  2015/04/30 08:27:53  brouard
                    416:   *** empty log message ***
                    417: 
1.188     brouard   418:   Revision 1.187  2015/04/29 09:11:15  brouard
                    419:   *** empty log message ***
                    420: 
1.187     brouard   421:   Revision 1.186  2015/04/23 12:01:52  brouard
                    422:   Summary: V1*age is working now, version 0.98q1
                    423: 
                    424:   Some codes had been disabled in order to simplify and Vn*age was
                    425:   working in the optimization phase, ie, giving correct MLE parameters,
                    426:   but, as usual, outputs were not correct and program core dumped.
                    427: 
1.186     brouard   428:   Revision 1.185  2015/03/11 13:26:42  brouard
                    429:   Summary: Inclusion of compile and links command line for Intel Compiler
                    430: 
1.185     brouard   431:   Revision 1.184  2015/03/11 11:52:39  brouard
                    432:   Summary: Back from Windows 8. Intel Compiler
                    433: 
1.184     brouard   434:   Revision 1.183  2015/03/10 20:34:32  brouard
                    435:   Summary: 0.98q0, trying with directest, mnbrak fixed
                    436: 
                    437:   We use directest instead of original Powell test; probably no
                    438:   incidence on the results, but better justifications;
                    439:   We fixed Numerical Recipes mnbrak routine which was wrong and gave
                    440:   wrong results.
                    441: 
1.183     brouard   442:   Revision 1.182  2015/02/12 08:19:57  brouard
                    443:   Summary: Trying to keep directest which seems simpler and more general
                    444:   Author: Nicolas Brouard
                    445: 
1.182     brouard   446:   Revision 1.181  2015/02/11 23:22:24  brouard
                    447:   Summary: Comments on Powell added
                    448: 
                    449:   Author:
                    450: 
1.181     brouard   451:   Revision 1.180  2015/02/11 17:33:45  brouard
                    452:   Summary: Finishing move from main to function (hpijx and prevalence_limit)
                    453: 
1.180     brouard   454:   Revision 1.179  2015/01/04 09:57:06  brouard
                    455:   Summary: back to OS/X
                    456: 
1.179     brouard   457:   Revision 1.178  2015/01/04 09:35:48  brouard
                    458:   *** empty log message ***
                    459: 
1.178     brouard   460:   Revision 1.177  2015/01/03 18:40:56  brouard
                    461:   Summary: Still testing ilc32 on OSX
                    462: 
1.177     brouard   463:   Revision 1.176  2015/01/03 16:45:04  brouard
                    464:   *** empty log message ***
                    465: 
1.176     brouard   466:   Revision 1.175  2015/01/03 16:33:42  brouard
                    467:   *** empty log message ***
                    468: 
1.175     brouard   469:   Revision 1.174  2015/01/03 16:15:49  brouard
                    470:   Summary: Still in cross-compilation
                    471: 
1.174     brouard   472:   Revision 1.173  2015/01/03 12:06:26  brouard
                    473:   Summary: trying to detect cross-compilation
                    474: 
1.173     brouard   475:   Revision 1.172  2014/12/27 12:07:47  brouard
                    476:   Summary: Back from Visual Studio and Intel, options for compiling for Windows XP
                    477: 
1.172     brouard   478:   Revision 1.171  2014/12/23 13:26:59  brouard
                    479:   Summary: Back from Visual C
                    480: 
                    481:   Still problem with utsname.h on Windows
                    482: 
1.171     brouard   483:   Revision 1.170  2014/12/23 11:17:12  brouard
                    484:   Summary: Cleaning some \%% back to %%
                    485: 
                    486:   The escape was mandatory for a specific compiler (which one?), but too many warnings.
                    487: 
1.170     brouard   488:   Revision 1.169  2014/12/22 23:08:31  brouard
                    489:   Summary: 0.98p
                    490: 
                    491:   Outputs some informations on compiler used, OS etc. Testing on different platforms.
                    492: 
1.169     brouard   493:   Revision 1.168  2014/12/22 15:17:42  brouard
1.170     brouard   494:   Summary: update
1.169     brouard   495: 
1.168     brouard   496:   Revision 1.167  2014/12/22 13:50:56  brouard
                    497:   Summary: Testing uname and compiler version and if compiled 32 or 64
                    498: 
                    499:   Testing on Linux 64
                    500: 
1.167     brouard   501:   Revision 1.166  2014/12/22 11:40:47  brouard
                    502:   *** empty log message ***
                    503: 
1.166     brouard   504:   Revision 1.165  2014/12/16 11:20:36  brouard
                    505:   Summary: After compiling on Visual C
                    506: 
                    507:   * imach.c (Module): Merging 1.61 to 1.162
                    508: 
1.165     brouard   509:   Revision 1.164  2014/12/16 10:52:11  brouard
                    510:   Summary: Merging with Visual C after suppressing some warnings for unused variables. Also fixing Saito's bug 0.98Xn
                    511: 
                    512:   * imach.c (Module): Merging 1.61 to 1.162
                    513: 
1.164     brouard   514:   Revision 1.163  2014/12/16 10:30:11  brouard
                    515:   * imach.c (Module): Merging 1.61 to 1.162
                    516: 
1.163     brouard   517:   Revision 1.162  2014/09/25 11:43:39  brouard
                    518:   Summary: temporary backup 0.99!
                    519: 
1.162     brouard   520:   Revision 1.1  2014/09/16 11:06:58  brouard
                    521:   Summary: With some code (wrong) for nlopt
                    522: 
                    523:   Author:
                    524: 
                    525:   Revision 1.161  2014/09/15 20:41:41  brouard
                    526:   Summary: Problem with macro SQR on Intel compiler
                    527: 
1.161     brouard   528:   Revision 1.160  2014/09/02 09:24:05  brouard
                    529:   *** empty log message ***
                    530: 
1.160     brouard   531:   Revision 1.159  2014/09/01 10:34:10  brouard
                    532:   Summary: WIN32
                    533:   Author: Brouard
                    534: 
1.159     brouard   535:   Revision 1.158  2014/08/27 17:11:51  brouard
                    536:   *** empty log message ***
                    537: 
1.158     brouard   538:   Revision 1.157  2014/08/27 16:26:55  brouard
                    539:   Summary: Preparing windows Visual studio version
                    540:   Author: Brouard
                    541: 
                    542:   In order to compile on Visual studio, time.h is now correct and time_t
                    543:   and tm struct should be used. difftime should be used but sometimes I
                    544:   just make the differences in raw time format (time(&now).
                    545:   Trying to suppress #ifdef LINUX
                    546:   Add xdg-open for __linux in order to open default browser.
                    547: 
1.157     brouard   548:   Revision 1.156  2014/08/25 20:10:10  brouard
                    549:   *** empty log message ***
                    550: 
1.156     brouard   551:   Revision 1.155  2014/08/25 18:32:34  brouard
                    552:   Summary: New compile, minor changes
                    553:   Author: Brouard
                    554: 
1.155     brouard   555:   Revision 1.154  2014/06/20 17:32:08  brouard
                    556:   Summary: Outputs now all graphs of convergence to period prevalence
                    557: 
1.154     brouard   558:   Revision 1.153  2014/06/20 16:45:46  brouard
                    559:   Summary: If 3 live state, convergence to period prevalence on same graph
                    560:   Author: Brouard
                    561: 
1.153     brouard   562:   Revision 1.152  2014/06/18 17:54:09  brouard
                    563:   Summary: open browser, use gnuplot on same dir than imach if not found in the path
                    564: 
1.152     brouard   565:   Revision 1.151  2014/06/18 16:43:30  brouard
                    566:   *** empty log message ***
                    567: 
1.151     brouard   568:   Revision 1.150  2014/06/18 16:42:35  brouard
                    569:   Summary: If gnuplot is not in the path try on same directory than imach binary (OSX)
                    570:   Author: brouard
                    571: 
1.150     brouard   572:   Revision 1.149  2014/06/18 15:51:14  brouard
                    573:   Summary: Some fixes in parameter files errors
                    574:   Author: Nicolas Brouard
                    575: 
1.149     brouard   576:   Revision 1.148  2014/06/17 17:38:48  brouard
                    577:   Summary: Nothing new
                    578:   Author: Brouard
                    579: 
                    580:   Just a new packaging for OS/X version 0.98nS
                    581: 
1.148     brouard   582:   Revision 1.147  2014/06/16 10:33:11  brouard
                    583:   *** empty log message ***
                    584: 
1.147     brouard   585:   Revision 1.146  2014/06/16 10:20:28  brouard
                    586:   Summary: Merge
                    587:   Author: Brouard
                    588: 
                    589:   Merge, before building revised version.
                    590: 
1.146     brouard   591:   Revision 1.145  2014/06/10 21:23:15  brouard
                    592:   Summary: Debugging with valgrind
                    593:   Author: Nicolas Brouard
                    594: 
                    595:   Lot of changes in order to output the results with some covariates
                    596:   After the Edimburgh REVES conference 2014, it seems mandatory to
                    597:   improve the code.
                    598:   No more memory valgrind error but a lot has to be done in order to
                    599:   continue the work of splitting the code into subroutines.
                    600:   Also, decodemodel has been improved. Tricode is still not
                    601:   optimal. nbcode should be improved. Documentation has been added in
                    602:   the source code.
                    603: 
1.144     brouard   604:   Revision 1.143  2014/01/26 09:45:38  brouard
                    605:   Summary: Version 0.98nR (to be improved, but gives same optimization results as 0.98k. Nice, promising
                    606: 
                    607:   * imach.c (Module): Trying to merge old staffs together while being at Tokyo. Not tested...
                    608:   (Module): Version 0.98nR Running ok, but output format still only works for three covariates.
                    609: 
1.143     brouard   610:   Revision 1.142  2014/01/26 03:57:36  brouard
                    611:   Summary: gnuplot changed plot w l 1 has to be changed to plot w l lt 2
                    612: 
                    613:   * imach.c (Module): Trying to merge old staffs together while being at Tokyo. Not tested...
                    614: 
1.142     brouard   615:   Revision 1.141  2014/01/26 02:42:01  brouard
                    616:   * imach.c (Module): Trying to merge old staffs together while being at Tokyo. Not tested...
                    617: 
1.141     brouard   618:   Revision 1.140  2011/09/02 10:37:54  brouard
                    619:   Summary: times.h is ok with mingw32 now.
                    620: 
1.140     brouard   621:   Revision 1.139  2010/06/14 07:50:17  brouard
                    622:   After the theft of my laptop, I probably lost some lines of codes which were not uploaded to the CVS tree.
                    623:   I remember having already fixed agemin agemax which are pointers now but not cvs saved.
                    624: 
1.139     brouard   625:   Revision 1.138  2010/04/30 18:19:40  brouard
                    626:   *** empty log message ***
                    627: 
1.138     brouard   628:   Revision 1.137  2010/04/29 18:11:38  brouard
                    629:   (Module): Checking covariates for more complex models
                    630:   than V1+V2. A lot of change to be done. Unstable.
                    631: 
1.137     brouard   632:   Revision 1.136  2010/04/26 20:30:53  brouard
                    633:   (Module): merging some libgsl code. Fixing computation
                    634:   of likelione (using inter/intrapolation if mle = 0) in order to
                    635:   get same likelihood as if mle=1.
                    636:   Some cleaning of code and comments added.
                    637: 
1.136     brouard   638:   Revision 1.135  2009/10/29 15:33:14  brouard
                    639:   (Module): Now imach stops if date of birth, at least year of birth, is not given. Some cleaning of the code.
                    640: 
1.135     brouard   641:   Revision 1.134  2009/10/29 13:18:53  brouard
                    642:   (Module): Now imach stops if date of birth, at least year of birth, is not given. Some cleaning of the code.
                    643: 
1.134     brouard   644:   Revision 1.133  2009/07/06 10:21:25  brouard
                    645:   just nforces
                    646: 
1.133     brouard   647:   Revision 1.132  2009/07/06 08:22:05  brouard
                    648:   Many tings
                    649: 
1.132     brouard   650:   Revision 1.131  2009/06/20 16:22:47  brouard
                    651:   Some dimensions resccaled
                    652: 
1.131     brouard   653:   Revision 1.130  2009/05/26 06:44:34  brouard
                    654:   (Module): Max Covariate is now set to 20 instead of 8. A
                    655:   lot of cleaning with variables initialized to 0. Trying to make
                    656:   V2+V3*age+V1+V4 strb=V3*age+V1+V4 working better.
                    657: 
1.130     brouard   658:   Revision 1.129  2007/08/31 13:49:27  lievre
                    659:   Modification of the way of exiting when the covariate is not binary in order to see on the window the error message before exiting
                    660: 
1.129     lievre    661:   Revision 1.128  2006/06/30 13:02:05  brouard
                    662:   (Module): Clarifications on computing e.j
                    663: 
1.128     brouard   664:   Revision 1.127  2006/04/28 18:11:50  brouard
                    665:   (Module): Yes the sum of survivors was wrong since
                    666:   imach-114 because nhstepm was no more computed in the age
                    667:   loop. Now we define nhstepma in the age loop.
                    668:   (Module): In order to speed up (in case of numerous covariates) we
                    669:   compute health expectancies (without variances) in a first step
                    670:   and then all the health expectancies with variances or standard
                    671:   deviation (needs data from the Hessian matrices) which slows the
                    672:   computation.
                    673:   In the future we should be able to stop the program is only health
                    674:   expectancies and graph are needed without standard deviations.
                    675: 
1.127     brouard   676:   Revision 1.126  2006/04/28 17:23:28  brouard
                    677:   (Module): Yes the sum of survivors was wrong since
                    678:   imach-114 because nhstepm was no more computed in the age
                    679:   loop. Now we define nhstepma in the age loop.
                    680:   Version 0.98h
                    681: 
1.126     brouard   682:   Revision 1.125  2006/04/04 15:20:31  lievre
                    683:   Errors in calculation of health expectancies. Age was not initialized.
                    684:   Forecasting file added.
                    685: 
                    686:   Revision 1.124  2006/03/22 17:13:53  lievre
                    687:   Parameters are printed with %lf instead of %f (more numbers after the comma).
                    688:   The log-likelihood is printed in the log file
                    689: 
                    690:   Revision 1.123  2006/03/20 10:52:43  brouard
                    691:   * imach.c (Module): <title> changed, corresponds to .htm file
                    692:   name. <head> headers where missing.
                    693: 
                    694:   * imach.c (Module): Weights can have a decimal point as for
                    695:   English (a comma might work with a correct LC_NUMERIC environment,
                    696:   otherwise the weight is truncated).
                    697:   Modification of warning when the covariates values are not 0 or
                    698:   1.
                    699:   Version 0.98g
                    700: 
                    701:   Revision 1.122  2006/03/20 09:45:41  brouard
                    702:   (Module): Weights can have a decimal point as for
                    703:   English (a comma might work with a correct LC_NUMERIC environment,
                    704:   otherwise the weight is truncated).
                    705:   Modification of warning when the covariates values are not 0 or
                    706:   1.
                    707:   Version 0.98g
                    708: 
                    709:   Revision 1.121  2006/03/16 17:45:01  lievre
                    710:   * imach.c (Module): Comments concerning covariates added
                    711: 
                    712:   * imach.c (Module): refinements in the computation of lli if
                    713:   status=-2 in order to have more reliable computation if stepm is
                    714:   not 1 month. Version 0.98f
                    715: 
                    716:   Revision 1.120  2006/03/16 15:10:38  lievre
                    717:   (Module): refinements in the computation of lli if
                    718:   status=-2 in order to have more reliable computation if stepm is
                    719:   not 1 month. Version 0.98f
                    720: 
                    721:   Revision 1.119  2006/03/15 17:42:26  brouard
                    722:   (Module): Bug if status = -2, the loglikelihood was
                    723:   computed as likelihood omitting the logarithm. Version O.98e
                    724: 
                    725:   Revision 1.118  2006/03/14 18:20:07  brouard
                    726:   (Module): varevsij Comments added explaining the second
                    727:   table of variances if popbased=1 .
                    728:   (Module): Covariances of eij, ekl added, graphs fixed, new html link.
                    729:   (Module): Function pstamp added
                    730:   (Module): Version 0.98d
                    731: 
                    732:   Revision 1.117  2006/03/14 17:16:22  brouard
                    733:   (Module): varevsij Comments added explaining the second
                    734:   table of variances if popbased=1 .
                    735:   (Module): Covariances of eij, ekl added, graphs fixed, new html link.
                    736:   (Module): Function pstamp added
                    737:   (Module): Version 0.98d
                    738: 
                    739:   Revision 1.116  2006/03/06 10:29:27  brouard
                    740:   (Module): Variance-covariance wrong links and
                    741:   varian-covariance of ej. is needed (Saito).
                    742: 
                    743:   Revision 1.115  2006/02/27 12:17:45  brouard
                    744:   (Module): One freematrix added in mlikeli! 0.98c
                    745: 
                    746:   Revision 1.114  2006/02/26 12:57:58  brouard
                    747:   (Module): Some improvements in processing parameter
                    748:   filename with strsep.
                    749: 
                    750:   Revision 1.113  2006/02/24 14:20:24  brouard
                    751:   (Module): Memory leaks checks with valgrind and:
                    752:   datafile was not closed, some imatrix were not freed and on matrix
                    753:   allocation too.
                    754: 
                    755:   Revision 1.112  2006/01/30 09:55:26  brouard
                    756:   (Module): Back to gnuplot.exe instead of wgnuplot.exe
                    757: 
                    758:   Revision 1.111  2006/01/25 20:38:18  brouard
                    759:   (Module): Lots of cleaning and bugs added (Gompertz)
                    760:   (Module): Comments can be added in data file. Missing date values
                    761:   can be a simple dot '.'.
                    762: 
                    763:   Revision 1.110  2006/01/25 00:51:50  brouard
                    764:   (Module): Lots of cleaning and bugs added (Gompertz)
                    765: 
                    766:   Revision 1.109  2006/01/24 19:37:15  brouard
                    767:   (Module): Comments (lines starting with a #) are allowed in data.
                    768: 
                    769:   Revision 1.108  2006/01/19 18:05:42  lievre
                    770:   Gnuplot problem appeared...
                    771:   To be fixed
                    772: 
                    773:   Revision 1.107  2006/01/19 16:20:37  brouard
                    774:   Test existence of gnuplot in imach path
                    775: 
                    776:   Revision 1.106  2006/01/19 13:24:36  brouard
                    777:   Some cleaning and links added in html output
                    778: 
                    779:   Revision 1.105  2006/01/05 20:23:19  lievre
                    780:   *** empty log message ***
                    781: 
                    782:   Revision 1.104  2005/09/30 16:11:43  lievre
                    783:   (Module): sump fixed, loop imx fixed, and simplifications.
                    784:   (Module): If the status is missing at the last wave but we know
                    785:   that the person is alive, then we can code his/her status as -2
                    786:   (instead of missing=-1 in earlier versions) and his/her
                    787:   contributions to the likelihood is 1 - Prob of dying from last
                    788:   health status (= 1-p13= p11+p12 in the easiest case of somebody in
                    789:   the healthy state at last known wave). Version is 0.98
                    790: 
                    791:   Revision 1.103  2005/09/30 15:54:49  lievre
                    792:   (Module): sump fixed, loop imx fixed, and simplifications.
                    793: 
                    794:   Revision 1.102  2004/09/15 17:31:30  brouard
                    795:   Add the possibility to read data file including tab characters.
                    796: 
                    797:   Revision 1.101  2004/09/15 10:38:38  brouard
                    798:   Fix on curr_time
                    799: 
                    800:   Revision 1.100  2004/07/12 18:29:06  brouard
                    801:   Add version for Mac OS X. Just define UNIX in Makefile
                    802: 
                    803:   Revision 1.99  2004/06/05 08:57:40  brouard
                    804:   *** empty log message ***
                    805: 
                    806:   Revision 1.98  2004/05/16 15:05:56  brouard
                    807:   New version 0.97 . First attempt to estimate force of mortality
                    808:   directly from the data i.e. without the need of knowing the health
                    809:   state at each age, but using a Gompertz model: log u =a + b*age .
                    810:   This is the basic analysis of mortality and should be done before any
                    811:   other analysis, in order to test if the mortality estimated from the
                    812:   cross-longitudinal survey is different from the mortality estimated
                    813:   from other sources like vital statistic data.
                    814: 
                    815:   The same imach parameter file can be used but the option for mle should be -3.
                    816: 
1.133     brouard   817:   Agnès, who wrote this part of the code, tried to keep most of the
1.126     brouard   818:   former routines in order to include the new code within the former code.
                    819: 
                    820:   The output is very simple: only an estimate of the intercept and of
                    821:   the slope with 95% confident intervals.
                    822: 
                    823:   Current limitations:
                    824:   A) Even if you enter covariates, i.e. with the
                    825:   model= V1+V2 equation for example, the programm does only estimate a unique global model without covariates.
                    826:   B) There is no computation of Life Expectancy nor Life Table.
                    827: 
                    828:   Revision 1.97  2004/02/20 13:25:42  lievre
                    829:   Version 0.96d. Population forecasting command line is (temporarily)
                    830:   suppressed.
                    831: 
                    832:   Revision 1.96  2003/07/15 15:38:55  brouard
                    833:   * imach.c (Repository): Errors in subdirf, 2, 3 while printing tmpout is
                    834:   rewritten within the same printf. Workaround: many printfs.
                    835: 
                    836:   Revision 1.95  2003/07/08 07:54:34  brouard
                    837:   * imach.c (Repository):
                    838:   (Repository): Using imachwizard code to output a more meaningful covariance
                    839:   matrix (cov(a12,c31) instead of numbers.
                    840: 
                    841:   Revision 1.94  2003/06/27 13:00:02  brouard
                    842:   Just cleaning
                    843: 
                    844:   Revision 1.93  2003/06/25 16:33:55  brouard
                    845:   (Module): On windows (cygwin) function asctime_r doesn't
                    846:   exist so I changed back to asctime which exists.
                    847:   (Module): Version 0.96b
                    848: 
                    849:   Revision 1.92  2003/06/25 16:30:45  brouard
                    850:   (Module): On windows (cygwin) function asctime_r doesn't
                    851:   exist so I changed back to asctime which exists.
                    852: 
                    853:   Revision 1.91  2003/06/25 15:30:29  brouard
                    854:   * imach.c (Repository): Duplicated warning errors corrected.
                    855:   (Repository): Elapsed time after each iteration is now output. It
                    856:   helps to forecast when convergence will be reached. Elapsed time
                    857:   is stamped in powell.  We created a new html file for the graphs
                    858:   concerning matrix of covariance. It has extension -cov.htm.
                    859: 
                    860:   Revision 1.90  2003/06/24 12:34:15  brouard
                    861:   (Module): Some bugs corrected for windows. Also, when
                    862:   mle=-1 a template is output in file "or"mypar.txt with the design
                    863:   of the covariance matrix to be input.
                    864: 
                    865:   Revision 1.89  2003/06/24 12:30:52  brouard
                    866:   (Module): Some bugs corrected for windows. Also, when
                    867:   mle=-1 a template is output in file "or"mypar.txt with the design
                    868:   of the covariance matrix to be input.
                    869: 
                    870:   Revision 1.88  2003/06/23 17:54:56  brouard
                    871:   * 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.
                    872: 
                    873:   Revision 1.87  2003/06/18 12:26:01  brouard
                    874:   Version 0.96
                    875: 
                    876:   Revision 1.86  2003/06/17 20:04:08  brouard
                    877:   (Module): Change position of html and gnuplot routines and added
                    878:   routine fileappend.
                    879: 
                    880:   Revision 1.85  2003/06/17 13:12:43  brouard
                    881:   * imach.c (Repository): Check when date of death was earlier that
                    882:   current date of interview. It may happen when the death was just
                    883:   prior to the death. In this case, dh was negative and likelihood
                    884:   was wrong (infinity). We still send an "Error" but patch by
                    885:   assuming that the date of death was just one stepm after the
                    886:   interview.
                    887:   (Repository): Because some people have very long ID (first column)
                    888:   we changed int to long in num[] and we added a new lvector for
                    889:   memory allocation. But we also truncated to 8 characters (left
                    890:   truncation)
                    891:   (Repository): No more line truncation errors.
                    892: 
                    893:   Revision 1.84  2003/06/13 21:44:43  brouard
                    894:   * imach.c (Repository): Replace "freqsummary" at a correct
                    895:   place. It differs from routine "prevalence" which may be called
                    896:   many times. Probs is memory consuming and must be used with
                    897:   parcimony.
                    898:   Version 0.95a3 (should output exactly the same maximization than 0.8a2)
                    899: 
                    900:   Revision 1.83  2003/06/10 13:39:11  lievre
                    901:   *** empty log message ***
                    902: 
                    903:   Revision 1.82  2003/06/05 15:57:20  brouard
                    904:   Add log in  imach.c and  fullversion number is now printed.
                    905: 
                    906: */
                    907: /*
                    908:    Interpolated Markov Chain
                    909: 
                    910:   Short summary of the programme:
                    911:   
1.227     brouard   912:   This program computes Healthy Life Expectancies or State-specific
                    913:   (if states aren't health statuses) Expectancies from
                    914:   cross-longitudinal data. Cross-longitudinal data consist in: 
                    915: 
                    916:   -1- a first survey ("cross") where individuals from different ages
                    917:   are interviewed on their health status or degree of disability (in
                    918:   the case of a health survey which is our main interest)
                    919: 
                    920:   -2- at least a second wave of interviews ("longitudinal") which
                    921:   measure each change (if any) in individual health status.  Health
                    922:   expectancies are computed from the time spent in each health state
                    923:   according to a model. More health states you consider, more time is
                    924:   necessary to reach the Maximum Likelihood of the parameters involved
                    925:   in the model.  The simplest model is the multinomial logistic model
                    926:   where pij is the probability to be observed in state j at the second
                    927:   wave conditional to be observed in state i at the first
                    928:   wave. Therefore the model is: log(pij/pii)= aij + bij*age+ cij*sex +
                    929:   etc , where 'age' is age and 'sex' is a covariate. If you want to
                    930:   have a more complex model than "constant and age", you should modify
                    931:   the program where the markup *Covariates have to be included here
                    932:   again* invites you to do it.  More covariates you add, slower the
1.126     brouard   933:   convergence.
                    934: 
                    935:   The advantage of this computer programme, compared to a simple
                    936:   multinomial logistic model, is clear when the delay between waves is not
                    937:   identical for each individual. Also, if a individual missed an
                    938:   intermediate interview, the information is lost, but taken into
                    939:   account using an interpolation or extrapolation.  
                    940: 
                    941:   hPijx is the probability to be observed in state i at age x+h
                    942:   conditional to the observed state i at age x. The delay 'h' can be
                    943:   split into an exact number (nh*stepm) of unobserved intermediate
                    944:   states. This elementary transition (by month, quarter,
                    945:   semester or year) is modelled as a multinomial logistic.  The hPx
                    946:   matrix is simply the matrix product of nh*stepm elementary matrices
                    947:   and the contribution of each individual to the likelihood is simply
                    948:   hPijx.
                    949: 
                    950:   Also this programme outputs the covariance matrix of the parameters but also
1.218     brouard   951:   of the life expectancies. It also computes the period (stable) prevalence.
                    952: 
                    953: Back prevalence and projections:
1.227     brouard   954: 
                    955:  - back_prevalence_limit(double *p, double **bprlim, double ageminpar,
                    956:    double agemaxpar, double ftolpl, int *ncvyearp, double
                    957:    dateprev1,double dateprev2, int firstpass, int lastpass, int
                    958:    mobilavproj)
                    959: 
                    960:     Computes the back prevalence limit for any combination of
                    961:     covariate values k at any age between ageminpar and agemaxpar and
                    962:     returns it in **bprlim. In the loops,
                    963: 
                    964:    - **bprevalim(**bprlim, ***mobaverage, nlstate, *p, age, **oldm,
                    965:        **savm, **dnewm, **doldm, **dsavm, ftolpl, ncvyearp, k);
                    966: 
                    967:    - hBijx Back Probability to be in state i at age x-h being in j at x
1.218     brouard   968:    Computes for any combination of covariates k and any age between bage and fage 
                    969:    p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                    970:                        oldm=oldms;savm=savms;
1.227     brouard   971: 
1.267     brouard   972:    - hbxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k, nres);
1.218     brouard   973:      Computes the transition matrix starting at age 'age' over
                    974:      'nhstepm*hstepm*stepm' months (i.e. until
                    975:      age (in years)  age+nhstepm*hstepm*stepm/12) by multiplying
1.227     brouard   976:      nhstepm*hstepm matrices. 
                    977: 
                    978:      Returns p3mat[i][j][h] after calling
                    979:      p3mat[i][j][h]=matprod2(newm,
                    980:      bmij(pmmij,cov,ncovmodel,x,nlstate,prevacurrent, dnewm, doldm,
                    981:      dsavm,ij),\ 1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath,
                    982:      oldm);
1.226     brouard   983: 
                    984: Important routines
                    985: 
                    986: - func (or funcone), computes logit (pij) distinguishing
                    987:   o fixed variables (single or product dummies or quantitative);
                    988:   o varying variables by:
                    989:    (1) wave (single, product dummies, quantitative), 
                    990:    (2) by age (can be month) age (done), age*age (done), age*Vn where Vn can be:
                    991:        % fixed dummy (treated) or quantitative (not done because time-consuming);
                    992:        % varying dummy (not done) or quantitative (not done);
                    993: - Tricode which tests the modality of dummy variables (in order to warn with wrong or empty modalities)
                    994:   and returns the number of efficient covariates cptcoveff and modalities nbcode[Tvar[k]][1]= 0 and nbcode[Tvar[k]][2]= 1 usually.
                    995: - printinghtml which outputs results like life expectancy in and from a state for a combination of modalities of dummy variables
                    996:   o There are 2*cptcoveff combinations of (0,1) for cptcoveff variables. Outputting only combinations with people, éliminating 1 1 if
                    997:     race White (0 0), Black vs White (1 0), Hispanic (0 1) and 1 1 being meaningless.
1.218     brouard   998: 
1.226     brouard   999: 
                   1000:   
1.133     brouard  1001:   Authors: Nicolas Brouard (brouard@ined.fr) and Agnès Lièvre (lievre@ined.fr).
                   1002:            Institut national d'études démographiques, Paris.
1.126     brouard  1003:   This software have been partly granted by Euro-REVES, a concerted action
                   1004:   from the European Union.
                   1005:   It is copyrighted identically to a GNU software product, ie programme and
                   1006:   software can be distributed freely for non commercial use. Latest version
                   1007:   can be accessed at http://euroreves.ined.fr/imach .
                   1008: 
                   1009:   Help to debug: LD_PRELOAD=/usr/local/lib/libnjamd.so ./imach foo.imach
                   1010:   or better on gdb : set env LD_PRELOAD=/usr/local/lib/libnjamd.so
                   1011:   
                   1012:   **********************************************************************/
                   1013: /*
                   1014:   main
                   1015:   read parameterfile
                   1016:   read datafile
                   1017:   concatwav
                   1018:   freqsummary
                   1019:   if (mle >= 1)
                   1020:     mlikeli
                   1021:   print results files
                   1022:   if mle==1 
                   1023:      computes hessian
                   1024:   read end of parameter file: agemin, agemax, bage, fage, estepm
                   1025:       begin-prev-date,...
                   1026:   open gnuplot file
                   1027:   open html file
1.145     brouard  1028:   period (stable) prevalence      | pl_nom    1-1 2-2 etc by covariate
                   1029:    for age prevalim()             | #****** V1=0  V2=1  V3=1  V4=0 ******
                   1030:                                   | 65 1 0 2 1 3 1 4 0  0.96326 0.03674
                   1031:     freexexit2 possible for memory heap.
                   1032: 
                   1033:   h Pij x                         | pij_nom  ficrestpij
                   1034:    # Cov Agex agex+h hpijx with i,j= 1-1 1-2     1-3     2-1     2-2     2-3
                   1035:        1  85   85    1.00000             0.00000 0.00000 0.00000 1.00000 0.00000
                   1036:        1  85   86    0.68299             0.22291 0.09410 0.71093 0.00000 0.28907
                   1037: 
                   1038:        1  65   99    0.00364             0.00322 0.99314 0.00350 0.00310 0.99340
                   1039:        1  65  100    0.00214             0.00204 0.99581 0.00206 0.00196 0.99597
                   1040:   variance of p one-step probabilities varprob  | prob_nom   ficresprob #One-step probabilities and stand. devi in ()
                   1041:    Standard deviation of one-step probabilities | probcor_nom   ficresprobcor #One-step probabilities and correlation matrix
                   1042:    Matrix of variance covariance of one-step probabilities |  probcov_nom ficresprobcov #One-step probabilities and covariance matrix
                   1043: 
1.126     brouard  1044:   forecasting if prevfcast==1 prevforecast call prevalence()
                   1045:   health expectancies
                   1046:   Variance-covariance of DFLE
                   1047:   prevalence()
                   1048:    movingaverage()
                   1049:   varevsij() 
                   1050:   if popbased==1 varevsij(,popbased)
                   1051:   total life expectancies
                   1052:   Variance of period (stable) prevalence
                   1053:  end
                   1054: */
                   1055: 
1.187     brouard  1056: /* #define DEBUG */
                   1057: /* #define DEBUGBRENT */
1.203     brouard  1058: /* #define DEBUGLINMIN */
                   1059: /* #define DEBUGHESS */
                   1060: #define DEBUGHESSIJ
1.224     brouard  1061: /* #define LINMINORIGINAL  /\* Don't use loop on scale in linmin (accepting nan) *\/ */
1.165     brouard  1062: #define POWELL /* Instead of NLOPT */
1.224     brouard  1063: #define POWELLNOF3INFF1TEST /* Skip test */
1.186     brouard  1064: /* #define POWELLORIGINAL /\* Don't use Directest to decide new direction but original Powell test *\/ */
                   1065: /* #define MNBRAKORIGINAL /\* Don't use mnbrak fix *\/ */
1.126     brouard  1066: 
                   1067: #include <math.h>
                   1068: #include <stdio.h>
                   1069: #include <stdlib.h>
                   1070: #include <string.h>
1.226     brouard  1071: #include <ctype.h>
1.159     brouard  1072: 
                   1073: #ifdef _WIN32
                   1074: #include <io.h>
1.172     brouard  1075: #include <windows.h>
                   1076: #include <tchar.h>
1.159     brouard  1077: #else
1.126     brouard  1078: #include <unistd.h>
1.159     brouard  1079: #endif
1.126     brouard  1080: 
                   1081: #include <limits.h>
                   1082: #include <sys/types.h>
1.171     brouard  1083: 
                   1084: #if defined(__GNUC__)
                   1085: #include <sys/utsname.h> /* Doesn't work on Windows */
                   1086: #endif
                   1087: 
1.126     brouard  1088: #include <sys/stat.h>
                   1089: #include <errno.h>
1.159     brouard  1090: /* extern int errno; */
1.126     brouard  1091: 
1.157     brouard  1092: /* #ifdef LINUX */
                   1093: /* #include <time.h> */
                   1094: /* #include "timeval.h" */
                   1095: /* #else */
                   1096: /* #include <sys/time.h> */
                   1097: /* #endif */
                   1098: 
1.126     brouard  1099: #include <time.h>
                   1100: 
1.136     brouard  1101: #ifdef GSL
                   1102: #include <gsl/gsl_errno.h>
                   1103: #include <gsl/gsl_multimin.h>
                   1104: #endif
                   1105: 
1.167     brouard  1106: 
1.162     brouard  1107: #ifdef NLOPT
                   1108: #include <nlopt.h>
                   1109: typedef struct {
                   1110:   double (* function)(double [] );
                   1111: } myfunc_data ;
                   1112: #endif
                   1113: 
1.126     brouard  1114: /* #include <libintl.h> */
                   1115: /* #define _(String) gettext (String) */
                   1116: 
1.251     brouard  1117: #define MAXLINE 2048 /* Was 256 and 1024. Overflow with 312 with 2 states and 4 covariates. Should be ok */
1.126     brouard  1118: 
                   1119: #define GNUPLOTPROGRAM "gnuplot"
                   1120: /*#define GNUPLOTPROGRAM "..\\gp37mgw\\wgnuplot"*/
                   1121: #define FILENAMELENGTH 132
                   1122: 
                   1123: #define        GLOCK_ERROR_NOPATH              -1      /* empty path */
                   1124: #define        GLOCK_ERROR_GETCWD              -2      /* cannot get cwd */
                   1125: 
1.144     brouard  1126: #define MAXPARM 128 /**< Maximum number of parameters for the optimization */
                   1127: #define NPARMAX 64 /**< (nlstate+ndeath-1)*nlstate*ncovmodel */
1.126     brouard  1128: 
                   1129: #define NINTERVMAX 8
1.144     brouard  1130: #define NLSTATEMAX 8 /**< Maximum number of live states (for func) */
                   1131: #define NDEATHMAX 8 /**< Maximum number of dead states (for func) */
1.291     brouard  1132: #define NCOVMAX 20  /**< Maximum number of covariates, including generated covariates V1*V2 */
1.197     brouard  1133: #define codtabm(h,k)  (1 & (h-1) >> (k-1))+1
1.211     brouard  1134: /*#define decodtabm(h,k,cptcoveff)= (h <= (1<<cptcoveff)?(((h-1) >> (k-1)) & 1) +1 : -1)*/
                   1135: #define decodtabm(h,k,cptcoveff) (((h-1) >> (k-1)) & 1) +1 
1.290     brouard  1136: /*#define MAXN 20000 */ /* Should by replaced by nobs, real number of observations and unlimited */
1.144     brouard  1137: #define YEARM 12. /**< Number of months per year */
1.218     brouard  1138: /* #define AGESUP 130 */
1.288     brouard  1139: /* #define AGESUP 150 */
                   1140: #define AGESUP 200
1.268     brouard  1141: #define AGEINF 0
1.218     brouard  1142: #define AGEMARGE 25 /* Marge for agemin and agemax for(iage=agemin-AGEMARGE; iage <= agemax+3+AGEMARGE; iage++) */
1.126     brouard  1143: #define AGEBASE 40
1.194     brouard  1144: #define AGEOVERFLOW 1.e20
1.164     brouard  1145: #define AGEGOMP 10 /**< Minimal age for Gompertz adjustment */
1.157     brouard  1146: #ifdef _WIN32
                   1147: #define DIRSEPARATOR '\\'
                   1148: #define CHARSEPARATOR "\\"
                   1149: #define ODIRSEPARATOR '/'
                   1150: #else
1.126     brouard  1151: #define DIRSEPARATOR '/'
                   1152: #define CHARSEPARATOR "/"
                   1153: #define ODIRSEPARATOR '\\'
                   1154: #endif
                   1155: 
1.310   ! brouard  1156: /* $Id: imach.c,v 1.309 2021/05/20 12:39:14 brouard Exp $ */
1.126     brouard  1157: /* $State: Exp $ */
1.196     brouard  1158: #include "version.h"
                   1159: char version[]=__IMACH_VERSION__;
1.308     brouard  1160: char copyright[]="March 2021,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, INED 2000-2021";
1.310   ! brouard  1161: char fullversion[]="$Revision: 1.309 $ $Date: 2021/05/20 12:39:14 $"; 
1.126     brouard  1162: char strstart[80];
                   1163: char optionfilext[10], optionfilefiname[FILENAMELENGTH];
1.130     brouard  1164: int erreur=0, nberr=0, nbwarn=0; /* Error number, number of errors number of warnings  */
1.187     brouard  1165: int nagesqr=0, nforce=0; /* nagesqr=1 if model is including age*age, number of forces */
1.145     brouard  1166: /* Number of covariates model=V2+V1+ V3*age+V2*V4 */
                   1167: int cptcovn=0; /**< cptcovn number of covariates added in the model (excepting constant and age and age*product) */
                   1168: int cptcovt=0; /**< cptcovt number of covariates added in the model (excepting constant and age) */
1.225     brouard  1169: int cptcovs=0; /**< cptcovs number of simple covariates in the model V2+V1 =2 */
                   1170: int cptcovsnq=0; /**< cptcovsnq number of simple covariates in the model but non quantitative V2+V1 =2 */
1.145     brouard  1171: int cptcovage=0; /**< Number of covariates with age: V3*age only =1 */
                   1172: int cptcovprodnoage=0; /**< Number of covariate products without age */   
                   1173: int cptcoveff=0; /* Total number of covariates to vary for printing results */
1.233     brouard  1174: int ncovf=0; /* Total number of effective fixed covariates (dummy or quantitative) in the model */
                   1175: int ncovv=0; /* Total number of effective (wave) varying covariates (dummy or quantitative) in the model */
1.232     brouard  1176: int ncova=0; /* Total number of effective (wave and stepm) varying with age covariates (dummy of quantitative) in the model */
1.234     brouard  1177: int nsd=0; /**< Total number of single dummy variables (output) */
                   1178: int nsq=0; /**< Total number of single quantitative variables (output) */
1.232     brouard  1179: int ncoveff=0; /* Total number of effective fixed dummy covariates in the model */
1.225     brouard  1180: int nqfveff=0; /**< nqfveff Number of Quantitative Fixed Variables Effective */
1.224     brouard  1181: int ntveff=0; /**< ntveff number of effective time varying variables */
                   1182: int nqtveff=0; /**< ntqveff number of effective time varying quantitative variables */
1.145     brouard  1183: int cptcov=0; /* Working variable */
1.290     brouard  1184: int nobs=10;  /* Number of observations in the data lastobs-firstobs */
1.218     brouard  1185: int ncovcombmax=NCOVMAX; /* Maximum calculated number of covariate combination = pow(2, cptcoveff) */
1.302     brouard  1186: int npar=NPARMAX; /* Number of parameters (nlstate+ndeath-1)*nlstate*ncovmodel; */
1.126     brouard  1187: int nlstate=2; /* Number of live states */
                   1188: int ndeath=1; /* Number of dead states */
1.130     brouard  1189: int ncovmodel=0, ncovcol=0;     /* Total number of covariables including constant a12*1 +b12*x ncovmodel=2 */
1.223     brouard  1190: int  nqv=0, ntv=0, nqtv=0;    /* Total number of quantitative variables, time variable (dummy), quantitative and time variable */ 
1.126     brouard  1191: int popbased=0;
                   1192: 
                   1193: int *wav; /* Number of waves for this individuual 0 is possible */
1.130     brouard  1194: int maxwav=0; /* Maxim number of waves */
                   1195: int jmin=0, jmax=0; /* min, max spacing between 2 waves */
                   1196: int ijmin=0, ijmax=0; /* Individuals having jmin and jmax */ 
                   1197: int gipmx=0, gsw=0; /* Global variables on the number of contributions 
1.126     brouard  1198:                   to the likelihood and the sum of weights (done by funcone)*/
1.130     brouard  1199: int mle=1, weightopt=0;
1.126     brouard  1200: int **mw; /* mw[mi][i] is number of the mi wave for this individual */
                   1201: int **dh; /* dh[mi][i] is number of steps between mi,mi+1 for this individual */
                   1202: int **bh; /* bh[mi][i] is the bias (+ or -) for this individual if the delay between
                   1203:           * wave mi and wave mi+1 is not an exact multiple of stepm. */
1.162     brouard  1204: int countcallfunc=0;  /* Count the number of calls to func */
1.230     brouard  1205: int selected(int kvar); /* Is covariate kvar selected for printing results */
                   1206: 
1.130     brouard  1207: double jmean=1; /* Mean space between 2 waves */
1.145     brouard  1208: double **matprod2(); /* test */
1.126     brouard  1209: double **oldm, **newm, **savm; /* Working pointers to matrices */
                   1210: double **oldms, **newms, **savms; /* Fixed working pointers to matrices */
1.218     brouard  1211: double  **ddnewms, **ddoldms, **ddsavms; /* for freeing later */
                   1212: 
1.136     brouard  1213: /*FILE *fic ; */ /* Used in readdata only */
1.217     brouard  1214: FILE *ficpar, *ficparo,*ficres, *ficresp, *ficresphtm, *ficresphtmfr, *ficrespl, *ficresplb,*ficrespij, *ficrespijb, *ficrest,*ficresf, *ficresfb,*ficrespop;
1.126     brouard  1215: FILE *ficlog, *ficrespow;
1.130     brouard  1216: int globpr=0; /* Global variable for printing or not */
1.126     brouard  1217: double fretone; /* Only one call to likelihood */
1.130     brouard  1218: long ipmx=0; /* Number of contributions */
1.126     brouard  1219: double sw; /* Sum of weights */
                   1220: char filerespow[FILENAMELENGTH];
                   1221: char fileresilk[FILENAMELENGTH]; /* File of individual contributions to the likelihood */
                   1222: FILE *ficresilk;
                   1223: FILE *ficgp,*ficresprob,*ficpop, *ficresprobcov, *ficresprobcor;
                   1224: FILE *ficresprobmorprev;
                   1225: FILE *fichtm, *fichtmcov; /* Html File */
                   1226: FILE *ficreseij;
                   1227: char filerese[FILENAMELENGTH];
                   1228: FILE *ficresstdeij;
                   1229: char fileresstde[FILENAMELENGTH];
                   1230: FILE *ficrescveij;
                   1231: char filerescve[FILENAMELENGTH];
                   1232: FILE  *ficresvij;
                   1233: char fileresv[FILENAMELENGTH];
1.269     brouard  1234: 
1.126     brouard  1235: char title[MAXLINE];
1.234     brouard  1236: char model[MAXLINE]; /**< The model line */
1.217     brouard  1237: char optionfile[FILENAMELENGTH], datafile[FILENAMELENGTH],  filerespl[FILENAMELENGTH],  fileresplb[FILENAMELENGTH];
1.126     brouard  1238: char plotcmd[FILENAMELENGTH], pplotcmd[FILENAMELENGTH];
                   1239: char tmpout[FILENAMELENGTH],  tmpout2[FILENAMELENGTH]; 
                   1240: char command[FILENAMELENGTH];
                   1241: int  outcmd=0;
                   1242: 
1.217     brouard  1243: char fileres[FILENAMELENGTH], filerespij[FILENAMELENGTH], filerespijb[FILENAMELENGTH], filereso[FILENAMELENGTH], rfileres[FILENAMELENGTH];
1.202     brouard  1244: char fileresu[FILENAMELENGTH]; /* fileres without r in front */
1.126     brouard  1245: char filelog[FILENAMELENGTH]; /* Log file */
                   1246: char filerest[FILENAMELENGTH];
                   1247: char fileregp[FILENAMELENGTH];
                   1248: char popfile[FILENAMELENGTH];
                   1249: 
                   1250: char optionfilegnuplot[FILENAMELENGTH], optionfilehtm[FILENAMELENGTH], optionfilehtmcov[FILENAMELENGTH] ;
                   1251: 
1.157     brouard  1252: /* struct timeval start_time, end_time, curr_time, last_time, forecast_time; */
                   1253: /* struct timezone tzp; */
                   1254: /* extern int gettimeofday(); */
                   1255: struct tm tml, *gmtime(), *localtime();
                   1256: 
                   1257: extern time_t time();
                   1258: 
                   1259: struct tm start_time, end_time, curr_time, last_time, forecast_time;
                   1260: time_t  rstart_time, rend_time, rcurr_time, rlast_time, rforecast_time; /* raw time */
                   1261: struct tm tm;
                   1262: 
1.126     brouard  1263: char strcurr[80], strfor[80];
                   1264: 
                   1265: char *endptr;
                   1266: long lval;
                   1267: double dval;
                   1268: 
                   1269: #define NR_END 1
                   1270: #define FREE_ARG char*
                   1271: #define FTOL 1.0e-10
                   1272: 
                   1273: #define NRANSI 
1.240     brouard  1274: #define ITMAX 200
                   1275: #define ITPOWMAX 20 /* This is now multiplied by the number of parameters */ 
1.126     brouard  1276: 
                   1277: #define TOL 2.0e-4 
                   1278: 
                   1279: #define CGOLD 0.3819660 
                   1280: #define ZEPS 1.0e-10 
                   1281: #define SHFT(a,b,c,d) (a)=(b);(b)=(c);(c)=(d); 
                   1282: 
                   1283: #define GOLD 1.618034 
                   1284: #define GLIMIT 100.0 
                   1285: #define TINY 1.0e-20 
                   1286: 
                   1287: static double maxarg1,maxarg2;
                   1288: #define FMAX(a,b) (maxarg1=(a),maxarg2=(b),(maxarg1)>(maxarg2)? (maxarg1):(maxarg2))
                   1289: #define FMIN(a,b) (maxarg1=(a),maxarg2=(b),(maxarg1)<(maxarg2)? (maxarg1):(maxarg2))
                   1290:   
                   1291: #define SIGN(a,b) ((b)>0.0 ? fabs(a) : -fabs(a))
                   1292: #define rint(a) floor(a+0.5)
1.166     brouard  1293: /* http://www.thphys.uni-heidelberg.de/~robbers/cmbeasy/doc/html/myutils_8h-source.html */
1.183     brouard  1294: #define mytinydouble 1.0e-16
1.166     brouard  1295: /* #define DEQUAL(a,b) (fabs((a)-(b))<mytinydouble) */
                   1296: /* http://www.thphys.uni-heidelberg.de/~robbers/cmbeasy/doc/html/mynrutils_8h-source.html */
                   1297: /* static double dsqrarg; */
                   1298: /* #define DSQR(a) (DEQUAL((dsqrarg=(a)),0.0) ? 0.0 : dsqrarg*dsqrarg) */
1.126     brouard  1299: static double sqrarg;
                   1300: #define SQR(a) ((sqrarg=(a)) == 0.0 ? 0.0 :sqrarg*sqrarg)
                   1301: #define SWAP(a,b) {temp=(a);(a)=(b);(b)=temp;} 
                   1302: int agegomp= AGEGOMP;
                   1303: 
                   1304: int imx; 
                   1305: int stepm=1;
                   1306: /* Stepm, step in month: minimum step interpolation*/
                   1307: 
                   1308: int estepm;
                   1309: /* Estepm, step in month to interpolate survival function in order to approximate Life Expectancy*/
                   1310: 
                   1311: int m,nb;
                   1312: long *num;
1.197     brouard  1313: int firstpass=0, lastpass=4,*cod, *cens;
1.192     brouard  1314: int *ncodemax;  /* ncodemax[j]= Number of modalities of the j th
                   1315:                   covariate for which somebody answered excluding 
                   1316:                   undefined. Usually 2: 0 and 1. */
                   1317: int *ncodemaxwundef;  /* ncodemax[j]= Number of modalities of the j th
                   1318:                             covariate for which somebody answered including 
                   1319:                             undefined. Usually 3: -1, 0 and 1. */
1.126     brouard  1320: double **agev,*moisnais, *annais, *moisdc, *andc,**mint, **anint;
1.218     brouard  1321: double **pmmij, ***probs; /* Global pointer */
1.219     brouard  1322: double ***mobaverage, ***mobaverages; /* New global variable */
1.126     brouard  1323: double *ageexmed,*agecens;
                   1324: double dateintmean=0;
1.296     brouard  1325:   double anprojd, mprojd, jprojd; /* For eventual projections */
                   1326:   double anprojf, mprojf, jprojf;
1.126     brouard  1327: 
1.296     brouard  1328:   double anbackd, mbackd, jbackd; /* For eventual backprojections */
                   1329:   double anbackf, mbackf, jbackf;
                   1330:   double jintmean,mintmean,aintmean;  
1.126     brouard  1331: double *weight;
                   1332: int **s; /* Status */
1.141     brouard  1333: double *agedc;
1.145     brouard  1334: double  **covar; /**< covar[j,i], value of jth covariate for individual i,
1.141     brouard  1335:                  * covar=matrix(0,NCOVMAX,1,n); 
1.187     brouard  1336:                  * cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*age; */
1.268     brouard  1337: double **coqvar; /* Fixed quantitative covariate nqv */
                   1338: double ***cotvar; /* Time varying covariate ntv */
1.225     brouard  1339: double ***cotqvar; /* Time varying quantitative covariate itqv */
1.141     brouard  1340: double  idx; 
                   1341: int **nbcode, *Tvar; /**< model=V2 => Tvar[1]= 2 */
1.234     brouard  1342: /*           V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
                   1343: /*k          1  2   3   4     5    6    7     8    9 */
                   1344: /*Tvar[k]=   5  4   3   6     5    2    7     1    1 */
                   1345: /* Tndvar[k]    1   2   3               4          5 */
                   1346: /*TDvar         4   3   6               7          1 */ /* For outputs only; combination of dummies fixed or varying */
                   1347: /* Tns[k]    1  2   2              4               5 */ /* Number of single cova */
                   1348: /* TvarsD[k]    1   2                              3 */ /* Number of single dummy cova */
                   1349: /* TvarsDind    2   3                              9 */ /* position K of single dummy cova */
                   1350: /* TvarsQ[k] 1                     2                 */ /* Number of single quantitative cova */
                   1351: /* TvarsQind 1                     6                 */ /* position K of single quantitative cova */
                   1352: /* Tprod[i]=k           4               7            */
                   1353: /* Tage[i]=k                  5               8      */
                   1354: /* */
                   1355: /* Type                    */
                   1356: /* V         1  2  3  4  5 */
                   1357: /*           F  F  V  V  V */
                   1358: /*           D  Q  D  D  Q */
                   1359: /*                         */
                   1360: int *TvarsD;
                   1361: int *TvarsDind;
                   1362: int *TvarsQ;
                   1363: int *TvarsQind;
                   1364: 
1.235     brouard  1365: #define MAXRESULTLINES 10
                   1366: int nresult=0;
1.258     brouard  1367: int parameterline=0; /* # of the parameter (type) line */
1.235     brouard  1368: int TKresult[MAXRESULTLINES];
1.237     brouard  1369: int Tresult[MAXRESULTLINES][NCOVMAX];/* For dummy variable , value (output) */
                   1370: int Tinvresult[MAXRESULTLINES][NCOVMAX];/* For dummy variable , value (output) */
1.235     brouard  1371: int Tvresult[MAXRESULTLINES][NCOVMAX]; /* For dummy variable , variable # (output) */
                   1372: double Tqresult[MAXRESULTLINES][NCOVMAX]; /* For quantitative variable , value (output) */
1.237     brouard  1373: double Tqinvresult[MAXRESULTLINES][NCOVMAX]; /* For quantitative variable , value (output) */
1.235     brouard  1374: int Tvqresult[MAXRESULTLINES][NCOVMAX]; /* For quantitative variable , variable # (output) */
                   1375: 
1.234     brouard  1376: /* 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  1377: 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 */
                   1378: 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 */
                   1379: 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 */
                   1380: int *TvarVind; /**< TvarVind[1]=1, TvarVind[2]=2  in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
                   1381: 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 */
                   1382: 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  1383: int *TvarFD; /**< TvarFD[1]=V1 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
                   1384: int *TvarFDind; /* TvarFDind[1]=9 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
                   1385: int *TvarFQ; /* TvarFQ[1]=V2 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */ /* Only simple fixed quantitative variable */
                   1386: int *TvarFQind; /* TvarFQind[1]=6 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */ /* Only simple fixed quantitative variable */
                   1387: int *TvarVD; /* TvarVD[1]=V5 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */ /* Only simple fixed quantitative variable */
                   1388: int *TvarVDind; /* TvarVDind[1]=1 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */ /* Only simple fixed quantitative variable */
                   1389: 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 */
                   1390: 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 */
                   1391: 
1.230     brouard  1392: int *Tvarsel; /**< Selected covariates for output */
                   1393: double *Tvalsel; /**< Selected modality value of covariate for output */
1.226     brouard  1394: int *Typevar; /**< 0 for simple covariate (dummy, quantitative, fixed or varying), 1 for age product, 2 for  product */
1.227     brouard  1395: int *Fixed; /** Fixed[k] 0=fixed, 1 varying, 2 fixed with age product, 3 varying with age product */ 
                   1396: 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  1397: int *DummyV; /** Dummy[v] 0=dummy (0 1), 1 quantitative */
                   1398: int *FixedV; /** FixedV[v] 0 fixed, 1 varying */
1.197     brouard  1399: int *Tage;
1.227     brouard  1400: int anyvaryingduminmodel=0; /**< Any varying dummy in Model=1 yes, 0 no, to avoid a loop on waves in freq */ 
1.228     brouard  1401: 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  1402: 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*/ 
                   1403: 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  1404: int *Ndum; /** Freq of modality (tricode */
1.200     brouard  1405: /* int **codtab;*/ /**< codtab=imatrix(1,100,1,10); */
1.227     brouard  1406: int **Tvard;
                   1407: int *Tprod;/**< Gives the k position of the k1 product */
1.238     brouard  1408: /* Tprod[k1=1]=3(=V1*V4) for V2+V1+V1*V4+age*V3  */
1.227     brouard  1409: int *Tposprod; /**< Gives the k1 product from the k position */
1.238     brouard  1410:    /* if  V2+V1+V1*V4+age*V3+V3*V2   TProd[k1=2]=5 (V3*V2) */
                   1411:    /* Tposprod[k]=k1 , Tposprod[3]=1, Tposprod[5(V3*V2)]=2 (2nd product without age) */
1.227     brouard  1412: int cptcovprod, *Tvaraff, *invalidvarcomb;
1.126     brouard  1413: double *lsurv, *lpop, *tpop;
                   1414: 
1.231     brouard  1415: #define FD 1; /* Fixed dummy covariate */
                   1416: #define FQ 2; /* Fixed quantitative covariate */
                   1417: #define FP 3; /* Fixed product covariate */
                   1418: #define FPDD 7; /* Fixed product dummy*dummy covariate */
                   1419: #define FPDQ 8; /* Fixed product dummy*quantitative covariate */
                   1420: #define FPQQ 9; /* Fixed product quantitative*quantitative covariate */
                   1421: #define VD 10; /* Varying dummy covariate */
                   1422: #define VQ 11; /* Varying quantitative covariate */
                   1423: #define VP 12; /* Varying product covariate */
                   1424: #define VPDD 13; /* Varying product dummy*dummy covariate */
                   1425: #define VPDQ 14; /* Varying product dummy*quantitative covariate */
                   1426: #define VPQQ 15; /* Varying product quantitative*quantitative covariate */
                   1427: #define APFD 16; /* Age product * fixed dummy covariate */
                   1428: #define APFQ 17; /* Age product * fixed quantitative covariate */
                   1429: #define APVD 18; /* Age product * varying dummy covariate */
                   1430: #define APVQ 19; /* Age product * varying quantitative covariate */
                   1431: 
                   1432: #define FTYPE 1; /* Fixed covariate */
                   1433: #define VTYPE 2; /* Varying covariate (loop in wave) */
                   1434: #define ATYPE 2; /* Age product covariate (loop in dh within wave)*/
                   1435: 
                   1436: struct kmodel{
                   1437:        int maintype; /* main type */
                   1438:        int subtype; /* subtype */
                   1439: };
                   1440: struct kmodel modell[NCOVMAX];
                   1441: 
1.143     brouard  1442: double ftol=FTOL; /**< Tolerance for computing Max Likelihood */
                   1443: double ftolhess; /**< Tolerance for computing hessian */
1.126     brouard  1444: 
                   1445: /**************** split *************************/
                   1446: static int split( char *path, char *dirc, char *name, char *ext, char *finame )
                   1447: {
                   1448:   /* From a file name with (full) path (either Unix or Windows) we extract the directory (dirc)
                   1449:      the name of the file (name), its extension only (ext) and its first part of the name (finame)
                   1450:   */ 
                   1451:   char *ss;                            /* pointer */
1.186     brouard  1452:   int  l1=0, l2=0;                             /* length counters */
1.126     brouard  1453: 
                   1454:   l1 = strlen(path );                  /* length of path */
                   1455:   if ( l1 == 0 ) return( GLOCK_ERROR_NOPATH );
                   1456:   ss= strrchr( path, DIRSEPARATOR );           /* find last / */
                   1457:   if ( ss == NULL ) {                  /* no directory, so determine current directory */
                   1458:     strcpy( name, path );              /* we got the fullname name because no directory */
                   1459:     /*if(strrchr(path, ODIRSEPARATOR )==NULL)
                   1460:       printf("Warning you should use %s as a separator\n",DIRSEPARATOR);*/
                   1461:     /* get current working directory */
                   1462:     /*    extern  char* getcwd ( char *buf , int len);*/
1.184     brouard  1463: #ifdef WIN32
                   1464:     if (_getcwd( dirc, FILENAME_MAX ) == NULL ) {
                   1465: #else
                   1466:        if (getcwd(dirc, FILENAME_MAX) == NULL) {
                   1467: #endif
1.126     brouard  1468:       return( GLOCK_ERROR_GETCWD );
                   1469:     }
                   1470:     /* got dirc from getcwd*/
                   1471:     printf(" DIRC = %s \n",dirc);
1.205     brouard  1472:   } else {                             /* strip directory from path */
1.126     brouard  1473:     ss++;                              /* after this, the filename */
                   1474:     l2 = strlen( ss );                 /* length of filename */
                   1475:     if ( l2 == 0 ) return( GLOCK_ERROR_NOPATH );
                   1476:     strcpy( name, ss );                /* save file name */
                   1477:     strncpy( dirc, path, l1 - l2 );    /* now the directory */
1.186     brouard  1478:     dirc[l1-l2] = '\0';                        /* add zero */
1.126     brouard  1479:     printf(" DIRC2 = %s \n",dirc);
                   1480:   }
                   1481:   /* We add a separator at the end of dirc if not exists */
                   1482:   l1 = strlen( dirc );                 /* length of directory */
                   1483:   if( dirc[l1-1] != DIRSEPARATOR ){
                   1484:     dirc[l1] =  DIRSEPARATOR;
                   1485:     dirc[l1+1] = 0; 
                   1486:     printf(" DIRC3 = %s \n",dirc);
                   1487:   }
                   1488:   ss = strrchr( name, '.' );           /* find last / */
                   1489:   if (ss >0){
                   1490:     ss++;
                   1491:     strcpy(ext,ss);                    /* save extension */
                   1492:     l1= strlen( name);
                   1493:     l2= strlen(ss)+1;
                   1494:     strncpy( finame, name, l1-l2);
                   1495:     finame[l1-l2]= 0;
                   1496:   }
                   1497: 
                   1498:   return( 0 );                         /* we're done */
                   1499: }
                   1500: 
                   1501: 
                   1502: /******************************************/
                   1503: 
                   1504: void replace_back_to_slash(char *s, char*t)
                   1505: {
                   1506:   int i;
                   1507:   int lg=0;
                   1508:   i=0;
                   1509:   lg=strlen(t);
                   1510:   for(i=0; i<= lg; i++) {
                   1511:     (s[i] = t[i]);
                   1512:     if (t[i]== '\\') s[i]='/';
                   1513:   }
                   1514: }
                   1515: 
1.132     brouard  1516: char *trimbb(char *out, char *in)
1.137     brouard  1517: { /* Trim multiple blanks in line but keeps first blanks if line starts with blanks */
1.132     brouard  1518:   char *s;
                   1519:   s=out;
                   1520:   while (*in != '\0'){
1.137     brouard  1521:     while( *in == ' ' && *(in+1) == ' '){ /* && *(in+1) != '\0'){*/
1.132     brouard  1522:       in++;
                   1523:     }
                   1524:     *out++ = *in++;
                   1525:   }
                   1526:   *out='\0';
                   1527:   return s;
                   1528: }
                   1529: 
1.187     brouard  1530: /* char *substrchaine(char *out, char *in, char *chain) */
                   1531: /* { */
                   1532: /*   /\* Substract chain 'chain' from 'in', return and output 'out' *\/ */
                   1533: /*   char *s, *t; */
                   1534: /*   t=in;s=out; */
                   1535: /*   while ((*in != *chain) && (*in != '\0')){ */
                   1536: /*     *out++ = *in++; */
                   1537: /*   } */
                   1538: 
                   1539: /*   /\* *in matches *chain *\/ */
                   1540: /*   while ((*in++ == *chain++) && (*in != '\0')){ */
                   1541: /*     printf("*in = %c, *out= %c *chain= %c \n", *in, *out, *chain);  */
                   1542: /*   } */
                   1543: /*   in--; chain--; */
                   1544: /*   while ( (*in != '\0')){ */
                   1545: /*     printf("Bef *in = %c, *out= %c *chain= %c \n", *in, *out, *chain);  */
                   1546: /*     *out++ = *in++; */
                   1547: /*     printf("Aft *in = %c, *out= %c *chain= %c \n", *in, *out, *chain);  */
                   1548: /*   } */
                   1549: /*   *out='\0'; */
                   1550: /*   out=s; */
                   1551: /*   return out; */
                   1552: /* } */
                   1553: char *substrchaine(char *out, char *in, char *chain)
                   1554: {
                   1555:   /* Substract chain 'chain' from 'in', return and output 'out' */
                   1556:   /* in="V1+V1*age+age*age+V2", chain="age*age" */
                   1557: 
                   1558:   char *strloc;
                   1559: 
                   1560:   strcpy (out, in); 
                   1561:   strloc = strstr(out, chain); /* strloc points to out at age*age+V2 */
                   1562:   printf("Bef strloc=%s chain=%s out=%s \n", strloc, chain, out);
                   1563:   if(strloc != NULL){ 
                   1564:     /* will affect out */ /* strloc+strlenc(chain)=+V2 */ /* Will also work in Unicode */
                   1565:     memmove(strloc,strloc+strlen(chain), strlen(strloc+strlen(chain))+1);
                   1566:     /* strcpy (strloc, strloc +strlen(chain));*/
                   1567:   }
                   1568:   printf("Aft strloc=%s chain=%s in=%s out=%s \n", strloc, chain, in, out);
                   1569:   return out;
                   1570: }
                   1571: 
                   1572: 
1.145     brouard  1573: char *cutl(char *blocc, char *alocc, char *in, char occ)
                   1574: {
1.187     brouard  1575:   /* cuts string in into blocc and alocc where blocc ends before FIRST occurence of char 'occ' 
1.145     brouard  1576:      and alocc starts after first occurence of char 'occ' : ex cutv(blocc,alocc,"abcdef2ghi2j",'2')
1.310   ! brouard  1577:      gives alocc="abcdef" and blocc="ghi2j".
1.145     brouard  1578:      If occ is not found blocc is null and alocc is equal to in. Returns blocc
                   1579:   */
1.160     brouard  1580:   char *s, *t;
1.145     brouard  1581:   t=in;s=in;
                   1582:   while ((*in != occ) && (*in != '\0')){
                   1583:     *alocc++ = *in++;
                   1584:   }
                   1585:   if( *in == occ){
                   1586:     *(alocc)='\0';
                   1587:     s=++in;
                   1588:   }
                   1589:  
                   1590:   if (s == t) {/* occ not found */
                   1591:     *(alocc-(in-s))='\0';
                   1592:     in=s;
                   1593:   }
                   1594:   while ( *in != '\0'){
                   1595:     *blocc++ = *in++;
                   1596:   }
                   1597: 
                   1598:   *blocc='\0';
                   1599:   return t;
                   1600: }
1.137     brouard  1601: char *cutv(char *blocc, char *alocc, char *in, char occ)
                   1602: {
1.187     brouard  1603:   /* cuts string in into blocc and alocc where blocc ends before LAST occurence of char 'occ' 
1.137     brouard  1604:      and alocc starts after last occurence of char 'occ' : ex cutv(blocc,alocc,"abcdef2ghi2j",'2')
                   1605:      gives blocc="abcdef2ghi" and alocc="j".
                   1606:      If occ is not found blocc is null and alocc is equal to in. Returns alocc
                   1607:   */
                   1608:   char *s, *t;
                   1609:   t=in;s=in;
                   1610:   while (*in != '\0'){
                   1611:     while( *in == occ){
                   1612:       *blocc++ = *in++;
                   1613:       s=in;
                   1614:     }
                   1615:     *blocc++ = *in++;
                   1616:   }
                   1617:   if (s == t) /* occ not found */
                   1618:     *(blocc-(in-s))='\0';
                   1619:   else
                   1620:     *(blocc-(in-s)-1)='\0';
                   1621:   in=s;
                   1622:   while ( *in != '\0'){
                   1623:     *alocc++ = *in++;
                   1624:   }
                   1625: 
                   1626:   *alocc='\0';
                   1627:   return s;
                   1628: }
                   1629: 
1.126     brouard  1630: int nbocc(char *s, char occ)
                   1631: {
                   1632:   int i,j=0;
                   1633:   int lg=20;
                   1634:   i=0;
                   1635:   lg=strlen(s);
                   1636:   for(i=0; i<= lg; i++) {
1.234     brouard  1637:     if  (s[i] == occ ) j++;
1.126     brouard  1638:   }
                   1639:   return j;
                   1640: }
                   1641: 
1.137     brouard  1642: /* void cutv(char *u,char *v, char*t, char occ) */
                   1643: /* { */
                   1644: /*   /\* cuts string t into u and v where u ends before last occurence of char 'occ'  */
                   1645: /*      and v starts after last occurence of char 'occ' : ex cutv(u,v,"abcdef2ghi2j",'2') */
                   1646: /*      gives u="abcdef2ghi" and v="j" *\/ */
                   1647: /*   int i,lg,j,p=0; */
                   1648: /*   i=0; */
                   1649: /*   lg=strlen(t); */
                   1650: /*   for(j=0; j<=lg-1; j++) { */
                   1651: /*     if((t[j]!= occ) && (t[j+1]== occ)) p=j+1; */
                   1652: /*   } */
1.126     brouard  1653: 
1.137     brouard  1654: /*   for(j=0; j<p; j++) { */
                   1655: /*     (u[j] = t[j]); */
                   1656: /*   } */
                   1657: /*      u[p]='\0'; */
1.126     brouard  1658: 
1.137     brouard  1659: /*    for(j=0; j<= lg; j++) { */
                   1660: /*     if (j>=(p+1))(v[j-p-1] = t[j]); */
                   1661: /*   } */
                   1662: /* } */
1.126     brouard  1663: 
1.160     brouard  1664: #ifdef _WIN32
                   1665: char * strsep(char **pp, const char *delim)
                   1666: {
                   1667:   char *p, *q;
                   1668:          
                   1669:   if ((p = *pp) == NULL)
                   1670:     return 0;
                   1671:   if ((q = strpbrk (p, delim)) != NULL)
                   1672:   {
                   1673:     *pp = q + 1;
                   1674:     *q = '\0';
                   1675:   }
                   1676:   else
                   1677:     *pp = 0;
                   1678:   return p;
                   1679: }
                   1680: #endif
                   1681: 
1.126     brouard  1682: /********************** nrerror ********************/
                   1683: 
                   1684: void nrerror(char error_text[])
                   1685: {
                   1686:   fprintf(stderr,"ERREUR ...\n");
                   1687:   fprintf(stderr,"%s\n",error_text);
                   1688:   exit(EXIT_FAILURE);
                   1689: }
                   1690: /*********************** vector *******************/
                   1691: double *vector(int nl, int nh)
                   1692: {
                   1693:   double *v;
                   1694:   v=(double *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(double)));
                   1695:   if (!v) nrerror("allocation failure in vector");
                   1696:   return v-nl+NR_END;
                   1697: }
                   1698: 
                   1699: /************************ free vector ******************/
                   1700: void free_vector(double*v, int nl, int nh)
                   1701: {
                   1702:   free((FREE_ARG)(v+nl-NR_END));
                   1703: }
                   1704: 
                   1705: /************************ivector *******************************/
                   1706: int *ivector(long nl,long nh)
                   1707: {
                   1708:   int *v;
                   1709:   v=(int *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(int)));
                   1710:   if (!v) nrerror("allocation failure in ivector");
                   1711:   return v-nl+NR_END;
                   1712: }
                   1713: 
                   1714: /******************free ivector **************************/
                   1715: void free_ivector(int *v, long nl, long nh)
                   1716: {
                   1717:   free((FREE_ARG)(v+nl-NR_END));
                   1718: }
                   1719: 
                   1720: /************************lvector *******************************/
                   1721: long *lvector(long nl,long nh)
                   1722: {
                   1723:   long *v;
                   1724:   v=(long *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(long)));
                   1725:   if (!v) nrerror("allocation failure in ivector");
                   1726:   return v-nl+NR_END;
                   1727: }
                   1728: 
                   1729: /******************free lvector **************************/
                   1730: void free_lvector(long *v, long nl, long nh)
                   1731: {
                   1732:   free((FREE_ARG)(v+nl-NR_END));
                   1733: }
                   1734: 
                   1735: /******************* imatrix *******************************/
                   1736: int **imatrix(long nrl, long nrh, long ncl, long nch) 
                   1737:      /* allocate a int matrix with subscript range m[nrl..nrh][ncl..nch] */ 
                   1738: { 
                   1739:   long i, nrow=nrh-nrl+1,ncol=nch-ncl+1; 
                   1740:   int **m; 
                   1741:   
                   1742:   /* allocate pointers to rows */ 
                   1743:   m=(int **) malloc((size_t)((nrow+NR_END)*sizeof(int*))); 
                   1744:   if (!m) nrerror("allocation failure 1 in matrix()"); 
                   1745:   m += NR_END; 
                   1746:   m -= nrl; 
                   1747:   
                   1748:   
                   1749:   /* allocate rows and set pointers to them */ 
                   1750:   m[nrl]=(int *) malloc((size_t)((nrow*ncol+NR_END)*sizeof(int))); 
                   1751:   if (!m[nrl]) nrerror("allocation failure 2 in matrix()"); 
                   1752:   m[nrl] += NR_END; 
                   1753:   m[nrl] -= ncl; 
                   1754:   
                   1755:   for(i=nrl+1;i<=nrh;i++) m[i]=m[i-1]+ncol; 
                   1756:   
                   1757:   /* return pointer to array of pointers to rows */ 
                   1758:   return m; 
                   1759: } 
                   1760: 
                   1761: /****************** free_imatrix *************************/
                   1762: void free_imatrix(m,nrl,nrh,ncl,nch)
                   1763:       int **m;
                   1764:       long nch,ncl,nrh,nrl; 
                   1765:      /* free an int matrix allocated by imatrix() */ 
                   1766: { 
                   1767:   free((FREE_ARG) (m[nrl]+ncl-NR_END)); 
                   1768:   free((FREE_ARG) (m+nrl-NR_END)); 
                   1769: } 
                   1770: 
                   1771: /******************* matrix *******************************/
                   1772: double **matrix(long nrl, long nrh, long ncl, long nch)
                   1773: {
                   1774:   long i, nrow=nrh-nrl+1, ncol=nch-ncl+1;
                   1775:   double **m;
                   1776: 
                   1777:   m=(double **) malloc((size_t)((nrow+NR_END)*sizeof(double*)));
                   1778:   if (!m) nrerror("allocation failure 1 in matrix()");
                   1779:   m += NR_END;
                   1780:   m -= nrl;
                   1781: 
                   1782:   m[nrl]=(double *) malloc((size_t)((nrow*ncol+NR_END)*sizeof(double)));
                   1783:   if (!m[nrl]) nrerror("allocation failure 2 in matrix()");
                   1784:   m[nrl] += NR_END;
                   1785:   m[nrl] -= ncl;
                   1786: 
                   1787:   for (i=nrl+1; i<=nrh; i++) m[i]=m[i-1]+ncol;
                   1788:   return m;
1.145     brouard  1789:   /* print *(*(m+1)+70) or print m[1][70]; print m+1 or print &(m[1]) or &(m[1][0])
                   1790: m[i] = address of ith row of the table. &(m[i]) is its value which is another adress
                   1791: that of m[i][0]. In order to get the value p m[i][0] but it is unitialized.
1.126     brouard  1792:    */
                   1793: }
                   1794: 
                   1795: /*************************free matrix ************************/
                   1796: void free_matrix(double **m, long nrl, long nrh, long ncl, long nch)
                   1797: {
                   1798:   free((FREE_ARG)(m[nrl]+ncl-NR_END));
                   1799:   free((FREE_ARG)(m+nrl-NR_END));
                   1800: }
                   1801: 
                   1802: /******************* ma3x *******************************/
                   1803: double ***ma3x(long nrl, long nrh, long ncl, long nch, long nll, long nlh)
                   1804: {
                   1805:   long i, j, nrow=nrh-nrl+1, ncol=nch-ncl+1, nlay=nlh-nll+1;
                   1806:   double ***m;
                   1807: 
                   1808:   m=(double ***) malloc((size_t)((nrow+NR_END)*sizeof(double*)));
                   1809:   if (!m) nrerror("allocation failure 1 in matrix()");
                   1810:   m += NR_END;
                   1811:   m -= nrl;
                   1812: 
                   1813:   m[nrl]=(double **) malloc((size_t)((nrow*ncol+NR_END)*sizeof(double)));
                   1814:   if (!m[nrl]) nrerror("allocation failure 2 in matrix()");
                   1815:   m[nrl] += NR_END;
                   1816:   m[nrl] -= ncl;
                   1817: 
                   1818:   for (i=nrl+1; i<=nrh; i++) m[i]=m[i-1]+ncol;
                   1819: 
                   1820:   m[nrl][ncl]=(double *) malloc((size_t)((nrow*ncol*nlay+NR_END)*sizeof(double)));
                   1821:   if (!m[nrl][ncl]) nrerror("allocation failure 3 in matrix()");
                   1822:   m[nrl][ncl] += NR_END;
                   1823:   m[nrl][ncl] -= nll;
                   1824:   for (j=ncl+1; j<=nch; j++) 
                   1825:     m[nrl][j]=m[nrl][j-1]+nlay;
                   1826:   
                   1827:   for (i=nrl+1; i<=nrh; i++) {
                   1828:     m[i][ncl]=m[i-1l][ncl]+ncol*nlay;
                   1829:     for (j=ncl+1; j<=nch; j++) 
                   1830:       m[i][j]=m[i][j-1]+nlay;
                   1831:   }
                   1832:   return m; 
                   1833:   /*  gdb: p *(m+1) <=> p m[1] and p (m+1) <=> p (m+1) <=> p &(m[1])
                   1834:            &(m[i][j][k]) <=> *((*(m+i) + j)+k)
                   1835:   */
                   1836: }
                   1837: 
                   1838: /*************************free ma3x ************************/
                   1839: void free_ma3x(double ***m, long nrl, long nrh, long ncl, long nch,long nll, long nlh)
                   1840: {
                   1841:   free((FREE_ARG)(m[nrl][ncl]+ nll-NR_END));
                   1842:   free((FREE_ARG)(m[nrl]+ncl-NR_END));
                   1843:   free((FREE_ARG)(m+nrl-NR_END));
                   1844: }
                   1845: 
                   1846: /*************** function subdirf ***********/
                   1847: char *subdirf(char fileres[])
                   1848: {
                   1849:   /* Caution optionfilefiname is hidden */
                   1850:   strcpy(tmpout,optionfilefiname);
                   1851:   strcat(tmpout,"/"); /* Add to the right */
                   1852:   strcat(tmpout,fileres);
                   1853:   return tmpout;
                   1854: }
                   1855: 
                   1856: /*************** function subdirf2 ***********/
                   1857: char *subdirf2(char fileres[], char *preop)
                   1858: {
                   1859:   
                   1860:   /* Caution optionfilefiname is hidden */
                   1861:   strcpy(tmpout,optionfilefiname);
                   1862:   strcat(tmpout,"/");
                   1863:   strcat(tmpout,preop);
                   1864:   strcat(tmpout,fileres);
                   1865:   return tmpout;
                   1866: }
                   1867: 
                   1868: /*************** function subdirf3 ***********/
                   1869: char *subdirf3(char fileres[], char *preop, char *preop2)
                   1870: {
                   1871:   
                   1872:   /* Caution optionfilefiname is hidden */
                   1873:   strcpy(tmpout,optionfilefiname);
                   1874:   strcat(tmpout,"/");
                   1875:   strcat(tmpout,preop);
                   1876:   strcat(tmpout,preop2);
                   1877:   strcat(tmpout,fileres);
                   1878:   return tmpout;
                   1879: }
1.213     brouard  1880:  
                   1881: /*************** function subdirfext ***********/
                   1882: char *subdirfext(char fileres[], char *preop, char *postop)
                   1883: {
                   1884:   
                   1885:   strcpy(tmpout,preop);
                   1886:   strcat(tmpout,fileres);
                   1887:   strcat(tmpout,postop);
                   1888:   return tmpout;
                   1889: }
1.126     brouard  1890: 
1.213     brouard  1891: /*************** function subdirfext3 ***********/
                   1892: char *subdirfext3(char fileres[], char *preop, char *postop)
                   1893: {
                   1894:   
                   1895:   /* Caution optionfilefiname is hidden */
                   1896:   strcpy(tmpout,optionfilefiname);
                   1897:   strcat(tmpout,"/");
                   1898:   strcat(tmpout,preop);
                   1899:   strcat(tmpout,fileres);
                   1900:   strcat(tmpout,postop);
                   1901:   return tmpout;
                   1902: }
                   1903:  
1.162     brouard  1904: char *asc_diff_time(long time_sec, char ascdiff[])
                   1905: {
                   1906:   long sec_left, days, hours, minutes;
                   1907:   days = (time_sec) / (60*60*24);
                   1908:   sec_left = (time_sec) % (60*60*24);
                   1909:   hours = (sec_left) / (60*60) ;
                   1910:   sec_left = (sec_left) %(60*60);
                   1911:   minutes = (sec_left) /60;
                   1912:   sec_left = (sec_left) % (60);
                   1913:   sprintf(ascdiff,"%ld day(s) %ld hour(s) %ld minute(s) %ld second(s)",days, hours, minutes, sec_left);  
                   1914:   return ascdiff;
                   1915: }
                   1916: 
1.126     brouard  1917: /***************** f1dim *************************/
                   1918: extern int ncom; 
                   1919: extern double *pcom,*xicom;
                   1920: extern double (*nrfunc)(double []); 
                   1921:  
                   1922: double f1dim(double x) 
                   1923: { 
                   1924:   int j; 
                   1925:   double f;
                   1926:   double *xt; 
                   1927:  
                   1928:   xt=vector(1,ncom); 
                   1929:   for (j=1;j<=ncom;j++) xt[j]=pcom[j]+x*xicom[j]; 
                   1930:   f=(*nrfunc)(xt); 
                   1931:   free_vector(xt,1,ncom); 
                   1932:   return f; 
                   1933: } 
                   1934: 
                   1935: /*****************brent *************************/
                   1936: double brent(double ax, double bx, double cx, double (*f)(double), double tol,         double *xmin) 
1.187     brouard  1937: {
                   1938:   /* Given a function f, and given a bracketing triplet of abscissas ax, bx, cx (such that bx is
                   1939:    * between ax and cx, and f(bx) is less than both f(ax) and f(cx) ), this routine isolates
                   1940:    * the minimum to a fractional precision of about tol using Brent’s method. The abscissa of
                   1941:    * the minimum is returned as xmin, and the minimum function value is returned as brent , the
                   1942:    * returned function value. 
                   1943:   */
1.126     brouard  1944:   int iter; 
                   1945:   double a,b,d,etemp;
1.159     brouard  1946:   double fu=0,fv,fw,fx;
1.164     brouard  1947:   double ftemp=0.;
1.126     brouard  1948:   double p,q,r,tol1,tol2,u,v,w,x,xm; 
                   1949:   double e=0.0; 
                   1950:  
                   1951:   a=(ax < cx ? ax : cx); 
                   1952:   b=(ax > cx ? ax : cx); 
                   1953:   x=w=v=bx; 
                   1954:   fw=fv=fx=(*f)(x); 
                   1955:   for (iter=1;iter<=ITMAX;iter++) { 
                   1956:     xm=0.5*(a+b); 
                   1957:     tol2=2.0*(tol1=tol*fabs(x)+ZEPS); 
                   1958:     /*         if (2.0*fabs(fp-(*fret)) <= ftol*(fabs(fp)+fabs(*fret)))*/
                   1959:     printf(".");fflush(stdout);
                   1960:     fprintf(ficlog,".");fflush(ficlog);
1.162     brouard  1961: #ifdef DEBUGBRENT
1.126     brouard  1962:     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);
                   1963:     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);
                   1964:     /*         if ((fabs(x-xm) <= (tol2-0.5*(b-a)))||(2.0*fabs(fu-ftemp) <= ftol*1.e-2*(fabs(fu)+fabs(ftemp)))) { */
                   1965: #endif
                   1966:     if (fabs(x-xm) <= (tol2-0.5*(b-a))){ 
                   1967:       *xmin=x; 
                   1968:       return fx; 
                   1969:     } 
                   1970:     ftemp=fu;
                   1971:     if (fabs(e) > tol1) { 
                   1972:       r=(x-w)*(fx-fv); 
                   1973:       q=(x-v)*(fx-fw); 
                   1974:       p=(x-v)*q-(x-w)*r; 
                   1975:       q=2.0*(q-r); 
                   1976:       if (q > 0.0) p = -p; 
                   1977:       q=fabs(q); 
                   1978:       etemp=e; 
                   1979:       e=d; 
                   1980:       if (fabs(p) >= fabs(0.5*q*etemp) || p <= q*(a-x) || p >= q*(b-x)) 
1.224     brouard  1981:                                d=CGOLD*(e=(x >= xm ? a-x : b-x)); 
1.126     brouard  1982:       else { 
1.224     brouard  1983:                                d=p/q; 
                   1984:                                u=x+d; 
                   1985:                                if (u-a < tol2 || b-u < tol2) 
                   1986:                                        d=SIGN(tol1,xm-x); 
1.126     brouard  1987:       } 
                   1988:     } else { 
                   1989:       d=CGOLD*(e=(x >= xm ? a-x : b-x)); 
                   1990:     } 
                   1991:     u=(fabs(d) >= tol1 ? x+d : x+SIGN(tol1,d)); 
                   1992:     fu=(*f)(u); 
                   1993:     if (fu <= fx) { 
                   1994:       if (u >= x) a=x; else b=x; 
                   1995:       SHFT(v,w,x,u) 
1.183     brouard  1996:       SHFT(fv,fw,fx,fu) 
                   1997:     } else { 
                   1998:       if (u < x) a=u; else b=u; 
                   1999:       if (fu <= fw || w == x) { 
1.224     brouard  2000:                                v=w; 
                   2001:                                w=u; 
                   2002:                                fv=fw; 
                   2003:                                fw=fu; 
1.183     brouard  2004:       } else if (fu <= fv || v == x || v == w) { 
1.224     brouard  2005:                                v=u; 
                   2006:                                fv=fu; 
1.183     brouard  2007:       } 
                   2008:     } 
1.126     brouard  2009:   } 
                   2010:   nrerror("Too many iterations in brent"); 
                   2011:   *xmin=x; 
                   2012:   return fx; 
                   2013: } 
                   2014: 
                   2015: /****************** mnbrak ***********************/
                   2016: 
                   2017: void mnbrak(double *ax, double *bx, double *cx, double *fa, double *fb, double *fc, 
                   2018:            double (*func)(double)) 
1.183     brouard  2019: { /* Given a function func , and given distinct initial points ax and bx , this routine searches in
                   2020: the downhill direction (defined by the function as evaluated at the initial points) and returns
                   2021: new points ax , bx , cx that bracket a minimum of the function. Also returned are the function
                   2022: values at the three points, fa, fb , and fc such that fa > fb and fb < fc.
                   2023:    */
1.126     brouard  2024:   double ulim,u,r,q, dum;
                   2025:   double fu; 
1.187     brouard  2026: 
                   2027:   double scale=10.;
                   2028:   int iterscale=0;
                   2029: 
                   2030:   *fa=(*func)(*ax); /*  xta[j]=pcom[j]+(*ax)*xicom[j]; fa=f(xta[j])*/
                   2031:   *fb=(*func)(*bx); /*  xtb[j]=pcom[j]+(*bx)*xicom[j]; fb=f(xtb[j]) */
                   2032: 
                   2033: 
                   2034:   /* while(*fb != *fb){ /\* *ax should be ok, reducing distance to *ax *\/ */
                   2035:   /*   printf("Warning mnbrak *fb = %lf, *bx=%lf *ax=%lf *fa==%lf iter=%d\n",*fb, *bx, *ax, *fa, iterscale++); */
                   2036:   /*   *bx = *ax - (*ax - *bx)/scale; */
                   2037:   /*   *fb=(*func)(*bx);  /\*  xtb[j]=pcom[j]+(*bx)*xicom[j]; fb=f(xtb[j]) *\/ */
                   2038:   /* } */
                   2039: 
1.126     brouard  2040:   if (*fb > *fa) { 
                   2041:     SHFT(dum,*ax,*bx,dum) 
1.183     brouard  2042:     SHFT(dum,*fb,*fa,dum) 
                   2043:   } 
1.126     brouard  2044:   *cx=(*bx)+GOLD*(*bx-*ax); 
                   2045:   *fc=(*func)(*cx); 
1.183     brouard  2046: #ifdef DEBUG
1.224     brouard  2047:   printf("mnbrak0 a=%lf *fa=%lf, b=%lf *fb=%lf, c=%lf *fc=%lf\n",*ax,*fa,*bx,*fb,*cx, *fc);
                   2048:   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  2049: #endif
1.224     brouard  2050:   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  2051:     r=(*bx-*ax)*(*fb-*fc); 
1.224     brouard  2052:     q=(*bx-*cx)*(*fb-*fa); /* What if fa=inf */
1.126     brouard  2053:     u=(*bx)-((*bx-*cx)*q-(*bx-*ax)*r)/ 
1.183     brouard  2054:       (2.0*SIGN(FMAX(fabs(q-r),TINY),q-r)); /* Minimum abscissa of a parabolic estimated from (a,fa), (b,fb) and (c,fc). */
                   2055:     ulim=(*bx)+GLIMIT*(*cx-*bx); /* Maximum abscissa where function should be evaluated */
                   2056:     if ((*bx-u)*(u-*cx) > 0.0) { /* if u_p is between b and c */
1.126     brouard  2057:       fu=(*func)(u); 
1.163     brouard  2058: #ifdef DEBUG
                   2059:       /* f(x)=A(x-u)**2+f(u) */
                   2060:       double A, fparabu; 
                   2061:       A= (*fb - *fa)/(*bx-*ax)/(*bx+*ax-2*u);
                   2062:       fparabu= *fa - A*(*ax-u)*(*ax-u);
1.224     brouard  2063:       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);
                   2064:       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  2065:       /* And thus,it can be that fu > *fc even if fparabu < *fc */
                   2066:       /* mnbrak (*ax=7.666299858533, *fa=299039.693133272231), (*bx=8.595447774979, *fb=298976.598289369489),
                   2067:         (*cx=10.098840694817, *fc=298946.631474258087),  (*u=9.852501168332, fu=298948.773013752128, fparabu=298945.434711494134) */
                   2068:       /* In that case, there is no bracket in the output! Routine is wrong with many consequences.*/
1.163     brouard  2069: #endif 
1.184     brouard  2070: #ifdef MNBRAKORIGINAL
1.183     brouard  2071: #else
1.191     brouard  2072: /*       if (fu > *fc) { */
                   2073: /* #ifdef DEBUG */
                   2074: /*       printf("mnbrak4  fu > fc \n"); */
                   2075: /*       fprintf(ficlog, "mnbrak4 fu > fc\n"); */
                   2076: /* #endif */
                   2077: /*     /\* 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 *\\/  *\/ */
                   2078: /*     /\* SHFT(*fa,*fc,fu,*fc) /\\* (b, u, c) is a bracket while test fb > fc will be fu > fc  will exit *\\/ *\/ */
                   2079: /*     dum=u; /\* Shifting c and u *\/ */
                   2080: /*     u = *cx; */
                   2081: /*     *cx = dum; */
                   2082: /*     dum = fu; */
                   2083: /*     fu = *fc; */
                   2084: /*     *fc =dum; */
                   2085: /*       } else { /\* end *\/ */
                   2086: /* #ifdef DEBUG */
                   2087: /*       printf("mnbrak3  fu < fc \n"); */
                   2088: /*       fprintf(ficlog, "mnbrak3 fu < fc\n"); */
                   2089: /* #endif */
                   2090: /*     dum=u; /\* Shifting c and u *\/ */
                   2091: /*     u = *cx; */
                   2092: /*     *cx = dum; */
                   2093: /*     dum = fu; */
                   2094: /*     fu = *fc; */
                   2095: /*     *fc =dum; */
                   2096: /*       } */
1.224     brouard  2097: #ifdef DEBUGMNBRAK
                   2098:                 double A, fparabu; 
                   2099:      A= (*fb - *fa)/(*bx-*ax)/(*bx+*ax-2*u);
                   2100:      fparabu= *fa - A*(*ax-u)*(*ax-u);
                   2101:      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);
                   2102:      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  2103: #endif
1.191     brouard  2104:       dum=u; /* Shifting c and u */
                   2105:       u = *cx;
                   2106:       *cx = dum;
                   2107:       dum = fu;
                   2108:       fu = *fc;
                   2109:       *fc =dum;
1.183     brouard  2110: #endif
1.162     brouard  2111:     } else if ((*cx-u)*(u-ulim) > 0.0) { /* u is after c but before ulim */
1.183     brouard  2112: #ifdef DEBUG
1.224     brouard  2113:       printf("\nmnbrak2  u=%lf after c=%lf but before ulim\n",u,*cx);
                   2114:       fprintf(ficlog,"\nmnbrak2  u=%lf after c=%lf but before ulim\n",u,*cx);
1.183     brouard  2115: #endif
1.126     brouard  2116:       fu=(*func)(u); 
                   2117:       if (fu < *fc) { 
1.183     brouard  2118: #ifdef DEBUG
1.224     brouard  2119:                                printf("\nmnbrak2  u=%lf after c=%lf but before ulim=%lf AND fu=%lf < %lf=fc\n",u,*cx,ulim,fu, *fc);
                   2120:                          fprintf(ficlog,"\nmnbrak2  u=%lf after c=%lf but before ulim=%lf AND fu=%lf < %lf=fc\n",u,*cx,ulim,fu, *fc);
                   2121: #endif
                   2122:                          SHFT(*bx,*cx,u,*cx+GOLD*(*cx-*bx)) 
                   2123:                                SHFT(*fb,*fc,fu,(*func)(u)) 
                   2124: #ifdef DEBUG
                   2125:                                        printf("\nmnbrak2 shift GOLD c=%lf",*cx+GOLD*(*cx-*bx));
1.183     brouard  2126: #endif
                   2127:       } 
1.162     brouard  2128:     } else if ((u-ulim)*(ulim-*cx) >= 0.0) { /* u outside ulim (verifying that ulim is beyond c) */
1.183     brouard  2129: #ifdef DEBUG
1.224     brouard  2130:       printf("\nmnbrak2  u=%lf outside ulim=%lf (verifying that ulim is beyond c=%lf)\n",u,ulim,*cx);
                   2131:       fprintf(ficlog,"\nmnbrak2  u=%lf outside ulim=%lf (verifying that ulim is beyond c=%lf)\n",u,ulim,*cx);
1.183     brouard  2132: #endif
1.126     brouard  2133:       u=ulim; 
                   2134:       fu=(*func)(u); 
1.183     brouard  2135:     } else { /* u could be left to b (if r > q parabola has a maximum) */
                   2136: #ifdef DEBUG
1.224     brouard  2137:       printf("\nmnbrak2  u=%lf could be left to b=%lf (if r=%lf > q=%lf parabola has a maximum)\n",u,*bx,r,q);
                   2138:       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  2139: #endif
1.126     brouard  2140:       u=(*cx)+GOLD*(*cx-*bx); 
                   2141:       fu=(*func)(u); 
1.224     brouard  2142: #ifdef DEBUG
                   2143:       printf("\nmnbrak2 new u=%lf fu=%lf shifted gold left from c=%lf and b=%lf \n",u,fu,*cx,*bx);
                   2144:       fprintf(ficlog,"\nmnbrak2 new u=%lf fu=%lf shifted gold left from c=%lf and b=%lf \n",u,fu,*cx,*bx);
                   2145: #endif
1.183     brouard  2146:     } /* end tests */
1.126     brouard  2147:     SHFT(*ax,*bx,*cx,u) 
1.183     brouard  2148:     SHFT(*fa,*fb,*fc,fu) 
                   2149: #ifdef DEBUG
1.224     brouard  2150:       printf("\nmnbrak2 shift (*ax=%.12f, *fa=%.12lf), (*bx=%.12f, *fb=%.12lf), (*cx=%.12f, *fc=%.12lf)\n",*ax,*fa,*bx,*fb,*cx,*fc);
                   2151:       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  2152: #endif
                   2153:   } /* 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  2154: } 
                   2155: 
                   2156: /*************** linmin ************************/
1.162     brouard  2157: /* Given an n -dimensional point p[1..n] and an n -dimensional direction xi[1..n] , moves and
                   2158: resets p to where the function func(p) takes on a minimum along the direction xi from p ,
                   2159: and replaces xi by the actual vector displacement that p was moved. Also returns as fret
                   2160: the value of func at the returned location p . This is actually all accomplished by calling the
                   2161: routines mnbrak and brent .*/
1.126     brouard  2162: int ncom; 
                   2163: double *pcom,*xicom;
                   2164: double (*nrfunc)(double []); 
                   2165:  
1.224     brouard  2166: #ifdef LINMINORIGINAL
1.126     brouard  2167: void linmin(double p[], double xi[], int n, double *fret,double (*func)(double [])) 
1.224     brouard  2168: #else
                   2169: void linmin(double p[], double xi[], int n, double *fret,double (*func)(double []), int *flat) 
                   2170: #endif
1.126     brouard  2171: { 
                   2172:   double brent(double ax, double bx, double cx, 
                   2173:               double (*f)(double), double tol, double *xmin); 
                   2174:   double f1dim(double x); 
                   2175:   void mnbrak(double *ax, double *bx, double *cx, double *fa, double *fb, 
                   2176:              double *fc, double (*func)(double)); 
                   2177:   int j; 
                   2178:   double xx,xmin,bx,ax; 
                   2179:   double fx,fb,fa;
1.187     brouard  2180: 
1.203     brouard  2181: #ifdef LINMINORIGINAL
                   2182: #else
                   2183:   double scale=10., axs, xxs; /* Scale added for infinity */
                   2184: #endif
                   2185:   
1.126     brouard  2186:   ncom=n; 
                   2187:   pcom=vector(1,n); 
                   2188:   xicom=vector(1,n); 
                   2189:   nrfunc=func; 
                   2190:   for (j=1;j<=n;j++) { 
                   2191:     pcom[j]=p[j]; 
1.202     brouard  2192:     xicom[j]=xi[j]; /* Former scale xi[j] of currrent direction i */
1.126     brouard  2193:   } 
1.187     brouard  2194: 
1.203     brouard  2195: #ifdef LINMINORIGINAL
                   2196:   xx=1.;
                   2197: #else
                   2198:   axs=0.0;
                   2199:   xxs=1.;
                   2200:   do{
                   2201:     xx= xxs;
                   2202: #endif
1.187     brouard  2203:     ax=0.;
                   2204:     mnbrak(&ax,&xx,&bx,&fa,&fx,&fb,f1dim);  /* Outputs: xtx[j]=pcom[j]+(*xx)*xicom[j]; fx=f(xtx[j]) */
                   2205:     /* brackets with inputs ax=0 and xx=1, but points, pcom=p, and directions values, xicom=xi, are sent via f1dim(x) */
                   2206:     /* 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))   */
                   2207:     /* Outputs: fa=f(p(j)) and fx=f(p(j) + xxs * xi(j) ) and f(bx)= f(p(j)+ bx* xi(j)) */
                   2208:     /* Given input ax=axs and xx=xxs, xx might be too far from ax to get a finite f(xx) */
                   2209:     /* Searches on line, outputs (ax, xx, bx) such that fx < min(fa and fb) */
                   2210:     /* 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  2211: #ifdef LINMINORIGINAL
                   2212: #else
                   2213:     if (fx != fx){
1.224     brouard  2214:                        xxs=xxs/scale; /* Trying a smaller xx, closer to initial ax=0 */
                   2215:                        printf("|");
                   2216:                        fprintf(ficlog,"|");
1.203     brouard  2217: #ifdef DEBUGLINMIN
1.224     brouard  2218:                        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  2219: #endif
                   2220:     }
1.224     brouard  2221:   }while(fx != fx && xxs > 1.e-5);
1.203     brouard  2222: #endif
                   2223:   
1.191     brouard  2224: #ifdef DEBUGLINMIN
                   2225:   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  2226:   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  2227: #endif
1.224     brouard  2228: #ifdef LINMINORIGINAL
                   2229: #else
                   2230:        if(fb == fx){ /* Flat function in the direction */
                   2231:                xmin=xx;
                   2232:     *flat=1;
                   2233:        }else{
                   2234:     *flat=0;
                   2235: #endif
                   2236:                /*Flat mnbrak2 shift (*ax=0.000000000000, *fa=51626.272983130431), (*bx=-1.618034000000, *fb=51590.149499362531), (*cx=-4.236068025156, *fc=51590.149499362531) */
1.187     brouard  2237:   *fret=brent(ax,xx,bx,f1dim,TOL,&xmin); /* Giving a bracketting triplet (ax, xx, bx), find a minimum, xmin, according to f1dim, *fret(xmin),*/
                   2238:   /* fa = f(p[j] + ax * xi[j]), fx = f(p[j] + xx * xi[j]), fb = f(p[j] + bx * xi[j]) */
                   2239:   /* fmin = f(p[j] + xmin * xi[j]) */
                   2240:   /* P+lambda n in that direction (lambdamin), with TOL between abscisses */
                   2241:   /* f1dim(xmin): for (j=1;j<=ncom;j++) xt[j]=pcom[j]+xmin*xicom[j]; */
1.126     brouard  2242: #ifdef DEBUG
1.224     brouard  2243:   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);
                   2244:   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);
                   2245: #endif
                   2246: #ifdef LINMINORIGINAL
                   2247: #else
                   2248:                        }
1.126     brouard  2249: #endif
1.191     brouard  2250: #ifdef DEBUGLINMIN
                   2251:   printf("linmin end ");
1.202     brouard  2252:   fprintf(ficlog,"linmin end ");
1.191     brouard  2253: #endif
1.126     brouard  2254:   for (j=1;j<=n;j++) { 
1.203     brouard  2255: #ifdef LINMINORIGINAL
                   2256:     xi[j] *= xmin; 
                   2257: #else
                   2258: #ifdef DEBUGLINMIN
                   2259:     if(xxs <1.0)
                   2260:       printf(" before xi[%d]=%12.8f", j,xi[j]);
                   2261: #endif
                   2262:     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) */
                   2263: #ifdef DEBUGLINMIN
                   2264:     if(xxs <1.0)
                   2265:       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 );
                   2266: #endif
                   2267: #endif
1.187     brouard  2268:     p[j] += xi[j]; /* Parameters values are updated accordingly */
1.126     brouard  2269:   } 
1.191     brouard  2270: #ifdef DEBUGLINMIN
1.203     brouard  2271:   printf("\n");
1.191     brouard  2272:   printf("Comparing last *frec(xmin=%12.8f)=%12.8f from Brent and frec(0.)=%12.8f \n", xmin, *fret, (*func)(p));
1.202     brouard  2273:   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  2274:   for (j=1;j<=n;j++) { 
1.202     brouard  2275:     printf(" xi[%d]= %14.10f p[%d]= %12.7f",j,xi[j],j,p[j]);
                   2276:     fprintf(ficlog," xi[%d]= %14.10f p[%d]= %12.7f",j,xi[j],j,p[j]);
                   2277:     if(j % ncovmodel == 0){
1.191     brouard  2278:       printf("\n");
1.202     brouard  2279:       fprintf(ficlog,"\n");
                   2280:     }
1.191     brouard  2281:   }
1.203     brouard  2282: #else
1.191     brouard  2283: #endif
1.126     brouard  2284:   free_vector(xicom,1,n); 
                   2285:   free_vector(pcom,1,n); 
                   2286: } 
                   2287: 
                   2288: 
                   2289: /*************** powell ************************/
1.162     brouard  2290: /*
                   2291: Minimization of a function func of n variables. Input consists of an initial starting point
                   2292: p[1..n] ; an initial matrix xi[1..n][1..n] , whose columns contain the initial set of di-
                   2293: rections (usually the n unit vectors); and ftol , the fractional tolerance in the function value
                   2294: such that failure to decrease by more than this amount on one iteration signals doneness. On
                   2295: output, p is set to the best point found, xi is the then-current direction set, fret is the returned
                   2296: function value at p , and iter is the number of iterations taken. The routine linmin is used.
                   2297:  */
1.224     brouard  2298: #ifdef LINMINORIGINAL
                   2299: #else
                   2300:        int *flatdir; /* Function is vanishing in that direction */
1.225     brouard  2301:        int flat=0, flatd=0; /* Function is vanishing in that direction */
1.224     brouard  2302: #endif
1.126     brouard  2303: void powell(double p[], double **xi, int n, double ftol, int *iter, double *fret, 
                   2304:            double (*func)(double [])) 
                   2305: { 
1.224     brouard  2306: #ifdef LINMINORIGINAL
                   2307:  void linmin(double p[], double xi[], int n, double *fret, 
1.126     brouard  2308:              double (*func)(double [])); 
1.224     brouard  2309: #else 
1.241     brouard  2310:  void linmin(double p[], double xi[], int n, double *fret,
                   2311:             double (*func)(double []),int *flat); 
1.224     brouard  2312: #endif
1.239     brouard  2313:  int i,ibig,j,jk,k; 
1.126     brouard  2314:   double del,t,*pt,*ptt,*xit;
1.181     brouard  2315:   double directest;
1.126     brouard  2316:   double fp,fptt;
                   2317:   double *xits;
                   2318:   int niterf, itmp;
1.224     brouard  2319: #ifdef LINMINORIGINAL
                   2320: #else
                   2321: 
                   2322:   flatdir=ivector(1,n); 
                   2323:   for (j=1;j<=n;j++) flatdir[j]=0; 
                   2324: #endif
1.126     brouard  2325: 
                   2326:   pt=vector(1,n); 
                   2327:   ptt=vector(1,n); 
                   2328:   xit=vector(1,n); 
                   2329:   xits=vector(1,n); 
                   2330:   *fret=(*func)(p); 
                   2331:   for (j=1;j<=n;j++) pt[j]=p[j]; 
1.202     brouard  2332:   rcurr_time = time(NULL);  
1.126     brouard  2333:   for (*iter=1;;++(*iter)) { 
1.187     brouard  2334:     fp=(*fret); /* From former iteration or initial value */
1.126     brouard  2335:     ibig=0; 
                   2336:     del=0.0; 
1.157     brouard  2337:     rlast_time=rcurr_time;
                   2338:     /* (void) gettimeofday(&curr_time,&tzp); */
                   2339:     rcurr_time = time(NULL);  
                   2340:     curr_time = *localtime(&rcurr_time);
                   2341:     printf("\nPowell iter=%d -2*LL=%.12f %ld sec. %ld sec.",*iter,*fret, rcurr_time-rlast_time, rcurr_time-rstart_time);fflush(stdout);
                   2342:     fprintf(ficlog,"\nPowell iter=%d -2*LL=%.12f %ld sec. %ld sec.",*iter,*fret,rcurr_time-rlast_time, rcurr_time-rstart_time); fflush(ficlog);
                   2343: /*     fprintf(ficrespow,"%d %.12f %ld",*iter,*fret,curr_time.tm_sec-start_time.tm_sec); */
1.192     brouard  2344:     for (i=1;i<=n;i++) {
1.126     brouard  2345:       fprintf(ficrespow," %.12lf", p[i]);
                   2346:     }
1.239     brouard  2347:     fprintf(ficrespow,"\n");fflush(ficrespow);
                   2348:     printf("\n#model=  1      +     age ");
                   2349:     fprintf(ficlog,"\n#model=  1      +     age ");
                   2350:     if(nagesqr==1){
1.241     brouard  2351:        printf("  + age*age  ");
                   2352:        fprintf(ficlog,"  + age*age  ");
1.239     brouard  2353:     }
                   2354:     for(j=1;j <=ncovmodel-2;j++){
                   2355:       if(Typevar[j]==0) {
                   2356:        printf("  +      V%d  ",Tvar[j]);
                   2357:        fprintf(ficlog,"  +      V%d  ",Tvar[j]);
                   2358:       }else if(Typevar[j]==1) {
                   2359:        printf("  +    V%d*age ",Tvar[j]);
                   2360:        fprintf(ficlog,"  +    V%d*age ",Tvar[j]);
                   2361:       }else if(Typevar[j]==2) {
                   2362:        printf("  +    V%d*V%d ",Tvard[Tposprod[j]][1],Tvard[Tposprod[j]][2]);
                   2363:        fprintf(ficlog,"  +    V%d*V%d ",Tvard[Tposprod[j]][1],Tvard[Tposprod[j]][2]);
                   2364:       }
                   2365:     }
1.126     brouard  2366:     printf("\n");
1.239     brouard  2367: /*     printf("12   47.0114589    0.0154322   33.2424412    0.3279905    2.3731903  */
                   2368: /* 13  -21.5392400    0.1118147    1.2680506    1.2973408   -1.0663662  */
1.126     brouard  2369:     fprintf(ficlog,"\n");
1.239     brouard  2370:     for(i=1,jk=1; i <=nlstate; i++){
                   2371:       for(k=1; k <=(nlstate+ndeath); k++){
                   2372:        if (k != i) {
                   2373:          printf("%d%d ",i,k);
                   2374:          fprintf(ficlog,"%d%d ",i,k);
                   2375:          for(j=1; j <=ncovmodel; j++){
                   2376:            printf("%12.7f ",p[jk]);
                   2377:            fprintf(ficlog,"%12.7f ",p[jk]);
                   2378:            jk++; 
                   2379:          }
                   2380:          printf("\n");
                   2381:          fprintf(ficlog,"\n");
                   2382:        }
                   2383:       }
                   2384:     }
1.241     brouard  2385:     if(*iter <=3 && *iter >1){
1.157     brouard  2386:       tml = *localtime(&rcurr_time);
                   2387:       strcpy(strcurr,asctime(&tml));
                   2388:       rforecast_time=rcurr_time; 
1.126     brouard  2389:       itmp = strlen(strcurr);
                   2390:       if(strcurr[itmp-1]=='\n')  /* Windows outputs with a new line */
1.241     brouard  2391:        strcurr[itmp-1]='\0';
1.162     brouard  2392:       printf("\nConsidering the time needed for the last iteration #%d: %ld seconds,\n",*iter,rcurr_time-rlast_time);
1.157     brouard  2393:       fprintf(ficlog,"\nConsidering the time needed for this last iteration #%d: %ld seconds,\n",*iter,rcurr_time-rlast_time);
1.126     brouard  2394:       for(niterf=10;niterf<=30;niterf+=10){
1.241     brouard  2395:        rforecast_time=rcurr_time+(niterf-*iter)*(rcurr_time-rlast_time);
                   2396:        forecast_time = *localtime(&rforecast_time);
                   2397:        strcpy(strfor,asctime(&forecast_time));
                   2398:        itmp = strlen(strfor);
                   2399:        if(strfor[itmp-1]=='\n')
                   2400:          strfor[itmp-1]='\0';
                   2401:        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);
                   2402:        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  2403:       }
                   2404:     }
1.187     brouard  2405:     for (i=1;i<=n;i++) { /* For each direction i */
                   2406:       for (j=1;j<=n;j++) xit[j]=xi[j][i]; /* Directions stored from previous iteration with previous scales */
1.126     brouard  2407:       fptt=(*fret); 
                   2408: #ifdef DEBUG
1.203     brouard  2409:       printf("fret=%lf, %lf, %lf \n", *fret, *fret, *fret);
                   2410:       fprintf(ficlog, "fret=%lf, %lf, %lf \n", *fret, *fret, *fret);
1.126     brouard  2411: #endif
1.203     brouard  2412:       printf("%d",i);fflush(stdout); /* print direction (parameter) i */
1.126     brouard  2413:       fprintf(ficlog,"%d",i);fflush(ficlog);
1.224     brouard  2414: #ifdef LINMINORIGINAL
1.188     brouard  2415:       linmin(p,xit,n,fret,func); /* Point p[n]. xit[n] has been loaded for direction i as input.*/
1.224     brouard  2416: #else
                   2417:       linmin(p,xit,n,fret,func,&flat); /* Point p[n]. xit[n] has been loaded for direction i as input.*/
                   2418:                        flatdir[i]=flat; /* Function is vanishing in that direction i */
                   2419: #endif
                   2420:                        /* Outputs are fret(new point p) p is updated and xit rescaled */
1.188     brouard  2421:       if (fabs(fptt-(*fret)) > del) { /* We are keeping the max gain on each of the n directions */
1.224     brouard  2422:                                /* because that direction will be replaced unless the gain del is small */
                   2423:                                /* in comparison with the 'probable' gain, mu^2, with the last average direction. */
                   2424:                                /* Unless the n directions are conjugate some gain in the determinant may be obtained */
                   2425:                                /* with the new direction. */
                   2426:                                del=fabs(fptt-(*fret)); 
                   2427:                                ibig=i; 
1.126     brouard  2428:       } 
                   2429: #ifdef DEBUG
                   2430:       printf("%d %.12e",i,(*fret));
                   2431:       fprintf(ficlog,"%d %.12e",i,(*fret));
                   2432:       for (j=1;j<=n;j++) {
1.224     brouard  2433:                                xits[j]=FMAX(fabs(p[j]-pt[j]),1.e-5);
                   2434:                                printf(" x(%d)=%.12e",j,xit[j]);
                   2435:                                fprintf(ficlog," x(%d)=%.12e",j,xit[j]);
1.126     brouard  2436:       }
                   2437:       for(j=1;j<=n;j++) {
1.225     brouard  2438:                                printf(" p(%d)=%.12e",j,p[j]);
                   2439:                                fprintf(ficlog," p(%d)=%.12e",j,p[j]);
1.126     brouard  2440:       }
                   2441:       printf("\n");
                   2442:       fprintf(ficlog,"\n");
                   2443: #endif
1.187     brouard  2444:     } /* end loop on each direction i */
                   2445:     /* Convergence test will use last linmin estimation (fret) and compare former iteration (fp) */ 
1.188     brouard  2446:     /* But p and xit have been updated at the end of linmin, *fret corresponds to new p, xit  */
1.187     brouard  2447:     /* New value of last point Pn is not computed, P(n-1) */
1.224     brouard  2448:       for(j=1;j<=n;j++) {
1.302     brouard  2449:        if(flatdir[j] >0){
                   2450:          printf(" p(%d)=%lf flat=%d ",j,p[j],flatdir[j]);
                   2451:          fprintf(ficlog," p(%d)=%lf flat=%d ",j,p[j],flatdir[j]);
                   2452:        }
                   2453:        /* printf("\n"); */
                   2454:        /* fprintf(ficlog,"\n"); */
                   2455:       }
1.243     brouard  2456:     /* if (2.0*fabs(fp-(*fret)) <= ftol*(fabs(fp)+fabs(*fret))) { /\* Did we reach enough precision? *\/ */
                   2457:     if (2.0*fabs(fp-(*fret)) <= ftol) { /* Did we reach enough precision? */
1.188     brouard  2458:       /* We could compare with a chi^2. chisquare(0.95,ddl=1)=3.84 */
                   2459:       /* By adding age*age in a model, the new -2LL should be lower and the difference follows a */
                   2460:       /* a chisquare statistics with 1 degree. To be significant at the 95% level, it should have */
                   2461:       /* decreased of more than 3.84  */
                   2462:       /* By adding age*age and V1*age the gain (-2LL) should be more than 5.99 (ddl=2) */
                   2463:       /* By using V1+V2+V3, the gain should be  7.82, compared with basic 1+age. */
                   2464:       /* By adding 10 parameters more the gain should be 18.31 */
1.224     brouard  2465:                        
1.188     brouard  2466:       /* Starting the program with initial values given by a former maximization will simply change */
                   2467:       /* the scales of the directions and the directions, because the are reset to canonical directions */
                   2468:       /* Thus the first calls to linmin will give new points and better maximizations until fp-(*fret) is */
                   2469:       /* under the tolerance value. If the tolerance is very small 1.e-9, it could last long.  */
1.126     brouard  2470: #ifdef DEBUG
                   2471:       int k[2],l;
                   2472:       k[0]=1;
                   2473:       k[1]=-1;
                   2474:       printf("Max: %.12e",(*func)(p));
                   2475:       fprintf(ficlog,"Max: %.12e",(*func)(p));
                   2476:       for (j=1;j<=n;j++) {
                   2477:        printf(" %.12e",p[j]);
                   2478:        fprintf(ficlog," %.12e",p[j]);
                   2479:       }
                   2480:       printf("\n");
                   2481:       fprintf(ficlog,"\n");
                   2482:       for(l=0;l<=1;l++) {
                   2483:        for (j=1;j<=n;j++) {
                   2484:          ptt[j]=p[j]+(p[j]-pt[j])*k[l];
                   2485:          printf("l=%d j=%d ptt=%.12e, xits=%.12e, p=%.12e, xit=%.12e", l,j,ptt[j],xits[j],p[j],xit[j]);
                   2486:          fprintf(ficlog,"l=%d j=%d ptt=%.12e, xits=%.12e, p=%.12e, xit=%.12e", l,j,ptt[j],xits[j],p[j],xit[j]);
                   2487:        }
                   2488:        printf("func(ptt)=%.12e, deriv=%.12e\n",(*func)(ptt),(ptt[j]-p[j])/((*func)(ptt)-(*func)(p)));
                   2489:        fprintf(ficlog,"func(ptt)=%.12e, deriv=%.12e\n",(*func)(ptt),(ptt[j]-p[j])/((*func)(ptt)-(*func)(p)));
                   2490:       }
                   2491: #endif
                   2492: 
1.224     brouard  2493: #ifdef LINMINORIGINAL
                   2494: #else
                   2495:       free_ivector(flatdir,1,n); 
                   2496: #endif
1.126     brouard  2497:       free_vector(xit,1,n); 
                   2498:       free_vector(xits,1,n); 
                   2499:       free_vector(ptt,1,n); 
                   2500:       free_vector(pt,1,n); 
                   2501:       return; 
1.192     brouard  2502:     } /* enough precision */ 
1.240     brouard  2503:     if (*iter == ITMAX*n) nrerror("powell exceeding maximum iterations."); 
1.181     brouard  2504:     for (j=1;j<=n;j++) { /* Computes the extrapolated point P_0 + 2 (P_n-P_0) */
1.126     brouard  2505:       ptt[j]=2.0*p[j]-pt[j]; 
                   2506:       xit[j]=p[j]-pt[j]; 
                   2507:       pt[j]=p[j]; 
                   2508:     } 
1.181     brouard  2509:     fptt=(*func)(ptt); /* f_3 */
1.224     brouard  2510: #ifdef NODIRECTIONCHANGEDUNTILNITER  /* No change in drections until some iterations are done */
                   2511:                if (*iter <=4) {
1.225     brouard  2512: #else
                   2513: #endif
1.224     brouard  2514: #ifdef POWELLNOF3INFF1TEST    /* skips test F3 <F1 */
1.192     brouard  2515: #else
1.161     brouard  2516:     if (fptt < fp) { /* If extrapolated point is better, decide if we keep that new direction or not */
1.192     brouard  2517: #endif
1.162     brouard  2518:       /* (x1 f1=fp), (x2 f2=*fret), (x3 f3=fptt), (xm fm) */
1.161     brouard  2519:       /* From x1 (P0) distance of x2 is at h and x3 is 2h */
1.162     brouard  2520:       /* Let f"(x2) be the 2nd derivative equal everywhere.  */
                   2521:       /* Then the parabolic through (x1,f1), (x2,f2) and (x3,f3) */
                   2522:       /* will reach at f3 = fm + h^2/2 f"m  ; f" = (f1 -2f2 +f3 ) / h**2 */
1.224     brouard  2523:       /* Conditional for using this new direction is that mu^2 = (f1-2f2+f3)^2 /2 < del or directest <0 */
                   2524:       /* also  lamda^2=(f1-f2)^2/mu² is a parasite solution of powell */
                   2525:       /* For powell, inclusion of this average direction is only if t(del)<0 or del inbetween mu^2 and lambda^2 */
1.161     brouard  2526:       /* t=2.0*(fp-2.0*(*fret)+fptt)*SQR(fp-(*fret)-del)-del*SQR(fp-fptt); */
1.224     brouard  2527:       /*  Even if f3 <f1, directest can be negative and t >0 */
                   2528:       /* mu² and del² are equal when f3=f1 */
                   2529:                        /* f3 < f1 : mu² < del <= lambda^2 both test are equivalent */
                   2530:                        /* f3 < f1 : mu² < lambda^2 < del then directtest is negative and powell t is positive */
                   2531:                        /* f3 > f1 : lambda² < mu^2 < del then t is negative and directest >0  */
                   2532:                        /* f3 > f1 : lambda² < del < mu^2 then t is positive and directest >0  */
1.183     brouard  2533: #ifdef NRCORIGINAL
                   2534:       t=2.0*(fp-2.0*(*fret)+fptt)*SQR(fp-(*fret)-del)- del*SQR(fp-fptt); /* Original Numerical Recipes in C*/
                   2535: #else
                   2536:       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  2537:       t= t- del*SQR(fp-fptt);
1.183     brouard  2538: #endif
1.202     brouard  2539:       directest = fp-2.0*(*fret)+fptt - 2.0 * del; /* If delta was big enough we change it for a new direction */
1.161     brouard  2540: #ifdef DEBUG
1.181     brouard  2541:       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);
                   2542:       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  2543:       printf("t3= %.12lf, t4= %.12lf, t3*= %.12lf, t4*= %.12lf\n",SQR(fp-(*fret)-del),SQR(fp-fptt),
                   2544:             (fp-(*fret)-del)*(fp-(*fret)-del),(fp-fptt)*(fp-fptt));
                   2545:       fprintf(ficlog,"t3= %.12lf, t4= %.12lf, t3*= %.12lf, t4*= %.12lf\n",SQR(fp-(*fret)-del),SQR(fp-fptt),
                   2546:             (fp-(*fret)-del)*(fp-(*fret)-del),(fp-fptt)*(fp-fptt));
                   2547:       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);
                   2548:       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);
                   2549: #endif
1.183     brouard  2550: #ifdef POWELLORIGINAL
                   2551:       if (t < 0.0) { /* Then we use it for new direction */
                   2552: #else
1.182     brouard  2553:       if (directest*t < 0.0) { /* Contradiction between both tests */
1.224     brouard  2554:                                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  2555:         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  2556:         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  2557:         fprintf(ficlog,"f1-2f2+f3= %.12lf, f1-f2-del= %.12lf, f1-f3= %.12lf\n",fp-2.0*(*fret)+fptt, fp -(*fret) -del, fp-fptt);
                   2558:       } 
1.181     brouard  2559:       if (directest < 0.0) { /* Then we use it for new direction */
                   2560: #endif
1.191     brouard  2561: #ifdef DEBUGLINMIN
1.234     brouard  2562:        printf("Before linmin in direction P%d-P0\n",n);
                   2563:        for (j=1;j<=n;j++) {
                   2564:          printf(" Before xit[%d]= %12.7f p[%d]= %12.7f",j,xit[j],j,p[j]);
                   2565:          fprintf(ficlog," Before xit[%d]= %12.7f p[%d]= %12.7f",j,xit[j],j,p[j]);
                   2566:          if(j % ncovmodel == 0){
                   2567:            printf("\n");
                   2568:            fprintf(ficlog,"\n");
                   2569:          }
                   2570:        }
1.224     brouard  2571: #endif
                   2572: #ifdef LINMINORIGINAL
1.234     brouard  2573:        linmin(p,xit,n,fret,func); /* computes minimum on the extrapolated direction: changes p and rescales xit.*/
1.224     brouard  2574: #else
1.234     brouard  2575:        linmin(p,xit,n,fret,func,&flat); /* computes minimum on the extrapolated direction: changes p and rescales xit.*/
                   2576:        flatdir[i]=flat; /* Function is vanishing in that direction i */
1.191     brouard  2577: #endif
1.234     brouard  2578:        
1.191     brouard  2579: #ifdef DEBUGLINMIN
1.234     brouard  2580:        for (j=1;j<=n;j++) { 
                   2581:          printf("After xit[%d]= %12.7f p[%d]= %12.7f",j,xit[j],j,p[j]);
                   2582:          fprintf(ficlog,"After xit[%d]= %12.7f p[%d]= %12.7f",j,xit[j],j,p[j]);
                   2583:          if(j % ncovmodel == 0){
                   2584:            printf("\n");
                   2585:            fprintf(ficlog,"\n");
                   2586:          }
                   2587:        }
1.224     brouard  2588: #endif
1.234     brouard  2589:        for (j=1;j<=n;j++) { 
                   2590:          xi[j][ibig]=xi[j][n]; /* Replace direction with biggest decrease by last direction n */
                   2591:          xi[j][n]=xit[j];      /* and this nth direction by the by the average p_0 p_n */
                   2592:        }
1.224     brouard  2593: #ifdef LINMINORIGINAL
                   2594: #else
1.234     brouard  2595:        for (j=1, flatd=0;j<=n;j++) {
                   2596:          if(flatdir[j]>0)
                   2597:            flatd++;
                   2598:        }
                   2599:        if(flatd >0){
1.255     brouard  2600:          printf("%d flat directions: ",flatd);
                   2601:          fprintf(ficlog,"%d flat directions :",flatd);
1.234     brouard  2602:          for (j=1;j<=n;j++) { 
                   2603:            if(flatdir[j]>0){
                   2604:              printf("%d ",j);
                   2605:              fprintf(ficlog,"%d ",j);
                   2606:            }
                   2607:          }
                   2608:          printf("\n");
                   2609:          fprintf(ficlog,"\n");
                   2610:        }
1.191     brouard  2611: #endif
1.234     brouard  2612:        printf("Gaining to use new average direction of P0 P%d instead of biggest increase direction %d :\n",n,ibig);
                   2613:        fprintf(ficlog,"Gaining to use new average direction of P0 P%d instead of biggest increase direction %d :\n",n,ibig);
                   2614:        
1.126     brouard  2615: #ifdef DEBUG
1.234     brouard  2616:        printf("Direction changed  last moved %d in place of ibig=%d, new last is the average:\n",n,ibig);
                   2617:        fprintf(ficlog,"Direction changed  last moved %d in place of ibig=%d, new last is the average:\n",n,ibig);
                   2618:        for(j=1;j<=n;j++){
                   2619:          printf(" %lf",xit[j]);
                   2620:          fprintf(ficlog," %lf",xit[j]);
                   2621:        }
                   2622:        printf("\n");
                   2623:        fprintf(ficlog,"\n");
1.126     brouard  2624: #endif
1.192     brouard  2625:       } /* end of t or directest negative */
1.224     brouard  2626: #ifdef POWELLNOF3INFF1TEST
1.192     brouard  2627: #else
1.234     brouard  2628:       } /* end if (fptt < fp)  */
1.192     brouard  2629: #endif
1.225     brouard  2630: #ifdef NODIRECTIONCHANGEDUNTILNITER  /* No change in drections until some iterations are done */
1.234     brouard  2631:     } /*NODIRECTIONCHANGEDUNTILNITER  No change in drections until some iterations are done */
1.225     brouard  2632: #else
1.224     brouard  2633: #endif
1.234     brouard  2634:                } /* loop iteration */ 
1.126     brouard  2635: } 
1.234     brouard  2636:   
1.126     brouard  2637: /**** Prevalence limit (stable or period prevalence)  ****************/
1.234     brouard  2638:   
1.235     brouard  2639:   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  2640:   {
1.279     brouard  2641:     /**< Computes the prevalence limit in each live state at age x and for covariate combination ij 
                   2642:      *   (and selected quantitative values in nres)
                   2643:      *  by left multiplying the unit
                   2644:      *  matrix by transitions matrix until convergence is reached with precision ftolpl 
                   2645:      * Wx= Wx-1 Px-1= Wx-2 Px-2 Px-1  = Wx-n Px-n ... Px-2 Px-1 I
                   2646:      * Wx is row vector: population in state 1, population in state 2, population dead
                   2647:      * or prevalence in state 1, prevalence in state 2, 0
                   2648:      * newm is the matrix after multiplications, its rows are identical at a factor.
                   2649:      * Inputs are the parameter, age, a tolerance for the prevalence limit ftolpl.
                   2650:      * Output is prlim.
                   2651:      * Initial matrix pimij 
                   2652:      */
1.206     brouard  2653:   /* {0.85204250825084937, 0.13044499163996345, 0.017512500109187184, */
                   2654:   /* 0.090851990222114765, 0.88271245433047185, 0.026435555447413338, */
                   2655:   /*  0,                   0                  , 1} */
                   2656:   /*
                   2657:    * and after some iteration: */
                   2658:   /* {0.45504275246439968, 0.42731458730878791, 0.11764266022681241, */
                   2659:   /*  0.45201005341706885, 0.42865420071559901, 0.11933574586733192, */
                   2660:   /*  0,                   0                  , 1} */
                   2661:   /* And prevalence by suppressing the deaths are close to identical rows in prlim: */
                   2662:   /* {0.51571254859325999, 0.4842874514067399, */
                   2663:   /*  0.51326036147820708, 0.48673963852179264} */
                   2664:   /* If we start from prlim again, prlim tends to a constant matrix */
1.234     brouard  2665:     
1.126     brouard  2666:   int i, ii,j,k;
1.209     brouard  2667:   double *min, *max, *meandiff, maxmax,sumnew=0.;
1.145     brouard  2668:   /* double **matprod2(); */ /* test */
1.218     brouard  2669:   double **out, cov[NCOVMAX+1], **pmij(); /* **pmmij is a global variable feeded with oldms etc */
1.126     brouard  2670:   double **newm;
1.209     brouard  2671:   double agefin, delaymax=200. ; /* 100 Max number of years to converge */
1.203     brouard  2672:   int ncvloop=0;
1.288     brouard  2673:   int first=0;
1.169     brouard  2674:   
1.209     brouard  2675:   min=vector(1,nlstate);
                   2676:   max=vector(1,nlstate);
                   2677:   meandiff=vector(1,nlstate);
                   2678: 
1.218     brouard  2679:        /* Starting with matrix unity */
1.126     brouard  2680:   for (ii=1;ii<=nlstate+ndeath;ii++)
                   2681:     for (j=1;j<=nlstate+ndeath;j++){
                   2682:       oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   2683:     }
1.169     brouard  2684:   
                   2685:   cov[1]=1.;
                   2686:   
                   2687:   /* Even if hstepm = 1, at least one multiplication by the unit matrix */
1.202     brouard  2688:   /* Start at agefin= age, computes the matrix of passage and loops decreasing agefin until convergence is reached */
1.126     brouard  2689:   for(agefin=age-stepm/YEARM; agefin>=age-delaymax; agefin=agefin-stepm/YEARM){
1.202     brouard  2690:     ncvloop++;
1.126     brouard  2691:     newm=savm;
                   2692:     /* Covariates have to be included here again */
1.138     brouard  2693:     cov[2]=agefin;
1.187     brouard  2694:     if(nagesqr==1)
                   2695:       cov[3]= agefin*agefin;;
1.234     brouard  2696:     for (k=1; k<=nsd;k++) { /* For single dummy covariates only */
                   2697:                        /* Here comes the value of the covariate 'ij' after renumbering k with single dummy covariates */
                   2698:       cov[2+nagesqr+TvarsDind[k]]=nbcode[TvarsD[k]][codtabm(ij,k)];
1.235     brouard  2699:       /* 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  2700:     }
                   2701:     for (k=1; k<=nsq;k++) { /* For single varying covariates only */
                   2702:                        /* Here comes the value of quantitative after renumbering k with single quantitative covariates */
1.235     brouard  2703:       cov[2+nagesqr+TvarsQind[k]]=Tqresult[nres][k]; 
                   2704:       /* 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  2705:     }
1.237     brouard  2706:     for (k=1; k<=cptcovage;k++){  /* For product with age */
1.234     brouard  2707:       if(Dummy[Tvar[Tage[k]]]){
                   2708:        cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,k)]*cov[2];
                   2709:       } else{
1.235     brouard  2710:        cov[2+nagesqr+Tage[k]]=Tqresult[nres][k]; 
1.234     brouard  2711:       }
1.235     brouard  2712:       /* 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  2713:     }
1.237     brouard  2714:     for (k=1; k<=cptcovprod;k++){ /* For product without age */
1.235     brouard  2715:       /* 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  2716:       if(Dummy[Tvard[k][1]==0]){
                   2717:        if(Dummy[Tvard[k][2]==0]){
                   2718:          cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)] * nbcode[Tvard[k][2]][codtabm(ij,k)];
                   2719:        }else{
                   2720:          cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)] * Tqresult[nres][k];
                   2721:        }
                   2722:       }else{
                   2723:        if(Dummy[Tvard[k][2]==0]){
                   2724:          cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][2]][codtabm(ij,k)] * Tqinvresult[nres][Tvard[k][1]];
                   2725:        }else{
                   2726:          cov[2+nagesqr+Tprod[k]]=Tqinvresult[nres][Tvard[k][1]]*  Tqinvresult[nres][Tvard[k][2]];
                   2727:        }
                   2728:       }
1.234     brouard  2729:     }
1.138     brouard  2730:     /*printf("ij=%d cptcovprod=%d tvar=%d ", ij, cptcovprod, Tvar[1]);*/
                   2731:     /*printf("ij=%d cov[3]=%lf cov[4]=%lf \n",ij, cov[3],cov[4]);*/
                   2732:     /*printf("ij=%d cov[3]=%lf \n",ij, cov[3]);*/
1.145     brouard  2733:     /* savm=pmij(pmmij,cov,ncovmodel,x,nlstate); */
                   2734:     /* out=matprod2(newm, pmij(pmmij,cov,ncovmodel,x,nlstate),1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm); /\* Bug Valgrind *\/ */
1.218     brouard  2735:                /* age and covariate values of ij are in 'cov' */
1.142     brouard  2736:     out=matprod2(newm, pmij(pmmij,cov,ncovmodel,x,nlstate),1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm); /* Bug Valgrind */
1.138     brouard  2737:     
1.126     brouard  2738:     savm=oldm;
                   2739:     oldm=newm;
1.209     brouard  2740: 
                   2741:     for(j=1; j<=nlstate; j++){
                   2742:       max[j]=0.;
                   2743:       min[j]=1.;
                   2744:     }
                   2745:     for(i=1;i<=nlstate;i++){
                   2746:       sumnew=0;
                   2747:       for(k=1; k<=ndeath; k++) sumnew+=newm[i][nlstate+k];
                   2748:       for(j=1; j<=nlstate; j++){ 
                   2749:        prlim[i][j]= newm[i][j]/(1-sumnew);
                   2750:        max[j]=FMAX(max[j],prlim[i][j]);
                   2751:        min[j]=FMIN(min[j],prlim[i][j]);
                   2752:       }
                   2753:     }
                   2754: 
1.126     brouard  2755:     maxmax=0.;
1.209     brouard  2756:     for(j=1; j<=nlstate; j++){
                   2757:       meandiff[j]=(max[j]-min[j])/(max[j]+min[j])*2.; /* mean difference for each column */
                   2758:       maxmax=FMAX(maxmax,meandiff[j]);
                   2759:       /* 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  2760:     } /* j loop */
1.203     brouard  2761:     *ncvyear= (int)age- (int)agefin;
1.208     brouard  2762:     /* 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  2763:     if(maxmax < ftolpl){
1.209     brouard  2764:       /* printf("maxmax=%lf ncvloop=%ld, age=%d, agefin=%d ncvyear=%d \n", maxmax, ncvloop, (int)age, (int)agefin, *ncvyear); */
                   2765:       free_vector(min,1,nlstate);
                   2766:       free_vector(max,1,nlstate);
                   2767:       free_vector(meandiff,1,nlstate);
1.126     brouard  2768:       return prlim;
                   2769:     }
1.288     brouard  2770:   } /* agefin loop */
1.208     brouard  2771:     /* After some age loop it doesn't converge */
1.288     brouard  2772:   if(!first){
                   2773:     first=1;
                   2774:     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);
                   2775:   }
                   2776:   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);
                   2777: 
1.209     brouard  2778:   /* 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); */
                   2779:   free_vector(min,1,nlstate);
                   2780:   free_vector(max,1,nlstate);
                   2781:   free_vector(meandiff,1,nlstate);
1.208     brouard  2782:   
1.169     brouard  2783:   return prlim; /* should not reach here */
1.126     brouard  2784: }
                   2785: 
1.217     brouard  2786: 
                   2787:  /**** Back Prevalence limit (stable or period prevalence)  ****************/
                   2788: 
1.218     brouard  2789:  /* 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) */
                   2790:  /* 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  2791:   double **bprevalim(double **bprlim, double ***prevacurrent, int nlstate, double x[], double age, double ftolpl, int *ncvyear, int ij, int nres)
1.217     brouard  2792: {
1.264     brouard  2793:   /* 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  2794:      matrix by transitions matrix until convergence is reached with precision ftolpl */
                   2795:   /* Wx= Wx-1 Px-1= Wx-2 Px-2 Px-1  = Wx-n Px-n ... Px-2 Px-1 I */
                   2796:   /* Wx is row vector: population in state 1, population in state 2, population dead */
                   2797:   /* or prevalence in state 1, prevalence in state 2, 0 */
                   2798:   /* newm is the matrix after multiplications, its rows are identical at a factor */
                   2799:   /* Initial matrix pimij */
                   2800:   /* {0.85204250825084937, 0.13044499163996345, 0.017512500109187184, */
                   2801:   /* 0.090851990222114765, 0.88271245433047185, 0.026435555447413338, */
                   2802:   /*  0,                   0                  , 1} */
                   2803:   /*
                   2804:    * and after some iteration: */
                   2805:   /* {0.45504275246439968, 0.42731458730878791, 0.11764266022681241, */
                   2806:   /*  0.45201005341706885, 0.42865420071559901, 0.11933574586733192, */
                   2807:   /*  0,                   0                  , 1} */
                   2808:   /* And prevalence by suppressing the deaths are close to identical rows in prlim: */
                   2809:   /* {0.51571254859325999, 0.4842874514067399, */
                   2810:   /*  0.51326036147820708, 0.48673963852179264} */
                   2811:   /* If we start from prlim again, prlim tends to a constant matrix */
                   2812: 
                   2813:   int i, ii,j,k;
1.247     brouard  2814:   int first=0;
1.217     brouard  2815:   double *min, *max, *meandiff, maxmax,sumnew=0.;
                   2816:   /* double **matprod2(); */ /* test */
                   2817:   double **out, cov[NCOVMAX+1], **bmij();
                   2818:   double **newm;
1.218     brouard  2819:   double        **dnewm, **doldm, **dsavm;  /* for use */
                   2820:   double        **oldm, **savm;  /* for use */
                   2821: 
1.217     brouard  2822:   double agefin, delaymax=200. ; /* 100 Max number of years to converge */
                   2823:   int ncvloop=0;
                   2824:   
                   2825:   min=vector(1,nlstate);
                   2826:   max=vector(1,nlstate);
                   2827:   meandiff=vector(1,nlstate);
                   2828: 
1.266     brouard  2829:   dnewm=ddnewms; doldm=ddoldms; dsavm=ddsavms;
                   2830:   oldm=oldms; savm=savms;
                   2831:   
                   2832:   /* Starting with matrix unity */
                   2833:   for (ii=1;ii<=nlstate+ndeath;ii++)
                   2834:     for (j=1;j<=nlstate+ndeath;j++){
1.217     brouard  2835:       oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   2836:     }
                   2837:   
                   2838:   cov[1]=1.;
                   2839:   
                   2840:   /* Even if hstepm = 1, at least one multiplication by the unit matrix */
                   2841:   /* Start at agefin= age, computes the matrix of passage and loops decreasing agefin until convergence is reached */
1.218     brouard  2842:   /* for(agefin=age+stepm/YEARM; agefin<=age+delaymax; agefin=agefin+stepm/YEARM){ /\* A changer en age *\/ */
1.288     brouard  2843:   /* for(agefin=age; agefin<AGESUP; agefin=agefin+stepm/YEARM){ /\* A changer en age *\/ */
                   2844:   for(agefin=age; agefin<FMIN(AGESUP,age+delaymax); agefin=agefin+stepm/YEARM){ /* A changer en age */
1.217     brouard  2845:     ncvloop++;
1.218     brouard  2846:     newm=savm; /* oldm should be kept from previous iteration or unity at start */
                   2847:                /* newm points to the allocated table savm passed by the function it can be written, savm could be reallocated */
1.217     brouard  2848:     /* Covariates have to be included here again */
                   2849:     cov[2]=agefin;
                   2850:     if(nagesqr==1)
                   2851:       cov[3]= agefin*agefin;;
1.242     brouard  2852:     for (k=1; k<=nsd;k++) { /* For single dummy covariates only */
                   2853:                        /* Here comes the value of the covariate 'ij' after renumbering k with single dummy covariates */
                   2854:       cov[2+nagesqr+TvarsDind[k]]=nbcode[TvarsD[k]][codtabm(ij,k)];
1.264     brouard  2855:       /* 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  2856:     }
                   2857:     /* for (k=1; k<=cptcovn;k++) { */
                   2858:     /*   /\* cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,Tvar[k])]; *\/ */
                   2859:     /*   cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,k)]; */
                   2860:     /*   /\* 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])]); *\/ */
                   2861:     /* } */
                   2862:     for (k=1; k<=nsq;k++) { /* For single varying covariates only */
                   2863:                        /* Here comes the value of quantitative after renumbering k with single quantitative covariates */
                   2864:       cov[2+nagesqr+TvarsQind[k]]=Tqresult[nres][k]; 
                   2865:       /* 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]); */
                   2866:     }
                   2867:     /* for (k=1; k<=cptcovage;k++) cov[2+nagesqr+Tage[k]]=nbcode[Tvar[k]][codtabm(ij,k)]*cov[2]; */
                   2868:     /* for (k=1; k<=cptcovprod;k++) /\* Useless *\/ */
                   2869:     /*   /\* cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,Tvard[k][1])] * nbcode[Tvard[k][2]][codtabm(ij,Tvard[k][2])]; *\/ */
                   2870:     /*   cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)] * nbcode[Tvard[k][2]][codtabm(ij,k)]; */
                   2871:     for (k=1; k<=cptcovage;k++){  /* For product with age */
                   2872:       if(Dummy[Tvar[Tage[k]]]){
                   2873:        cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,k)]*cov[2];
                   2874:       } else{
                   2875:        cov[2+nagesqr+Tage[k]]=Tqresult[nres][k]; 
                   2876:       }
                   2877:       /* 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]); */
                   2878:     }
                   2879:     for (k=1; k<=cptcovprod;k++){ /* For product without age */
                   2880:       /* 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]); */
                   2881:       if(Dummy[Tvard[k][1]==0]){
                   2882:        if(Dummy[Tvard[k][2]==0]){
                   2883:          cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)] * nbcode[Tvard[k][2]][codtabm(ij,k)];
                   2884:        }else{
                   2885:          cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)] * Tqresult[nres][k];
                   2886:        }
                   2887:       }else{
                   2888:        if(Dummy[Tvard[k][2]==0]){
                   2889:          cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][2]][codtabm(ij,k)] * Tqinvresult[nres][Tvard[k][1]];
                   2890:        }else{
                   2891:          cov[2+nagesqr+Tprod[k]]=Tqinvresult[nres][Tvard[k][1]]*  Tqinvresult[nres][Tvard[k][2]];
                   2892:        }
                   2893:       }
1.217     brouard  2894:     }
                   2895:     
                   2896:     /*printf("ij=%d cptcovprod=%d tvar=%d ", ij, cptcovprod, Tvar[1]);*/
                   2897:     /*printf("ij=%d cov[3]=%lf cov[4]=%lf \n",ij, cov[3],cov[4]);*/
                   2898:     /*printf("ij=%d cov[3]=%lf \n",ij, cov[3]);*/
                   2899:     /* savm=pmij(pmmij,cov,ncovmodel,x,nlstate); */
                   2900:     /* out=matprod2(newm, pmij(pmmij,cov,ncovmodel,x,nlstate),1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm); /\* Bug Valgrind *\/ */
1.218     brouard  2901:                /* ij should be linked to the correct index of cov */
                   2902:                /* age and covariate values ij are in 'cov', but we need to pass
                   2903:                 * ij for the observed prevalence at age and status and covariate
                   2904:                 * number:  prevacurrent[(int)agefin][ii][ij]
                   2905:                 */
                   2906:     /* 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 *\/ */
                   2907:     /* 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 *\/ */
                   2908:     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  2909:     /* if((int)age == 86 || (int)age == 87){ */
1.266     brouard  2910:     /*   printf(" Backward prevalim age=%d agefin=%d \n", (int) age, (int) agefin); */
                   2911:     /*   for(i=1; i<=nlstate+ndeath; i++) { */
                   2912:     /*         printf("%d newm= ",i); */
                   2913:     /*         for(j=1;j<=nlstate+ndeath;j++) { */
                   2914:     /*           printf("%f ",newm[i][j]); */
                   2915:     /*         } */
                   2916:     /*         printf("oldm * "); */
                   2917:     /*         for(j=1;j<=nlstate+ndeath;j++) { */
                   2918:     /*           printf("%f ",oldm[i][j]); */
                   2919:     /*         } */
1.268     brouard  2920:     /*         printf(" bmmij "); */
1.266     brouard  2921:     /*         for(j=1;j<=nlstate+ndeath;j++) { */
                   2922:     /*           printf("%f ",pmmij[i][j]); */
                   2923:     /*         } */
                   2924:     /*         printf("\n"); */
                   2925:     /*   } */
                   2926:     /* } */
1.217     brouard  2927:     savm=oldm;
                   2928:     oldm=newm;
1.266     brouard  2929: 
1.217     brouard  2930:     for(j=1; j<=nlstate; j++){
                   2931:       max[j]=0.;
                   2932:       min[j]=1.;
                   2933:     }
                   2934:     for(j=1; j<=nlstate; j++){ 
                   2935:       for(i=1;i<=nlstate;i++){
1.234     brouard  2936:        /* bprlim[i][j]= newm[i][j]/(1-sumnew); */
                   2937:        bprlim[i][j]= newm[i][j];
                   2938:        max[i]=FMAX(max[i],bprlim[i][j]); /* Max in line */
                   2939:        min[i]=FMIN(min[i],bprlim[i][j]);
1.217     brouard  2940:       }
                   2941:     }
1.218     brouard  2942:                
1.217     brouard  2943:     maxmax=0.;
                   2944:     for(i=1; i<=nlstate; i++){
                   2945:       meandiff[i]=(max[i]-min[i])/(max[i]+min[i])*2.; /* mean difference for each column */
                   2946:       maxmax=FMAX(maxmax,meandiff[i]);
                   2947:       /* 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  2948:     } /* i loop */
1.217     brouard  2949:     *ncvyear= -( (int)age- (int)agefin);
1.268     brouard  2950:     /* printf("Back maxmax=%lf ncvloop=%d, age=%d, agefin=%d ncvyear=%d \n", maxmax, ncvloop, (int)age, (int)agefin, *ncvyear); */
1.217     brouard  2951:     if(maxmax < ftolpl){
1.220     brouard  2952:       /* printf("OK Back maxmax=%lf ncvloop=%d, age=%d, agefin=%d ncvyear=%d \n", maxmax, ncvloop, (int)age, (int)agefin, *ncvyear); */
1.217     brouard  2953:       free_vector(min,1,nlstate);
                   2954:       free_vector(max,1,nlstate);
                   2955:       free_vector(meandiff,1,nlstate);
                   2956:       return bprlim;
                   2957:     }
1.288     brouard  2958:   } /* agefin loop */
1.217     brouard  2959:     /* After some age loop it doesn't converge */
1.288     brouard  2960:   if(!first){
1.247     brouard  2961:     first=1;
                   2962:     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\
                   2963: 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);
                   2964:   }
                   2965:   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  2966: 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);
                   2967:   /* 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); */
                   2968:   free_vector(min,1,nlstate);
                   2969:   free_vector(max,1,nlstate);
                   2970:   free_vector(meandiff,1,nlstate);
                   2971:   
                   2972:   return bprlim; /* should not reach here */
                   2973: }
                   2974: 
1.126     brouard  2975: /*************** transition probabilities ***************/ 
                   2976: 
                   2977: double **pmij(double **ps, double *cov, int ncovmodel, double *x, int nlstate )
                   2978: {
1.138     brouard  2979:   /* According to parameters values stored in x and the covariate's values stored in cov,
1.266     brouard  2980:      computes the probability to be observed in state j (after stepm years) being in state i by appying the
1.138     brouard  2981:      model to the ncovmodel covariates (including constant and age).
                   2982:      lnpijopii=ln(pij/pii)= aij+bij*age+cij*v1+dij*v2+... = sum_nc=1^ncovmodel xij(nc)*cov[nc]
                   2983:      and, according on how parameters are entered, the position of the coefficient xij(nc) of the
                   2984:      ncth covariate in the global vector x is given by the formula:
                   2985:      j<i nc+((i-1)*(nlstate+ndeath-1)+j-1)*ncovmodel
                   2986:      j>=i nc + ((i-1)*(nlstate+ndeath-1)+(j-2))*ncovmodel
                   2987:      Computes ln(pij/pii) (lnpijopii), deduces pij/pii by exponentiation,
                   2988:      sums on j different of i to get 1-pii/pii, deduces pii, and then all pij.
1.266     brouard  2989:      Outputs ps[i][j] or probability to be observed in j being in i according to
1.138     brouard  2990:      the values of the covariates cov[nc] and corresponding parameter values x[nc+shiftij]
1.266     brouard  2991:      Sum on j ps[i][j] should equal to 1.
1.138     brouard  2992:   */
                   2993:   double s1, lnpijopii;
1.126     brouard  2994:   /*double t34;*/
1.164     brouard  2995:   int i,j, nc, ii, jj;
1.126     brouard  2996: 
1.223     brouard  2997:   for(i=1; i<= nlstate; i++){
                   2998:     for(j=1; j<i;j++){
                   2999:       for (nc=1, lnpijopii=0.;nc <=ncovmodel; nc++){
                   3000:        /*lnpijopii += param[i][j][nc]*cov[nc];*/
                   3001:        lnpijopii += x[nc+((i-1)*(nlstate+ndeath-1)+j-1)*ncovmodel]*cov[nc];
                   3002:        /*       printf("Int j<i s1=%.17e, lnpijopii=%.17e\n",s1,lnpijopii); */
                   3003:       }
                   3004:       ps[i][j]=lnpijopii; /* In fact ln(pij/pii) */
                   3005:       /*       printf("s1=%.17e, lnpijopii=%.17e\n",s1,lnpijopii); */
                   3006:     }
                   3007:     for(j=i+1; j<=nlstate+ndeath;j++){
                   3008:       for (nc=1, lnpijopii=0.;nc <=ncovmodel; nc++){
                   3009:        /*lnpijopii += x[(i-1)*nlstate*ncovmodel+(j-2)*ncovmodel+nc+(i-1)*(ndeath-1)*ncovmodel]*cov[nc];*/
                   3010:        lnpijopii += x[nc + ((i-1)*(nlstate+ndeath-1)+(j-2))*ncovmodel]*cov[nc];
                   3011:        /*        printf("Int j>i s1=%.17e, lnpijopii=%.17e %lx %lx\n",s1,lnpijopii,s1,lnpijopii); */
                   3012:       }
                   3013:       ps[i][j]=lnpijopii; /* In fact ln(pij/pii) */
                   3014:     }
                   3015:   }
1.218     brouard  3016:   
1.223     brouard  3017:   for(i=1; i<= nlstate; i++){
                   3018:     s1=0;
                   3019:     for(j=1; j<i; j++){
                   3020:       s1+=exp(ps[i][j]); /* In fact sums pij/pii */
                   3021:       /*printf("debug1 %d %d ps=%lf exp(ps)=%lf s1+=%lf\n",i,j,ps[i][j],exp(ps[i][j]),s1); */
                   3022:     }
                   3023:     for(j=i+1; j<=nlstate+ndeath; j++){
                   3024:       s1+=exp(ps[i][j]); /* In fact sums pij/pii */
                   3025:       /*printf("debug2 %d %d ps=%lf exp(ps)=%lf s1+=%lf\n",i,j,ps[i][j],exp(ps[i][j]),s1); */
                   3026:     }
                   3027:     /* s1= sum_{j<>i} pij/pii=(1-pii)/pii and thus pii is known from s1 */
                   3028:     ps[i][i]=1./(s1+1.);
                   3029:     /* Computing other pijs */
                   3030:     for(j=1; j<i; j++)
                   3031:       ps[i][j]= exp(ps[i][j])*ps[i][i];
                   3032:     for(j=i+1; j<=nlstate+ndeath; j++)
                   3033:       ps[i][j]= exp(ps[i][j])*ps[i][i];
                   3034:     /* ps[i][nlstate+1]=1.-s1- ps[i][i];*/ /* Sum should be 1 */
                   3035:   } /* end i */
1.218     brouard  3036:   
1.223     brouard  3037:   for(ii=nlstate+1; ii<= nlstate+ndeath; ii++){
                   3038:     for(jj=1; jj<= nlstate+ndeath; jj++){
                   3039:       ps[ii][jj]=0;
                   3040:       ps[ii][ii]=1;
                   3041:     }
                   3042:   }
1.294     brouard  3043: 
                   3044: 
1.223     brouard  3045:   /* for(ii=1; ii<= nlstate+ndeath; ii++){ */
                   3046:   /*   for(jj=1; jj<= nlstate+ndeath; jj++){ */
                   3047:   /*   printf(" pmij  ps[%d][%d]=%lf ",ii,jj,ps[ii][jj]); */
                   3048:   /*   } */
                   3049:   /*   printf("\n "); */
                   3050:   /* } */
                   3051:   /* printf("\n ");printf("%lf ",cov[2]);*/
                   3052:   /*
                   3053:     for(i=1; i<= npar; i++) printf("%f ",x[i]);
1.218     brouard  3054:                goto end;*/
1.266     brouard  3055:   return ps; /* Pointer is unchanged since its call */
1.126     brouard  3056: }
                   3057: 
1.218     brouard  3058: /*************** backward transition probabilities ***************/ 
                   3059: 
                   3060:  /* 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 ) */
                   3061: /* double **bmij(double **ps, double *cov, int ncovmodel, double *x, int nlstate,  double ***prevacurrent, double ***dnewm, double **doldm, double **dsavm, int ij ) */
                   3062:  double **bmij(double **ps, double *cov, int ncovmodel, double *x, int nlstate,  double ***prevacurrent, int ij )
                   3063: {
1.302     brouard  3064:   /* 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  3065:    * 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  3066:    */
1.218     brouard  3067:   int i, ii, j,k;
1.222     brouard  3068:   
                   3069:   double **out, **pmij();
                   3070:   double sumnew=0.;
1.218     brouard  3071:   double agefin;
1.292     brouard  3072:   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  3073:   double **dnewm, **dsavm, **doldm;
                   3074:   double **bbmij;
                   3075:   
1.218     brouard  3076:   doldm=ddoldms; /* global pointers */
1.222     brouard  3077:   dnewm=ddnewms;
                   3078:   dsavm=ddsavms;
                   3079:   
                   3080:   agefin=cov[2];
1.268     brouard  3081:   /* Bx = Diag(w_x) P_x Diag(Sum_i w^i_x p^ij_x */
1.222     brouard  3082:   /* bmij *//* age is cov[2], ij is included in cov, but we need for
1.266     brouard  3083:      the observed prevalence (with this covariate ij) at beginning of transition */
                   3084:   /* dsavm=pmij(pmmij,cov,ncovmodel,x,nlstate); */
1.268     brouard  3085: 
                   3086:   /* P_x */
1.266     brouard  3087:   pmmij=pmij(pmmij,cov,ncovmodel,x,nlstate); /*This is forward probability from agefin to agefin + stepm */
1.268     brouard  3088:   /* outputs pmmij which is a stochastic matrix in row */
                   3089: 
                   3090:   /* Diag(w_x) */
1.292     brouard  3091:   /* Rescaling the cross-sectional prevalence: Problem with prevacurrent which can be zero */
1.268     brouard  3092:   sumnew=0.;
1.269     brouard  3093:   /*for (ii=1;ii<=nlstate+ndeath;ii++){*/
1.268     brouard  3094:   for (ii=1;ii<=nlstate;ii++){ /* Only on live states */
1.297     brouard  3095:     /* printf(" agefin=%d, ii=%d, ij=%d, prev=%f\n",(int)agefin,ii, ij, prevacurrent[(int)agefin][ii][ij]); */
1.268     brouard  3096:     sumnew+=prevacurrent[(int)agefin][ii][ij];
                   3097:   }
                   3098:   if(sumnew >0.01){  /* At least some value in the prevalence */
                   3099:     for (ii=1;ii<=nlstate+ndeath;ii++){
                   3100:       for (j=1;j<=nlstate+ndeath;j++)
1.269     brouard  3101:        doldm[ii][j]=(ii==j ? prevacurrent[(int)agefin][ii][ij]/sumnew : 0.0);
1.268     brouard  3102:     }
                   3103:   }else{
                   3104:     for (ii=1;ii<=nlstate+ndeath;ii++){
                   3105:       for (j=1;j<=nlstate+ndeath;j++)
                   3106:       doldm[ii][j]=(ii==j ? 1./nlstate : 0.0);
                   3107:     }
                   3108:     /* if(sumnew <0.9){ */
                   3109:     /*   printf("Problem internal bmij B: sum on i wi <0.9: j=%d, sum_i wi=%lf,agefin=%d\n",j,sumnew, (int)agefin); */
                   3110:     /* } */
                   3111:   }
                   3112:   k3=0.0;  /* We put the last diagonal to 0 */
                   3113:   for (ii=nlstate+1;ii<=nlstate+ndeath;ii++){
                   3114:       doldm[ii][ii]= k3;
                   3115:   }
                   3116:   /* End doldm, At the end doldm is diag[(w_i)] */
                   3117:   
1.292     brouard  3118:   /* Left product of this diag matrix by pmmij=Px (dnewm=dsavm*doldm): diag[(w_i)*Px */
                   3119:   bbmij=matprod2(dnewm, doldm,1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, pmmij); /* was a Bug Valgrind */
1.268     brouard  3120: 
1.292     brouard  3121:   /* Diag(Sum_i w^i_x p^ij_x, should be the prevalence at age x+stepm */
1.268     brouard  3122:   /* 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  3123:   for (j=1;j<=nlstate+ndeath;j++){
1.268     brouard  3124:     sumnew=0.;
1.222     brouard  3125:     for (ii=1;ii<=nlstate;ii++){
1.266     brouard  3126:       /* sumnew+=dsavm[ii][j]*prevacurrent[(int)agefin][ii][ij]; */
1.268     brouard  3127:       sumnew+=pmmij[ii][j]*doldm[ii][ii]; /* Yes prevalence at beginning of transition */
1.222     brouard  3128:     } /* sumnew is (N11+N21)/N..= N.1/N.. = sum on i of w_i pij */
1.268     brouard  3129:     for (ii=1;ii<=nlstate+ndeath;ii++){
1.222     brouard  3130:        /* if(agefin >= agemaxpar && agefin <= agemaxpar+stepm/YEARM){ */
1.268     brouard  3131:        /*      dsavm[ii][j]=(ii==j ? 1./sumnew : 0.0); */
1.222     brouard  3132:        /* }else if(agefin >= agemaxpar+stepm/YEARM){ */
1.268     brouard  3133:        /*      dsavm[ii][j]=(ii==j ? 1./sumnew : 0.0); */
1.222     brouard  3134:        /* }else */
1.268     brouard  3135:       dsavm[ii][j]=(ii==j ? 1./sumnew : 0.0);
                   3136:     } /*End ii */
                   3137:   } /* 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 */
                   3138: 
1.292     brouard  3139:   ps=matprod2(ps, dnewm,1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, dsavm); /* was a Bug Valgrind */
1.268     brouard  3140:   /* ps is now diag[w_i] * Px * diag [1/(w_1p1i+w_2 p2i)] */
1.222     brouard  3141:   /* end bmij */
1.266     brouard  3142:   return ps; /*pointer is unchanged */
1.218     brouard  3143: }
1.217     brouard  3144: /*************** transition probabilities ***************/ 
                   3145: 
1.218     brouard  3146: double **bpmij(double **ps, double *cov, int ncovmodel, double *x, int nlstate )
1.217     brouard  3147: {
                   3148:   /* According to parameters values stored in x and the covariate's values stored in cov,
                   3149:      computes the probability to be observed in state j being in state i by appying the
                   3150:      model to the ncovmodel covariates (including constant and age).
                   3151:      lnpijopii=ln(pij/pii)= aij+bij*age+cij*v1+dij*v2+... = sum_nc=1^ncovmodel xij(nc)*cov[nc]
                   3152:      and, according on how parameters are entered, the position of the coefficient xij(nc) of the
                   3153:      ncth covariate in the global vector x is given by the formula:
                   3154:      j<i nc+((i-1)*(nlstate+ndeath-1)+j-1)*ncovmodel
                   3155:      j>=i nc + ((i-1)*(nlstate+ndeath-1)+(j-2))*ncovmodel
                   3156:      Computes ln(pij/pii) (lnpijopii), deduces pij/pii by exponentiation,
                   3157:      sums on j different of i to get 1-pii/pii, deduces pii, and then all pij.
                   3158:      Outputs ps[i][j] the probability to be observed in j being in j according to
                   3159:      the values of the covariates cov[nc] and corresponding parameter values x[nc+shiftij]
                   3160:   */
                   3161:   double s1, lnpijopii;
                   3162:   /*double t34;*/
                   3163:   int i,j, nc, ii, jj;
                   3164: 
1.234     brouard  3165:   for(i=1; i<= nlstate; i++){
                   3166:     for(j=1; j<i;j++){
                   3167:       for (nc=1, lnpijopii=0.;nc <=ncovmodel; nc++){
                   3168:        /*lnpijopii += param[i][j][nc]*cov[nc];*/
                   3169:        lnpijopii += x[nc+((i-1)*(nlstate+ndeath-1)+j-1)*ncovmodel]*cov[nc];
                   3170:        /*       printf("Int j<i s1=%.17e, lnpijopii=%.17e\n",s1,lnpijopii); */
                   3171:       }
                   3172:       ps[i][j]=lnpijopii; /* In fact ln(pij/pii) */
                   3173:       /*       printf("s1=%.17e, lnpijopii=%.17e\n",s1,lnpijopii); */
                   3174:     }
                   3175:     for(j=i+1; j<=nlstate+ndeath;j++){
                   3176:       for (nc=1, lnpijopii=0.;nc <=ncovmodel; nc++){
                   3177:        /*lnpijopii += x[(i-1)*nlstate*ncovmodel+(j-2)*ncovmodel+nc+(i-1)*(ndeath-1)*ncovmodel]*cov[nc];*/
                   3178:        lnpijopii += x[nc + ((i-1)*(nlstate+ndeath-1)+(j-2))*ncovmodel]*cov[nc];
                   3179:        /*        printf("Int j>i s1=%.17e, lnpijopii=%.17e %lx %lx\n",s1,lnpijopii,s1,lnpijopii); */
                   3180:       }
                   3181:       ps[i][j]=lnpijopii; /* In fact ln(pij/pii) */
                   3182:     }
                   3183:   }
                   3184:   
                   3185:   for(i=1; i<= nlstate; i++){
                   3186:     s1=0;
                   3187:     for(j=1; j<i; j++){
                   3188:       s1+=exp(ps[i][j]); /* In fact sums pij/pii */
                   3189:       /*printf("debug1 %d %d ps=%lf exp(ps)=%lf s1+=%lf\n",i,j,ps[i][j],exp(ps[i][j]),s1); */
                   3190:     }
                   3191:     for(j=i+1; j<=nlstate+ndeath; j++){
                   3192:       s1+=exp(ps[i][j]); /* In fact sums pij/pii */
                   3193:       /*printf("debug2 %d %d ps=%lf exp(ps)=%lf s1+=%lf\n",i,j,ps[i][j],exp(ps[i][j]),s1); */
                   3194:     }
                   3195:     /* s1= sum_{j<>i} pij/pii=(1-pii)/pii and thus pii is known from s1 */
                   3196:     ps[i][i]=1./(s1+1.);
                   3197:     /* Computing other pijs */
                   3198:     for(j=1; j<i; j++)
                   3199:       ps[i][j]= exp(ps[i][j])*ps[i][i];
                   3200:     for(j=i+1; j<=nlstate+ndeath; j++)
                   3201:       ps[i][j]= exp(ps[i][j])*ps[i][i];
                   3202:     /* ps[i][nlstate+1]=1.-s1- ps[i][i];*/ /* Sum should be 1 */
                   3203:   } /* end i */
                   3204:   
                   3205:   for(ii=nlstate+1; ii<= nlstate+ndeath; ii++){
                   3206:     for(jj=1; jj<= nlstate+ndeath; jj++){
                   3207:       ps[ii][jj]=0;
                   3208:       ps[ii][ii]=1;
                   3209:     }
                   3210:   }
1.296     brouard  3211:   /* Added for prevbcast */ /* Transposed matrix too */
1.234     brouard  3212:   for(jj=1; jj<= nlstate+ndeath; jj++){
                   3213:     s1=0.;
                   3214:     for(ii=1; ii<= nlstate+ndeath; ii++){
                   3215:       s1+=ps[ii][jj];
                   3216:     }
                   3217:     for(ii=1; ii<= nlstate; ii++){
                   3218:       ps[ii][jj]=ps[ii][jj]/s1;
                   3219:     }
                   3220:   }
                   3221:   /* Transposition */
                   3222:   for(jj=1; jj<= nlstate+ndeath; jj++){
                   3223:     for(ii=jj; ii<= nlstate+ndeath; ii++){
                   3224:       s1=ps[ii][jj];
                   3225:       ps[ii][jj]=ps[jj][ii];
                   3226:       ps[jj][ii]=s1;
                   3227:     }
                   3228:   }
                   3229:   /* for(ii=1; ii<= nlstate+ndeath; ii++){ */
                   3230:   /*   for(jj=1; jj<= nlstate+ndeath; jj++){ */
                   3231:   /*   printf(" pmij  ps[%d][%d]=%lf ",ii,jj,ps[ii][jj]); */
                   3232:   /*   } */
                   3233:   /*   printf("\n "); */
                   3234:   /* } */
                   3235:   /* printf("\n ");printf("%lf ",cov[2]);*/
                   3236:   /*
                   3237:     for(i=1; i<= npar; i++) printf("%f ",x[i]);
                   3238:     goto end;*/
                   3239:   return ps;
1.217     brouard  3240: }
                   3241: 
                   3242: 
1.126     brouard  3243: /**************** Product of 2 matrices ******************/
                   3244: 
1.145     brouard  3245: double **matprod2(double **out, double **in,int nrl, int nrh, int ncl, int nch, int ncolol, int ncoloh, double **b)
1.126     brouard  3246: {
                   3247:   /* Computes the matrix product of in(1,nrh-nrl+1)(1,nch-ncl+1) times
                   3248:      b(1,nch-ncl+1)(1,ncoloh-ncolol+1) into out(...) */
                   3249:   /* in, b, out are matrice of pointers which should have been initialized 
                   3250:      before: only the contents of out is modified. The function returns
                   3251:      a pointer to pointers identical to out */
1.145     brouard  3252:   int i, j, k;
1.126     brouard  3253:   for(i=nrl; i<= nrh; i++)
1.145     brouard  3254:     for(k=ncolol; k<=ncoloh; k++){
                   3255:       out[i][k]=0.;
                   3256:       for(j=ncl; j<=nch; j++)
                   3257:        out[i][k] +=in[i][j]*b[j][k];
                   3258:     }
1.126     brouard  3259:   return out;
                   3260: }
                   3261: 
                   3262: 
                   3263: /************* Higher Matrix Product ***************/
                   3264: 
1.235     brouard  3265: 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  3266: {
1.218     brouard  3267:   /* Computes the transition matrix starting at age 'age' and combination of covariate values corresponding to ij over 
1.126     brouard  3268:      'nhstepm*hstepm*stepm' months (i.e. until
                   3269:      age (in years)  age+nhstepm*hstepm*stepm/12) by multiplying 
                   3270:      nhstepm*hstepm matrices. 
                   3271:      Output is stored in matrix po[i][j][h] for h every 'hstepm' step 
                   3272:      (typically every 2 years instead of every month which is too big 
                   3273:      for the memory).
                   3274:      Model is determined by parameters x and covariates have to be 
                   3275:      included manually here. 
                   3276: 
                   3277:      */
                   3278: 
                   3279:   int i, j, d, h, k;
1.131     brouard  3280:   double **out, cov[NCOVMAX+1];
1.126     brouard  3281:   double **newm;
1.187     brouard  3282:   double agexact;
1.214     brouard  3283:   double agebegin, ageend;
1.126     brouard  3284: 
                   3285:   /* Hstepm could be zero and should return the unit matrix */
                   3286:   for (i=1;i<=nlstate+ndeath;i++)
                   3287:     for (j=1;j<=nlstate+ndeath;j++){
                   3288:       oldm[i][j]=(i==j ? 1.0 : 0.0);
                   3289:       po[i][j][0]=(i==j ? 1.0 : 0.0);
                   3290:     }
                   3291:   /* Even if hstepm = 1, at least one multiplication by the unit matrix */
                   3292:   for(h=1; h <=nhstepm; h++){
                   3293:     for(d=1; d <=hstepm; d++){
                   3294:       newm=savm;
                   3295:       /* Covariates have to be included here again */
                   3296:       cov[1]=1.;
1.214     brouard  3297:       agexact=age+((h-1)*hstepm + (d-1))*stepm/YEARM; /* age just before transition */
1.187     brouard  3298:       cov[2]=agexact;
                   3299:       if(nagesqr==1)
1.227     brouard  3300:        cov[3]= agexact*agexact;
1.235     brouard  3301:       for (k=1; k<=nsd;k++) { /* For single dummy covariates only */
                   3302:                        /* Here comes the value of the covariate 'ij' after renumbering k with single dummy covariates */
                   3303:        cov[2+nagesqr+TvarsDind[k]]=nbcode[TvarsD[k]][codtabm(ij,k)];
                   3304:        /* 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)); */
                   3305:       }
                   3306:       for (k=1; k<=nsq;k++) { /* For single varying covariates only */
                   3307:        /* Here comes the value of quantitative after renumbering k with single quantitative covariates */
                   3308:        cov[2+nagesqr+TvarsQind[k]]=Tqresult[nres][k]; 
                   3309:        /* 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]); */
                   3310:       }
                   3311:       for (k=1; k<=cptcovage;k++){
                   3312:        if(Dummy[Tvar[Tage[k]]]){
                   3313:          cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,k)]*cov[2];
                   3314:        } else{
                   3315:          cov[2+nagesqr+Tage[k]]=Tqresult[nres][k]; 
                   3316:        }
                   3317:        /* 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]); */
                   3318:       }
                   3319:       for (k=1; k<=cptcovprod;k++){ /*  */
                   3320:        /* 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]); */
                   3321:        cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)] * nbcode[Tvard[k][2]][codtabm(ij,k)];
                   3322:       }
                   3323:       /* for (k=1; k<=cptcovn;k++)  */
                   3324:       /*       cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,k)]; */
                   3325:       /* for (k=1; k<=cptcovage;k++) /\* Should start at cptcovn+1 *\/ */
                   3326:       /*       cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,k)]*cov[2]; */
                   3327:       /* for (k=1; k<=cptcovprod;k++) /\* Useless because included in cptcovn *\/ */
                   3328:       /*       cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)]*nbcode[Tvard[k][2]][codtabm(ij,k)]; */
1.227     brouard  3329:       
                   3330:       
1.126     brouard  3331:       /*printf("hxi cptcov=%d cptcode=%d\n",cptcov,cptcode);*/
                   3332:       /*printf("h=%d d=%d age=%f cov=%f\n",h,d,age,cov[2]);*/
1.218     brouard  3333:                        /* right multiplication of oldm by the current matrix */
1.126     brouard  3334:       out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, 
                   3335:                   pmij(pmmij,cov,ncovmodel,x,nlstate));
1.217     brouard  3336:       /* if((int)age == 70){ */
                   3337:       /*       printf(" Forward hpxij age=%d agexact=%f d=%d nhstepm=%d hstepm=%d\n", (int) age, agexact, d, nhstepm, hstepm); */
                   3338:       /*       for(i=1; i<=nlstate+ndeath; i++) { */
                   3339:       /*         printf("%d pmmij ",i); */
                   3340:       /*         for(j=1;j<=nlstate+ndeath;j++) { */
                   3341:       /*           printf("%f ",pmmij[i][j]); */
                   3342:       /*         } */
                   3343:       /*         printf(" oldm "); */
                   3344:       /*         for(j=1;j<=nlstate+ndeath;j++) { */
                   3345:       /*           printf("%f ",oldm[i][j]); */
                   3346:       /*         } */
                   3347:       /*         printf("\n"); */
                   3348:       /*       } */
                   3349:       /* } */
1.126     brouard  3350:       savm=oldm;
                   3351:       oldm=newm;
                   3352:     }
                   3353:     for(i=1; i<=nlstate+ndeath; i++)
                   3354:       for(j=1;j<=nlstate+ndeath;j++) {
1.267     brouard  3355:        po[i][j][h]=newm[i][j];
                   3356:        /*if(h==nhstepm) printf("po[%d][%d][%d]=%f ",i,j,h,po[i][j][h]);*/
1.126     brouard  3357:       }
1.128     brouard  3358:     /*printf("h=%d ",h);*/
1.126     brouard  3359:   } /* end h */
1.267     brouard  3360:   /*     printf("\n H=%d \n",h); */
1.126     brouard  3361:   return po;
                   3362: }
                   3363: 
1.217     brouard  3364: /************* Higher Back Matrix Product ***************/
1.218     brouard  3365: /* 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  3366: 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  3367: {
1.266     brouard  3368:   /* For a combination of dummy covariate ij, computes the transition matrix starting at age 'age' over
1.217     brouard  3369:      'nhstepm*hstepm*stepm' months (i.e. until
1.218     brouard  3370:      age (in years)  age+nhstepm*hstepm*stepm/12) by multiplying
                   3371:      nhstepm*hstepm matrices.
                   3372:      Output is stored in matrix po[i][j][h] for h every 'hstepm' step
                   3373:      (typically every 2 years instead of every month which is too big
1.217     brouard  3374:      for the memory).
1.218     brouard  3375:      Model is determined by parameters x and covariates have to be
1.266     brouard  3376:      included manually here. Then we use a call to bmij(x and cov)
                   3377:      The addresss of po (p3mat allocated to the dimension of nhstepm) should be stored for output
1.222     brouard  3378:   */
1.217     brouard  3379: 
                   3380:   int i, j, d, h, k;
1.266     brouard  3381:   double **out, cov[NCOVMAX+1], **bmij();
                   3382:   double **newm, ***newmm;
1.217     brouard  3383:   double agexact;
                   3384:   double agebegin, ageend;
1.222     brouard  3385:   double **oldm, **savm;
1.217     brouard  3386: 
1.266     brouard  3387:   newmm=po; /* To be saved */
                   3388:   oldm=oldms;savm=savms; /* Global pointers */
1.217     brouard  3389:   /* Hstepm could be zero and should return the unit matrix */
                   3390:   for (i=1;i<=nlstate+ndeath;i++)
                   3391:     for (j=1;j<=nlstate+ndeath;j++){
                   3392:       oldm[i][j]=(i==j ? 1.0 : 0.0);
                   3393:       po[i][j][0]=(i==j ? 1.0 : 0.0);
                   3394:     }
                   3395:   /* Even if hstepm = 1, at least one multiplication by the unit matrix */
                   3396:   for(h=1; h <=nhstepm; h++){
                   3397:     for(d=1; d <=hstepm; d++){
                   3398:       newm=savm;
                   3399:       /* Covariates have to be included here again */
                   3400:       cov[1]=1.;
1.271     brouard  3401:       agexact=age-( (h-1)*hstepm + (d)  )*stepm/YEARM; /* age just before transition, d or d-1? */
1.217     brouard  3402:       /* agexact=age+((h-1)*hstepm + (d-1))*stepm/YEARM; /\* age just before transition *\/ */
                   3403:       cov[2]=agexact;
                   3404:       if(nagesqr==1)
1.222     brouard  3405:        cov[3]= agexact*agexact;
1.266     brouard  3406:       for (k=1; k<=cptcovn;k++){
                   3407:       /*       cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,k)]; */
                   3408:       /* /\* cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,Tvar[k])]; *\/ */
                   3409:        cov[2+nagesqr+TvarsDind[k]]=nbcode[TvarsD[k]][codtabm(ij,k)];
                   3410:         /* 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)); */
                   3411:       }
1.267     brouard  3412:       for (k=1; k<=nsq;k++) { /* For single varying covariates only */
                   3413:        /* Here comes the value of quantitative after renumbering k with single quantitative covariates */
                   3414:        cov[2+nagesqr+TvarsQind[k]]=Tqresult[nres][k]; 
                   3415:        /* 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]); */
                   3416:       }
                   3417:       for (k=1; k<=cptcovage;k++){ /* Should start at cptcovn+1 */
                   3418:        if(Dummy[Tvar[Tage[k]]]){
                   3419:          cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,k)]*cov[2];
                   3420:        } else{
                   3421:          cov[2+nagesqr+Tage[k]]=Tqresult[nres][k]; 
                   3422:        }
                   3423:        /* 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]); */
                   3424:       }
                   3425:       for (k=1; k<=cptcovprod;k++){ /* Useless because included in cptcovn */
1.222     brouard  3426:        cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)]*nbcode[Tvard[k][2]][codtabm(ij,k)];
1.267     brouard  3427:       }                        
1.217     brouard  3428:       /*printf("hxi cptcov=%d cptcode=%d\n",cptcov,cptcode);*/
                   3429:       /*printf("h=%d d=%d age=%f cov=%f\n",h,d,age,cov[2]);*/
1.267     brouard  3430: 
1.218     brouard  3431:       /* Careful transposed matrix */
1.266     brouard  3432:       /* age is in cov[2], prevacurrent at beginning of transition. */
1.218     brouard  3433:       /* out=matprod2(newm, bmij(pmmij,cov,ncovmodel,x,nlstate,prevacurrent, dnewm, doldm, dsavm,ij),\ */
1.222     brouard  3434:       /*                                                1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm); */
1.218     brouard  3435:       out=matprod2(newm, bmij(pmmij,cov,ncovmodel,x,nlstate,prevacurrent,ij),\
1.222     brouard  3436:                   1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm);
1.217     brouard  3437:       /* if((int)age == 70){ */
                   3438:       /*       printf(" Backward hbxij age=%d agexact=%f d=%d nhstepm=%d hstepm=%d\n", (int) age, agexact, d, nhstepm, hstepm); */
                   3439:       /*       for(i=1; i<=nlstate+ndeath; i++) { */
                   3440:       /*         printf("%d pmmij ",i); */
                   3441:       /*         for(j=1;j<=nlstate+ndeath;j++) { */
                   3442:       /*           printf("%f ",pmmij[i][j]); */
                   3443:       /*         } */
                   3444:       /*         printf(" oldm "); */
                   3445:       /*         for(j=1;j<=nlstate+ndeath;j++) { */
                   3446:       /*           printf("%f ",oldm[i][j]); */
                   3447:       /*         } */
                   3448:       /*         printf("\n"); */
                   3449:       /*       } */
                   3450:       /* } */
                   3451:       savm=oldm;
                   3452:       oldm=newm;
                   3453:     }
                   3454:     for(i=1; i<=nlstate+ndeath; i++)
                   3455:       for(j=1;j<=nlstate+ndeath;j++) {
1.222     brouard  3456:        po[i][j][h]=newm[i][j];
1.268     brouard  3457:        /* if(h==nhstepm) */
                   3458:        /*   printf("po[%d][%d][%d]=%f ",i,j,h,po[i][j][h]); */
1.217     brouard  3459:       }
1.268     brouard  3460:     /* printf("h=%d %.1f ",h, agexact); */
1.217     brouard  3461:   } /* end h */
1.268     brouard  3462:   /* printf("\n H=%d nhs=%d \n",h, nhstepm); */
1.217     brouard  3463:   return po;
                   3464: }
                   3465: 
                   3466: 
1.162     brouard  3467: #ifdef NLOPT
                   3468:   double  myfunc(unsigned n, const double *p1, double *grad, void *pd){
                   3469:   double fret;
                   3470:   double *xt;
                   3471:   int j;
                   3472:   myfunc_data *d2 = (myfunc_data *) pd;
                   3473: /* xt = (p1-1); */
                   3474:   xt=vector(1,n); 
                   3475:   for (j=1;j<=n;j++)   xt[j]=p1[j-1]; /* xt[1]=p1[0] */
                   3476: 
                   3477:   fret=(d2->function)(xt); /*  p xt[1]@8 is fine */
                   3478:   /* fret=(*func)(xt); /\*  p xt[1]@8 is fine *\/ */
                   3479:   printf("Function = %.12lf ",fret);
                   3480:   for (j=1;j<=n;j++) printf(" %d %.8lf", j, xt[j]); 
                   3481:   printf("\n");
                   3482:  free_vector(xt,1,n);
                   3483:   return fret;
                   3484: }
                   3485: #endif
1.126     brouard  3486: 
                   3487: /*************** log-likelihood *************/
                   3488: double func( double *x)
                   3489: {
1.226     brouard  3490:   int i, ii, j, k, mi, d, kk;
                   3491:   int ioffset=0;
                   3492:   double l, ll[NLSTATEMAX+1], cov[NCOVMAX+1];
                   3493:   double **out;
                   3494:   double lli; /* Individual log likelihood */
                   3495:   int s1, s2;
1.228     brouard  3496:   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  3497:   double bbh, survp;
                   3498:   long ipmx;
                   3499:   double agexact;
                   3500:   /*extern weight */
                   3501:   /* We are differentiating ll according to initial status */
                   3502:   /*  for (i=1;i<=npar;i++) printf("%f ", x[i]);*/
                   3503:   /*for(i=1;i<imx;i++) 
                   3504:     printf(" %d\n",s[4][i]);
                   3505:   */
1.162     brouard  3506: 
1.226     brouard  3507:   ++countcallfunc;
1.162     brouard  3508: 
1.226     brouard  3509:   cov[1]=1.;
1.126     brouard  3510: 
1.226     brouard  3511:   for(k=1; k<=nlstate; k++) ll[k]=0.;
1.224     brouard  3512:   ioffset=0;
1.226     brouard  3513:   if(mle==1){
                   3514:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
                   3515:       /* Computes the values of the ncovmodel covariates of the model
                   3516:         depending if the covariates are fixed or varying (age dependent) and stores them in cov[]
                   3517:         Then computes with function pmij which return a matrix p[i][j] giving the elementary probability
                   3518:         to be observed in j being in i according to the model.
                   3519:       */
1.243     brouard  3520:       ioffset=2+nagesqr ;
1.233     brouard  3521:    /* Fixed */
1.234     brouard  3522:       for (k=1; k<=ncovf;k++){ /* Simple and product fixed covariates without age* products */
                   3523:        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)*/
                   3524:       }
1.226     brouard  3525:       /* In model V2+V1*V4+age*V3+V3*V2 Tvar[1] is V2, Tvar[2=V1*V4] 
                   3526:         is 6, Tvar[3=age*V3] should not be computed because of age Tvar[4=V3*V2] 
                   3527:         has been calculated etc */
                   3528:       /* For an individual i, wav[i] gives the number of effective waves */
                   3529:       /* We compute the contribution to Likelihood of each effective transition
                   3530:         mw[mi][i] is real wave of the mi th effectve wave */
                   3531:       /* Then statuses are computed at each begin and end of an effective wave s1=s[ mw[mi][i] ][i];
                   3532:         s2=s[mw[mi+1][i]][i];
                   3533:         And the iv th varying covariate is the cotvar[mw[mi+1][i]][iv][i]
                   3534:         But if the variable is not in the model TTvar[iv] is the real variable effective in the model:
                   3535:         meaning that decodemodel should be used cotvar[mw[mi+1][i]][TTvar[iv]][i]
                   3536:       */
                   3537:       for(mi=1; mi<= wav[i]-1; mi++){
1.234     brouard  3538:        for(k=1; k <= ncovv ; k++){ /* Varying  covariates (single and product but no age )*/
1.242     brouard  3539:          /* cov[ioffset+TvarVind[k]]=cotvar[mw[mi][i]][Tvar[TvarVind[k]]][i]; */
                   3540:          cov[ioffset+TvarVind[k]]=cotvar[mw[mi][i]][Tvar[TvarVind[k]]-ncovcol-nqv][i];
1.234     brouard  3541:        }
                   3542:        for (ii=1;ii<=nlstate+ndeath;ii++)
                   3543:          for (j=1;j<=nlstate+ndeath;j++){
                   3544:            oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   3545:            savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   3546:          }
                   3547:        for(d=0; d<dh[mi][i]; d++){
                   3548:          newm=savm;
                   3549:          agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
                   3550:          cov[2]=agexact;
                   3551:          if(nagesqr==1)
                   3552:            cov[3]= agexact*agexact;  /* Should be changed here */
                   3553:          for (kk=1; kk<=cptcovage;kk++) {
1.242     brouard  3554:          if(!FixedV[Tvar[Tage[kk]]])
1.234     brouard  3555:            cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact; /* Tage[kk] gives the data-covariate associated with age */
1.242     brouard  3556:          else
                   3557:            cov[Tage[kk]+2+nagesqr]=cotvar[mw[mi][i]][Tvar[Tage[kk]]-ncovcol-nqv][i]*agexact;
1.234     brouard  3558:          }
                   3559:          out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   3560:                       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   3561:          savm=oldm;
                   3562:          oldm=newm;
                   3563:        } /* end mult */
                   3564:        
                   3565:        /*lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]);*/ /* Original formula */
                   3566:        /* But now since version 0.9 we anticipate for bias at large stepm.
                   3567:         * If stepm is larger than one month (smallest stepm) and if the exact delay 
                   3568:         * (in months) between two waves is not a multiple of stepm, we rounded to 
                   3569:         * the nearest (and in case of equal distance, to the lowest) interval but now
                   3570:         * we keep into memory the bias bh[mi][i] and also the previous matrix product
                   3571:         * (i.e to dh[mi][i]-1) saved in 'savm'. Then we inter(extra)polate the
                   3572:         * probability in order to take into account the bias as a fraction of the way
1.231     brouard  3573:                                 * from savm to out if bh is negative or even beyond if bh is positive. bh varies
                   3574:                                 * -stepm/2 to stepm/2 .
                   3575:                                 * For stepm=1 the results are the same as for previous versions of Imach.
                   3576:                                 * For stepm > 1 the results are less biased than in previous versions. 
                   3577:                                 */
1.234     brouard  3578:        s1=s[mw[mi][i]][i];
                   3579:        s2=s[mw[mi+1][i]][i];
                   3580:        bbh=(double)bh[mi][i]/(double)stepm; 
                   3581:        /* bias bh is positive if real duration
                   3582:         * is higher than the multiple of stepm and negative otherwise.
                   3583:         */
                   3584:        /* lli= (savm[s1][s2]>1.e-8 ?(1.+bbh)*log(out[s1][s2])- bbh*log(savm[s1][s2]):log((1.+bbh)*out[s1][s2]));*/
                   3585:        if( s2 > nlstate){ 
                   3586:          /* i.e. if s2 is a death state and if the date of death is known 
                   3587:             then the contribution to the likelihood is the probability to 
                   3588:             die between last step unit time and current  step unit time, 
                   3589:             which is also equal to probability to die before dh 
                   3590:             minus probability to die before dh-stepm . 
                   3591:             In version up to 0.92 likelihood was computed
                   3592:             as if date of death was unknown. Death was treated as any other
                   3593:             health state: the date of the interview describes the actual state
                   3594:             and not the date of a change in health state. The former idea was
                   3595:             to consider that at each interview the state was recorded
                   3596:             (healthy, disable or death) and IMaCh was corrected; but when we
                   3597:             introduced the exact date of death then we should have modified
                   3598:             the contribution of an exact death to the likelihood. This new
                   3599:             contribution is smaller and very dependent of the step unit
                   3600:             stepm. It is no more the probability to die between last interview
                   3601:             and month of death but the probability to survive from last
                   3602:             interview up to one month before death multiplied by the
                   3603:             probability to die within a month. Thanks to Chris
                   3604:             Jackson for correcting this bug.  Former versions increased
                   3605:             mortality artificially. The bad side is that we add another loop
                   3606:             which slows down the processing. The difference can be up to 10%
                   3607:             lower mortality.
                   3608:          */
                   3609:          /* If, at the beginning of the maximization mostly, the
                   3610:             cumulative probability or probability to be dead is
                   3611:             constant (ie = 1) over time d, the difference is equal to
                   3612:             0.  out[s1][3] = savm[s1][3]: probability, being at state
                   3613:             s1 at precedent wave, to be dead a month before current
                   3614:             wave is equal to probability, being at state s1 at
                   3615:             precedent wave, to be dead at mont of the current
                   3616:             wave. Then the observed probability (that this person died)
                   3617:             is null according to current estimated parameter. In fact,
                   3618:             it should be very low but not zero otherwise the log go to
                   3619:             infinity.
                   3620:          */
1.183     brouard  3621: /* #ifdef INFINITYORIGINAL */
                   3622: /*         lli=log(out[s1][s2] - savm[s1][s2]); */
                   3623: /* #else */
                   3624: /*       if ((out[s1][s2] - savm[s1][s2]) < mytinydouble)  */
                   3625: /*         lli=log(mytinydouble); */
                   3626: /*       else */
                   3627: /*         lli=log(out[s1][s2] - savm[s1][s2]); */
                   3628: /* #endif */
1.226     brouard  3629:          lli=log(out[s1][s2] - savm[s1][s2]);
1.216     brouard  3630:          
1.226     brouard  3631:        } else if  ( s2==-1 ) { /* alive */
                   3632:          for (j=1,survp=0. ; j<=nlstate; j++) 
                   3633:            survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
                   3634:          /*survp += out[s1][j]; */
                   3635:          lli= log(survp);
                   3636:        }
                   3637:        else if  (s2==-4) { 
                   3638:          for (j=3,survp=0. ; j<=nlstate; j++)  
                   3639:            survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
                   3640:          lli= log(survp); 
                   3641:        } 
                   3642:        else if  (s2==-5) { 
                   3643:          for (j=1,survp=0. ; j<=2; j++)  
                   3644:            survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
                   3645:          lli= log(survp); 
                   3646:        } 
                   3647:        else{
                   3648:          lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */
                   3649:          /*  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 */
                   3650:        } 
                   3651:        /*lli=(1.+bbh)*log(out[s1][s2])- bbh*log(savm[s1][s2]);*/
                   3652:        /*if(lli ==000.0)*/
                   3653:        /*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); */
                   3654:        ipmx +=1;
                   3655:        sw += weight[i];
                   3656:        ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
                   3657:        /* if (lli < log(mytinydouble)){ */
                   3658:        /*   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); */
                   3659:        /*   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]); */
                   3660:        /* } */
                   3661:       } /* end of wave */
                   3662:     } /* end of individual */
                   3663:   }  else if(mle==2){
                   3664:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
                   3665:       for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i];
                   3666:       for(mi=1; mi<= wav[i]-1; mi++){
                   3667:        for (ii=1;ii<=nlstate+ndeath;ii++)
                   3668:          for (j=1;j<=nlstate+ndeath;j++){
                   3669:            oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   3670:            savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   3671:          }
                   3672:        for(d=0; d<=dh[mi][i]; d++){
                   3673:          newm=savm;
                   3674:          agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
                   3675:          cov[2]=agexact;
                   3676:          if(nagesqr==1)
                   3677:            cov[3]= agexact*agexact;
                   3678:          for (kk=1; kk<=cptcovage;kk++) {
                   3679:            cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact;
                   3680:          }
                   3681:          out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   3682:                       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   3683:          savm=oldm;
                   3684:          oldm=newm;
                   3685:        } /* end mult */
                   3686:       
                   3687:        s1=s[mw[mi][i]][i];
                   3688:        s2=s[mw[mi+1][i]][i];
                   3689:        bbh=(double)bh[mi][i]/(double)stepm; 
                   3690:        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 */
                   3691:        ipmx +=1;
                   3692:        sw += weight[i];
                   3693:        ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
                   3694:       } /* end of wave */
                   3695:     } /* end of individual */
                   3696:   }  else if(mle==3){  /* exponential inter-extrapolation */
                   3697:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
                   3698:       for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i];
                   3699:       for(mi=1; mi<= wav[i]-1; mi++){
                   3700:        for (ii=1;ii<=nlstate+ndeath;ii++)
                   3701:          for (j=1;j<=nlstate+ndeath;j++){
                   3702:            oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   3703:            savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   3704:          }
                   3705:        for(d=0; d<dh[mi][i]; d++){
                   3706:          newm=savm;
                   3707:          agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
                   3708:          cov[2]=agexact;
                   3709:          if(nagesqr==1)
                   3710:            cov[3]= agexact*agexact;
                   3711:          for (kk=1; kk<=cptcovage;kk++) {
                   3712:            cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact;
                   3713:          }
                   3714:          out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   3715:                       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   3716:          savm=oldm;
                   3717:          oldm=newm;
                   3718:        } /* end mult */
                   3719:       
                   3720:        s1=s[mw[mi][i]][i];
                   3721:        s2=s[mw[mi+1][i]][i];
                   3722:        bbh=(double)bh[mi][i]/(double)stepm; 
                   3723:        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 */
                   3724:        ipmx +=1;
                   3725:        sw += weight[i];
                   3726:        ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
                   3727:       } /* end of wave */
                   3728:     } /* end of individual */
                   3729:   }else if (mle==4){  /* ml=4 no inter-extrapolation */
                   3730:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
                   3731:       for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i];
                   3732:       for(mi=1; mi<= wav[i]-1; mi++){
                   3733:        for (ii=1;ii<=nlstate+ndeath;ii++)
                   3734:          for (j=1;j<=nlstate+ndeath;j++){
                   3735:            oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   3736:            savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   3737:          }
                   3738:        for(d=0; d<dh[mi][i]; d++){
                   3739:          newm=savm;
                   3740:          agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
                   3741:          cov[2]=agexact;
                   3742:          if(nagesqr==1)
                   3743:            cov[3]= agexact*agexact;
                   3744:          for (kk=1; kk<=cptcovage;kk++) {
                   3745:            cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact;
                   3746:          }
1.126     brouard  3747:        
1.226     brouard  3748:          out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   3749:                       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   3750:          savm=oldm;
                   3751:          oldm=newm;
                   3752:        } /* end mult */
                   3753:       
                   3754:        s1=s[mw[mi][i]][i];
                   3755:        s2=s[mw[mi+1][i]][i];
                   3756:        if( s2 > nlstate){ 
                   3757:          lli=log(out[s1][s2] - savm[s1][s2]);
                   3758:        } else if  ( s2==-1 ) { /* alive */
                   3759:          for (j=1,survp=0. ; j<=nlstate; j++) 
                   3760:            survp += out[s1][j];
                   3761:          lli= log(survp);
                   3762:        }else{
                   3763:          lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]); /* Original formula */
                   3764:        }
                   3765:        ipmx +=1;
                   3766:        sw += weight[i];
                   3767:        ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
1.126     brouard  3768: /*     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  3769:       } /* end of wave */
                   3770:     } /* end of individual */
                   3771:   }else{  /* ml=5 no inter-extrapolation no jackson =0.8a */
                   3772:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
                   3773:       for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i];
                   3774:       for(mi=1; mi<= wav[i]-1; mi++){
                   3775:        for (ii=1;ii<=nlstate+ndeath;ii++)
                   3776:          for (j=1;j<=nlstate+ndeath;j++){
                   3777:            oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   3778:            savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   3779:          }
                   3780:        for(d=0; d<dh[mi][i]; d++){
                   3781:          newm=savm;
                   3782:          agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
                   3783:          cov[2]=agexact;
                   3784:          if(nagesqr==1)
                   3785:            cov[3]= agexact*agexact;
                   3786:          for (kk=1; kk<=cptcovage;kk++) {
                   3787:            cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact;
                   3788:          }
1.126     brouard  3789:        
1.226     brouard  3790:          out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   3791:                       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   3792:          savm=oldm;
                   3793:          oldm=newm;
                   3794:        } /* end mult */
                   3795:       
                   3796:        s1=s[mw[mi][i]][i];
                   3797:        s2=s[mw[mi+1][i]][i];
                   3798:        lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]); /* Original formula */
                   3799:        ipmx +=1;
                   3800:        sw += weight[i];
                   3801:        ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
                   3802:        /*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]);*/
                   3803:       } /* end of wave */
                   3804:     } /* end of individual */
                   3805:   } /* End of if */
                   3806:   for(k=1,l=0.; k<=nlstate; k++) l += ll[k];
                   3807:   /* printf("l1=%f l2=%f ",ll[1],ll[2]); */
                   3808:   l= l*ipmx/sw; /* To get the same order of magnitude as if weight=1 for every body */
                   3809:   return -l;
1.126     brouard  3810: }
                   3811: 
                   3812: /*************** log-likelihood *************/
                   3813: double funcone( double *x)
                   3814: {
1.228     brouard  3815:   /* Same as func but slower because of a lot of printf and if */
1.126     brouard  3816:   int i, ii, j, k, mi, d, kk;
1.228     brouard  3817:   int ioffset=0;
1.131     brouard  3818:   double l, ll[NLSTATEMAX+1], cov[NCOVMAX+1];
1.126     brouard  3819:   double **out;
                   3820:   double lli; /* Individual log likelihood */
                   3821:   double llt;
                   3822:   int s1, s2;
1.228     brouard  3823:   int iv=0, iqv=0, itv=0, iqtv=0 ; /* Index of varying covariate, fixed quantitative cov, time varying covariate, quantitative time varying covariate */
                   3824: 
1.126     brouard  3825:   double bbh, survp;
1.187     brouard  3826:   double agexact;
1.214     brouard  3827:   double agebegin, ageend;
1.126     brouard  3828:   /*extern weight */
                   3829:   /* We are differentiating ll according to initial status */
                   3830:   /*  for (i=1;i<=npar;i++) printf("%f ", x[i]);*/
                   3831:   /*for(i=1;i<imx;i++) 
                   3832:     printf(" %d\n",s[4][i]);
                   3833:   */
                   3834:   cov[1]=1.;
                   3835: 
                   3836:   for(k=1; k<=nlstate; k++) ll[k]=0.;
1.224     brouard  3837:   ioffset=0;
                   3838:   for (i=1,ipmx=0, sw=0.; i<=imx; i++){
1.243     brouard  3839:     /* ioffset=2+nagesqr+cptcovage; */
                   3840:     ioffset=2+nagesqr;
1.232     brouard  3841:     /* Fixed */
1.224     brouard  3842:     /* for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i]; */
1.232     brouard  3843:     /* for (k=1; k<=ncoveff;k++){ /\* Simple and product fixed Dummy covariates without age* products *\/ */
                   3844:     for (k=1; k<=ncovf;k++){ /* Simple and product fixed covariates without age* products */
                   3845:       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)*/
                   3846: /*    cov[ioffset+TvarFind[1]]=covar[Tvar[TvarFind[1]]][i];  */
                   3847: /*    cov[2+6]=covar[Tvar[6]][i];  */
                   3848: /*    cov[2+6]=covar[2][i]; V2  */
                   3849: /*    cov[TvarFind[2]]=covar[Tvar[TvarFind[2]]][i];  */
                   3850: /*    cov[2+7]=covar[Tvar[7]][i];  */
                   3851: /*    cov[2+7]=covar[7][i]; V7=V1*V2  */
                   3852: /*    cov[TvarFind[3]]=covar[Tvar[TvarFind[3]]][i];  */
                   3853: /*    cov[2+9]=covar[Tvar[9]][i];  */
                   3854: /*    cov[2+9]=covar[1][i]; V1  */
1.225     brouard  3855:     }
1.232     brouard  3856:     /* for (k=1; k<=nqfveff;k++){ /\* Simple and product fixed Quantitative covariates without age* products *\/ */
                   3857:     /*   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?)*\/ */
                   3858:     /* } */
1.231     brouard  3859:     /* for(iqv=1; iqv <= nqfveff; iqv++){ /\* Quantitative fixed covariates *\/ */
                   3860:     /*   cov[++ioffset]=coqvar[Tvar[iqv]][i]; /\* Only V2 k=6 and V1*V2 7 *\/ */
                   3861:     /* } */
1.225     brouard  3862:     
1.233     brouard  3863: 
                   3864:     for(mi=1; mi<= wav[i]-1; mi++){  /* Varying with waves */
1.232     brouard  3865:     /* Wave varying (but not age varying) */
                   3866:       for(k=1; k <= ncovv ; k++){ /* Varying  covariates (single and product but no age )*/
1.242     brouard  3867:        /* cov[ioffset+TvarVind[k]]=cotvar[mw[mi][i]][Tvar[TvarVind[k]]][i]; */
                   3868:        cov[ioffset+TvarVind[k]]=cotvar[mw[mi][i]][Tvar[TvarVind[k]]-ncovcol-nqv][i];
                   3869:       }
1.232     brouard  3870:       /* for(itv=1; itv <= ntveff; itv++){ /\* Varying dummy covariates (single??)*\/ */
1.242     brouard  3871:       /* iv= Tvar[Tmodelind[ioffset-2-nagesqr-cptcovage+itv]]-ncovcol-nqv; /\* Counting the # varying covariate from 1 to ntveff *\/ */
                   3872:       /* cov[ioffset+iv]=cotvar[mw[mi][i]][iv][i]; */
                   3873:       /* k=ioffset-2-nagesqr-cptcovage+itv; /\* position in simple model *\/ */
                   3874:       /* cov[ioffset+itv]=cotvar[mw[mi][i]][TmodelInvind[itv]][i]; */
                   3875:       /* 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  3876:       /* for(iqtv=1; iqtv <= nqtveff; iqtv++){ /\* Varying quantitatives covariates *\/ */
1.242     brouard  3877:       /*       iv=TmodelInvQind[iqtv]; /\* Counting the # varying covariate from 1 to ntveff *\/ */
                   3878:       /*       /\* 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]); *\/ */
                   3879:       /*       cov[ioffset+ntveff+iqtv]=cotqvar[mw[mi][i]][TmodelInvQind[iqtv]][i]; */
1.232     brouard  3880:       /* } */
1.126     brouard  3881:       for (ii=1;ii<=nlstate+ndeath;ii++)
1.242     brouard  3882:        for (j=1;j<=nlstate+ndeath;j++){
                   3883:          oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   3884:          savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   3885:        }
1.214     brouard  3886:       
                   3887:       agebegin=agev[mw[mi][i]][i]; /* Age at beginning of effective wave */
                   3888:       ageend=agev[mw[mi][i]][i] + (dh[mi][i])*stepm/YEARM; /* Age at end of effective wave and at the end of transition */
                   3889:       for(d=0; d<dh[mi][i]; d++){  /* Delay between two effective waves */
1.247     brouard  3890:       /* for(d=0; d<=0; d++){  /\* Delay between two effective waves Only one matrix to speed up*\/ */
1.242     brouard  3891:        /*dh[m][i] or dh[mw[mi][i]][i] is the delay between two effective waves m=mw[mi][i]
                   3892:          and mw[mi+1][i]. dh depends on stepm.*/
                   3893:        newm=savm;
1.247     brouard  3894:        agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;  /* Here d is needed */
1.242     brouard  3895:        cov[2]=agexact;
                   3896:        if(nagesqr==1)
                   3897:          cov[3]= agexact*agexact;
                   3898:        for (kk=1; kk<=cptcovage;kk++) {
                   3899:          if(!FixedV[Tvar[Tage[kk]]])
                   3900:            cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact;
                   3901:          else
                   3902:            cov[Tage[kk]+2+nagesqr]=cotvar[mw[mi][i]][Tvar[Tage[kk]]-ncovcol-nqv][i]*agexact;
                   3903:        }
                   3904:        /* printf("i=%d,mi=%d,d=%d,mw[mi][i]=%d\n",i, mi,d,mw[mi][i]); */
                   3905:        /* savm=pmij(pmmij,cov,ncovmodel,x,nlstate); */
                   3906:        out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   3907:                     1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   3908:        /* out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath, */
                   3909:        /*           1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate)); */
                   3910:        savm=oldm;
                   3911:        oldm=newm;
1.126     brouard  3912:       } /* end mult */
                   3913:       
                   3914:       s1=s[mw[mi][i]][i];
                   3915:       s2=s[mw[mi+1][i]][i];
1.217     brouard  3916:       /* if(s2==-1){ */
1.268     brouard  3917:       /*       printf(" ERROR s1=%d, s2=%d i=%d \n", s1, s2, i); */
1.217     brouard  3918:       /*       /\* exit(1); *\/ */
                   3919:       /* } */
1.126     brouard  3920:       bbh=(double)bh[mi][i]/(double)stepm; 
                   3921:       /* bias is positive if real duration
                   3922:        * is higher than the multiple of stepm and negative otherwise.
                   3923:        */
                   3924:       if( s2 > nlstate && (mle <5) ){  /* Jackson */
1.242     brouard  3925:        lli=log(out[s1][s2] - savm[s1][s2]);
1.216     brouard  3926:       } else if  ( s2==-1 ) { /* alive */
1.242     brouard  3927:        for (j=1,survp=0. ; j<=nlstate; j++) 
                   3928:          survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
                   3929:        lli= log(survp);
1.126     brouard  3930:       }else if (mle==1){
1.242     brouard  3931:        lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */
1.126     brouard  3932:       } else if(mle==2){
1.242     brouard  3933:        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  3934:       } else if(mle==3){  /* exponential inter-extrapolation */
1.242     brouard  3935:        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  3936:       } else if (mle==4){  /* mle=4 no inter-extrapolation */
1.242     brouard  3937:        lli=log(out[s1][s2]); /* Original formula */
1.136     brouard  3938:       } else{  /* mle=0 back to 1 */
1.242     brouard  3939:        lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */
                   3940:        /*lli=log(out[s1][s2]); */ /* Original formula */
1.126     brouard  3941:       } /* End of if */
                   3942:       ipmx +=1;
                   3943:       sw += weight[i];
                   3944:       ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
1.132     brouard  3945:       /*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  3946:       if(globpr){
1.246     brouard  3947:        fprintf(ficresilk,"%09ld %6.1f %6.1f %6d %2d %2d %2d %2d %3d %15.6f %8.4f %8.3f\
1.126     brouard  3948:  %11.6f %11.6f %11.6f ", \
1.242     brouard  3949:                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  3950:                2*weight[i]*lli,(s2==-1? -1: out[s1][s2]),(s2==-1? -1: savm[s1][s2]));
1.242     brouard  3951:        for(k=1,llt=0.,l=0.; k<=nlstate; k++){
                   3952:          llt +=ll[k]*gipmx/gsw;
                   3953:          fprintf(ficresilk," %10.6f",-ll[k]*gipmx/gsw);
                   3954:        }
                   3955:        fprintf(ficresilk," %10.6f\n", -llt);
1.126     brouard  3956:       }
1.232     brouard  3957:        } /* end of wave */
                   3958: } /* end of individual */
                   3959: for(k=1,l=0.; k<=nlstate; k++) l += ll[k];
                   3960: /* printf("l1=%f l2=%f ",ll[1],ll[2]); */
                   3961: l= l*ipmx/sw; /* To get the same order of magnitude as if weight=1 for every body */
                   3962: if(globpr==0){ /* First time we count the contributions and weights */
                   3963:        gipmx=ipmx;
                   3964:        gsw=sw;
                   3965: }
                   3966: return -l;
1.126     brouard  3967: }
                   3968: 
                   3969: 
                   3970: /*************** function likelione ***********/
1.292     brouard  3971: void likelione(FILE *ficres,double p[], int npar, int nlstate, int *globpri, long *ipmx, double *sw, double *fretone, double (*func)(double []))
1.126     brouard  3972: {
                   3973:   /* This routine should help understanding what is done with 
                   3974:      the selection of individuals/waves and
                   3975:      to check the exact contribution to the likelihood.
                   3976:      Plotting could be done.
                   3977:    */
                   3978:   int k;
                   3979: 
                   3980:   if(*globpri !=0){ /* Just counts and sums, no printings */
1.201     brouard  3981:     strcpy(fileresilk,"ILK_"); 
1.202     brouard  3982:     strcat(fileresilk,fileresu);
1.126     brouard  3983:     if((ficresilk=fopen(fileresilk,"w"))==NULL) {
                   3984:       printf("Problem with resultfile: %s\n", fileresilk);
                   3985:       fprintf(ficlog,"Problem with resultfile: %s\n", fileresilk);
                   3986:     }
1.214     brouard  3987:     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");
                   3988:     fprintf(ficresilk, "#num_i ageb agend i s1 s2 mi mw dh likeli weight %%weight 2wlli out sav ");
1.126     brouard  3989:     /*         i,s1,s2,mi,mw[mi][i],dh[mi][i],exp(lli),weight[i],2*weight[i]*lli,out[s1][s2],savm[s1][s2]); */
                   3990:     for(k=1; k<=nlstate; k++) 
                   3991:       fprintf(ficresilk," -2*gipw/gsw*weight*ll[%d]++",k);
                   3992:     fprintf(ficresilk," -2*gipw/gsw*weight*ll(total)\n");
                   3993:   }
                   3994: 
1.292     brouard  3995:   *fretone=(*func)(p);
1.126     brouard  3996:   if(*globpri !=0){
                   3997:     fclose(ficresilk);
1.205     brouard  3998:     if (mle ==0)
                   3999:       fprintf(fichtm,"\n<br>File of contributions to the likelihood computed with initial parameters and mle = %d.",mle);
                   4000:     else if(mle >=1)
                   4001:       fprintf(fichtm,"\n<br>File of contributions to the likelihood computed with optimized parameters mle = %d.",mle);
                   4002:     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  4003:     fprintf(fichtm,"\n<br>Equation of the model: <b>model=1+age+%s</b><br>\n",model); 
1.208     brouard  4004:       
                   4005:     for (k=1; k<= nlstate ; k++) {
1.211     brouard  4006:       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  4007: <img src=\"%s-p%dj.png\">",k,k,subdirf2(optionfilefiname,"ILK_"),k,subdirf2(optionfilefiname,"ILK_"),k,subdirf2(optionfilefiname,"ILK_"),k);
                   4008:     }
1.207     brouard  4009:     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  4010: <img src=\"%s-ori.png\">",subdirf2(optionfilefiname,"ILK_"),subdirf2(optionfilefiname,"ILK_"),subdirf2(optionfilefiname,"ILK_"));
1.207     brouard  4011:     fprintf(fichtm,"<br>- and by state of destination <a href=\"%s-dest.png\">%s-dest.png</a><br> \
1.204     brouard  4012: <img src=\"%s-dest.png\">",subdirf2(optionfilefiname,"ILK_"),subdirf2(optionfilefiname,"ILK_"),subdirf2(optionfilefiname,"ILK_"));
1.207     brouard  4013:     fflush(fichtm);
1.205     brouard  4014:   }
1.126     brouard  4015:   return;
                   4016: }
                   4017: 
                   4018: 
                   4019: /*********** Maximum Likelihood Estimation ***************/
                   4020: 
                   4021: void mlikeli(FILE *ficres,double p[], int npar, int ncovmodel, int nlstate, double ftol, double (*func)(double []))
                   4022: {
1.165     brouard  4023:   int i,j, iter=0;
1.126     brouard  4024:   double **xi;
                   4025:   double fret;
                   4026:   double fretone; /* Only one call to likelihood */
                   4027:   /*  char filerespow[FILENAMELENGTH];*/
1.162     brouard  4028: 
                   4029: #ifdef NLOPT
                   4030:   int creturn;
                   4031:   nlopt_opt opt;
                   4032:   /* double lb[9] = { -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL }; /\* lower bounds *\/ */
                   4033:   double *lb;
                   4034:   double minf; /* the minimum objective value, upon return */
                   4035:   double * p1; /* Shifted parameters from 0 instead of 1 */
                   4036:   myfunc_data dinst, *d = &dinst;
                   4037: #endif
                   4038: 
                   4039: 
1.126     brouard  4040:   xi=matrix(1,npar,1,npar);
                   4041:   for (i=1;i<=npar;i++)
                   4042:     for (j=1;j<=npar;j++)
                   4043:       xi[i][j]=(i==j ? 1.0 : 0.0);
                   4044:   printf("Powell\n");  fprintf(ficlog,"Powell\n");
1.201     brouard  4045:   strcpy(filerespow,"POW_"); 
1.126     brouard  4046:   strcat(filerespow,fileres);
                   4047:   if((ficrespow=fopen(filerespow,"w"))==NULL) {
                   4048:     printf("Problem with resultfile: %s\n", filerespow);
                   4049:     fprintf(ficlog,"Problem with resultfile: %s\n", filerespow);
                   4050:   }
                   4051:   fprintf(ficrespow,"# Powell\n# iter -2*LL");
                   4052:   for (i=1;i<=nlstate;i++)
                   4053:     for(j=1;j<=nlstate+ndeath;j++)
                   4054:       if(j!=i)fprintf(ficrespow," p%1d%1d",i,j);
                   4055:   fprintf(ficrespow,"\n");
1.162     brouard  4056: #ifdef POWELL
1.126     brouard  4057:   powell(p,xi,npar,ftol,&iter,&fret,func);
1.162     brouard  4058: #endif
1.126     brouard  4059: 
1.162     brouard  4060: #ifdef NLOPT
                   4061: #ifdef NEWUOA
                   4062:   opt = nlopt_create(NLOPT_LN_NEWUOA,npar);
                   4063: #else
                   4064:   opt = nlopt_create(NLOPT_LN_BOBYQA,npar);
                   4065: #endif
                   4066:   lb=vector(0,npar-1);
                   4067:   for (i=0;i<npar;i++) lb[i]= -HUGE_VAL;
                   4068:   nlopt_set_lower_bounds(opt, lb);
                   4069:   nlopt_set_initial_step1(opt, 0.1);
                   4070:   
                   4071:   p1= (p+1); /*  p *(p+1)@8 and p *(p1)@8 are equal p1[0]=p[1] */
                   4072:   d->function = func;
                   4073:   printf(" Func %.12lf \n",myfunc(npar,p1,NULL,d));
                   4074:   nlopt_set_min_objective(opt, myfunc, d);
                   4075:   nlopt_set_xtol_rel(opt, ftol);
                   4076:   if ((creturn=nlopt_optimize(opt, p1, &minf)) < 0) {
                   4077:     printf("nlopt failed! %d\n",creturn); 
                   4078:   }
                   4079:   else {
                   4080:     printf("found minimum after %d evaluations (NLOPT=%d)\n", countcallfunc ,NLOPT);
                   4081:     printf("found minimum at f(%g,%g) = %0.10g\n", p[0], p[1], minf);
                   4082:     iter=1; /* not equal */
                   4083:   }
                   4084:   nlopt_destroy(opt);
                   4085: #endif
1.126     brouard  4086:   free_matrix(xi,1,npar,1,npar);
                   4087:   fclose(ficrespow);
1.203     brouard  4088:   printf("\n#Number of iterations & function calls = %d & %d, -2 Log likelihood = %.12f\n",iter, countcallfunc,func(p));
                   4089:   fprintf(ficlog,"\n#Number of iterations & function calls = %d & %d, -2 Log likelihood = %.12f\n",iter, countcallfunc,func(p));
1.180     brouard  4090:   fprintf(ficres,"#Number of iterations & function calls = %d & %d, -2 Log likelihood = %.12f\n",iter, countcallfunc,func(p));
1.126     brouard  4091: 
                   4092: }
                   4093: 
                   4094: /**** Computes Hessian and covariance matrix ***/
1.203     brouard  4095: void hesscov(double **matcov, double **hess, double p[], int npar, double delti[], double ftolhess, double (*func)(double []))
1.126     brouard  4096: {
                   4097:   double  **a,**y,*x,pd;
1.203     brouard  4098:   /* double **hess; */
1.164     brouard  4099:   int i, j;
1.126     brouard  4100:   int *indx;
                   4101: 
                   4102:   double hessii(double p[], double delta, int theta, double delti[],double (*func)(double []),int npar);
1.203     brouard  4103:   double hessij(double p[], double **hess, double delti[], int i, int j,double (*func)(double []),int npar);
1.126     brouard  4104:   void lubksb(double **a, int npar, int *indx, double b[]) ;
                   4105:   void ludcmp(double **a, int npar, int *indx, double *d) ;
                   4106:   double gompertz(double p[]);
1.203     brouard  4107:   /* hess=matrix(1,npar,1,npar); */
1.126     brouard  4108: 
                   4109:   printf("\nCalculation of the hessian matrix. Wait...\n");
                   4110:   fprintf(ficlog,"\nCalculation of the hessian matrix. Wait...\n");
                   4111:   for (i=1;i<=npar;i++){
1.203     brouard  4112:     printf("%d-",i);fflush(stdout);
                   4113:     fprintf(ficlog,"%d-",i);fflush(ficlog);
1.126     brouard  4114:    
                   4115:      hess[i][i]=hessii(p,ftolhess,i,delti,func,npar);
                   4116:     
                   4117:     /*  printf(" %f ",p[i]);
                   4118:        printf(" %lf %lf %lf",hess[i][i],ftolhess,delti[i]);*/
                   4119:   }
                   4120:   
                   4121:   for (i=1;i<=npar;i++) {
                   4122:     for (j=1;j<=npar;j++)  {
                   4123:       if (j>i) { 
1.203     brouard  4124:        printf(".%d-%d",i,j);fflush(stdout);
                   4125:        fprintf(ficlog,".%d-%d",i,j);fflush(ficlog);
                   4126:        hess[i][j]=hessij(p,hess, delti,i,j,func,npar);
1.126     brouard  4127:        
                   4128:        hess[j][i]=hess[i][j];    
                   4129:        /*printf(" %lf ",hess[i][j]);*/
                   4130:       }
                   4131:     }
                   4132:   }
                   4133:   printf("\n");
                   4134:   fprintf(ficlog,"\n");
                   4135: 
                   4136:   printf("\nInverting the hessian to get the covariance matrix. Wait...\n");
                   4137:   fprintf(ficlog,"\nInverting the hessian to get the covariance matrix. Wait...\n");
                   4138:   
                   4139:   a=matrix(1,npar,1,npar);
                   4140:   y=matrix(1,npar,1,npar);
                   4141:   x=vector(1,npar);
                   4142:   indx=ivector(1,npar);
                   4143:   for (i=1;i<=npar;i++)
                   4144:     for (j=1;j<=npar;j++) a[i][j]=hess[i][j];
                   4145:   ludcmp(a,npar,indx,&pd);
                   4146: 
                   4147:   for (j=1;j<=npar;j++) {
                   4148:     for (i=1;i<=npar;i++) x[i]=0;
                   4149:     x[j]=1;
                   4150:     lubksb(a,npar,indx,x);
                   4151:     for (i=1;i<=npar;i++){ 
                   4152:       matcov[i][j]=x[i];
                   4153:     }
                   4154:   }
                   4155: 
                   4156:   printf("\n#Hessian matrix#\n");
                   4157:   fprintf(ficlog,"\n#Hessian matrix#\n");
                   4158:   for (i=1;i<=npar;i++) { 
                   4159:     for (j=1;j<=npar;j++) { 
1.203     brouard  4160:       printf("%.6e ",hess[i][j]);
                   4161:       fprintf(ficlog,"%.6e ",hess[i][j]);
1.126     brouard  4162:     }
                   4163:     printf("\n");
                   4164:     fprintf(ficlog,"\n");
                   4165:   }
                   4166: 
1.203     brouard  4167:   /* printf("\n#Covariance matrix#\n"); */
                   4168:   /* fprintf(ficlog,"\n#Covariance matrix#\n"); */
                   4169:   /* for (i=1;i<=npar;i++) {  */
                   4170:   /*   for (j=1;j<=npar;j++) {  */
                   4171:   /*     printf("%.6e ",matcov[i][j]); */
                   4172:   /*     fprintf(ficlog,"%.6e ",matcov[i][j]); */
                   4173:   /*   } */
                   4174:   /*   printf("\n"); */
                   4175:   /*   fprintf(ficlog,"\n"); */
                   4176:   /* } */
                   4177: 
1.126     brouard  4178:   /* Recompute Inverse */
1.203     brouard  4179:   /* for (i=1;i<=npar;i++) */
                   4180:   /*   for (j=1;j<=npar;j++) a[i][j]=matcov[i][j]; */
                   4181:   /* ludcmp(a,npar,indx,&pd); */
                   4182: 
                   4183:   /*  printf("\n#Hessian matrix recomputed#\n"); */
                   4184: 
                   4185:   /* for (j=1;j<=npar;j++) { */
                   4186:   /*   for (i=1;i<=npar;i++) x[i]=0; */
                   4187:   /*   x[j]=1; */
                   4188:   /*   lubksb(a,npar,indx,x); */
                   4189:   /*   for (i=1;i<=npar;i++){  */
                   4190:   /*     y[i][j]=x[i]; */
                   4191:   /*     printf("%.3e ",y[i][j]); */
                   4192:   /*     fprintf(ficlog,"%.3e ",y[i][j]); */
                   4193:   /*   } */
                   4194:   /*   printf("\n"); */
                   4195:   /*   fprintf(ficlog,"\n"); */
                   4196:   /* } */
                   4197: 
                   4198:   /* Verifying the inverse matrix */
                   4199: #ifdef DEBUGHESS
                   4200:   y=matprod2(y,hess,1,npar,1,npar,1,npar,matcov);
1.126     brouard  4201: 
1.203     brouard  4202:    printf("\n#Verification: multiplying the matrix of covariance by the Hessian matrix, should be unity:#\n");
                   4203:    fprintf(ficlog,"\n#Verification: multiplying the matrix of covariance by the Hessian matrix. Should be unity:#\n");
1.126     brouard  4204: 
                   4205:   for (j=1;j<=npar;j++) {
                   4206:     for (i=1;i<=npar;i++){ 
1.203     brouard  4207:       printf("%.2f ",y[i][j]);
                   4208:       fprintf(ficlog,"%.2f ",y[i][j]);
1.126     brouard  4209:     }
                   4210:     printf("\n");
                   4211:     fprintf(ficlog,"\n");
                   4212:   }
1.203     brouard  4213: #endif
1.126     brouard  4214: 
                   4215:   free_matrix(a,1,npar,1,npar);
                   4216:   free_matrix(y,1,npar,1,npar);
                   4217:   free_vector(x,1,npar);
                   4218:   free_ivector(indx,1,npar);
1.203     brouard  4219:   /* free_matrix(hess,1,npar,1,npar); */
1.126     brouard  4220: 
                   4221: 
                   4222: }
                   4223: 
                   4224: /*************** hessian matrix ****************/
                   4225: double hessii(double x[], double delta, int theta, double delti[], double (*func)(double []), int npar)
1.203     brouard  4226: { /* Around values of x, computes the function func and returns the scales delti and hessian */
1.126     brouard  4227:   int i;
                   4228:   int l=1, lmax=20;
1.203     brouard  4229:   double k1,k2, res, fx;
1.132     brouard  4230:   double p2[MAXPARM+1]; /* identical to x */
1.126     brouard  4231:   double delt=0.0001, delts, nkhi=10.,nkhif=1., khi=1.e-4;
                   4232:   int k=0,kmax=10;
                   4233:   double l1;
                   4234: 
                   4235:   fx=func(x);
                   4236:   for (i=1;i<=npar;i++) p2[i]=x[i];
1.145     brouard  4237:   for(l=0 ; l <=lmax; l++){  /* Enlarging the zone around the Maximum */
1.126     brouard  4238:     l1=pow(10,l);
                   4239:     delts=delt;
                   4240:     for(k=1 ; k <kmax; k=k+1){
                   4241:       delt = delta*(l1*k);
                   4242:       p2[theta]=x[theta] +delt;
1.145     brouard  4243:       k1=func(p2)-fx;   /* Might be negative if too close to the theoretical maximum */
1.126     brouard  4244:       p2[theta]=x[theta]-delt;
                   4245:       k2=func(p2)-fx;
                   4246:       /*res= (k1-2.0*fx+k2)/delt/delt; */
1.203     brouard  4247:       res= (k1+k2)/delt/delt/2.; /* Divided by 2 because L and not 2*L */
1.126     brouard  4248:       
1.203     brouard  4249: #ifdef DEBUGHESSII
1.126     brouard  4250:       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);
                   4251:       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);
                   4252: #endif
                   4253:       /*if(fabs(k1-2.0*fx+k2) <1.e-13){ */
                   4254:       if((k1 <khi/nkhi/2.) || (k2 <khi/nkhi/2.)){
                   4255:        k=kmax;
                   4256:       }
                   4257:       else if((k1 >khi/nkhif) || (k2 >khi/nkhif)){ /* Keeps lastvalue before 3.84/2 KHI2 5% 1d.f. */
1.164     brouard  4258:        k=kmax; l=lmax*10;
1.126     brouard  4259:       }
                   4260:       else if((k1 >khi/nkhi) || (k2 >khi/nkhi)){ 
                   4261:        delts=delt;
                   4262:       }
1.203     brouard  4263:     } /* End loop k */
1.126     brouard  4264:   }
                   4265:   delti[theta]=delts;
                   4266:   return res; 
                   4267:   
                   4268: }
                   4269: 
1.203     brouard  4270: double hessij( double x[], double **hess, double delti[], int thetai,int thetaj,double (*func)(double []),int npar)
1.126     brouard  4271: {
                   4272:   int i;
1.164     brouard  4273:   int l=1, lmax=20;
1.126     brouard  4274:   double k1,k2,k3,k4,res,fx;
1.132     brouard  4275:   double p2[MAXPARM+1];
1.203     brouard  4276:   int k, kmax=1;
                   4277:   double v1, v2, cv12, lc1, lc2;
1.208     brouard  4278: 
                   4279:   int firstime=0;
1.203     brouard  4280:   
1.126     brouard  4281:   fx=func(x);
1.203     brouard  4282:   for (k=1; k<=kmax; k=k+10) {
1.126     brouard  4283:     for (i=1;i<=npar;i++) p2[i]=x[i];
1.203     brouard  4284:     p2[thetai]=x[thetai]+delti[thetai]*k;
                   4285:     p2[thetaj]=x[thetaj]+delti[thetaj]*k;
1.126     brouard  4286:     k1=func(p2)-fx;
                   4287:   
1.203     brouard  4288:     p2[thetai]=x[thetai]+delti[thetai]*k;
                   4289:     p2[thetaj]=x[thetaj]-delti[thetaj]*k;
1.126     brouard  4290:     k2=func(p2)-fx;
                   4291:   
1.203     brouard  4292:     p2[thetai]=x[thetai]-delti[thetai]*k;
                   4293:     p2[thetaj]=x[thetaj]+delti[thetaj]*k;
1.126     brouard  4294:     k3=func(p2)-fx;
                   4295:   
1.203     brouard  4296:     p2[thetai]=x[thetai]-delti[thetai]*k;
                   4297:     p2[thetaj]=x[thetaj]-delti[thetaj]*k;
1.126     brouard  4298:     k4=func(p2)-fx;
1.203     brouard  4299:     res=(k1-k2-k3+k4)/4.0/delti[thetai]/k/delti[thetaj]/k/2.; /* Because of L not 2*L */
                   4300:     if(k1*k2*k3*k4 <0.){
1.208     brouard  4301:       firstime=1;
1.203     brouard  4302:       kmax=kmax+10;
1.208     brouard  4303:     }
                   4304:     if(kmax >=10 || firstime ==1){
1.246     brouard  4305:       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);
                   4306:       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  4307:       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);
                   4308:       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);
                   4309:     }
                   4310: #ifdef DEBUGHESSIJ
                   4311:     v1=hess[thetai][thetai];
                   4312:     v2=hess[thetaj][thetaj];
                   4313:     cv12=res;
                   4314:     /* Computing eigen value of Hessian matrix */
                   4315:     lc1=((v1+v2)+sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
                   4316:     lc2=((v1+v2)-sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
                   4317:     if ((lc2 <0) || (lc1 <0) ){
                   4318:       printf("Warning: sub Hessian matrix '%d%d' does not have positive eigen values \n",thetai,thetaj);
                   4319:       fprintf(ficlog, "Warning: sub Hessian matrix '%d%d' does not have positive eigen values \n",thetai,thetaj);
                   4320:       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);
                   4321:       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);
                   4322:     }
1.126     brouard  4323: #endif
                   4324:   }
                   4325:   return res;
                   4326: }
                   4327: 
1.203     brouard  4328:     /* Not done yet: Was supposed to fix if not exactly at the maximum */
                   4329: /* double hessij( double x[], double delti[], int thetai,int thetaj,double (*func)(double []),int npar) */
                   4330: /* { */
                   4331: /*   int i; */
                   4332: /*   int l=1, lmax=20; */
                   4333: /*   double k1,k2,k3,k4,res,fx; */
                   4334: /*   double p2[MAXPARM+1]; */
                   4335: /*   double delt=0.0001, delts, nkhi=10.,nkhif=1., khi=1.e-4; */
                   4336: /*   int k=0,kmax=10; */
                   4337: /*   double l1; */
                   4338:   
                   4339: /*   fx=func(x); */
                   4340: /*   for(l=0 ; l <=lmax; l++){  /\* Enlarging the zone around the Maximum *\/ */
                   4341: /*     l1=pow(10,l); */
                   4342: /*     delts=delt; */
                   4343: /*     for(k=1 ; k <kmax; k=k+1){ */
                   4344: /*       delt = delti*(l1*k); */
                   4345: /*       for (i=1;i<=npar;i++) p2[i]=x[i]; */
                   4346: /*       p2[thetai]=x[thetai]+delti[thetai]/k; */
                   4347: /*       p2[thetaj]=x[thetaj]+delti[thetaj]/k; */
                   4348: /*       k1=func(p2)-fx; */
                   4349:       
                   4350: /*       p2[thetai]=x[thetai]+delti[thetai]/k; */
                   4351: /*       p2[thetaj]=x[thetaj]-delti[thetaj]/k; */
                   4352: /*       k2=func(p2)-fx; */
                   4353:       
                   4354: /*       p2[thetai]=x[thetai]-delti[thetai]/k; */
                   4355: /*       p2[thetaj]=x[thetaj]+delti[thetaj]/k; */
                   4356: /*       k3=func(p2)-fx; */
                   4357:       
                   4358: /*       p2[thetai]=x[thetai]-delti[thetai]/k; */
                   4359: /*       p2[thetaj]=x[thetaj]-delti[thetaj]/k; */
                   4360: /*       k4=func(p2)-fx; */
                   4361: /*       res=(k1-k2-k3+k4)/4.0/delti[thetai]*k/delti[thetaj]*k/2.; /\* Because of L not 2*L *\/ */
                   4362: /* #ifdef DEBUGHESSIJ */
                   4363: /*       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); */
                   4364: /*       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); */
                   4365: /* #endif */
                   4366: /*       if((k1 <khi/nkhi/2.) || (k2 <khi/nkhi/2.)|| (k4 <khi/nkhi/2.)|| (k4 <khi/nkhi/2.)){ */
                   4367: /*     k=kmax; */
                   4368: /*       } */
                   4369: /*       else if((k1 >khi/nkhif) || (k2 >khi/nkhif) || (k4 >khi/nkhif) || (k4 >khi/nkhif)){ /\* Keeps lastvalue before 3.84/2 KHI2 5% 1d.f. *\/ */
                   4370: /*     k=kmax; l=lmax*10; */
                   4371: /*       } */
                   4372: /*       else if((k1 >khi/nkhi) || (k2 >khi/nkhi)){  */
                   4373: /*     delts=delt; */
                   4374: /*       } */
                   4375: /*     } /\* End loop k *\/ */
                   4376: /*   } */
                   4377: /*   delti[theta]=delts; */
                   4378: /*   return res;  */
                   4379: /* } */
                   4380: 
                   4381: 
1.126     brouard  4382: /************** Inverse of matrix **************/
                   4383: void ludcmp(double **a, int n, int *indx, double *d) 
                   4384: { 
                   4385:   int i,imax,j,k; 
                   4386:   double big,dum,sum,temp; 
                   4387:   double *vv; 
                   4388:  
                   4389:   vv=vector(1,n); 
                   4390:   *d=1.0; 
                   4391:   for (i=1;i<=n;i++) { 
                   4392:     big=0.0; 
                   4393:     for (j=1;j<=n;j++) 
                   4394:       if ((temp=fabs(a[i][j])) > big) big=temp; 
1.256     brouard  4395:     if (big == 0.0){
                   4396:       printf(" Singular Hessian matrix at row %d:\n",i);
                   4397:       for (j=1;j<=n;j++) {
                   4398:        printf(" a[%d][%d]=%f,",i,j,a[i][j]);
                   4399:        fprintf(ficlog," a[%d][%d]=%f,",i,j,a[i][j]);
                   4400:       }
                   4401:       fflush(ficlog);
                   4402:       fclose(ficlog);
                   4403:       nrerror("Singular matrix in routine ludcmp"); 
                   4404:     }
1.126     brouard  4405:     vv[i]=1.0/big; 
                   4406:   } 
                   4407:   for (j=1;j<=n;j++) { 
                   4408:     for (i=1;i<j;i++) { 
                   4409:       sum=a[i][j]; 
                   4410:       for (k=1;k<i;k++) sum -= a[i][k]*a[k][j]; 
                   4411:       a[i][j]=sum; 
                   4412:     } 
                   4413:     big=0.0; 
                   4414:     for (i=j;i<=n;i++) { 
                   4415:       sum=a[i][j]; 
                   4416:       for (k=1;k<j;k++) 
                   4417:        sum -= a[i][k]*a[k][j]; 
                   4418:       a[i][j]=sum; 
                   4419:       if ( (dum=vv[i]*fabs(sum)) >= big) { 
                   4420:        big=dum; 
                   4421:        imax=i; 
                   4422:       } 
                   4423:     } 
                   4424:     if (j != imax) { 
                   4425:       for (k=1;k<=n;k++) { 
                   4426:        dum=a[imax][k]; 
                   4427:        a[imax][k]=a[j][k]; 
                   4428:        a[j][k]=dum; 
                   4429:       } 
                   4430:       *d = -(*d); 
                   4431:       vv[imax]=vv[j]; 
                   4432:     } 
                   4433:     indx[j]=imax; 
                   4434:     if (a[j][j] == 0.0) a[j][j]=TINY; 
                   4435:     if (j != n) { 
                   4436:       dum=1.0/(a[j][j]); 
                   4437:       for (i=j+1;i<=n;i++) a[i][j] *= dum; 
                   4438:     } 
                   4439:   } 
                   4440:   free_vector(vv,1,n);  /* Doesn't work */
                   4441: ;
                   4442: } 
                   4443: 
                   4444: void lubksb(double **a, int n, int *indx, double b[]) 
                   4445: { 
                   4446:   int i,ii=0,ip,j; 
                   4447:   double sum; 
                   4448:  
                   4449:   for (i=1;i<=n;i++) { 
                   4450:     ip=indx[i]; 
                   4451:     sum=b[ip]; 
                   4452:     b[ip]=b[i]; 
                   4453:     if (ii) 
                   4454:       for (j=ii;j<=i-1;j++) sum -= a[i][j]*b[j]; 
                   4455:     else if (sum) ii=i; 
                   4456:     b[i]=sum; 
                   4457:   } 
                   4458:   for (i=n;i>=1;i--) { 
                   4459:     sum=b[i]; 
                   4460:     for (j=i+1;j<=n;j++) sum -= a[i][j]*b[j]; 
                   4461:     b[i]=sum/a[i][i]; 
                   4462:   } 
                   4463: } 
                   4464: 
                   4465: void pstamp(FILE *fichier)
                   4466: {
1.196     brouard  4467:   fprintf(fichier,"# %s.%s\n#IMaCh version %s, %s\n#%s\n# %s", optionfilefiname,optionfilext,version,copyright, fullversion, strstart);
1.126     brouard  4468: }
                   4469: 
1.297     brouard  4470: void date2dmy(double date,double *day, double *month, double *year){
                   4471:   double yp=0., yp1=0., yp2=0.;
                   4472:   
                   4473:   yp1=modf(date,&yp);/* extracts integral of date in yp  and
                   4474:                        fractional in yp1 */
                   4475:   *year=yp;
                   4476:   yp2=modf((yp1*12),&yp);
                   4477:   *month=yp;
                   4478:   yp1=modf((yp2*30.5),&yp);
                   4479:   *day=yp;
                   4480:   if(*day==0) *day=1;
                   4481:   if(*month==0) *month=1;
                   4482: }
                   4483: 
1.253     brouard  4484: 
                   4485: 
1.126     brouard  4486: /************ Frequencies ********************/
1.251     brouard  4487: void  freqsummary(char fileres[], double p[], double pstart[], int iagemin, int iagemax, int **s, double **agev, int nlstate, int imx, \
1.226     brouard  4488:                  int *Tvaraff, int *invalidvarcomb, int **nbcode, int *ncodemax,double **mint,double **anint, char strstart[], \
                   4489:                  int firstpass,  int lastpass, int stepm, int weightopt, char model[])
1.250     brouard  4490: {  /* Some frequencies as well as proposing some starting values */
1.226     brouard  4491:   
1.265     brouard  4492:   int i, m, jk, j1, bool, z1,j, nj, nl, k, iv, jj=0, s1=1, s2=1;
1.226     brouard  4493:   int iind=0, iage=0;
                   4494:   int mi; /* Effective wave */
                   4495:   int first;
                   4496:   double ***freq; /* Frequencies */
1.268     brouard  4497:   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 */
                   4498:   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  4499:   double *meanq, *stdq, *idq;
1.226     brouard  4500:   double **meanqt;
                   4501:   double *pp, **prop, *posprop, *pospropt;
                   4502:   double pos=0., posproptt=0., pospropta=0., k2, dateintsum=0,k2cpt=0;
                   4503:   char fileresp[FILENAMELENGTH], fileresphtm[FILENAMELENGTH], fileresphtmfr[FILENAMELENGTH];
                   4504:   double agebegin, ageend;
                   4505:     
                   4506:   pp=vector(1,nlstate);
1.251     brouard  4507:   prop=matrix(1,nlstate,iagemin-AGEMARGE,iagemax+4+AGEMARGE); 
1.226     brouard  4508:   posprop=vector(1,nlstate); /* Counting the number of transition starting from a live state per age */ 
                   4509:   pospropt=vector(1,nlstate); /* Counting the number of transition starting from a live state */ 
                   4510:   /* prop=matrix(1,nlstate,iagemin,iagemax+3); */
                   4511:   meanq=vector(1,nqfveff); /* Number of Quantitative Fixed Variables Effective */
1.284     brouard  4512:   stdq=vector(1,nqfveff); /* Number of Quantitative Fixed Variables Effective */
1.283     brouard  4513:   idq=vector(1,nqfveff); /* Number of Quantitative Fixed Variables Effective */
1.226     brouard  4514:   meanqt=matrix(1,lastpass,1,nqtveff);
                   4515:   strcpy(fileresp,"P_");
                   4516:   strcat(fileresp,fileresu);
                   4517:   /*strcat(fileresphtm,fileresu);*/
                   4518:   if((ficresp=fopen(fileresp,"w"))==NULL) {
                   4519:     printf("Problem with prevalence resultfile: %s\n", fileresp);
                   4520:     fprintf(ficlog,"Problem with prevalence resultfile: %s\n", fileresp);
                   4521:     exit(0);
                   4522:   }
1.240     brouard  4523:   
1.226     brouard  4524:   strcpy(fileresphtm,subdirfext(optionfilefiname,"PHTM_",".htm"));
                   4525:   if((ficresphtm=fopen(fileresphtm,"w"))==NULL) {
                   4526:     printf("Problem with prevalence HTM resultfile '%s' with errno='%s'\n",fileresphtm,strerror(errno));
                   4527:     fprintf(ficlog,"Problem with prevalence HTM resultfile '%s' with errno='%s'\n",fileresphtm,strerror(errno));
                   4528:     fflush(ficlog);
                   4529:     exit(70); 
                   4530:   }
                   4531:   else{
                   4532:     fprintf(ficresphtm,"<html><head>\n<title>IMaCh PHTM_ %s</title></head>\n <body><font size=\"2\">%s <br> %s</font> \
1.240     brouard  4533: <hr size=\"2\" color=\"#EC5E5E\"> \n                                   \
1.214     brouard  4534: Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=1+age+%s<br>\n",\
1.226     brouard  4535:            fileresphtm,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model);
                   4536:   }
1.237     brouard  4537:   fprintf(ficresphtm,"Current page is file <a href=\"%s\">%s</a><br>\n\n<h4>Frequencies and prevalence by age at begin of transition and dummy covariate value at beginning of transition</h4>\n",fileresphtm, fileresphtm);
1.240     brouard  4538:   
1.226     brouard  4539:   strcpy(fileresphtmfr,subdirfext(optionfilefiname,"PHTMFR_",".htm"));
                   4540:   if((ficresphtmfr=fopen(fileresphtmfr,"w"))==NULL) {
                   4541:     printf("Problem with frequency table HTM resultfile '%s' with errno='%s'\n",fileresphtmfr,strerror(errno));
                   4542:     fprintf(ficlog,"Problem with frequency table HTM resultfile '%s' with errno='%s'\n",fileresphtmfr,strerror(errno));
                   4543:     fflush(ficlog);
                   4544:     exit(70); 
1.240     brouard  4545:   } else{
1.226     brouard  4546:     fprintf(ficresphtmfr,"<html><head>\n<title>IMaCh PHTM_Frequency table %s</title></head>\n <body><font size=\"2\">%s <br> %s</font> \
1.240     brouard  4547: <hr size=\"2\" color=\"#EC5E5E\"> \n                                   \
1.214     brouard  4548: Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=1+age+%s<br>\n",\
1.226     brouard  4549:            fileresphtmfr,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model);
                   4550:   }
1.240     brouard  4551:   fprintf(ficresphtmfr,"Current page is file <a href=\"%s\">%s</a><br>\n\n<h4>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);
                   4552:   
1.253     brouard  4553:   y= vector(iagemin-AGEMARGE,iagemax+4+AGEMARGE);
                   4554:   x= vector(iagemin-AGEMARGE,iagemax+4+AGEMARGE);
1.251     brouard  4555:   freq= ma3x(-5,nlstate+ndeath,-5,nlstate+ndeath,iagemin-AGEMARGE,iagemax+4+AGEMARGE);
1.226     brouard  4556:   j1=0;
1.126     brouard  4557:   
1.227     brouard  4558:   /* j=ncoveff;  /\* Only fixed dummy covariates *\/ */
                   4559:   j=cptcoveff;  /* Only dummy covariates of the model */
1.226     brouard  4560:   if (cptcovn<1) {j=1;ncodemax[1]=1;}
1.240     brouard  4561:   
                   4562:   
1.226     brouard  4563:   /* Detects if a combination j1 is empty: for a multinomial variable like 3 education levels:
                   4564:      reference=low_education V1=0,V2=0
                   4565:      med_educ                V1=1 V2=0, 
                   4566:      high_educ               V1=0 V2=1
                   4567:      Then V1=1 and V2=1 is a noisy combination that we want to exclude for the list 2**cptcoveff 
                   4568:   */
1.249     brouard  4569:   dateintsum=0;
                   4570:   k2cpt=0;
                   4571: 
1.253     brouard  4572:   if(cptcoveff == 0 )
1.265     brouard  4573:     nl=1;  /* Constant and age model only */
1.253     brouard  4574:   else
                   4575:     nl=2;
1.265     brouard  4576: 
                   4577:   /* if a constant only model, one pass to compute frequency tables and to write it on ficresp */
                   4578:   /* Loop on nj=1 or 2 if dummy covariates j!=0
                   4579:    *   Loop on j1(1 to 2**cptcoveff) covariate combination
                   4580:    *     freq[s1][s2][iage] =0.
                   4581:    *     Loop on iind
                   4582:    *       ++freq[s1][s2][iage] weighted
                   4583:    *     end iind
                   4584:    *     if covariate and j!0
                   4585:    *       headers Variable on one line
                   4586:    *     endif cov j!=0
                   4587:    *     header of frequency table by age
                   4588:    *     Loop on age
                   4589:    *       pp[s1]+=freq[s1][s2][iage] weighted
                   4590:    *       pos+=freq[s1][s2][iage] weighted
                   4591:    *       Loop on s1 initial state
                   4592:    *         fprintf(ficresp
                   4593:    *       end s1
                   4594:    *     end age
                   4595:    *     if j!=0 computes starting values
                   4596:    *     end compute starting values
                   4597:    *   end j1
                   4598:    * end nl 
                   4599:    */
1.253     brouard  4600:   for (nj = 1; nj <= nl; nj++){   /* nj= 1 constant model, nl number of loops. */
                   4601:     if(nj==1)
                   4602:       j=0;  /* First pass for the constant */
1.265     brouard  4603:     else{
1.253     brouard  4604:       j=cptcoveff; /* Other passes for the covariate values */
1.265     brouard  4605:     }
1.251     brouard  4606:     first=1;
1.265     brouard  4607:     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  4608:       posproptt=0.;
                   4609:       /*printf("cptcoveff=%d Tvaraff=%d", cptcoveff,Tvaraff[1]);
                   4610:        scanf("%d", i);*/
                   4611:       for (i=-5; i<=nlstate+ndeath; i++)  
1.265     brouard  4612:        for (s2=-5; s2<=nlstate+ndeath; s2++)  
1.251     brouard  4613:          for(m=iagemin; m <= iagemax+3; m++)
1.265     brouard  4614:            freq[i][s2][m]=0;
1.251     brouard  4615:       
                   4616:       for (i=1; i<=nlstate; i++)  {
1.240     brouard  4617:        for(m=iagemin; m <= iagemax+3; m++)
1.251     brouard  4618:          prop[i][m]=0;
                   4619:        posprop[i]=0;
                   4620:        pospropt[i]=0;
                   4621:       }
1.283     brouard  4622:       for (z1=1; z1<= nqfveff; z1++) { /* zeroing for each combination j1 as well as for the total */
1.284     brouard  4623:         idq[z1]=0.;
                   4624:         meanq[z1]=0.;
                   4625:         stdq[z1]=0.;
1.283     brouard  4626:       }
                   4627:       /* for (z1=1; z1<= nqtveff; z1++) { */
1.251     brouard  4628:       /*   for(m=1;m<=lastpass;m++){ */
1.283     brouard  4629:       /*         meanqt[m][z1]=0.; */
                   4630:       /*       } */
                   4631:       /* }       */
1.251     brouard  4632:       /* dateintsum=0; */
                   4633:       /* k2cpt=0; */
                   4634:       
1.265     brouard  4635:       /* For that combination of covariates j1 (V4=1 V3=0 for example), we count and print the frequencies in one pass */
1.251     brouard  4636:       for (iind=1; iind<=imx; iind++) { /* For each individual iind */
                   4637:        bool=1;
                   4638:        if(j !=0){
                   4639:          if(anyvaryingduminmodel==0){ /* If All fixed covariates */
                   4640:            if (cptcoveff >0) { /* Filter is here: Must be looked at for model=V1+V2+V3+V4 */
                   4641:              for (z1=1; z1<=cptcoveff; z1++) { /* loops on covariates in the model */
                   4642:                /* if(Tvaraff[z1] ==-20){ */
                   4643:                /*       /\* sumnew+=cotvar[mw[mi][iind]][z1][iind]; *\/ */
                   4644:                /* }else  if(Tvaraff[z1] ==-10){ */
                   4645:                /*       /\* sumnew+=coqvar[z1][iind]; *\/ */
                   4646:                /* }else  */
                   4647:                if (covar[Tvaraff[z1]][iind]!= nbcode[Tvaraff[z1]][codtabm(j1,z1)]){ /* for combination j1 of covariates */
1.265     brouard  4648:                  /* Tests if the value of the covariate z1 for this individual iind responded to combination j1 (V4=1 V3=0) */
1.251     brouard  4649:                  bool=0; /* bool should be equal to 1 to be selected, one covariate value failed */
                   4650:                  /* 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", 
                   4651:                     bool,i,z1, z1, Tvaraff[z1],i,covar[Tvaraff[z1]][i],j1,z1,codtabm(j1,z1),
                   4652:                     j1,z1,nbcode[Tvaraff[z1]][codtabm(j1,z1)],j1);*/
                   4653:                  /* For j1=7 in V1+V2+V3+V4 = 0 1 1 0 and codtabm(7,3)=1 and nbcde[3][?]=1*/
                   4654:                } /* Onlyf fixed */
                   4655:              } /* end z1 */
                   4656:            } /* cptcovn > 0 */
                   4657:          } /* end any */
                   4658:        }/* end j==0 */
1.265     brouard  4659:        if (bool==1){ /* We selected an individual iind satisfying combination j1 (V4=1 V3=0) or all fixed covariates */
1.251     brouard  4660:          /* for(m=firstpass; m<=lastpass; m++){ */
1.284     brouard  4661:          for(mi=1; mi<wav[iind];mi++){ /* For each wave */
1.251     brouard  4662:            m=mw[mi][iind];
                   4663:            if(j!=0){
                   4664:              if(anyvaryingduminmodel==1){ /* Some are varying covariates */
                   4665:                for (z1=1; z1<=cptcoveff; z1++) {
                   4666:                  if( Fixed[Tmodelind[z1]]==1){
                   4667:                    iv= Tvar[Tmodelind[z1]]-ncovcol-nqv;
                   4668:                    if (cotvar[m][iv][iind]!= nbcode[Tvaraff[z1]][codtabm(j1,z1)]) /* iv=1 to ntv, right modality. If covariate's 
                   4669:                                                                                      value is -1, we don't select. It differs from the 
                   4670:                                                                                      constant and age model which counts them. */
                   4671:                      bool=0; /* not selected */
                   4672:                  }else if( Fixed[Tmodelind[z1]]== 0) { /* fixed */
                   4673:                    if (covar[Tvaraff[z1]][iind]!= nbcode[Tvaraff[z1]][codtabm(j1,z1)]) {
                   4674:                      bool=0;
                   4675:                    }
                   4676:                  }
                   4677:                }
                   4678:              }/* Some are varying covariates, we tried to speed up if all fixed covariates in the model, avoiding waves loop  */
                   4679:            } /* end j==0 */
                   4680:            /* bool =0 we keep that guy which corresponds to the combination of dummy values */
1.284     brouard  4681:            if(bool==1){ /*Selected */
1.251     brouard  4682:              /* dh[m][iind] or dh[mw[mi][iind]][iind] is the delay between two effective (mi) waves m=mw[mi][iind]
                   4683:                 and mw[mi+1][iind]. dh depends on stepm. */
                   4684:              agebegin=agev[m][iind]; /* Age at beginning of wave before transition*/
                   4685:              ageend=agev[m][iind]+(dh[m][iind])*stepm/YEARM; /* Age at end of wave and transition */
                   4686:              if(m >=firstpass && m <=lastpass){
                   4687:                k2=anint[m][iind]+(mint[m][iind]/12.);
                   4688:                /*if ((k2>=dateprev1) && (k2<=dateprev2)) {*/
                   4689:                if(agev[m][iind]==0) agev[m][iind]=iagemax+1;  /* All ages equal to 0 are in iagemax+1 */
                   4690:                if(agev[m][iind]==1) agev[m][iind]=iagemax+2;  /* All ages equal to 1 are in iagemax+2 */
                   4691:                if (s[m][iind]>0 && s[m][iind]<=nlstate)  /* If status at wave m is known and a live state */
                   4692:                  prop[s[m][iind]][(int)agev[m][iind]] += weight[iind];  /* At age of beginning of transition, where status is known */
                   4693:                if (m<lastpass) {
                   4694:                  /* if(s[m][iind]==4 && s[m+1][iind]==4) */
                   4695:                  /*   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]); */
                   4696:                  if(s[m][iind]==-1)
                   4697:                    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.));
                   4698:                  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.284     brouard  4699:                  for (z1=1; z1<= nqfveff; z1++) { /* Quantitative variables, calculating mean */
                   4700:                    idq[z1]=idq[z1]+weight[iind];
                   4701:                    meanq[z1]+=covar[ncovcol+z1][iind]*weight[iind];  /* Computes mean of quantitative with selected filter */
                   4702:                    stdq[z1]+=covar[ncovcol+z1][iind]*covar[ncovcol+z1][iind]*weight[iind]*weight[iind]; /* *weight[iind];*/  /* Computes mean of quantitative with selected filter */
                   4703:                  }
1.251     brouard  4704:                  /* if((int)agev[m][iind] == 55) */
                   4705:                  /*   printf("j=%d, j1=%d Age %d, iind=%d, num=%09ld m=%d\n",j,j1,(int)agev[m][iind],iind, num[iind],m); */
                   4706:                  /* freq[s[m][iind]][s[m+1][iind]][(int)((agebegin+ageend)/2.)] += weight[iind]; */
                   4707:                  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  4708:                }
1.251     brouard  4709:              } /* end if between passes */  
                   4710:              if ((agev[m][iind]>1) && (agev[m][iind]< (iagemax+3)) && (anint[m][iind]!=9999) && (mint[m][iind]!=99) && (j==0)) {
                   4711:                dateintsum=dateintsum+k2; /* on all covariates ?*/
                   4712:                k2cpt++;
                   4713:                /* printf("iind=%ld dateintmean = %lf dateintsum=%lf k2cpt=%lf k2=%lf\n",iind, dateintsum/k2cpt, dateintsum,k2cpt, k2); */
1.234     brouard  4714:              }
1.251     brouard  4715:            }else{
                   4716:              bool=1;
                   4717:            }/* end bool 2 */
                   4718:          } /* end m */
1.284     brouard  4719:          /* for (z1=1; z1<= nqfveff; z1++) { /\* Quantitative variables, calculating mean *\/ */
                   4720:          /*   idq[z1]=idq[z1]+weight[iind]; */
                   4721:          /*   meanq[z1]+=covar[ncovcol+z1][iind]*weight[iind];  /\* Computes mean of quantitative with selected filter *\/ */
                   4722:          /*   stdq[z1]+=covar[ncovcol+z1][iind]*covar[ncovcol+z1][iind]*weight[iind]*weight[iind]; /\* *weight[iind];*\/  /\* Computes mean of quantitative with selected filter *\/ */
                   4723:          /* } */
1.251     brouard  4724:        } /* end bool */
                   4725:       } /* end iind = 1 to imx */
                   4726:       /* prop[s][age] is feeded for any initial and valid live state as well as
                   4727:         freq[s1][s2][age] at single age of beginning the transition, for a combination j1 */
                   4728:       
                   4729:       
                   4730:       /*      fprintf(ficresp, "#Count between %.lf/%.lf/%.lf and %.lf/%.lf/%.lf\n",jprev1, mprev1,anprev1,jprev2, mprev2,anprev2);*/
1.265     brouard  4731:       if(cptcoveff==0 && nj==1) /* no covariate and first pass */
                   4732:         pstamp(ficresp);
1.251     brouard  4733:       if  (cptcoveff>0 && j!=0){
1.265     brouard  4734:         pstamp(ficresp);
1.251     brouard  4735:        printf( "\n#********** Variable "); 
                   4736:        fprintf(ficresp, "\n#********** Variable "); 
                   4737:        fprintf(ficresphtm, "\n<br/><br/><h3>********** Variable "); 
                   4738:        fprintf(ficresphtmfr, "\n<br/><br/><h3>********** Variable "); 
                   4739:        fprintf(ficlog, "\n#********** Variable "); 
                   4740:        for (z1=1; z1<=cptcoveff; z1++){
                   4741:          if(!FixedV[Tvaraff[z1]]){
                   4742:            printf( "V%d(fixed)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
                   4743:            fprintf(ficresp, "V%d(fixed)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
                   4744:            fprintf(ficresphtm, "V%d(fixed)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
                   4745:            fprintf(ficresphtmfr, "V%d(fixed)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
                   4746:            fprintf(ficlog, "V%d(fixed)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
1.250     brouard  4747:          }else{
1.251     brouard  4748:            printf( "V%d(varying)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
                   4749:            fprintf(ficresp, "V%d(varying)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
                   4750:            fprintf(ficresphtm, "V%d(varying)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
                   4751:            fprintf(ficresphtmfr, "V%d(varying)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
                   4752:            fprintf(ficlog, "V%d(varying)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
                   4753:          }
                   4754:        }
                   4755:        printf( "**********\n#");
                   4756:        fprintf(ficresp, "**********\n#");
                   4757:        fprintf(ficresphtm, "**********</h3>\n");
                   4758:        fprintf(ficresphtmfr, "**********</h3>\n");
                   4759:        fprintf(ficlog, "**********\n");
                   4760:       }
1.284     brouard  4761:       /*
                   4762:        Printing means of quantitative variables if any
                   4763:       */
                   4764:       for (z1=1; z1<= nqfveff; z1++) {
1.285     brouard  4765:        fprintf(ficlog,"Mean of fixed quantitative variable V%d on %.0f individuals sum=%f", ncovcol+z1, idq[z1], meanq[z1]);
1.284     brouard  4766:        fprintf(ficlog,", mean=%.3g\n",meanq[z1]/idq[z1]);
                   4767:        if(weightopt==1){
                   4768:          printf(" Weighted mean and standard deviation of");
                   4769:          fprintf(ficlog," Weighted mean and standard deviation of");
                   4770:          fprintf(ficresphtmfr," Weighted mean and standard deviation of");
                   4771:        }
1.285     brouard  4772:        printf(" fixed quantitative variable V%d on %.0f representatives of the population : %6.3g (%6.3g)\n", ncovcol+z1, idq[z1],meanq[z1]/idq[z1], sqrt((stdq[z1]-meanq[z1]*meanq[z1]/idq[z1])/idq[z1]));
                   4773:        fprintf(ficlog," fixed quantitative variable V%d on %.0f representatives of the population : %6.3g (%6.3g)\n", ncovcol+z1, idq[z1],meanq[z1]/idq[z1], sqrt((stdq[z1]-meanq[z1]*meanq[z1]/idq[z1])/idq[z1]));
                   4774:        fprintf(ficresphtmfr," fixed quantitative variable V%d on %.0f representatives of the population : %6.3g (%6.3g)<p>\n", ncovcol+z1, idq[z1],meanq[z1]/idq[z1], sqrt((stdq[z1]-meanq[z1]*meanq[z1]/idq[z1])/idq[z1]));
1.284     brouard  4775:       }
                   4776:       /* for (z1=1; z1<= nqtveff; z1++) { */
                   4777:       /*       for(m=1;m<=lastpass;m++){ */
                   4778:       /*         fprintf(ficresphtmfr,"V quantitative id %d, pass id=%d, mean=%f<p>\n", z1, m, meanqt[m][z1]); */
                   4779:       /*   } */
                   4780:       /* } */
1.283     brouard  4781: 
1.251     brouard  4782:       fprintf(ficresphtm,"<table style=\"text-align:center; border: 1px solid\">");
1.265     brouard  4783:       if((cptcoveff==0 && nj==1)|| nj==2 ) /* no covariate and first pass */
                   4784:         fprintf(ficresp, " Age");
                   4785:       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  4786:       for(i=1; i<=nlstate;i++) {
1.265     brouard  4787:        if((cptcoveff==0 && nj==1)|| nj==2 ) fprintf(ficresp," Prev(%d)  N(%d)  N  ",i,i);
1.251     brouard  4788:        fprintf(ficresphtm, "<th>Age</th><th>Prev(%d)</th><th>N(%d)</th><th>N</th>",i,i);
                   4789:       }
1.265     brouard  4790:       if((cptcoveff==0 && nj==1)|| nj==2 ) fprintf(ficresp, "\n");
1.251     brouard  4791:       fprintf(ficresphtm, "\n");
                   4792:       
                   4793:       /* Header of frequency table by age */
                   4794:       fprintf(ficresphtmfr,"<table style=\"text-align:center; border: 1px solid\">");
                   4795:       fprintf(ficresphtmfr,"<th>Age</th> ");
1.265     brouard  4796:       for(s2=-1; s2 <=nlstate+ndeath; s2++){
1.251     brouard  4797:        for(m=-1; m <=nlstate+ndeath; m++){
1.265     brouard  4798:          if(s2!=0 && m!=0)
                   4799:            fprintf(ficresphtmfr,"<th>%d%d</th> ",s2,m);
1.240     brouard  4800:        }
1.226     brouard  4801:       }
1.251     brouard  4802:       fprintf(ficresphtmfr, "\n");
                   4803:     
                   4804:       /* For each age */
                   4805:       for(iage=iagemin; iage <= iagemax+3; iage++){
                   4806:        fprintf(ficresphtm,"<tr>");
                   4807:        if(iage==iagemax+1){
                   4808:          fprintf(ficlog,"1");
                   4809:          fprintf(ficresphtmfr,"<tr><th>0</th> ");
                   4810:        }else if(iage==iagemax+2){
                   4811:          fprintf(ficlog,"0");
                   4812:          fprintf(ficresphtmfr,"<tr><th>Unknown</th> ");
                   4813:        }else if(iage==iagemax+3){
                   4814:          fprintf(ficlog,"Total");
                   4815:          fprintf(ficresphtmfr,"<tr><th>Total</th> ");
                   4816:        }else{
1.240     brouard  4817:          if(first==1){
1.251     brouard  4818:            first=0;
                   4819:            printf("See log file for details...\n");
                   4820:          }
                   4821:          fprintf(ficresphtmfr,"<tr><th>%d</th> ",iage);
                   4822:          fprintf(ficlog,"Age %d", iage);
                   4823:        }
1.265     brouard  4824:        for(s1=1; s1 <=nlstate ; s1++){
                   4825:          for(m=-1, pp[s1]=0; m <=nlstate+ndeath ; m++)
                   4826:            pp[s1] += freq[s1][m][iage]; 
1.251     brouard  4827:        }
1.265     brouard  4828:        for(s1=1; s1 <=nlstate ; s1++){
1.251     brouard  4829:          for(m=-1, pos=0; m <=0 ; m++)
1.265     brouard  4830:            pos += freq[s1][m][iage];
                   4831:          if(pp[s1]>=1.e-10){
1.251     brouard  4832:            if(first==1){
1.265     brouard  4833:              printf(" %d.=%.0f loss[%d]=%.1f%%",s1,pp[s1],s1,100*pos/pp[s1]);
1.251     brouard  4834:            }
1.265     brouard  4835:            fprintf(ficlog," %d.=%.0f loss[%d]=%.1f%%",s1,pp[s1],s1,100*pos/pp[s1]);
1.251     brouard  4836:          }else{
                   4837:            if(first==1)
1.265     brouard  4838:              printf(" %d.=%.0f loss[%d]=NaNQ%%",s1,pp[s1],s1);
                   4839:            fprintf(ficlog," %d.=%.0f loss[%d]=NaNQ%%",s1,pp[s1],s1);
1.240     brouard  4840:          }
                   4841:        }
                   4842:       
1.265     brouard  4843:        for(s1=1; s1 <=nlstate ; s1++){ 
                   4844:          /* posprop[s1]=0; */
                   4845:          for(m=0, pp[s1]=0; m <=nlstate+ndeath; m++)/* Summing on all ages */
                   4846:            pp[s1] += freq[s1][m][iage];
                   4847:        }       /* pp[s1] is the total number of transitions starting from state s1 and any ending status until this age */
                   4848:       
                   4849:        for(s1=1,pos=0, pospropta=0.; s1 <=nlstate ; s1++){
                   4850:          pos += pp[s1]; /* pos is the total number of transitions until this age */
                   4851:          posprop[s1] += prop[s1][iage]; /* prop is the number of transitions from a live state
                   4852:                                            from s1 at age iage prop[s[m][iind]][(int)agev[m][iind]] += weight[iind] */
                   4853:          pospropta += prop[s1][iage]; /* prop is the number of transitions from a live state
                   4854:                                          from s1 at age iage prop[s[m][iind]][(int)agev[m][iind]] += weight[iind] */
                   4855:        }
                   4856:        
                   4857:        /* Writing ficresp */
                   4858:        if(cptcoveff==0 && nj==1){ /* no covariate and first pass */
                   4859:           if( iage <= iagemax){
                   4860:            fprintf(ficresp," %d",iage);
                   4861:           }
                   4862:         }else if( nj==2){
                   4863:           if( iage <= iagemax){
                   4864:            fprintf(ficresp," %d",iage);
                   4865:             for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresp, " %d %d",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
                   4866:           }
1.240     brouard  4867:        }
1.265     brouard  4868:        for(s1=1; s1 <=nlstate ; s1++){
1.240     brouard  4869:          if(pos>=1.e-5){
1.251     brouard  4870:            if(first==1)
1.265     brouard  4871:              printf(" %d.=%.0f prev[%d]=%.1f%%",s1,pp[s1],s1,100*pp[s1]/pos);
                   4872:            fprintf(ficlog," %d.=%.0f prev[%d]=%.1f%%",s1,pp[s1],s1,100*pp[s1]/pos);
1.251     brouard  4873:          }else{
                   4874:            if(first==1)
1.265     brouard  4875:              printf(" %d.=%.0f prev[%d]=NaNQ%%",s1,pp[s1],s1);
                   4876:            fprintf(ficlog," %d.=%.0f prev[%d]=NaNQ%%",s1,pp[s1],s1);
1.251     brouard  4877:          }
                   4878:          if( iage <= iagemax){
                   4879:            if(pos>=1.e-5){
1.265     brouard  4880:              if(cptcoveff==0 && nj==1){ /* no covariate and first pass */
                   4881:                fprintf(ficresp," %.5f %.0f %.0f",prop[s1][iage]/pospropta, prop[s1][iage],pospropta);
                   4882:               }else if( nj==2){
                   4883:                fprintf(ficresp," %.5f %.0f %.0f",prop[s1][iage]/pospropta, prop[s1][iage],pospropta);
                   4884:               }
                   4885:              fprintf(ficresphtm,"<th>%d</th><td>%.5f</td><td>%.0f</td><td>%.0f</td>",iage,prop[s1][iage]/pospropta, prop[s1][iage],pospropta);
                   4886:              /*probs[iage][s1][j1]= pp[s1]/pos;*/
                   4887:              /*printf("\niage=%d s1=%d j1=%d %.5f %.0f %.0f %f",iage,s1,j1,pp[s1]/pos, pp[s1],pos,probs[iage][s1][j1]);*/
                   4888:            } else{
                   4889:              if((cptcoveff==0 && nj==1)|| nj==2 ) fprintf(ficresp," NaNq %.0f %.0f",prop[s1][iage],pospropta);
                   4890:              fprintf(ficresphtm,"<th>%d</th><td>NaNq</td><td>%.0f</td><td>%.0f</td>",iage, prop[s1][iage],pospropta);
1.251     brouard  4891:            }
1.240     brouard  4892:          }
1.265     brouard  4893:          pospropt[s1] +=posprop[s1];
                   4894:        } /* end loop s1 */
1.251     brouard  4895:        /* pospropt=0.; */
1.265     brouard  4896:        for(s1=-1; s1 <=nlstate+ndeath; s1++){
1.251     brouard  4897:          for(m=-1; m <=nlstate+ndeath; m++){
1.265     brouard  4898:            if(freq[s1][m][iage] !=0 ) { /* minimizing output */
1.251     brouard  4899:              if(first==1){
1.265     brouard  4900:                printf(" %d%d=%.0f",s1,m,freq[s1][m][iage]);
1.251     brouard  4901:              }
1.265     brouard  4902:              /* printf(" %d%d=%.0f",s1,m,freq[s1][m][iage]); */
                   4903:              fprintf(ficlog," %d%d=%.0f",s1,m,freq[s1][m][iage]);
1.251     brouard  4904:            }
1.265     brouard  4905:            if(s1!=0 && m!=0)
                   4906:              fprintf(ficresphtmfr,"<td>%.0f</td> ",freq[s1][m][iage]);
1.240     brouard  4907:          }
1.265     brouard  4908:        } /* end loop s1 */
1.251     brouard  4909:        posproptt=0.; 
1.265     brouard  4910:        for(s1=1; s1 <=nlstate; s1++){
                   4911:          posproptt += pospropt[s1];
1.251     brouard  4912:        }
                   4913:        fprintf(ficresphtmfr,"</tr>\n ");
1.265     brouard  4914:        fprintf(ficresphtm,"</tr>\n");
                   4915:        if((cptcoveff==0 && nj==1)|| nj==2 ) {
                   4916:          if(iage <= iagemax)
                   4917:            fprintf(ficresp,"\n");
1.240     brouard  4918:        }
1.251     brouard  4919:        if(first==1)
                   4920:          printf("Others in log...\n");
                   4921:        fprintf(ficlog,"\n");
                   4922:       } /* end loop age iage */
1.265     brouard  4923:       
1.251     brouard  4924:       fprintf(ficresphtm,"<tr><th>Tot</th>");
1.265     brouard  4925:       for(s1=1; s1 <=nlstate ; s1++){
1.251     brouard  4926:        if(posproptt < 1.e-5){
1.265     brouard  4927:          fprintf(ficresphtm,"<td>Nanq</td><td>%.0f</td><td>%.0f</td>",pospropt[s1],posproptt); 
1.251     brouard  4928:        }else{
1.265     brouard  4929:          fprintf(ficresphtm,"<td>%.5f</td><td>%.0f</td><td>%.0f</td>",pospropt[s1]/posproptt,pospropt[s1],posproptt);  
1.240     brouard  4930:        }
1.226     brouard  4931:       }
1.251     brouard  4932:       fprintf(ficresphtm,"</tr>\n");
                   4933:       fprintf(ficresphtm,"</table>\n");
                   4934:       fprintf(ficresphtmfr,"</table>\n");
1.226     brouard  4935:       if(posproptt < 1.e-5){
1.251     brouard  4936:        fprintf(ficresphtm,"\n <p><b> This combination (%d) is not valid and no result will be produced</b></p>",j1);
                   4937:        fprintf(ficresphtmfr,"\n <p><b> This combination (%d) is not valid and no result will be produced</b></p>",j1);
1.260     brouard  4938:        fprintf(ficlog,"#  This combination (%d) is not valid and no result will be produced\n",j1);
                   4939:        printf("#  This combination (%d) is not valid and no result will be produced\n",j1);
1.251     brouard  4940:        invalidvarcomb[j1]=1;
1.226     brouard  4941:       }else{
1.251     brouard  4942:        fprintf(ficresphtm,"\n <p> This combination (%d) is valid and result will be produced.</p>",j1);
                   4943:        invalidvarcomb[j1]=0;
1.226     brouard  4944:       }
1.251     brouard  4945:       fprintf(ficresphtmfr,"</table>\n");
                   4946:       fprintf(ficlog,"\n");
                   4947:       if(j!=0){
                   4948:        printf("#Freqsummary: Starting values for combination j1=%d:\n", j1);
1.265     brouard  4949:        for(i=1,s1=1; i <=nlstate; i++){
1.251     brouard  4950:          for(k=1; k <=(nlstate+ndeath); k++){
                   4951:            if (k != i) {
1.265     brouard  4952:              for(jj=1; jj <=ncovmodel; jj++){ /* For counting s1 */
1.253     brouard  4953:                if(jj==1){  /* Constant case (in fact cste + age) */
1.251     brouard  4954:                  if(j1==1){ /* All dummy covariates to zero */
                   4955:                    freq[i][k][iagemax+4]=freq[i][k][iagemax+3]; /* Stores case 0 0 0 */
                   4956:                    freq[i][i][iagemax+4]=freq[i][i][iagemax+3]; /* Stores case 0 0 0 */
1.252     brouard  4957:                    printf("%d%d ",i,k);
                   4958:                    fprintf(ficlog,"%d%d ",i,k);
1.265     brouard  4959:                    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]));
                   4960:                    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]));
                   4961:                    pstart[s1]= log(freq[i][k][iagemax+3]/freq[i][i][iagemax+3]);
1.251     brouard  4962:                  }
1.253     brouard  4963:                }else if((j1==1) && (jj==2 || nagesqr==1)){ /* age or age*age parameter without covariate V4*age (to be done later) */
                   4964:                  for(iage=iagemin; iage <= iagemax+3; iage++){
                   4965:                    x[iage]= (double)iage;
                   4966:                    y[iage]= log(freq[i][k][iage]/freq[i][i][iage]);
1.265     brouard  4967:                    /* 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  4968:                  }
1.268     brouard  4969:                  /* Some are not finite, but linreg will ignore these ages */
                   4970:                  no=0;
1.253     brouard  4971:                  linreg(iagemin,iagemax,&no,x,y,&a,&b,&r, &sa, &sb ); /* y= a+b*x with standard errors */
1.265     brouard  4972:                  pstart[s1]=b;
                   4973:                  pstart[s1-1]=a;
1.252     brouard  4974:                }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 */ 
                   4975:                  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]);
                   4976:                  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  4977:                  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  4978:                  printf("%d%d ",i,k);
                   4979:                  fprintf(ficlog,"%d%d ",i,k);
1.265     brouard  4980:                  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  4981:                }else{ /* Other cases, like quantitative fixed or varying covariates */
                   4982:                  ;
                   4983:                }
                   4984:                /* printf("%12.7f )", param[i][jj][k]); */
                   4985:                /* fprintf(ficlog,"%12.7f )", param[i][jj][k]); */
1.265     brouard  4986:                s1++; 
1.251     brouard  4987:              } /* end jj */
                   4988:            } /* end k!= i */
                   4989:          } /* end k */
1.265     brouard  4990:        } /* end i, s1 */
1.251     brouard  4991:       } /* end j !=0 */
                   4992:     } /* end selected combination of covariate j1 */
                   4993:     if(j==0){ /* We can estimate starting values from the occurences in each case */
                   4994:       printf("#Freqsummary: Starting values for the constants:\n");
                   4995:       fprintf(ficlog,"\n");
1.265     brouard  4996:       for(i=1,s1=1; i <=nlstate; i++){
1.251     brouard  4997:        for(k=1; k <=(nlstate+ndeath); k++){
                   4998:          if (k != i) {
                   4999:            printf("%d%d ",i,k);
                   5000:            fprintf(ficlog,"%d%d ",i,k);
                   5001:            for(jj=1; jj <=ncovmodel; jj++){
1.265     brouard  5002:              pstart[s1]=p[s1]; /* Setting pstart to p values by default */
1.253     brouard  5003:              if(jj==1){ /* Age has to be done */
1.265     brouard  5004:                pstart[s1]= log(freq[i][k][iagemax+3]/freq[i][i][iagemax+3]);
                   5005:                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]));
                   5006:                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  5007:              }
                   5008:              /* printf("%12.7f )", param[i][jj][k]); */
                   5009:              /* fprintf(ficlog,"%12.7f )", param[i][jj][k]); */
1.265     brouard  5010:              s1++; 
1.250     brouard  5011:            }
1.251     brouard  5012:            printf("\n");
                   5013:            fprintf(ficlog,"\n");
1.250     brouard  5014:          }
                   5015:        }
1.284     brouard  5016:       } /* end of state i */
1.251     brouard  5017:       printf("#Freqsummary\n");
                   5018:       fprintf(ficlog,"\n");
1.265     brouard  5019:       for(s1=-1; s1 <=nlstate+ndeath; s1++){
                   5020:        for(s2=-1; s2 <=nlstate+ndeath; s2++){
                   5021:          /* param[i]|j][k]= freq[s1][s2][iagemax+3] */
                   5022:          printf(" %d%d=%.0f",s1,s2,freq[s1][s2][iagemax+3]);
                   5023:          fprintf(ficlog," %d%d=%.0f",s1,s2,freq[s1][s2][iagemax+3]);
                   5024:          /* if(freq[s1][s2][iage] !=0 ) { /\* minimizing output *\/ */
                   5025:          /*   printf(" %d%d=%.0f",s1,s2,freq[s1][s2][iagemax+3]); */
                   5026:          /*   fprintf(ficlog," %d%d=%.0f",s1,s2,freq[s1][s2][iagemax+3]); */
1.251     brouard  5027:          /* } */
                   5028:        }
1.265     brouard  5029:       } /* end loop s1 */
1.251     brouard  5030:       
                   5031:       printf("\n");
                   5032:       fprintf(ficlog,"\n");
                   5033:     } /* end j=0 */
1.249     brouard  5034:   } /* end j */
1.252     brouard  5035: 
1.253     brouard  5036:   if(mle == -2){  /* We want to use these values as starting values */
1.252     brouard  5037:     for(i=1, jk=1; i <=nlstate; i++){
                   5038:       for(j=1; j <=nlstate+ndeath; j++){
                   5039:        if(j!=i){
                   5040:          /*ca[0]= k+'a'-1;ca[1]='\0';*/
                   5041:          printf("%1d%1d",i,j);
                   5042:          fprintf(ficparo,"%1d%1d",i,j);
                   5043:          for(k=1; k<=ncovmodel;k++){
                   5044:            /*    printf(" %lf",param[i][j][k]); */
                   5045:            /*    fprintf(ficparo," %lf",param[i][j][k]); */
                   5046:            p[jk]=pstart[jk];
                   5047:            printf(" %f ",pstart[jk]);
                   5048:            fprintf(ficparo," %f ",pstart[jk]);
                   5049:            jk++;
                   5050:          }
                   5051:          printf("\n");
                   5052:          fprintf(ficparo,"\n");
                   5053:        }
                   5054:       }
                   5055:     }
                   5056:   } /* end mle=-2 */
1.226     brouard  5057:   dateintmean=dateintsum/k2cpt; 
1.296     brouard  5058:   date2dmy(dateintmean,&jintmean,&mintmean,&aintmean);
1.240     brouard  5059:   
1.226     brouard  5060:   fclose(ficresp);
                   5061:   fclose(ficresphtm);
                   5062:   fclose(ficresphtmfr);
1.283     brouard  5063:   free_vector(idq,1,nqfveff);
1.226     brouard  5064:   free_vector(meanq,1,nqfveff);
1.284     brouard  5065:   free_vector(stdq,1,nqfveff);
1.226     brouard  5066:   free_matrix(meanqt,1,lastpass,1,nqtveff);
1.253     brouard  5067:   free_vector(x, iagemin-AGEMARGE, iagemax+4+AGEMARGE);
                   5068:   free_vector(y, iagemin-AGEMARGE, iagemax+4+AGEMARGE);
1.251     brouard  5069:   free_ma3x(freq,-5,nlstate+ndeath,-5,nlstate+ndeath, iagemin-AGEMARGE, iagemax+4+AGEMARGE);
1.226     brouard  5070:   free_vector(pospropt,1,nlstate);
                   5071:   free_vector(posprop,1,nlstate);
1.251     brouard  5072:   free_matrix(prop,1,nlstate,iagemin-AGEMARGE, iagemax+4+AGEMARGE);
1.226     brouard  5073:   free_vector(pp,1,nlstate);
                   5074:   /* End of freqsummary */
                   5075: }
1.126     brouard  5076: 
1.268     brouard  5077: /* Simple linear regression */
                   5078: int linreg(int ifi, int ila, int *no, const double x[], const double y[], double* a, double* b, double* r, double* sa, double * sb) {
                   5079: 
                   5080:   /* y=a+bx regression */
                   5081:   double   sumx = 0.0;                        /* sum of x                      */
                   5082:   double   sumx2 = 0.0;                       /* sum of x**2                   */
                   5083:   double   sumxy = 0.0;                       /* sum of x * y                  */
                   5084:   double   sumy = 0.0;                        /* sum of y                      */
                   5085:   double   sumy2 = 0.0;                       /* sum of y**2                   */
                   5086:   double   sume2 = 0.0;                       /* sum of square or residuals */
                   5087:   double yhat;
                   5088:   
                   5089:   double denom=0;
                   5090:   int i;
                   5091:   int ne=*no;
                   5092:   
                   5093:   for ( i=ifi, ne=0;i<=ila;i++) {
                   5094:     if(!isfinite(x[i]) || !isfinite(y[i])){
                   5095:       /* printf(" x[%d]=%f, y[%d]=%f\n",i,x[i],i,y[i]); */
                   5096:       continue;
                   5097:     }
                   5098:     ne=ne+1;
                   5099:     sumx  += x[i];       
                   5100:     sumx2 += x[i]*x[i];  
                   5101:     sumxy += x[i] * y[i];
                   5102:     sumy  += y[i];      
                   5103:     sumy2 += y[i]*y[i]; 
                   5104:     denom = (ne * sumx2 - sumx*sumx);
                   5105:     /* 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); */
                   5106:   } 
                   5107:   
                   5108:   denom = (ne * sumx2 - sumx*sumx);
                   5109:   if (denom == 0) {
                   5110:     // vertical, slope m is infinity
                   5111:     *b = INFINITY;
                   5112:     *a = 0;
                   5113:     if (r) *r = 0;
                   5114:     return 1;
                   5115:   }
                   5116:   
                   5117:   *b = (ne * sumxy  -  sumx * sumy) / denom;
                   5118:   *a = (sumy * sumx2  -  sumx * sumxy) / denom;
                   5119:   if (r!=NULL) {
                   5120:     *r = (sumxy - sumx * sumy / ne) /          /* compute correlation coeff     */
                   5121:       sqrt((sumx2 - sumx*sumx/ne) *
                   5122:           (sumy2 - sumy*sumy/ne));
                   5123:   }
                   5124:   *no=ne;
                   5125:   for ( i=ifi, ne=0;i<=ila;i++) {
                   5126:     if(!isfinite(x[i]) || !isfinite(y[i])){
                   5127:       /* printf(" x[%d]=%f, y[%d]=%f\n",i,x[i],i,y[i]); */
                   5128:       continue;
                   5129:     }
                   5130:     ne=ne+1;
                   5131:     yhat = y[i] - *a -*b* x[i];
                   5132:     sume2  += yhat * yhat ;       
                   5133:     
                   5134:     denom = (ne * sumx2 - sumx*sumx);
                   5135:     /* 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); */
                   5136:   } 
                   5137:   *sb = sqrt(sume2/(double)(ne-2)/(sumx2 - sumx * sumx /(double)ne));
                   5138:   *sa= *sb * sqrt(sumx2/ne);
                   5139:   
                   5140:   return 0; 
                   5141: }
                   5142: 
1.126     brouard  5143: /************ Prevalence ********************/
1.227     brouard  5144: 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)
                   5145: {  
                   5146:   /* Compute observed prevalence between dateprev1 and dateprev2 by counting the number of people
                   5147:      in each health status at the date of interview (if between dateprev1 and dateprev2).
                   5148:      We still use firstpass and lastpass as another selection.
                   5149:   */
1.126     brouard  5150:  
1.227     brouard  5151:   int i, m, jk, j1, bool, z1,j, iv;
                   5152:   int mi; /* Effective wave */
                   5153:   int iage;
                   5154:   double agebegin, ageend;
                   5155: 
                   5156:   double **prop;
                   5157:   double posprop; 
                   5158:   double  y2; /* in fractional years */
                   5159:   int iagemin, iagemax;
                   5160:   int first; /** to stop verbosity which is redirected to log file */
                   5161: 
                   5162:   iagemin= (int) agemin;
                   5163:   iagemax= (int) agemax;
                   5164:   /*pp=vector(1,nlstate);*/
1.251     brouard  5165:   prop=matrix(1,nlstate,iagemin-AGEMARGE,iagemax+4+AGEMARGE); 
1.227     brouard  5166:   /*  freq=ma3x(-1,nlstate+ndeath,-1,nlstate+ndeath,iagemin,iagemax+3);*/
                   5167:   j1=0;
1.222     brouard  5168:   
1.227     brouard  5169:   /*j=cptcoveff;*/
                   5170:   if (cptcovn<1) {j=1;ncodemax[1]=1;}
1.222     brouard  5171:   
1.288     brouard  5172:   first=0;
1.227     brouard  5173:   for(j1=1; j1<= (int) pow(2,cptcoveff);j1++){ /* For each combination of covariate */
                   5174:     for (i=1; i<=nlstate; i++)  
1.251     brouard  5175:       for(iage=iagemin-AGEMARGE; iage <= iagemax+4+AGEMARGE; iage++)
1.227     brouard  5176:        prop[i][iage]=0.0;
                   5177:     printf("Prevalence combination of varying and fixed dummies %d\n",j1);
                   5178:     /* fprintf(ficlog," V%d=%d ",Tvaraff[j1],nbcode[Tvaraff[j1]][codtabm(k,j1)]); */
                   5179:     fprintf(ficlog,"Prevalence combination of varying and fixed dummies %d\n",j1);
                   5180:     
                   5181:     for (i=1; i<=imx; i++) { /* Each individual */
                   5182:       bool=1;
                   5183:       /* for(m=firstpass; m<=lastpass; m++){/\* Other selection (we can limit to certain interviews*\/ */
                   5184:       for(mi=1; mi<wav[i];mi++){ /* For this wave too look where individual can be counted V4=0 V3=0 */
                   5185:        m=mw[mi][i];
                   5186:        /* Tmodelind[z1]=k is the position of the varying covariate in the model, but which # within 1 to ntv? */
                   5187:        /* Tvar[Tmodelind[z1]] is the n of Vn; n-ncovcol-nqv is the first time varying covariate or iv */
                   5188:        for (z1=1; z1<=cptcoveff; z1++){
                   5189:          if( Fixed[Tmodelind[z1]]==1){
                   5190:            iv= Tvar[Tmodelind[z1]]-ncovcol-nqv;
                   5191:            if (cotvar[m][iv][i]!= nbcode[Tvaraff[z1]][codtabm(j1,z1)]) /* iv=1 to ntv, right modality */
                   5192:              bool=0;
                   5193:          }else if( Fixed[Tmodelind[z1]]== 0)  /* fixed */
                   5194:            if (covar[Tvaraff[z1]][i]!= nbcode[Tvaraff[z1]][codtabm(j1,z1)]) {
                   5195:              bool=0;
                   5196:            }
                   5197:        }
                   5198:        if(bool==1){ /* Otherwise we skip that wave/person */
                   5199:          agebegin=agev[m][i]; /* Age at beginning of wave before transition*/
                   5200:          /* ageend=agev[m][i]+(dh[m][i])*stepm/YEARM; /\* Age at end of wave and transition *\/ */
                   5201:          if(m >=firstpass && m <=lastpass){
                   5202:            y2=anint[m][i]+(mint[m][i]/12.); /* Fractional date in year */
                   5203:            if ((y2>=dateprev1) && (y2<=dateprev2)) { /* Here is the main selection (fractional years) */
                   5204:              if(agev[m][i]==0) agev[m][i]=iagemax+1;
                   5205:              if(agev[m][i]==1) agev[m][i]=iagemax+2;
1.251     brouard  5206:              if((int)agev[m][i] <iagemin-AGEMARGE || (int)agev[m][i] >iagemax+4+AGEMARGE){
1.227     brouard  5207:                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); 
                   5208:                exit(1);
                   5209:              }
                   5210:              if (s[m][i]>0 && s[m][i]<=nlstate) { 
                   5211:                /*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]]);*/
                   5212:                prop[s[m][i]][(int)agev[m][i]] += weight[i];/* At age of beginning of transition, where status is known */
                   5213:                prop[s[m][i]][iagemax+3] += weight[i]; 
                   5214:              } /* end valid statuses */ 
                   5215:            } /* end selection of dates */
                   5216:          } /* end selection of waves */
                   5217:        } /* end bool */
                   5218:       } /* end wave */
                   5219:     } /* end individual */
                   5220:     for(i=iagemin; i <= iagemax+3; i++){  
                   5221:       for(jk=1,posprop=0; jk <=nlstate ; jk++) { 
                   5222:        posprop += prop[jk][i]; 
                   5223:       } 
                   5224:       
                   5225:       for(jk=1; jk <=nlstate ; jk++){      
                   5226:        if( i <=  iagemax){ 
                   5227:          if(posprop>=1.e-5){ 
                   5228:            probs[i][jk][j1]= prop[jk][i]/posprop;
                   5229:          } else{
1.288     brouard  5230:            if(!first){
                   5231:              first=1;
1.266     brouard  5232:              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]);
                   5233:            }else{
1.288     brouard  5234:              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  5235:            }
                   5236:          }
                   5237:        } 
                   5238:       }/* end jk */ 
                   5239:     }/* end i */ 
1.222     brouard  5240:      /*} *//* end i1 */
1.227     brouard  5241:   } /* end j1 */
1.222     brouard  5242:   
1.227     brouard  5243:   /*  free_ma3x(freq,-1,nlstate+ndeath,-1,nlstate+ndeath, iagemin, iagemax+3);*/
                   5244:   /*free_vector(pp,1,nlstate);*/
1.251     brouard  5245:   free_matrix(prop,1,nlstate, iagemin-AGEMARGE,iagemax+4+AGEMARGE);
1.227     brouard  5246: }  /* End of prevalence */
1.126     brouard  5247: 
                   5248: /************* Waves Concatenation ***************/
                   5249: 
                   5250: 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)
                   5251: {
1.298     brouard  5252:   /* 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  5253:      Death is a valid wave (if date is known).
                   5254:      mw[mi][i] is the mi (mi=1 to wav[i])  effective wave of individual i
                   5255:      dh[m][i] or dh[mw[mi][i]][i] is the delay between two effective waves m=mw[mi][i]
1.298     brouard  5256:      and mw[mi+1][i]. dh depends on stepm. s[m][i] exists for any wave from firstpass to lastpass
1.227     brouard  5257:   */
1.126     brouard  5258: 
1.224     brouard  5259:   int i=0, mi=0, m=0, mli=0;
1.126     brouard  5260:   /* int j, k=0,jk, ju, jl,jmin=1e+5, jmax=-1;
                   5261:      double sum=0., jmean=0.;*/
1.224     brouard  5262:   int first=0, firstwo=0, firsthree=0, firstfour=0, firstfiv=0;
1.126     brouard  5263:   int j, k=0,jk, ju, jl;
                   5264:   double sum=0.;
                   5265:   first=0;
1.214     brouard  5266:   firstwo=0;
1.217     brouard  5267:   firsthree=0;
1.218     brouard  5268:   firstfour=0;
1.164     brouard  5269:   jmin=100000;
1.126     brouard  5270:   jmax=-1;
                   5271:   jmean=0.;
1.224     brouard  5272: 
                   5273: /* Treating live states */
1.214     brouard  5274:   for(i=1; i<=imx; i++){  /* For simple cases and if state is death */
1.224     brouard  5275:     mi=0;  /* First valid wave */
1.227     brouard  5276:     mli=0; /* Last valid wave */
1.309     brouard  5277:     m=firstpass;  /* Loop on waves */
                   5278:     while(s[m][i] <= nlstate){  /* a live state or unknown state  */
1.227     brouard  5279:       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 */
                   5280:        mli=m-1;/* mw[++mi][i]=m-1; */
                   5281:       }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  5282:        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  5283:        mli=m;
1.224     brouard  5284:       } /* else might be a useless wave  -1 and mi is not incremented and mw[mi] not updated */
                   5285:       if(m < lastpass){ /* m < lastpass, standard case */
1.227     brouard  5286:        m++; /* mi gives the "effective" current wave, m the current wave, go to next wave by incrementing m */
1.216     brouard  5287:       }
1.309     brouard  5288:       else{ /* m = lastpass, eventual special issue with warning */
1.224     brouard  5289: #ifdef UNKNOWNSTATUSNOTCONTRIBUTING
1.227     brouard  5290:        break;
1.224     brouard  5291: #else
1.309     brouard  5292:        if(s[m][i]==-1 && (int) andc[i] == 9999 && (int)anint[m][i] != 9999){ /* case -2 (vital status unknown is warned later */
1.227     brouard  5293:          if(firsthree == 0){
1.302     brouard  5294:            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  5295:            firsthree=1;
                   5296:          }
1.302     brouard  5297:          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);
1.309     brouard  5298:          mw[++mi][i]=m; /* Valid transition with unknown status */
1.227     brouard  5299:          mli=m;
                   5300:        }
                   5301:        if(s[m][i]==-2){ /* Vital status is really unknown */
                   5302:          nbwarn++;
1.309     brouard  5303:          if((int)anint[m][i] == 9999){  /*  Has the vital status really been verified?not a transition */
1.227     brouard  5304:            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);
                   5305:            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);
                   5306:          }
                   5307:          break;
                   5308:        }
                   5309:        break;
1.224     brouard  5310: #endif
1.227     brouard  5311:       }/* End m >= lastpass */
1.126     brouard  5312:     }/* end while */
1.224     brouard  5313: 
1.227     brouard  5314:     /* 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  5315:     /* After last pass */
1.224     brouard  5316: /* Treating death states */
1.214     brouard  5317:     if (s[m][i] > nlstate){  /* In a death state */
1.227     brouard  5318:       /* if( mint[m][i]==mdc[m][i] && anint[m][i]==andc[m][i]){ /\* same date of death and date of interview *\/ */
                   5319:       /* } */
1.126     brouard  5320:       mi++;    /* Death is another wave */
                   5321:       /* if(mi==0)  never been interviewed correctly before death */
1.227     brouard  5322:       /* Only death is a correct wave */
1.126     brouard  5323:       mw[mi][i]=m;
1.257     brouard  5324:     } /* else not in a death state */
1.224     brouard  5325: #ifndef DISPATCHINGKNOWNDEATHAFTERLASTWAVE
1.257     brouard  5326:     else if ((int) andc[i] != 9999) {  /* Date of death is known */
1.218     brouard  5327:       if ((int)anint[m][i]!= 9999) { /* date of last interview is known */
1.309     brouard  5328:        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  5329:          nbwarn++;
                   5330:          if(firstfiv==0){
1.309     brouard  5331:            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  5332:            firstfiv=1;
                   5333:          }else{
1.309     brouard  5334:            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  5335:          }
1.309     brouard  5336:            s[m][i]=nlstate+1; /* Fixing the status as death. Be careful if multiple death states */
                   5337:        }else{ /* Month of Death occured afer last wave month, potential bias */
1.227     brouard  5338:          nberr++;
                   5339:          if(firstwo==0){
1.309     brouard  5340:            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  5341:            firstwo=1;
                   5342:          }
1.309     brouard  5343:          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  5344:        }
1.257     brouard  5345:       }else{ /* if date of interview is unknown */
1.227     brouard  5346:        /* death is known but not confirmed by death status at any wave */
                   5347:        if(firstfour==0){
1.309     brouard  5348:          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  5349:          firstfour=1;
                   5350:        }
1.309     brouard  5351:        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  5352:       }
1.224     brouard  5353:     } /* end if date of death is known */
                   5354: #endif
1.309     brouard  5355:     wav[i]=mi; /* mi should be the last effective wave (or mli),  */
                   5356:     /* wav[i]=mw[mi][i];   */
1.126     brouard  5357:     if(mi==0){
                   5358:       nbwarn++;
                   5359:       if(first==0){
1.227     brouard  5360:        printf("Warning! No valid information for individual %ld line=%d (skipped) and may be others, see log file\n",num[i],i);
                   5361:        first=1;
1.126     brouard  5362:       }
                   5363:       if(first==1){
1.227     brouard  5364:        fprintf(ficlog,"Warning! No valid information for individual %ld line=%d (skipped)\n",num[i],i);
1.126     brouard  5365:       }
                   5366:     } /* end mi==0 */
                   5367:   } /* End individuals */
1.214     brouard  5368:   /* wav and mw are no more changed */
1.223     brouard  5369:        
1.214     brouard  5370:   
1.126     brouard  5371:   for(i=1; i<=imx; i++){
                   5372:     for(mi=1; mi<wav[i];mi++){
                   5373:       if (stepm <=0)
1.227     brouard  5374:        dh[mi][i]=1;
1.126     brouard  5375:       else{
1.260     brouard  5376:        if (s[mw[mi+1][i]][i] > nlstate) { /* A death, but what if date is unknown? */
1.227     brouard  5377:          if (agedc[i] < 2*AGESUP) {
                   5378:            j= rint(agedc[i]*12-agev[mw[mi][i]][i]*12); 
                   5379:            if(j==0) j=1;  /* Survives at least one month after exam */
                   5380:            else if(j<0){
                   5381:              nberr++;
                   5382:              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]);
                   5383:              j=1; /* Temporary Dangerous patch */
                   5384:              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);
                   5385:              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]);
                   5386:              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);
                   5387:            }
                   5388:            k=k+1;
                   5389:            if (j >= jmax){
                   5390:              jmax=j;
                   5391:              ijmax=i;
                   5392:            }
                   5393:            if (j <= jmin){
                   5394:              jmin=j;
                   5395:              ijmin=i;
                   5396:            }
                   5397:            sum=sum+j;
                   5398:            /*if (j<0) printf("j=%d num=%d \n",j,i);*/
                   5399:            /*    printf("%d %d %d %d\n", s[mw[mi][i]][i] ,s[mw[mi+1][i]][i],j,i);*/
                   5400:          }
                   5401:        }
                   5402:        else{
                   5403:          j= rint( (agev[mw[mi+1][i]][i]*12 - agev[mw[mi][i]][i]*12));
1.126     brouard  5404: /*       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  5405:                                        
1.227     brouard  5406:          k=k+1;
                   5407:          if (j >= jmax) {
                   5408:            jmax=j;
                   5409:            ijmax=i;
                   5410:          }
                   5411:          else if (j <= jmin){
                   5412:            jmin=j;
                   5413:            ijmin=i;
                   5414:          }
                   5415:          /*        if (j<10) printf("j=%d jmin=%d num=%d ",j,jmin,i); */
                   5416:          /*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]);*/
                   5417:          if(j<0){
                   5418:            nberr++;
                   5419:            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]);
                   5420:            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]);
                   5421:          }
                   5422:          sum=sum+j;
                   5423:        }
                   5424:        jk= j/stepm;
                   5425:        jl= j -jk*stepm;
                   5426:        ju= j -(jk+1)*stepm;
                   5427:        if(mle <=1){ /* only if we use a the linear-interpoloation pseudo-likelihood */
                   5428:          if(jl==0){
                   5429:            dh[mi][i]=jk;
                   5430:            bh[mi][i]=0;
                   5431:          }else{ /* We want a negative bias in order to only have interpolation ie
                   5432:                  * to avoid the price of an extra matrix product in likelihood */
                   5433:            dh[mi][i]=jk+1;
                   5434:            bh[mi][i]=ju;
                   5435:          }
                   5436:        }else{
                   5437:          if(jl <= -ju){
                   5438:            dh[mi][i]=jk;
                   5439:            bh[mi][i]=jl;       /* bias is positive if real duration
                   5440:                                 * is higher than the multiple of stepm and negative otherwise.
                   5441:                                 */
                   5442:          }
                   5443:          else{
                   5444:            dh[mi][i]=jk+1;
                   5445:            bh[mi][i]=ju;
                   5446:          }
                   5447:          if(dh[mi][i]==0){
                   5448:            dh[mi][i]=1; /* At least one step */
                   5449:            bh[mi][i]=ju; /* At least one step */
                   5450:            /*  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);*/
                   5451:          }
                   5452:        } /* end if mle */
1.126     brouard  5453:       }
                   5454:     } /* end wave */
                   5455:   }
                   5456:   jmean=sum/k;
                   5457:   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  5458:   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  5459: }
1.126     brouard  5460: 
                   5461: /*********** Tricode ****************************/
1.220     brouard  5462:  void tricode(int *cptcov, int *Tvar, int **nbcode, int imx, int *Ndum)
1.242     brouard  5463:  {
                   5464:    /**< Uses cptcovn+2*cptcovprod as the number of covariates */
                   5465:    /*    Tvar[i]=atoi(stre);  find 'n' in Vn and stores in Tvar. If model=V2+V1 Tvar[1]=2 and Tvar[2]=1 
                   5466:     * Boring subroutine which should only output nbcode[Tvar[j]][k]
                   5467:     * Tvar[5] in V2+V1+V3*age+V2*V4 is 4 (V4) even it is a time varying or quantitative variable
                   5468:     * nbcode[Tvar[5]][1]= nbcode[4][1]=0, nbcode[4][2]=1 (usually);
                   5469:     */
1.130     brouard  5470: 
1.242     brouard  5471:    int ij=1, k=0, j=0, i=0, maxncov=NCOVMAX;
                   5472:    int modmaxcovj=0; /* Modality max of covariates j */
                   5473:    int cptcode=0; /* Modality max of covariates j */
                   5474:    int modmincovj=0; /* Modality min of covariates j */
1.145     brouard  5475: 
                   5476: 
1.242     brouard  5477:    /* cptcoveff=0;  */
                   5478:    /* *cptcov=0; */
1.126     brouard  5479:  
1.242     brouard  5480:    for (k=1; k <= maxncov; k++) ncodemax[k]=0; /* Horrible constant again replaced by NCOVMAX */
1.285     brouard  5481:    for (k=1; k <= maxncov; k++)
                   5482:      for(j=1; j<=2; j++)
                   5483:        nbcode[k][j]=0; /* Valgrind */
1.126     brouard  5484: 
1.242     brouard  5485:    /* Loop on covariates without age and products and no quantitative variable */
                   5486:    for (k=1; k<=cptcovt; k++) { /* From model V1 + V2*age + V3 + V3*V4 keeps V1 + V3 = 2 only */
                   5487:      for (j=-1; (j < maxncov); j++) Ndum[j]=0;
                   5488:      if(Dummy[k]==0 && Typevar[k] !=1){ /* Dummy covariate and not age product */ 
                   5489:        switch(Fixed[k]) {
                   5490:        case 0: /* Testing on fixed dummy covariate, simple or product of fixed */
                   5491:         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*/
                   5492:           ij=(int)(covar[Tvar[k]][i]);
                   5493:           /* ij=0 or 1 or -1. Value of the covariate Tvar[j] for individual i
                   5494:            * If product of Vn*Vm, still boolean *:
                   5495:            * If it was coded 1, 2, 3, 4 should be splitted into 3 boolean variables
                   5496:            * 1 => 0 0 0, 2 => 0 0 1, 3 => 0 1 1, 4=1 0 0   */
                   5497:           /* Finds for covariate j, n=Tvar[j] of Vn . ij is the
                   5498:              modality of the nth covariate of individual i. */
                   5499:           if (ij > modmaxcovj)
                   5500:             modmaxcovj=ij; 
                   5501:           else if (ij < modmincovj) 
                   5502:             modmincovj=ij; 
1.287     brouard  5503:           if (ij <0 || ij >1 ){
                   5504:             printf("Information, IMaCh doesn't treat covariate with missing values (-1), individual %d will be skipped.\n",i);
                   5505:             fprintf(ficlog,"Information, currently IMaCh doesn't treat covariate with missing values (-1), individual %d will be skipped.\n",i);
                   5506:           }
                   5507:           if ((ij < -1) || (ij > NCOVMAX)){
1.242     brouard  5508:             printf( "Error: minimal is less than -1 or maximal is bigger than %d. Exiting. \n", NCOVMAX );
                   5509:             exit(1);
                   5510:           }else
                   5511:             Ndum[ij]++; /*counts and stores the occurence of this modality 0, 1, -1*/
                   5512:           /*  If coded 1, 2, 3 , counts the number of 1 Ndum[1], number of 2, Ndum[2], etc */
                   5513:           /*printf("i=%d ij=%d Ndum[ij]=%d imx=%d",i,ij,Ndum[ij],imx);*/
                   5514:           /* getting the maximum value of the modality of the covariate
                   5515:              (should be 0 or 1 now) Tvar[j]. If V=sex and male is coded 0 and
                   5516:              female ies 1, then modmaxcovj=1.
                   5517:           */
                   5518:         } /* end for loop on individuals i */
                   5519:         printf(" Minimal and maximal values of %d th (fixed) covariate V%d: min=%d max=%d \n", k, Tvar[k], modmincovj, modmaxcovj);
                   5520:         fprintf(ficlog," Minimal and maximal values of %d th (fixed) covariate V%d: min=%d max=%d \n", k, Tvar[k], modmincovj, modmaxcovj);
                   5521:         cptcode=modmaxcovj;
                   5522:         /* Ndum[0] = frequency of 0 for model-covariate j, Ndum[1] frequency of 1 etc. */
                   5523:         /*for (i=0; i<=cptcode; i++) {*/
                   5524:         for (j=modmincovj;  j<=modmaxcovj; j++) { /* j=-1 ? 0 and 1*//* For each value j of the modality of model-cov k */
                   5525:           printf("Frequencies of (fixed) covariate %d ie V%d with value %d: %d\n", k, Tvar[k], j, Ndum[j]);
                   5526:           fprintf(ficlog, "Frequencies of (fixed) covariate %d ie V%d with value %d: %d\n", k, Tvar[k], j, Ndum[j]);
                   5527:           if( Ndum[j] != 0 ){ /* Counts if nobody answered modality j ie empty modality, we skip it and reorder */
                   5528:             if( j != -1){
                   5529:               ncodemax[k]++;  /* ncodemax[k]= Number of modalities of the k th
                   5530:                                  covariate for which somebody answered excluding 
                   5531:                                  undefined. Usually 2: 0 and 1. */
                   5532:             }
                   5533:             ncodemaxwundef[k]++; /* ncodemax[j]= Number of modalities of the k th
                   5534:                                     covariate for which somebody answered including 
                   5535:                                     undefined. Usually 3: -1, 0 and 1. */
                   5536:           }    /* In fact  ncodemax[k]=2 (dichotom. variables only) but it could be more for
                   5537:                 * historical reasons: 3 if coded 1, 2, 3 and 4 and Ndum[2]=0 */
                   5538:         } /* Ndum[-1] number of undefined modalities */
1.231     brouard  5539:                        
1.242     brouard  5540:         /* j is a covariate, n=Tvar[j] of Vn; Fills nbcode */
                   5541:         /* For covariate j, modalities could be 1, 2, 3, 4, 5, 6, 7. */
                   5542:         /* If Ndum[1]=0, Ndum[2]=0, Ndum[3]= 635, Ndum[4]=0, Ndum[5]=0, Ndum[6]=27, Ndum[7]=125; */
                   5543:         /* modmincovj=3; modmaxcovj = 7; */
                   5544:         /* There are only 3 modalities non empty 3, 6, 7 (or 2 if 27 is too few) : ncodemax[j]=3; */
                   5545:         /* which will be coded 0, 1, 2 which in binary on 2=3-1 digits are 0=00 1=01, 2=10; */
                   5546:         /*              defining two dummy variables: variables V1_1 and V1_2.*/
                   5547:         /* nbcode[Tvar[j]][ij]=k; */
                   5548:         /* nbcode[Tvar[j]][1]=0; */
                   5549:         /* nbcode[Tvar[j]][2]=1; */
                   5550:         /* nbcode[Tvar[j]][3]=2; */
                   5551:         /* To be continued (not working yet). */
                   5552:         ij=0; /* ij is similar to i but can jump over null modalities */
1.287     brouard  5553: 
                   5554:         /* 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*/
                   5555:         /* Skipping the case of missing values by reducing nbcode to 0 and 1 and not -1, 0, 1 */
                   5556:         /* model=V1+V2+V3, if V2=-1, 0 or 1, then nbcode[2][1]=0 and nbcode[2][2]=1 instead of
                   5557:          * nbcode[2][1]=-1, nbcode[2][2]=0 and nbcode[2][3]=1 */
                   5558:         /*, could be restored in the future */
                   5559:         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  5560:           if (Ndum[i] == 0) { /* If nobody responded to this modality k */
                   5561:             break;
                   5562:           }
                   5563:           ij++;
1.287     brouard  5564:           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  5565:           cptcode = ij; /* New max modality for covar j */
                   5566:         } /* end of loop on modality i=-1 to 1 or more */
                   5567:         break;
                   5568:        case 1: /* Testing on varying covariate, could be simple and
                   5569:                * should look at waves or product of fixed *
                   5570:                * varying. No time to test -1, assuming 0 and 1 only */
                   5571:         ij=0;
                   5572:         for(i=0; i<=1;i++){
                   5573:           nbcode[Tvar[k]][++ij]=i;
                   5574:         }
                   5575:         break;
                   5576:        default:
                   5577:         break;
                   5578:        } /* end switch */
                   5579:      } /* end dummy test */
1.287     brouard  5580:    } /* 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  5581:   
                   5582:    for (k=-1; k< maxncov; k++) Ndum[k]=0; 
                   5583:    /* Look at fixed dummy (single or product) covariates to check empty modalities */
                   5584:    for (i=1; i<=ncovmodel-2-nagesqr; i++) { /* -2, cste and age and eventually age*age */ 
                   5585:      /* Listing of all covariables in statement model to see if some covariates appear twice. For example, V1 appears twice in V1+V1*V2.*/ 
                   5586:      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 */ 
                   5587:      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 */
                   5588:      /* V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1,  {2, 1, 1, 1, 2, 1, 1, 0, 0} */
                   5589:    } /* V4+V3+V5, Ndum[1]@5={0, 0, 1, 1, 1} */
                   5590:   
                   5591:    ij=0;
                   5592:    /* for (i=0; i<=  maxncov-1; i++) { /\* modmaxcovj is unknown here. Only Ndum[2(V2),3(age*V3), 5(V3*V2) 6(V1*V4) *\/ */
                   5593:    for (k=1; k<=  cptcovt; k++) { /* modmaxcovj is unknown here. Only Ndum[2(V2),3(age*V3), 5(V3*V2) 6(V1*V4) */
                   5594:      /*printf("Ndum[%d]=%d\n",i, Ndum[i]);*/
                   5595:      /* if((Ndum[i]!=0) && (i<=ncovcol)){  /\* Tvar[i] <= ncovmodel ? *\/ */
                   5596:      if(Ndum[Tvar[k]]!=0 && Dummy[k] == 0 && Typevar[k]==0){  /* Only Dummy and non empty in the model */
                   5597:        /* If product not in single variable we don't print results */
                   5598:        /*printf("diff Ndum[%d]=%d\n",i, Ndum[i]);*/
                   5599:        ++ij;/* V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1, */
                   5600:        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*/
                   5601:        Tmodelind[ij]=k; /* Tmodelind: index in model of dummies Tmodelind[1]=2 V4: pos=2; V3: pos=3, V1=9 {2, 3, 9, ?, ?,} */
                   5602:        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 */
                   5603:        if(Fixed[k]!=0)
                   5604:         anyvaryingduminmodel=1;
                   5605:        /* }else if((Ndum[i]!=0) && (i<=ncovcol+nqv)){ */
                   5606:        /*   Tvaraff[++ij]=-10; /\* Dont'n know how to treat quantitative variables yet *\/ */
                   5607:        /* }else if((Ndum[i]!=0) && (i<=ncovcol+nqv+ntv)){ */
                   5608:        /*   Tvaraff[++ij]=i; /\*For printing (unclear) *\/ */
                   5609:        /* }else if((Ndum[i]!=0) && (i<=ncovcol+nqv+ntv+nqtv)){ */
                   5610:        /*   Tvaraff[++ij]=-20; /\* Dont'n know how to treat quantitative variables yet *\/ */
                   5611:      } 
                   5612:    } /* Tvaraff[1]@5 {3, 4, -20, 0, 0} Very strange */
                   5613:    /* ij--; */
                   5614:    /* cptcoveff=ij; /\*Number of total covariates*\/ */
                   5615:    *cptcov=ij; /*Number of total real effective covariates: effective
                   5616:                * because they can be excluded from the model and real
                   5617:                * if in the model but excluded because missing values, but how to get k from ij?*/
                   5618:    for(j=ij+1; j<= cptcovt; j++){
                   5619:      Tvaraff[j]=0;
                   5620:      Tmodelind[j]=0;
                   5621:    }
                   5622:    for(j=ntveff+1; j<= cptcovt; j++){
                   5623:      TmodelInvind[j]=0;
                   5624:    }
                   5625:    /* To be sorted */
                   5626:    ;
                   5627:  }
1.126     brouard  5628: 
1.145     brouard  5629: 
1.126     brouard  5630: /*********** Health Expectancies ****************/
                   5631: 
1.235     brouard  5632:  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  5633: 
                   5634: {
                   5635:   /* Health expectancies, no variances */
1.164     brouard  5636:   int i, j, nhstepm, hstepm, h, nstepm;
1.126     brouard  5637:   int nhstepma, nstepma; /* Decreasing with age */
                   5638:   double age, agelim, hf;
                   5639:   double ***p3mat;
                   5640:   double eip;
                   5641: 
1.238     brouard  5642:   /* pstamp(ficreseij); */
1.126     brouard  5643:   fprintf(ficreseij,"# (a) Life expectancies by health status at initial age and (b) health expectancies by health status at initial age\n");
                   5644:   fprintf(ficreseij,"# Age");
                   5645:   for(i=1; i<=nlstate;i++){
                   5646:     for(j=1; j<=nlstate;j++){
                   5647:       fprintf(ficreseij," e%1d%1d ",i,j);
                   5648:     }
                   5649:     fprintf(ficreseij," e%1d. ",i);
                   5650:   }
                   5651:   fprintf(ficreseij,"\n");
                   5652: 
                   5653:   
                   5654:   if(estepm < stepm){
                   5655:     printf ("Problem %d lower than %d\n",estepm, stepm);
                   5656:   }
                   5657:   else  hstepm=estepm;   
                   5658:   /* We compute the life expectancy from trapezoids spaced every estepm months
                   5659:    * This is mainly to measure the difference between two models: for example
                   5660:    * if stepm=24 months pijx are given only every 2 years and by summing them
                   5661:    * we are calculating an estimate of the Life Expectancy assuming a linear 
                   5662:    * progression in between and thus overestimating or underestimating according
                   5663:    * to the curvature of the survival function. If, for the same date, we 
                   5664:    * estimate the model with stepm=1 month, we can keep estepm to 24 months
                   5665:    * to compare the new estimate of Life expectancy with the same linear 
                   5666:    * hypothesis. A more precise result, taking into account a more precise
                   5667:    * curvature will be obtained if estepm is as small as stepm. */
                   5668: 
                   5669:   /* For example we decided to compute the life expectancy with the smallest unit */
                   5670:   /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm. 
                   5671:      nhstepm is the number of hstepm from age to agelim 
                   5672:      nstepm is the number of stepm from age to agelin. 
1.270     brouard  5673:      Look at hpijx to understand the reason which relies in memory size consideration
1.126     brouard  5674:      and note for a fixed period like estepm months */
                   5675:   /* We decided (b) to get a life expectancy respecting the most precise curvature of the
                   5676:      survival function given by stepm (the optimization length). Unfortunately it
                   5677:      means that if the survival funtion is printed only each two years of age and if
                   5678:      you sum them up and add 1 year (area under the trapezoids) you won't get the same 
                   5679:      results. So we changed our mind and took the option of the best precision.
                   5680:   */
                   5681:   hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */ 
                   5682: 
                   5683:   agelim=AGESUP;
                   5684:   /* If stepm=6 months */
                   5685:     /* Computed by stepm unit matrices, product of hstepm matrices, stored
                   5686:        in an array of nhstepm length: nhstepm=10, hstepm=4, stepm=6 months */
                   5687:     
                   5688: /* nhstepm age range expressed in number of stepm */
                   5689:   nstepm=(int) rint((agelim-bage)*YEARM/stepm); /* Biggest nstepm */
                   5690:   /* Typically if 20 years nstepm = 20*12/6=40 stepm */ 
                   5691:   /* if (stepm >= YEARM) hstepm=1;*/
                   5692:   nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
                   5693:   p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   5694: 
                   5695:   for (age=bage; age<=fage; age ++){ 
                   5696:     nstepma=(int) rint((agelim-bage)*YEARM/stepm); /* Biggest nstepm */
                   5697:     /* Typically if 20 years nstepm = 20*12/6=40 stepm */ 
                   5698:     /* if (stepm >= YEARM) hstepm=1;*/
                   5699:     nhstepma = nstepma/hstepm;/* Expressed in hstepm, typically nhstepma=40/4=10 */
                   5700: 
                   5701:     /* If stepm=6 months */
                   5702:     /* Computed by stepm unit matrices, product of hstepma matrices, stored
                   5703:        in an array of nhstepma length: nhstepma=10, hstepm=4, stepm=6 months */
                   5704:     
1.235     brouard  5705:     hpxij(p3mat,nhstepma,age,hstepm,x,nlstate,stepm,oldm, savm, cij, nres);  
1.126     brouard  5706:     
                   5707:     hf=hstepm*stepm/YEARM;  /* Duration of hstepm expressed in year unit. */
                   5708:     
                   5709:     printf("%d|",(int)age);fflush(stdout);
                   5710:     fprintf(ficlog,"%d|",(int)age);fflush(ficlog);
                   5711:     
                   5712:     /* Computing expectancies */
                   5713:     for(i=1; i<=nlstate;i++)
                   5714:       for(j=1; j<=nlstate;j++)
                   5715:        for (h=0, eij[i][j][(int)age]=0; h<=nhstepm-1; h++){
                   5716:          eij[i][j][(int)age] += (p3mat[i][j][h]+p3mat[i][j][h+1])/2.0*hf;
                   5717:          
                   5718:          /* 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]);*/
                   5719: 
                   5720:        }
                   5721: 
                   5722:     fprintf(ficreseij,"%3.0f",age );
                   5723:     for(i=1; i<=nlstate;i++){
                   5724:       eip=0;
                   5725:       for(j=1; j<=nlstate;j++){
                   5726:        eip +=eij[i][j][(int)age];
                   5727:        fprintf(ficreseij,"%9.4f", eij[i][j][(int)age] );
                   5728:       }
                   5729:       fprintf(ficreseij,"%9.4f", eip );
                   5730:     }
                   5731:     fprintf(ficreseij,"\n");
                   5732:     
                   5733:   }
                   5734:   free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   5735:   printf("\n");
                   5736:   fprintf(ficlog,"\n");
                   5737:   
                   5738: }
                   5739: 
1.235     brouard  5740:  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  5741: 
                   5742: {
                   5743:   /* Covariances of health expectancies eij and of total life expectancies according
1.222     brouard  5744:      to initial status i, ei. .
1.126     brouard  5745:   */
                   5746:   int i, j, nhstepm, hstepm, h, nstepm, k, cptj, cptj2, i2, j2, ij, ji;
                   5747:   int nhstepma, nstepma; /* Decreasing with age */
                   5748:   double age, agelim, hf;
                   5749:   double ***p3matp, ***p3matm, ***varhe;
                   5750:   double **dnewm,**doldm;
                   5751:   double *xp, *xm;
                   5752:   double **gp, **gm;
                   5753:   double ***gradg, ***trgradg;
                   5754:   int theta;
                   5755: 
                   5756:   double eip, vip;
                   5757: 
                   5758:   varhe=ma3x(1,nlstate*nlstate,1,nlstate*nlstate,(int) bage, (int) fage);
                   5759:   xp=vector(1,npar);
                   5760:   xm=vector(1,npar);
                   5761:   dnewm=matrix(1,nlstate*nlstate,1,npar);
                   5762:   doldm=matrix(1,nlstate*nlstate,1,nlstate*nlstate);
                   5763:   
                   5764:   pstamp(ficresstdeij);
                   5765:   fprintf(ficresstdeij,"# Health expectancies with standard errors\n");
                   5766:   fprintf(ficresstdeij,"# Age");
                   5767:   for(i=1; i<=nlstate;i++){
                   5768:     for(j=1; j<=nlstate;j++)
                   5769:       fprintf(ficresstdeij," e%1d%1d (SE)",i,j);
                   5770:     fprintf(ficresstdeij," e%1d. ",i);
                   5771:   }
                   5772:   fprintf(ficresstdeij,"\n");
                   5773: 
                   5774:   pstamp(ficrescveij);
                   5775:   fprintf(ficrescveij,"# Subdiagonal matrix of covariances of health expectancies by age: cov(eij,ekl)\n");
                   5776:   fprintf(ficrescveij,"# Age");
                   5777:   for(i=1; i<=nlstate;i++)
                   5778:     for(j=1; j<=nlstate;j++){
                   5779:       cptj= (j-1)*nlstate+i;
                   5780:       for(i2=1; i2<=nlstate;i2++)
                   5781:        for(j2=1; j2<=nlstate;j2++){
                   5782:          cptj2= (j2-1)*nlstate+i2;
                   5783:          if(cptj2 <= cptj)
                   5784:            fprintf(ficrescveij,"  %1d%1d,%1d%1d",i,j,i2,j2);
                   5785:        }
                   5786:     }
                   5787:   fprintf(ficrescveij,"\n");
                   5788:   
                   5789:   if(estepm < stepm){
                   5790:     printf ("Problem %d lower than %d\n",estepm, stepm);
                   5791:   }
                   5792:   else  hstepm=estepm;   
                   5793:   /* We compute the life expectancy from trapezoids spaced every estepm months
                   5794:    * This is mainly to measure the difference between two models: for example
                   5795:    * if stepm=24 months pijx are given only every 2 years and by summing them
                   5796:    * we are calculating an estimate of the Life Expectancy assuming a linear 
                   5797:    * progression in between and thus overestimating or underestimating according
                   5798:    * to the curvature of the survival function. If, for the same date, we 
                   5799:    * estimate the model with stepm=1 month, we can keep estepm to 24 months
                   5800:    * to compare the new estimate of Life expectancy with the same linear 
                   5801:    * hypothesis. A more precise result, taking into account a more precise
                   5802:    * curvature will be obtained if estepm is as small as stepm. */
                   5803: 
                   5804:   /* For example we decided to compute the life expectancy with the smallest unit */
                   5805:   /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm. 
                   5806:      nhstepm is the number of hstepm from age to agelim 
                   5807:      nstepm is the number of stepm from age to agelin. 
                   5808:      Look at hpijx to understand the reason of that which relies in memory size
                   5809:      and note for a fixed period like estepm months */
                   5810:   /* We decided (b) to get a life expectancy respecting the most precise curvature of the
                   5811:      survival function given by stepm (the optimization length). Unfortunately it
                   5812:      means that if the survival funtion is printed only each two years of age and if
                   5813:      you sum them up and add 1 year (area under the trapezoids) you won't get the same 
                   5814:      results. So we changed our mind and took the option of the best precision.
                   5815:   */
                   5816:   hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */ 
                   5817: 
                   5818:   /* If stepm=6 months */
                   5819:   /* nhstepm age range expressed in number of stepm */
                   5820:   agelim=AGESUP;
                   5821:   nstepm=(int) rint((agelim-bage)*YEARM/stepm); 
                   5822:   /* Typically if 20 years nstepm = 20*12/6=40 stepm */ 
                   5823:   /* if (stepm >= YEARM) hstepm=1;*/
                   5824:   nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
                   5825:   
                   5826:   p3matp=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   5827:   p3matm=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   5828:   gradg=ma3x(0,nhstepm,1,npar,1,nlstate*nlstate);
                   5829:   trgradg =ma3x(0,nhstepm,1,nlstate*nlstate,1,npar);
                   5830:   gp=matrix(0,nhstepm,1,nlstate*nlstate);
                   5831:   gm=matrix(0,nhstepm,1,nlstate*nlstate);
                   5832: 
                   5833:   for (age=bage; age<=fage; age ++){ 
                   5834:     nstepma=(int) rint((agelim-bage)*YEARM/stepm); /* Biggest nstepm */
                   5835:     /* Typically if 20 years nstepm = 20*12/6=40 stepm */ 
                   5836:     /* if (stepm >= YEARM) hstepm=1;*/
                   5837:     nhstepma = nstepma/hstepm;/* Expressed in hstepm, typically nhstepma=40/4=10 */
1.218     brouard  5838:                
1.126     brouard  5839:     /* If stepm=6 months */
                   5840:     /* Computed by stepm unit matrices, product of hstepma matrices, stored
                   5841:        in an array of nhstepma length: nhstepma=10, hstepm=4, stepm=6 months */
                   5842:     
                   5843:     hf=hstepm*stepm/YEARM;  /* Duration of hstepm expressed in year unit. */
1.218     brouard  5844:                
1.126     brouard  5845:     /* Computing  Variances of health expectancies */
                   5846:     /* Gradient is computed with plus gp and minus gm. Code is duplicated in order to
                   5847:        decrease memory allocation */
                   5848:     for(theta=1; theta <=npar; theta++){
                   5849:       for(i=1; i<=npar; i++){ 
1.222     brouard  5850:        xp[i] = x[i] + (i==theta ?delti[theta]:0);
                   5851:        xm[i] = x[i] - (i==theta ?delti[theta]:0);
1.126     brouard  5852:       }
1.235     brouard  5853:       hpxij(p3matp,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, cij, nres);  
                   5854:       hpxij(p3matm,nhstepm,age,hstepm,xm,nlstate,stepm,oldm,savm, cij, nres);  
1.218     brouard  5855:                        
1.126     brouard  5856:       for(j=1; j<= nlstate; j++){
1.222     brouard  5857:        for(i=1; i<=nlstate; i++){
                   5858:          for(h=0; h<=nhstepm-1; h++){
                   5859:            gp[h][(j-1)*nlstate + i] = (p3matp[i][j][h]+p3matp[i][j][h+1])/2.;
                   5860:            gm[h][(j-1)*nlstate + i] = (p3matm[i][j][h]+p3matm[i][j][h+1])/2.;
                   5861:          }
                   5862:        }
1.126     brouard  5863:       }
1.218     brouard  5864:                        
1.126     brouard  5865:       for(ij=1; ij<= nlstate*nlstate; ij++)
1.222     brouard  5866:        for(h=0; h<=nhstepm-1; h++){
                   5867:          gradg[h][theta][ij]= (gp[h][ij]-gm[h][ij])/2./delti[theta];
                   5868:        }
1.126     brouard  5869:     }/* End theta */
                   5870:     
                   5871:     
                   5872:     for(h=0; h<=nhstepm-1; h++)
                   5873:       for(j=1; j<=nlstate*nlstate;j++)
1.222     brouard  5874:        for(theta=1; theta <=npar; theta++)
                   5875:          trgradg[h][j][theta]=gradg[h][theta][j];
1.126     brouard  5876:     
1.218     brouard  5877:                
1.222     brouard  5878:     for(ij=1;ij<=nlstate*nlstate;ij++)
1.126     brouard  5879:       for(ji=1;ji<=nlstate*nlstate;ji++)
1.222     brouard  5880:        varhe[ij][ji][(int)age] =0.;
1.218     brouard  5881:                
1.222     brouard  5882:     printf("%d|",(int)age);fflush(stdout);
                   5883:     fprintf(ficlog,"%d|",(int)age);fflush(ficlog);
                   5884:     for(h=0;h<=nhstepm-1;h++){
1.126     brouard  5885:       for(k=0;k<=nhstepm-1;k++){
1.222     brouard  5886:        matprod2(dnewm,trgradg[h],1,nlstate*nlstate,1,npar,1,npar,matcov);
                   5887:        matprod2(doldm,dnewm,1,nlstate*nlstate,1,npar,1,nlstate*nlstate,gradg[k]);
                   5888:        for(ij=1;ij<=nlstate*nlstate;ij++)
                   5889:          for(ji=1;ji<=nlstate*nlstate;ji++)
                   5890:            varhe[ij][ji][(int)age] += doldm[ij][ji]*hf*hf;
1.126     brouard  5891:       }
                   5892:     }
1.218     brouard  5893:                
1.126     brouard  5894:     /* Computing expectancies */
1.235     brouard  5895:     hpxij(p3matm,nhstepm,age,hstepm,x,nlstate,stepm,oldm, savm, cij,nres);  
1.126     brouard  5896:     for(i=1; i<=nlstate;i++)
                   5897:       for(j=1; j<=nlstate;j++)
1.222     brouard  5898:        for (h=0, eij[i][j][(int)age]=0; h<=nhstepm-1; h++){
                   5899:          eij[i][j][(int)age] += (p3matm[i][j][h]+p3matm[i][j][h+1])/2.0*hf;
1.218     brouard  5900:                                        
1.222     brouard  5901:          /* 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  5902:                                        
1.222     brouard  5903:        }
1.269     brouard  5904: 
                   5905:     /* Standard deviation of expectancies ij */                
1.126     brouard  5906:     fprintf(ficresstdeij,"%3.0f",age );
                   5907:     for(i=1; i<=nlstate;i++){
                   5908:       eip=0.;
                   5909:       vip=0.;
                   5910:       for(j=1; j<=nlstate;j++){
1.222     brouard  5911:        eip += eij[i][j][(int)age];
                   5912:        for(k=1; k<=nlstate;k++) /* Sum on j and k of cov(eij,eik) */
                   5913:          vip += varhe[(j-1)*nlstate+i][(k-1)*nlstate+i][(int)age];
                   5914:        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  5915:       }
                   5916:       fprintf(ficresstdeij," %9.4f (%.4f)", eip, sqrt(vip));
                   5917:     }
                   5918:     fprintf(ficresstdeij,"\n");
1.218     brouard  5919:                
1.269     brouard  5920:     /* Variance of expectancies ij */          
1.126     brouard  5921:     fprintf(ficrescveij,"%3.0f",age );
                   5922:     for(i=1; i<=nlstate;i++)
                   5923:       for(j=1; j<=nlstate;j++){
1.222     brouard  5924:        cptj= (j-1)*nlstate+i;
                   5925:        for(i2=1; i2<=nlstate;i2++)
                   5926:          for(j2=1; j2<=nlstate;j2++){
                   5927:            cptj2= (j2-1)*nlstate+i2;
                   5928:            if(cptj2 <= cptj)
                   5929:              fprintf(ficrescveij," %.4f", varhe[cptj][cptj2][(int)age]);
                   5930:          }
1.126     brouard  5931:       }
                   5932:     fprintf(ficrescveij,"\n");
1.218     brouard  5933:                
1.126     brouard  5934:   }
                   5935:   free_matrix(gm,0,nhstepm,1,nlstate*nlstate);
                   5936:   free_matrix(gp,0,nhstepm,1,nlstate*nlstate);
                   5937:   free_ma3x(gradg,0,nhstepm,1,npar,1,nlstate*nlstate);
                   5938:   free_ma3x(trgradg,0,nhstepm,1,nlstate*nlstate,1,npar);
                   5939:   free_ma3x(p3matm,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   5940:   free_ma3x(p3matp,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   5941:   printf("\n");
                   5942:   fprintf(ficlog,"\n");
1.218     brouard  5943:        
1.126     brouard  5944:   free_vector(xm,1,npar);
                   5945:   free_vector(xp,1,npar);
                   5946:   free_matrix(dnewm,1,nlstate*nlstate,1,npar);
                   5947:   free_matrix(doldm,1,nlstate*nlstate,1,nlstate*nlstate);
                   5948:   free_ma3x(varhe,1,nlstate*nlstate,1,nlstate*nlstate,(int) bage, (int)fage);
                   5949: }
1.218     brouard  5950:  
1.126     brouard  5951: /************ Variance ******************/
1.235     brouard  5952:  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  5953:  {
1.279     brouard  5954:    /** Variance of health expectancies 
                   5955:     *  double **prevalim(double **prlim, int nlstate, double *xp, double age, double **oldm, double ** savm,double ftolpl);
                   5956:     * double **newm;
                   5957:     * int movingaverage(double ***probs, double bage,double fage, double ***mobaverage, int mobilav) 
                   5958:     */
1.218     brouard  5959:   
                   5960:    /* int movingaverage(); */
                   5961:    double **dnewm,**doldm;
                   5962:    double **dnewmp,**doldmp;
                   5963:    int i, j, nhstepm, hstepm, h, nstepm ;
1.288     brouard  5964:    int first=0;
1.218     brouard  5965:    int k;
                   5966:    double *xp;
1.279     brouard  5967:    double **gp, **gm;  /**< for var eij */
                   5968:    double ***gradg, ***trgradg; /**< for var eij */
                   5969:    double **gradgp, **trgradgp; /**< for var p point j */
                   5970:    double *gpp, *gmp; /**< for var p point j */
                   5971:    double **varppt; /**< for var p point j nlstate to nlstate+ndeath */
1.218     brouard  5972:    double ***p3mat;
                   5973:    double age,agelim, hf;
                   5974:    /* double ***mobaverage; */
                   5975:    int theta;
                   5976:    char digit[4];
                   5977:    char digitp[25];
                   5978: 
                   5979:    char fileresprobmorprev[FILENAMELENGTH];
                   5980: 
                   5981:    if(popbased==1){
                   5982:      if(mobilav!=0)
                   5983:        strcpy(digitp,"-POPULBASED-MOBILAV_");
                   5984:      else strcpy(digitp,"-POPULBASED-NOMOBIL_");
                   5985:    }
                   5986:    else 
                   5987:      strcpy(digitp,"-STABLBASED_");
1.126     brouard  5988: 
1.218     brouard  5989:    /* if (mobilav!=0) { */
                   5990:    /*   mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX); */
                   5991:    /*   if (movingaverage(probs, bage, fage, mobaverage,mobilav)!=0){ */
                   5992:    /*     fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav); */
                   5993:    /*     printf(" Error in movingaverage mobilav=%d\n",mobilav); */
                   5994:    /*   } */
                   5995:    /* } */
                   5996: 
                   5997:    strcpy(fileresprobmorprev,"PRMORPREV-"); 
                   5998:    sprintf(digit,"%-d",ij);
                   5999:    /*printf("DIGIT=%s, ij=%d ijr=%-d|\n",digit, ij,ij);*/
                   6000:    strcat(fileresprobmorprev,digit); /* Tvar to be done */
                   6001:    strcat(fileresprobmorprev,digitp); /* Popbased or not, mobilav or not */
                   6002:    strcat(fileresprobmorprev,fileresu);
                   6003:    if((ficresprobmorprev=fopen(fileresprobmorprev,"w"))==NULL) {
                   6004:      printf("Problem with resultfile: %s\n", fileresprobmorprev);
                   6005:      fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobmorprev);
                   6006:    }
                   6007:    printf("Computing total mortality p.j=w1*p1j+w2*p2j+..: result on file '%s' \n",fileresprobmorprev);
                   6008:    fprintf(ficlog,"Computing total mortality p.j=w1*p1j+w2*p2j+..: result on file '%s' \n",fileresprobmorprev);
                   6009:    pstamp(ficresprobmorprev);
                   6010:    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  6011:    fprintf(ficresprobmorprev,"# Selected quantitative variables and dummies");
                   6012:    for (j=1; j<= nsq; j++){ /* For each selected (single) quantitative value */
                   6013:      fprintf(ficresprobmorprev," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]);
                   6014:    }
                   6015:    for(j=1;j<=cptcoveff;j++) 
                   6016:      fprintf(ficresprobmorprev,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(ij,j)]);
                   6017:    fprintf(ficresprobmorprev,"\n");
                   6018: 
1.218     brouard  6019:    fprintf(ficresprobmorprev,"# Age cov=%-d",ij);
                   6020:    for(j=nlstate+1; j<=(nlstate+ndeath);j++){
                   6021:      fprintf(ficresprobmorprev," p.%-d SE",j);
                   6022:      for(i=1; i<=nlstate;i++)
                   6023:        fprintf(ficresprobmorprev," w%1d p%-d%-d",i,i,j);
                   6024:    }  
                   6025:    fprintf(ficresprobmorprev,"\n");
                   6026:   
                   6027:    fprintf(ficgp,"\n# Routine varevsij");
                   6028:    fprintf(ficgp,"\nunset title \n");
                   6029:    /* fprintf(fichtm, "#Local time at start: %s", strstart);*/
                   6030:    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");
                   6031:    fprintf(fichtm,"\n<br>%s  <br>\n",digitp);
1.279     brouard  6032: 
1.218     brouard  6033:    varppt = matrix(nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
                   6034:    pstamp(ficresvij);
                   6035:    fprintf(ficresvij,"# Variance and covariance of health expectancies e.j \n#  (weighted average of eij where weights are ");
                   6036:    if(popbased==1)
                   6037:      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);
                   6038:    else
                   6039:      fprintf(ficresvij,"the age specific period (stable) prevalences in each health state \n");
                   6040:    fprintf(ficresvij,"# Age");
                   6041:    for(i=1; i<=nlstate;i++)
                   6042:      for(j=1; j<=nlstate;j++)
                   6043:        fprintf(ficresvij," Cov(e.%1d, e.%1d)",i,j);
                   6044:    fprintf(ficresvij,"\n");
                   6045: 
                   6046:    xp=vector(1,npar);
                   6047:    dnewm=matrix(1,nlstate,1,npar);
                   6048:    doldm=matrix(1,nlstate,1,nlstate);
                   6049:    dnewmp= matrix(nlstate+1,nlstate+ndeath,1,npar);
                   6050:    doldmp= matrix(nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
                   6051: 
                   6052:    gradgp=matrix(1,npar,nlstate+1,nlstate+ndeath);
                   6053:    gpp=vector(nlstate+1,nlstate+ndeath);
                   6054:    gmp=vector(nlstate+1,nlstate+ndeath);
                   6055:    trgradgp =matrix(nlstate+1,nlstate+ndeath,1,npar); /* mu or p point j*/
1.126     brouard  6056:   
1.218     brouard  6057:    if(estepm < stepm){
                   6058:      printf ("Problem %d lower than %d\n",estepm, stepm);
                   6059:    }
                   6060:    else  hstepm=estepm;   
                   6061:    /* For example we decided to compute the life expectancy with the smallest unit */
                   6062:    /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm. 
                   6063:       nhstepm is the number of hstepm from age to agelim 
                   6064:       nstepm is the number of stepm from age to agelim. 
                   6065:       Look at function hpijx to understand why because of memory size limitations, 
                   6066:       we decided (b) to get a life expectancy respecting the most precise curvature of the
                   6067:       survival function given by stepm (the optimization length). Unfortunately it
                   6068:       means that if the survival funtion is printed every two years of age and if
                   6069:       you sum them up and add 1 year (area under the trapezoids) you won't get the same 
                   6070:       results. So we changed our mind and took the option of the best precision.
                   6071:    */
                   6072:    hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */ 
                   6073:    agelim = AGESUP;
                   6074:    for (age=bage; age<=fage; age ++){ /* If stepm=6 months */
                   6075:      nstepm=(int) rint((agelim-age)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */ 
                   6076:      nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
                   6077:      p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   6078:      gradg=ma3x(0,nhstepm,1,npar,1,nlstate);
                   6079:      gp=matrix(0,nhstepm,1,nlstate);
                   6080:      gm=matrix(0,nhstepm,1,nlstate);
                   6081:                
                   6082:                
                   6083:      for(theta=1; theta <=npar; theta++){
                   6084:        for(i=1; i<=npar; i++){ /* Computes gradient x + delta*/
                   6085:         xp[i] = x[i] + (i==theta ?delti[theta]:0);
                   6086:        }
1.279     brouard  6087:        /**< Computes the prevalence limit with parameter theta shifted of delta up to ftolpl precision and 
                   6088:        * returns into prlim .
1.288     brouard  6089:        */
1.242     brouard  6090:        prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp,ij, nres);
1.279     brouard  6091: 
                   6092:        /* If popbased = 1 we use crossection prevalences. Previous step is useless but prlim is created */
1.218     brouard  6093:        if (popbased==1) {
                   6094:         if(mobilav ==0){
                   6095:           for(i=1; i<=nlstate;i++)
                   6096:             prlim[i][i]=probs[(int)age][i][ij];
                   6097:         }else{ /* mobilav */ 
                   6098:           for(i=1; i<=nlstate;i++)
                   6099:             prlim[i][i]=mobaverage[(int)age][i][ij];
                   6100:         }
                   6101:        }
1.295     brouard  6102:        /**< Computes the shifted transition matrix \f$ {}{h}_p^{ij}x\f$ at horizon h.
1.279     brouard  6103:        */                      
                   6104:        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  6105:        /**< 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  6106:        * at horizon h in state j including mortality.
                   6107:        */
1.218     brouard  6108:        for(j=1; j<= nlstate; j++){
                   6109:         for(h=0; h<=nhstepm; h++){
                   6110:           for(i=1, gp[h][j]=0.;i<=nlstate;i++)
                   6111:             gp[h][j] += prlim[i][i]*p3mat[i][j][h];
                   6112:         }
                   6113:        }
1.279     brouard  6114:        /* Next for computing shifted+ probability of death (h=1 means
1.218     brouard  6115:          computed over hstepm matrices product = hstepm*stepm months) 
1.279     brouard  6116:          as a weighted average of prlim(i) * p(i,j) p.3=w1*p13 + w2*p23 .
1.218     brouard  6117:        */
                   6118:        for(j=nlstate+1;j<=nlstate+ndeath;j++){
                   6119:         for(i=1,gpp[j]=0.; i<= nlstate; i++)
                   6120:           gpp[j] += prlim[i][i]*p3mat[i][j][1];
1.279     brouard  6121:        }
                   6122:        
                   6123:        /* Again with minus shift */
1.218     brouard  6124:                        
                   6125:        for(i=1; i<=npar; i++) /* Computes gradient x - delta */
                   6126:         xp[i] = x[i] - (i==theta ?delti[theta]:0);
1.288     brouard  6127: 
1.242     brouard  6128:        prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp, ij, nres);
1.218     brouard  6129:                        
                   6130:        if (popbased==1) {
                   6131:         if(mobilav ==0){
                   6132:           for(i=1; i<=nlstate;i++)
                   6133:             prlim[i][i]=probs[(int)age][i][ij];
                   6134:         }else{ /* mobilav */ 
                   6135:           for(i=1; i<=nlstate;i++)
                   6136:             prlim[i][i]=mobaverage[(int)age][i][ij];
                   6137:         }
                   6138:        }
                   6139:                        
1.235     brouard  6140:        hpxij(p3mat,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, ij,nres);  
1.218     brouard  6141:                        
                   6142:        for(j=1; j<= nlstate; j++){  /* Sum of wi * eij = e.j */
                   6143:         for(h=0; h<=nhstepm; h++){
                   6144:           for(i=1, gm[h][j]=0.;i<=nlstate;i++)
                   6145:             gm[h][j] += prlim[i][i]*p3mat[i][j][h];
                   6146:         }
                   6147:        }
                   6148:        /* This for computing probability of death (h=1 means
                   6149:          computed over hstepm matrices product = hstepm*stepm months) 
                   6150:          as a weighted average of prlim.
                   6151:        */
                   6152:        for(j=nlstate+1;j<=nlstate+ndeath;j++){
                   6153:         for(i=1,gmp[j]=0.; i<= nlstate; i++)
                   6154:           gmp[j] += prlim[i][i]*p3mat[i][j][1];
                   6155:        }    
1.279     brouard  6156:        /* end shifting computations */
                   6157: 
                   6158:        /**< Computing gradient matrix at horizon h 
                   6159:        */
1.218     brouard  6160:        for(j=1; j<= nlstate; j++) /* vareij */
                   6161:         for(h=0; h<=nhstepm; h++){
                   6162:           gradg[h][theta][j]= (gp[h][j]-gm[h][j])/2./delti[theta];
                   6163:         }
1.279     brouard  6164:        /**< Gradient of overall mortality p.3 (or p.j) 
                   6165:        */
                   6166:        for(j=nlstate+1; j<= nlstate+ndeath; j++){ /* var mu mortality from j */
1.218     brouard  6167:         gradgp[theta][j]= (gpp[j]-gmp[j])/2./delti[theta];
                   6168:        }
                   6169:                        
                   6170:      } /* End theta */
1.279     brouard  6171:      
                   6172:      /* We got the gradient matrix for each theta and state j */               
1.218     brouard  6173:      trgradg =ma3x(0,nhstepm,1,nlstate,1,npar); /* veij */
                   6174:                
                   6175:      for(h=0; h<=nhstepm; h++) /* veij */
                   6176:        for(j=1; j<=nlstate;j++)
                   6177:         for(theta=1; theta <=npar; theta++)
                   6178:           trgradg[h][j][theta]=gradg[h][theta][j];
                   6179:                
                   6180:      for(j=nlstate+1; j<=nlstate+ndeath;j++) /* mu */
                   6181:        for(theta=1; theta <=npar; theta++)
                   6182:         trgradgp[j][theta]=gradgp[theta][j];
1.279     brouard  6183:      /**< as well as its transposed matrix 
                   6184:       */               
1.218     brouard  6185:                
                   6186:      hf=hstepm*stepm/YEARM;  /* Duration of hstepm expressed in year unit. */
                   6187:      for(i=1;i<=nlstate;i++)
                   6188:        for(j=1;j<=nlstate;j++)
                   6189:         vareij[i][j][(int)age] =0.;
1.279     brouard  6190: 
                   6191:      /* Computing trgradg by matcov by gradg at age and summing over h
                   6192:       * and k (nhstepm) formula 15 of article
                   6193:       * Lievre-Brouard-Heathcote
                   6194:       */
                   6195:      
1.218     brouard  6196:      for(h=0;h<=nhstepm;h++){
                   6197:        for(k=0;k<=nhstepm;k++){
                   6198:         matprod2(dnewm,trgradg[h],1,nlstate,1,npar,1,npar,matcov);
                   6199:         matprod2(doldm,dnewm,1,nlstate,1,npar,1,nlstate,gradg[k]);
                   6200:         for(i=1;i<=nlstate;i++)
                   6201:           for(j=1;j<=nlstate;j++)
                   6202:             vareij[i][j][(int)age] += doldm[i][j]*hf*hf;
                   6203:        }
                   6204:      }
                   6205:                
1.279     brouard  6206:      /* pptj is p.3 or p.j = trgradgp by cov by gradgp, variance of
                   6207:       * p.j overall mortality formula 49 but computed directly because
                   6208:       * we compute the grad (wix pijx) instead of grad (pijx),even if
                   6209:       * wix is independent of theta.
                   6210:       */
1.218     brouard  6211:      matprod2(dnewmp,trgradgp,nlstate+1,nlstate+ndeath,1,npar,1,npar,matcov);
                   6212:      matprod2(doldmp,dnewmp,nlstate+1,nlstate+ndeath,1,npar,nlstate+1,nlstate+ndeath,gradgp);
                   6213:      for(j=nlstate+1;j<=nlstate+ndeath;j++)
                   6214:        for(i=nlstate+1;i<=nlstate+ndeath;i++)
                   6215:         varppt[j][i]=doldmp[j][i];
                   6216:      /* end ppptj */
                   6217:      /*  x centered again */
                   6218:                
1.242     brouard  6219:      prevalim(prlim,nlstate,x,age,oldm,savm,ftolpl,ncvyearp,ij, nres);
1.218     brouard  6220:                
                   6221:      if (popbased==1) {
                   6222:        if(mobilav ==0){
                   6223:         for(i=1; i<=nlstate;i++)
                   6224:           prlim[i][i]=probs[(int)age][i][ij];
                   6225:        }else{ /* mobilav */ 
                   6226:         for(i=1; i<=nlstate;i++)
                   6227:           prlim[i][i]=mobaverage[(int)age][i][ij];
                   6228:        }
                   6229:      }
                   6230:                
                   6231:      /* This for computing probability of death (h=1 means
                   6232:        computed over hstepm (estepm) matrices product = hstepm*stepm months) 
                   6233:        as a weighted average of prlim.
                   6234:      */
1.235     brouard  6235:      hpxij(p3mat,nhstepm,age,hstepm,x,nlstate,stepm,oldm,savm, ij, nres);  
1.218     brouard  6236:      for(j=nlstate+1;j<=nlstate+ndeath;j++){
                   6237:        for(i=1,gmp[j]=0.;i<= nlstate; i++) 
                   6238:         gmp[j] += prlim[i][i]*p3mat[i][j][1]; 
                   6239:      }    
                   6240:      /* end probability of death */
                   6241:                
                   6242:      fprintf(ficresprobmorprev,"%3d %d ",(int) age, ij);
                   6243:      for(j=nlstate+1; j<=(nlstate+ndeath);j++){
                   6244:        fprintf(ficresprobmorprev," %11.3e %11.3e",gmp[j], sqrt(varppt[j][j]));
                   6245:        for(i=1; i<=nlstate;i++){
                   6246:         fprintf(ficresprobmorprev," %11.3e %11.3e ",prlim[i][i],p3mat[i][j][1]);
                   6247:        }
                   6248:      } 
                   6249:      fprintf(ficresprobmorprev,"\n");
                   6250:                
                   6251:      fprintf(ficresvij,"%.0f ",age );
                   6252:      for(i=1; i<=nlstate;i++)
                   6253:        for(j=1; j<=nlstate;j++){
                   6254:         fprintf(ficresvij," %.4f", vareij[i][j][(int)age]);
                   6255:        }
                   6256:      fprintf(ficresvij,"\n");
                   6257:      free_matrix(gp,0,nhstepm,1,nlstate);
                   6258:      free_matrix(gm,0,nhstepm,1,nlstate);
                   6259:      free_ma3x(gradg,0,nhstepm,1,npar,1,nlstate);
                   6260:      free_ma3x(trgradg,0,nhstepm,1,nlstate,1,npar);
                   6261:      free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   6262:    } /* End age */
                   6263:    free_vector(gpp,nlstate+1,nlstate+ndeath);
                   6264:    free_vector(gmp,nlstate+1,nlstate+ndeath);
                   6265:    free_matrix(gradgp,1,npar,nlstate+1,nlstate+ndeath);
                   6266:    free_matrix(trgradgp,nlstate+1,nlstate+ndeath,1,npar); /* mu or p point j*/
                   6267:    /* fprintf(ficgp,"\nunset parametric;unset label; set ter png small size 320, 240"); */
                   6268:    fprintf(ficgp,"\nunset parametric;unset label; set ter svg size 640, 480");
                   6269:    /* for(j=nlstate+1; j<= nlstate+ndeath; j++){ *//* Only the first actually */
                   6270:    fprintf(ficgp,"\n set log y; unset log x;set xlabel \"Age\"; set ylabel \"Force of mortality (year-1)\";");
                   6271:    fprintf(ficgp,"\nset out \"%s%s.svg\";",subdirf3(optionfilefiname,"VARMUPTJGR-",digitp),digit);
                   6272:    /*   fprintf(ficgp,"\n plot \"%s\"  u 1:($3*%6.3f) not w l 1 ",fileresprobmorprev,YEARM/estepm); */
                   6273:    /*   fprintf(ficgp,"\n replot \"%s\"  u 1:(($3+1.96*$4)*%6.3f) t \"95\%% interval\" w l 2 ",fileresprobmorprev,YEARM/estepm); */
                   6274:    /*   fprintf(ficgp,"\n replot \"%s\"  u 1:(($3-1.96*$4)*%6.3f) not w l 2 ",fileresprobmorprev,YEARM/estepm); */
                   6275:    fprintf(ficgp,"\n plot \"%s\"  u 1:($3) not w l lt 1 ",subdirf(fileresprobmorprev));
                   6276:    fprintf(ficgp,"\n replot \"%s\"  u 1:(($3+1.96*$4)) t \"95%% interval\" w l lt 2 ",subdirf(fileresprobmorprev));
                   6277:    fprintf(ficgp,"\n replot \"%s\"  u 1:(($3-1.96*$4)) not w l lt 2 ",subdirf(fileresprobmorprev));
                   6278:    fprintf(fichtm,"\n<br> File (multiple files are possible if covariates are present): <A href=\"%s\">%s</a>\n",subdirf(fileresprobmorprev),subdirf(fileresprobmorprev));
                   6279:    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);
                   6280:    /*  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  6281:     */
1.218     brouard  6282:    /*   fprintf(ficgp,"\nset out \"varmuptjgr%s%s%s.svg\";replot;",digitp,optionfilefiname,digit); */
                   6283:    fprintf(ficgp,"\nset out;\nset out \"%s%s.svg\";replot;set out;\n",subdirf3(optionfilefiname,"VARMUPTJGR-",digitp),digit);
1.126     brouard  6284: 
1.218     brouard  6285:    free_vector(xp,1,npar);
                   6286:    free_matrix(doldm,1,nlstate,1,nlstate);
                   6287:    free_matrix(dnewm,1,nlstate,1,npar);
                   6288:    free_matrix(doldmp,nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
                   6289:    free_matrix(dnewmp,nlstate+1,nlstate+ndeath,1,npar);
                   6290:    free_matrix(varppt,nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
                   6291:    /* if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX); */
                   6292:    fclose(ficresprobmorprev);
                   6293:    fflush(ficgp);
                   6294:    fflush(fichtm); 
                   6295:  }  /* end varevsij */
1.126     brouard  6296: 
                   6297: /************ Variance of prevlim ******************/
1.269     brouard  6298:  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  6299: {
1.205     brouard  6300:   /* Variance of prevalence limit  for each state ij using current parameters x[] and estimates of neighbourhood give by delti*/
1.126     brouard  6301:   /*  double **prevalim(double **prlim, int nlstate, double *xp, double age, double **oldm, double **savm,double ftolpl);*/
1.164     brouard  6302: 
1.268     brouard  6303:   double **dnewmpar,**doldm;
1.126     brouard  6304:   int i, j, nhstepm, hstepm;
                   6305:   double *xp;
                   6306:   double *gp, *gm;
                   6307:   double **gradg, **trgradg;
1.208     brouard  6308:   double **mgm, **mgp;
1.126     brouard  6309:   double age,agelim;
                   6310:   int theta;
                   6311:   
                   6312:   pstamp(ficresvpl);
1.288     brouard  6313:   fprintf(ficresvpl,"# Standard deviation of period (forward stable) prevalences \n");
1.241     brouard  6314:   fprintf(ficresvpl,"# Age ");
                   6315:   if(nresult >=1)
                   6316:     fprintf(ficresvpl," Result# ");
1.126     brouard  6317:   for(i=1; i<=nlstate;i++)
                   6318:       fprintf(ficresvpl," %1d-%1d",i,i);
                   6319:   fprintf(ficresvpl,"\n");
                   6320: 
                   6321:   xp=vector(1,npar);
1.268     brouard  6322:   dnewmpar=matrix(1,nlstate,1,npar);
1.126     brouard  6323:   doldm=matrix(1,nlstate,1,nlstate);
                   6324:   
                   6325:   hstepm=1*YEARM; /* Every year of age */
                   6326:   hstepm=hstepm/stepm; /* Typically in stepm units, if j= 2 years, = 2/6 months = 4 */ 
                   6327:   agelim = AGESUP;
                   6328:   for (age=bage; age<=fage; age ++){ /* If stepm=6 months */
                   6329:     nhstepm=(int) rint((agelim-age)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */ 
                   6330:     if (stepm >= YEARM) hstepm=1;
                   6331:     nhstepm = nhstepm/hstepm; /* Typically 40/4=10 */
                   6332:     gradg=matrix(1,npar,1,nlstate);
1.208     brouard  6333:     mgp=matrix(1,npar,1,nlstate);
                   6334:     mgm=matrix(1,npar,1,nlstate);
1.126     brouard  6335:     gp=vector(1,nlstate);
                   6336:     gm=vector(1,nlstate);
                   6337: 
                   6338:     for(theta=1; theta <=npar; theta++){
                   6339:       for(i=1; i<=npar; i++){ /* Computes gradient */
                   6340:        xp[i] = x[i] + (i==theta ?delti[theta]:0);
                   6341:       }
1.288     brouard  6342:       /* if((int)age==79 ||(int)age== 80 ||(int)age== 81 ) */
                   6343:       /*       prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp,ij,nres); */
                   6344:       /* else */
                   6345:       prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp,ij,nres);
1.208     brouard  6346:       for(i=1;i<=nlstate;i++){
1.126     brouard  6347:        gp[i] = prlim[i][i];
1.208     brouard  6348:        mgp[theta][i] = prlim[i][i];
                   6349:       }
1.126     brouard  6350:       for(i=1; i<=npar; i++) /* Computes gradient */
                   6351:        xp[i] = x[i] - (i==theta ?delti[theta]:0);
1.288     brouard  6352:       /* if((int)age==79 ||(int)age== 80 ||(int)age== 81 ) */
                   6353:       /*       prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp,ij,nres); */
                   6354:       /* else */
                   6355:       prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp,ij,nres);
1.208     brouard  6356:       for(i=1;i<=nlstate;i++){
1.126     brouard  6357:        gm[i] = prlim[i][i];
1.208     brouard  6358:        mgm[theta][i] = prlim[i][i];
                   6359:       }
1.126     brouard  6360:       for(i=1;i<=nlstate;i++)
                   6361:        gradg[theta][i]= (gp[i]-gm[i])/2./delti[theta];
1.209     brouard  6362:       /* gradg[theta][2]= -gradg[theta][1]; */ /* For testing if nlstate=2 */
1.126     brouard  6363:     } /* End theta */
                   6364: 
                   6365:     trgradg =matrix(1,nlstate,1,npar);
                   6366: 
                   6367:     for(j=1; j<=nlstate;j++)
                   6368:       for(theta=1; theta <=npar; theta++)
                   6369:        trgradg[j][theta]=gradg[theta][j];
1.209     brouard  6370:     /* if((int)age==79 ||(int)age== 80 ||(int)age== 81 ){ */
                   6371:     /*   printf("\nmgm mgp %d ",(int)age); */
                   6372:     /*   for(j=1; j<=nlstate;j++){ */
                   6373:     /*         printf(" %d ",j); */
                   6374:     /*         for(theta=1; theta <=npar; theta++) */
                   6375:     /*           printf(" %d %lf %lf",theta,mgm[theta][j],mgp[theta][j]); */
                   6376:     /*         printf("\n "); */
                   6377:     /*   } */
                   6378:     /* } */
                   6379:     /* if((int)age==79 ||(int)age== 80 ||(int)age== 81 ){ */
                   6380:     /*   printf("\n gradg %d ",(int)age); */
                   6381:     /*   for(j=1; j<=nlstate;j++){ */
                   6382:     /*         printf("%d ",j); */
                   6383:     /*         for(theta=1; theta <=npar; theta++) */
                   6384:     /*           printf("%d %lf ",theta,gradg[theta][j]); */
                   6385:     /*         printf("\n "); */
                   6386:     /*   } */
                   6387:     /* } */
1.126     brouard  6388: 
                   6389:     for(i=1;i<=nlstate;i++)
                   6390:       varpl[i][(int)age] =0.;
1.209     brouard  6391:     if((int)age==79 ||(int)age== 80  ||(int)age== 81){
1.268     brouard  6392:     matprod2(dnewmpar,trgradg,1,nlstate,1,npar,1,npar,matcov);
                   6393:     matprod2(doldm,dnewmpar,1,nlstate,1,npar,1,nlstate,gradg);
1.205     brouard  6394:     }else{
1.268     brouard  6395:     matprod2(dnewmpar,trgradg,1,nlstate,1,npar,1,npar,matcov);
                   6396:     matprod2(doldm,dnewmpar,1,nlstate,1,npar,1,nlstate,gradg);
1.205     brouard  6397:     }
1.126     brouard  6398:     for(i=1;i<=nlstate;i++)
                   6399:       varpl[i][(int)age] = doldm[i][i]; /* Covariances are useless */
                   6400: 
                   6401:     fprintf(ficresvpl,"%.0f ",age );
1.241     brouard  6402:     if(nresult >=1)
                   6403:       fprintf(ficresvpl,"%d ",nres );
1.288     brouard  6404:     for(i=1; i<=nlstate;i++){
1.126     brouard  6405:       fprintf(ficresvpl," %.5f (%.5f)",prlim[i][i],sqrt(varpl[i][(int)age]));
1.288     brouard  6406:       /* for(j=1;j<=nlstate;j++) */
                   6407:       /*       fprintf(ficresvpl," %d %.5f ",j,prlim[j][i]); */
                   6408:     }
1.126     brouard  6409:     fprintf(ficresvpl,"\n");
                   6410:     free_vector(gp,1,nlstate);
                   6411:     free_vector(gm,1,nlstate);
1.208     brouard  6412:     free_matrix(mgm,1,npar,1,nlstate);
                   6413:     free_matrix(mgp,1,npar,1,nlstate);
1.126     brouard  6414:     free_matrix(gradg,1,npar,1,nlstate);
                   6415:     free_matrix(trgradg,1,nlstate,1,npar);
                   6416:   } /* End age */
                   6417: 
                   6418:   free_vector(xp,1,npar);
                   6419:   free_matrix(doldm,1,nlstate,1,npar);
1.268     brouard  6420:   free_matrix(dnewmpar,1,nlstate,1,nlstate);
                   6421: 
                   6422: }
                   6423: 
                   6424: 
                   6425: /************ Variance of backprevalence limit ******************/
1.269     brouard  6426:  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  6427: {
                   6428:   /* Variance of backward prevalence limit  for each state ij using current parameters x[] and estimates of neighbourhood give by delti*/
                   6429:   /*  double **prevalim(double **prlim, int nlstate, double *xp, double age, double **oldm, double **savm,double ftolpl);*/
                   6430: 
                   6431:   double **dnewmpar,**doldm;
                   6432:   int i, j, nhstepm, hstepm;
                   6433:   double *xp;
                   6434:   double *gp, *gm;
                   6435:   double **gradg, **trgradg;
                   6436:   double **mgm, **mgp;
                   6437:   double age,agelim;
                   6438:   int theta;
                   6439:   
                   6440:   pstamp(ficresvbl);
                   6441:   fprintf(ficresvbl,"# Standard deviation of back (stable) prevalences \n");
                   6442:   fprintf(ficresvbl,"# Age ");
                   6443:   if(nresult >=1)
                   6444:     fprintf(ficresvbl," Result# ");
                   6445:   for(i=1; i<=nlstate;i++)
                   6446:       fprintf(ficresvbl," %1d-%1d",i,i);
                   6447:   fprintf(ficresvbl,"\n");
                   6448: 
                   6449:   xp=vector(1,npar);
                   6450:   dnewmpar=matrix(1,nlstate,1,npar);
                   6451:   doldm=matrix(1,nlstate,1,nlstate);
                   6452:   
                   6453:   hstepm=1*YEARM; /* Every year of age */
                   6454:   hstepm=hstepm/stepm; /* Typically in stepm units, if j= 2 years, = 2/6 months = 4 */ 
                   6455:   agelim = AGEINF;
                   6456:   for (age=fage; age>=bage; age --){ /* If stepm=6 months */
                   6457:     nhstepm=(int) rint((age-agelim)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */ 
                   6458:     if (stepm >= YEARM) hstepm=1;
                   6459:     nhstepm = nhstepm/hstepm; /* Typically 40/4=10 */
                   6460:     gradg=matrix(1,npar,1,nlstate);
                   6461:     mgp=matrix(1,npar,1,nlstate);
                   6462:     mgm=matrix(1,npar,1,nlstate);
                   6463:     gp=vector(1,nlstate);
                   6464:     gm=vector(1,nlstate);
                   6465: 
                   6466:     for(theta=1; theta <=npar; theta++){
                   6467:       for(i=1; i<=npar; i++){ /* Computes gradient */
                   6468:        xp[i] = x[i] + (i==theta ?delti[theta]:0);
                   6469:       }
                   6470:       if(mobilavproj > 0 )
                   6471:        bprevalim(bprlim, mobaverage,nlstate,xp,age,ftolpl,ncvyearp,ij,nres);
                   6472:       else
                   6473:        bprevalim(bprlim, mobaverage,nlstate,xp,age,ftolpl,ncvyearp,ij,nres);
                   6474:       for(i=1;i<=nlstate;i++){
                   6475:        gp[i] = bprlim[i][i];
                   6476:        mgp[theta][i] = bprlim[i][i];
                   6477:       }
                   6478:      for(i=1; i<=npar; i++) /* Computes gradient */
                   6479:        xp[i] = x[i] - (i==theta ?delti[theta]:0);
                   6480:        if(mobilavproj > 0 )
                   6481:        bprevalim(bprlim, mobaverage,nlstate,xp,age,ftolpl,ncvyearp,ij,nres);
                   6482:        else
                   6483:        bprevalim(bprlim, mobaverage,nlstate,xp,age,ftolpl,ncvyearp,ij,nres);
                   6484:       for(i=1;i<=nlstate;i++){
                   6485:        gm[i] = bprlim[i][i];
                   6486:        mgm[theta][i] = bprlim[i][i];
                   6487:       }
                   6488:       for(i=1;i<=nlstate;i++)
                   6489:        gradg[theta][i]= (gp[i]-gm[i])/2./delti[theta];
                   6490:       /* gradg[theta][2]= -gradg[theta][1]; */ /* For testing if nlstate=2 */
                   6491:     } /* End theta */
                   6492: 
                   6493:     trgradg =matrix(1,nlstate,1,npar);
                   6494: 
                   6495:     for(j=1; j<=nlstate;j++)
                   6496:       for(theta=1; theta <=npar; theta++)
                   6497:        trgradg[j][theta]=gradg[theta][j];
                   6498:     /* if((int)age==79 ||(int)age== 80 ||(int)age== 81 ){ */
                   6499:     /*   printf("\nmgm mgp %d ",(int)age); */
                   6500:     /*   for(j=1; j<=nlstate;j++){ */
                   6501:     /*         printf(" %d ",j); */
                   6502:     /*         for(theta=1; theta <=npar; theta++) */
                   6503:     /*           printf(" %d %lf %lf",theta,mgm[theta][j],mgp[theta][j]); */
                   6504:     /*         printf("\n "); */
                   6505:     /*   } */
                   6506:     /* } */
                   6507:     /* if((int)age==79 ||(int)age== 80 ||(int)age== 81 ){ */
                   6508:     /*   printf("\n gradg %d ",(int)age); */
                   6509:     /*   for(j=1; j<=nlstate;j++){ */
                   6510:     /*         printf("%d ",j); */
                   6511:     /*         for(theta=1; theta <=npar; theta++) */
                   6512:     /*           printf("%d %lf ",theta,gradg[theta][j]); */
                   6513:     /*         printf("\n "); */
                   6514:     /*   } */
                   6515:     /* } */
                   6516: 
                   6517:     for(i=1;i<=nlstate;i++)
                   6518:       varbpl[i][(int)age] =0.;
                   6519:     if((int)age==79 ||(int)age== 80  ||(int)age== 81){
                   6520:     matprod2(dnewmpar,trgradg,1,nlstate,1,npar,1,npar,matcov);
                   6521:     matprod2(doldm,dnewmpar,1,nlstate,1,npar,1,nlstate,gradg);
                   6522:     }else{
                   6523:     matprod2(dnewmpar,trgradg,1,nlstate,1,npar,1,npar,matcov);
                   6524:     matprod2(doldm,dnewmpar,1,nlstate,1,npar,1,nlstate,gradg);
                   6525:     }
                   6526:     for(i=1;i<=nlstate;i++)
                   6527:       varbpl[i][(int)age] = doldm[i][i]; /* Covariances are useless */
                   6528: 
                   6529:     fprintf(ficresvbl,"%.0f ",age );
                   6530:     if(nresult >=1)
                   6531:       fprintf(ficresvbl,"%d ",nres );
                   6532:     for(i=1; i<=nlstate;i++)
                   6533:       fprintf(ficresvbl," %.5f (%.5f)",bprlim[i][i],sqrt(varbpl[i][(int)age]));
                   6534:     fprintf(ficresvbl,"\n");
                   6535:     free_vector(gp,1,nlstate);
                   6536:     free_vector(gm,1,nlstate);
                   6537:     free_matrix(mgm,1,npar,1,nlstate);
                   6538:     free_matrix(mgp,1,npar,1,nlstate);
                   6539:     free_matrix(gradg,1,npar,1,nlstate);
                   6540:     free_matrix(trgradg,1,nlstate,1,npar);
                   6541:   } /* End age */
                   6542: 
                   6543:   free_vector(xp,1,npar);
                   6544:   free_matrix(doldm,1,nlstate,1,npar);
                   6545:   free_matrix(dnewmpar,1,nlstate,1,nlstate);
1.126     brouard  6546: 
                   6547: }
                   6548: 
                   6549: /************ Variance of one-step probabilities  ******************/
                   6550: 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  6551:  {
                   6552:    int i, j=0,  k1, l1, tj;
                   6553:    int k2, l2, j1,  z1;
                   6554:    int k=0, l;
                   6555:    int first=1, first1, first2;
                   6556:    double cv12, mu1, mu2, lc1, lc2, v12, v21, v11, v22,v1,v2, c12, tnalp;
                   6557:    double **dnewm,**doldm;
                   6558:    double *xp;
                   6559:    double *gp, *gm;
                   6560:    double **gradg, **trgradg;
                   6561:    double **mu;
                   6562:    double age, cov[NCOVMAX+1];
                   6563:    double std=2.0; /* Number of standard deviation wide of confidence ellipsoids */
                   6564:    int theta;
                   6565:    char fileresprob[FILENAMELENGTH];
                   6566:    char fileresprobcov[FILENAMELENGTH];
                   6567:    char fileresprobcor[FILENAMELENGTH];
                   6568:    double ***varpij;
                   6569: 
                   6570:    strcpy(fileresprob,"PROB_"); 
                   6571:    strcat(fileresprob,fileres);
                   6572:    if((ficresprob=fopen(fileresprob,"w"))==NULL) {
                   6573:      printf("Problem with resultfile: %s\n", fileresprob);
                   6574:      fprintf(ficlog,"Problem with resultfile: %s\n", fileresprob);
                   6575:    }
                   6576:    strcpy(fileresprobcov,"PROBCOV_"); 
                   6577:    strcat(fileresprobcov,fileresu);
                   6578:    if((ficresprobcov=fopen(fileresprobcov,"w"))==NULL) {
                   6579:      printf("Problem with resultfile: %s\n", fileresprobcov);
                   6580:      fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobcov);
                   6581:    }
                   6582:    strcpy(fileresprobcor,"PROBCOR_"); 
                   6583:    strcat(fileresprobcor,fileresu);
                   6584:    if((ficresprobcor=fopen(fileresprobcor,"w"))==NULL) {
                   6585:      printf("Problem with resultfile: %s\n", fileresprobcor);
                   6586:      fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobcor);
                   6587:    }
                   6588:    printf("Computing standard deviation of one-step probabilities: result on file '%s' \n",fileresprob);
                   6589:    fprintf(ficlog,"Computing standard deviation of one-step probabilities: result on file '%s' \n",fileresprob);
                   6590:    printf("Computing matrix of variance covariance of one-step probabilities: result on file '%s' \n",fileresprobcov);
                   6591:    fprintf(ficlog,"Computing matrix of variance covariance of one-step probabilities: result on file '%s' \n",fileresprobcov);
                   6592:    printf("and correlation matrix of one-step probabilities: result on file '%s' \n",fileresprobcor);
                   6593:    fprintf(ficlog,"and correlation matrix of one-step probabilities: result on file '%s' \n",fileresprobcor);
                   6594:    pstamp(ficresprob);
                   6595:    fprintf(ficresprob,"#One-step probabilities and stand. devi in ()\n");
                   6596:    fprintf(ficresprob,"# Age");
                   6597:    pstamp(ficresprobcov);
                   6598:    fprintf(ficresprobcov,"#One-step probabilities and covariance matrix\n");
                   6599:    fprintf(ficresprobcov,"# Age");
                   6600:    pstamp(ficresprobcor);
                   6601:    fprintf(ficresprobcor,"#One-step probabilities and correlation matrix\n");
                   6602:    fprintf(ficresprobcor,"# Age");
1.126     brouard  6603: 
                   6604: 
1.222     brouard  6605:    for(i=1; i<=nlstate;i++)
                   6606:      for(j=1; j<=(nlstate+ndeath);j++){
                   6607:        fprintf(ficresprob," p%1d-%1d (SE)",i,j);
                   6608:        fprintf(ficresprobcov," p%1d-%1d ",i,j);
                   6609:        fprintf(ficresprobcor," p%1d-%1d ",i,j);
                   6610:      }  
                   6611:    /* fprintf(ficresprob,"\n");
                   6612:       fprintf(ficresprobcov,"\n");
                   6613:       fprintf(ficresprobcor,"\n");
                   6614:    */
                   6615:    xp=vector(1,npar);
                   6616:    dnewm=matrix(1,(nlstate)*(nlstate+ndeath),1,npar);
                   6617:    doldm=matrix(1,(nlstate)*(nlstate+ndeath),1,(nlstate)*(nlstate+ndeath));
                   6618:    mu=matrix(1,(nlstate)*(nlstate+ndeath), (int) bage, (int)fage);
                   6619:    varpij=ma3x(1,nlstate*(nlstate+ndeath),1,nlstate*(nlstate+ndeath),(int) bage, (int) fage);
                   6620:    first=1;
                   6621:    fprintf(ficgp,"\n# Routine varprob");
                   6622:    fprintf(fichtm,"\n<li><h4> Computing and drawing one step probabilities with their confidence intervals</h4></li>\n");
                   6623:    fprintf(fichtm,"\n");
                   6624: 
1.288     brouard  6625:    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  6626:    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);
                   6627:    fprintf(fichtmcov,"\nEllipsoids of confidence centered on point (p<inf>ij</inf>, p<inf>kl</inf>) are estimated \
1.126     brouard  6628: and drawn. It helps understanding how is the covariance between two incidences.\
                   6629:  They are expressed in year<sup>-1</sup> in order to be less dependent of stepm.<br>\n");
1.222     brouard  6630:    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  6631: It can be understood this way: if pij and pkl where uncorrelated the (2x2) matrix of covariance \
                   6632: would have been (1/(var pij), 0 , 0, 1/(var pkl)), and the confidence interval would be 2 \
                   6633: standard deviations wide on each axis. <br>\
                   6634:  Now, if both incidences are correlated (usual case) we diagonalised the inverse of the covariance matrix\
                   6635:  and made the appropriate rotation to look at the uncorrelated principal directions.<br>\
                   6636: To be simple, these graphs help to understand the significativity of each parameter in relation to a second other one.<br> \n");
                   6637: 
1.222     brouard  6638:    cov[1]=1;
                   6639:    /* tj=cptcoveff; */
1.225     brouard  6640:    tj = (int) pow(2,cptcoveff);
1.222     brouard  6641:    if (cptcovn<1) {tj=1;ncodemax[1]=1;}
                   6642:    j1=0;
1.224     brouard  6643:    for(j1=1; j1<=tj;j1++){  /* For each valid combination of covariates or only once*/
1.222     brouard  6644:      if  (cptcovn>0) {
                   6645:        fprintf(ficresprob, "\n#********** Variable "); 
1.225     brouard  6646:        for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresprob, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
1.222     brouard  6647:        fprintf(ficresprob, "**********\n#\n");
                   6648:        fprintf(ficresprobcov, "\n#********** Variable "); 
1.225     brouard  6649:        for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresprobcov, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
1.222     brouard  6650:        fprintf(ficresprobcov, "**********\n#\n");
1.220     brouard  6651:                        
1.222     brouard  6652:        fprintf(ficgp, "\n#********** Variable "); 
1.225     brouard  6653:        for (z1=1; z1<=cptcoveff; z1++) fprintf(ficgp, " V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
1.222     brouard  6654:        fprintf(ficgp, "**********\n#\n");
1.220     brouard  6655:                        
                   6656:                        
1.222     brouard  6657:        fprintf(fichtmcov, "\n<hr  size=\"2\" color=\"#EC5E5E\">********** Variable "); 
1.225     brouard  6658:        for (z1=1; z1<=cptcoveff; z1++) fprintf(fichtm, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
1.222     brouard  6659:        fprintf(fichtmcov, "**********\n<hr size=\"2\" color=\"#EC5E5E\">");
1.220     brouard  6660:                        
1.222     brouard  6661:        fprintf(ficresprobcor, "\n#********** Variable ");    
1.225     brouard  6662:        for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresprobcor, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
1.222     brouard  6663:        fprintf(ficresprobcor, "**********\n#");    
                   6664:        if(invalidvarcomb[j1]){
                   6665:         fprintf(ficgp,"\n#Combination (%d) ignored because no cases \n",j1); 
                   6666:         fprintf(fichtmcov,"\n<h3>Combination (%d) ignored because no cases </h3>\n",j1); 
                   6667:         continue;
                   6668:        }
                   6669:      }
                   6670:      gradg=matrix(1,npar,1,(nlstate)*(nlstate+ndeath));
                   6671:      trgradg=matrix(1,(nlstate)*(nlstate+ndeath),1,npar);
                   6672:      gp=vector(1,(nlstate)*(nlstate+ndeath));
                   6673:      gm=vector(1,(nlstate)*(nlstate+ndeath));
                   6674:      for (age=bage; age<=fage; age ++){ 
                   6675:        cov[2]=age;
                   6676:        if(nagesqr==1)
                   6677:         cov[3]= age*age;
                   6678:        for (k=1; k<=cptcovn;k++) {
                   6679:         cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(j1,k)];
                   6680:         /*cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(j1,Tvar[k])];*//* j1 1 2 3 4
                   6681:                                                                    * 1  1 1 1 1
                   6682:                                                                    * 2  2 1 1 1
                   6683:                                                                    * 3  1 2 1 1
                   6684:                                                                    */
                   6685:         /* nbcode[1][1]=0 nbcode[1][2]=1;*/
                   6686:        }
                   6687:        /* for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2]; */
                   6688:        for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,k)]*cov[2];
                   6689:        for (k=1; k<=cptcovprod;k++)
                   6690:         cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)]*nbcode[Tvard[k][2]][codtabm(ij,k)];
1.220     brouard  6691:                        
                   6692:                        
1.222     brouard  6693:        for(theta=1; theta <=npar; theta++){
                   6694:         for(i=1; i<=npar; i++)
                   6695:           xp[i] = x[i] + (i==theta ?delti[theta]:(double)0);
1.220     brouard  6696:                                
1.222     brouard  6697:         pmij(pmmij,cov,ncovmodel,xp,nlstate);
1.220     brouard  6698:                                
1.222     brouard  6699:         k=0;
                   6700:         for(i=1; i<= (nlstate); i++){
                   6701:           for(j=1; j<=(nlstate+ndeath);j++){
                   6702:             k=k+1;
                   6703:             gp[k]=pmmij[i][j];
                   6704:           }
                   6705:         }
1.220     brouard  6706:                                
1.222     brouard  6707:         for(i=1; i<=npar; i++)
                   6708:           xp[i] = x[i] - (i==theta ?delti[theta]:(double)0);
1.220     brouard  6709:                                
1.222     brouard  6710:         pmij(pmmij,cov,ncovmodel,xp,nlstate);
                   6711:         k=0;
                   6712:         for(i=1; i<=(nlstate); i++){
                   6713:           for(j=1; j<=(nlstate+ndeath);j++){
                   6714:             k=k+1;
                   6715:             gm[k]=pmmij[i][j];
                   6716:           }
                   6717:         }
1.220     brouard  6718:                                
1.222     brouard  6719:         for(i=1; i<= (nlstate)*(nlstate+ndeath); i++) 
                   6720:           gradg[theta][i]=(gp[i]-gm[i])/(double)2./delti[theta];  
                   6721:        }
1.126     brouard  6722: 
1.222     brouard  6723:        for(j=1; j<=(nlstate)*(nlstate+ndeath);j++)
                   6724:         for(theta=1; theta <=npar; theta++)
                   6725:           trgradg[j][theta]=gradg[theta][j];
1.220     brouard  6726:                        
1.222     brouard  6727:        matprod2(dnewm,trgradg,1,(nlstate)*(nlstate+ndeath),1,npar,1,npar,matcov); 
                   6728:        matprod2(doldm,dnewm,1,(nlstate)*(nlstate+ndeath),1,npar,1,(nlstate)*(nlstate+ndeath),gradg);
1.220     brouard  6729:                        
1.222     brouard  6730:        pmij(pmmij,cov,ncovmodel,x,nlstate);
1.220     brouard  6731:                        
1.222     brouard  6732:        k=0;
                   6733:        for(i=1; i<=(nlstate); i++){
                   6734:         for(j=1; j<=(nlstate+ndeath);j++){
                   6735:           k=k+1;
                   6736:           mu[k][(int) age]=pmmij[i][j];
                   6737:         }
                   6738:        }
                   6739:        for(i=1;i<=(nlstate)*(nlstate+ndeath);i++)
                   6740:         for(j=1;j<=(nlstate)*(nlstate+ndeath);j++)
                   6741:           varpij[i][j][(int)age] = doldm[i][j];
1.220     brouard  6742:                        
1.222     brouard  6743:        /*printf("\n%d ",(int)age);
                   6744:         for (i=1; i<=(nlstate)*(nlstate+ndeath);i++){
                   6745:         printf("%e [%e ;%e] ",gm[i],gm[i]-2*sqrt(doldm[i][i]),gm[i]+2*sqrt(doldm[i][i]));
                   6746:         fprintf(ficlog,"%e [%e ;%e] ",gm[i],gm[i]-2*sqrt(doldm[i][i]),gm[i]+2*sqrt(doldm[i][i]));
                   6747:         }*/
1.220     brouard  6748:                        
1.222     brouard  6749:        fprintf(ficresprob,"\n%d ",(int)age);
                   6750:        fprintf(ficresprobcov,"\n%d ",(int)age);
                   6751:        fprintf(ficresprobcor,"\n%d ",(int)age);
1.220     brouard  6752:                        
1.222     brouard  6753:        for (i=1; i<=(nlstate)*(nlstate+ndeath);i++)
                   6754:         fprintf(ficresprob,"%11.3e (%11.3e) ",mu[i][(int) age],sqrt(varpij[i][i][(int)age]));
                   6755:        for (i=1; i<=(nlstate)*(nlstate+ndeath);i++){
                   6756:         fprintf(ficresprobcov,"%11.3e ",mu[i][(int) age]);
                   6757:         fprintf(ficresprobcor,"%11.3e ",mu[i][(int) age]);
                   6758:        }
                   6759:        i=0;
                   6760:        for (k=1; k<=(nlstate);k++){
                   6761:         for (l=1; l<=(nlstate+ndeath);l++){ 
                   6762:           i++;
                   6763:           fprintf(ficresprobcov,"\n%d %d-%d",(int)age,k,l);
                   6764:           fprintf(ficresprobcor,"\n%d %d-%d",(int)age,k,l);
                   6765:           for (j=1; j<=i;j++){
                   6766:             /* printf(" k=%d l=%d i=%d j=%d\n",k,l,i,j);fflush(stdout); */
                   6767:             fprintf(ficresprobcov," %11.3e",varpij[i][j][(int)age]);
                   6768:             fprintf(ficresprobcor," %11.3e",varpij[i][j][(int) age]/sqrt(varpij[i][i][(int) age])/sqrt(varpij[j][j][(int)age]));
                   6769:           }
                   6770:         }
                   6771:        }/* end of loop for state */
                   6772:      } /* end of loop for age */
                   6773:      free_vector(gp,1,(nlstate+ndeath)*(nlstate+ndeath));
                   6774:      free_vector(gm,1,(nlstate+ndeath)*(nlstate+ndeath));
                   6775:      free_matrix(trgradg,1,(nlstate+ndeath)*(nlstate+ndeath),1,npar);
                   6776:      free_matrix(gradg,1,(nlstate+ndeath)*(nlstate+ndeath),1,npar);
                   6777:     
                   6778:      /* Confidence intervalle of pij  */
                   6779:      /*
                   6780:        fprintf(ficgp,"\nunset parametric;unset label");
                   6781:        fprintf(ficgp,"\nset log y;unset log x; set xlabel \"Age\";set ylabel \"probability (year-1)\"");
                   6782:        fprintf(ficgp,"\nset ter png small\nset size 0.65,0.65");
                   6783:        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);
                   6784:        fprintf(fichtm,"\n<br><img src=\"pijgr%s.png\"> ",optionfilefiname);
                   6785:        fprintf(ficgp,"\nset out \"pijgr%s.png\"",optionfilefiname);
                   6786:        fprintf(ficgp,"\nplot \"%s\" every :::%d::%d u 1:2 \"\%%lf",k1,k2,xfilevarprob);
                   6787:      */
                   6788:                
                   6789:      /* Drawing ellipsoids of confidence of two variables p(k1-l1,k2-l2)*/
                   6790:      first1=1;first2=2;
                   6791:      for (k2=1; k2<=(nlstate);k2++){
                   6792:        for (l2=1; l2<=(nlstate+ndeath);l2++){ 
                   6793:         if(l2==k2) continue;
                   6794:         j=(k2-1)*(nlstate+ndeath)+l2;
                   6795:         for (k1=1; k1<=(nlstate);k1++){
                   6796:           for (l1=1; l1<=(nlstate+ndeath);l1++){ 
                   6797:             if(l1==k1) continue;
                   6798:             i=(k1-1)*(nlstate+ndeath)+l1;
                   6799:             if(i<=j) continue;
                   6800:             for (age=bage; age<=fage; age ++){ 
                   6801:               if ((int)age %5==0){
                   6802:                 v1=varpij[i][i][(int)age]/stepm*YEARM/stepm*YEARM;
                   6803:                 v2=varpij[j][j][(int)age]/stepm*YEARM/stepm*YEARM;
                   6804:                 cv12=varpij[i][j][(int)age]/stepm*YEARM/stepm*YEARM;
                   6805:                 mu1=mu[i][(int) age]/stepm*YEARM ;
                   6806:                 mu2=mu[j][(int) age]/stepm*YEARM;
                   6807:                 c12=cv12/sqrt(v1*v2);
                   6808:                 /* Computing eigen value of matrix of covariance */
                   6809:                 lc1=((v1+v2)+sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
                   6810:                 lc2=((v1+v2)-sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
                   6811:                 if ((lc2 <0) || (lc1 <0) ){
                   6812:                   if(first2==1){
                   6813:                     first1=0;
                   6814:                     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);
                   6815:                   }
                   6816:                   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);
                   6817:                   /* lc1=fabs(lc1); */ /* If we want to have them positive */
                   6818:                   /* lc2=fabs(lc2); */
                   6819:                 }
1.220     brouard  6820:                                                                
1.222     brouard  6821:                 /* Eigen vectors */
1.280     brouard  6822:                 if(1+(v1-lc1)*(v1-lc1)/cv12/cv12 <1.e-5){
                   6823:                   printf(" Error sqrt of a negative number: %lf\n",1+(v1-lc1)*(v1-lc1)/cv12/cv12);
                   6824:                   fprintf(ficlog," Error sqrt of a negative number: %lf\n",1+(v1-lc1)*(v1-lc1)/cv12/cv12);
                   6825:                   v11=(1./sqrt(fabs(1+(v1-lc1)*(v1-lc1)/cv12/cv12)));
                   6826:                 }else
                   6827:                   v11=(1./sqrt(1+(v1-lc1)*(v1-lc1)/cv12/cv12));
1.222     brouard  6828:                 /*v21=sqrt(1.-v11*v11); *//* error */
                   6829:                 v21=(lc1-v1)/cv12*v11;
                   6830:                 v12=-v21;
                   6831:                 v22=v11;
                   6832:                 tnalp=v21/v11;
                   6833:                 if(first1==1){
                   6834:                   first1=0;
                   6835:                   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);
                   6836:                 }
                   6837:                 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);
                   6838:                 /*printf(fignu*/
                   6839:                 /* mu1+ v11*lc1*cost + v12*lc2*sin(t) */
                   6840:                 /* mu2+ v21*lc1*cost + v22*lc2*sin(t) */
                   6841:                 if(first==1){
                   6842:                   first=0;
                   6843:                   fprintf(ficgp,"\n# Ellipsoids of confidence\n#\n");
                   6844:                   fprintf(ficgp,"\nset parametric;unset label");
                   6845:                   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);
                   6846:                   fprintf(ficgp,"\nset ter svg size 640, 480");
1.266     brouard  6847:                   fprintf(fichtmcov,"\n<p><br>Ellipsoids of confidence cov(p%1d%1d,p%1d%1d) expressed in year<sup>-1</sup>\
1.220     brouard  6848:  :<a href=\"%s_%d%1d%1d-%1d%1d.svg\">                                                                                                                                          \
1.201     brouard  6849: %s_%d%1d%1d-%1d%1d.svg</A>, ",k1,l1,k2,l2,\
1.222     brouard  6850:                           subdirf2(optionfilefiname,"VARPIJGR_"), j1,k1,l1,k2,l2,      \
                   6851:                           subdirf2(optionfilefiname,"VARPIJGR_"), j1,k1,l1,k2,l2);
                   6852:                   fprintf(fichtmcov,"\n<br><img src=\"%s_%d%1d%1d-%1d%1d.svg\"> ",subdirf2(optionfilefiname,"VARPIJGR_"), j1,k1,l1,k2,l2);
                   6853:                   fprintf(fichtmcov,"\n<br> Correlation at age %d (%.3f),",(int) age, c12);
                   6854:                   fprintf(ficgp,"\nset out \"%s_%d%1d%1d-%1d%1d.svg\"",subdirf2(optionfilefiname,"VARPIJGR_"), j1,k1,l1,k2,l2);
                   6855:                   fprintf(ficgp,"\nset label \"%d\" at %11.3e,%11.3e center",(int) age, mu1,mu2);
                   6856:                   fprintf(ficgp,"\n# Age %d, p%1d%1d - p%1d%1d",(int) age, k1,l1,k2,l2);
                   6857:                   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  6858:                           mu1,std,v11,sqrt(fabs(lc1)),v12,sqrt(fabs(lc2)), \
                   6859:                           mu2,std,v21,sqrt(fabs(lc1)),v22,sqrt(fabs(lc2))); /* For gnuplot only */
1.222     brouard  6860:                 }else{
                   6861:                   first=0;
                   6862:                   fprintf(fichtmcov," %d (%.3f),",(int) age, c12);
                   6863:                   fprintf(ficgp,"\n# Age %d, p%1d%1d - p%1d%1d",(int) age, k1,l1,k2,l2);
                   6864:                   fprintf(ficgp,"\nset label \"%d\" at %11.3e,%11.3e center",(int) age, mu1,mu2);
                   6865:                   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  6866:                           mu1,std,v11,sqrt(lc1),v12,sqrt(fabs(lc2)),   \
                   6867:                           mu2,std,v21,sqrt(lc1),v22,sqrt(fabs(lc2)));
1.222     brouard  6868:                 }/* if first */
                   6869:               } /* age mod 5 */
                   6870:             } /* end loop age */
                   6871:             fprintf(ficgp,"\nset out;\nset out \"%s_%d%1d%1d-%1d%1d.svg\";replot;set out;",subdirf2(optionfilefiname,"VARPIJGR_"), j1,k1,l1,k2,l2);
                   6872:             first=1;
                   6873:           } /*l12 */
                   6874:         } /* k12 */
                   6875:        } /*l1 */
                   6876:      }/* k1 */
                   6877:    }  /* loop on combination of covariates j1 */
                   6878:    free_ma3x(varpij,1,nlstate,1,nlstate+ndeath,(int) bage, (int)fage);
                   6879:    free_matrix(mu,1,(nlstate+ndeath)*(nlstate+ndeath),(int) bage, (int)fage);
                   6880:    free_matrix(doldm,1,(nlstate)*(nlstate+ndeath),1,(nlstate)*(nlstate+ndeath));
                   6881:    free_matrix(dnewm,1,(nlstate)*(nlstate+ndeath),1,npar);
                   6882:    free_vector(xp,1,npar);
                   6883:    fclose(ficresprob);
                   6884:    fclose(ficresprobcov);
                   6885:    fclose(ficresprobcor);
                   6886:    fflush(ficgp);
                   6887:    fflush(fichtmcov);
                   6888:  }
1.126     brouard  6889: 
                   6890: 
                   6891: /******************* Printing html file ***********/
1.201     brouard  6892: void printinghtml(char fileresu[], char title[], char datafile[], int firstpass, \
1.126     brouard  6893:                  int lastpass, int stepm, int weightopt, char model[],\
                   6894:                  int imx,int jmin, int jmax, double jmeanint,char rfileres[],\
1.296     brouard  6895:                  int popforecast, int mobilav, int prevfcast, int mobilavproj, int prevbcast, int estepm , \
                   6896:                  double jprev1, double mprev1,double anprev1, double dateprev1, double dateprojd, double dateback1, \
                   6897:                  double jprev2, double mprev2,double anprev2, double dateprev2, double dateprojf, double dateback2){
1.237     brouard  6898:   int jj1, k1, i1, cpt, k4, nres;
1.126     brouard  6899: 
                   6900:    fprintf(fichtm,"<ul><li><a href='#firstorder'>Result files (first order: no variance)</a>\n \
                   6901:    <li><a href='#secondorder'>Result files (second order (variance)</a>\n \
                   6902: </ul>");
1.237     brouard  6903:    fprintf(fichtm,"<ul><li> model=1+age+%s\n \
                   6904: </ul>", model);
1.214     brouard  6905:    fprintf(fichtm,"<ul><li><h4><a name='firstorder'>Result files (first order: no variance)</a></h4>\n");
                   6906:    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",
                   6907:           jprev1, mprev1,anprev1,jprev2, mprev2,anprev2,subdirfext3(optionfilefiname,"PHTMFR_",".htm"),subdirfext3(optionfilefiname,"PHTMFR_",".htm"));
                   6908:    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  6909:           jprev1, mprev1,anprev1,jprev2, mprev2,anprev2,subdirfext3(optionfilefiname,"PHTM_",".htm"),subdirfext3(optionfilefiname,"PHTM_",".htm"));
                   6910:    fprintf(fichtm,",  <a href=\"%s\">%s</a> (text file) <br>\n",subdirf2(fileresu,"P_"),subdirf2(fileresu,"P_"));
1.126     brouard  6911:    fprintf(fichtm,"\
                   6912:  - Estimated transition probabilities over %d (stepm) months: <a href=\"%s\">%s</a><br>\n ",
1.201     brouard  6913:           stepm,subdirf2(fileresu,"PIJ_"),subdirf2(fileresu,"PIJ_"));
1.126     brouard  6914:    fprintf(fichtm,"\
1.217     brouard  6915:  - Estimated back transition probabilities over %d (stepm) months: <a href=\"%s\">%s</a><br>\n ",
                   6916:           stepm,subdirf2(fileresu,"PIJB_"),subdirf2(fileresu,"PIJB_"));
                   6917:    fprintf(fichtm,"\
1.288     brouard  6918:  - Period (forward) prevalence in each health state: <a href=\"%s\">%s</a> <br>\n",
1.201     brouard  6919:           subdirf2(fileresu,"PL_"),subdirf2(fileresu,"PL_"));
1.126     brouard  6920:    fprintf(fichtm,"\
1.288     brouard  6921:  - Backward prevalence in each health state: <a href=\"%s\">%s</a> <br>\n",
1.217     brouard  6922:           subdirf2(fileresu,"PLB_"),subdirf2(fileresu,"PLB_"));
                   6923:    fprintf(fichtm,"\
1.211     brouard  6924:  - (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  6925:    <a href=\"%s\">%s</a> <br>\n",
1.201     brouard  6926:           estepm,subdirf2(fileresu,"E_"),subdirf2(fileresu,"E_"));
1.211     brouard  6927:    if(prevfcast==1){
                   6928:      fprintf(fichtm,"\
                   6929:  - Prevalence projections by age and states:                           \
1.201     brouard  6930:    <a href=\"%s\">%s</a> <br>\n</li>", subdirf2(fileresu,"F_"),subdirf2(fileresu,"F_"));
1.211     brouard  6931:    }
1.126     brouard  6932: 
                   6933: 
1.225     brouard  6934:    m=pow(2,cptcoveff);
1.222     brouard  6935:    if (cptcovn < 1) {m=1;ncodemax[1]=1;}
1.126     brouard  6936: 
1.264     brouard  6937:    fprintf(fichtm," \n<ul><li><b>Graphs</b></li><p>");
                   6938: 
                   6939:    jj1=0;
                   6940: 
                   6941:    fprintf(fichtm," \n<ul>");
                   6942:    for(nres=1; nres <= nresult; nres++) /* For each resultline */
                   6943:    for(k1=1; k1<=m;k1++){ /* For each combination of covariate */
                   6944:      if(m != 1 && TKresult[nres]!= k1)
                   6945:        continue;
                   6946:      jj1++;
                   6947:      if (cptcovn > 0) {
                   6948:        fprintf(fichtm,"\n<li><a  size=\"1\" color=\"#EC5E5E\" href=\"#rescov");
                   6949:        for (cpt=1; cpt<=cptcoveff;cpt++){ 
                   6950:         fprintf(fichtm,"_V%d=%d_",Tvresult[nres][cpt],(int)Tresult[nres][cpt]);
                   6951:        }
                   6952:        for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
                   6953:         fprintf(fichtm,"_V%d=%f_",Tvqresult[nres][k4],Tqresult[nres][k4]);
                   6954:        }
                   6955:        fprintf(fichtm,"\">");
                   6956:        
                   6957:        /* if(nqfveff+nqtveff 0) */ /* Test to be done */
                   6958:        fprintf(fichtm,"************ Results for covariates");
                   6959:        for (cpt=1; cpt<=cptcoveff;cpt++){ 
                   6960:         fprintf(fichtm," V%d=%d ",Tvresult[nres][cpt],(int)Tresult[nres][cpt]);
                   6961:        }
                   6962:        for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
                   6963:         fprintf(fichtm," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
                   6964:        }
                   6965:        if(invalidvarcomb[k1]){
                   6966:         fprintf(fichtm," Warning Combination (%d) ignored because no cases ",k1); 
                   6967:         continue;
                   6968:        }
                   6969:        fprintf(fichtm,"</a></li>");
                   6970:      } /* cptcovn >0 */
                   6971:    }
                   6972:      fprintf(fichtm," \n</ul>");
                   6973: 
1.222     brouard  6974:    jj1=0;
1.237     brouard  6975: 
                   6976:    for(nres=1; nres <= nresult; nres++) /* For each resultline */
1.241     brouard  6977:    for(k1=1; k1<=m;k1++){ /* For each combination of covariate */
1.253     brouard  6978:      if(m != 1 && TKresult[nres]!= k1)
1.237     brouard  6979:        continue;
1.220     brouard  6980: 
1.222     brouard  6981:      /* for(i1=1; i1<=ncodemax[k1];i1++){ */
                   6982:      jj1++;
                   6983:      if (cptcovn > 0) {
1.264     brouard  6984:        fprintf(fichtm,"\n<p><a name=\"rescov");
                   6985:        for (cpt=1; cpt<=cptcoveff;cpt++){ 
                   6986:         fprintf(fichtm,"_V%d=%d_",Tvresult[nres][cpt],(int)Tresult[nres][cpt]);
                   6987:        }
                   6988:        for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
                   6989:         fprintf(fichtm,"_V%d=%f_",Tvqresult[nres][k4],Tqresult[nres][k4]);
                   6990:        }
                   6991:        fprintf(fichtm,"\"</a>");
                   6992:  
1.222     brouard  6993:        fprintf(fichtm,"<hr  size=\"2\" color=\"#EC5E5E\">************ Results for covariates");
1.225     brouard  6994:        for (cpt=1; cpt<=cptcoveff;cpt++){ 
1.237     brouard  6995:         fprintf(fichtm," V%d=%d ",Tvresult[nres][cpt],(int)Tresult[nres][cpt]);
                   6996:         printf(" V%d=%d ",Tvresult[nres][cpt],Tresult[nres][cpt]);fflush(stdout);
                   6997:         /* fprintf(fichtm," V%d=%d ",Tvaraff[cpt],nbcode[Tvaraff[cpt]][codtabm(jj1,cpt)]); */
                   6998:         /* printf(" V%d=%d ",Tvaraff[cpt],nbcode[Tvaraff[cpt]][codtabm(jj1,cpt)]);fflush(stdout); */
1.222     brouard  6999:        }
1.237     brouard  7000:        for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
                   7001:        fprintf(fichtm," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
                   7002:        printf(" V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);fflush(stdout);
                   7003:       }
                   7004:        
1.230     brouard  7005:        /* if(nqfveff+nqtveff 0) */ /* Test to be done */
1.222     brouard  7006:        fprintf(fichtm," ************\n<hr size=\"2\" color=\"#EC5E5E\">");
                   7007:        if(invalidvarcomb[k1]){
                   7008:         fprintf(fichtm,"\n<h3>Combination (%d) ignored because no cases </h3>\n",k1); 
                   7009:         printf("\nCombination (%d) ignored because no cases \n",k1); 
                   7010:         continue;
                   7011:        }
                   7012:      }
                   7013:      /* aij, bij */
1.259     brouard  7014:      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  7015: <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  7016:      /* Pij */
1.241     brouard  7017:      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> \
                   7018: <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  7019:      /* Quasi-incidences */
                   7020:      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  7021:  before but expressed in per year i.e. quasi incidences if stepm is small and probabilities too, \
1.211     brouard  7022:  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  7023: 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> \
                   7024: <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  7025:      /* Survival functions (period) in state j */
                   7026:      for(cpt=1; cpt<=nlstate;cpt++){
1.292     brouard  7027:        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  7028: <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  7029:      }
                   7030:      /* State specific survival functions (period) */
                   7031:      for(cpt=1; cpt<=nlstate;cpt++){
1.292     brouard  7032:        fprintf(fichtm,"<br>\n- Survival functions in state %d and in any other live state (total).\
                   7033:  And probability to be observed in various states (up to %d) being in state %d at different ages.      \
1.283     brouard  7034:  <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  7035:      }
1.288     brouard  7036:      /* Period (forward stable) prevalence in each health state */
1.222     brouard  7037:      for(cpt=1; cpt<=nlstate;cpt++){
1.264     brouard  7038:        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> \
                   7039: <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  7040:      }
1.296     brouard  7041:      if(prevbcast==1){
1.288     brouard  7042:        /* Backward prevalence in each health state */
1.222     brouard  7043:        for(cpt=1; cpt<=nlstate;cpt++){
1.264     brouard  7044:         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  7045: <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  7046:        }
1.217     brouard  7047:      }
1.222     brouard  7048:      if(prevfcast==1){
1.288     brouard  7049:        /* Projection of prevalence up to period (forward stable) prevalence in each health state */
1.222     brouard  7050:        for(cpt=1; cpt<=nlstate;cpt++){
1.288     brouard  7051:         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><br> \
1.296     brouard  7052: <img src=\"%s_%d-%d-%d.svg\">", dateprev1, dateprev2, mobilavproj, dateprojd, dateprojf, cpt, cpt, nlstate, subdirf2(optionfilefiname,"PROJ_"),cpt,k1,nres,subdirf2(optionfilefiname,"PROJ_"),cpt,k1,nres,subdirf2(optionfilefiname,"PROJ_"),cpt,k1,nres);
1.222     brouard  7053:        }
                   7054:      }
1.296     brouard  7055:      if(prevbcast==1){
1.268     brouard  7056:       /* Back projection of prevalence up to stable (mixed) back-prevalence in each health state */
                   7057:        for(cpt=1; cpt<=nlstate;cpt++){
1.273     brouard  7058:         fprintf(fichtm,"<br>\n- Back projection of cross-sectional prevalence (estimated with cases observed from %.1f to %.1f and mobil_average=%d), \
                   7059:  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 \
                   7060:  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) \
                   7061: with weights corresponding to observed prevalence at different ages. <a href=\"%s_%d-%d-%d.svg\">%s_%d-%d-%d.svg</a><br> \
                   7062:  <img src=\"%s_%d-%d-%d.svg\">", dateprev1, dateprev2, mobilavproj, dateback1, dateback2, cpt, cpt, nlstate, subdirf2(optionfilefiname,"PROJB_"),cpt,k1,nres,subdirf2(optionfilefiname,"PROJB_"),cpt,k1,nres,subdirf2(optionfilefiname,"PROJB_"),cpt,k1,nres);
1.268     brouard  7063:        }
                   7064:      }
1.220     brouard  7065:         
1.222     brouard  7066:      for(cpt=1; cpt<=nlstate;cpt++) {
1.241     brouard  7067:        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> <br> \
                   7068: <img src=\"%s_%d-%d-%d.svg\">",cpt,nlstate,subdirf2(optionfilefiname,"EXP_"),cpt,k1,nres,subdirf2(optionfilefiname,"EXP_"),cpt,k1,nres,subdirf2(optionfilefiname,"EXP_"),cpt,k1,nres);
1.222     brouard  7069:      }
                   7070:      /* } /\* end i1 *\/ */
                   7071:    }/* End k1 */
                   7072:    fprintf(fichtm,"</ul>");
1.126     brouard  7073: 
1.222     brouard  7074:    fprintf(fichtm,"\
1.126     brouard  7075: \n<br><li><h4> <a name='secondorder'>Result files (second order: variances)</a></h4>\n\
1.193     brouard  7076:  - Parameter file with estimated parameters and covariance matrix: <a href=\"%s\">%s</a> <br> \
1.203     brouard  7077:  - 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  7078: But because parameters are usually highly correlated (a higher incidence of disability \
                   7079: and a higher incidence of recovery can give very close observed transition) it might \
                   7080: be very useful to look not only at linear confidence intervals estimated from the \
                   7081: variances but at the covariance matrix. And instead of looking at the estimated coefficients \
                   7082: (parameters) of the logistic regression, it might be more meaningful to visualize the \
                   7083: covariance matrix of the one-step probabilities. \
                   7084: See page 'Matrix of variance-covariance of one-step probabilities' below. \n", rfileres,rfileres);
1.126     brouard  7085: 
1.222     brouard  7086:    fprintf(fichtm," - Standard deviation of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
                   7087:           subdirf2(fileresu,"PROB_"),subdirf2(fileresu,"PROB_"));
                   7088:    fprintf(fichtm,"\
1.126     brouard  7089:  - Variance-covariance of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
1.222     brouard  7090:           subdirf2(fileresu,"PROBCOV_"),subdirf2(fileresu,"PROBCOV_"));
1.126     brouard  7091: 
1.222     brouard  7092:    fprintf(fichtm,"\
1.126     brouard  7093:  - Correlation matrix of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
1.222     brouard  7094:           subdirf2(fileresu,"PROBCOR_"),subdirf2(fileresu,"PROBCOR_"));
                   7095:    fprintf(fichtm,"\
1.126     brouard  7096:  - 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): \
                   7097:    <a href=\"%s\">%s</a> <br>\n</li>",
1.201     brouard  7098:           estepm,subdirf2(fileresu,"CVE_"),subdirf2(fileresu,"CVE_"));
1.222     brouard  7099:    fprintf(fichtm,"\
1.126     brouard  7100:  - (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): \
                   7101:    <a href=\"%s\">%s</a> <br>\n</li>",
1.201     brouard  7102:           estepm,subdirf2(fileresu,"STDE_"),subdirf2(fileresu,"STDE_"));
1.222     brouard  7103:    fprintf(fichtm,"\
1.288     brouard  7104:  - 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  7105:           estepm, subdirf2(fileresu,"V_"),subdirf2(fileresu,"V_"));
                   7106:    fprintf(fichtm,"\
1.128     brouard  7107:  - 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  7108:           estepm, subdirf2(fileresu,"T_"),subdirf2(fileresu,"T_"));
                   7109:    fprintf(fichtm,"\
1.288     brouard  7110:  - Standard deviation of forward (period) prevalences: <a href=\"%s\">%s</a> <br>\n",\
1.222     brouard  7111:           subdirf2(fileresu,"VPL_"),subdirf2(fileresu,"VPL_"));
1.126     brouard  7112: 
                   7113: /*  if(popforecast==1) fprintf(fichtm,"\n */
                   7114: /*  - Prevalences forecasting: <a href=\"f%s\">f%s</a> <br>\n */
                   7115: /*  - Population forecasting (if popforecast=1): <a href=\"pop%s\">pop%s</a> <br>\n */
                   7116: /*     <br>",fileres,fileres,fileres,fileres); */
                   7117: /*  else  */
                   7118: /*    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  7119:    fflush(fichtm);
                   7120:    fprintf(fichtm," <ul><li><b>Graphs</b></li><p>");
1.126     brouard  7121: 
1.225     brouard  7122:    m=pow(2,cptcoveff);
1.222     brouard  7123:    if (cptcovn < 1) {m=1;ncodemax[1]=1;}
1.126     brouard  7124: 
1.222     brouard  7125:    jj1=0;
1.237     brouard  7126: 
1.241     brouard  7127:    for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.222     brouard  7128:    for(k1=1; k1<=m;k1++){
1.253     brouard  7129:      if(m != 1 && TKresult[nres]!= k1)
1.237     brouard  7130:        continue;
1.222     brouard  7131:      /* for(i1=1; i1<=ncodemax[k1];i1++){ */
                   7132:      jj1++;
1.126     brouard  7133:      if (cptcovn > 0) {
                   7134:        fprintf(fichtm,"<hr  size=\"2\" color=\"#EC5E5E\">************ Results for covariates");
1.225     brouard  7135:        for (cpt=1; cpt<=cptcoveff;cpt++)  /**< cptcoveff number of variables */
1.237     brouard  7136:         fprintf(fichtm," V%d=%d ",Tvresult[nres][cpt],Tresult[nres][cpt]);
                   7137:         /* fprintf(fichtm," V%d=%d ",Tvaraff[cpt],nbcode[Tvaraff[cpt]][codtabm(jj1,cpt)]); */
                   7138:        for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
                   7139:        fprintf(fichtm," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
                   7140:       }
                   7141: 
1.126     brouard  7142:        fprintf(fichtm," ************\n<hr size=\"2\" color=\"#EC5E5E\">");
1.220     brouard  7143: 
1.222     brouard  7144:        if(invalidvarcomb[k1]){
                   7145:         fprintf(fichtm,"\n<h4>Combination (%d) ignored because no cases </h4>\n",k1); 
                   7146:         continue;
                   7147:        }
1.126     brouard  7148:      }
                   7149:      for(cpt=1; cpt<=nlstate;cpt++) {
1.258     brouard  7150:        fprintf(fichtm,"\n<br>- Observed (cross-sectional with mov_average=%d) and period (incidence based) \
1.241     brouard  7151: prevalence (with 95%% confidence interval) in state (%d): <a href=\"%s_%d-%d-%d.svg\"> %s_%d-%d-%d.svg</a>\n <br>\
1.258     brouard  7152: <img src=\"%s_%d-%d-%d.svg\">",mobilav,cpt,subdirf2(optionfilefiname,"V_"),cpt,k1,nres,subdirf2(optionfilefiname,"V_"),cpt,k1,nres,subdirf2(optionfilefiname,"V_"),cpt,k1,nres);  
1.126     brouard  7153:      }
                   7154:      fprintf(fichtm,"\n<br>- Total life expectancy by age and \
1.128     brouard  7155: health expectancies in states (1) and (2). If popbased=1 the smooth (due to the model) \
                   7156: true period expectancies (those weighted with period prevalences are also\
                   7157:  drawn in addition to the population based expectancies computed using\
1.241     brouard  7158:  observed and cahotic prevalences:  <a href=\"%s_%d-%d.svg\">%s_%d-%d.svg</a>\n<br>\
                   7159: <img src=\"%s_%d-%d.svg\">",subdirf2(optionfilefiname,"E_"),k1,nres,subdirf2(optionfilefiname,"E_"),k1,nres,subdirf2(optionfilefiname,"E_"),k1,nres);
1.222     brouard  7160:      /* } /\* end i1 *\/ */
                   7161:    }/* End k1 */
1.241     brouard  7162:   }/* End nres */
1.222     brouard  7163:    fprintf(fichtm,"</ul>");
                   7164:    fflush(fichtm);
1.126     brouard  7165: }
                   7166: 
                   7167: /******************* Gnuplot file **************/
1.296     brouard  7168: 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  7169: 
                   7170:   char dirfileres[132],optfileres[132];
1.264     brouard  7171:   char gplotcondition[132], gplotlabel[132];
1.237     brouard  7172:   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  7173:   int lv=0, vlv=0, kl=0;
1.130     brouard  7174:   int ng=0;
1.201     brouard  7175:   int vpopbased;
1.223     brouard  7176:   int ioffset; /* variable offset for columns */
1.270     brouard  7177:   int iyearc=1; /* variable column for year of projection  */
                   7178:   int iagec=1; /* variable column for age of projection  */
1.235     brouard  7179:   int nres=0; /* Index of resultline */
1.266     brouard  7180:   int istart=1; /* For starting graphs in projections */
1.219     brouard  7181: 
1.126     brouard  7182: /*   if((ficgp=fopen(optionfilegnuplot,"a"))==NULL) { */
                   7183: /*     printf("Problem with file %s",optionfilegnuplot); */
                   7184: /*     fprintf(ficlog,"Problem with file %s",optionfilegnuplot); */
                   7185: /*   } */
                   7186: 
                   7187:   /*#ifdef windows */
                   7188:   fprintf(ficgp,"cd \"%s\" \n",pathc);
1.223     brouard  7189:   /*#endif */
1.225     brouard  7190:   m=pow(2,cptcoveff);
1.126     brouard  7191: 
1.274     brouard  7192:   /* diagram of the model */
                   7193:   fprintf(ficgp,"\n#Diagram of the model \n");
                   7194:   fprintf(ficgp,"\ndelta=0.03;delta2=0.07;unset arrow;\n");
                   7195:   fprintf(ficgp,"yoff=(%d > 2? 0:1);\n",nlstate);
                   7196:   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);
                   7197: 
                   7198:   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);
                   7199:   fprintf(ficgp,"\n#show arrow\nunset label\n");
                   7200:   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);
                   7201:   fprintf(ficgp,"\nset label %d+1 sprintf(\"State %%d\",%d+1) center at 0.,0.  font \"helvetica, 16\" tc rgbcolor \"red\"\n",nlstate,nlstate);
                   7202:   fprintf(ficgp,"\n#show label\nunset border;unset xtics; unset ytics;\n");
                   7203:   fprintf(ficgp,"\n\nset ter svg size 640, 480;set out \"%s_.svg\" \n",subdirf2(optionfilefiname,"D_"));
                   7204:   fprintf(ficgp,"unset log y; plot [-1.2:1.2][yoff-1.2:1.2] 1/0 not; set out;reset;\n");
                   7205: 
1.202     brouard  7206:   /* Contribution to likelihood */
                   7207:   /* Plot the probability implied in the likelihood */
1.223     brouard  7208:   fprintf(ficgp,"\n# Contributions to the Likelihood, mle >=1. For mle=4 no interpolation, pure matrix products.\n#\n");
                   7209:   fprintf(ficgp,"\n set log y; unset log x;set xlabel \"Age\"; set ylabel \"Likelihood (-2Log(L))\";");
                   7210:   /* fprintf(ficgp,"\nset ter svg size 640, 480"); */ /* Too big for svg */
                   7211:   fprintf(ficgp,"\nset ter pngcairo size 640, 480");
1.204     brouard  7212: /* nice for mle=4 plot by number of matrix products.
1.202     brouard  7213:    replot  "rrtest1/toto.txt" u 2:($4 == 1 && $5==2 ? $9 : 1/0):5 t "p12" with point lc 1 */
                   7214: /* replot exp(p1+p2*x)/(1+exp(p1+p2*x)+exp(p3+p4*x)+exp(p5+p6*x)) t "p12(x)"  */
1.223     brouard  7215:   /* fprintf(ficgp,"\nset out \"%s.svg\";",subdirf2(optionfilefiname,"ILK_")); */
                   7216:   fprintf(ficgp,"\nset out \"%s-dest.png\";",subdirf2(optionfilefiname,"ILK_"));
                   7217:   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));
                   7218:   fprintf(ficgp,"\nset out \"%s-ori.png\";",subdirf2(optionfilefiname,"ILK_"));
                   7219:   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));
                   7220:   for (i=1; i<= nlstate ; i ++) {
                   7221:     fprintf(ficgp,"\nset out \"%s-p%dj.png\";set ylabel \"Probability for each individual/wave\";",subdirf2(optionfilefiname,"ILK_"),i);
                   7222:     fprintf(ficgp,"unset log;\n# plot weighted, mean weight should have point size of 0.5\n plot  \"%s\"",subdirf(fileresilk));
                   7223:     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);
                   7224:     for (j=2; j<= nlstate+ndeath ; j ++) {
                   7225:       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);
                   7226:     }
                   7227:     fprintf(ficgp,";\nset out; unset ylabel;\n"); 
                   7228:   }
                   7229:   /* 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 */               
                   7230:   /* fprintf(ficgp,"\nset log y;plot  \"%s\" u 2:(-$11):3 t \"All sample, all transitions\" with dots lc variable",subdirf(fileresilk)); */
                   7231:   /* fprintf(ficgp,"\nreplot  \"%s\" u 2:($3 <= 3 ? -$11 : 1/0):3 t \"First 3 individuals\" with line lc variable", subdirf(fileresilk)); */
                   7232:   fprintf(ficgp,"\nset out;unset log\n");
                   7233:   /* fprintf(ficgp,"\nset out \"%s.svg\"; replot; set out; # bug gnuplot",subdirf2(optionfilefiname,"ILK_")); */
1.202     brouard  7234: 
1.126     brouard  7235:   strcpy(dirfileres,optionfilefiname);
                   7236:   strcpy(optfileres,"vpl");
1.223     brouard  7237:   /* 1eme*/
1.238     brouard  7238:   for (cpt=1; cpt<= nlstate ; cpt ++){ /* For each live state */
                   7239:     for (k1=1; k1<= m ; k1 ++){ /* For each valid combination of covariate */
1.236     brouard  7240:       for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.238     brouard  7241:        /* plot [100000000000000000000:-100000000000000000000] "mysbiaspar/vplrmysbiaspar.txt to check */
1.253     brouard  7242:        if(m != 1 && TKresult[nres]!= k1)
1.238     brouard  7243:          continue;
                   7244:        /* We are interested in selected combination by the resultline */
1.246     brouard  7245:        /* printf("\n# 1st: Period (stable) prevalence with CI: 'VPL_' files and live state =%d ", cpt); */
1.288     brouard  7246:        fprintf(ficgp,"\n# 1st: Forward (stable period) prevalence with CI: 'VPL_' files  and live state =%d ", cpt);
1.264     brouard  7247:        strcpy(gplotlabel,"(");
1.238     brouard  7248:        for (k=1; k<=cptcoveff; k++){    /* For each covariate k get corresponding value lv for combination k1 */
                   7249:          lv= decodtabm(k1,k,cptcoveff); /* Should be the value of the covariate corresponding to k1 combination */
                   7250:          /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   7251:          /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   7252:          /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
                   7253:          vlv= nbcode[Tvaraff[k]][lv]; /* vlv is the value of the covariate lv, 0 or 1 */
                   7254:          /* For each combination of covariate k1 (V1=1, V3=0), we printed the current covariate k and its value vlv */
1.246     brouard  7255:          /* printf(" V%d=%d ",Tvaraff[k],vlv); */
1.238     brouard  7256:          fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv);
1.264     brouard  7257:          sprintf(gplotlabel+strlen(gplotlabel)," V%d=%d ",Tvaraff[k],vlv);
1.238     brouard  7258:        }
                   7259:        for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
1.246     brouard  7260:          /* printf(" V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]); */
1.238     brouard  7261:          fprintf(ficgp," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
1.264     brouard  7262:          sprintf(gplotlabel+strlen(gplotlabel)," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
                   7263:        }
                   7264:        strcpy(gplotlabel+strlen(gplotlabel),")");
1.246     brouard  7265:        /* printf("\n#\n"); */
1.238     brouard  7266:        fprintf(ficgp,"\n#\n");
                   7267:        if(invalidvarcomb[k1]){
1.260     brouard  7268:           /*k1=k1-1;*/ /* To be checked */
1.238     brouard  7269:          fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   7270:          continue;
                   7271:        }
1.235     brouard  7272:       
1.241     brouard  7273:        fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" \n",subdirf2(optionfilefiname,"V_"),cpt,k1,nres);
                   7274:        fprintf(ficgp,"\n#set out \"V_%s_%d-%d-%d.svg\" \n",optionfilefiname,cpt,k1,nres);
1.276     brouard  7275:        /* fprintf(ficgp,"set label \"Alive state %d %s\" at graph 0.98,0.5 center rotate font \"Helvetica,12\"\n",cpt,gplotlabel); */
                   7276:        fprintf(ficgp,"set title \"Alive state %d %s\" font \"Helvetica,12\"\n",cpt,gplotlabel);
1.260     brouard  7277:        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);
                   7278:        /* 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); */
                   7279:       /* k1-1 error should be nres-1*/
1.238     brouard  7280:        for (i=1; i<= nlstate ; i ++) {
                   7281:          if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
                   7282:          else        fprintf(ficgp," %%*lf (%%*lf)");
                   7283:        }
1.288     brouard  7284:        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  7285:        for (i=1; i<= nlstate ; i ++) {
                   7286:          if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
                   7287:          else fprintf(ficgp," %%*lf (%%*lf)");
                   7288:        } 
1.260     brouard  7289:        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  7290:        for (i=1; i<= nlstate ; i ++) {
                   7291:          if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
                   7292:          else fprintf(ficgp," %%*lf (%%*lf)");
                   7293:        }  
1.265     brouard  7294:        /* 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)); */
                   7295:        
                   7296:        fprintf(ficgp,"\" t\"\" w l lt 1,\"%s\" u 1:((",subdirf2(fileresu,"P_"));
                   7297:         if(cptcoveff ==0){
1.271     brouard  7298:          fprintf(ficgp,"$%d)) t 'Observed prevalence in state %d' with line lt 3",      2+3*(cpt-1),  cpt );
1.265     brouard  7299:        }else{
                   7300:          kl=0;
                   7301:          for (k=1; k<=cptcoveff; k++){    /* For each combination of covariate  */
                   7302:            lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate value corresponding to k1 combination and kth covariate */
                   7303:            /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   7304:            /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   7305:            /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
                   7306:            vlv= nbcode[Tvaraff[k]][lv];
                   7307:            kl++;
                   7308:            /* 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 *\/ */
                   7309:            /*6+(cpt-1)*(nlstate+1)+1+(i-1)+(nlstate+1)*nlstate; 6+(1-1)*(2+1)+1+(1-1) +(2+1)*2=13 */ 
                   7310:            /*6+1+(i-1)+(nlstate+1)*nlstate; 6+1+(1-1) +(2+1)*2=13 */ 
                   7311:            /* ''  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*/
                   7312:            if(k==cptcoveff){
                   7313:              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], \
                   7314:                      2+cptcoveff*2+3*(cpt-1),  cpt );  /* 4 or 6 ?*/
                   7315:            }else{
                   7316:              fprintf(ficgp,"$%d==%d && $%d==%d && ",kl+1, Tvaraff[k],kl+1+1,nbcode[Tvaraff[k]][lv]);
                   7317:              kl++;
                   7318:            }
                   7319:          } /* end covariate */
                   7320:        } /* end if no covariate */
                   7321: 
1.296     brouard  7322:        if(prevbcast==1){ /* We need to get the corresponding values of the covariates involved in this combination k1 */
1.238     brouard  7323:          /* 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  7324:          fprintf(ficgp,",\"%s\" u 1:((",subdirf2(fileresu,"PLB_")); /* Age is in 1, nres in 2 to be fixed */
1.238     brouard  7325:          if(cptcoveff ==0){
1.245     brouard  7326:            fprintf(ficgp,"$%d)) t 'Backward prevalence in state %d' with line lt 3",    2+(cpt-1),  cpt );
1.238     brouard  7327:          }else{
                   7328:            kl=0;
                   7329:            for (k=1; k<=cptcoveff; k++){    /* For each combination of covariate  */
                   7330:              lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate value corresponding to k1 combination and kth covariate */
                   7331:              /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   7332:              /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   7333:              /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
                   7334:              vlv= nbcode[Tvaraff[k]][lv];
1.223     brouard  7335:              kl++;
1.238     brouard  7336:              /* 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 *\/ */
                   7337:              /*6+(cpt-1)*(nlstate+1)+1+(i-1)+(nlstate+1)*nlstate; 6+(1-1)*(2+1)+1+(1-1) +(2+1)*2=13 */ 
                   7338:              /*6+1+(i-1)+(nlstate+1)*nlstate; 6+1+(1-1) +(2+1)*2=13 */ 
                   7339:              /* ''  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*/
                   7340:              if(k==cptcoveff){
1.245     brouard  7341:                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  7342:                        2+cptcoveff*2+(cpt-1),  cpt );  /* 4 or 6 ?*/
1.238     brouard  7343:              }else{
                   7344:                fprintf(ficgp,"$%d==%d && $%d==%d && ",kl+1, Tvaraff[k],kl+1+1,nbcode[Tvaraff[k]][lv]);
                   7345:                kl++;
                   7346:              }
                   7347:            } /* end covariate */
                   7348:          } /* end if no covariate */
1.296     brouard  7349:          if(prevbcast == 1){
1.268     brouard  7350:            fprintf(ficgp,", \"%s\" every :::%d::%d u 1:($2==%d ? $3:1/0) \"%%lf %%lf",subdirf2(fileresu,"VBL_"),nres-1,nres-1,nres);
                   7351:            /* k1-1 error should be nres-1*/
                   7352:            for (i=1; i<= nlstate ; i ++) {
                   7353:              if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
                   7354:              else        fprintf(ficgp," %%*lf (%%*lf)");
                   7355:            }
1.271     brouard  7356:            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  7357:            for (i=1; i<= nlstate ; i ++) {
                   7358:              if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
                   7359:              else fprintf(ficgp," %%*lf (%%*lf)");
                   7360:            } 
1.276     brouard  7361:            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  7362:            for (i=1; i<= nlstate ; i ++) {
                   7363:              if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
                   7364:              else fprintf(ficgp," %%*lf (%%*lf)");
                   7365:            } 
1.274     brouard  7366:            fprintf(ficgp,"\" t\"\" w l lt 4");
1.268     brouard  7367:          } /* end if backprojcast */
1.296     brouard  7368:        } /* end if prevbcast */
1.276     brouard  7369:        /* fprintf(ficgp,"\nset out ;unset label;\n"); */
                   7370:        fprintf(ficgp,"\nset out ;unset title;\n");
1.238     brouard  7371:       } /* nres */
1.201     brouard  7372:     } /* k1 */
                   7373:   } /* cpt */
1.235     brouard  7374: 
                   7375:   
1.126     brouard  7376:   /*2 eme*/
1.238     brouard  7377:   for (k1=1; k1<= m ; k1 ++){  
                   7378:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.253     brouard  7379:       if(m != 1 && TKresult[nres]!= k1)
1.238     brouard  7380:        continue;
                   7381:       fprintf(ficgp,"\n# 2nd: Total life expectancy with CI: 't' files ");
1.264     brouard  7382:       strcpy(gplotlabel,"(");
1.238     brouard  7383:       for (k=1; k<=cptcoveff; k++){    /* For each covariate and each value */
1.225     brouard  7384:        lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate number corresponding to k1 combination */
1.223     brouard  7385:        /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   7386:        /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   7387:        /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
                   7388:        vlv= nbcode[Tvaraff[k]][lv];
                   7389:        fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv);
1.264     brouard  7390:        sprintf(gplotlabel+strlen(gplotlabel)," V%d=%d ",Tvaraff[k],vlv);
1.211     brouard  7391:       }
1.237     brouard  7392:       /* for(k=1; k <= ncovds; k++){ */
1.236     brouard  7393:       for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
1.238     brouard  7394:        printf(" V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
1.236     brouard  7395:        fprintf(ficgp," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
1.264     brouard  7396:        sprintf(gplotlabel+strlen(gplotlabel)," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
1.238     brouard  7397:       }
1.264     brouard  7398:       strcpy(gplotlabel+strlen(gplotlabel),")");
1.211     brouard  7399:       fprintf(ficgp,"\n#\n");
1.223     brouard  7400:       if(invalidvarcomb[k1]){
                   7401:        fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   7402:        continue;
                   7403:       }
1.219     brouard  7404:                        
1.241     brouard  7405:       fprintf(ficgp,"\nset out \"%s_%d-%d.svg\" \n",subdirf2(optionfilefiname,"E_"),k1,nres);
1.238     brouard  7406:       for(vpopbased=0; vpopbased <= popbased; vpopbased++){ /* Done for vpopbased=0 and vpopbased=1 if popbased==1*/
1.264     brouard  7407:        fprintf(ficgp,"\nset label \"popbased %d %s\" at graph 0.98,0.5 center rotate font \"Helvetica,12\"\n",vpopbased,gplotlabel);
                   7408:        if(vpopbased==0){
1.238     brouard  7409:          fprintf(ficgp,"set ylabel \"Years\" \nset ter svg size 640, 480\nplot [%.f:%.f] ",ageminpar,fage);
1.264     brouard  7410:        }else
1.238     brouard  7411:          fprintf(ficgp,"\nreplot ");
                   7412:        for (i=1; i<= nlstate+1 ; i ++) {
                   7413:          k=2*i;
1.261     brouard  7414:          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  7415:          for (j=1; j<= nlstate+1 ; j ++) {
                   7416:            if (j==i) fprintf(ficgp," %%lf (%%lf)");
                   7417:            else fprintf(ficgp," %%*lf (%%*lf)");
                   7418:          }   
                   7419:          if (i== 1) fprintf(ficgp,"\" t\"TLE\" w l lt %d, \\\n",i);
                   7420:          else fprintf(ficgp,"\" t\"LE in state (%d)\" w l lt %d, \\\n",i-1,i+1);
1.261     brouard  7421:          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  7422:          for (j=1; j<= nlstate+1 ; j ++) {
                   7423:            if (j==i) fprintf(ficgp," %%lf (%%lf)");
                   7424:            else fprintf(ficgp," %%*lf (%%*lf)");
                   7425:          }   
                   7426:          fprintf(ficgp,"\" t\"\" w l lt 0,");
1.261     brouard  7427:          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  7428:          for (j=1; j<= nlstate+1 ; j ++) {
                   7429:            if (j==i) fprintf(ficgp," %%lf (%%lf)");
                   7430:            else fprintf(ficgp," %%*lf (%%*lf)");
                   7431:          }   
                   7432:          if (i== (nlstate+1)) fprintf(ficgp,"\" t\"\" w l lt 0");
                   7433:          else fprintf(ficgp,"\" t\"\" w l lt 0,\\\n");
                   7434:        } /* state */
                   7435:       } /* vpopbased */
1.264     brouard  7436:       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  7437:     } /* end nres */
                   7438:   } /* k1 end 2 eme*/
                   7439:        
                   7440:        
                   7441:   /*3eme*/
                   7442:   for (k1=1; k1<= m ; k1 ++){
                   7443:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.253     brouard  7444:       if(m != 1 && TKresult[nres]!= k1)
1.238     brouard  7445:        continue;
                   7446: 
                   7447:       for (cpt=1; cpt<= nlstate ; cpt ++) {
1.261     brouard  7448:        fprintf(ficgp,"\n\n# 3d: Life expectancy with EXP_ files:  combination=%d state=%d",k1, cpt);
1.264     brouard  7449:        strcpy(gplotlabel,"(");
1.238     brouard  7450:        for (k=1; k<=cptcoveff; k++){    /* For each covariate and each value */
                   7451:          lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate number corresponding to k1 combination */
                   7452:          /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   7453:          /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   7454:          /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
                   7455:          vlv= nbcode[Tvaraff[k]][lv];
                   7456:          fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv);
1.264     brouard  7457:          sprintf(gplotlabel+strlen(gplotlabel)," V%d=%d ",Tvaraff[k],vlv);
1.238     brouard  7458:        }
                   7459:        for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
                   7460:          fprintf(ficgp," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
1.264     brouard  7461:          sprintf(gplotlabel+strlen(gplotlabel)," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
1.238     brouard  7462:        }       
1.264     brouard  7463:        strcpy(gplotlabel+strlen(gplotlabel),")");
1.238     brouard  7464:        fprintf(ficgp,"\n#\n");
                   7465:        if(invalidvarcomb[k1]){
                   7466:          fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   7467:          continue;
                   7468:        }
                   7469:                        
                   7470:        /*       k=2+nlstate*(2*cpt-2); */
                   7471:        k=2+(nlstate+1)*(cpt-1);
1.241     brouard  7472:        fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" \n",subdirf2(optionfilefiname,"EXP_"),cpt,k1,nres);
1.264     brouard  7473:        fprintf(ficgp,"set label \"%s\" at graph 0.98,0.5 center rotate font \"Helvetica,12\"\n",gplotlabel);
1.238     brouard  7474:        fprintf(ficgp,"set ter svg size 640, 480\n\
1.261     brouard  7475: 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  7476:        /*fprintf(ficgp,",\"e%s\" every :::%d::%d u 1:($%d-2*$%d) \"\%%lf ",fileres,k1-1,k1-1,k,k+1);
                   7477:          for (i=1; i<= nlstate*2 ; i ++) fprintf(ficgp,"\%%lf (\%%lf) ");
                   7478:          fprintf(ficgp,"\" t \"e%d1\" w l",cpt);
                   7479:          fprintf(ficgp,",\"e%s\" every :::%d::%d u 1:($%d+2*$%d) \"\%%lf ",fileres,k1-1,k1-1,k,k+1);
                   7480:          for (i=1; i<= nlstate*2 ; i ++) fprintf(ficgp,"\%%lf (\%%lf) ");
                   7481:          fprintf(ficgp,"\" t \"e%d1\" w l",cpt);
1.219     brouard  7482:                                
1.238     brouard  7483:        */
                   7484:        for (i=1; i< nlstate ; i ++) {
1.261     brouard  7485:          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  7486:          /*    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  7487:                                
1.238     brouard  7488:        } 
1.261     brouard  7489:        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  7490:       }
1.264     brouard  7491:       fprintf(ficgp,"\nunset label;\n");
1.238     brouard  7492:     } /* end nres */
                   7493:   } /* end kl 3eme */
1.126     brouard  7494:   
1.223     brouard  7495:   /* 4eme */
1.201     brouard  7496:   /* Survival functions (period) from state i in state j by initial state i */
1.238     brouard  7497:   for (k1=1; k1<=m; k1++){    /* For each covariate and each value */
                   7498:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.253     brouard  7499:       if(m != 1 && TKresult[nres]!= k1)
1.223     brouard  7500:        continue;
1.238     brouard  7501:       for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each life state cpt*/
1.264     brouard  7502:        strcpy(gplotlabel,"(");
1.238     brouard  7503:        fprintf(ficgp,"\n#\n#\n# Survival functions in state j : 'LIJ_' files, cov=%d state=%d",k1, cpt);
                   7504:        for (k=1; k<=cptcoveff; k++){    /* For each covariate and each value */
                   7505:          lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate number corresponding to k1 combination */
                   7506:          /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   7507:          /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   7508:          /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
                   7509:          vlv= nbcode[Tvaraff[k]][lv];
                   7510:          fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv);
1.264     brouard  7511:          sprintf(gplotlabel+strlen(gplotlabel)," V%d=%d ",Tvaraff[k],vlv);
1.238     brouard  7512:        }
                   7513:        for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
                   7514:          fprintf(ficgp," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
1.264     brouard  7515:          sprintf(gplotlabel+strlen(gplotlabel)," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
1.238     brouard  7516:        }       
1.264     brouard  7517:        strcpy(gplotlabel+strlen(gplotlabel),")");
1.238     brouard  7518:        fprintf(ficgp,"\n#\n");
                   7519:        if(invalidvarcomb[k1]){
                   7520:          fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   7521:          continue;
1.223     brouard  7522:        }
1.238     brouard  7523:       
1.241     brouard  7524:        fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" \n",subdirf2(optionfilefiname,"LIJ_"),cpt,k1,nres);
1.264     brouard  7525:        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  7526:        fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Probability to be alive\" \n\
                   7527: set ter svg size 640, 480\nunset log y\nplot [%.f:%.f]  ", ageminpar, agemaxpar);
                   7528:        k=3;
                   7529:        for (i=1; i<= nlstate ; i ++){
                   7530:          if(i==1){
                   7531:            fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"PIJ_"));
                   7532:          }else{
                   7533:            fprintf(ficgp,", '' ");
                   7534:          }
                   7535:          l=(nlstate+ndeath)*(i-1)+1;
                   7536:          fprintf(ficgp," u ($1==%d ? ($3):1/0):($%d/($%d",k1,k+l+(cpt-1),k+l);
                   7537:          for (j=2; j<= nlstate+ndeath ; j ++)
                   7538:            fprintf(ficgp,"+$%d",k+l+j-1);
                   7539:          fprintf(ficgp,")) t \"l(%d,%d)\" w l",i,cpt);
                   7540:        } /* nlstate */
1.264     brouard  7541:        fprintf(ficgp,"\nset out; unset label;\n");
1.238     brouard  7542:       } /* end cpt state*/ 
                   7543:     } /* end nres */
                   7544:   } /* end covariate k1 */  
                   7545: 
1.220     brouard  7546: /* 5eme */
1.201     brouard  7547:   /* Survival functions (period) from state i in state j by final state j */
1.238     brouard  7548:   for (k1=1; k1<= m ; k1++){ /* For each covariate combination if any */
                   7549:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.253     brouard  7550:       if(m != 1 && TKresult[nres]!= k1)
1.227     brouard  7551:        continue;
1.238     brouard  7552:       for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each inital state  */
1.264     brouard  7553:        strcpy(gplotlabel,"(");
1.238     brouard  7554:        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);
                   7555:        for (k=1; k<=cptcoveff; k++){    /* For each covariate and each value */
                   7556:          lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate number corresponding to k1 combination */
                   7557:          /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   7558:          /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   7559:          /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
                   7560:          vlv= nbcode[Tvaraff[k]][lv];
                   7561:          fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv);
1.264     brouard  7562:          sprintf(gplotlabel+strlen(gplotlabel)," V%d=%d ",Tvaraff[k],vlv);
1.238     brouard  7563:        }
                   7564:        for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
                   7565:          fprintf(ficgp," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
1.264     brouard  7566:          sprintf(gplotlabel+strlen(gplotlabel)," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
1.238     brouard  7567:        }       
1.264     brouard  7568:        strcpy(gplotlabel+strlen(gplotlabel),")");
1.238     brouard  7569:        fprintf(ficgp,"\n#\n");
                   7570:        if(invalidvarcomb[k1]){
                   7571:          fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   7572:          continue;
                   7573:        }
1.227     brouard  7574:       
1.241     brouard  7575:        fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" \n",subdirf2(optionfilefiname,"LIJT_"),cpt,k1,nres);
1.264     brouard  7576:        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  7577:        fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Probability to be alive\" \n\
                   7578: set ter svg size 640, 480\nunset log y\nplot [%.f:%.f]  ", ageminpar, agemaxpar);
                   7579:        k=3;
                   7580:        for (j=1; j<= nlstate ; j ++){ /* Lived in state j */
                   7581:          if(j==1)
                   7582:            fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"PIJ_"));
                   7583:          else
                   7584:            fprintf(ficgp,", '' ");
                   7585:          l=(nlstate+ndeath)*(cpt-1) +j;
                   7586:          fprintf(ficgp," u (($1==%d && (floor($2)%%5 == 0)) ? ($3):1/0):($%d",k1,k+l);
                   7587:          /* for (i=2; i<= nlstate+ndeath ; i ++) */
                   7588:          /*   fprintf(ficgp,"+$%d",k+l+i-1); */
                   7589:          fprintf(ficgp,") t \"l(%d,%d)\" w l",cpt,j);
                   7590:        } /* nlstate */
                   7591:        fprintf(ficgp,", '' ");
                   7592:        fprintf(ficgp," u (($1==%d && (floor($2)%%5 == 0)) ? ($3):1/0):(",k1);
                   7593:        for (j=1; j<= nlstate ; j ++){ /* Lived in state j */
                   7594:          l=(nlstate+ndeath)*(cpt-1) +j;
                   7595:          if(j < nlstate)
                   7596:            fprintf(ficgp,"$%d +",k+l);
                   7597:          else
                   7598:            fprintf(ficgp,"$%d) t\"l(%d,.)\" w l",k+l,cpt);
                   7599:        }
1.264     brouard  7600:        fprintf(ficgp,"\nset out; unset label;\n");
1.238     brouard  7601:       } /* end cpt state*/ 
                   7602:     } /* end covariate */  
                   7603:   } /* end nres */
1.227     brouard  7604:   
1.220     brouard  7605: /* 6eme */
1.202     brouard  7606:   /* CV preval stable (period) for each covariate */
1.237     brouard  7607:   for (k1=1; k1<= m ; k1 ++) /* For each covariate combination if any */
                   7608:   for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.253     brouard  7609:     if(m != 1 && TKresult[nres]!= k1)
1.237     brouard  7610:       continue;
1.255     brouard  7611:     for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each life state of arrival */
1.264     brouard  7612:       strcpy(gplotlabel,"(");      
1.288     brouard  7613:       fprintf(ficgp,"\n#\n#\n#CV preval stable (forward): 'pij' files, covariatecombination#=%d state=%d",k1, cpt);
1.225     brouard  7614:       for (k=1; k<=cptcoveff; k++){    /* For each covariate and each value */
1.227     brouard  7615:        lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate number corresponding to k1 combination */
                   7616:        /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   7617:        /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   7618:        /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
                   7619:        vlv= nbcode[Tvaraff[k]][lv];
                   7620:        fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv);
1.264     brouard  7621:        sprintf(gplotlabel+strlen(gplotlabel)," V%d=%d ",Tvaraff[k],vlv);
1.211     brouard  7622:       }
1.237     brouard  7623:       for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
                   7624:        fprintf(ficgp," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
1.264     brouard  7625:        sprintf(gplotlabel+strlen(gplotlabel)," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
1.237     brouard  7626:       }        
1.264     brouard  7627:       strcpy(gplotlabel+strlen(gplotlabel),")");
1.211     brouard  7628:       fprintf(ficgp,"\n#\n");
1.223     brouard  7629:       if(invalidvarcomb[k1]){
1.227     brouard  7630:        fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   7631:        continue;
1.223     brouard  7632:       }
1.227     brouard  7633:       
1.241     brouard  7634:       fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" \n",subdirf2(optionfilefiname,"P_"),cpt,k1,nres);
1.264     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.126     brouard  7636:       fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Probability\" \n\
1.238     brouard  7637: set ter svg size 640, 480\nunset log y\nplot [%.f:%.f]  ", ageminpar, agemaxpar);
1.211     brouard  7638:       k=3; /* Offset */
1.255     brouard  7639:       for (i=1; i<= nlstate ; i ++){ /* State of origin */
1.227     brouard  7640:        if(i==1)
                   7641:          fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"PIJ_"));
                   7642:        else
                   7643:          fprintf(ficgp,", '' ");
1.255     brouard  7644:        l=(nlstate+ndeath)*(i-1)+1; /* 1, 1+ nlstate+ndeath, 1+2*(nlstate+ndeath) */
1.227     brouard  7645:        fprintf(ficgp," u ($1==%d ? ($3):1/0):($%d/($%d",k1,k+l+(cpt-1),k+l);
                   7646:        for (j=2; j<= nlstate ; j ++)
                   7647:          fprintf(ficgp,"+$%d",k+l+j-1);
                   7648:        fprintf(ficgp,")) t \"prev(%d,%d)\" w l",i,cpt);
1.153     brouard  7649:       } /* nlstate */
1.264     brouard  7650:       fprintf(ficgp,"\nset out; unset label;\n");
1.153     brouard  7651:     } /* end cpt state*/ 
                   7652:   } /* end covariate */  
1.227     brouard  7653:   
                   7654:   
1.220     brouard  7655: /* 7eme */
1.296     brouard  7656:   if(prevbcast == 1){
1.288     brouard  7657:     /* CV backward prevalence  for each covariate */
1.237     brouard  7658:     for (k1=1; k1<= m ; k1 ++) /* For each covariate combination if any */
                   7659:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.253     brouard  7660:       if(m != 1 && TKresult[nres]!= k1)
1.237     brouard  7661:        continue;
1.268     brouard  7662:       for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each life origin state */
1.264     brouard  7663:        strcpy(gplotlabel,"(");      
1.288     brouard  7664:        fprintf(ficgp,"\n#\n#\n#CV Backward stable prevalence: 'pijb' files, covariatecombination#=%d state=%d",k1, cpt);
1.227     brouard  7665:        for (k=1; k<=cptcoveff; k++){    /* For each covariate and each value */
                   7666:          lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate number corresponding to k1 combination */
                   7667:          /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   7668:          /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
1.223     brouard  7669:          /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
1.227     brouard  7670:          vlv= nbcode[Tvaraff[k]][lv];
                   7671:          fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv);
1.264     brouard  7672:          sprintf(gplotlabel+strlen(gplotlabel)," V%d=%d ",Tvaraff[k],vlv);
1.227     brouard  7673:        }
1.237     brouard  7674:        for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
                   7675:          fprintf(ficgp," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
1.264     brouard  7676:          sprintf(gplotlabel+strlen(gplotlabel)," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
1.237     brouard  7677:        }       
1.264     brouard  7678:        strcpy(gplotlabel+strlen(gplotlabel),")");
1.227     brouard  7679:        fprintf(ficgp,"\n#\n");
                   7680:        if(invalidvarcomb[k1]){
                   7681:          fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   7682:          continue;
                   7683:        }
                   7684:        
1.241     brouard  7685:        fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" \n",subdirf2(optionfilefiname,"PB_"),cpt,k1,nres);
1.268     brouard  7686:        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  7687:        fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Probability\" \n\
1.238     brouard  7688: set ter svg size 640, 480\nunset log y\nplot [%.f:%.f]  ", ageminpar, agemaxpar);
1.227     brouard  7689:        k=3; /* Offset */
1.268     brouard  7690:        for (i=1; i<= nlstate ; i ++){ /* State of arrival */
1.227     brouard  7691:          if(i==1)
                   7692:            fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"PIJB_"));
                   7693:          else
                   7694:            fprintf(ficgp,", '' ");
                   7695:          /* l=(nlstate+ndeath)*(i-1)+1; */
1.255     brouard  7696:          l=(nlstate+ndeath)*(cpt-1)+1; /* fixed for i; cpt=1 1, cpt=2 1+ nlstate+ndeath, 1+2*(nlstate+ndeath) */
1.227     brouard  7697:          /* fprintf(ficgp," u ($1==%d ? ($3):1/0):($%d/($%d",k1,k+l+(cpt-1),k+l); /\* a vérifier *\/ */
                   7698:          /* 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  7699:          fprintf(ficgp," u ($1==%d ? ($3):1/0):($%d",k1,k+l+i-1); /* To be verified */
1.227     brouard  7700:          /* for (j=2; j<= nlstate ; j ++) */
                   7701:          /*    fprintf(ficgp,"+$%d",k+l+j-1); */
                   7702:          /*    /\* fprintf(ficgp,"+$%d",k+l+j-1); *\/ */
1.268     brouard  7703:          fprintf(ficgp,") t \"bprev(%d,%d)\" w l",cpt,i);
1.227     brouard  7704:        } /* nlstate */
1.264     brouard  7705:        fprintf(ficgp,"\nset out; unset label;\n");
1.218     brouard  7706:       } /* end cpt state*/ 
                   7707:     } /* end covariate */  
1.296     brouard  7708:   } /* End if prevbcast */
1.218     brouard  7709:   
1.223     brouard  7710:   /* 8eme */
1.218     brouard  7711:   if(prevfcast==1){
1.288     brouard  7712:     /* Projection from cross-sectional to forward stable (period) prevalence for each covariate */
1.218     brouard  7713:     
1.237     brouard  7714:     for (k1=1; k1<= m ; k1 ++) /* For each covariate combination if any */
                   7715:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.253     brouard  7716:       if(m != 1 && TKresult[nres]!= k1)
1.237     brouard  7717:        continue;
1.211     brouard  7718:       for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each life state */
1.264     brouard  7719:        strcpy(gplotlabel,"(");      
1.288     brouard  7720:        fprintf(ficgp,"\n#\n#\n#Projection of prevalence to forward stable prevalence (period): 'PROJ_' files, covariatecombination#=%d state=%d",k1, cpt);
1.227     brouard  7721:        for (k=1; k<=cptcoveff; k++){    /* For each correspondig covariate value  */
                   7722:          lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate value corresponding to k1 combination and kth covariate */
                   7723:          /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   7724:          /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   7725:          /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
                   7726:          vlv= nbcode[Tvaraff[k]][lv];
                   7727:          fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv);
1.264     brouard  7728:          sprintf(gplotlabel+strlen(gplotlabel)," V%d=%d ",Tvaraff[k],vlv);
1.227     brouard  7729:        }
1.237     brouard  7730:        for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
                   7731:          fprintf(ficgp," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
1.264     brouard  7732:          sprintf(gplotlabel+strlen(gplotlabel)," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
1.237     brouard  7733:        }       
1.264     brouard  7734:        strcpy(gplotlabel+strlen(gplotlabel),")");
1.227     brouard  7735:        fprintf(ficgp,"\n#\n");
                   7736:        if(invalidvarcomb[k1]){
                   7737:          fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   7738:          continue;
                   7739:        }
                   7740:        
                   7741:        fprintf(ficgp,"# hpijx=probability over h years, hp.jx is weighted by observed prev\n ");
1.241     brouard  7742:        fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" \n",subdirf2(optionfilefiname,"PROJ_"),cpt,k1,nres);
1.264     brouard  7743:        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  7744:        fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Prevalence\" \n\
1.238     brouard  7745: set ter svg size 640, 480\nunset log y\nplot [%.f:%.f]  ", ageminpar, agemaxpar);
1.266     brouard  7746: 
                   7747:        /* for (i=1; i<= nlstate+1 ; i ++){  /\* nlstate +1 p11 p21 p.1 *\/ */
                   7748:        istart=nlstate+1; /* Could be one if by state, but nlstate+1 is w.i projection only */
                   7749:        /*istart=1;*/ /* Could be one if by state, but nlstate+1 is w.i projection only */
                   7750:        for (i=istart; i<= nlstate+1 ; i ++){  /* nlstate +1 p11 p21 p.1 */
1.227     brouard  7751:          /*#  V1  = 1  V2 =  0 yearproj age p11 p21 p.1 p12 p22 p.2 p13 p23 p.3*/
                   7752:          /*#   1    2   3    4    5      6  7   8   9   10   11 12  13   14  15 */   
                   7753:          /*# yearproj age p11 p21 p.1 p12 p22 p.2 p13 p23 p.3*/
                   7754:          /*#   1       2   3    4    5      6  7   8   9   10   11 12  13   14  15 */   
1.266     brouard  7755:          if(i==istart){
1.227     brouard  7756:            fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"F_"));
                   7757:          }else{
                   7758:            fprintf(ficgp,",\\\n '' ");
                   7759:          }
                   7760:          if(cptcoveff ==0){ /* No covariate */
                   7761:            ioffset=2; /* Age is in 2 */
                   7762:            /*# yearproj age p11 p21 p31 p.1 p12 p22 p32 p.2 p13 p23 p33 p.3 p14 p24 p34 p.4*/
                   7763:            /*#   1       2   3   4   5  6    7  8   9   10  11  12  13  14  15  16  17  18 */
                   7764:            /*# V1  = 1 yearproj age p11 p21 p31 p.1 p12 p22 p32 p.2 p13 p23 p33 p.3 p14 p24 p34 p.4*/
                   7765:            /*#  1    2        3   4   5  6    7  8   9   10  11  12  13  14  15  16  17  18 */
                   7766:            fprintf(ficgp," u %d:(", ioffset); 
1.266     brouard  7767:            if(i==nlstate+1){
1.270     brouard  7768:              fprintf(ficgp," $%d/(1.-$%d)):1 t 'pw.%d' with line lc variable ",        \
1.266     brouard  7769:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1),  ioffset+1+(i-1)+(nlstate+1)*nlstate,cpt );
                   7770:              fprintf(ficgp,",\\\n '' ");
                   7771:              fprintf(ficgp," u %d:(",ioffset); 
1.270     brouard  7772:              fprintf(ficgp," (($1-$2) == %d ) ? $%d/(1.-$%d) : 1/0):1 with labels center not ", \
1.266     brouard  7773:                     offyear,                           \
1.268     brouard  7774:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1),  ioffset+1+(i-1)+(nlstate+1)*nlstate );
1.266     brouard  7775:            }else
1.227     brouard  7776:              fprintf(ficgp," $%d/(1.-$%d)) t 'p%d%d' with line ",      \
                   7777:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1),  ioffset+1+(i-1)+(nlstate+1)*nlstate,i,cpt );
                   7778:          }else{ /* more than 2 covariates */
1.270     brouard  7779:            ioffset=2*cptcoveff+2; /* Age is in 4 or 6 or etc.*/
                   7780:            /*#  V1  = 1  V2 =  0 yearproj age p11 p21 p.1 p12 p22 p.2 p13 p23 p.3*/
                   7781:            /*#   1    2   3    4    5      6  7   8   9   10   11 12  13   14  15 */
                   7782:            iyearc=ioffset-1;
                   7783:            iagec=ioffset;
1.227     brouard  7784:            fprintf(ficgp," u %d:(",ioffset); 
                   7785:            kl=0;
                   7786:            strcpy(gplotcondition,"(");
                   7787:            for (k=1; k<=cptcoveff; k++){    /* For each covariate writing the chain of conditions */
                   7788:              lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate value corresponding to combination k1 and covariate k */
                   7789:              /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   7790:              /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   7791:              /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
                   7792:              vlv= nbcode[Tvaraff[k]][lv]; /* Value of the modality of Tvaraff[k] */
                   7793:              kl++;
                   7794:              sprintf(gplotcondition+strlen(gplotcondition),"$%d==%d && $%d==%d " ,kl,Tvaraff[k], kl+1, nbcode[Tvaraff[k]][lv]);
                   7795:              kl++;
                   7796:              if(k <cptcoveff && cptcoveff>1)
                   7797:                sprintf(gplotcondition+strlen(gplotcondition)," && ");
                   7798:            }
                   7799:            strcpy(gplotcondition+strlen(gplotcondition),")");
                   7800:            /* 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 *\/ */
                   7801:            /*6+(cpt-1)*(nlstate+1)+1+(i-1)+(nlstate+1)*nlstate; 6+(1-1)*(2+1)+1+(1-1) +(2+1)*2=13 */ 
                   7802:            /*6+1+(i-1)+(nlstate+1)*nlstate; 6+1+(1-1) +(2+1)*2=13 */ 
                   7803:            /* ''  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*/
                   7804:            if(i==nlstate+1){
1.270     brouard  7805:              fprintf(ficgp,"%s ? $%d/(1.-$%d) : 1/0):%d t 'p.%d' with line lc variable", gplotcondition, \
                   7806:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1),  ioffset+1+(i-1)+(nlstate+1)*nlstate,iyearc, cpt );
1.266     brouard  7807:              fprintf(ficgp,",\\\n '' ");
1.270     brouard  7808:              fprintf(ficgp," u %d:(",iagec); 
                   7809:              fprintf(ficgp,"%s && (($%d-$%d) == %d ) ? $%d/(1.-$%d) : 1/0):%d with labels center not ", gplotcondition, \
                   7810:                      iyearc, iagec, offyear,                           \
                   7811:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1),  ioffset+1+(i-1)+(nlstate+1)*nlstate, iyearc );
1.266     brouard  7812: /*  '' 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  7813:            }else{
                   7814:              fprintf(ficgp,"%s ? $%d/(1.-$%d) : 1/0) t 'p%d%d' with line ", gplotcondition, \
                   7815:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1), ioffset +1+(i-1)+(nlstate+1)*nlstate,i,cpt );
                   7816:            }
                   7817:          } /* end if covariate */
                   7818:        } /* nlstate */
1.264     brouard  7819:        fprintf(ficgp,"\nset out; unset label;\n");
1.223     brouard  7820:       } /* end cpt state*/
                   7821:     } /* end covariate */
                   7822:   } /* End if prevfcast */
1.227     brouard  7823:   
1.296     brouard  7824:   if(prevbcast==1){
1.268     brouard  7825:     /* Back projection from cross-sectional to stable (mixed) for each covariate */
                   7826:     
                   7827:     for (k1=1; k1<= m ; k1 ++) /* For each covariate combination if any */
                   7828:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
                   7829:       if(m != 1 && TKresult[nres]!= k1)
                   7830:        continue;
                   7831:       for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each life state */
                   7832:        strcpy(gplotlabel,"(");      
                   7833:        fprintf(ficgp,"\n#\n#\n#Back projection of prevalence to stable (mixed) back prevalence: 'BPROJ_' files, covariatecombination#=%d originstate=%d",k1, cpt);
                   7834:        for (k=1; k<=cptcoveff; k++){    /* For each correspondig covariate value  */
                   7835:          lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate value corresponding to k1 combination and kth covariate */
                   7836:          /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   7837:          /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   7838:          /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
                   7839:          vlv= nbcode[Tvaraff[k]][lv];
                   7840:          fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv);
                   7841:          sprintf(gplotlabel+strlen(gplotlabel)," V%d=%d ",Tvaraff[k],vlv);
                   7842:        }
                   7843:        for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
                   7844:          fprintf(ficgp," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
                   7845:          sprintf(gplotlabel+strlen(gplotlabel)," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
                   7846:        }       
                   7847:        strcpy(gplotlabel+strlen(gplotlabel),")");
                   7848:        fprintf(ficgp,"\n#\n");
                   7849:        if(invalidvarcomb[k1]){
                   7850:          fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   7851:          continue;
                   7852:        }
                   7853:        
                   7854:        fprintf(ficgp,"# hbijx=backprobability over h years, hb.jx is weighted by observed prev at destination state\n ");
                   7855:        fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" \n",subdirf2(optionfilefiname,"PROJB_"),cpt,k1,nres);
                   7856:        fprintf(ficgp,"set label \"Origin alive state %d %s\" at graph 0.98,0.5 center rotate font \"Helvetica,12\"\n",cpt,gplotlabel);
                   7857:        fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Prevalence\" \n\
                   7858: set ter svg size 640, 480\nunset log y\nplot [%.f:%.f]  ", ageminpar, agemaxpar);
                   7859: 
                   7860:        /* for (i=1; i<= nlstate+1 ; i ++){  /\* nlstate +1 p11 p21 p.1 *\/ */
                   7861:        istart=nlstate+1; /* Could be one if by state, but nlstate+1 is w.i projection only */
                   7862:        /*istart=1;*/ /* Could be one if by state, but nlstate+1 is w.i projection only */
                   7863:        for (i=istart; i<= nlstate+1 ; i ++){  /* nlstate +1 p11 p21 p.1 */
                   7864:          /*#  V1  = 1  V2 =  0 yearproj age p11 p21 p.1 p12 p22 p.2 p13 p23 p.3*/
                   7865:          /*#   1    2   3    4    5      6  7   8   9   10   11 12  13   14  15 */   
                   7866:          /*# yearproj age p11 p21 p.1 p12 p22 p.2 p13 p23 p.3*/
                   7867:          /*#   1       2   3    4    5      6  7   8   9   10   11 12  13   14  15 */   
                   7868:          if(i==istart){
                   7869:            fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"FB_"));
                   7870:          }else{
                   7871:            fprintf(ficgp,",\\\n '' ");
                   7872:          }
                   7873:          if(cptcoveff ==0){ /* No covariate */
                   7874:            ioffset=2; /* Age is in 2 */
                   7875:            /*# yearproj age p11 p21 p31 p.1 p12 p22 p32 p.2 p13 p23 p33 p.3 p14 p24 p34 p.4*/
                   7876:            /*#   1       2   3   4   5  6    7  8   9   10  11  12  13  14  15  16  17  18 */
                   7877:            /*# V1  = 1 yearproj age p11 p21 p31 p.1 p12 p22 p32 p.2 p13 p23 p33 p.3 p14 p24 p34 p.4*/
                   7878:            /*#  1    2        3   4   5  6    7  8   9   10  11  12  13  14  15  16  17  18 */
                   7879:            fprintf(ficgp," u %d:(", ioffset); 
                   7880:            if(i==nlstate+1){
1.270     brouard  7881:              fprintf(ficgp," $%d/(1.-$%d)):1 t 'bw%d' with line lc variable ", \
1.268     brouard  7882:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1),  ioffset+1+(i-1)+(nlstate+1)*nlstate,cpt );
                   7883:              fprintf(ficgp,",\\\n '' ");
                   7884:              fprintf(ficgp," u %d:(",ioffset); 
1.270     brouard  7885:              fprintf(ficgp," (($1-$2) == %d ) ? $%d : 1/0):1 with labels center not ", \
1.268     brouard  7886:                     offbyear,                          \
                   7887:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1) );
                   7888:            }else
                   7889:              fprintf(ficgp," $%d/(1.-$%d)) t 'b%d%d' with line ",      \
                   7890:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1),  ioffset+1+(i-1)+(nlstate+1)*nlstate,cpt,i );
                   7891:          }else{ /* more than 2 covariates */
1.270     brouard  7892:            ioffset=2*cptcoveff+2; /* Age is in 4 or 6 or etc.*/
                   7893:            /*#  V1  = 1  V2 =  0 yearproj age p11 p21 p.1 p12 p22 p.2 p13 p23 p.3*/
                   7894:            /*#   1    2   3    4    5      6  7   8   9   10   11 12  13   14  15 */
                   7895:            iyearc=ioffset-1;
                   7896:            iagec=ioffset;
1.268     brouard  7897:            fprintf(ficgp," u %d:(",ioffset); 
                   7898:            kl=0;
                   7899:            strcpy(gplotcondition,"(");
                   7900:            for (k=1; k<=cptcoveff; k++){    /* For each covariate writing the chain of conditions */
                   7901:              lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate value corresponding to combination k1 and covariate k */
                   7902:              /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   7903:              /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   7904:              /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
                   7905:              vlv= nbcode[Tvaraff[k]][lv]; /* Value of the modality of Tvaraff[k] */
                   7906:              kl++;
                   7907:              sprintf(gplotcondition+strlen(gplotcondition),"$%d==%d && $%d==%d " ,kl,Tvaraff[k], kl+1, nbcode[Tvaraff[k]][lv]);
                   7908:              kl++;
                   7909:              if(k <cptcoveff && cptcoveff>1)
                   7910:                sprintf(gplotcondition+strlen(gplotcondition)," && ");
                   7911:            }
                   7912:            strcpy(gplotcondition+strlen(gplotcondition),")");
                   7913:            /* 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 *\/ */
                   7914:            /*6+(cpt-1)*(nlstate+1)+1+(i-1)+(nlstate+1)*nlstate; 6+(1-1)*(2+1)+1+(1-1) +(2+1)*2=13 */ 
                   7915:            /*6+1+(i-1)+(nlstate+1)*nlstate; 6+1+(1-1) +(2+1)*2=13 */ 
                   7916:            /* ''  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*/
                   7917:            if(i==nlstate+1){
1.270     brouard  7918:              fprintf(ficgp,"%s ? $%d : 1/0):%d t 'bw%d' with line lc variable", gplotcondition, \
                   7919:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1),iyearc,cpt );
1.268     brouard  7920:              fprintf(ficgp,",\\\n '' ");
1.270     brouard  7921:              fprintf(ficgp," u %d:(",iagec); 
1.268     brouard  7922:              /* fprintf(ficgp,"%s && (($5-$6) == %d ) ? $%d/(1.-$%d) : 1/0):5 with labels center not ", gplotcondition, \ */
1.270     brouard  7923:              fprintf(ficgp,"%s && (($%d-$%d) == %d ) ? $%d : 1/0):%d with labels center not ", gplotcondition, \
                   7924:                      iyearc,iagec,offbyear,                            \
                   7925:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1), iyearc );
1.268     brouard  7926: /*  '' u 6:(($1==1 && $2==0  && $3==2 && $4==0) && (($5-$6) == 1947) ? $10/(1.-$22) : 1/0):5 with labels center boxed not*/
                   7927:            }else{
                   7928:              /* fprintf(ficgp,"%s ? $%d/(1.-$%d) : 1/0) t 'p%d%d' with line ", gplotcondition, \ */
                   7929:              fprintf(ficgp,"%s ? $%d : 1/0) t 'b%d%d' with line ", gplotcondition, \
                   7930:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1), cpt,i );
                   7931:            }
                   7932:          } /* end if covariate */
                   7933:        } /* nlstate */
                   7934:        fprintf(ficgp,"\nset out; unset label;\n");
                   7935:       } /* end cpt state*/
                   7936:     } /* end covariate */
1.296     brouard  7937:   } /* End if prevbcast */
1.268     brouard  7938:   
1.227     brouard  7939:   
1.238     brouard  7940:   /* 9eme writing MLE parameters */
                   7941:   fprintf(ficgp,"\n##############\n#9eme MLE estimated parameters\n#############\n");
1.126     brouard  7942:   for(i=1,jk=1; i <=nlstate; i++){
1.187     brouard  7943:     fprintf(ficgp,"# initial state %d\n",i);
1.126     brouard  7944:     for(k=1; k <=(nlstate+ndeath); k++){
                   7945:       if (k != i) {
1.227     brouard  7946:        fprintf(ficgp,"#   current state %d\n",k);
                   7947:        for(j=1; j <=ncovmodel; j++){
                   7948:          fprintf(ficgp,"p%d=%f; ",jk,p[jk]);
                   7949:          jk++; 
                   7950:        }
                   7951:        fprintf(ficgp,"\n");
1.126     brouard  7952:       }
                   7953:     }
1.223     brouard  7954:   }
1.187     brouard  7955:   fprintf(ficgp,"##############\n#\n");
1.227     brouard  7956:   
1.145     brouard  7957:   /*goto avoid;*/
1.238     brouard  7958:   /* 10eme Graphics of probabilities or incidences using written MLE parameters */
                   7959:   fprintf(ficgp,"\n##############\n#10eme Graphics of probabilities or incidences\n#############\n");
1.187     brouard  7960:   fprintf(ficgp,"# logi(p12/p11)=a12+b12*age+c12age*age+d12*V1+e12*V1*age\n");
                   7961:   fprintf(ficgp,"# logi(p12/p11)=p1 +p2*age +p3*age*age+ p4*V1+ p5*V1*age\n");
                   7962:   fprintf(ficgp,"# logi(p13/p11)=a13+b13*age+c13age*age+d13*V1+e13*V1*age\n");
                   7963:   fprintf(ficgp,"# logi(p13/p11)=p6 +p7*age +p8*age*age+ p9*V1+ p10*V1*age\n");
                   7964:   fprintf(ficgp,"# p12+p13+p14+p11=1=p11(1+exp(a12+b12*age+c12age*age+d12*V1+e12*V1*age)\n");
                   7965:   fprintf(ficgp,"#                      +exp(a13+b13*age+c13age*age+d13*V1+e13*V1*age)+...)\n");
                   7966:   fprintf(ficgp,"# p11=1/(1+exp(a12+b12*age+c12age*age+d12*V1+e12*V1*age)\n");
                   7967:   fprintf(ficgp,"#                      +exp(a13+b13*age+c13age*age+d13*V1+e13*V1*age)+...)\n");
                   7968:   fprintf(ficgp,"# p12=exp(a12+b12*age+c12age*age+d12*V1+e12*V1*age)/\n");
                   7969:   fprintf(ficgp,"#     (1+exp(a12+b12*age+c12age*age+d12*V1+e12*V1*age)\n");
                   7970:   fprintf(ficgp,"#       +exp(a13+b13*age+c13age*age+d13*V1+e13*V1*age))\n");
                   7971:   fprintf(ficgp,"#       +exp(a14+b14*age+c14age*age+d14*V1+e14*V1*age)+...)\n");
                   7972:   fprintf(ficgp,"#\n");
1.223     brouard  7973:   for(ng=1; ng<=3;ng++){ /* Number of graphics: first is logit, 2nd is probabilities, third is incidences per year*/
1.238     brouard  7974:     fprintf(ficgp,"#Number of graphics: first is logit, 2nd is probabilities, third is incidences per year\n");
1.237     brouard  7975:     fprintf(ficgp,"#model=%s \n",model);
1.238     brouard  7976:     fprintf(ficgp,"# Type of graphic ng=%d\n",ng);
1.264     brouard  7977:     fprintf(ficgp,"#   k1=1 to 2^%d=%d\n",cptcoveff,m);/* to be checked */
                   7978:     for(k1=1; k1 <=m; k1++)  /* For each combination of covariate */
1.237     brouard  7979:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.264     brouard  7980:       if(m != 1 && TKresult[nres]!= k1)
1.237     brouard  7981:        continue;
1.264     brouard  7982:       fprintf(ficgp,"\n\n# Combination of dummy  k1=%d which is ",k1);
                   7983:       strcpy(gplotlabel,"(");
1.276     brouard  7984:       /*sprintf(gplotlabel+strlen(gplotlabel)," Dummy combination %d ",k1);*/
1.264     brouard  7985:       for (k=1; k<=cptcoveff; k++){    /* For each correspondig covariate value  */
                   7986:        lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate value corresponding to k1 combination and kth covariate */
                   7987:        /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   7988:        /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   7989:        /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
                   7990:        vlv= nbcode[Tvaraff[k]][lv];
                   7991:        fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv);
                   7992:        sprintf(gplotlabel+strlen(gplotlabel)," V%d=%d ",Tvaraff[k],vlv);
                   7993:       }
1.237     brouard  7994:       for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
                   7995:        fprintf(ficgp," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
1.264     brouard  7996:        sprintf(gplotlabel+strlen(gplotlabel)," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
1.237     brouard  7997:       }        
1.264     brouard  7998:       strcpy(gplotlabel+strlen(gplotlabel),")");
1.237     brouard  7999:       fprintf(ficgp,"\n#\n");
1.264     brouard  8000:       fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" ",subdirf2(optionfilefiname,"PE_"),k1,ng,nres);
1.276     brouard  8001:       fprintf(ficgp,"\nset key outside ");
                   8002:       /* fprintf(ficgp,"\nset label \"%s\" at graph 1.2,0.5 center rotate font \"Helvetica,12\"\n",gplotlabel); */
                   8003:       fprintf(ficgp,"\nset title \"%s\" font \"Helvetica,12\"\n",gplotlabel);
1.223     brouard  8004:       fprintf(ficgp,"\nset ter svg size 640, 480 ");
                   8005:       if (ng==1){
                   8006:        fprintf(ficgp,"\nset ylabel \"Value of the logit of the model\"\n"); /* exp(a12+b12*x) could be nice */
                   8007:        fprintf(ficgp,"\nunset log y");
                   8008:       }else if (ng==2){
                   8009:        fprintf(ficgp,"\nset ylabel \"Probability\"\n");
                   8010:        fprintf(ficgp,"\nset log y");
                   8011:       }else if (ng==3){
                   8012:        fprintf(ficgp,"\nset ylabel \"Quasi-incidence per year\"\n");
                   8013:        fprintf(ficgp,"\nset log y");
                   8014:       }else
                   8015:        fprintf(ficgp,"\nunset title ");
                   8016:       fprintf(ficgp,"\nplot  [%.f:%.f] ",ageminpar,agemaxpar);
                   8017:       i=1;
                   8018:       for(k2=1; k2<=nlstate; k2++) {
                   8019:        k3=i;
                   8020:        for(k=1; k<=(nlstate+ndeath); k++) {
                   8021:          if (k != k2){
                   8022:            switch( ng) {
                   8023:            case 1:
                   8024:              if(nagesqr==0)
                   8025:                fprintf(ficgp," p%d+p%d*x",i,i+1);
                   8026:              else /* nagesqr =1 */
                   8027:                fprintf(ficgp," p%d+p%d*x+p%d*x*x",i,i+1,i+1+nagesqr);
                   8028:              break;
                   8029:            case 2: /* ng=2 */
                   8030:              if(nagesqr==0)
                   8031:                fprintf(ficgp," exp(p%d+p%d*x",i,i+1);
                   8032:              else /* nagesqr =1 */
                   8033:                fprintf(ficgp," exp(p%d+p%d*x+p%d*x*x",i,i+1,i+1+nagesqr);
                   8034:              break;
                   8035:            case 3:
                   8036:              if(nagesqr==0)
                   8037:                fprintf(ficgp," %f*exp(p%d+p%d*x",YEARM/stepm,i,i+1);
                   8038:              else /* nagesqr =1 */
                   8039:                fprintf(ficgp," %f*exp(p%d+p%d*x+p%d*x*x",YEARM/stepm,i,i+1,i+1+nagesqr);
                   8040:              break;
                   8041:            }
                   8042:            ij=1;/* To be checked else nbcode[0][0] wrong */
1.237     brouard  8043:            ijp=1; /* product no age */
                   8044:            /* for(j=3; j <=ncovmodel-nagesqr; j++) { */
                   8045:            for(j=1; j <=cptcovt; j++) { /* For each covariate of the simplified model */
1.223     brouard  8046:              /* printf("Tage[%d]=%d, j=%d\n", ij, Tage[ij], j); */
1.268     brouard  8047:              if(cptcovage >0){ /* V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1, 2 V5 and V1 */
                   8048:                if(j==Tage[ij]) { /* Product by age  To be looked at!!*/
                   8049:                  if(ij <=cptcovage) { /* V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1, 2 V5 and V1 */
                   8050:                    if(DummyV[j]==0){
                   8051:                      fprintf(ficgp,"+p%d*%d*x",i+j+2+nagesqr-1,Tinvresult[nres][Tvar[j]]);;
                   8052:                    }else{ /* quantitative */
                   8053:                      fprintf(ficgp,"+p%d*%f*x",i+j+2+nagesqr-1,Tqinvresult[nres][Tvar[j]]); /* Tqinvresult in decoderesult */
                   8054:                      /* fprintf(ficgp,"+p%d*%d*x",i+j+nagesqr-1,nbcode[Tvar[j-2]][codtabm(k1,Tvar[j-2])]); */
                   8055:                    }
                   8056:                    ij++;
1.237     brouard  8057:                  }
1.268     brouard  8058:                } 
                   8059:              }else if(cptcovprod >0){
                   8060:                if(j==Tprod[ijp]) { /* */ 
                   8061:                  /* printf("Tprod[%d]=%d, j=%d\n", ij, Tprod[ijp], j); */
                   8062:                  if(ijp <=cptcovprod) { /* Product */
                   8063:                    if(DummyV[Tvard[ijp][1]]==0){/* Vn is dummy */
                   8064:                      if(DummyV[Tvard[ijp][2]]==0){/* Vn and Vm are dummy */
                   8065:                        /* 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)]); */
                   8066:                        fprintf(ficgp,"+p%d*%d*%d",i+j+2+nagesqr-1,Tinvresult[nres][Tvard[ijp][1]],Tinvresult[nres][Tvard[ijp][2]]);
                   8067:                      }else{ /* Vn is dummy and Vm is quanti */
                   8068:                        /* fprintf(ficgp,"+p%d*%d*%f",i+j+2+nagesqr-1,nbcode[Tvard[ijp][1]][codtabm(k1,j)],Tqinvresult[nres][Tvard[ijp][2]]); */
                   8069:                        fprintf(ficgp,"+p%d*%d*%f",i+j+2+nagesqr-1,Tinvresult[nres][Tvard[ijp][1]],Tqinvresult[nres][Tvard[ijp][2]]);
                   8070:                      }
                   8071:                    }else{ /* Vn*Vm Vn is quanti */
                   8072:                      if(DummyV[Tvard[ijp][2]]==0){
                   8073:                        fprintf(ficgp,"+p%d*%d*%f",i+j+2+nagesqr-1,Tinvresult[nres][Tvard[ijp][2]],Tqinvresult[nres][Tvard[ijp][1]]);
                   8074:                      }else{ /* Both quanti */
                   8075:                        fprintf(ficgp,"+p%d*%f*%f",i+j+2+nagesqr-1,Tqinvresult[nres][Tvard[ijp][1]],Tqinvresult[nres][Tvard[ijp][2]]);
                   8076:                      }
1.237     brouard  8077:                    }
1.268     brouard  8078:                    ijp++;
1.237     brouard  8079:                  }
1.268     brouard  8080:                } /* end Tprod */
1.237     brouard  8081:              } else{  /* simple covariate */
1.264     brouard  8082:                /* fprintf(ficgp,"+p%d*%d",i+j+2+nagesqr-1,nbcode[Tvar[j]][codtabm(k1,j)]); /\* Valgrind bug nbcode *\/ */
1.237     brouard  8083:                if(Dummy[j]==0){
                   8084:                  fprintf(ficgp,"+p%d*%d",i+j+2+nagesqr-1,Tinvresult[nres][Tvar[j]]); /*  */
                   8085:                }else{ /* quantitative */
                   8086:                  fprintf(ficgp,"+p%d*%f",i+j+2+nagesqr-1,Tqinvresult[nres][Tvar[j]]); /* */
1.264     brouard  8087:                  /* fprintf(ficgp,"+p%d*%d*x",i+j+nagesqr-1,nbcode[Tvar[j-2]][codtabm(k1,Tvar[j-2])]); */
1.223     brouard  8088:                }
1.237     brouard  8089:              } /* end simple */
                   8090:            } /* end j */
1.223     brouard  8091:          }else{
                   8092:            i=i-ncovmodel;
                   8093:            if(ng !=1 ) /* For logit formula of log p11 is more difficult to get */
                   8094:              fprintf(ficgp," (1.");
                   8095:          }
1.227     brouard  8096:          
1.223     brouard  8097:          if(ng != 1){
                   8098:            fprintf(ficgp,")/(1");
1.227     brouard  8099:            
1.264     brouard  8100:            for(cpt=1; cpt <=nlstate; cpt++){ 
1.223     brouard  8101:              if(nagesqr==0)
1.264     brouard  8102:                fprintf(ficgp,"+exp(p%d+p%d*x",k3+(cpt-1)*ncovmodel,k3+(cpt-1)*ncovmodel+1);
1.223     brouard  8103:              else /* nagesqr =1 */
1.264     brouard  8104:                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  8105:               
1.223     brouard  8106:              ij=1;
                   8107:              for(j=3; j <=ncovmodel-nagesqr; j++){
1.268     brouard  8108:                 if(cptcovage >0){ 
                   8109:                   if((j-2)==Tage[ij]) { /* Bug valgrind */
                   8110:                     if(ij <=cptcovage) { /* Bug valgrind */
                   8111:                       fprintf(ficgp,"+p%d*%d*x",k3+(cpt-1)*ncovmodel+1+j-2+nagesqr,nbcode[Tvar[j-2]][codtabm(k1,j-2)]);
                   8112:                       /* fprintf(ficgp,"+p%d*%d*x",k3+(cpt-1)*ncovmodel+1+j-2+nagesqr,nbcode[Tvar[j-2]][codtabm(k1,Tvar[j-2])]); */
                   8113:                       ij++;
                   8114:                     }
                   8115:                   }
                   8116:                 }else
                   8117:                   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  8118:              }
                   8119:              fprintf(ficgp,")");
                   8120:            }
                   8121:            fprintf(ficgp,")");
                   8122:            if(ng ==2)
1.276     brouard  8123:              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  8124:            else /* ng= 3 */
1.276     brouard  8125:              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  8126:          }else{ /* end ng <> 1 */
                   8127:            if( k !=k2) /* logit p11 is hard to draw */
1.276     brouard  8128:              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  8129:          }
                   8130:          if ((k+k2)!= (nlstate*2+ndeath) && ng != 1)
                   8131:            fprintf(ficgp,",");
                   8132:          if (ng == 1 && k!=k2 && (k+k2)!= (nlstate*2+ndeath))
                   8133:            fprintf(ficgp,",");
                   8134:          i=i+ncovmodel;
                   8135:        } /* end k */
                   8136:       } /* end k2 */
1.276     brouard  8137:       /* fprintf(ficgp,"\n set out; unset label;set key default;\n"); */
                   8138:       fprintf(ficgp,"\n set out; unset title;set key default;\n");
1.264     brouard  8139:     } /* end k1 */
1.223     brouard  8140:   } /* end ng */
                   8141:   /* avoid: */
                   8142:   fflush(ficgp); 
1.126     brouard  8143: }  /* end gnuplot */
                   8144: 
                   8145: 
                   8146: /*************** Moving average **************/
1.219     brouard  8147: /* int movingaverage(double ***probs, double bage, double fage, double ***mobaverage, int mobilav, double bageout, double fageout){ */
1.222     brouard  8148:  int movingaverage(double ***probs, double bage, double fage, double ***mobaverage, int mobilav){
1.218     brouard  8149:    
1.222     brouard  8150:    int i, cpt, cptcod;
                   8151:    int modcovmax =1;
                   8152:    int mobilavrange, mob;
                   8153:    int iage=0;
1.288     brouard  8154:    int firstA1=0, firstA2=0;
1.222     brouard  8155: 
1.266     brouard  8156:    double sum=0., sumr=0.;
1.222     brouard  8157:    double age;
1.266     brouard  8158:    double *sumnewp, *sumnewm, *sumnewmr;
                   8159:    double *agemingood, *agemaxgood; 
                   8160:    double *agemingoodr, *agemaxgoodr; 
1.222     brouard  8161:   
                   8162:   
1.278     brouard  8163:    /* modcovmax=2*cptcoveff;  Max number of modalities. We suppose  */
                   8164:    /*             a covariate has 2 modalities, should be equal to ncovcombmax   */
1.222     brouard  8165: 
                   8166:    sumnewp = vector(1,ncovcombmax);
                   8167:    sumnewm = vector(1,ncovcombmax);
1.266     brouard  8168:    sumnewmr = vector(1,ncovcombmax);
1.222     brouard  8169:    agemingood = vector(1,ncovcombmax); 
1.266     brouard  8170:    agemingoodr = vector(1,ncovcombmax);        
1.222     brouard  8171:    agemaxgood = vector(1,ncovcombmax);
1.266     brouard  8172:    agemaxgoodr = vector(1,ncovcombmax);
1.222     brouard  8173: 
                   8174:    for (cptcod=1;cptcod<=ncovcombmax;cptcod++){
1.266     brouard  8175:      sumnewm[cptcod]=0.; sumnewmr[cptcod]=0.;
1.222     brouard  8176:      sumnewp[cptcod]=0.;
1.266     brouard  8177:      agemingood[cptcod]=0, agemingoodr[cptcod]=0;
                   8178:      agemaxgood[cptcod]=0, agemaxgoodr[cptcod]=0;
1.222     brouard  8179:    }
                   8180:    if (cptcovn<1) ncovcombmax=1; /* At least 1 pass */
                   8181:   
1.266     brouard  8182:    if(mobilav==-1 || mobilav==1||mobilav ==3 ||mobilav==5 ||mobilav== 7){
                   8183:      if(mobilav==1 || mobilav==-1) mobilavrange=5; /* default */
1.222     brouard  8184:      else mobilavrange=mobilav;
                   8185:      for (age=bage; age<=fage; age++)
                   8186:        for (i=1; i<=nlstate;i++)
                   8187:         for (cptcod=1;cptcod<=ncovcombmax;cptcod++)
                   8188:           mobaverage[(int)age][i][cptcod]=probs[(int)age][i][cptcod];
                   8189:      /* We keep the original values on the extreme ages bage, fage and for 
                   8190:        fage+1 and bage-1 we use a 3 terms moving average; for fage+2 bage+2
                   8191:        we use a 5 terms etc. until the borders are no more concerned. 
                   8192:      */ 
                   8193:      for (mob=3;mob <=mobilavrange;mob=mob+2){
                   8194:        for (age=bage+(mob-1)/2; age<=fage-(mob-1)/2; age++){
1.266     brouard  8195:         for (cptcod=1;cptcod<=ncovcombmax;cptcod++){
                   8196:           sumnewm[cptcod]=0.;
                   8197:           for (i=1; i<=nlstate;i++){
1.222     brouard  8198:             mobaverage[(int)age][i][cptcod] =probs[(int)age][i][cptcod];
                   8199:             for (cpt=1;cpt<=(mob-1)/2;cpt++){
                   8200:               mobaverage[(int)age][i][cptcod] +=probs[(int)age-cpt][i][cptcod];
                   8201:               mobaverage[(int)age][i][cptcod] +=probs[(int)age+cpt][i][cptcod];
                   8202:             }
                   8203:             mobaverage[(int)age][i][cptcod]=mobaverage[(int)age][i][cptcod]/mob;
1.266     brouard  8204:             sumnewm[cptcod]+=mobaverage[(int)age][i][cptcod];
                   8205:           } /* end i */
                   8206:           if(sumnewm[cptcod] >1.e-3) mobaverage[(int)age][i][cptcod]=mobaverage[(int)age][i][cptcod]/sumnewm[cptcod]; /* Rescaling to sum one */
                   8207:         } /* end cptcod */
1.222     brouard  8208:        }/* end age */
                   8209:      }/* end mob */
1.266     brouard  8210:    }else{
                   8211:      printf("Error internal in movingaverage, mobilav=%d.\n",mobilav);
1.222     brouard  8212:      return -1;
1.266     brouard  8213:    }
                   8214: 
                   8215:    for (cptcod=1;cptcod<=ncovcombmax;cptcod++){ /* for each combination */
1.222     brouard  8216:      /* for (age=bage+(mob-1)/2; age<=fage-(mob-1)/2; age++){ */
                   8217:      if(invalidvarcomb[cptcod]){
                   8218:        printf("\nCombination (%d) ignored because no cases \n",cptcod); 
                   8219:        continue;
                   8220:      }
1.219     brouard  8221: 
1.266     brouard  8222:      for (age=fage-(mob-1)/2; age>=bage+(mob-1)/2; age--){ /*looking for the youngest and oldest good age */
                   8223:        sumnewm[cptcod]=0.;
                   8224:        sumnewmr[cptcod]=0.;
                   8225:        for (i=1; i<=nlstate;i++){
                   8226:         sumnewm[cptcod]+=mobaverage[(int)age][i][cptcod];
                   8227:         sumnewmr[cptcod]+=probs[(int)age][i][cptcod];
                   8228:        }
                   8229:        if(fabs(sumnewmr[cptcod] - 1.) <= 1.e-3) { /* good without smoothing */
                   8230:         agemingoodr[cptcod]=age;
                   8231:        }
                   8232:        if(fabs(sumnewm[cptcod] - 1.) <= 1.e-3) { /* good */
                   8233:           agemingood[cptcod]=age;
                   8234:        }
                   8235:      } /* age */
                   8236:      for (age=bage+(mob-1)/2; age<=fage-(mob-1)/2; age++){ /*looking for the youngest and oldest good age */
1.222     brouard  8237:        sumnewm[cptcod]=0.;
1.266     brouard  8238:        sumnewmr[cptcod]=0.;
1.222     brouard  8239:        for (i=1; i<=nlstate;i++){
                   8240:         sumnewm[cptcod]+=mobaverage[(int)age][i][cptcod];
1.266     brouard  8241:         sumnewmr[cptcod]+=probs[(int)age][i][cptcod];
                   8242:        }
                   8243:        if(fabs(sumnewmr[cptcod] - 1.) <= 1.e-3) { /* good without smoothing */
                   8244:         agemaxgoodr[cptcod]=age;
1.222     brouard  8245:        }
                   8246:        if(fabs(sumnewm[cptcod] - 1.) <= 1.e-3) { /* good */
1.266     brouard  8247:         agemaxgood[cptcod]=age;
                   8248:        }
                   8249:      } /* age */
                   8250:      /* Thus we have agemingood and agemaxgood as well as goodr for raw (preobs) */
                   8251:      /* but they will change */
1.288     brouard  8252:      firstA1=0;firstA2=0;
1.266     brouard  8253:      for (age=fage-(mob-1)/2; age>=bage; age--){/* From oldest to youngest, filling up to the youngest */
                   8254:        sumnewm[cptcod]=0.;
                   8255:        sumnewmr[cptcod]=0.;
                   8256:        for (i=1; i<=nlstate;i++){
                   8257:         sumnewm[cptcod]+=mobaverage[(int)age][i][cptcod];
                   8258:         sumnewmr[cptcod]+=probs[(int)age][i][cptcod];
                   8259:        }
                   8260:        if(mobilav==-1){ /* Forcing raw ages if good else agemingood */
                   8261:         if(fabs(sumnewmr[cptcod] - 1.) <= 1.e-3) { /* good without smoothing */
                   8262:           agemaxgoodr[cptcod]=age;  /* age min */
                   8263:           for (i=1; i<=nlstate;i++)
                   8264:             mobaverage[(int)age][i][cptcod]=probs[(int)age][i][cptcod];
                   8265:         }else{ /* bad we change the value with the values of good ages */
                   8266:           for (i=1; i<=nlstate;i++){
                   8267:             mobaverage[(int)age][i][cptcod]=mobaverage[(int)agemaxgoodr[cptcod]][i][cptcod];
                   8268:           } /* i */
                   8269:         } /* end bad */
                   8270:        }else{
                   8271:         if(fabs(sumnewm[cptcod] - 1.) <= 1.e-3) { /* good */
                   8272:           agemaxgood[cptcod]=age;
                   8273:         }else{ /* bad we change the value with the values of good ages */
                   8274:           for (i=1; i<=nlstate;i++){
                   8275:             mobaverage[(int)age][i][cptcod]=mobaverage[(int)agemaxgood[cptcod]][i][cptcod];
                   8276:           } /* i */
                   8277:         } /* end bad */
                   8278:        }/* end else */
                   8279:        sum=0.;sumr=0.;
                   8280:        for (i=1; i<=nlstate;i++){
                   8281:         sum+=mobaverage[(int)age][i][cptcod];
                   8282:         sumr+=probs[(int)age][i][cptcod];
                   8283:        }
                   8284:        if(fabs(sum - 1.) > 1.e-3) { /* bad */
1.288     brouard  8285:         if(!firstA1){
                   8286:           firstA1=1;
                   8287:           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);
                   8288:         }
                   8289:         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  8290:        } /* end bad */
                   8291:        /* else{ /\* We found some ages summing to one, we will smooth the oldest *\/ */
                   8292:        if(fabs(sumr - 1.) > 1.e-3) { /* bad */
1.288     brouard  8293:         if(!firstA2){
                   8294:           firstA2=1;
                   8295:           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);
                   8296:         }
                   8297:         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  8298:        } /* end bad */
                   8299:      }/* age */
1.266     brouard  8300: 
                   8301:      for (age=bage+(mob-1)/2; age<=fage; age++){/* From youngest, finding the oldest wrong */
1.222     brouard  8302:        sumnewm[cptcod]=0.;
1.266     brouard  8303:        sumnewmr[cptcod]=0.;
1.222     brouard  8304:        for (i=1; i<=nlstate;i++){
                   8305:         sumnewm[cptcod]+=mobaverage[(int)age][i][cptcod];
1.266     brouard  8306:         sumnewmr[cptcod]+=probs[(int)age][i][cptcod];
                   8307:        } 
                   8308:        if(mobilav==-1){ /* Forcing raw ages if good else agemingood */
                   8309:         if(fabs(sumnewmr[cptcod] - 1.) <= 1.e-3) { /* good */
                   8310:           agemingoodr[cptcod]=age;
                   8311:           for (i=1; i<=nlstate;i++)
                   8312:             mobaverage[(int)age][i][cptcod]=probs[(int)age][i][cptcod];
                   8313:         }else{ /* bad we change the value with the values of good ages */
                   8314:           for (i=1; i<=nlstate;i++){
                   8315:             mobaverage[(int)age][i][cptcod]=mobaverage[(int)agemingoodr[cptcod]][i][cptcod];
                   8316:           } /* i */
                   8317:         } /* end bad */
                   8318:        }else{
                   8319:         if(fabs(sumnewm[cptcod] - 1.) <= 1.e-3) { /* good */
                   8320:           agemingood[cptcod]=age;
                   8321:         }else{ /* bad */
                   8322:           for (i=1; i<=nlstate;i++){
                   8323:             mobaverage[(int)age][i][cptcod]=mobaverage[(int)agemingood[cptcod]][i][cptcod];
                   8324:           } /* i */
                   8325:         } /* end bad */
                   8326:        }/* end else */
                   8327:        sum=0.;sumr=0.;
                   8328:        for (i=1; i<=nlstate;i++){
                   8329:         sum+=mobaverage[(int)age][i][cptcod];
                   8330:         sumr+=mobaverage[(int)age][i][cptcod];
1.222     brouard  8331:        }
1.266     brouard  8332:        if(fabs(sum - 1.) > 1.e-3) { /* bad */
1.268     brouard  8333:         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  8334:        } /* end bad */
                   8335:        /* else{ /\* We found some ages summing to one, we will smooth the oldest *\/ */
                   8336:        if(fabs(sumr - 1.) > 1.e-3) { /* bad */
1.268     brouard  8337:         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  8338:        } /* end bad */
                   8339:      }/* age */
1.266     brouard  8340: 
1.222     brouard  8341:                
                   8342:      for (age=bage; age<=fage; age++){
1.235     brouard  8343:        /* printf("%d %d ", cptcod, (int)age); */
1.222     brouard  8344:        sumnewp[cptcod]=0.;
                   8345:        sumnewm[cptcod]=0.;
                   8346:        for (i=1; i<=nlstate;i++){
                   8347:         sumnewp[cptcod]+=probs[(int)age][i][cptcod];
                   8348:         sumnewm[cptcod]+=mobaverage[(int)age][i][cptcod];
                   8349:         /* printf("%.4f %.4f ",probs[(int)age][i][cptcod], mobaverage[(int)age][i][cptcod]); */
                   8350:        }
                   8351:        /* printf("%.4f %.4f \n",sumnewp[cptcod], sumnewm[cptcod]); */
                   8352:      }
                   8353:      /* printf("\n"); */
                   8354:      /* } */
1.266     brouard  8355: 
1.222     brouard  8356:      /* brutal averaging */
1.266     brouard  8357:      /* for (i=1; i<=nlstate;i++){ */
                   8358:      /*   for (age=1; age<=bage; age++){ */
                   8359:      /*         mobaverage[(int)age][i][cptcod]=mobaverage[(int)agemingood[cptcod]][i][cptcod]; */
                   8360:      /*         /\* printf("age=%d i=%d cptcod=%d mobaverage=%.4f \n",(int)age,i, cptcod, mobaverage[(int)age][i][cptcod]); *\/ */
                   8361:      /*   }     */
                   8362:      /*   for (age=fage; age<=AGESUP; age++){ */
                   8363:      /*         mobaverage[(int)age][i][cptcod]=mobaverage[(int)agemaxgood[cptcod]][i][cptcod]; */
                   8364:      /*         /\* printf("age=%d i=%d cptcod=%d mobaverage=%.4f \n",(int)age,i, cptcod, mobaverage[(int)age][i][cptcod]); *\/ */
                   8365:      /*   } */
                   8366:      /* } /\* end i status *\/ */
                   8367:      /* for (i=nlstate+1; i<=nlstate+ndeath;i++){ */
                   8368:      /*   for (age=1; age<=AGESUP; age++){ */
                   8369:      /*         /\*printf("i=%d, age=%d, cptcod=%d\n",i, (int)age, cptcod);*\/ */
                   8370:      /*         mobaverage[(int)age][i][cptcod]=0.; */
                   8371:      /*   } */
                   8372:      /* } */
1.222     brouard  8373:    }/* end cptcod */
1.266     brouard  8374:    free_vector(agemaxgoodr,1, ncovcombmax);
                   8375:    free_vector(agemaxgood,1, ncovcombmax);
                   8376:    free_vector(agemingood,1, ncovcombmax);
                   8377:    free_vector(agemingoodr,1, ncovcombmax);
                   8378:    free_vector(sumnewmr,1, ncovcombmax);
1.222     brouard  8379:    free_vector(sumnewm,1, ncovcombmax);
                   8380:    free_vector(sumnewp,1, ncovcombmax);
                   8381:    return 0;
                   8382:  }/* End movingaverage */
1.218     brouard  8383:  
1.126     brouard  8384: 
1.296     brouard  8385:  
1.126     brouard  8386: /************** Forecasting ******************/
1.296     brouard  8387: /* 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)*/
                   8388: 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){
                   8389:   /* dateintemean, mean date of interviews
                   8390:      dateprojd, year, month, day of starting projection 
                   8391:      dateprojf date of end of projection;year of end of projection (same day and month as proj1).
1.126     brouard  8392:      agemin, agemax range of age
                   8393:      dateprev1 dateprev2 range of dates during which prevalence is computed
                   8394:   */
1.296     brouard  8395:   /* double anprojd, mprojd, jprojd; */
                   8396:   /* double anprojf, mprojf, jprojf; */
1.267     brouard  8397:   int yearp, stepsize, hstepm, nhstepm, j, k, cptcod, i, h, i1, k4, nres=0;
1.126     brouard  8398:   double agec; /* generic age */
1.296     brouard  8399:   double agelim, ppij, yp,yp1,yp2;
1.126     brouard  8400:   double *popeffectif,*popcount;
                   8401:   double ***p3mat;
1.218     brouard  8402:   /* double ***mobaverage; */
1.126     brouard  8403:   char fileresf[FILENAMELENGTH];
                   8404: 
                   8405:   agelim=AGESUP;
1.211     brouard  8406:   /* Compute observed prevalence between dateprev1 and dateprev2 by counting the number of people
                   8407:      in each health status at the date of interview (if between dateprev1 and dateprev2).
                   8408:      We still use firstpass and lastpass as another selection.
                   8409:   */
1.214     brouard  8410:   /* freqsummary(fileres, agemin, agemax, s, agev, nlstate, imx,Tvaraff,nbcode, ncodemax,mint,anint,strstart,\ */
                   8411:   /*         firstpass, lastpass,  stepm,  weightopt, model); */
1.126     brouard  8412:  
1.201     brouard  8413:   strcpy(fileresf,"F_"); 
                   8414:   strcat(fileresf,fileresu);
1.126     brouard  8415:   if((ficresf=fopen(fileresf,"w"))==NULL) {
                   8416:     printf("Problem with forecast resultfile: %s\n", fileresf);
                   8417:     fprintf(ficlog,"Problem with forecast resultfile: %s\n", fileresf);
                   8418:   }
1.235     brouard  8419:   printf("\nComputing forecasting: result on file '%s', please wait... \n", fileresf);
                   8420:   fprintf(ficlog,"\nComputing forecasting: result on file '%s', please wait... \n", fileresf);
1.126     brouard  8421: 
1.225     brouard  8422:   if (cptcoveff==0) ncodemax[cptcoveff]=1;
1.126     brouard  8423: 
                   8424: 
                   8425:   stepsize=(int) (stepm+YEARM-1)/YEARM;
                   8426:   if (stepm<=12) stepsize=1;
                   8427:   if(estepm < stepm){
                   8428:     printf ("Problem %d lower than %d\n",estepm, stepm);
                   8429:   }
1.270     brouard  8430:   else{
                   8431:     hstepm=estepm;   
                   8432:   }
                   8433:   if(estepm > stepm){ /* Yes every two year */
                   8434:     stepsize=2;
                   8435:   }
1.296     brouard  8436:   hstepm=hstepm/stepm;
1.126     brouard  8437: 
1.296     brouard  8438:   
                   8439:   /* yp1=modf(dateintmean,&yp);/\* extracts integral of datemean in yp  and */
                   8440:   /*                              fractional in yp1 *\/ */
                   8441:   /* aintmean=yp; */
                   8442:   /* yp2=modf((yp1*12),&yp); */
                   8443:   /* mintmean=yp; */
                   8444:   /* yp1=modf((yp2*30.5),&yp); */
                   8445:   /* jintmean=yp; */
                   8446:   /* if(jintmean==0) jintmean=1; */
                   8447:   /* if(mintmean==0) mintmean=1; */
1.126     brouard  8448: 
1.296     brouard  8449: 
                   8450:   /* date2dmy(dateintmean,&jintmean,&mintmean,&aintmean); */
                   8451:   /* date2dmy(dateprojd,&jprojd, &mprojd, &anprojd); */
                   8452:   /* date2dmy(dateprojf,&jprojf, &mprojf, &anprojf); */
1.227     brouard  8453:   i1=pow(2,cptcoveff);
1.126     brouard  8454:   if (cptcovn < 1){i1=1;}
                   8455:   
1.296     brouard  8456:   fprintf(ficresf,"# Mean day of interviews %.lf/%.lf/%.lf (%.2f) between %.2f and %.2f \n",jintmean,mintmean,aintmean,dateintmean,dateprev1,dateprev2); 
1.126     brouard  8457:   
                   8458:   fprintf(ficresf,"#****** Routine prevforecast **\n");
1.227     brouard  8459:   
1.126     brouard  8460: /*           if (h==(int)(YEARM*yearp)){ */
1.235     brouard  8461:   for(nres=1; nres <= nresult; nres++) /* For each resultline */
                   8462:   for(k=1; k<=i1;k++){
1.253     brouard  8463:     if(i1 != 1 && TKresult[nres]!= k)
1.235     brouard  8464:       continue;
1.227     brouard  8465:     if(invalidvarcomb[k]){
                   8466:       printf("\nCombination (%d) projection ignored because no cases \n",k); 
                   8467:       continue;
                   8468:     }
                   8469:     fprintf(ficresf,"\n#****** hpijx=probability over h years, hp.jx is weighted by observed prev \n#");
                   8470:     for(j=1;j<=cptcoveff;j++) {
                   8471:       fprintf(ficresf," V%d (=) %d",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   8472:     }
1.235     brouard  8473:     for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
1.238     brouard  8474:       fprintf(ficresf," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
1.235     brouard  8475:     }
1.227     brouard  8476:     fprintf(ficresf," yearproj age");
                   8477:     for(j=1; j<=nlstate+ndeath;j++){ 
                   8478:       for(i=1; i<=nlstate;i++)               
                   8479:        fprintf(ficresf," p%d%d",i,j);
                   8480:       fprintf(ficresf," wp.%d",j);
                   8481:     }
1.296     brouard  8482:     for (yearp=0; yearp<=(anprojf-anprojd);yearp +=stepsize) {
1.227     brouard  8483:       fprintf(ficresf,"\n");
1.296     brouard  8484:       fprintf(ficresf,"\n# Forecasting at date %.lf/%.lf/%.lf ",jprojd,mprojd,anprojd+yearp);   
1.270     brouard  8485:       /* for (agec=fage; agec>=(ageminpar-1); agec--){  */
                   8486:       for (agec=fage; agec>=(bage); agec--){ 
1.227     brouard  8487:        nhstepm=(int) rint((agelim-agec)*YEARM/stepm); 
                   8488:        nhstepm = nhstepm/hstepm; 
                   8489:        p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   8490:        oldm=oldms;savm=savms;
1.268     brouard  8491:        /* We compute pii at age agec over nhstepm);*/
1.235     brouard  8492:        hpxij(p3mat,nhstepm,agec,hstepm,p,nlstate,stepm,oldm,savm, k,nres);
1.268     brouard  8493:        /* Then we print p3mat for h corresponding to the right agec+h*stepms=yearp */
1.227     brouard  8494:        for (h=0; h<=nhstepm; h++){
                   8495:          if (h*hstepm/YEARM*stepm ==yearp) {
1.268     brouard  8496:            break;
                   8497:          }
                   8498:        }
                   8499:        fprintf(ficresf,"\n");
                   8500:        for(j=1;j<=cptcoveff;j++) 
                   8501:          fprintf(ficresf,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
1.296     brouard  8502:        fprintf(ficresf,"%.f %.f ",anprojd+yearp,agec+h*hstepm/YEARM*stepm);
1.268     brouard  8503:        
                   8504:        for(j=1; j<=nlstate+ndeath;j++) {
                   8505:          ppij=0.;
                   8506:          for(i=1; i<=nlstate;i++) {
1.278     brouard  8507:            if (mobilav>=1)
                   8508:             ppij=ppij+p3mat[i][j][h]*prev[(int)agec][i][k];
                   8509:            else { /* even if mobilav==-1 we use mobaverage, probs may not sums to 1 */
                   8510:                ppij=ppij+p3mat[i][j][h]*probs[(int)(agec)][i][k];
                   8511:            }
1.268     brouard  8512:            fprintf(ficresf," %.3f", p3mat[i][j][h]);
                   8513:          } /* end i */
                   8514:          fprintf(ficresf," %.3f", ppij);
                   8515:        }/* end j */
1.227     brouard  8516:        free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   8517:       } /* end agec */
1.266     brouard  8518:       /* diffyear=(int) anproj1+yearp-ageminpar-1; */
                   8519:       /*printf("Prevforecast %d+%d-%d=diffyear=%d\n",(int) anproj1, (int)yearp,(int)ageminpar,(int) anproj1-(int)ageminpar);*/
1.227     brouard  8520:     } /* end yearp */
                   8521:   } /* end  k */
1.219     brouard  8522:        
1.126     brouard  8523:   fclose(ficresf);
1.215     brouard  8524:   printf("End of Computing forecasting \n");
                   8525:   fprintf(ficlog,"End of Computing forecasting\n");
                   8526: 
1.126     brouard  8527: }
                   8528: 
1.269     brouard  8529: /************** Back Forecasting ******************/
1.296     brouard  8530:  /* 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){ */
                   8531:  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){
                   8532:   /* back1, year, month, day of starting backprojection
1.267     brouard  8533:      agemin, agemax range of age
                   8534:      dateprev1 dateprev2 range of dates during which prevalence is computed
1.269     brouard  8535:      anback2 year of end of backprojection (same day and month as back1).
                   8536:      prevacurrent and prev are prevalences.
1.267     brouard  8537:   */
                   8538:   int yearp, stepsize, hstepm, nhstepm, j, k, cptcod, i, h, i1, k4, nres=0;
                   8539:   double agec; /* generic age */
1.302     brouard  8540:   double agelim, ppij, ppi, yp,yp1,yp2; /* ,jintmean,mintmean,aintmean;*/
1.267     brouard  8541:   double *popeffectif,*popcount;
                   8542:   double ***p3mat;
                   8543:   /* double ***mobaverage; */
                   8544:   char fileresfb[FILENAMELENGTH];
                   8545:  
1.268     brouard  8546:   agelim=AGEINF;
1.267     brouard  8547:   /* Compute observed prevalence between dateprev1 and dateprev2 by counting the number of people
                   8548:      in each health status at the date of interview (if between dateprev1 and dateprev2).
                   8549:      We still use firstpass and lastpass as another selection.
                   8550:   */
                   8551:   /* freqsummary(fileres, agemin, agemax, s, agev, nlstate, imx,Tvaraff,nbcode, ncodemax,mint,anint,strstart,\ */
                   8552:   /*         firstpass, lastpass,  stepm,  weightopt, model); */
                   8553: 
                   8554:   /*Do we need to compute prevalence again?*/
                   8555: 
                   8556:   /* prevalence(probs, ageminpar, agemax, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass); */
                   8557:   
                   8558:   strcpy(fileresfb,"FB_");
                   8559:   strcat(fileresfb,fileresu);
                   8560:   if((ficresfb=fopen(fileresfb,"w"))==NULL) {
                   8561:     printf("Problem with back forecast resultfile: %s\n", fileresfb);
                   8562:     fprintf(ficlog,"Problem with back forecast resultfile: %s\n", fileresfb);
                   8563:   }
                   8564:   printf("\nComputing back forecasting: result on file '%s', please wait... \n", fileresfb);
                   8565:   fprintf(ficlog,"\nComputing back forecasting: result on file '%s', please wait... \n", fileresfb);
                   8566:   
                   8567:   if (cptcoveff==0) ncodemax[cptcoveff]=1;
                   8568:   
                   8569:    
                   8570:   stepsize=(int) (stepm+YEARM-1)/YEARM;
                   8571:   if (stepm<=12) stepsize=1;
                   8572:   if(estepm < stepm){
                   8573:     printf ("Problem %d lower than %d\n",estepm, stepm);
                   8574:   }
1.270     brouard  8575:   else{
                   8576:     hstepm=estepm;   
                   8577:   }
                   8578:   if(estepm >= stepm){ /* Yes every two year */
                   8579:     stepsize=2;
                   8580:   }
1.267     brouard  8581:   
                   8582:   hstepm=hstepm/stepm;
1.296     brouard  8583:   /* yp1=modf(dateintmean,&yp);/\* extracts integral of datemean in yp  and */
                   8584:   /*                              fractional in yp1 *\/ */
                   8585:   /* aintmean=yp; */
                   8586:   /* yp2=modf((yp1*12),&yp); */
                   8587:   /* mintmean=yp; */
                   8588:   /* yp1=modf((yp2*30.5),&yp); */
                   8589:   /* jintmean=yp; */
                   8590:   /* if(jintmean==0) jintmean=1; */
                   8591:   /* if(mintmean==0) jintmean=1; */
1.267     brouard  8592:   
                   8593:   i1=pow(2,cptcoveff);
                   8594:   if (cptcovn < 1){i1=1;}
                   8595:   
1.296     brouard  8596:   fprintf(ficresfb,"# Mean day of interviews %.lf/%.lf/%.lf (%.2f) between %.2f and %.2f \n",jintmean,mintmean,aintmean,dateintmean,dateprev1,dateprev2);
                   8597:   printf("# Mean day of interviews %.lf/%.lf/%.lf (%.2f) between %.2f and %.2f \n",jintmean,mintmean,aintmean,dateintmean,dateprev1,dateprev2);
1.267     brouard  8598:   
                   8599:   fprintf(ficresfb,"#****** Routine prevbackforecast **\n");
                   8600:   
                   8601:   for(nres=1; nres <= nresult; nres++) /* For each resultline */
                   8602:   for(k=1; k<=i1;k++){
                   8603:     if(i1 != 1 && TKresult[nres]!= k)
                   8604:       continue;
                   8605:     if(invalidvarcomb[k]){
                   8606:       printf("\nCombination (%d) projection ignored because no cases \n",k); 
                   8607:       continue;
                   8608:     }
1.268     brouard  8609:     fprintf(ficresfb,"\n#****** hbijx=probability over h years, hb.jx is weighted by observed prev \n#");
1.267     brouard  8610:     for(j=1;j<=cptcoveff;j++) {
                   8611:       fprintf(ficresfb," V%d (=) %d",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   8612:     }
                   8613:     for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
                   8614:       fprintf(ficresf," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
                   8615:     }
                   8616:     fprintf(ficresfb," yearbproj age");
                   8617:     for(j=1; j<=nlstate+ndeath;j++){
                   8618:       for(i=1; i<=nlstate;i++)
1.268     brouard  8619:        fprintf(ficresfb," b%d%d",i,j);
                   8620:       fprintf(ficresfb," b.%d",j);
1.267     brouard  8621:     }
1.296     brouard  8622:     for (yearp=0; yearp>=(anbackf-anbackd);yearp -=stepsize) {
1.267     brouard  8623:       /* for (yearp=0; yearp<=(anproj2-anproj1);yearp +=stepsize) {  */
                   8624:       fprintf(ficresfb,"\n");
1.296     brouard  8625:       fprintf(ficresfb,"\n# Back Forecasting at date %.lf/%.lf/%.lf ",jbackd,mbackd,anbackd+yearp);
1.273     brouard  8626:       /* printf("\n# Back Forecasting at date %.lf/%.lf/%.lf ",jback1,mback1,anback1+yearp); */
1.270     brouard  8627:       /* for (agec=bage; agec<=agemax-1; agec++){  /\* testing *\/ */
                   8628:       for (agec=bage; agec<=fage; agec++){  /* testing */
1.268     brouard  8629:        /* We compute bij at age agec over nhstepm, nhstepm decreases when agec increases because of agemax;*/
1.271     brouard  8630:        nhstepm=(int) (agec-agelim) *YEARM/stepm;/*     nhstepm=(int) rint((agec-agelim)*YEARM/stepm);*/
1.267     brouard  8631:        nhstepm = nhstepm/hstepm;
                   8632:        p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   8633:        oldm=oldms;savm=savms;
1.268     brouard  8634:        /* computes hbxij at age agec over 1 to nhstepm */
1.271     brouard  8635:        /* printf("####prevbackforecast debug  agec=%.2f nhstepm=%d\n",agec, nhstepm);fflush(stdout); */
1.267     brouard  8636:        hbxij(p3mat,nhstepm,agec,hstepm,p,prevacurrent,nlstate,stepm, k, nres);
1.268     brouard  8637:        /* hpxij(p3mat,nhstepm,agec,hstepm,p,             nlstate,stepm,oldm,savm, k,nres); */
                   8638:        /* Then we print p3mat for h corresponding to the right agec+h*stepms=yearp */
                   8639:        /* printf(" agec=%.2f\n",agec);fflush(stdout); */
1.267     brouard  8640:        for (h=0; h<=nhstepm; h++){
1.268     brouard  8641:          if (h*hstepm/YEARM*stepm ==-yearp) {
                   8642:            break;
                   8643:          }
                   8644:        }
                   8645:        fprintf(ficresfb,"\n");
                   8646:        for(j=1;j<=cptcoveff;j++)
                   8647:          fprintf(ficresfb,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
1.296     brouard  8648:        fprintf(ficresfb,"%.f %.f ",anbackd+yearp,agec-h*hstepm/YEARM*stepm);
1.268     brouard  8649:        for(i=1; i<=nlstate+ndeath;i++) {
                   8650:          ppij=0.;ppi=0.;
                   8651:          for(j=1; j<=nlstate;j++) {
                   8652:            /* if (mobilav==1) */
1.269     brouard  8653:            ppij=ppij+p3mat[i][j][h]*prevacurrent[(int)agec][j][k];
                   8654:            ppi=ppi+prevacurrent[(int)agec][j][k];
                   8655:            /* ppij=ppij+p3mat[i][j][h]*mobaverage[(int)agec][j][k]; */
                   8656:            /* ppi=ppi+mobaverage[(int)agec][j][k]; */
1.267     brouard  8657:              /* else { */
                   8658:              /*        ppij=ppij+p3mat[i][j][h]*probs[(int)(agec)][i][k]; */
                   8659:              /* } */
1.268     brouard  8660:            fprintf(ficresfb," %.3f", p3mat[i][j][h]);
                   8661:          } /* end j */
                   8662:          if(ppi <0.99){
                   8663:            printf("Error in prevbackforecast, prevalence doesn't sum to 1 for state %d: %3f\n",i, ppi);
                   8664:            fprintf(ficlog,"Error in prevbackforecast, prevalence doesn't sum to 1 for state %d: %3f\n",i, ppi);
                   8665:          }
                   8666:          fprintf(ficresfb," %.3f", ppij);
                   8667:        }/* end j */
1.267     brouard  8668:        free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   8669:       } /* end agec */
                   8670:     } /* end yearp */
                   8671:   } /* end k */
1.217     brouard  8672:   
1.267     brouard  8673:   /* if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX); */
1.217     brouard  8674:   
1.267     brouard  8675:   fclose(ficresfb);
                   8676:   printf("End of Computing Back forecasting \n");
                   8677:   fprintf(ficlog,"End of Computing Back forecasting\n");
1.218     brouard  8678:        
1.267     brouard  8679: }
1.217     brouard  8680: 
1.269     brouard  8681: /* Variance of prevalence limit: varprlim */
                   8682:  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  8683:     /*------- Variance of forward period (stable) prevalence------*/   
1.269     brouard  8684:  
                   8685:    char fileresvpl[FILENAMELENGTH];  
                   8686:    FILE *ficresvpl;
                   8687:    double **oldm, **savm;
                   8688:    double **varpl; /* Variances of prevalence limits by age */   
                   8689:    int i1, k, nres, j ;
                   8690:    
                   8691:     strcpy(fileresvpl,"VPL_");
                   8692:     strcat(fileresvpl,fileresu);
                   8693:     if((ficresvpl=fopen(fileresvpl,"w"))==NULL) {
1.288     brouard  8694:       printf("Problem with variance of forward period (stable) prevalence  resultfile: %s\n", fileresvpl);
1.269     brouard  8695:       exit(0);
                   8696:     }
1.288     brouard  8697:     printf("Computing Variance-covariance of forward period (stable) prevalence: file '%s' ...", fileresvpl);fflush(stdout);
                   8698:     fprintf(ficlog, "Computing Variance-covariance of forward period (stable) prevalence: file '%s' ...", fileresvpl);fflush(ficlog);
1.269     brouard  8699:     
                   8700:     /*for(cptcov=1,k=0;cptcov<=i1;cptcov++){
                   8701:       for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*/
                   8702:     
                   8703:     i1=pow(2,cptcoveff);
                   8704:     if (cptcovn < 1){i1=1;}
                   8705: 
                   8706:     for(nres=1; nres <= nresult; nres++) /* For each resultline */
                   8707:     for(k=1; k<=i1;k++){
                   8708:       if(i1 != 1 && TKresult[nres]!= k)
                   8709:        continue;
                   8710:       fprintf(ficresvpl,"\n#****** ");
                   8711:       printf("\n#****** ");
                   8712:       fprintf(ficlog,"\n#****** ");
                   8713:       for(j=1;j<=cptcoveff;j++) {
                   8714:        fprintf(ficresvpl,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   8715:        fprintf(ficlog,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   8716:        printf("V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   8717:       }
                   8718:       for (j=1; j<= nsq; j++){ /* For each selected (single) quantitative value */
                   8719:        printf(" V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]);
                   8720:        fprintf(ficresvpl," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]);
                   8721:        fprintf(ficlog," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]);
                   8722:       }        
                   8723:       fprintf(ficresvpl,"******\n");
                   8724:       printf("******\n");
                   8725:       fprintf(ficlog,"******\n");
                   8726:       
                   8727:       varpl=matrix(1,nlstate,(int) bage, (int) fage);
                   8728:       oldm=oldms;savm=savms;
                   8729:       varprevlim(fileresvpl, ficresvpl, varpl, matcov, p, delti, nlstate, stepm, (int) bage, (int) fage, oldm, savm, prlim, ftolpl, ncvyearp, k, strstart, nres);
                   8730:       free_matrix(varpl,1,nlstate,(int) bage, (int)fage);
                   8731:       /*}*/
                   8732:     }
                   8733:     
                   8734:     fclose(ficresvpl);
1.288     brouard  8735:     printf("done variance-covariance of forward period prevalence\n");fflush(stdout);
                   8736:     fprintf(ficlog,"done variance-covariance of forward period prevalence\n");fflush(ficlog);
1.269     brouard  8737: 
                   8738:  }
                   8739: /* Variance of back prevalence: varbprlim */
                   8740:  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){
                   8741:       /*------- Variance of back (stable) prevalence------*/
                   8742: 
                   8743:    char fileresvbl[FILENAMELENGTH];  
                   8744:    FILE  *ficresvbl;
                   8745: 
                   8746:    double **oldm, **savm;
                   8747:    double **varbpl; /* Variances of back prevalence limits by age */   
                   8748:    int i1, k, nres, j ;
                   8749: 
                   8750:    strcpy(fileresvbl,"VBL_");
                   8751:    strcat(fileresvbl,fileresu);
                   8752:    if((ficresvbl=fopen(fileresvbl,"w"))==NULL) {
                   8753:      printf("Problem with variance of back (stable) prevalence  resultfile: %s\n", fileresvbl);
                   8754:      exit(0);
                   8755:    }
                   8756:    printf("Computing Variance-covariance of back (stable) prevalence: file '%s' ...", fileresvbl);fflush(stdout);
                   8757:    fprintf(ficlog, "Computing Variance-covariance of back (stable) prevalence: file '%s' ...", fileresvbl);fflush(ficlog);
                   8758:    
                   8759:    
                   8760:    i1=pow(2,cptcoveff);
                   8761:    if (cptcovn < 1){i1=1;}
                   8762:    
                   8763:    for(nres=1; nres <= nresult; nres++) /* For each resultline */
                   8764:      for(k=1; k<=i1;k++){
                   8765:        if(i1 != 1 && TKresult[nres]!= k)
                   8766:         continue;
                   8767:        fprintf(ficresvbl,"\n#****** ");
                   8768:        printf("\n#****** ");
                   8769:        fprintf(ficlog,"\n#****** ");
                   8770:        for(j=1;j<=cptcoveff;j++) {
                   8771:         fprintf(ficresvbl,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   8772:         fprintf(ficlog,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   8773:         printf("V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   8774:        }
                   8775:        for (j=1; j<= nsq; j++){ /* For each selected (single) quantitative value */
                   8776:         printf(" V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]);
                   8777:         fprintf(ficresvbl," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]);
                   8778:         fprintf(ficlog," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]);
                   8779:        }
                   8780:        fprintf(ficresvbl,"******\n");
                   8781:        printf("******\n");
                   8782:        fprintf(ficlog,"******\n");
                   8783:        
                   8784:        varbpl=matrix(1,nlstate,(int) bage, (int) fage);
                   8785:        oldm=oldms;savm=savms;
                   8786:        
                   8787:        varbrevlim(fileresvbl, ficresvbl, varbpl, matcov, p, delti, nlstate, stepm, (int) bage, (int) fage, oldm, savm, bprlim, ftolpl, mobilavproj, ncvyearp, k, strstart, nres);
                   8788:        free_matrix(varbpl,1,nlstate,(int) bage, (int)fage);
                   8789:        /*}*/
                   8790:      }
                   8791:    
                   8792:    fclose(ficresvbl);
                   8793:    printf("done variance-covariance of back prevalence\n");fflush(stdout);
                   8794:    fprintf(ficlog,"done variance-covariance of back prevalence\n");fflush(ficlog);
                   8795: 
                   8796:  } /* End of varbprlim */
                   8797: 
1.126     brouard  8798: /************** Forecasting *****not tested NB*************/
1.227     brouard  8799: /* 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  8800:   
1.227     brouard  8801: /*   int cpt, stepsize, hstepm, nhstepm, j,k,c, cptcod, i,h; */
                   8802: /*   int *popage; */
                   8803: /*   double calagedatem, agelim, kk1, kk2; */
                   8804: /*   double *popeffectif,*popcount; */
                   8805: /*   double ***p3mat,***tabpop,***tabpopprev; */
                   8806: /*   /\* double ***mobaverage; *\/ */
                   8807: /*   char filerespop[FILENAMELENGTH]; */
1.126     brouard  8808: 
1.227     brouard  8809: /*   tabpop= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX); */
                   8810: /*   tabpopprev= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX); */
                   8811: /*   agelim=AGESUP; */
                   8812: /*   calagedatem=(anpyram+mpyram/12.+jpyram/365.-dateintmean)*YEARM; */
1.126     brouard  8813:   
1.227     brouard  8814: /*   prevalence(probs, ageminpar, agemax, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass); */
1.126     brouard  8815:   
                   8816:   
1.227     brouard  8817: /*   strcpy(filerespop,"POP_");  */
                   8818: /*   strcat(filerespop,fileresu); */
                   8819: /*   if((ficrespop=fopen(filerespop,"w"))==NULL) { */
                   8820: /*     printf("Problem with forecast resultfile: %s\n", filerespop); */
                   8821: /*     fprintf(ficlog,"Problem with forecast resultfile: %s\n", filerespop); */
                   8822: /*   } */
                   8823: /*   printf("Computing forecasting: result on file '%s' \n", filerespop); */
                   8824: /*   fprintf(ficlog,"Computing forecasting: result on file '%s' \n", filerespop); */
1.126     brouard  8825: 
1.227     brouard  8826: /*   if (cptcoveff==0) ncodemax[cptcoveff]=1; */
1.126     brouard  8827: 
1.227     brouard  8828: /*   /\* if (mobilav!=0) { *\/ */
                   8829: /*   /\*   mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX); *\/ */
                   8830: /*   /\*   if (movingaverage(probs, ageminpar, fage, mobaverage,mobilav)!=0){ *\/ */
                   8831: /*   /\*     fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav); *\/ */
                   8832: /*   /\*     printf(" Error in movingaverage mobilav=%d\n",mobilav); *\/ */
                   8833: /*   /\*   } *\/ */
                   8834: /*   /\* } *\/ */
1.126     brouard  8835: 
1.227     brouard  8836: /*   stepsize=(int) (stepm+YEARM-1)/YEARM; */
                   8837: /*   if (stepm<=12) stepsize=1; */
1.126     brouard  8838:   
1.227     brouard  8839: /*   agelim=AGESUP; */
1.126     brouard  8840:   
1.227     brouard  8841: /*   hstepm=1; */
                   8842: /*   hstepm=hstepm/stepm;  */
1.218     brouard  8843:        
1.227     brouard  8844: /*   if (popforecast==1) { */
                   8845: /*     if((ficpop=fopen(popfile,"r"))==NULL) { */
                   8846: /*       printf("Problem with population file : %s\n",popfile);exit(0); */
                   8847: /*       fprintf(ficlog,"Problem with population file : %s\n",popfile);exit(0); */
                   8848: /*     }  */
                   8849: /*     popage=ivector(0,AGESUP); */
                   8850: /*     popeffectif=vector(0,AGESUP); */
                   8851: /*     popcount=vector(0,AGESUP); */
1.126     brouard  8852:     
1.227     brouard  8853: /*     i=1;    */
                   8854: /*     while ((c=fscanf(ficpop,"%d %lf\n",&popage[i],&popcount[i])) != EOF) i=i+1; */
1.218     brouard  8855:     
1.227     brouard  8856: /*     imx=i; */
                   8857: /*     for (i=1; i<imx;i++) popeffectif[popage[i]]=popcount[i]; */
                   8858: /*   } */
1.218     brouard  8859:   
1.227     brouard  8860: /*   for(cptcov=1,k=0;cptcov<=i2;cptcov++){ */
                   8861: /*     for(cptcod=1;cptcod<=ncodemax[cptcoveff];cptcod++){ */
                   8862: /*       k=k+1; */
                   8863: /*       fprintf(ficrespop,"\n#******"); */
                   8864: /*       for(j=1;j<=cptcoveff;j++) { */
                   8865: /*     fprintf(ficrespop," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]); */
                   8866: /*       } */
                   8867: /*       fprintf(ficrespop,"******\n"); */
                   8868: /*       fprintf(ficrespop,"# Age"); */
                   8869: /*       for(j=1; j<=nlstate+ndeath;j++) fprintf(ficrespop," P.%d",j); */
                   8870: /*       if (popforecast==1)  fprintf(ficrespop," [Population]"); */
1.126     brouard  8871:       
1.227     brouard  8872: /*       for (cpt=0; cpt<=0;cpt++) {  */
                   8873: /*     fprintf(ficrespop,"\n\n# Forecasting at date %.lf/%.lf/%.lf ",jpyram,mpyram,anpyram+cpt);    */
1.126     brouard  8874:        
1.227     brouard  8875: /*     for (agedeb=(fage-((int)calagedatem %12/12.)); agedeb>=(ageminpar-((int)calagedatem %12)/12.); agedeb--){  */
                   8876: /*       nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm);  */
                   8877: /*       nhstepm = nhstepm/hstepm;  */
1.126     brouard  8878:          
1.227     brouard  8879: /*       p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm); */
                   8880: /*       oldm=oldms;savm=savms; */
                   8881: /*       hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);   */
1.218     brouard  8882:          
1.227     brouard  8883: /*       for (h=0; h<=nhstepm; h++){ */
                   8884: /*         if (h==(int) (calagedatem+YEARM*cpt)) { */
                   8885: /*           fprintf(ficrespop,"\n %3.f ",agedeb+h*hstepm/YEARM*stepm); */
                   8886: /*         }  */
                   8887: /*         for(j=1; j<=nlstate+ndeath;j++) { */
                   8888: /*           kk1=0.;kk2=0; */
                   8889: /*           for(i=1; i<=nlstate;i++) {               */
                   8890: /*             if (mobilav==1)  */
                   8891: /*               kk1=kk1+p3mat[i][j][h]*mobaverage[(int)agedeb+1][i][cptcod]; */
                   8892: /*             else { */
                   8893: /*               kk1=kk1+p3mat[i][j][h]*probs[(int)(agedeb+1)][i][cptcod]; */
                   8894: /*             } */
                   8895: /*           } */
                   8896: /*           if (h==(int)(calagedatem+12*cpt)){ */
                   8897: /*             tabpop[(int)(agedeb)][j][cptcod]=kk1; */
                   8898: /*             /\*fprintf(ficrespop," %.3f", kk1); */
                   8899: /*               if (popforecast==1) fprintf(ficrespop," [%.f]", kk1*popeffectif[(int)agedeb+1]);*\/ */
                   8900: /*           } */
                   8901: /*         } */
                   8902: /*         for(i=1; i<=nlstate;i++){ */
                   8903: /*           kk1=0.; */
                   8904: /*           for(j=1; j<=nlstate;j++){ */
                   8905: /*             kk1= kk1+tabpop[(int)(agedeb)][j][cptcod];  */
                   8906: /*           } */
                   8907: /*           tabpopprev[(int)(agedeb)][i][cptcod]=tabpop[(int)(agedeb)][i][cptcod]/kk1*popeffectif[(int)(agedeb+(calagedatem+12*cpt)*hstepm/YEARM*stepm-1)]; */
                   8908: /*         } */
1.218     brouard  8909:            
1.227     brouard  8910: /*         if (h==(int)(calagedatem+12*cpt)) */
                   8911: /*           for(j=1; j<=nlstate;j++)  */
                   8912: /*             fprintf(ficrespop," %15.2f",tabpopprev[(int)(agedeb+1)][j][cptcod]); */
                   8913: /*       } */
                   8914: /*       free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm); */
                   8915: /*     } */
                   8916: /*       } */
1.218     brouard  8917:       
1.227     brouard  8918: /*       /\******\/ */
1.218     brouard  8919:       
1.227     brouard  8920: /*       for (cpt=1; cpt<=(anpyram1-anpyram);cpt++) {  */
                   8921: /*     fprintf(ficrespop,"\n\n# Forecasting at date %.lf/%.lf/%.lf ",jpyram,mpyram,anpyram+cpt);    */
                   8922: /*     for (agedeb=(fage-((int)calagedatem %12/12.)); agedeb>=(ageminpar-((int)calagedatem %12)/12.); agedeb--){  */
                   8923: /*       nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm);  */
                   8924: /*       nhstepm = nhstepm/hstepm;  */
1.126     brouard  8925:          
1.227     brouard  8926: /*       p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm); */
                   8927: /*       oldm=oldms;savm=savms; */
                   8928: /*       hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);   */
                   8929: /*       for (h=0; h<=nhstepm; h++){ */
                   8930: /*         if (h==(int) (calagedatem+YEARM*cpt)) { */
                   8931: /*           fprintf(ficresf,"\n %3.f ",agedeb+h*hstepm/YEARM*stepm); */
                   8932: /*         }  */
                   8933: /*         for(j=1; j<=nlstate+ndeath;j++) { */
                   8934: /*           kk1=0.;kk2=0; */
                   8935: /*           for(i=1; i<=nlstate;i++) {               */
                   8936: /*             kk1=kk1+p3mat[i][j][h]*tabpopprev[(int)agedeb+1][i][cptcod];     */
                   8937: /*           } */
                   8938: /*           if (h==(int)(calagedatem+12*cpt)) fprintf(ficresf," %15.2f", kk1);         */
                   8939: /*         } */
                   8940: /*       } */
                   8941: /*       free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm); */
                   8942: /*     } */
                   8943: /*       } */
                   8944: /*     }  */
                   8945: /*   } */
1.218     brouard  8946:   
1.227     brouard  8947: /*   /\* if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX); *\/ */
1.218     brouard  8948:   
1.227     brouard  8949: /*   if (popforecast==1) { */
                   8950: /*     free_ivector(popage,0,AGESUP); */
                   8951: /*     free_vector(popeffectif,0,AGESUP); */
                   8952: /*     free_vector(popcount,0,AGESUP); */
                   8953: /*   } */
                   8954: /*   free_ma3x(tabpop,1, AGESUP,1,NCOVMAX, 1,NCOVMAX); */
                   8955: /*   free_ma3x(tabpopprev,1, AGESUP,1,NCOVMAX, 1,NCOVMAX); */
                   8956: /*   fclose(ficrespop); */
                   8957: /* } /\* End of popforecast *\/ */
1.218     brouard  8958:  
1.126     brouard  8959: int fileappend(FILE *fichier, char *optionfich)
                   8960: {
                   8961:   if((fichier=fopen(optionfich,"a"))==NULL) {
                   8962:     printf("Problem with file: %s\n", optionfich);
                   8963:     fprintf(ficlog,"Problem with file: %s\n", optionfich);
                   8964:     return (0);
                   8965:   }
                   8966:   fflush(fichier);
                   8967:   return (1);
                   8968: }
                   8969: 
                   8970: 
                   8971: /**************** function prwizard **********************/
                   8972: void prwizard(int ncovmodel, int nlstate, int ndeath,  char model[], FILE *ficparo)
                   8973: {
                   8974: 
                   8975:   /* Wizard to print covariance matrix template */
                   8976: 
1.164     brouard  8977:   char ca[32], cb[32];
                   8978:   int i,j, k, li, lj, lk, ll, jj, npar, itimes;
1.126     brouard  8979:   int numlinepar;
                   8980: 
                   8981:   printf("# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
                   8982:   fprintf(ficparo,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
                   8983:   for(i=1; i <=nlstate; i++){
                   8984:     jj=0;
                   8985:     for(j=1; j <=nlstate+ndeath; j++){
                   8986:       if(j==i) continue;
                   8987:       jj++;
                   8988:       /*ca[0]= k+'a'-1;ca[1]='\0';*/
                   8989:       printf("%1d%1d",i,j);
                   8990:       fprintf(ficparo,"%1d%1d",i,j);
                   8991:       for(k=1; k<=ncovmodel;k++){
                   8992:        /*        printf(" %lf",param[i][j][k]); */
                   8993:        /*        fprintf(ficparo," %lf",param[i][j][k]); */
                   8994:        printf(" 0.");
                   8995:        fprintf(ficparo," 0.");
                   8996:       }
                   8997:       printf("\n");
                   8998:       fprintf(ficparo,"\n");
                   8999:     }
                   9000:   }
                   9001:   printf("# Scales (for hessian or gradient estimation)\n");
                   9002:   fprintf(ficparo,"# Scales (for hessian or gradient estimation)\n");
                   9003:   npar= (nlstate+ndeath-1)*nlstate*ncovmodel; /* Number of parameters*/ 
                   9004:   for(i=1; i <=nlstate; i++){
                   9005:     jj=0;
                   9006:     for(j=1; j <=nlstate+ndeath; j++){
                   9007:       if(j==i) continue;
                   9008:       jj++;
                   9009:       fprintf(ficparo,"%1d%1d",i,j);
                   9010:       printf("%1d%1d",i,j);
                   9011:       fflush(stdout);
                   9012:       for(k=1; k<=ncovmodel;k++){
                   9013:        /*      printf(" %le",delti3[i][j][k]); */
                   9014:        /*      fprintf(ficparo," %le",delti3[i][j][k]); */
                   9015:        printf(" 0.");
                   9016:        fprintf(ficparo," 0.");
                   9017:       }
                   9018:       numlinepar++;
                   9019:       printf("\n");
                   9020:       fprintf(ficparo,"\n");
                   9021:     }
                   9022:   }
                   9023:   printf("# Covariance matrix\n");
                   9024: /* # 121 Var(a12)\n\ */
                   9025: /* # 122 Cov(b12,a12) Var(b12)\n\ */
                   9026: /* # 131 Cov(a13,a12) Cov(a13,b12, Var(a13)\n\ */
                   9027: /* # 132 Cov(b13,a12) Cov(b13,b12, Cov(b13,a13) Var(b13)\n\ */
                   9028: /* # 212 Cov(a21,a12) Cov(a21,b12, Cov(a21,a13) Cov(a21,b13) Var(a21)\n\ */
                   9029: /* # 212 Cov(b21,a12) Cov(b21,b12, Cov(b21,a13) Cov(b21,b13) Cov(b21,a21) Var(b21)\n\ */
                   9030: /* # 232 Cov(a23,a12) Cov(a23,b12, Cov(a23,a13) Cov(a23,b13) Cov(a23,a21) Cov(a23,b21) Var(a23)\n\ */
                   9031: /* # 232 Cov(b23,a12) Cov(b23,b12) ... Var (b23)\n" */
                   9032:   fflush(stdout);
                   9033:   fprintf(ficparo,"# Covariance matrix\n");
                   9034:   /* # 121 Var(a12)\n\ */
                   9035:   /* # 122 Cov(b12,a12) Var(b12)\n\ */
                   9036:   /* #   ...\n\ */
                   9037:   /* # 232 Cov(b23,a12)  Cov(b23,b12) ... Var (b23)\n" */
                   9038:   
                   9039:   for(itimes=1;itimes<=2;itimes++){
                   9040:     jj=0;
                   9041:     for(i=1; i <=nlstate; i++){
                   9042:       for(j=1; j <=nlstate+ndeath; j++){
                   9043:        if(j==i) continue;
                   9044:        for(k=1; k<=ncovmodel;k++){
                   9045:          jj++;
                   9046:          ca[0]= k+'a'-1;ca[1]='\0';
                   9047:          if(itimes==1){
                   9048:            printf("#%1d%1d%d",i,j,k);
                   9049:            fprintf(ficparo,"#%1d%1d%d",i,j,k);
                   9050:          }else{
                   9051:            printf("%1d%1d%d",i,j,k);
                   9052:            fprintf(ficparo,"%1d%1d%d",i,j,k);
                   9053:            /*  printf(" %.5le",matcov[i][j]); */
                   9054:          }
                   9055:          ll=0;
                   9056:          for(li=1;li <=nlstate; li++){
                   9057:            for(lj=1;lj <=nlstate+ndeath; lj++){
                   9058:              if(lj==li) continue;
                   9059:              for(lk=1;lk<=ncovmodel;lk++){
                   9060:                ll++;
                   9061:                if(ll<=jj){
                   9062:                  cb[0]= lk +'a'-1;cb[1]='\0';
                   9063:                  if(ll<jj){
                   9064:                    if(itimes==1){
                   9065:                      printf(" Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
                   9066:                      fprintf(ficparo," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
                   9067:                    }else{
                   9068:                      printf(" 0.");
                   9069:                      fprintf(ficparo," 0.");
                   9070:                    }
                   9071:                  }else{
                   9072:                    if(itimes==1){
                   9073:                      printf(" Var(%s%1d%1d)",ca,i,j);
                   9074:                      fprintf(ficparo," Var(%s%1d%1d)",ca,i,j);
                   9075:                    }else{
                   9076:                      printf(" 0.");
                   9077:                      fprintf(ficparo," 0.");
                   9078:                    }
                   9079:                  }
                   9080:                }
                   9081:              } /* end lk */
                   9082:            } /* end lj */
                   9083:          } /* end li */
                   9084:          printf("\n");
                   9085:          fprintf(ficparo,"\n");
                   9086:          numlinepar++;
                   9087:        } /* end k*/
                   9088:       } /*end j */
                   9089:     } /* end i */
                   9090:   } /* end itimes */
                   9091: 
                   9092: } /* end of prwizard */
                   9093: /******************* Gompertz Likelihood ******************************/
                   9094: double gompertz(double x[])
                   9095: { 
1.302     brouard  9096:   double A=0.0,B=0.,L=0.0,sump=0.,num=0.;
1.126     brouard  9097:   int i,n=0; /* n is the size of the sample */
                   9098: 
1.220     brouard  9099:   for (i=1;i<=imx ; i++) {
1.126     brouard  9100:     sump=sump+weight[i];
                   9101:     /*    sump=sump+1;*/
                   9102:     num=num+1;
                   9103:   }
1.302     brouard  9104:   L=0.0;
                   9105:   /* agegomp=AGEGOMP; */
1.126     brouard  9106:   /* for (i=0; i<=imx; i++) 
                   9107:      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]);*/
                   9108: 
1.302     brouard  9109:   for (i=1;i<=imx ; i++) {
                   9110:     /* mu(a)=mu(agecomp)*exp(teta*(age-agegomp))
                   9111:        mu(a)=x[1]*exp(x[2]*(age-agegomp)); x[1] and x[2] are per year.
                   9112:      * L= Product mu(agedeces)exp(-\int_ageexam^agedc mu(u) du ) for a death between agedc (in month) 
                   9113:      *   and agedc +1 month, cens[i]=0: log(x[1]/YEARM)
                   9114:      * +
                   9115:      * exp(-\int_ageexam^agecens mu(u) du ) when censored, cens[i]=1
                   9116:      */
                   9117:      if (wav[i] > 1 || agedc[i] < AGESUP) {
                   9118:        if (cens[i] == 1){
                   9119:         A=-x[1]/(x[2])*(exp(x[2]*(agecens[i]-agegomp))-exp(x[2]*(ageexmed[i]-agegomp)));
                   9120:        } else if (cens[i] == 0){
1.126     brouard  9121:        A=-x[1]/(x[2])*(exp(x[2]*(agedc[i]-agegomp))-exp(x[2]*(ageexmed[i]-agegomp)))
1.302     brouard  9122:          +log(x[1]/YEARM) +x[2]*(agedc[i]-agegomp)+log(YEARM);
                   9123:       } else
                   9124:         printf("Gompertz cens[%d] neither 1 nor 0\n",i);
1.126     brouard  9125:       /*if (wav[i] > 1 && agecens[i] > 15) {*/ /* ??? */
1.302     brouard  9126:        L=L+A*weight[i];
1.126     brouard  9127:        /*      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  9128:      }
                   9129:   }
1.126     brouard  9130: 
1.302     brouard  9131:   /*printf("x1=%2.9f x2=%2.9f x3=%2.9f L=%f\n",x[1],x[2],x[3],L);*/
1.126     brouard  9132:  
                   9133:   return -2*L*num/sump;
                   9134: }
                   9135: 
1.136     brouard  9136: #ifdef GSL
                   9137: /******************* Gompertz_f Likelihood ******************************/
                   9138: double gompertz_f(const gsl_vector *v, void *params)
                   9139: { 
1.302     brouard  9140:   double A=0.,B=0.,LL=0.0,sump=0.,num=0.;
1.136     brouard  9141:   double *x= (double *) v->data;
                   9142:   int i,n=0; /* n is the size of the sample */
                   9143: 
                   9144:   for (i=0;i<=imx-1 ; i++) {
                   9145:     sump=sump+weight[i];
                   9146:     /*    sump=sump+1;*/
                   9147:     num=num+1;
                   9148:   }
                   9149:  
                   9150:  
                   9151:   /* for (i=0; i<=imx; i++) 
                   9152:      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]);*/
                   9153:   printf("x[0]=%lf x[1]=%lf\n",x[0],x[1]);
                   9154:   for (i=1;i<=imx ; i++)
                   9155:     {
                   9156:       if (cens[i] == 1 && wav[i]>1)
                   9157:        A=-x[0]/(x[1])*(exp(x[1]*(agecens[i]-agegomp))-exp(x[1]*(ageexmed[i]-agegomp)));
                   9158:       
                   9159:       if (cens[i] == 0 && wav[i]>1)
                   9160:        A=-x[0]/(x[1])*(exp(x[1]*(agedc[i]-agegomp))-exp(x[1]*(ageexmed[i]-agegomp)))
                   9161:             +log(x[0]/YEARM)+x[1]*(agedc[i]-agegomp)+log(YEARM);  
                   9162:       
                   9163:       /*if (wav[i] > 1 && agecens[i] > 15) {*/ /* ??? */
                   9164:       if (wav[i] > 1 ) { /* ??? */
                   9165:        LL=LL+A*weight[i];
                   9166:        /*      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]);*/
                   9167:       }
                   9168:     }
                   9169: 
                   9170:  /*printf("x1=%2.9f x2=%2.9f x3=%2.9f L=%f\n",x[1],x[2],x[3],L);*/
                   9171:   printf("x[0]=%lf x[1]=%lf -2*LL*num/sump=%lf\n",x[0],x[1],-2*LL*num/sump);
                   9172:  
                   9173:   return -2*LL*num/sump;
                   9174: }
                   9175: #endif
                   9176: 
1.126     brouard  9177: /******************* Printing html file ***********/
1.201     brouard  9178: void printinghtmlmort(char fileresu[], char title[], char datafile[], int firstpass, \
1.126     brouard  9179:                  int lastpass, int stepm, int weightopt, char model[],\
                   9180:                  int imx,  double p[],double **matcov,double agemortsup){
                   9181:   int i,k;
                   9182: 
                   9183:   fprintf(fichtm,"<ul><li><h4>Result files </h4>\n Force of mortality. Parameters of the Gompertz fit (with confidence interval in brackets):<br>");
                   9184:   fprintf(fichtm,"  mu(age) =%lf*exp(%lf*(age-%d)) per year<br><br>",p[1],p[2],agegomp);
                   9185:   for (i=1;i<=2;i++) 
                   9186:     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  9187:   fprintf(fichtm,"<br><br><img src=\"graphmort.svg\">");
1.126     brouard  9188:   fprintf(fichtm,"</ul>");
                   9189: 
                   9190: fprintf(fichtm,"<ul><li><h4>Life table</h4>\n <br>");
                   9191: 
                   9192:  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>");
                   9193: 
                   9194:  for (k=agegomp;k<(agemortsup-2);k++) 
                   9195:    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]);
                   9196: 
                   9197:  
                   9198:   fflush(fichtm);
                   9199: }
                   9200: 
                   9201: /******************* Gnuplot file **************/
1.201     brouard  9202: void printinggnuplotmort(char fileresu[], char optionfilefiname[], double ageminpar, double agemaxpar, double fage , char pathc[], double p[]){
1.126     brouard  9203: 
                   9204:   char dirfileres[132],optfileres[132];
1.164     brouard  9205: 
1.126     brouard  9206:   int ng;
                   9207: 
                   9208: 
                   9209:   /*#ifdef windows */
                   9210:   fprintf(ficgp,"cd \"%s\" \n",pathc);
                   9211:     /*#endif */
                   9212: 
                   9213: 
                   9214:   strcpy(dirfileres,optionfilefiname);
                   9215:   strcpy(optfileres,"vpl");
1.199     brouard  9216:   fprintf(ficgp,"set out \"graphmort.svg\"\n "); 
1.126     brouard  9217:   fprintf(ficgp,"set xlabel \"Age\"\n set ylabel \"Force of mortality (per year)\" \n "); 
1.199     brouard  9218:   fprintf(ficgp, "set ter svg size 640, 480\n set log y\n"); 
1.145     brouard  9219:   /* fprintf(ficgp, "set size 0.65,0.65\n"); */
1.126     brouard  9220:   fprintf(ficgp,"plot [%d:100] %lf*exp(%lf*(x-%d))",agegomp,p[1],p[2],agegomp);
                   9221: 
                   9222: } 
                   9223: 
1.136     brouard  9224: int readdata(char datafile[], int firstobs, int lastobs, int *imax)
                   9225: {
1.126     brouard  9226: 
1.136     brouard  9227:   /*-------- data file ----------*/
                   9228:   FILE *fic;
                   9229:   char dummy[]="                         ";
1.240     brouard  9230:   int i=0, j=0, n=0, iv=0, v;
1.223     brouard  9231:   int lstra;
1.136     brouard  9232:   int linei, month, year,iout;
1.302     brouard  9233:   int noffset=0; /* This is the offset if BOM data file */
1.136     brouard  9234:   char line[MAXLINE], linetmp[MAXLINE];
1.164     brouard  9235:   char stra[MAXLINE], strb[MAXLINE];
1.136     brouard  9236:   char *stratrunc;
1.223     brouard  9237: 
1.240     brouard  9238:   DummyV=ivector(1,NCOVMAX); /* 1 to 3 */
                   9239:   FixedV=ivector(1,NCOVMAX); /* 1 to 3 */
1.126     brouard  9240: 
1.240     brouard  9241:   for(v=1; v <=ncovcol;v++){
                   9242:     DummyV[v]=0;
                   9243:     FixedV[v]=0;
                   9244:   }
                   9245:   for(v=ncovcol+1; v <=ncovcol+nqv;v++){
                   9246:     DummyV[v]=1;
                   9247:     FixedV[v]=0;
                   9248:   }
                   9249:   for(v=ncovcol+nqv+1; v <=ncovcol+nqv+ntv;v++){
                   9250:     DummyV[v]=0;
                   9251:     FixedV[v]=1;
                   9252:   }
                   9253:   for(v=ncovcol+nqv+ntv+1; v <=ncovcol+nqv+ntv+nqtv;v++){
                   9254:     DummyV[v]=1;
                   9255:     FixedV[v]=1;
                   9256:   }
                   9257:   for(v=1; v <=ncovcol+nqv+ntv+nqtv;v++){
                   9258:     printf("Covariate type in the data: V%d, DummyV(V%d)=%d, FixedV(V%d)=%d\n",v,v,DummyV[v],v,FixedV[v]);
                   9259:     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]);
                   9260:   }
1.126     brouard  9261: 
1.136     brouard  9262:   if((fic=fopen(datafile,"r"))==NULL)    {
1.218     brouard  9263:     printf("Problem while opening datafile: %s with errno='%s'\n", datafile,strerror(errno));fflush(stdout);
                   9264:     fprintf(ficlog,"Problem while opening datafile: %s with errno='%s'\n", datafile,strerror(errno));fflush(ficlog);return 1;
1.136     brouard  9265:   }
1.126     brouard  9266: 
1.302     brouard  9267:     /* Is it a BOM UTF-8 Windows file? */
                   9268:   /* First data line */
                   9269:   linei=0;
                   9270:   while(fgets(line, MAXLINE, fic)) {
                   9271:     noffset=0;
                   9272:     if( line[0] == (char)0xEF && line[1] == (char)0xBB) /* EF BB BF */
                   9273:     {
                   9274:       noffset=noffset+3;
                   9275:       printf("# Data file '%s'  is an UTF8 BOM file, please convert to UTF8 or ascii file and rerun.\n",datafile);fflush(stdout);
                   9276:       fprintf(ficlog,"# Data file '%s'  is an UTF8 BOM file, please convert to UTF8 or ascii file and rerun.\n",datafile);
                   9277:       fflush(ficlog); return 1;
                   9278:     }
                   9279:     /*    else if( line[0] == (char)0xFE && line[1] == (char)0xFF)*/
                   9280:     else if( line[0] == (char)0xFF && line[1] == (char)0xFE)
                   9281:     {
                   9282:       noffset=noffset+2;
1.304     brouard  9283:       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);
                   9284:       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  9285:       fflush(ficlog); return 1;
                   9286:     }
                   9287:     else if( line[0] == 0 && line[1] == 0)
                   9288:     {
                   9289:       if( line[2] == (char)0xFE && line[3] == (char)0xFF){
                   9290:        noffset=noffset+4;
1.304     brouard  9291:        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);
                   9292:        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  9293:        fflush(ficlog); return 1;
                   9294:       }
                   9295:     } else{
                   9296:       ;/*printf(" Not a BOM file\n");*/
                   9297:     }
                   9298:         /* If line starts with a # it is a comment */
                   9299:     if (line[noffset] == '#') {
                   9300:       linei=linei+1;
                   9301:       break;
                   9302:     }else{
                   9303:       break;
                   9304:     }
                   9305:   }
                   9306:   fclose(fic);
                   9307:   if((fic=fopen(datafile,"r"))==NULL)    {
                   9308:     printf("Problem while opening datafile: %s with errno='%s'\n", datafile,strerror(errno));fflush(stdout);
                   9309:     fprintf(ficlog,"Problem while opening datafile: %s with errno='%s'\n", datafile,strerror(errno));fflush(ficlog);return 1;
                   9310:   }
                   9311:   /* Not a Bom file */
                   9312:   
1.136     brouard  9313:   i=1;
                   9314:   while ((fgets(line, MAXLINE, fic) != NULL) &&((i >= firstobs) && (i <=lastobs))) {
                   9315:     linei=linei+1;
                   9316:     for(j=strlen(line); j>=0;j--){  /* Untabifies line */
                   9317:       if(line[j] == '\t')
                   9318:        line[j] = ' ';
                   9319:     }
                   9320:     for(j=strlen(line)-1; (line[j]==' ')||(line[j]==10)||(line[j]==13);j--){
                   9321:       ;
                   9322:     };
                   9323:     line[j+1]=0;  /* Trims blanks at end of line */
                   9324:     if(line[0]=='#'){
                   9325:       fprintf(ficlog,"Comment line\n%s\n",line);
                   9326:       printf("Comment line\n%s\n",line);
                   9327:       continue;
                   9328:     }
                   9329:     trimbb(linetmp,line); /* Trims multiple blanks in line */
1.164     brouard  9330:     strcpy(line, linetmp);
1.223     brouard  9331:     
                   9332:     /* Loops on waves */
                   9333:     for (j=maxwav;j>=1;j--){
                   9334:       for (iv=nqtv;iv>=1;iv--){  /* Loop  on time varying quantitative variables */
1.238     brouard  9335:        cutv(stra, strb, line, ' '); 
                   9336:        if(strb[0]=='.') { /* Missing value */
                   9337:          lval=-1;
                   9338:          cotqvar[j][iv][i]=-1; /* 0.0/0.0 */
                   9339:          cotvar[j][ntv+iv][i]=-1; /* For performance reasons */
                   9340:          if(isalpha(strb[1])) { /* .m or .d Really Missing value */
                   9341:            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);
                   9342:            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);
                   9343:            return 1;
                   9344:          }
                   9345:        }else{
                   9346:          errno=0;
                   9347:          /* what_kind_of_number(strb); */
                   9348:          dval=strtod(strb,&endptr); 
                   9349:          /* if( strb[0]=='\0' || (*endptr != '\0')){ */
                   9350:          /* if(strb != endptr && *endptr == '\0') */
                   9351:          /*    dval=dlval; */
                   9352:          /* if (errno == ERANGE && (lval == LONG_MAX || lval == LONG_MIN)) */
                   9353:          if( strb[0]=='\0' || (*endptr != '\0')){
                   9354:            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);
                   9355:            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);
                   9356:            return 1;
                   9357:          }
                   9358:          cotqvar[j][iv][i]=dval; 
                   9359:          cotvar[j][ntv+iv][i]=dval; 
                   9360:        }
                   9361:        strcpy(line,stra);
1.223     brouard  9362:       }/* end loop ntqv */
1.225     brouard  9363:       
1.223     brouard  9364:       for (iv=ntv;iv>=1;iv--){  /* Loop  on time varying dummies */
1.238     brouard  9365:        cutv(stra, strb, line, ' '); 
                   9366:        if(strb[0]=='.') { /* Missing value */
                   9367:          lval=-1;
                   9368:        }else{
                   9369:          errno=0;
                   9370:          lval=strtol(strb,&endptr,10); 
                   9371:          /*    if (errno == ERANGE && (lval == LONG_MAX || lval == LONG_MIN))*/
                   9372:          if( strb[0]=='\0' || (*endptr != '\0')){
                   9373:            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);
                   9374:            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);
                   9375:            return 1;
                   9376:          }
                   9377:        }
                   9378:        if(lval <-1 || lval >1){
                   9379:          printf("Error reading data around '%ld' at line number %d for individual %d, '%s'\n \
1.223     brouard  9380:  Should be a value of %d(nth) covariate (0 should be the value for the reference and 1\n \
                   9381:  for the alternative. IMaCh does not build design variables automatically, do it yourself.\n \
1.238     brouard  9382:  For example, for multinomial values like 1, 2 and 3,\n                        \
                   9383:  build V1=0 V2=0 for the reference value (1),\n                                \
                   9384:         V1=1 V2=0 for (2) \n                                           \
1.223     brouard  9385:  and V1=0 V2=1 for (3). V1=1 V2=1 should not exist and the corresponding\n \
1.238     brouard  9386:  output of IMaCh is often meaningless.\n                               \
1.223     brouard  9387:  Exiting.\n",lval,linei, i,line,j);
1.238     brouard  9388:          fprintf(ficlog,"Error reading data around '%ld' at line number %d for individual %d, '%s'\n \
1.223     brouard  9389:  Should be a value of %d(nth) covariate (0 should be the value for the reference and 1\n \
                   9390:  for the alternative. IMaCh does not build design variables automatically, do it yourself.\n \
1.238     brouard  9391:  For example, for multinomial values like 1, 2 and 3,\n                        \
                   9392:  build V1=0 V2=0 for the reference value (1),\n                                \
                   9393:         V1=1 V2=0 for (2) \n                                           \
1.223     brouard  9394:  and V1=0 V2=1 for (3). V1=1 V2=1 should not exist and the corresponding\n \
1.238     brouard  9395:  output of IMaCh is often meaningless.\n                               \
1.223     brouard  9396:  Exiting.\n",lval,linei, i,line,j);fflush(ficlog);
1.238     brouard  9397:          return 1;
                   9398:        }
                   9399:        cotvar[j][iv][i]=(double)(lval);
                   9400:        strcpy(line,stra);
1.223     brouard  9401:       }/* end loop ntv */
1.225     brouard  9402:       
1.223     brouard  9403:       /* Statuses  at wave */
1.137     brouard  9404:       cutv(stra, strb, line, ' '); 
1.223     brouard  9405:       if(strb[0]=='.') { /* Missing value */
1.238     brouard  9406:        lval=-1;
1.136     brouard  9407:       }else{
1.238     brouard  9408:        errno=0;
                   9409:        lval=strtol(strb,&endptr,10); 
                   9410:        /*      if (errno == ERANGE && (lval == LONG_MAX || lval == LONG_MIN))*/
                   9411:        if( strb[0]=='\0' || (*endptr != '\0')){
                   9412:          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);
                   9413:          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);
                   9414:          return 1;
                   9415:        }
1.136     brouard  9416:       }
1.225     brouard  9417:       
1.136     brouard  9418:       s[j][i]=lval;
1.225     brouard  9419:       
1.223     brouard  9420:       /* Date of Interview */
1.136     brouard  9421:       strcpy(line,stra);
                   9422:       cutv(stra, strb,line,' ');
1.169     brouard  9423:       if( (iout=sscanf(strb,"%d/%d",&month, &year)) != 0){
1.136     brouard  9424:       }
1.169     brouard  9425:       else  if( (iout=sscanf(strb,"%s.",dummy)) != 0){
1.225     brouard  9426:        month=99;
                   9427:        year=9999;
1.136     brouard  9428:       }else{
1.225     brouard  9429:        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);
                   9430:        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);
                   9431:        return 1;
1.136     brouard  9432:       }
                   9433:       anint[j][i]= (double) year; 
1.302     brouard  9434:       mint[j][i]= (double)month;
                   9435:       /* if( (int)anint[j][i]+ (int)(mint[j][i])/12. < (int) (moisnais[i]/12.+annais[i])){ */
                   9436:       /*       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]); */
                   9437:       /*       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]); */
                   9438:       /* } */
1.136     brouard  9439:       strcpy(line,stra);
1.223     brouard  9440:     } /* End loop on waves */
1.225     brouard  9441:     
1.223     brouard  9442:     /* Date of death */
1.136     brouard  9443:     cutv(stra, strb,line,' '); 
1.169     brouard  9444:     if( (iout=sscanf(strb,"%d/%d",&month, &year)) != 0){
1.136     brouard  9445:     }
1.169     brouard  9446:     else  if( (iout=sscanf(strb,"%s.",dummy)) != 0){
1.136     brouard  9447:       month=99;
                   9448:       year=9999;
                   9449:     }else{
1.141     brouard  9450:       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  9451:       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);
                   9452:       return 1;
1.136     brouard  9453:     }
                   9454:     andc[i]=(double) year; 
                   9455:     moisdc[i]=(double) month; 
                   9456:     strcpy(line,stra);
                   9457:     
1.223     brouard  9458:     /* Date of birth */
1.136     brouard  9459:     cutv(stra, strb,line,' '); 
1.169     brouard  9460:     if( (iout=sscanf(strb,"%d/%d",&month, &year)) != 0){
1.136     brouard  9461:     }
1.169     brouard  9462:     else  if( (iout=sscanf(strb,"%s.", dummy)) != 0){
1.136     brouard  9463:       month=99;
                   9464:       year=9999;
                   9465:     }else{
1.141     brouard  9466:       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);
                   9467:       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  9468:       return 1;
1.136     brouard  9469:     }
                   9470:     if (year==9999) {
1.141     brouard  9471:       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);
                   9472:       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  9473:       return 1;
                   9474:       
1.136     brouard  9475:     }
                   9476:     annais[i]=(double)(year);
1.302     brouard  9477:     moisnais[i]=(double)(month);
                   9478:     for (j=1;j<=maxwav;j++){
                   9479:       if( (int)anint[j][i]+ (int)(mint[j][i])/12. < (int) (moisnais[i]/12.+annais[i])){
                   9480:        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]);
                   9481:        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]);
                   9482:       }
                   9483:     }
                   9484: 
1.136     brouard  9485:     strcpy(line,stra);
1.225     brouard  9486:     
1.223     brouard  9487:     /* Sample weight */
1.136     brouard  9488:     cutv(stra, strb,line,' '); 
                   9489:     errno=0;
                   9490:     dval=strtod(strb,&endptr); 
                   9491:     if( strb[0]=='\0' || (*endptr != '\0')){
1.141     brouard  9492:       printf("Error reading data around '%f' at line number %d, \"%s\" for individual %d\nShould be a weight.  Exiting.\n",dval, i,line,linei);
                   9493:       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  9494:       fflush(ficlog);
                   9495:       return 1;
                   9496:     }
                   9497:     weight[i]=dval; 
                   9498:     strcpy(line,stra);
1.225     brouard  9499:     
1.223     brouard  9500:     for (iv=nqv;iv>=1;iv--){  /* Loop  on fixed quantitative variables */
                   9501:       cutv(stra, strb, line, ' '); 
                   9502:       if(strb[0]=='.') { /* Missing value */
1.225     brouard  9503:        lval=-1;
1.223     brouard  9504:       }else{
1.225     brouard  9505:        errno=0;
                   9506:        /* what_kind_of_number(strb); */
                   9507:        dval=strtod(strb,&endptr);
                   9508:        /* if(strb != endptr && *endptr == '\0') */
                   9509:        /*   dval=dlval; */
                   9510:        /* if (errno == ERANGE && (lval == LONG_MAX || lval == LONG_MIN)) */
                   9511:        if( strb[0]=='\0' || (*endptr != '\0')){
                   9512:          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);
                   9513:          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);
                   9514:          return 1;
                   9515:        }
                   9516:        coqvar[iv][i]=dval; 
1.226     brouard  9517:        covar[ncovcol+iv][i]=dval; /* including qvar in standard covar for performance reasons */ 
1.223     brouard  9518:       }
                   9519:       strcpy(line,stra);
                   9520:     }/* end loop nqv */
1.136     brouard  9521:     
1.223     brouard  9522:     /* Covariate values */
1.136     brouard  9523:     for (j=ncovcol;j>=1;j--){
                   9524:       cutv(stra, strb,line,' '); 
1.223     brouard  9525:       if(strb[0]=='.') { /* Missing covariate value */
1.225     brouard  9526:        lval=-1;
1.136     brouard  9527:       }else{
1.225     brouard  9528:        errno=0;
                   9529:        lval=strtol(strb,&endptr,10); 
                   9530:        if( strb[0]=='\0' || (*endptr != '\0')){
                   9531:          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);
                   9532:          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);
                   9533:          return 1;
                   9534:        }
1.136     brouard  9535:       }
                   9536:       if(lval <-1 || lval >1){
1.225     brouard  9537:        printf("Error reading data around '%ld' at line number %d for individual %d, '%s'\n \
1.136     brouard  9538:  Should be a value of %d(nth) covariate (0 should be the value for the reference and 1\n \
                   9539:  for the alternative. IMaCh does not build design variables automatically, do it yourself.\n \
1.225     brouard  9540:  For example, for multinomial values like 1, 2 and 3,\n                        \
                   9541:  build V1=0 V2=0 for the reference value (1),\n                                \
                   9542:         V1=1 V2=0 for (2) \n                                           \
1.136     brouard  9543:  and V1=0 V2=1 for (3). V1=1 V2=1 should not exist and the corresponding\n \
1.225     brouard  9544:  output of IMaCh is often meaningless.\n                               \
1.136     brouard  9545:  Exiting.\n",lval,linei, i,line,j);
1.225     brouard  9546:        fprintf(ficlog,"Error reading data around '%ld' at line number %d for individual %d, '%s'\n \
1.136     brouard  9547:  Should be a value of %d(nth) covariate (0 should be the value for the reference and 1\n \
                   9548:  for the alternative. IMaCh does not build design variables automatically, do it yourself.\n \
1.225     brouard  9549:  For example, for multinomial values like 1, 2 and 3,\n                        \
                   9550:  build V1=0 V2=0 for the reference value (1),\n                                \
                   9551:         V1=1 V2=0 for (2) \n                                           \
1.136     brouard  9552:  and V1=0 V2=1 for (3). V1=1 V2=1 should not exist and the corresponding\n \
1.225     brouard  9553:  output of IMaCh is often meaningless.\n                               \
1.136     brouard  9554:  Exiting.\n",lval,linei, i,line,j);fflush(ficlog);
1.225     brouard  9555:        return 1;
1.136     brouard  9556:       }
                   9557:       covar[j][i]=(double)(lval);
                   9558:       strcpy(line,stra);
                   9559:     }  
                   9560:     lstra=strlen(stra);
1.225     brouard  9561:     
1.136     brouard  9562:     if(lstra > 9){ /* More than 2**32 or max of what printf can write with %ld */
                   9563:       stratrunc = &(stra[lstra-9]);
                   9564:       num[i]=atol(stratrunc);
                   9565:     }
                   9566:     else
                   9567:       num[i]=atol(stra);
                   9568:     /*if((s[2][i]==2) && (s[3][i]==-1)&&(s[4][i]==9)){
                   9569:       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;}*/
                   9570:     
                   9571:     i=i+1;
                   9572:   } /* End loop reading  data */
1.225     brouard  9573:   
1.136     brouard  9574:   *imax=i-1; /* Number of individuals */
                   9575:   fclose(fic);
1.225     brouard  9576:   
1.136     brouard  9577:   return (0);
1.164     brouard  9578:   /* endread: */
1.225     brouard  9579:   printf("Exiting readdata: ");
                   9580:   fclose(fic);
                   9581:   return (1);
1.223     brouard  9582: }
1.126     brouard  9583: 
1.234     brouard  9584: void removefirstspace(char **stri){/*, char stro[]) {*/
1.230     brouard  9585:   char *p1 = *stri, *p2 = *stri;
1.235     brouard  9586:   while (*p2 == ' ')
1.234     brouard  9587:     p2++; 
                   9588:   /* while ((*p1++ = *p2++) !=0) */
                   9589:   /*   ; */
                   9590:   /* do */
                   9591:   /*   while (*p2 == ' ') */
                   9592:   /*     p2++; */
                   9593:   /* while (*p1++ == *p2++); */
                   9594:   *stri=p2; 
1.145     brouard  9595: }
                   9596: 
1.235     brouard  9597: int decoderesult ( char resultline[], int nres)
1.230     brouard  9598: /**< This routine decode one result line and returns the combination # of dummy covariates only **/
                   9599: {
1.235     brouard  9600:   int j=0, k=0, k1=0, k2=0, k3=0, k4=0, match=0, k2q=0, k3q=0, k4q=0;
1.230     brouard  9601:   char resultsav[MAXLINE];
1.234     brouard  9602:   int resultmodel[MAXLINE];
                   9603:   int modelresult[MAXLINE];
1.230     brouard  9604:   char stra[80], strb[80], strc[80], strd[80],stre[80];
                   9605: 
1.234     brouard  9606:   removefirstspace(&resultline);
1.230     brouard  9607: 
                   9608:   if (strstr(resultline,"v") !=0){
                   9609:     printf("Error. 'v' must be in upper case 'V' result: %s ",resultline);
                   9610:     fprintf(ficlog,"Error. 'v' must be in upper case result: %s ",resultline);fflush(ficlog);
                   9611:     return 1;
                   9612:   }
                   9613:   trimbb(resultsav, resultline);
                   9614:   if (strlen(resultsav) >1){
                   9615:     j=nbocc(resultsav,'='); /**< j=Number of covariate values'=' */
                   9616:   }
1.253     brouard  9617:   if(j == 0){ /* Resultline but no = */
                   9618:     TKresult[nres]=0; /* Combination for the nresult and the model */
                   9619:     return (0);
                   9620:   }
1.234     brouard  9621:   if( j != cptcovs ){ /* Be careful if a variable is in a product but not single */
1.310   ! brouard  9622:     printf("ERROR: the number of variables in the resultline, %d, differs from the number of variables used in the model line, %d.\n",j, cptcovs);
        !          9623:     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  9624:   }
                   9625:   for(k=1; k<=j;k++){ /* Loop on any covariate of the result line */
                   9626:     if(nbocc(resultsav,'=') >1){
                   9627:        cutl(stra,strb,resultsav,' '); /* keeps in strb after the first ' ' 
1.310   ! brouard  9628:                                      resultsav= V4=1 V5=25.1 V3=0 stra= V5=25.1 V3=0 strb= V4=1 */
1.234     brouard  9629:        cutl(strc,strd,strb,'=');  /* strb:V4=1 strc=1 strd=V4 */
                   9630:     }else
                   9631:       cutl(strc,strd,resultsav,'=');
1.230     brouard  9632:     Tvalsel[k]=atof(strc); /* 1 */
1.234     brouard  9633:     
1.230     brouard  9634:     cutl(strc,stre,strd,'V'); /* strd='V4' strc=4 stre='V' */;
                   9635:     Tvarsel[k]=atoi(strc);
                   9636:     /* Typevarsel[k]=1;  /\* 1 for age product *\/ */
                   9637:     /* cptcovsel++;     */
                   9638:     if (nbocc(stra,'=') >0)
                   9639:       strcpy(resultsav,stra); /* and analyzes it */
                   9640:   }
1.235     brouard  9641:   /* Checking for missing or useless values in comparison of current model needs */
1.236     brouard  9642:   for(k1=1; k1<= cptcovt ;k1++){ /* model line V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
                   9643:     if(Typevar[k1]==0){ /* Single covariate in model */
1.234     brouard  9644:       match=0;
1.236     brouard  9645:       for(k2=1; k2 <=j;k2++){/* result line V4=1 V5=24.1 V3=1  V2=8 V1=0 */
1.237     brouard  9646:        if(Tvar[k1]==Tvarsel[k2]) {/* Tvar[1]=5 == Tvarsel[2]=5   */
1.236     brouard  9647:          modelresult[k2]=k1;/* modelresult[2]=1 modelresult[1]=2  modelresult[3]=3  modelresult[6]=4 modelresult[9]=5 */
1.234     brouard  9648:          match=1;
                   9649:          break;
                   9650:        }
                   9651:       }
                   9652:       if(match == 0){
1.310   ! brouard  9653:        printf("Error in result line: V%d is missing in result: %s according to model=%s\n",k1, resultline, model);
        !          9654:        fprintf(ficlog,"Error in result line: V%d is missing in result: %s according to model=%s\n",k1, resultline, model);
        !          9655:        return 1;
1.234     brouard  9656:       }
                   9657:     }
                   9658:   }
1.235     brouard  9659:   /* Checking for missing or useless values in comparison of current model needs */
                   9660:   for(k2=1; k2 <=j;k2++){ /* result line V4=1 V5=24.1 V3=1  V2=8 V1=0 */
1.234     brouard  9661:     match=0;
1.235     brouard  9662:     for(k1=1; k1<= cptcovt ;k1++){ /* model line V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
                   9663:       if(Typevar[k1]==0){ /* Single */
1.237     brouard  9664:        if(Tvar[k1]==Tvarsel[k2]) { /* Tvar[2]=4 == Tvarsel[1]=4   */
1.235     brouard  9665:          resultmodel[k1]=k2;  /* resultmodel[2]=1 resultmodel[1]=2  resultmodel[3]=3  resultmodel[6]=4 resultmodel[9]=5 */
1.234     brouard  9666:          ++match;
                   9667:        }
                   9668:       }
                   9669:     }
                   9670:     if(match == 0){
                   9671:       printf("Error in result line: %d value missing; result: %s, model=%s\n",k1, resultline, model);
1.310   ! brouard  9672:       fprintf(ficlog,"Error in result line: %d value missing; result: %s, model=%s\n",k1, resultline, model);
        !          9673:       return 1;
1.234     brouard  9674:     }else if(match > 1){
                   9675:       printf("Error in result line: %d doubled; result: %s, model=%s\n",k2, resultline, model);
1.310   ! brouard  9676:       fprintf(ficlog,"Error in result line: %d doubled; result: %s, model=%s\n",k2, resultline, model);
        !          9677:       return 1;
1.234     brouard  9678:     }
                   9679:   }
1.235     brouard  9680:       
1.234     brouard  9681:   /* We need to deduce which combination number is chosen and save quantitative values */
1.235     brouard  9682:   /* model line V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
                   9683:   /* result line V4=1 V5=25.1 V3=0  V2=8 V1=1 */
                   9684:   /* should give a combination of dummy V4=1, V3=0, V1=1 => V4*2**(0) + V3*2**(1) + V1*2**(2) = 5 + (1offset) = 6*/
                   9685:   /* result line V4=1 V5=24.1 V3=1  V2=8 V1=0 */
                   9686:   /* should give a combination of dummy V4=1, V3=1, V1=0 => V4*2**(0) + V3*2**(1) + V1*2**(2) = 3 + (1offset) = 4*/
                   9687:   /*    1 0 0 0 */
                   9688:   /*    2 1 0 0 */
                   9689:   /*    3 0 1 0 */ 
                   9690:   /*    4 1 1 0 */ /* V4=1, V3=1, V1=0 */
                   9691:   /*    5 0 0 1 */
                   9692:   /*    6 1 0 1 */ /* V4=1, V3=0, V1=1 */
                   9693:   /*    7 0 1 1 */
                   9694:   /*    8 1 1 1 */
1.237     brouard  9695:   /* V(Tvresult)=Tresult V4=1 V3=0 V1=1 Tresult[nres=1][2]=0 */
                   9696:   /* V(Tvqresult)=Tqresult V5=25.1 V2=8 Tqresult[nres=1][1]=25.1 */
                   9697:   /* V5*age V5 known which value for nres?  */
                   9698:   /* Tqinvresult[2]=8 Tqinvresult[1]=25.1  */
1.235     brouard  9699:   for(k1=1, k=0, k4=0, k4q=0; k1 <=cptcovt;k1++){ /* model line */
                   9700:     if( Dummy[k1]==0 && Typevar[k1]==0 ){ /* Single dummy */
1.237     brouard  9701:       k3= resultmodel[k1]; /* resultmodel[2(V4)] = 1=k3 */
1.235     brouard  9702:       k2=(int)Tvarsel[k3]; /*  Tvarsel[resultmodel[2]]= Tvarsel[1] = 4=k2 */
                   9703:       k+=Tvalsel[k3]*pow(2,k4);  /*  Tvalsel[1]=1  */
1.237     brouard  9704:       Tresult[nres][k4+1]=Tvalsel[k3];/* Tresult[nres][1]=1(V4=1)  Tresult[nres][2]=0(V3=0) */
                   9705:       Tvresult[nres][k4+1]=(int)Tvarsel[k3];/* Tvresult[nres][1]=4 Tvresult[nres][3]=1 */
                   9706:       Tinvresult[nres][(int)Tvarsel[k3]]=Tvalsel[k3]; /* Tinvresult[nres][4]=1 */
1.235     brouard  9707:       printf("Decoderesult Dummy k=%d, V(k2=V%d)= Tvalsel[%d]=%d, 2**(%d)\n",k, k2, k3, (int)Tvalsel[k3], k4);
                   9708:       k4++;;
                   9709:     }  else if( Dummy[k1]==1 && Typevar[k1]==0 ){ /* Single quantitative */
                   9710:       k3q= resultmodel[k1]; /* resultmodel[2] = 1=k3 */
                   9711:       k2q=(int)Tvarsel[k3q]; /*  Tvarsel[resultmodel[2]]= Tvarsel[1] = 4=k2 */
1.237     brouard  9712:       Tqresult[nres][k4q+1]=Tvalsel[k3q]; /* Tqresult[nres][1]=25.1 */
                   9713:       Tvqresult[nres][k4q+1]=(int)Tvarsel[k3q]; /* Tvqresult[nres][1]=5 */
                   9714:       Tqinvresult[nres][(int)Tvarsel[k3q]]=Tvalsel[k3q]; /* Tqinvresult[nres][5]=25.1 */
1.235     brouard  9715:       printf("Decoderesult Quantitative nres=%d, V(k2q=V%d)= Tvalsel[%d]=%d, Tvarsel[%d]=%f\n",nres, k2q, k3q, Tvarsel[k3q], k3q, Tvalsel[k3q]);
                   9716:       k4q++;;
                   9717:     }
                   9718:   }
1.234     brouard  9719:   
1.235     brouard  9720:   TKresult[nres]=++k; /* Combination for the nresult and the model */
1.230     brouard  9721:   return (0);
                   9722: }
1.235     brouard  9723: 
1.230     brouard  9724: int decodemodel( char model[], int lastobs)
                   9725:  /**< This routine decodes the model and returns:
1.224     brouard  9726:        * Model  V1+V2+V3+V8+V7*V8+V5*V6+V8*age+V3*age+age*age
                   9727:        * - nagesqr = 1 if age*age in the model, otherwise 0.
                   9728:        * - cptcovt total number of covariates of the model nbocc(+)+1 = 8 excepting constant and age and age*age
                   9729:        * - cptcovn or number of covariates k of the models excluding age*products =6 and age*age
                   9730:        * - cptcovage number of covariates with age*products =2
                   9731:        * - cptcovs number of simple covariates
                   9732:        * - 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
                   9733:        *     which is a new column after the 9 (ncovcol) variables. 
                   9734:        * - if k is a product Vn*Vm covar[k][i] is filled with correct values for each individual
                   9735:        * - Tprod[l] gives the kth covariates of the product Vn*Vm l=1 to cptcovprod-cptcovage
                   9736:        *    Tprod[1]@2 {5, 6}: position of first product V7*V8 is 5, and second V5*V6 is 6.
                   9737:        * - Tvard[k]  p Tvard[1][1]@4 {7, 8, 5, 6} for V7*V8 and V5*V6 .
                   9738:        */
1.136     brouard  9739: {
1.238     brouard  9740:   int i, j, k, ks, v;
1.227     brouard  9741:   int  j1, k1, k2, k3, k4;
1.136     brouard  9742:   char modelsav[80];
1.145     brouard  9743:   char stra[80], strb[80], strc[80], strd[80],stre[80];
1.187     brouard  9744:   char *strpt;
1.136     brouard  9745: 
1.145     brouard  9746:   /*removespace(model);*/
1.136     brouard  9747:   if (strlen(model) >1){ /* If there is at least 1 covariate */
1.145     brouard  9748:     j=0, j1=0, k1=0, k2=-1, ks=0, cptcovn=0;
1.137     brouard  9749:     if (strstr(model,"AGE") !=0){
1.192     brouard  9750:       printf("Error. AGE must be in lower case 'age' model=1+age+%s. ",model);
                   9751:       fprintf(ficlog,"Error. AGE must be in lower case model=1+age+%s. ",model);fflush(ficlog);
1.136     brouard  9752:       return 1;
                   9753:     }
1.141     brouard  9754:     if (strstr(model,"v") !=0){
                   9755:       printf("Error. 'v' must be in upper case 'V' model=%s ",model);
                   9756:       fprintf(ficlog,"Error. 'v' must be in upper case model=%s ",model);fflush(ficlog);
                   9757:       return 1;
                   9758:     }
1.187     brouard  9759:     strcpy(modelsav,model); 
                   9760:     if ((strpt=strstr(model,"age*age")) !=0){
                   9761:       printf(" strpt=%s, model=%s\n",strpt, model);
                   9762:       if(strpt != model){
1.234     brouard  9763:        printf("Error in model: 'model=%s'; 'age*age' should in first place before other covariates\n \
1.192     brouard  9764:  'model=1+age+age*age+V1.' or 'model=1+age+age*age+V1+V1*age.', please swap as well as \n \
1.187     brouard  9765:  corresponding column of parameters.\n",model);
1.234     brouard  9766:        fprintf(ficlog,"Error in model: 'model=%s'; 'age*age' should in first place before other covariates\n \
1.192     brouard  9767:  'model=1+age+age*age+V1.' or 'model=1+age+age*age+V1+V1*age.', please swap as well as \n \
1.187     brouard  9768:  corresponding column of parameters.\n",model); fflush(ficlog);
1.234     brouard  9769:        return 1;
1.225     brouard  9770:       }
1.187     brouard  9771:       nagesqr=1;
                   9772:       if (strstr(model,"+age*age") !=0)
1.234     brouard  9773:        substrchaine(modelsav, model, "+age*age");
1.187     brouard  9774:       else if (strstr(model,"age*age+") !=0)
1.234     brouard  9775:        substrchaine(modelsav, model, "age*age+");
1.187     brouard  9776:       else 
1.234     brouard  9777:        substrchaine(modelsav, model, "age*age");
1.187     brouard  9778:     }else
                   9779:       nagesqr=0;
                   9780:     if (strlen(modelsav) >1){
                   9781:       j=nbocc(modelsav,'+'); /**< j=Number of '+' */
                   9782:       j1=nbocc(modelsav,'*'); /**< j1=Number of '*' */
1.224     brouard  9783:       cptcovs=j+1-j1; /**<  Number of simple covariates V1+V1*age+V3 +V3*V4+age*age=> V1 + V3 =5-3=2  */
1.187     brouard  9784:       cptcovt= j+1; /* Number of total covariates in the model, not including
1.225     brouard  9785:                     * cst, age and age*age 
                   9786:                     * V1+V1*age+ V3 + V3*V4+age*age=> 3+1=4*/
                   9787:       /* including age products which are counted in cptcovage.
                   9788:        * but the covariates which are products must be treated 
                   9789:        * separately: ncovn=4- 2=2 (V1+V3). */
1.187     brouard  9790:       cptcovprod=j1; /**< Number of products  V1*V2 +v3*age = 2 */
                   9791:       cptcovprodnoage=0; /**< Number of covariate products without age: V3*V4 =1  */
1.225     brouard  9792:       
                   9793:       
1.187     brouard  9794:       /*   Design
                   9795:        *  V1   V2   V3   V4  V5  V6  V7  V8  V9 Weight
                   9796:        *  <          ncovcol=8                >
                   9797:        * Model V2 + V1 + V3*age + V3 + V5*V6 + V7*V8 + V8*age + V8
                   9798:        *   k=  1    2      3       4     5       6      7        8
                   9799:        *  cptcovn number of covariates (not including constant and age ) = # of + plus 1 = 7+1=8
                   9800:        *  covar[k,i], value of kth covariate if not including age for individual i:
1.224     brouard  9801:        *       covar[1][i]= (V1), covar[4][i]=(V4), covar[8][i]=(V8)
                   9802:        *  Tvar[k] # of the kth covariate:  Tvar[1]=2  Tvar[2]=1 Tvar[4]=3 Tvar[8]=8
1.187     brouard  9803:        *       if multiplied by age: V3*age Tvar[3=V3*age]=3 (V3) Tvar[7]=8 and 
                   9804:        *  Tage[++cptcovage]=k
                   9805:        *       if products, new covar are created after ncovcol with k1
                   9806:        *  Tvar[k]=ncovcol+k1; # of the kth covariate product:  Tvar[5]=ncovcol+1=10  Tvar[6]=ncovcol+1=11
                   9807:        *  Tprod[k1]=k; Tprod[1]=5 Tprod[2]= 6; gives the position of the k1th product
                   9808:        *  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
                   9809:        *  Tvar[cptcovn+k2]=Tvard[k1][1];Tvar[cptcovn+k2+1]=Tvard[k1][2];
                   9810:        *  Tvar[8+1]=5;Tvar[8+2]=6;Tvar[8+3]=7;Tvar[8+4]=8 inverted
                   9811:        *  V1   V2   V3   V4  V5  V6  V7  V8  V9  V10  V11
                   9812:        *  <          ncovcol=8                >
                   9813:        *       Model V2 + V1 + V3*age + V3 + V5*V6 + V7*V8 + V8*age + V8    d1   d1   d2  d2
                   9814:        *          k=  1    2      3       4     5       6      7        8    9   10   11  12
                   9815:        *     Tvar[k]= 2    1      3       3    10      11      8        8    5    6    7   8
                   9816:        * p Tvar[1]@12={2,   1,     3,      3,   11,     10,     8,       8,   7,   8,   5,  6}
                   9817:        * p Tprod[1]@2={                         6, 5}
                   9818:        *p Tvard[1][1]@4= {7, 8, 5, 6}
                   9819:        * covar[k][i]= V2   V1      ?      V3    V5*V6?   V7*V8?  ?       V8   
                   9820:        *  cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];
                   9821:        *How to reorganize?
                   9822:        * Model V1 + V2 + V3 + V8 + V5*V6 + V7*V8 + V3*age + V8*age
                   9823:        * Tvars {2,   1,     3,      3,   11,     10,     8,       8,   7,   8,   5,  6}
                   9824:        *       {2,   1,     4,      8,    5,      6,     3,       7}
                   9825:        * Struct []
                   9826:        */
1.225     brouard  9827:       
1.187     brouard  9828:       /* This loop fills the array Tvar from the string 'model'.*/
                   9829:       /* j is the number of + signs in the model V1+V2+V3 j=2 i=3 to 1 */
                   9830:       /*   modelsav=V2+V1+V4+age*V3 strb=age*V3 stra=V2+V1+V4  */
                   9831:       /*       k=4 (age*V3) Tvar[k=4]= 3 (from V3) Tage[cptcovage=1]=4 */
                   9832:       /*       k=3 V4 Tvar[k=3]= 4 (from V4) */
                   9833:       /*       k=2 V1 Tvar[k=2]= 1 (from V1) */
                   9834:       /*       k=1 Tvar[1]=2 (from V2) */
                   9835:       /*       k=5 Tvar[5] */
                   9836:       /* for (k=1; k<=cptcovn;k++) { */
1.198     brouard  9837:       /*       cov[2+k]=nbcode[Tvar[k]][codtabm(ij,Tvar[k])]; */
1.187     brouard  9838:       /*       } */
1.198     brouard  9839:       /* for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,Tvar[Tage[k])]]*cov[2]; */
1.187     brouard  9840:       /*
                   9841:        * Treating invertedly V2+V1+V3*age+V2*V4 is as if written V2*V4 +V3*age + V1 + V2 */
1.227     brouard  9842:       for(k=cptcovt; k>=1;k--){ /**< Number of covariates not including constant and age, neither age*age*/
                   9843:         Tvar[k]=0; Tprod[k]=0; Tposprod[k]=0;
                   9844:       }
1.187     brouard  9845:       cptcovage=0;
                   9846:       for(k=1; k<=cptcovt;k++){ /* Loop on total covariates of the model */
1.234     brouard  9847:        cutl(stra,strb,modelsav,'+'); /* keeps in strb after the first '+' 
1.225     brouard  9848:                                         modelsav==V2+V1+V4+V3*age strb=V3*age stra=V2+V1+V4 */ 
1.234     brouard  9849:        if (nbocc(modelsav,'+')==0) strcpy(strb,modelsav); /* and analyzes it */
                   9850:        /*      printf("i=%d a=%s b=%s sav=%s\n",i, stra,strb,modelsav);*/
                   9851:        /*scanf("%d",i);*/
                   9852:        if (strchr(strb,'*')) {  /**< Model includes a product V2+V1+V4+V3*age strb=V3*age */
                   9853:          cutl(strc,strd,strb,'*'); /**< strd*strc  Vm*Vn: strb=V3*age(input) strc=age strd=V3 ; V3*V2 strc=V2, strd=V3 */
                   9854:          if (strcmp(strc,"age")==0) { /**< Model includes age: Vn*age */
                   9855:            /* covar is not filled and then is empty */
                   9856:            cptcovprod--;
                   9857:            cutl(stre,strb,strd,'V'); /* strd=V3(input): stre="3" */
                   9858:            Tvar[k]=atoi(stre);  /* V2+V1+V4+V3*age Tvar[4]=3 ; V1+V2*age Tvar[2]=2; V1+V1*age Tvar[2]=1 */
                   9859:            Typevar[k]=1;  /* 1 for age product */
                   9860:            cptcovage++; /* Sums the number of covariates which include age as a product */
                   9861:            Tage[cptcovage]=k;  /* Tvar[4]=3, Tage[1] = 4 or V1+V1*age Tvar[2]=1, Tage[1]=2 */
                   9862:            /*printf("stre=%s ", stre);*/
                   9863:          } else if (strcmp(strd,"age")==0) { /* or age*Vn */
                   9864:            cptcovprod--;
                   9865:            cutl(stre,strb,strc,'V');
                   9866:            Tvar[k]=atoi(stre);
                   9867:            Typevar[k]=1;  /* 1 for age product */
                   9868:            cptcovage++;
                   9869:            Tage[cptcovage]=k;
                   9870:          } else {  /* Age is not in the model product V2+V1+V1*V4+V3*age+V3*V2  strb=V3*V2*/
                   9871:            /* loops on k1=1 (V3*V2) and k1=2 V4*V3 */
                   9872:            cptcovn++;
                   9873:            cptcovprodnoage++;k1++;
                   9874:            cutl(stre,strb,strc,'V'); /* strc= Vn, stre is n; strb=V3*V2 stre=3 strc=*/
                   9875:            Tvar[k]=ncovcol+nqv+ntv+nqtv+k1; /* For model-covariate k tells which data-covariate to use but
                   9876:                                                because this model-covariate is a construction we invent a new column
                   9877:                                                which is after existing variables ncovcol+nqv+ntv+nqtv + k1
                   9878:                                                If already ncovcol=4 and model=V2+V1+V1*V4+age*V3+V3*V2
                   9879:                                                Tvar[3=V1*V4]=4+1 Tvar[5=V3*V2]=4 + 2= 6, etc */
                   9880:            Typevar[k]=2;  /* 2 for double fixed dummy covariates */
                   9881:            cutl(strc,strb,strd,'V'); /* strd was Vm, strc is m */
                   9882:            Tprod[k1]=k;  /* Tprod[1]=3(=V1*V4) for V2+V1+V1*V4+age*V3+V3*V2  */
                   9883:            Tposprod[k]=k1; /* Tpsprod[3]=1, Tposprod[2]=5 */
                   9884:            Tvard[k1][1] =atoi(strc); /* m 1 for V1*/
                   9885:            Tvard[k1][2] =atoi(stre); /* n 4 for V4*/
                   9886:            k2=k2+2;  /* k2 is initialize to -1, We want to store the n and m in Vn*Vm at the end of Tvar */
                   9887:            /* Tvar[cptcovt+k2]=Tvard[k1][1]; /\* Tvar[(cptcovt=4+k2=1)=5]= 1 (V1) *\/ */
                   9888:            /* Tvar[cptcovt+k2+1]=Tvard[k1][2];  /\* Tvar[(cptcovt=4+(k2=1)+1)=6]= 4 (V4) *\/ */
1.225     brouard  9889:             /*ncovcol=4 and model=V2+V1+V1*V4+age*V3+V3*V2, Tvar[3]=5, Tvar[4]=6, cptcovt=5 */
1.234     brouard  9890:            /*                     1  2   3      4     5 | Tvar[5+1)=1, Tvar[7]=2   */
                   9891:            for (i=1; i<=lastobs;i++){
                   9892:              /* Computes the new covariate which is a product of
                   9893:                 covar[n][i]* covar[m][i] and stores it at ncovol+k1 May not be defined */
                   9894:              covar[ncovcol+k1][i]=covar[atoi(stre)][i]*covar[atoi(strc)][i];
                   9895:            }
                   9896:          } /* End age is not in the model */
                   9897:        } /* End if model includes a product */
                   9898:        else { /* no more sum */
                   9899:          /*printf("d=%s c=%s b=%s\n", strd,strc,strb);*/
                   9900:          /*  scanf("%d",i);*/
                   9901:          cutl(strd,strc,strb,'V');
                   9902:          ks++; /**< Number of simple covariates dummy or quantitative, fixe or varying */
                   9903:          cptcovn++; /** V4+V3+V5: V4 and V3 timevarying dummy covariates, V5 timevarying quantitative */
                   9904:          Tvar[k]=atoi(strd);
                   9905:          Typevar[k]=0;  /* 0 for simple covariates */
                   9906:        }
                   9907:        strcpy(modelsav,stra);  /* modelsav=V2+V1+V4 stra=V2+V1+V4 */ 
1.223     brouard  9908:                                /*printf("a=%s b=%s sav=%s\n", stra,strb,modelsav);
1.225     brouard  9909:                                  scanf("%d",i);*/
1.187     brouard  9910:       } /* end of loop + on total covariates */
                   9911:     } /* end if strlen(modelsave == 0) age*age might exist */
                   9912:   } /* end if strlen(model == 0) */
1.136     brouard  9913:   
                   9914:   /*The number n of Vn is stored in Tvar. cptcovage =number of age covariate. Tage gives the position of age. cptcovprod= number of products.
                   9915:     If model=V1+V1*age then Tvar[1]=1 Tvar[2]=1 cptcovage=1 Tage[1]=2 cptcovprod=0*/
1.225     brouard  9916:   
1.136     brouard  9917:   /* printf("tvar1=%d tvar2=%d tvar3=%d cptcovage=%d Tage=%d",Tvar[1],Tvar[2],Tvar[3],cptcovage,Tage[1]);
1.225     brouard  9918:      printf("cptcovprod=%d ", cptcovprod);
                   9919:      fprintf(ficlog,"cptcovprod=%d ", cptcovprod);
                   9920:      scanf("%d ",i);*/
                   9921: 
                   9922: 
1.230     brouard  9923: /* Until here, decodemodel knows only the grammar (simple, product, age*) of the model but not what kind
                   9924:    of variable (dummy vs quantitative, fixed vs time varying) is behind. But we know the # of each. */
1.226     brouard  9925: /* ncovcol= 1, nqv=1 | ntv=2, nqtv= 1  = 5 possible variables data: 2 fixed 3, varying
                   9926:    model=        V5 + V4 +V3 + V4*V3 + V5*age + V2 + V1*V2 + V1*age + V5*age, V1 is not used saving its place
                   9927:    k =           1    2   3     4       5       6      7      8        9
                   9928:    Tvar[k]=      5    4   3 1+1+2+1+1=6 5       2      7      1        5
                   9929:    Typevar[k]=   0    0   0     2       1       0      2      1        1
1.227     brouard  9930:    Fixed[k]      1    1   1     1       3       0    0 or 2   2        3
                   9931:    Dummy[k]      1    0   0     0       3       1      1      2        3
                   9932:          Tmodelind[combination of covar]=k;
1.225     brouard  9933: */  
                   9934: /* Dispatching between quantitative and time varying covariates */
1.226     brouard  9935:   /* If Tvar[k] >ncovcol it is a product */
1.225     brouard  9936:   /* 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  9937:        /* Computing effective variables, ie used by the model, that is from the cptcovt variables */
1.227     brouard  9938:   printf("Model=%s\n\
                   9939: Typevar: 0 for simple covariate (dummy, quantitative, fixed or varying), 1 for age product, 2 for  product \n\
                   9940: Fixed[k] 0=fixed (product or simple), 1 varying, 2 fixed with age product, 3 varying with age product \n\
                   9941: 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);
                   9942:   fprintf(ficlog,"Model=%s\n\
                   9943: Typevar: 0 for simple covariate (dummy, quantitative, fixed or varying), 1 for age product, 2 for  product \n\
                   9944: Fixed[k] 0=fixed (product or simple), 1 varying, 2 fixed with age product, 3 varying with age product \n\
                   9945: 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  9946:   for(k=-1;k<=cptcovt; k++){ Fixed[k]=0; Dummy[k]=0;}
1.234     brouard  9947:   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 */
                   9948:     if (Tvar[k] <=ncovcol && Typevar[k]==0 ){ /* Simple fixed dummy (<=ncovcol) covariates */
1.227     brouard  9949:       Fixed[k]= 0;
                   9950:       Dummy[k]= 0;
1.225     brouard  9951:       ncoveff++;
1.232     brouard  9952:       ncovf++;
1.234     brouard  9953:       nsd++;
                   9954:       modell[k].maintype= FTYPE;
                   9955:       TvarsD[nsd]=Tvar[k];
                   9956:       TvarsDind[nsd]=k;
                   9957:       TvarF[ncovf]=Tvar[k];
                   9958:       TvarFind[ncovf]=k;
                   9959:       TvarFD[ncoveff]=Tvar[k]; /* TvarFD[1]=V1 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
                   9960:       TvarFDind[ncoveff]=k; /* TvarFDind[1]=9 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
                   9961:     }else if( Tvar[k] <=ncovcol &&  Typevar[k]==2){ /* Product of fixed dummy (<=ncovcol) covariates */
                   9962:       Fixed[k]= 0;
                   9963:       Dummy[k]= 0;
                   9964:       ncoveff++;
                   9965:       ncovf++;
                   9966:       modell[k].maintype= FTYPE;
                   9967:       TvarF[ncovf]=Tvar[k];
                   9968:       TvarFind[ncovf]=k;
1.230     brouard  9969:       TvarFD[ncoveff]=Tvar[k]; /* TvarFD[1]=V1 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
1.231     brouard  9970:       TvarFDind[ncoveff]=k; /* TvarFDind[1]=9 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
1.240     brouard  9971:     }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  9972:       Fixed[k]= 0;
                   9973:       Dummy[k]= 1;
1.230     brouard  9974:       nqfveff++;
1.234     brouard  9975:       modell[k].maintype= FTYPE;
                   9976:       modell[k].subtype= FQ;
                   9977:       nsq++;
                   9978:       TvarsQ[nsq]=Tvar[k];
                   9979:       TvarsQind[nsq]=k;
1.232     brouard  9980:       ncovf++;
1.234     brouard  9981:       TvarF[ncovf]=Tvar[k];
                   9982:       TvarFind[ncovf]=k;
1.231     brouard  9983:       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  9984:       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  9985:     }else if( Tvar[k] <=ncovcol+nqv+ntv && Typevar[k]==0){/* Only simple time varying dummy variables */
1.227     brouard  9986:       Fixed[k]= 1;
                   9987:       Dummy[k]= 0;
1.225     brouard  9988:       ntveff++; /* Only simple time varying dummy variable */
1.234     brouard  9989:       modell[k].maintype= VTYPE;
                   9990:       modell[k].subtype= VD;
                   9991:       nsd++;
                   9992:       TvarsD[nsd]=Tvar[k];
                   9993:       TvarsDind[nsd]=k;
                   9994:       ncovv++; /* Only simple time varying variables */
                   9995:       TvarV[ncovv]=Tvar[k];
1.242     brouard  9996:       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  9997:       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 */
                   9998:       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  9999:       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);
                   10000:       printf("Quasi TmodelInvind[%d]=%d\n",k,Tvar[k]- ncovcol-nqv);
1.231     brouard  10001:     }else if( Tvar[k] <=ncovcol+nqv+ntv+nqtv  && Typevar[k]==0){ /* Only simple time varying quantitative variable V5*/
1.234     brouard  10002:       Fixed[k]= 1;
                   10003:       Dummy[k]= 1;
                   10004:       nqtveff++;
                   10005:       modell[k].maintype= VTYPE;
                   10006:       modell[k].subtype= VQ;
                   10007:       ncovv++; /* Only simple time varying variables */
                   10008:       nsq++;
                   10009:       TvarsQ[nsq]=Tvar[k];
                   10010:       TvarsQind[nsq]=k;
                   10011:       TvarV[ncovv]=Tvar[k];
1.242     brouard  10012:       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  10013:       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 */
                   10014:       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  10015:       TmodelInvQind[nqtveff]=Tvar[k]- ncovcol-nqv-ntv;/* Only simple time varying quantitative variable */
                   10016:       /* Tmodeliqind[k]=nqtveff;/\* Only simple time varying quantitative variable *\/ */
                   10017:       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  10018:       printf("Quasi TmodelInvQind[%d]=%d\n",k,Tvar[k]- ncovcol-nqv-ntv);
1.227     brouard  10019:     }else if (Typevar[k] == 1) {  /* product with age */
1.234     brouard  10020:       ncova++;
                   10021:       TvarA[ncova]=Tvar[k];
                   10022:       TvarAind[ncova]=k;
1.231     brouard  10023:       if (Tvar[k] <=ncovcol ){ /* Product age with fixed dummy covariatee */
1.240     brouard  10024:        Fixed[k]= 2;
                   10025:        Dummy[k]= 2;
                   10026:        modell[k].maintype= ATYPE;
                   10027:        modell[k].subtype= APFD;
                   10028:        /* ncoveff++; */
1.227     brouard  10029:       }else if( Tvar[k] <=ncovcol+nqv) { /* Remind that product Vn*Vm are added in k*/
1.240     brouard  10030:        Fixed[k]= 2;
                   10031:        Dummy[k]= 3;
                   10032:        modell[k].maintype= ATYPE;
                   10033:        modell[k].subtype= APFQ;                /*      Product age * fixed quantitative */
                   10034:        /* nqfveff++;  /\* Only simple fixed quantitative variable *\/ */
1.227     brouard  10035:       }else if( Tvar[k] <=ncovcol+nqv+ntv ){
1.240     brouard  10036:        Fixed[k]= 3;
                   10037:        Dummy[k]= 2;
                   10038:        modell[k].maintype= ATYPE;
                   10039:        modell[k].subtype= APVD;                /*      Product age * varying dummy */
                   10040:        /* ntveff++; /\* Only simple time varying dummy variable *\/ */
1.227     brouard  10041:       }else if( Tvar[k] <=ncovcol+nqv+ntv+nqtv){
1.240     brouard  10042:        Fixed[k]= 3;
                   10043:        Dummy[k]= 3;
                   10044:        modell[k].maintype= ATYPE;
                   10045:        modell[k].subtype= APVQ;                /*      Product age * varying quantitative */
                   10046:        /* nqtveff++;/\* Only simple time varying quantitative variable *\/ */
1.227     brouard  10047:       }
                   10048:     }else if (Typevar[k] == 2) {  /* product without age */
                   10049:       k1=Tposprod[k];
                   10050:       if(Tvard[k1][1] <=ncovcol){
1.240     brouard  10051:        if(Tvard[k1][2] <=ncovcol){
                   10052:          Fixed[k]= 1;
                   10053:          Dummy[k]= 0;
                   10054:          modell[k].maintype= FTYPE;
                   10055:          modell[k].subtype= FPDD;              /*      Product fixed dummy * fixed dummy */
                   10056:          ncovf++; /* Fixed variables without age */
                   10057:          TvarF[ncovf]=Tvar[k];
                   10058:          TvarFind[ncovf]=k;
                   10059:        }else if(Tvard[k1][2] <=ncovcol+nqv){
                   10060:          Fixed[k]= 0;  /* or 2 ?*/
                   10061:          Dummy[k]= 1;
                   10062:          modell[k].maintype= FTYPE;
                   10063:          modell[k].subtype= FPDQ;              /*      Product fixed dummy * fixed quantitative */
                   10064:          ncovf++; /* Varying variables without age */
                   10065:          TvarF[ncovf]=Tvar[k];
                   10066:          TvarFind[ncovf]=k;
                   10067:        }else if(Tvard[k1][2] <=ncovcol+nqv+ntv){
                   10068:          Fixed[k]= 1;
                   10069:          Dummy[k]= 0;
                   10070:          modell[k].maintype= VTYPE;
                   10071:          modell[k].subtype= VPDD;              /*      Product fixed dummy * varying dummy */
                   10072:          ncovv++; /* Varying variables without age */
                   10073:          TvarV[ncovv]=Tvar[k];
                   10074:          TvarVind[ncovv]=k;
                   10075:        }else if(Tvard[k1][2] <=ncovcol+nqv+ntv+nqtv){
                   10076:          Fixed[k]= 1;
                   10077:          Dummy[k]= 1;
                   10078:          modell[k].maintype= VTYPE;
                   10079:          modell[k].subtype= VPDQ;              /*      Product fixed dummy * varying quantitative */
                   10080:          ncovv++; /* Varying variables without age */
                   10081:          TvarV[ncovv]=Tvar[k];
                   10082:          TvarVind[ncovv]=k;
                   10083:        }
1.227     brouard  10084:       }else if(Tvard[k1][1] <=ncovcol+nqv){
1.240     brouard  10085:        if(Tvard[k1][2] <=ncovcol){
                   10086:          Fixed[k]= 0;  /* or 2 ?*/
                   10087:          Dummy[k]= 1;
                   10088:          modell[k].maintype= FTYPE;
                   10089:          modell[k].subtype= FPDQ;              /*      Product fixed quantitative * fixed dummy */
                   10090:          ncovf++; /* Fixed variables without age */
                   10091:          TvarF[ncovf]=Tvar[k];
                   10092:          TvarFind[ncovf]=k;
                   10093:        }else if(Tvard[k1][2] <=ncovcol+nqv+ntv){
                   10094:          Fixed[k]= 1;
                   10095:          Dummy[k]= 1;
                   10096:          modell[k].maintype= VTYPE;
                   10097:          modell[k].subtype= VPDQ;              /*      Product fixed quantitative * varying dummy */
                   10098:          ncovv++; /* Varying variables without age */
                   10099:          TvarV[ncovv]=Tvar[k];
                   10100:          TvarVind[ncovv]=k;
                   10101:        }else if(Tvard[k1][2] <=ncovcol+nqv+ntv+nqtv){
                   10102:          Fixed[k]= 1;
                   10103:          Dummy[k]= 1;
                   10104:          modell[k].maintype= VTYPE;
                   10105:          modell[k].subtype= VPQQ;              /*      Product fixed quantitative * varying quantitative */
                   10106:          ncovv++; /* Varying variables without age */
                   10107:          TvarV[ncovv]=Tvar[k];
                   10108:          TvarVind[ncovv]=k;
                   10109:          ncovv++; /* Varying variables without age */
                   10110:          TvarV[ncovv]=Tvar[k];
                   10111:          TvarVind[ncovv]=k;
                   10112:        }
1.227     brouard  10113:       }else if(Tvard[k1][1] <=ncovcol+nqv+ntv){
1.240     brouard  10114:        if(Tvard[k1][2] <=ncovcol){
                   10115:          Fixed[k]= 1;
                   10116:          Dummy[k]= 1;
                   10117:          modell[k].maintype= VTYPE;
                   10118:          modell[k].subtype= VPDD;              /*      Product time varying dummy * fixed dummy */
                   10119:          ncovv++; /* Varying variables without age */
                   10120:          TvarV[ncovv]=Tvar[k];
                   10121:          TvarVind[ncovv]=k;
                   10122:        }else if(Tvard[k1][2] <=ncovcol+nqv){
                   10123:          Fixed[k]= 1;
                   10124:          Dummy[k]= 1;
                   10125:          modell[k].maintype= VTYPE;
                   10126:          modell[k].subtype= VPDQ;              /*      Product time varying dummy * fixed quantitative */
                   10127:          ncovv++; /* Varying variables without age */
                   10128:          TvarV[ncovv]=Tvar[k];
                   10129:          TvarVind[ncovv]=k;
                   10130:        }else if(Tvard[k1][2] <=ncovcol+nqv+ntv){
                   10131:          Fixed[k]= 1;
                   10132:          Dummy[k]= 0;
                   10133:          modell[k].maintype= VTYPE;
                   10134:          modell[k].subtype= VPDD;              /*      Product time varying dummy * time varying dummy */
                   10135:          ncovv++; /* Varying variables without age */
                   10136:          TvarV[ncovv]=Tvar[k];
                   10137:          TvarVind[ncovv]=k;
                   10138:        }else if(Tvard[k1][2] <=ncovcol+nqv+ntv+nqtv){
                   10139:          Fixed[k]= 1;
                   10140:          Dummy[k]= 1;
                   10141:          modell[k].maintype= VTYPE;
                   10142:          modell[k].subtype= VPDQ;              /*      Product time varying dummy * time varying quantitative */
                   10143:          ncovv++; /* Varying variables without age */
                   10144:          TvarV[ncovv]=Tvar[k];
                   10145:          TvarVind[ncovv]=k;
                   10146:        }
1.227     brouard  10147:       }else if(Tvard[k1][1] <=ncovcol+nqv+ntv+nqtv){
1.240     brouard  10148:        if(Tvard[k1][2] <=ncovcol){
                   10149:          Fixed[k]= 1;
                   10150:          Dummy[k]= 1;
                   10151:          modell[k].maintype= VTYPE;
                   10152:          modell[k].subtype= VPDQ;              /*      Product time varying quantitative * fixed dummy */
                   10153:          ncovv++; /* Varying variables without age */
                   10154:          TvarV[ncovv]=Tvar[k];
                   10155:          TvarVind[ncovv]=k;
                   10156:        }else if(Tvard[k1][2] <=ncovcol+nqv){
                   10157:          Fixed[k]= 1;
                   10158:          Dummy[k]= 1;
                   10159:          modell[k].maintype= VTYPE;
                   10160:          modell[k].subtype= VPQQ;              /*      Product time varying quantitative * fixed quantitative */
                   10161:          ncovv++; /* Varying variables without age */
                   10162:          TvarV[ncovv]=Tvar[k];
                   10163:          TvarVind[ncovv]=k;
                   10164:        }else if(Tvard[k1][2] <=ncovcol+nqv+ntv){
                   10165:          Fixed[k]= 1;
                   10166:          Dummy[k]= 1;
                   10167:          modell[k].maintype= VTYPE;
                   10168:          modell[k].subtype= VPDQ;              /*      Product time varying quantitative * time varying dummy */
                   10169:          ncovv++; /* Varying variables without age */
                   10170:          TvarV[ncovv]=Tvar[k];
                   10171:          TvarVind[ncovv]=k;
                   10172:        }else if(Tvard[k1][2] <=ncovcol+nqv+ntv+nqtv){
                   10173:          Fixed[k]= 1;
                   10174:          Dummy[k]= 1;
                   10175:          modell[k].maintype= VTYPE;
                   10176:          modell[k].subtype= VPQQ;              /*      Product time varying quantitative * time varying quantitative */
                   10177:          ncovv++; /* Varying variables without age */
                   10178:          TvarV[ncovv]=Tvar[k];
                   10179:          TvarVind[ncovv]=k;
                   10180:        }
1.227     brouard  10181:       }else{
1.240     brouard  10182:        printf("Error unknown type of covariate: Tvard[%d][1]=%d,Tvard[%d][2]=%d\n",k1,Tvard[k1][1],k1,Tvard[k1][2]);
                   10183:        fprintf(ficlog,"Error unknown type of covariate: Tvard[%d][1]=%d,Tvard[%d][2]=%d\n",k1,Tvard[k1][1],k1,Tvard[k1][2]);
                   10184:       } /*end k1*/
1.225     brouard  10185:     }else{
1.226     brouard  10186:       printf("Error, current version can't treat for performance reasons, Tvar[%d]=%d, Typevar[%d]=%d\n", k, Tvar[k], k, Typevar[k]);
                   10187:       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  10188:     }
1.227     brouard  10189:     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  10190:     printf("           modell[%d].maintype=%d, modell[%d].subtype=%d\n",k,modell[k].maintype,k,modell[k].subtype);
1.227     brouard  10191:     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]);
                   10192:   }
                   10193:   /* Searching for doublons in the model */
                   10194:   for(k1=1; k1<= cptcovt;k1++){
                   10195:     for(k2=1; k2 <k1;k2++){
1.285     brouard  10196:       /* if((Typevar[k1]==Typevar[k2]) && (Fixed[Tvar[k1]]==Fixed[Tvar[k2]]) && (Dummy[Tvar[k1]]==Dummy[Tvar[k2]] )){ */
                   10197:       if((Typevar[k1]==Typevar[k2]) && (Fixed[k1]==Fixed[k2]) && (Dummy[k1]==Dummy[k2] )){
1.234     brouard  10198:        if((Typevar[k1] == 0 || Typevar[k1] == 1)){ /* Simple or age product */
                   10199:          if(Tvar[k1]==Tvar[k2]){
1.285     brouard  10200:            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]);
                   10201:            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  10202:            return(1);
                   10203:          }
                   10204:        }else if (Typevar[k1] ==2){
                   10205:          k3=Tposprod[k1];
                   10206:          k4=Tposprod[k2];
                   10207:          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])) ){
                   10208:            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]]);
                   10209:            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);
                   10210:            return(1);
                   10211:          }
                   10212:        }
1.227     brouard  10213:       }
                   10214:     }
1.225     brouard  10215:   }
                   10216:   printf("ncoveff=%d, nqfveff=%d, ntveff=%d, nqtveff=%d, cptcovn=%d\n",ncoveff,nqfveff,ntveff,nqtveff,cptcovn);
                   10217:   fprintf(ficlog,"ncoveff=%d, nqfveff=%d, ntveff=%d, nqtveff=%d, cptcovn=%d\n",ncoveff,nqfveff,ntveff,nqtveff,cptcovn);
1.234     brouard  10218:   printf("ncovf=%d, ncovv=%d, ncova=%d, nsd=%d, nsq=%d\n",ncovf,ncovv,ncova,nsd,nsq);
                   10219:   fprintf(ficlog,"ncovf=%d, ncovv=%d, ncova=%d, nsd=%d, nsq=%d\n",ncovf,ncovv,ncova,nsd, nsq);
1.137     brouard  10220:   return (0); /* with covar[new additional covariate if product] and Tage if age */ 
1.164     brouard  10221:   /*endread:*/
1.225     brouard  10222:   printf("Exiting decodemodel: ");
                   10223:   return (1);
1.136     brouard  10224: }
                   10225: 
1.169     brouard  10226: int calandcheckages(int imx, int maxwav, double *agemin, double *agemax, int *nberr, int *nbwarn )
1.248     brouard  10227: {/* Check ages at death */
1.136     brouard  10228:   int i, m;
1.218     brouard  10229:   int firstone=0;
                   10230:   
1.136     brouard  10231:   for (i=1; i<=imx; i++) {
                   10232:     for(m=2; (m<= maxwav); m++) {
                   10233:       if (((int)mint[m][i]== 99) && (s[m][i] <= nlstate)){
                   10234:        anint[m][i]=9999;
1.216     brouard  10235:        if (s[m][i] != -2) /* Keeping initial status of unknown vital status */
                   10236:          s[m][i]=-1;
1.136     brouard  10237:       }
                   10238:       if((int)moisdc[i]==99 && (int)andc[i]==9999 && s[m][i]>nlstate){
1.260     brouard  10239:        *nberr = *nberr + 1;
1.218     brouard  10240:        if(firstone == 0){
                   10241:          firstone=1;
1.260     brouard  10242:        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  10243:        }
1.262     brouard  10244:        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  10245:        s[m][i]=-1;  /* Droping the death status */
1.136     brouard  10246:       }
                   10247:       if((int)moisdc[i]==99 && (int)andc[i]!=9999 && s[m][i]>nlstate){
1.169     brouard  10248:        (*nberr)++;
1.259     brouard  10249:        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  10250:        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  10251:        s[m][i]=-2; /* We prefer to skip it (and to skip it in version 0.8a1 too */
1.136     brouard  10252:       }
                   10253:     }
                   10254:   }
                   10255: 
                   10256:   for (i=1; i<=imx; i++)  {
                   10257:     agedc[i]=(moisdc[i]/12.+andc[i])-(moisnais[i]/12.+annais[i]);
                   10258:     for(m=firstpass; (m<= lastpass); m++){
1.214     brouard  10259:       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  10260:        if (s[m][i] >= nlstate+1) {
1.169     brouard  10261:          if(agedc[i]>0){
                   10262:            if((int)moisdc[i]!=99 && (int)andc[i]!=9999){
1.136     brouard  10263:              agev[m][i]=agedc[i];
1.214     brouard  10264:              /*if(moisdc[i]==99 && andc[i]==9999) s[m][i]=-1;*/
1.169     brouard  10265:            }else {
1.136     brouard  10266:              if ((int)andc[i]!=9999){
                   10267:                nbwarn++;
                   10268:                printf("Warning negative age at death: %ld line:%d\n",num[i],i);
                   10269:                fprintf(ficlog,"Warning negative age at death: %ld line:%d\n",num[i],i);
                   10270:                agev[m][i]=-1;
                   10271:              }
                   10272:            }
1.169     brouard  10273:          } /* agedc > 0 */
1.214     brouard  10274:        } /* end if */
1.136     brouard  10275:        else if(s[m][i] !=9){ /* Standard case, age in fractional
                   10276:                                 years but with the precision of a month */
                   10277:          agev[m][i]=(mint[m][i]/12.+1./24.+anint[m][i])-(moisnais[i]/12.+1./24.+annais[i]);
                   10278:          if((int)mint[m][i]==99 || (int)anint[m][i]==9999)
                   10279:            agev[m][i]=1;
                   10280:          else if(agev[m][i] < *agemin){ 
                   10281:            *agemin=agev[m][i];
                   10282:            printf(" Min anint[%d][%d]=%.2f annais[%d]=%.2f, agemin=%.2f\n",m,i,anint[m][i], i,annais[i], *agemin);
                   10283:          }
                   10284:          else if(agev[m][i] >*agemax){
                   10285:            *agemax=agev[m][i];
1.156     brouard  10286:            /* printf(" Max anint[%d][%d]=%.0f annais[%d]=%.0f, agemax=%.2f\n",m,i,anint[m][i], i,annais[i], *agemax);*/
1.136     brouard  10287:          }
                   10288:          /*agev[m][i]=anint[m][i]-annais[i];*/
                   10289:          /*     agev[m][i] = age[i]+2*m;*/
1.214     brouard  10290:        } /* en if 9*/
1.136     brouard  10291:        else { /* =9 */
1.214     brouard  10292:          /* printf("Debug num[%d]=%ld s[%d][%d]=%d\n",i,num[i], m,i, s[m][i]); */
1.136     brouard  10293:          agev[m][i]=1;
                   10294:          s[m][i]=-1;
                   10295:        }
                   10296:       }
1.214     brouard  10297:       else if(s[m][i]==0) /*= 0 Unknown */
1.136     brouard  10298:        agev[m][i]=1;
1.214     brouard  10299:       else{
                   10300:        printf("Warning, num[%d]=%ld, s[%d][%d]=%d\n", i, num[i], m, i,s[m][i]); 
                   10301:        fprintf(ficlog, "Warning, num[%d]=%ld, s[%d][%d]=%d\n", i, num[i], m, i,s[m][i]); 
                   10302:        agev[m][i]=0;
                   10303:       }
                   10304:     } /* End for lastpass */
                   10305:   }
1.136     brouard  10306:     
                   10307:   for (i=1; i<=imx; i++)  {
                   10308:     for(m=firstpass; (m<=lastpass); m++){
                   10309:       if (s[m][i] > (nlstate+ndeath)) {
1.169     brouard  10310:        (*nberr)++;
1.136     brouard  10311:        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);     
                   10312:        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);     
                   10313:        return 1;
                   10314:       }
                   10315:     }
                   10316:   }
                   10317: 
                   10318:   /*for (i=1; i<=imx; i++){
                   10319:   for (m=firstpass; (m<lastpass); m++){
                   10320:      printf("%ld %d %.lf %d %d\n", num[i],(covar[1][i]),agev[m][i],s[m][i],s[m+1][i]);
                   10321: }
                   10322: 
                   10323: }*/
                   10324: 
                   10325: 
1.139     brouard  10326:   printf("Total number of individuals= %d, Agemin = %.2f, Agemax= %.2f\n\n", imx, *agemin, *agemax);
                   10327:   fprintf(ficlog,"Total number of individuals= %d, Agemin = %.2f, Agemax= %.2f\n\n", imx, *agemin, *agemax); 
1.136     brouard  10328: 
                   10329:   return (0);
1.164     brouard  10330:  /* endread:*/
1.136     brouard  10331:     printf("Exiting calandcheckages: ");
                   10332:     return (1);
                   10333: }
                   10334: 
1.172     brouard  10335: #if defined(_MSC_VER)
                   10336: /*printf("Visual C++ compiler: %s \n;", _MSC_FULL_VER);*/
                   10337: /*fprintf(ficlog, "Visual C++ compiler: %s \n;", _MSC_FULL_VER);*/
                   10338: //#include "stdafx.h"
                   10339: //#include <stdio.h>
                   10340: //#include <tchar.h>
                   10341: //#include <windows.h>
                   10342: //#include <iostream>
                   10343: typedef BOOL(WINAPI *LPFN_ISWOW64PROCESS) (HANDLE, PBOOL);
                   10344: 
                   10345: LPFN_ISWOW64PROCESS fnIsWow64Process;
                   10346: 
                   10347: BOOL IsWow64()
                   10348: {
                   10349:        BOOL bIsWow64 = FALSE;
                   10350: 
                   10351:        //typedef BOOL (APIENTRY *LPFN_ISWOW64PROCESS)
                   10352:        //  (HANDLE, PBOOL);
                   10353: 
                   10354:        //LPFN_ISWOW64PROCESS fnIsWow64Process;
                   10355: 
                   10356:        HMODULE module = GetModuleHandle(_T("kernel32"));
                   10357:        const char funcName[] = "IsWow64Process";
                   10358:        fnIsWow64Process = (LPFN_ISWOW64PROCESS)
                   10359:                GetProcAddress(module, funcName);
                   10360: 
                   10361:        if (NULL != fnIsWow64Process)
                   10362:        {
                   10363:                if (!fnIsWow64Process(GetCurrentProcess(),
                   10364:                        &bIsWow64))
                   10365:                        //throw std::exception("Unknown error");
                   10366:                        printf("Unknown error\n");
                   10367:        }
                   10368:        return bIsWow64 != FALSE;
                   10369: }
                   10370: #endif
1.177     brouard  10371: 
1.191     brouard  10372: void syscompilerinfo(int logged)
1.292     brouard  10373: {
                   10374: #include <stdint.h>
                   10375: 
                   10376:   /* #include "syscompilerinfo.h"*/
1.185     brouard  10377:    /* command line Intel compiler 32bit windows, XP compatible:*/
                   10378:    /* /GS /W3 /Gy
                   10379:       /Zc:wchar_t /Zi /O2 /Fd"Release\vc120.pdb" /D "WIN32" /D "NDEBUG" /D
                   10380:       "_CONSOLE" /D "_LIB" /D "_USING_V110_SDK71_" /D "_UNICODE" /D
                   10381:       "UNICODE" /Qipo /Zc:forScope /Gd /Oi /MT /Fa"Release\" /EHsc /nologo
1.186     brouard  10382:       /Fo"Release\" /Qprof-dir "Release\" /Fp"Release\IMaCh.pch"
                   10383:    */ 
                   10384:    /* 64 bits */
1.185     brouard  10385:    /*
                   10386:      /GS /W3 /Gy
                   10387:      /Zc:wchar_t /Zi /O2 /Fd"x64\Release\vc120.pdb" /D "WIN32" /D "NDEBUG"
                   10388:      /D "_CONSOLE" /D "_LIB" /D "_UNICODE" /D "UNICODE" /Qipo /Zc:forScope
                   10389:      /Oi /MD /Fa"x64\Release\" /EHsc /nologo /Fo"x64\Release\" /Qprof-dir
                   10390:      "x64\Release\" /Fp"x64\Release\IMaCh.pch" */
                   10391:    /* Optimization are useless and O3 is slower than O2 */
                   10392:    /*
                   10393:      /GS /W3 /Gy /Zc:wchar_t /Zi /O3 /Fd"x64\Release\vc120.pdb" /D "WIN32" 
                   10394:      /D "NDEBUG" /D "_CONSOLE" /D "_LIB" /D "_UNICODE" /D "UNICODE" /Qipo 
                   10395:      /Zc:forScope /Oi /MD /Fa"x64\Release\" /EHsc /nologo /Qparallel 
                   10396:      /Fo"x64\Release\" /Qprof-dir "x64\Release\" /Fp"x64\Release\IMaCh.pch" 
                   10397:    */
1.186     brouard  10398:    /* Link is */ /* /OUT:"visual studio
1.185     brouard  10399:       2013\Projects\IMaCh\Release\IMaCh.exe" /MANIFEST /NXCOMPAT
                   10400:       /PDB:"visual studio
                   10401:       2013\Projects\IMaCh\Release\IMaCh.pdb" /DYNAMICBASE
                   10402:       "kernel32.lib" "user32.lib" "gdi32.lib" "winspool.lib"
                   10403:       "comdlg32.lib" "advapi32.lib" "shell32.lib" "ole32.lib"
                   10404:       "oleaut32.lib" "uuid.lib" "odbc32.lib" "odbccp32.lib"
                   10405:       /MACHINE:X86 /OPT:REF /SAFESEH /INCREMENTAL:NO
                   10406:       /SUBSYSTEM:CONSOLE",5.01" /MANIFESTUAC:"level='asInvoker'
                   10407:       uiAccess='false'"
                   10408:       /ManifestFile:"Release\IMaCh.exe.intermediate.manifest" /OPT:ICF
                   10409:       /NOLOGO /TLBID:1
                   10410:    */
1.292     brouard  10411: 
                   10412: 
1.177     brouard  10413: #if defined __INTEL_COMPILER
1.178     brouard  10414: #if defined(__GNUC__)
                   10415:        struct utsname sysInfo;  /* For Intel on Linux and OS/X */
                   10416: #endif
1.177     brouard  10417: #elif defined(__GNUC__) 
1.179     brouard  10418: #ifndef  __APPLE__
1.174     brouard  10419: #include <gnu/libc-version.h>  /* Only on gnu */
1.179     brouard  10420: #endif
1.177     brouard  10421:    struct utsname sysInfo;
1.178     brouard  10422:    int cross = CROSS;
                   10423:    if (cross){
                   10424:           printf("Cross-");
1.191     brouard  10425:           if(logged) fprintf(ficlog, "Cross-");
1.178     brouard  10426:    }
1.174     brouard  10427: #endif
                   10428: 
1.191     brouard  10429:    printf("Compiled with:");if(logged)fprintf(ficlog,"Compiled with:");
1.169     brouard  10430: #if defined(__clang__)
1.191     brouard  10431:    printf(" Clang/LLVM");if(logged)fprintf(ficlog," Clang/LLVM");      /* Clang/LLVM. ---------------------------------------------- */
1.169     brouard  10432: #endif
                   10433: #if defined(__ICC) || defined(__INTEL_COMPILER)
1.191     brouard  10434:    printf(" Intel ICC/ICPC");if(logged)fprintf(ficlog," Intel ICC/ICPC");/* Intel ICC/ICPC. ------------------------------------------ */
1.169     brouard  10435: #endif
                   10436: #if defined(__GNUC__) || defined(__GNUG__)
1.191     brouard  10437:    printf(" GNU GCC/G++");if(logged)fprintf(ficlog," GNU GCC/G++");/* GNU GCC/G++. --------------------------------------------- */
1.169     brouard  10438: #endif
                   10439: #if defined(__HP_cc) || defined(__HP_aCC)
1.191     brouard  10440:    printf(" Hewlett-Packard C/aC++");if(logged)fprintf(fcilog," Hewlett-Packard C/aC++"); /* Hewlett-Packard C/aC++. ---------------------------------- */
1.169     brouard  10441: #endif
                   10442: #if defined(__IBMC__) || defined(__IBMCPP__)
1.191     brouard  10443:    printf(" IBM XL C/C++"); if(logged) fprintf(ficlog," IBM XL C/C++");/* IBM XL C/C++. -------------------------------------------- */
1.169     brouard  10444: #endif
                   10445: #if defined(_MSC_VER)
1.191     brouard  10446:    printf(" Microsoft Visual Studio");if(logged)fprintf(ficlog," Microsoft Visual Studio");/* Microsoft Visual Studio. --------------------------------- */
1.169     brouard  10447: #endif
                   10448: #if defined(__PGI)
1.191     brouard  10449:    printf(" Portland Group PGCC/PGCPP");if(logged) fprintf(ficlog," Portland Group PGCC/PGCPP");/* Portland Group PGCC/PGCPP. ------------------------------- */
1.169     brouard  10450: #endif
                   10451: #if defined(__SUNPRO_C) || defined(__SUNPRO_CC)
1.191     brouard  10452:    printf(" Oracle Solaris Studio");if(logged)fprintf(ficlog," Oracle Solaris Studio\n");/* Oracle Solaris Studio. ----------------------------------- */
1.167     brouard  10453: #endif
1.191     brouard  10454:    printf(" for "); if (logged) fprintf(ficlog, " for ");
1.169     brouard  10455:    
1.167     brouard  10456: // http://stackoverflow.com/questions/4605842/how-to-identify-platform-compiler-from-preprocessor-macros
                   10457: #ifdef _WIN32 // note the underscore: without it, it's not msdn official!
                   10458:     // Windows (x64 and x86)
1.191     brouard  10459:    printf("Windows (x64 and x86) ");if(logged) fprintf(ficlog,"Windows (x64 and x86) ");
1.167     brouard  10460: #elif __unix__ // all unices, not all compilers
                   10461:     // Unix
1.191     brouard  10462:    printf("Unix ");if(logged) fprintf(ficlog,"Unix ");
1.167     brouard  10463: #elif __linux__
                   10464:     // linux
1.191     brouard  10465:    printf("linux ");if(logged) fprintf(ficlog,"linux ");
1.167     brouard  10466: #elif __APPLE__
1.174     brouard  10467:     // Mac OS, not sure if this is covered by __posix__ and/or __unix__ though..
1.191     brouard  10468:    printf("Mac OS ");if(logged) fprintf(ficlog,"Mac OS ");
1.167     brouard  10469: #endif
                   10470: 
                   10471: /*  __MINGW32__          */
                   10472: /*  __CYGWIN__  */
                   10473: /* __MINGW64__  */
                   10474: // http://msdn.microsoft.com/en-us/library/b0084kay.aspx
                   10475: /* _MSC_VER  //the Visual C++ compiler is 17.00.51106.1, the _MSC_VER macro evaluates to 1700. Type cl /?  */
                   10476: /* _MSC_FULL_VER //the Visual C++ compiler is 15.00.20706.01, the _MSC_FULL_VER macro evaluates to 150020706 */
                   10477: /* _WIN64  // Defined for applications for Win64. */
                   10478: /* _M_X64 // Defined for compilations that target x64 processors. */
                   10479: /* _DEBUG // Defined when you compile with /LDd, /MDd, and /MTd. */
1.171     brouard  10480: 
1.167     brouard  10481: #if UINTPTR_MAX == 0xffffffff
1.191     brouard  10482:    printf(" 32-bit"); if(logged) fprintf(ficlog," 32-bit");/* 32-bit */
1.167     brouard  10483: #elif UINTPTR_MAX == 0xffffffffffffffff
1.191     brouard  10484:    printf(" 64-bit"); if(logged) fprintf(ficlog," 64-bit");/* 64-bit */
1.167     brouard  10485: #else
1.191     brouard  10486:    printf(" wtf-bit"); if(logged) fprintf(ficlog," wtf-bit");/* wtf */
1.167     brouard  10487: #endif
                   10488: 
1.169     brouard  10489: #if defined(__GNUC__)
                   10490: # if defined(__GNUC_PATCHLEVEL__)
                   10491: #  define __GNUC_VERSION__ (__GNUC__ * 10000 \
                   10492:                             + __GNUC_MINOR__ * 100 \
                   10493:                             + __GNUC_PATCHLEVEL__)
                   10494: # else
                   10495: #  define __GNUC_VERSION__ (__GNUC__ * 10000 \
                   10496:                             + __GNUC_MINOR__ * 100)
                   10497: # endif
1.174     brouard  10498:    printf(" using GNU C version %d.\n", __GNUC_VERSION__);
1.191     brouard  10499:    if(logged) fprintf(ficlog, " using GNU C version %d.\n", __GNUC_VERSION__);
1.176     brouard  10500: 
                   10501:    if (uname(&sysInfo) != -1) {
                   10502:      printf("Running on: %s %s %s %s %s\n",sysInfo.sysname, sysInfo.nodename, sysInfo.release, sysInfo.version, sysInfo.machine);
1.191     brouard  10503:         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  10504:    }
                   10505:    else
                   10506:       perror("uname() error");
1.179     brouard  10507:    //#ifndef __INTEL_COMPILER 
                   10508: #if !defined (__INTEL_COMPILER) && !defined(__APPLE__)
1.174     brouard  10509:    printf("GNU libc version: %s\n", gnu_get_libc_version()); 
1.191     brouard  10510:    if(logged) fprintf(ficlog,"GNU libc version: %s\n", gnu_get_libc_version());
1.177     brouard  10511: #endif
1.169     brouard  10512: #endif
1.172     brouard  10513: 
1.286     brouard  10514:    //   void main ()
1.172     brouard  10515:    //   {
1.169     brouard  10516: #if defined(_MSC_VER)
1.174     brouard  10517:    if (IsWow64()){
1.191     brouard  10518:           printf("\nThe program (probably compiled for 32bit) is running under WOW64 (64bit) emulation.\n");
                   10519:           if (logged) fprintf(ficlog, "\nThe program (probably compiled for 32bit) is running under WOW64 (64bit) emulation.\n");
1.174     brouard  10520:    }
                   10521:    else{
1.191     brouard  10522:           printf("\nThe program is not running under WOW64 (i.e probably on a 64bit Windows).\n");
                   10523:           if (logged) fprintf(ficlog, "\nThe programm is not running under WOW64 (i.e probably on a 64bit Windows).\n");
1.174     brouard  10524:    }
1.172     brouard  10525:    //     printf("\nPress Enter to continue...");
                   10526:    //     getchar();
                   10527:    //   }
                   10528: 
1.169     brouard  10529: #endif
                   10530:    
1.167     brouard  10531: 
1.219     brouard  10532: }
1.136     brouard  10533: 
1.219     brouard  10534: int prevalence_limit(double *p, double **prlim, double ageminpar, double agemaxpar, double ftolpl, int *ncvyearp){
1.288     brouard  10535:   /*--------------- Prevalence limit  (forward period or forward stable prevalence) --------------*/
1.235     brouard  10536:   int i, j, k, i1, k4=0, nres=0 ;
1.202     brouard  10537:   /* double ftolpl = 1.e-10; */
1.180     brouard  10538:   double age, agebase, agelim;
1.203     brouard  10539:   double tot;
1.180     brouard  10540: 
1.202     brouard  10541:   strcpy(filerespl,"PL_");
                   10542:   strcat(filerespl,fileresu);
                   10543:   if((ficrespl=fopen(filerespl,"w"))==NULL) {
1.288     brouard  10544:     printf("Problem with forward period (stable) prevalence resultfile: %s\n", filerespl);return 1;
                   10545:     fprintf(ficlog,"Problem with forward period (stable) prevalence resultfile: %s\n", filerespl);return 1;
1.202     brouard  10546:   }
1.288     brouard  10547:   printf("\nComputing forward period (stable) prevalence: result on file '%s' \n", filerespl);
                   10548:   fprintf(ficlog,"\nComputing forward period (stable) prevalence: result on file '%s' \n", filerespl);
1.202     brouard  10549:   pstamp(ficrespl);
1.288     brouard  10550:   fprintf(ficrespl,"# Forward period (stable) prevalence. Precision given by ftolpl=%g \n", ftolpl);
1.202     brouard  10551:   fprintf(ficrespl,"#Age ");
                   10552:   for(i=1; i<=nlstate;i++) fprintf(ficrespl,"%d-%d ",i,i);
                   10553:   fprintf(ficrespl,"\n");
1.180     brouard  10554:   
1.219     brouard  10555:   /* prlim=matrix(1,nlstate,1,nlstate);*/ /* back in main */
1.180     brouard  10556: 
1.219     brouard  10557:   agebase=ageminpar;
                   10558:   agelim=agemaxpar;
1.180     brouard  10559: 
1.227     brouard  10560:   /* i1=pow(2,ncoveff); */
1.234     brouard  10561:   i1=pow(2,cptcoveff); /* Number of combination of dummy covariates */
1.219     brouard  10562:   if (cptcovn < 1){i1=1;}
1.180     brouard  10563: 
1.238     brouard  10564:   for(k=1; k<=i1;k++){ /* For each combination k of dummy covariates in the model */
                   10565:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.253     brouard  10566:       if(i1 != 1 && TKresult[nres]!= k)
1.238     brouard  10567:        continue;
1.235     brouard  10568: 
1.238     brouard  10569:       /* for(cptcov=1,k=0;cptcov<=i1;cptcov++){ */
                   10570:       /* for(cptcov=1,k=0;cptcov<=1;cptcov++){ */
                   10571:       //for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){
                   10572:       /* k=k+1; */
                   10573:       /* to clean */
                   10574:       //printf("cptcov=%d cptcod=%d codtab=%d\n",cptcov, cptcod,codtabm(cptcod,cptcov));
                   10575:       fprintf(ficrespl,"#******");
                   10576:       printf("#******");
                   10577:       fprintf(ficlog,"#******");
                   10578:       for(j=1;j<=cptcoveff ;j++) {/* all covariates */
                   10579:        fprintf(ficrespl," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]); /* Here problem for varying dummy*/
                   10580:        printf(" V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   10581:        fprintf(ficlog," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   10582:       }
                   10583:       for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
                   10584:        printf(" V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
                   10585:        fprintf(ficrespl," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
                   10586:        fprintf(ficlog," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
                   10587:       }
                   10588:       fprintf(ficrespl,"******\n");
                   10589:       printf("******\n");
                   10590:       fprintf(ficlog,"******\n");
                   10591:       if(invalidvarcomb[k]){
                   10592:        printf("\nCombination (%d) ignored because no case \n",k); 
                   10593:        fprintf(ficrespl,"#Combination (%d) ignored because no case \n",k); 
                   10594:        fprintf(ficlog,"\nCombination (%d) ignored because no case \n",k); 
                   10595:        continue;
                   10596:       }
1.219     brouard  10597: 
1.238     brouard  10598:       fprintf(ficrespl,"#Age ");
                   10599:       for(j=1;j<=cptcoveff;j++) {
                   10600:        fprintf(ficrespl,"V%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   10601:       }
                   10602:       for(i=1; i<=nlstate;i++) fprintf(ficrespl,"  %d-%d   ",i,i);
                   10603:       fprintf(ficrespl,"Total Years_to_converge\n");
1.227     brouard  10604:     
1.238     brouard  10605:       for (age=agebase; age<=agelim; age++){
                   10606:        /* for (age=agebase; age<=agebase; age++){ */
                   10607:        prevalim(prlim, nlstate, p, age, oldm, savm, ftolpl, ncvyearp, k, nres);
                   10608:        fprintf(ficrespl,"%.0f ",age );
                   10609:        for(j=1;j<=cptcoveff;j++)
                   10610:          fprintf(ficrespl,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   10611:        tot=0.;
                   10612:        for(i=1; i<=nlstate;i++){
                   10613:          tot +=  prlim[i][i];
                   10614:          fprintf(ficrespl," %.5f", prlim[i][i]);
                   10615:        }
                   10616:        fprintf(ficrespl," %.3f %d\n", tot, *ncvyearp);
                   10617:       } /* Age */
                   10618:       /* was end of cptcod */
                   10619:     } /* cptcov */
                   10620:   } /* nres */
1.219     brouard  10621:   return 0;
1.180     brouard  10622: }
                   10623: 
1.218     brouard  10624: 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  10625:        /*--------------- Back Prevalence limit  (backward stable prevalence) --------------*/
1.218     brouard  10626:        
                   10627:        /* Computes the back prevalence limit  for any combination      of covariate values 
                   10628:    * at any age between ageminpar and agemaxpar
                   10629:         */
1.235     brouard  10630:   int i, j, k, i1, nres=0 ;
1.217     brouard  10631:   /* double ftolpl = 1.e-10; */
                   10632:   double age, agebase, agelim;
                   10633:   double tot;
1.218     brouard  10634:   /* double ***mobaverage; */
                   10635:   /* double     **dnewm, **doldm, **dsavm;  /\* for use *\/ */
1.217     brouard  10636: 
                   10637:   strcpy(fileresplb,"PLB_");
                   10638:   strcat(fileresplb,fileresu);
                   10639:   if((ficresplb=fopen(fileresplb,"w"))==NULL) {
1.288     brouard  10640:     printf("Problem with backward prevalence resultfile: %s\n", fileresplb);return 1;
                   10641:     fprintf(ficlog,"Problem with backward prevalence resultfile: %s\n", fileresplb);return 1;
1.217     brouard  10642:   }
1.288     brouard  10643:   printf("Computing backward prevalence: result on file '%s' \n", fileresplb);
                   10644:   fprintf(ficlog,"Computing backward prevalence: result on file '%s' \n", fileresplb);
1.217     brouard  10645:   pstamp(ficresplb);
1.288     brouard  10646:   fprintf(ficresplb,"# Backward prevalence. Precision given by ftolpl=%g \n", ftolpl);
1.217     brouard  10647:   fprintf(ficresplb,"#Age ");
                   10648:   for(i=1; i<=nlstate;i++) fprintf(ficresplb,"%d-%d ",i,i);
                   10649:   fprintf(ficresplb,"\n");
                   10650:   
1.218     brouard  10651:   
                   10652:   /* prlim=matrix(1,nlstate,1,nlstate);*/ /* back in main */
                   10653:   
                   10654:   agebase=ageminpar;
                   10655:   agelim=agemaxpar;
                   10656:   
                   10657:   
1.227     brouard  10658:   i1=pow(2,cptcoveff);
1.218     brouard  10659:   if (cptcovn < 1){i1=1;}
1.227     brouard  10660:   
1.238     brouard  10661:   for(nres=1; nres <= nresult; nres++){ /* For each resultline */
                   10662:     for(k=1; k<=i1;k++){ /* For any combination of dummy covariates, fixed and varying */
1.253     brouard  10663:      if(i1 != 1 && TKresult[nres]!= k)
1.238     brouard  10664:        continue;
                   10665:       //printf("cptcov=%d cptcod=%d codtab=%d\n",cptcov, cptcod,codtabm(cptcod,cptcov));
                   10666:       fprintf(ficresplb,"#******");
                   10667:       printf("#******");
                   10668:       fprintf(ficlog,"#******");
                   10669:       for(j=1;j<=cptcoveff ;j++) {/* all covariates */
                   10670:        fprintf(ficresplb," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   10671:        printf(" V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   10672:        fprintf(ficlog," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   10673:       }
                   10674:       for (j=1; j<= nsq; j++){ /* For each selected (single) quantitative value */
                   10675:        printf(" V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]);
                   10676:        fprintf(ficresplb," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]);
                   10677:        fprintf(ficlog," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]);
                   10678:       }
                   10679:       fprintf(ficresplb,"******\n");
                   10680:       printf("******\n");
                   10681:       fprintf(ficlog,"******\n");
                   10682:       if(invalidvarcomb[k]){
                   10683:        printf("\nCombination (%d) ignored because no cases \n",k); 
                   10684:        fprintf(ficresplb,"#Combination (%d) ignored because no cases \n",k); 
                   10685:        fprintf(ficlog,"\nCombination (%d) ignored because no cases \n",k); 
                   10686:        continue;
                   10687:       }
1.218     brouard  10688:     
1.238     brouard  10689:       fprintf(ficresplb,"#Age ");
                   10690:       for(j=1;j<=cptcoveff;j++) {
                   10691:        fprintf(ficresplb,"V%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   10692:       }
                   10693:       for(i=1; i<=nlstate;i++) fprintf(ficresplb,"  %d-%d   ",i,i);
                   10694:       fprintf(ficresplb,"Total Years_to_converge\n");
1.218     brouard  10695:     
                   10696:     
1.238     brouard  10697:       for (age=agebase; age<=agelim; age++){
                   10698:        /* for (age=agebase; age<=agebase; age++){ */
                   10699:        if(mobilavproj > 0){
                   10700:          /* bprevalim(bprlim, mobaverage, nlstate, p, age, ageminpar, agemaxpar, oldm, savm, doldm, dsavm, ftolpl, ncvyearp, k); */
                   10701:          /* bprevalim(bprlim, mobaverage, nlstate, p, age, oldm, savm, dnewm, doldm, dsavm, ftolpl, ncvyearp, k); */
1.242     brouard  10702:          bprevalim(bprlim, mobaverage, nlstate, p, age, ftolpl, ncvyearp, k, nres);
1.238     brouard  10703:        }else if (mobilavproj == 0){
                   10704:          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);
                   10705:          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);
                   10706:          exit(1);
                   10707:        }else{
                   10708:          /* bprevalim(bprlim, probs, nlstate, p, age, oldm, savm, dnewm, doldm, dsavm, ftolpl, ncvyearp, k); */
1.242     brouard  10709:          bprevalim(bprlim, probs, nlstate, p, age, ftolpl, ncvyearp, k,nres);
1.266     brouard  10710:          /* printf("TOTOT\n"); */
                   10711:           /* exit(1); */
1.238     brouard  10712:        }
                   10713:        fprintf(ficresplb,"%.0f ",age );
                   10714:        for(j=1;j<=cptcoveff;j++)
                   10715:          fprintf(ficresplb,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   10716:        tot=0.;
                   10717:        for(i=1; i<=nlstate;i++){
                   10718:          tot +=  bprlim[i][i];
                   10719:          fprintf(ficresplb," %.5f", bprlim[i][i]);
                   10720:        }
                   10721:        fprintf(ficresplb," %.3f %d\n", tot, *ncvyearp);
                   10722:       } /* Age */
                   10723:       /* was end of cptcod */
1.255     brouard  10724:       /*fprintf(ficresplb,"\n");*/ /* Seems to be necessary for gnuplot only if two result lines and no covariate. */
1.238     brouard  10725:     } /* end of any combination */
                   10726:   } /* end of nres */  
1.218     brouard  10727:   /* hBijx(p, bage, fage); */
                   10728:   /* fclose(ficrespijb); */
                   10729:   
                   10730:   return 0;
1.217     brouard  10731: }
1.218     brouard  10732:  
1.180     brouard  10733: int hPijx(double *p, int bage, int fage){
                   10734:     /*------------- h Pij x at various ages ------------*/
                   10735: 
                   10736:   int stepsize;
                   10737:   int agelim;
                   10738:   int hstepm;
                   10739:   int nhstepm;
1.235     brouard  10740:   int h, i, i1, j, k, k4, nres=0;
1.180     brouard  10741: 
                   10742:   double agedeb;
                   10743:   double ***p3mat;
                   10744: 
1.201     brouard  10745:     strcpy(filerespij,"PIJ_");  strcat(filerespij,fileresu);
1.180     brouard  10746:     if((ficrespij=fopen(filerespij,"w"))==NULL) {
                   10747:       printf("Problem with Pij resultfile: %s\n", filerespij); return 1;
                   10748:       fprintf(ficlog,"Problem with Pij resultfile: %s\n", filerespij); return 1;
                   10749:     }
                   10750:     printf("Computing pij: result on file '%s' \n", filerespij);
                   10751:     fprintf(ficlog,"Computing pij: result on file '%s' \n", filerespij);
                   10752:   
                   10753:     stepsize=(int) (stepm+YEARM-1)/YEARM;
                   10754:     /*if (stepm<=24) stepsize=2;*/
                   10755: 
                   10756:     agelim=AGESUP;
                   10757:     hstepm=stepsize*YEARM; /* Every year of age */
                   10758:     hstepm=hstepm/stepm; /* Typically 2 years, = 2/6 months = 4 */ 
1.218     brouard  10759:                
1.180     brouard  10760:     /* hstepm=1;   aff par mois*/
                   10761:     pstamp(ficrespij);
                   10762:     fprintf(ficrespij,"#****** h Pij x Probability to be in state j at age x+h being in i at x ");
1.227     brouard  10763:     i1= pow(2,cptcoveff);
1.218     brouard  10764:                /* for(cptcov=1,k=0;cptcov<=i1;cptcov++){ */
                   10765:                /*    /\*for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*\/ */
                   10766:                /*      k=k+1;  */
1.235     brouard  10767:     for(nres=1; nres <= nresult; nres++) /* For each resultline */
                   10768:     for(k=1; k<=i1;k++){
1.253     brouard  10769:       if(i1 != 1 && TKresult[nres]!= k)
1.235     brouard  10770:        continue;
1.183     brouard  10771:       fprintf(ficrespij,"\n#****** ");
1.227     brouard  10772:       for(j=1;j<=cptcoveff;j++) 
1.198     brouard  10773:        fprintf(ficrespij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
1.235     brouard  10774:       for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
                   10775:        printf(" V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
                   10776:        fprintf(ficrespij," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
                   10777:       }
1.183     brouard  10778:       fprintf(ficrespij,"******\n");
                   10779:       
                   10780:       for (agedeb=fage; agedeb>=bage; agedeb--){ /* If stepm=6 months */
                   10781:        nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */ 
                   10782:        nhstepm = nhstepm/hstepm; /* Typically 40/4=10 */
                   10783:        
                   10784:        /*        nhstepm=nhstepm*YEARM; aff par mois*/
1.180     brouard  10785:        
1.183     brouard  10786:        p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   10787:        oldm=oldms;savm=savms;
1.235     brouard  10788:        hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k, nres);  
1.183     brouard  10789:        fprintf(ficrespij,"# Cov Agex agex+h hpijx with i,j=");
                   10790:        for(i=1; i<=nlstate;i++)
                   10791:          for(j=1; j<=nlstate+ndeath;j++)
                   10792:            fprintf(ficrespij," %1d-%1d",i,j);
                   10793:        fprintf(ficrespij,"\n");
                   10794:        for (h=0; h<=nhstepm; h++){
                   10795:          /*agedebphstep = agedeb + h*hstepm/YEARM*stepm;*/
                   10796:          fprintf(ficrespij,"%d %3.f %3.f",k, agedeb, agedeb + h*hstepm/YEARM*stepm );
1.180     brouard  10797:          for(i=1; i<=nlstate;i++)
                   10798:            for(j=1; j<=nlstate+ndeath;j++)
1.183     brouard  10799:              fprintf(ficrespij," %.5f", p3mat[i][j][h]);
1.180     brouard  10800:          fprintf(ficrespij,"\n");
                   10801:        }
1.183     brouard  10802:        free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   10803:        fprintf(ficrespij,"\n");
                   10804:       }
1.180     brouard  10805:       /*}*/
                   10806:     }
1.218     brouard  10807:     return 0;
1.180     brouard  10808: }
1.218     brouard  10809:  
                   10810:  int hBijx(double *p, int bage, int fage, double ***prevacurrent){
1.217     brouard  10811:     /*------------- h Bij x at various ages ------------*/
                   10812: 
                   10813:   int stepsize;
1.218     brouard  10814:   /* int agelim; */
                   10815:        int ageminl;
1.217     brouard  10816:   int hstepm;
                   10817:   int nhstepm;
1.238     brouard  10818:   int h, i, i1, j, k, nres;
1.218     brouard  10819:        
1.217     brouard  10820:   double agedeb;
                   10821:   double ***p3mat;
1.218     brouard  10822:        
                   10823:   strcpy(filerespijb,"PIJB_");  strcat(filerespijb,fileresu);
                   10824:   if((ficrespijb=fopen(filerespijb,"w"))==NULL) {
                   10825:     printf("Problem with Pij back resultfile: %s\n", filerespijb); return 1;
                   10826:     fprintf(ficlog,"Problem with Pij back resultfile: %s\n", filerespijb); return 1;
                   10827:   }
                   10828:   printf("Computing pij back: result on file '%s' \n", filerespijb);
                   10829:   fprintf(ficlog,"Computing pij back: result on file '%s' \n", filerespijb);
                   10830:   
                   10831:   stepsize=(int) (stepm+YEARM-1)/YEARM;
                   10832:   /*if (stepm<=24) stepsize=2;*/
1.217     brouard  10833:   
1.218     brouard  10834:   /* agelim=AGESUP; */
1.289     brouard  10835:   ageminl=AGEINF; /* was 30 */
1.218     brouard  10836:   hstepm=stepsize*YEARM; /* Every year of age */
                   10837:   hstepm=hstepm/stepm; /* Typically 2 years, = 2/6 months = 4 */
                   10838:   
                   10839:   /* hstepm=1;   aff par mois*/
                   10840:   pstamp(ficrespijb);
1.255     brouard  10841:   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  10842:   i1= pow(2,cptcoveff);
1.218     brouard  10843:   /* for(cptcov=1,k=0;cptcov<=i1;cptcov++){ */
                   10844:   /*    /\*for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*\/ */
                   10845:   /*   k=k+1;  */
1.238     brouard  10846:   for(nres=1; nres <= nresult; nres++){ /* For each resultline */
                   10847:     for(k=1; k<=i1;k++){ /* For any combination of dummy covariates, fixed and varying */
1.253     brouard  10848:       if(i1 != 1 && TKresult[nres]!= k)
1.238     brouard  10849:        continue;
                   10850:       fprintf(ficrespijb,"\n#****** ");
                   10851:       for(j=1;j<=cptcoveff;j++)
                   10852:        fprintf(ficrespijb,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   10853:       for (j=1; j<= nsq; j++){ /* For each selected (single) quantitative value */
                   10854:        fprintf(ficrespijb," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]);
                   10855:       }
                   10856:       fprintf(ficrespijb,"******\n");
1.264     brouard  10857:       if(invalidvarcomb[k]){  /* Is it necessary here? */
1.238     brouard  10858:        fprintf(ficrespijb,"\n#Combination (%d) ignored because no cases \n",k); 
                   10859:        continue;
                   10860:       }
                   10861:       
                   10862:       /* for (agedeb=fage; agedeb>=bage; agedeb--){ /\* If stepm=6 months *\/ */
                   10863:       for (agedeb=bage; agedeb<=fage; agedeb++){ /* If stepm=6 months and estepm=24 (2 years) */
                   10864:        /* nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm); /\* Typically 20 years = 20*12/6=40 *\/ */
1.297     brouard  10865:        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 */
                   10866:        nhstepm = nhstepm/hstepm; /* Typically 40/4=10, because estepm=24 stepm=6 => hstepm=24/6=4 or 28*/
1.238     brouard  10867:        
                   10868:        /*        nhstepm=nhstepm*YEARM; aff par mois*/
                   10869:        
1.266     brouard  10870:        p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm); /* We can't have it at an upper level because of nhstepm */
                   10871:        /* and memory limitations if stepm is small */
                   10872: 
1.238     brouard  10873:        /* oldm=oldms;savm=savms; */
                   10874:        /* hbxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);   */
1.267     brouard  10875:        hbxij(p3mat,nhstepm,agedeb,hstepm,p,prevacurrent,nlstate,stepm, k, nres);
1.238     brouard  10876:        /* hbxij(p3mat,nhstepm,agedeb,hstepm,p,prevacurrent,nlstate,stepm,oldm,savm, dnewm, doldm, dsavm, k); */
1.255     brouard  10877:        fprintf(ficrespijb,"# Cov Agex agex-h hbijx with i,j=");
1.217     brouard  10878:        for(i=1; i<=nlstate;i++)
                   10879:          for(j=1; j<=nlstate+ndeath;j++)
1.238     brouard  10880:            fprintf(ficrespijb," %1d-%1d",i,j);
1.217     brouard  10881:        fprintf(ficrespijb,"\n");
1.238     brouard  10882:        for (h=0; h<=nhstepm; h++){
                   10883:          /*agedebphstep = agedeb + h*hstepm/YEARM*stepm;*/
                   10884:          fprintf(ficrespijb,"%d %3.f %3.f",k, agedeb, agedeb - h*hstepm/YEARM*stepm );
                   10885:          /* fprintf(ficrespijb,"%d %3.f %3.f",k, agedeb, agedeb + h*hstepm/YEARM*stepm ); */
                   10886:          for(i=1; i<=nlstate;i++)
                   10887:            for(j=1; j<=nlstate+ndeath;j++)
                   10888:              fprintf(ficrespijb," %.5f", p3mat[i][j][h]);
                   10889:          fprintf(ficrespijb,"\n");
                   10890:        }
                   10891:        free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   10892:        fprintf(ficrespijb,"\n");
                   10893:       } /* end age deb */
                   10894:     } /* end combination */
                   10895:   } /* end nres */
1.218     brouard  10896:   return 0;
                   10897:  } /*  hBijx */
1.217     brouard  10898: 
1.180     brouard  10899: 
1.136     brouard  10900: /***********************************************/
                   10901: /**************** Main Program *****************/
                   10902: /***********************************************/
                   10903: 
                   10904: int main(int argc, char *argv[])
                   10905: {
                   10906: #ifdef GSL
                   10907:   const gsl_multimin_fminimizer_type *T;
                   10908:   size_t iteri = 0, it;
                   10909:   int rval = GSL_CONTINUE;
                   10910:   int status = GSL_SUCCESS;
                   10911:   double ssval;
                   10912: #endif
                   10913:   int movingaverage(double ***probs, double bage,double fage, double ***mobaverage, int mobilav);
1.290     brouard  10914:   int i,j, k, iter=0,m,size=100, cptcod; /* Suppressing because nobs */
                   10915:   /* int i,j, k, n=MAXN,iter=0,m,size=100, cptcod; */
1.209     brouard  10916:   int ncvyear=0; /* Number of years needed for the period prevalence to converge */
1.164     brouard  10917:   int jj, ll, li, lj, lk;
1.136     brouard  10918:   int numlinepar=0; /* Current linenumber of parameter file */
1.197     brouard  10919:   int num_filled;
1.136     brouard  10920:   int itimes;
                   10921:   int NDIM=2;
                   10922:   int vpopbased=0;
1.235     brouard  10923:   int nres=0;
1.258     brouard  10924:   int endishere=0;
1.277     brouard  10925:   int noffset=0;
1.274     brouard  10926:   int ncurrv=0; /* Temporary variable */
                   10927:   
1.164     brouard  10928:   char ca[32], cb[32];
1.136     brouard  10929:   /*  FILE *fichtm; *//* Html File */
                   10930:   /* FILE *ficgp;*/ /*Gnuplot File */
                   10931:   struct stat info;
1.191     brouard  10932:   double agedeb=0.;
1.194     brouard  10933: 
                   10934:   double ageminpar=AGEOVERFLOW,agemin=AGEOVERFLOW, agemaxpar=-AGEOVERFLOW, agemax=-AGEOVERFLOW;
1.219     brouard  10935:   double ageminout=-AGEOVERFLOW,agemaxout=AGEOVERFLOW; /* Smaller Age range redefined after movingaverage */
1.136     brouard  10936: 
1.165     brouard  10937:   double fret;
1.191     brouard  10938:   double dum=0.; /* Dummy variable */
1.136     brouard  10939:   double ***p3mat;
1.218     brouard  10940:   /* double ***mobaverage; */
1.164     brouard  10941: 
                   10942:   char line[MAXLINE];
1.197     brouard  10943:   char path[MAXLINE],pathc[MAXLINE],pathcd[MAXLINE],pathtot[MAXLINE];
                   10944: 
1.234     brouard  10945:   char  modeltemp[MAXLINE];
1.230     brouard  10946:   char resultline[MAXLINE];
                   10947:   
1.136     brouard  10948:   char pathr[MAXLINE], pathimach[MAXLINE]; 
1.164     brouard  10949:   char *tok, *val; /* pathtot */
1.290     brouard  10950:   int firstobs=1, lastobs=10; /* nobs = lastobs-firstobs declared globally ;*/
1.195     brouard  10951:   int c,  h , cpt, c2;
1.191     brouard  10952:   int jl=0;
                   10953:   int i1, j1, jk, stepsize=0;
1.194     brouard  10954:   int count=0;
                   10955: 
1.164     brouard  10956:   int *tab; 
1.136     brouard  10957:   int mobilavproj=0 , prevfcast=0 ; /* moving average of prev, If prevfcast=1 prevalence projection */
1.296     brouard  10958:   /* double anprojd, mprojd, jprojd; /\* For eventual projections *\/ */
                   10959:   /* double anprojf, mprojf, jprojf; */
                   10960:   /* double jintmean,mintmean,aintmean;   */
                   10961:   int prvforecast = 0; /* Might be 1 (date of beginning of projection is a choice or 2 is the dateintmean */
                   10962:   int prvbackcast = 0; /* Might be 1 (date of beginning of projection is a choice or 2 is the dateintmean */
                   10963:   double yrfproj= 10.0; /* Number of years of forward projections */
                   10964:   double yrbproj= 10.0; /* Number of years of backward projections */
                   10965:   int prevbcast=0; /* defined as global for mlikeli and mle, replacing backcast */
1.136     brouard  10966:   int mobilav=0,popforecast=0;
1.191     brouard  10967:   int hstepm=0, nhstepm=0;
1.136     brouard  10968:   int agemortsup;
                   10969:   float  sumlpop=0.;
                   10970:   double jprev1=1, mprev1=1,anprev1=2000,jprev2=1, mprev2=1,anprev2=2000;
                   10971:   double jpyram=1, mpyram=1,anpyram=2000,jpyram1=1, mpyram1=1,anpyram1=2000;
                   10972: 
1.191     brouard  10973:   double bage=0, fage=110., age, agelim=0., agebase=0.;
1.136     brouard  10974:   double ftolpl=FTOL;
                   10975:   double **prlim;
1.217     brouard  10976:   double **bprlim;
1.136     brouard  10977:   double ***param; /* Matrix of parameters */
1.251     brouard  10978:   double ***paramstart; /* Matrix of starting parameter values */
                   10979:   double  *p, *pstart; /* p=param[1][1] pstart is for starting values guessed by freqsummary */
1.136     brouard  10980:   double **matcov; /* Matrix of covariance */
1.203     brouard  10981:   double **hess; /* Hessian matrix */
1.136     brouard  10982:   double ***delti3; /* Scale */
                   10983:   double *delti; /* Scale */
                   10984:   double ***eij, ***vareij;
                   10985:   double **varpl; /* Variances of prevalence limits by age */
1.269     brouard  10986: 
1.136     brouard  10987:   double *epj, vepp;
1.164     brouard  10988: 
1.273     brouard  10989:   double dateprev1, dateprev2;
1.296     brouard  10990:   double jproj1=1,mproj1=1,anproj1=2000,jproj2=1,mproj2=1,anproj2=2000, dateproj1=0, dateproj2=0, dateprojd=0, dateprojf=0;
                   10991:   double jback1=1,mback1=1,anback1=2000,jback2=1,mback2=1,anback2=2000, dateback1=0, dateback2=0, datebackd=0, datebackf=0;
                   10992: 
1.217     brouard  10993: 
1.136     brouard  10994:   double **ximort;
1.145     brouard  10995:   char *alph[]={"a","a","b","c","d","e"}, str[4]="1234";
1.136     brouard  10996:   int *dcwave;
                   10997: 
1.164     brouard  10998:   char z[1]="c";
1.136     brouard  10999: 
                   11000:   /*char  *strt;*/
                   11001:   char strtend[80];
1.126     brouard  11002: 
1.164     brouard  11003: 
1.126     brouard  11004: /*   setlocale (LC_ALL, ""); */
                   11005: /*   bindtextdomain (PACKAGE, LOCALEDIR); */
                   11006: /*   textdomain (PACKAGE); */
                   11007: /*   setlocale (LC_CTYPE, ""); */
                   11008: /*   setlocale (LC_MESSAGES, ""); */
                   11009: 
                   11010:   /*   gettimeofday(&start_time, (struct timezone*)0); */ /* at first time */
1.157     brouard  11011:   rstart_time = time(NULL);  
                   11012:   /*  (void) gettimeofday(&start_time,&tzp);*/
                   11013:   start_time = *localtime(&rstart_time);
1.126     brouard  11014:   curr_time=start_time;
1.157     brouard  11015:   /*tml = *localtime(&start_time.tm_sec);*/
                   11016:   /* strcpy(strstart,asctime(&tml)); */
                   11017:   strcpy(strstart,asctime(&start_time));
1.126     brouard  11018: 
                   11019: /*  printf("Localtime (at start)=%s",strstart); */
1.157     brouard  11020: /*  tp.tm_sec = tp.tm_sec +86400; */
                   11021: /*  tm = *localtime(&start_time.tm_sec); */
1.126     brouard  11022: /*   tmg.tm_year=tmg.tm_year +dsign*dyear; */
                   11023: /*   tmg.tm_mon=tmg.tm_mon +dsign*dmonth; */
                   11024: /*   tmg.tm_hour=tmg.tm_hour + 1; */
1.157     brouard  11025: /*   tp.tm_sec = mktime(&tmg); */
1.126     brouard  11026: /*   strt=asctime(&tmg); */
                   11027: /*   printf("Time(after) =%s",strstart);  */
                   11028: /*  (void) time (&time_value);
                   11029: *  printf("time=%d,t-=%d\n",time_value,time_value-86400);
                   11030: *  tm = *localtime(&time_value);
                   11031: *  strstart=asctime(&tm);
                   11032: *  printf("tim_value=%d,asctime=%s\n",time_value,strstart); 
                   11033: */
                   11034: 
                   11035:   nberr=0; /* Number of errors and warnings */
                   11036:   nbwarn=0;
1.184     brouard  11037: #ifdef WIN32
                   11038:   _getcwd(pathcd, size);
                   11039: #else
1.126     brouard  11040:   getcwd(pathcd, size);
1.184     brouard  11041: #endif
1.191     brouard  11042:   syscompilerinfo(0);
1.196     brouard  11043:   printf("\nIMaCh version %s, %s\n%s",version, copyright, fullversion);
1.126     brouard  11044:   if(argc <=1){
                   11045:     printf("\nEnter the parameter file name: ");
1.205     brouard  11046:     if(!fgets(pathr,FILENAMELENGTH,stdin)){
                   11047:       printf("ERROR Empty parameter file name\n");
                   11048:       goto end;
                   11049:     }
1.126     brouard  11050:     i=strlen(pathr);
                   11051:     if(pathr[i-1]=='\n')
                   11052:       pathr[i-1]='\0';
1.156     brouard  11053:     i=strlen(pathr);
1.205     brouard  11054:     if(i >= 1 && pathr[i-1]==' ') {/* This may happen when dragging on oS/X! */
1.156     brouard  11055:       pathr[i-1]='\0';
1.205     brouard  11056:     }
                   11057:     i=strlen(pathr);
                   11058:     if( i==0 ){
                   11059:       printf("ERROR Empty parameter file name\n");
                   11060:       goto end;
                   11061:     }
                   11062:     for (tok = pathr; tok != NULL; ){
1.126     brouard  11063:       printf("Pathr |%s|\n",pathr);
                   11064:       while ((val = strsep(&tok, "\"" )) != NULL && *val == '\0');
                   11065:       printf("val= |%s| pathr=%s\n",val,pathr);
                   11066:       strcpy (pathtot, val);
                   11067:       if(pathr[0] == '\0') break; /* Dirty */
                   11068:     }
                   11069:   }
1.281     brouard  11070:   else if (argc<=2){
                   11071:     strcpy(pathtot,argv[1]);
                   11072:   }
1.126     brouard  11073:   else{
                   11074:     strcpy(pathtot,argv[1]);
1.281     brouard  11075:     strcpy(z,argv[2]);
                   11076:     printf("\nargv[2]=%s z=%c\n",argv[2],z[0]);
1.126     brouard  11077:   }
                   11078:   /*if(getcwd(pathcd, MAXLINE)!= NULL)printf ("Error pathcd\n");*/
                   11079:   /*cygwin_split_path(pathtot,path,optionfile);
                   11080:     printf("pathtot=%s, path=%s, optionfile=%s\n",pathtot,path,optionfile);*/
                   11081:   /* cutv(path,optionfile,pathtot,'\\');*/
                   11082: 
                   11083:   /* Split argv[0], imach program to get pathimach */
                   11084:   printf("\nargv[0]=%s argv[1]=%s, \n",argv[0],argv[1]);
                   11085:   split(argv[0],pathimach,optionfile,optionfilext,optionfilefiname);
                   11086:   printf("\nargv[0]=%s pathimach=%s, \noptionfile=%s \noptionfilext=%s \noptionfilefiname=%s\n",argv[0],pathimach,optionfile,optionfilext,optionfilefiname);
                   11087:  /*   strcpy(pathimach,argv[0]); */
                   11088:   /* Split argv[1]=pathtot, parameter file name to get path, optionfile, extension and name */
                   11089:   split(pathtot,path,optionfile,optionfilext,optionfilefiname);
                   11090:   printf("\npathtot=%s,\npath=%s,\noptionfile=%s \noptionfilext=%s \noptionfilefiname=%s\n",pathtot,path,optionfile,optionfilext,optionfilefiname);
1.184     brouard  11091: #ifdef WIN32
                   11092:   _chdir(path); /* Can be a relative path */
                   11093:   if(_getcwd(pathcd,MAXLINE) > 0) /* So pathcd is the full path */
                   11094: #else
1.126     brouard  11095:   chdir(path); /* Can be a relative path */
1.184     brouard  11096:   if (getcwd(pathcd, MAXLINE) > 0) /* So pathcd is the full path */
                   11097: #endif
                   11098:   printf("Current directory %s!\n",pathcd);
1.126     brouard  11099:   strcpy(command,"mkdir ");
                   11100:   strcat(command,optionfilefiname);
                   11101:   if((outcmd=system(command)) != 0){
1.169     brouard  11102:     printf("Directory already exists (or can't create it) %s%s, err=%d\n",path,optionfilefiname,outcmd);
1.126     brouard  11103:     /* fprintf(ficlog,"Problem creating directory %s%s\n",path,optionfilefiname); */
                   11104:     /* fclose(ficlog); */
                   11105: /*     exit(1); */
                   11106:   }
                   11107: /*   if((imk=mkdir(optionfilefiname))<0){ */
                   11108: /*     perror("mkdir"); */
                   11109: /*   } */
                   11110: 
                   11111:   /*-------- arguments in the command line --------*/
                   11112: 
1.186     brouard  11113:   /* Main Log file */
1.126     brouard  11114:   strcat(filelog, optionfilefiname);
                   11115:   strcat(filelog,".log");    /* */
                   11116:   if((ficlog=fopen(filelog,"w"))==NULL)    {
                   11117:     printf("Problem with logfile %s\n",filelog);
                   11118:     goto end;
                   11119:   }
                   11120:   fprintf(ficlog,"Log filename:%s\n",filelog);
1.197     brouard  11121:   fprintf(ficlog,"Version %s %s",version,fullversion);
1.126     brouard  11122:   fprintf(ficlog,"\nEnter the parameter file name: \n");
                   11123:   fprintf(ficlog,"pathimach=%s\npathtot=%s\n\
                   11124:  path=%s \n\
                   11125:  optionfile=%s\n\
                   11126:  optionfilext=%s\n\
1.156     brouard  11127:  optionfilefiname='%s'\n",pathimach,pathtot,path,optionfile,optionfilext,optionfilefiname);
1.126     brouard  11128: 
1.197     brouard  11129:   syscompilerinfo(1);
1.167     brouard  11130: 
1.126     brouard  11131:   printf("Local time (at start):%s",strstart);
                   11132:   fprintf(ficlog,"Local time (at start): %s",strstart);
                   11133:   fflush(ficlog);
                   11134: /*   (void) gettimeofday(&curr_time,&tzp); */
1.157     brouard  11135: /*   printf("Elapsed time %d\n", asc_diff_time(curr_time.tm_sec-start_time.tm_sec,tmpout)); */
1.126     brouard  11136: 
                   11137:   /* */
                   11138:   strcpy(fileres,"r");
                   11139:   strcat(fileres, optionfilefiname);
1.201     brouard  11140:   strcat(fileresu, optionfilefiname); /* Without r in front */
1.126     brouard  11141:   strcat(fileres,".txt");    /* Other files have txt extension */
1.201     brouard  11142:   strcat(fileresu,".txt");    /* Other files have txt extension */
1.126     brouard  11143: 
1.186     brouard  11144:   /* Main ---------arguments file --------*/
1.126     brouard  11145: 
                   11146:   if((ficpar=fopen(optionfile,"r"))==NULL)    {
1.155     brouard  11147:     printf("Problem with optionfile '%s' with errno='%s'\n",optionfile,strerror(errno));
                   11148:     fprintf(ficlog,"Problem with optionfile '%s' with errno='%s'\n",optionfile,strerror(errno));
1.126     brouard  11149:     fflush(ficlog);
1.149     brouard  11150:     /* goto end; */
                   11151:     exit(70); 
1.126     brouard  11152:   }
                   11153: 
                   11154:   strcpy(filereso,"o");
1.201     brouard  11155:   strcat(filereso,fileresu);
1.126     brouard  11156:   if((ficparo=fopen(filereso,"w"))==NULL) { /* opened on subdirectory */
                   11157:     printf("Problem with Output resultfile: %s\n", filereso);
                   11158:     fprintf(ficlog,"Problem with Output resultfile: %s\n", filereso);
                   11159:     fflush(ficlog);
                   11160:     goto end;
                   11161:   }
1.278     brouard  11162:       /*-------- Rewriting parameter file ----------*/
                   11163:   strcpy(rfileres,"r");    /* "Rparameterfile */
                   11164:   strcat(rfileres,optionfilefiname);    /* Parameter file first name */
                   11165:   strcat(rfileres,".");    /* */
                   11166:   strcat(rfileres,optionfilext);    /* Other files have txt extension */
                   11167:   if((ficres =fopen(rfileres,"w"))==NULL) {
                   11168:     printf("Problem writing new parameter file: %s\n", rfileres);goto end;
                   11169:     fprintf(ficlog,"Problem writing new parameter file: %s\n", rfileres);goto end;
                   11170:     fflush(ficlog);
                   11171:     goto end;
                   11172:   }
                   11173:   fprintf(ficres,"#IMaCh %s\n",version);
1.126     brouard  11174: 
1.278     brouard  11175:                                      
1.126     brouard  11176:   /* Reads comments: lines beginning with '#' */
                   11177:   numlinepar=0;
1.277     brouard  11178:   /* Is it a BOM UTF-8 Windows file? */
                   11179:   /* First parameter line */
1.197     brouard  11180:   while(fgets(line, MAXLINE, ficpar)) {
1.277     brouard  11181:     noffset=0;
                   11182:     if( line[0] == (char)0xEF && line[1] == (char)0xBB) /* EF BB BF */
                   11183:     {
                   11184:       noffset=noffset+3;
                   11185:       printf("# File is an UTF8 Bom.\n"); // 0xBF
                   11186:     }
1.302     brouard  11187: /*    else if( line[0] == (char)0xFE && line[1] == (char)0xFF)*/
                   11188:     else if( line[0] == (char)0xFF && line[1] == (char)0xFE)
1.277     brouard  11189:     {
                   11190:       noffset=noffset+2;
                   11191:       printf("# File is an UTF16BE BOM file\n");
                   11192:     }
                   11193:     else if( line[0] == 0 && line[1] == 0)
                   11194:     {
                   11195:       if( line[2] == (char)0xFE && line[3] == (char)0xFF){
                   11196:        noffset=noffset+4;
                   11197:        printf("# File is an UTF16BE BOM file\n");
                   11198:       }
                   11199:     } else{
                   11200:       ;/*printf(" Not a BOM file\n");*/
                   11201:     }
                   11202:   
1.197     brouard  11203:     /* If line starts with a # it is a comment */
1.277     brouard  11204:     if (line[noffset] == '#') {
1.197     brouard  11205:       numlinepar++;
                   11206:       fputs(line,stdout);
                   11207:       fputs(line,ficparo);
1.278     brouard  11208:       fputs(line,ficres);
1.197     brouard  11209:       fputs(line,ficlog);
                   11210:       continue;
                   11211:     }else
                   11212:       break;
                   11213:   }
                   11214:   if((num_filled=sscanf(line,"title=%s datafile=%s lastobs=%d firstpass=%d lastpass=%d\n", \
                   11215:                        title, datafile, &lastobs, &firstpass,&lastpass)) !=EOF){
                   11216:     if (num_filled != 5) {
                   11217:       printf("Should be 5 parameters\n");
1.283     brouard  11218:       fprintf(ficlog,"Should be 5 parameters\n");
1.197     brouard  11219:     }
1.126     brouard  11220:     numlinepar++;
1.197     brouard  11221:     printf("title=%s datafile=%s lastobs=%d firstpass=%d lastpass=%d\n", title, datafile, lastobs, firstpass,lastpass);
1.283     brouard  11222:     fprintf(ficparo,"title=%s datafile=%s lastobs=%d firstpass=%d lastpass=%d\n", title, datafile, lastobs, firstpass,lastpass);
                   11223:     fprintf(ficres,"title=%s datafile=%s lastobs=%d firstpass=%d lastpass=%d\n", title, datafile, lastobs, firstpass,lastpass);
                   11224:     fprintf(ficlog,"title=%s datafile=%s lastobs=%d firstpass=%d lastpass=%d\n", title, datafile, lastobs, firstpass,lastpass);
1.197     brouard  11225:   }
                   11226:   /* Second parameter line */
                   11227:   while(fgets(line, MAXLINE, ficpar)) {
1.283     brouard  11228:     /* while(fscanf(ficpar,"%[^\n]", line)) { */
                   11229:     /* If line starts with a # it is a comment. Strangely fgets reads the EOL and fputs doesn't */
1.197     brouard  11230:     if (line[0] == '#') {
                   11231:       numlinepar++;
1.283     brouard  11232:       printf("%s",line);
                   11233:       fprintf(ficres,"%s",line);
                   11234:       fprintf(ficparo,"%s",line);
                   11235:       fprintf(ficlog,"%s",line);
1.197     brouard  11236:       continue;
                   11237:     }else
                   11238:       break;
                   11239:   }
1.223     brouard  11240:   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", \
                   11241:                        &ftol, &stepm, &ncovcol, &nqv, &ntv, &nqtv, &nlstate, &ndeath, &maxwav, &mle, &weightopt)) !=EOF){
                   11242:     if (num_filled != 11) {
                   11243:       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  11244:       printf("but line=%s\n",line);
1.283     brouard  11245:       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");
                   11246:       fprintf(ficlog,"but line=%s\n",line);
1.197     brouard  11247:     }
1.286     brouard  11248:     if( lastpass > maxwav){
                   11249:       printf("Error (lastpass = %d) > (maxwav = %d)\n",lastpass, maxwav);
                   11250:       fprintf(ficlog,"Error (lastpass = %d) > (maxwav = %d)\n",lastpass, maxwav);
                   11251:       fflush(ficlog);
                   11252:       goto end;
                   11253:     }
                   11254:       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  11255:     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  11256:     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  11257:     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  11258:   }
1.203     brouard  11259:   /* ftolpl=6*ftol*1.e5; /\* 6.e-3 make convergences in less than 80 loops for the prevalence limit *\/ */
1.209     brouard  11260:   /*ftolpl=6.e-4; *//* 6.e-3 make convergences in less than 80 loops for the prevalence limit */
1.197     brouard  11261:   /* Third parameter line */
                   11262:   while(fgets(line, MAXLINE, ficpar)) {
                   11263:     /* If line starts with a # it is a comment */
                   11264:     if (line[0] == '#') {
                   11265:       numlinepar++;
1.283     brouard  11266:       printf("%s",line);
                   11267:       fprintf(ficres,"%s",line);
                   11268:       fprintf(ficparo,"%s",line);
                   11269:       fprintf(ficlog,"%s",line);
1.197     brouard  11270:       continue;
                   11271:     }else
                   11272:       break;
                   11273:   }
1.201     brouard  11274:   if((num_filled=sscanf(line,"model=1+age%[^.\n]", model)) !=EOF){
1.279     brouard  11275:     if (num_filled != 1){
1.302     brouard  11276:       printf("ERROR %d: Model should be at minimum 'model=1+age+' instead of '%s'\n",num_filled, line);
                   11277:       fprintf(ficlog,"ERROR %d: Model should be at minimum 'model=1+age+' instead of '%s'\n",num_filled, line);
1.197     brouard  11278:       model[0]='\0';
                   11279:       goto end;
                   11280:     }
                   11281:     else{
                   11282:       if (model[0]=='+'){
                   11283:        for(i=1; i<=strlen(model);i++)
                   11284:          modeltemp[i-1]=model[i];
1.201     brouard  11285:        strcpy(model,modeltemp); 
1.197     brouard  11286:       }
                   11287:     }
1.199     brouard  11288:     /* printf(" model=1+age%s modeltemp= %s, model=%s\n",model, modeltemp, model);fflush(stdout); */
1.203     brouard  11289:     printf("model=1+age+%s\n",model);fflush(stdout);
1.283     brouard  11290:     fprintf(ficparo,"model=1+age+%s\n",model);fflush(stdout);
                   11291:     fprintf(ficres,"model=1+age+%s\n",model);fflush(stdout);
                   11292:     fprintf(ficlog,"model=1+age+%s\n",model);fflush(stdout);
1.197     brouard  11293:   }
                   11294:   /* 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); */
                   11295:   /* numlinepar=numlinepar+3; /\* In general *\/ */
                   11296:   /* 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  11297:   /* 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); */
                   11298:   /* 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  11299:   fflush(ficlog);
1.190     brouard  11300:   /* if(model[0]=='#'|| model[0]== '\0'){ */
                   11301:   if(model[0]=='#'){
1.279     brouard  11302:     printf("Error in 'model' line: model should start with 'model=1+age+' and end without space \n \
                   11303:  'model=1+age+' or 'model=1+age+V1.' or 'model=1+age+age*age+V1+V1*age' or \n \
                   11304:  'model=1+age+V1+V2' or 'model=1+age+V1+V2+V1*V2' etc. \n");           \
1.187     brouard  11305:     if(mle != -1){
1.279     brouard  11306:       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  11307:       exit(1);
                   11308:     }
                   11309:   }
1.126     brouard  11310:   while((c=getc(ficpar))=='#' && c!= EOF){
                   11311:     ungetc(c,ficpar);
                   11312:     fgets(line, MAXLINE, ficpar);
                   11313:     numlinepar++;
1.195     brouard  11314:     if(line[1]=='q'){ /* This #q will quit imach (the answer is q) */
                   11315:       z[0]=line[1];
                   11316:     }
                   11317:     /* printf("****line [1] = %c \n",line[1]); */
1.141     brouard  11318:     fputs(line, stdout);
                   11319:     //puts(line);
1.126     brouard  11320:     fputs(line,ficparo);
                   11321:     fputs(line,ficlog);
                   11322:   }
                   11323:   ungetc(c,ficpar);
                   11324: 
                   11325:    
1.290     brouard  11326:   covar=matrix(0,NCOVMAX,firstobs,lastobs);  /**< used in readdata */
                   11327:   if(nqv>=1)coqvar=matrix(1,nqv,firstobs,lastobs);  /**< Fixed quantitative covariate */
                   11328:   if(nqtv>=1)cotqvar=ma3x(1,maxwav,1,nqtv,firstobs,lastobs);  /**< Time varying quantitative covariate */
                   11329:   if(ntv+nqtv>=1)cotvar=ma3x(1,maxwav,1,ntv+nqtv,firstobs,lastobs);  /**< Time varying covariate (dummy and quantitative)*/
1.136     brouard  11330:   cptcovn=0; /*Number of covariates, i.e. number of '+' in model statement plus one, indepently of n in Vn*/
                   11331:   /* v1+v2+v3+v2*v4+v5*age makes cptcovn = 5
                   11332:      v1+v2*age+v2*v3 makes cptcovn = 3
                   11333:   */
                   11334:   if (strlen(model)>1) 
1.187     brouard  11335:     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  11336:   else
1.187     brouard  11337:     ncovmodel=2; /* Constant and age */
1.133     brouard  11338:   nforce= (nlstate+ndeath-1)*nlstate; /* Number of forces ij from state i to j */
                   11339:   npar= nforce*ncovmodel; /* Number of parameters like aij*/
1.131     brouard  11340:   if(npar >MAXPARM || nlstate >NLSTATEMAX || ndeath >NDEATHMAX || ncovmodel>NCOVMAX){
                   11341:     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);
                   11342:     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);
                   11343:     fflush(stdout);
                   11344:     fclose (ficlog);
                   11345:     goto end;
                   11346:   }
1.126     brouard  11347:   delti3= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
                   11348:   delti=delti3[1][1];
                   11349:   /*delti=vector(1,npar); *//* Scale of each paramater (output from hesscov)*/
                   11350:   if(mle==-1){ /* Print a wizard for help writing covariance matrix */
1.247     brouard  11351: /* We could also provide initial parameters values giving by simple logistic regression 
                   11352:  * only one way, that is without matrix product. We will have nlstate maximizations */
                   11353:       /* for(i=1;i<nlstate;i++){ */
                   11354:       /*       /\*reducing xi for 1 to npar to 1 to ncovmodel; *\/ */
                   11355:       /*    mlikeli(ficres,p, ncovmodel, ncovmodel, nlstate, ftol, funcnoprod); */
                   11356:       /* } */
1.126     brouard  11357:     prwizard(ncovmodel, nlstate, ndeath, model, ficparo);
1.191     brouard  11358:     printf(" You chose mle=-1, look at file %s for a template of covariance matrix \n",filereso);
                   11359:     fprintf(ficlog," You chose mle=-1, look at file %s for a template of covariance matrix \n",filereso);
1.126     brouard  11360:     free_ma3x(delti3,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel); 
                   11361:     fclose (ficparo);
                   11362:     fclose (ficlog);
                   11363:     goto end;
                   11364:     exit(0);
1.220     brouard  11365:   }  else if(mle==-5) { /* Main Wizard */
1.126     brouard  11366:     prwizard(ncovmodel, nlstate, ndeath, model, ficparo);
1.192     brouard  11367:     printf(" You chose mle=-3, look at file %s for a template of covariance matrix \n",filereso);
                   11368:     fprintf(ficlog," You chose mle=-3, look at file %s for a template of covariance matrix \n",filereso);
1.126     brouard  11369:     param= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
                   11370:     matcov=matrix(1,npar,1,npar);
1.203     brouard  11371:     hess=matrix(1,npar,1,npar);
1.220     brouard  11372:   }  else{ /* Begin of mle != -1 or -5 */
1.145     brouard  11373:     /* Read guessed parameters */
1.126     brouard  11374:     /* Reads comments: lines beginning with '#' */
                   11375:     while((c=getc(ficpar))=='#' && c!= EOF){
                   11376:       ungetc(c,ficpar);
                   11377:       fgets(line, MAXLINE, ficpar);
                   11378:       numlinepar++;
1.141     brouard  11379:       fputs(line,stdout);
1.126     brouard  11380:       fputs(line,ficparo);
                   11381:       fputs(line,ficlog);
                   11382:     }
                   11383:     ungetc(c,ficpar);
                   11384:     
                   11385:     param= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
1.251     brouard  11386:     paramstart= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
1.126     brouard  11387:     for(i=1; i <=nlstate; i++){
1.234     brouard  11388:       j=0;
1.126     brouard  11389:       for(jj=1; jj <=nlstate+ndeath; jj++){
1.234     brouard  11390:        if(jj==i) continue;
                   11391:        j++;
1.292     brouard  11392:        while((c=getc(ficpar))=='#' && c!= EOF){
                   11393:          ungetc(c,ficpar);
                   11394:          fgets(line, MAXLINE, ficpar);
                   11395:          numlinepar++;
                   11396:          fputs(line,stdout);
                   11397:          fputs(line,ficparo);
                   11398:          fputs(line,ficlog);
                   11399:        }
                   11400:        ungetc(c,ficpar);
1.234     brouard  11401:        fscanf(ficpar,"%1d%1d",&i1,&j1);
                   11402:        if ((i1 != i) || (j1 != jj)){
                   11403:          printf("Error in line parameters number %d, %1d%1d instead of %1d%1d \n \
1.126     brouard  11404: It might be a problem of design; if ncovcol and the model are correct\n \
                   11405: run imach with mle=-1 to get a correct template of the parameter file.\n",numlinepar, i,j, i1, j1);
1.234     brouard  11406:          exit(1);
                   11407:        }
                   11408:        fprintf(ficparo,"%1d%1d",i1,j1);
                   11409:        if(mle==1)
                   11410:          printf("%1d%1d",i,jj);
                   11411:        fprintf(ficlog,"%1d%1d",i,jj);
                   11412:        for(k=1; k<=ncovmodel;k++){
                   11413:          fscanf(ficpar," %lf",&param[i][j][k]);
                   11414:          if(mle==1){
                   11415:            printf(" %lf",param[i][j][k]);
                   11416:            fprintf(ficlog," %lf",param[i][j][k]);
                   11417:          }
                   11418:          else
                   11419:            fprintf(ficlog," %lf",param[i][j][k]);
                   11420:          fprintf(ficparo," %lf",param[i][j][k]);
                   11421:        }
                   11422:        fscanf(ficpar,"\n");
                   11423:        numlinepar++;
                   11424:        if(mle==1)
                   11425:          printf("\n");
                   11426:        fprintf(ficlog,"\n");
                   11427:        fprintf(ficparo,"\n");
1.126     brouard  11428:       }
                   11429:     }  
                   11430:     fflush(ficlog);
1.234     brouard  11431:     
1.251     brouard  11432:     /* Reads parameters values */
1.126     brouard  11433:     p=param[1][1];
1.251     brouard  11434:     pstart=paramstart[1][1];
1.126     brouard  11435:     
                   11436:     /* Reads comments: lines beginning with '#' */
                   11437:     while((c=getc(ficpar))=='#' && c!= EOF){
                   11438:       ungetc(c,ficpar);
                   11439:       fgets(line, MAXLINE, ficpar);
                   11440:       numlinepar++;
1.141     brouard  11441:       fputs(line,stdout);
1.126     brouard  11442:       fputs(line,ficparo);
                   11443:       fputs(line,ficlog);
                   11444:     }
                   11445:     ungetc(c,ficpar);
                   11446: 
                   11447:     for(i=1; i <=nlstate; i++){
                   11448:       for(j=1; j <=nlstate+ndeath-1; j++){
1.234     brouard  11449:        fscanf(ficpar,"%1d%1d",&i1,&j1);
                   11450:        if ( (i1-i) * (j1-j) != 0){
                   11451:          printf("Error in line parameters number %d, %1d%1d instead of %1d%1d \n",numlinepar, i,j, i1, j1);
                   11452:          exit(1);
                   11453:        }
                   11454:        printf("%1d%1d",i,j);
                   11455:        fprintf(ficparo,"%1d%1d",i1,j1);
                   11456:        fprintf(ficlog,"%1d%1d",i1,j1);
                   11457:        for(k=1; k<=ncovmodel;k++){
                   11458:          fscanf(ficpar,"%le",&delti3[i][j][k]);
                   11459:          printf(" %le",delti3[i][j][k]);
                   11460:          fprintf(ficparo," %le",delti3[i][j][k]);
                   11461:          fprintf(ficlog," %le",delti3[i][j][k]);
                   11462:        }
                   11463:        fscanf(ficpar,"\n");
                   11464:        numlinepar++;
                   11465:        printf("\n");
                   11466:        fprintf(ficparo,"\n");
                   11467:        fprintf(ficlog,"\n");
1.126     brouard  11468:       }
                   11469:     }
                   11470:     fflush(ficlog);
1.234     brouard  11471:     
1.145     brouard  11472:     /* Reads covariance matrix */
1.126     brouard  11473:     delti=delti3[1][1];
1.220     brouard  11474:                
                   11475:                
1.126     brouard  11476:     /* 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  11477:                
1.126     brouard  11478:     /* Reads comments: lines beginning with '#' */
                   11479:     while((c=getc(ficpar))=='#' && c!= EOF){
                   11480:       ungetc(c,ficpar);
                   11481:       fgets(line, MAXLINE, ficpar);
                   11482:       numlinepar++;
1.141     brouard  11483:       fputs(line,stdout);
1.126     brouard  11484:       fputs(line,ficparo);
                   11485:       fputs(line,ficlog);
                   11486:     }
                   11487:     ungetc(c,ficpar);
1.220     brouard  11488:                
1.126     brouard  11489:     matcov=matrix(1,npar,1,npar);
1.203     brouard  11490:     hess=matrix(1,npar,1,npar);
1.131     brouard  11491:     for(i=1; i <=npar; i++)
                   11492:       for(j=1; j <=npar; j++) matcov[i][j]=0.;
1.220     brouard  11493:                
1.194     brouard  11494:     /* Scans npar lines */
1.126     brouard  11495:     for(i=1; i <=npar; i++){
1.226     brouard  11496:       count=fscanf(ficpar,"%1d%1d%d",&i1,&j1,&jk);
1.194     brouard  11497:       if(count != 3){
1.226     brouard  11498:        printf("Error! Error in parameter file %s at line %d after line starting with %1d%1d%1d\n\
1.194     brouard  11499: This is probably because your covariance matrix doesn't \n  contain exactly %d lines corresponding to your model line '1+age+%s'.\n\
                   11500: Please run with mle=-1 to get a correct covariance matrix.\n",optionfile,numlinepar, i1,j1,jk, npar, model);
1.226     brouard  11501:        fprintf(ficlog,"Error! Error in parameter file %s at line %d after line starting with %1d%1d%1d\n\
1.194     brouard  11502: This is probably because your covariance matrix doesn't \n  contain exactly %d lines corresponding to your model line '1+age+%s'.\n\
                   11503: Please run with mle=-1 to get a correct covariance matrix.\n",optionfile,numlinepar, i1,j1,jk, npar, model);
1.226     brouard  11504:        exit(1);
1.220     brouard  11505:       }else{
1.226     brouard  11506:        if(mle==1)
                   11507:          printf("%1d%1d%d",i1,j1,jk);
                   11508:       }
                   11509:       fprintf(ficlog,"%1d%1d%d",i1,j1,jk);
                   11510:       fprintf(ficparo,"%1d%1d%d",i1,j1,jk);
1.126     brouard  11511:       for(j=1; j <=i; j++){
1.226     brouard  11512:        fscanf(ficpar," %le",&matcov[i][j]);
                   11513:        if(mle==1){
                   11514:          printf(" %.5le",matcov[i][j]);
                   11515:        }
                   11516:        fprintf(ficlog," %.5le",matcov[i][j]);
                   11517:        fprintf(ficparo," %.5le",matcov[i][j]);
1.126     brouard  11518:       }
                   11519:       fscanf(ficpar,"\n");
                   11520:       numlinepar++;
                   11521:       if(mle==1)
1.220     brouard  11522:                                printf("\n");
1.126     brouard  11523:       fprintf(ficlog,"\n");
                   11524:       fprintf(ficparo,"\n");
                   11525:     }
1.194     brouard  11526:     /* End of read covariance matrix npar lines */
1.126     brouard  11527:     for(i=1; i <=npar; i++)
                   11528:       for(j=i+1;j<=npar;j++)
1.226     brouard  11529:        matcov[i][j]=matcov[j][i];
1.126     brouard  11530:     
                   11531:     if(mle==1)
                   11532:       printf("\n");
                   11533:     fprintf(ficlog,"\n");
                   11534:     
                   11535:     fflush(ficlog);
                   11536:     
                   11537:   }    /* End of mle != -3 */
1.218     brouard  11538:   
1.186     brouard  11539:   /*  Main data
                   11540:    */
1.290     brouard  11541:   nobs=lastobs-firstobs+1; /* was = lastobs;*/
                   11542:   /* num=lvector(1,n); */
                   11543:   /* moisnais=vector(1,n); */
                   11544:   /* annais=vector(1,n); */
                   11545:   /* moisdc=vector(1,n); */
                   11546:   /* andc=vector(1,n); */
                   11547:   /* weight=vector(1,n); */
                   11548:   /* agedc=vector(1,n); */
                   11549:   /* cod=ivector(1,n); */
                   11550:   /* for(i=1;i<=n;i++){ */
                   11551:   num=lvector(firstobs,lastobs);
                   11552:   moisnais=vector(firstobs,lastobs);
                   11553:   annais=vector(firstobs,lastobs);
                   11554:   moisdc=vector(firstobs,lastobs);
                   11555:   andc=vector(firstobs,lastobs);
                   11556:   weight=vector(firstobs,lastobs);
                   11557:   agedc=vector(firstobs,lastobs);
                   11558:   cod=ivector(firstobs,lastobs);
                   11559:   for(i=firstobs;i<=lastobs;i++){
1.234     brouard  11560:     num[i]=0;
                   11561:     moisnais[i]=0;
                   11562:     annais[i]=0;
                   11563:     moisdc[i]=0;
                   11564:     andc[i]=0;
                   11565:     agedc[i]=0;
                   11566:     cod[i]=0;
                   11567:     weight[i]=1.0; /* Equal weights, 1 by default */
                   11568:   }
1.290     brouard  11569:   mint=matrix(1,maxwav,firstobs,lastobs);
                   11570:   anint=matrix(1,maxwav,firstobs,lastobs);
                   11571:   s=imatrix(1,maxwav+1,firstobs,lastobs); /* s[i][j] health state for wave i and individual j */ 
1.126     brouard  11572:   tab=ivector(1,NCOVMAX);
1.144     brouard  11573:   ncodemax=ivector(1,NCOVMAX); /* Number of code per covariate; if O and 1 only, 2**ncov; V1+V2+V3+V4=>16 */
1.192     brouard  11574:   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  11575: 
1.136     brouard  11576:   /* Reads data from file datafile */
                   11577:   if (readdata(datafile, firstobs, lastobs, &imx)==1)
                   11578:     goto end;
                   11579: 
                   11580:   /* Calculation of the number of parameters from char model */
1.234     brouard  11581:   /*    modelsav=V2+V1+V4+age*V3 strb=age*V3 stra=V2+V1+V4 
1.137     brouard  11582:        k=4 (age*V3) Tvar[k=4]= 3 (from V3) Tag[cptcovage=1]=4
                   11583:        k=3 V4 Tvar[k=3]= 4 (from V4)
                   11584:        k=2 V1 Tvar[k=2]= 1 (from V1)
                   11585:        k=1 Tvar[1]=2 (from V2)
1.234     brouard  11586:   */
                   11587:   
                   11588:   Tvar=ivector(1,NCOVMAX); /* Was 15 changed to NCOVMAX. */
                   11589:   TvarsDind=ivector(1,NCOVMAX); /*  */
                   11590:   TvarsD=ivector(1,NCOVMAX); /*  */
                   11591:   TvarsQind=ivector(1,NCOVMAX); /*  */
                   11592:   TvarsQ=ivector(1,NCOVMAX); /*  */
1.232     brouard  11593:   TvarF=ivector(1,NCOVMAX); /*  */
                   11594:   TvarFind=ivector(1,NCOVMAX); /*  */
                   11595:   TvarV=ivector(1,NCOVMAX); /*  */
                   11596:   TvarVind=ivector(1,NCOVMAX); /*  */
                   11597:   TvarA=ivector(1,NCOVMAX); /*  */
                   11598:   TvarAind=ivector(1,NCOVMAX); /*  */
1.231     brouard  11599:   TvarFD=ivector(1,NCOVMAX); /*  */
                   11600:   TvarFDind=ivector(1,NCOVMAX); /*  */
                   11601:   TvarFQ=ivector(1,NCOVMAX); /*  */
                   11602:   TvarFQind=ivector(1,NCOVMAX); /*  */
                   11603:   TvarVD=ivector(1,NCOVMAX); /*  */
                   11604:   TvarVDind=ivector(1,NCOVMAX); /*  */
                   11605:   TvarVQ=ivector(1,NCOVMAX); /*  */
                   11606:   TvarVQind=ivector(1,NCOVMAX); /*  */
                   11607: 
1.230     brouard  11608:   Tvalsel=vector(1,NCOVMAX); /*  */
1.233     brouard  11609:   Tvarsel=ivector(1,NCOVMAX); /*  */
1.226     brouard  11610:   Typevar=ivector(-1,NCOVMAX); /* -1 to 2 */
                   11611:   Fixed=ivector(-1,NCOVMAX); /* -1 to 3 */
                   11612:   Dummy=ivector(-1,NCOVMAX); /* -1 to 3 */
1.137     brouard  11613:   /*  V2+V1+V4+age*V3 is a model with 4 covariates (3 plus signs). 
                   11614:       For each model-covariate stores the data-covariate id. Tvar[1]=2, Tvar[2]=1, Tvar[3]=4, 
                   11615:       Tvar[4=age*V3] is 3 and 'age' is recorded in Tage.
                   11616:   */
                   11617:   /* For model-covariate k tells which data-covariate to use but
                   11618:     because this model-covariate is a construction we invent a new column
                   11619:     ncovcol + k1
                   11620:     If already ncovcol=4 and model=V2+V1+V1*V4+age*V3
                   11621:     Tvar[3=V1*V4]=4+1 etc */
1.227     brouard  11622:   Tprod=ivector(1,NCOVMAX); /* Gives the k position of the k1 product */
                   11623:   Tposprod=ivector(1,NCOVMAX); /* Gives the k1 product from the k position */
1.137     brouard  11624:   /* Tprod[k1=1]=3(=V1*V4) for V2+V1+V1*V4+age*V3
                   11625:      if  V2+V1+V1*V4+age*V3+V3*V2   TProd[k1=2]=5 (V3*V2)
1.227     brouard  11626:      Tposprod[k]=k1 , Tposprod[3]=1, Tposprod[5]=2 
1.137     brouard  11627:   */
1.145     brouard  11628:   Tvaraff=ivector(1,NCOVMAX); /* Unclear */
                   11629:   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  11630:                            * For V3*V2 (in V2+V1+V1*V4+age*V3+V3*V2), V3*V2 position is 2nd. 
                   11631:                            * Tvard[k1=2][1]=3 (V3) Tvard[k1=2][2]=2(V2) */
1.145     brouard  11632:   Tage=ivector(1,NCOVMAX); /* Gives the covariate id of covariates associated with age: V2 + V1 + age*V4 + V3*age
1.137     brouard  11633:                         4 covariates (3 plus signs)
                   11634:                         Tage[1=V3*age]= 4; Tage[2=age*V4] = 3
                   11635:                      */  
1.230     brouard  11636:   Tmodelind=ivector(1,NCOVMAX);/** gives the k model position of an
1.227     brouard  11637:                                * individual dummy, fixed or varying:
                   11638:                                * Tmodelind[Tvaraff[3]]=9,Tvaraff[1]@9={4,
                   11639:                                * 3, 1, 0, 0, 0, 0, 0, 0},
1.230     brouard  11640:                                * model=V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 , 
                   11641:                                * V1 df, V2 qf, V3 & V4 dv, V5 qv
                   11642:                                * Tmodelind[1]@9={9,0,3,2,}*/
                   11643:   TmodelInvind=ivector(1,NCOVMAX); /* TmodelInvind=Tvar[k]- ncovcol-nqv={5-2-1=2,*/
                   11644:   TmodelInvQind=ivector(1,NCOVMAX);/** gives the k model position of an
1.228     brouard  11645:                                * individual quantitative, fixed or varying:
                   11646:                                * Tmodelqind[1]=1,Tvaraff[1]@9={4,
                   11647:                                * 3, 1, 0, 0, 0, 0, 0, 0},
                   11648:                                * model=V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1*/
1.186     brouard  11649: /* Main decodemodel */
                   11650: 
1.187     brouard  11651: 
1.223     brouard  11652:   if(decodemodel(model, lastobs) == 1) /* In order to get Tvar[k] V4+V3+V5 p Tvar[1]@3  = {4, 3, 5}*/
1.136     brouard  11653:     goto end;
                   11654: 
1.137     brouard  11655:   if((double)(lastobs-imx)/(double)imx > 1.10){
                   11656:     nbwarn++;
                   11657:     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); 
                   11658:     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); 
                   11659:   }
1.136     brouard  11660:     /*  if(mle==1){*/
1.137     brouard  11661:   if (weightopt != 1) { /* Maximisation without weights. We can have weights different from 1 but want no weight*/
                   11662:     for(i=1;i<=imx;i++) weight[i]=1.0; /* changed to imx */
1.136     brouard  11663:   }
                   11664: 
                   11665:     /*-calculation of age at interview from date of interview and age at death -*/
                   11666:   agev=matrix(1,maxwav,1,imx);
                   11667: 
                   11668:   if(calandcheckages(imx, maxwav, &agemin, &agemax, &nberr, &nbwarn) == 1)
                   11669:     goto end;
                   11670: 
1.126     brouard  11671: 
1.136     brouard  11672:   agegomp=(int)agemin;
1.290     brouard  11673:   free_vector(moisnais,firstobs,lastobs);
                   11674:   free_vector(annais,firstobs,lastobs);
1.126     brouard  11675:   /* free_matrix(mint,1,maxwav,1,n);
                   11676:      free_matrix(anint,1,maxwav,1,n);*/
1.215     brouard  11677:   /* free_vector(moisdc,1,n); */
                   11678:   /* free_vector(andc,1,n); */
1.145     brouard  11679:   /* */
                   11680:   
1.126     brouard  11681:   wav=ivector(1,imx);
1.214     brouard  11682:   /* dh=imatrix(1,lastpass-firstpass+1,1,imx); */
                   11683:   /* bh=imatrix(1,lastpass-firstpass+1,1,imx); */
                   11684:   /* mw=imatrix(1,lastpass-firstpass+1,1,imx); */
                   11685:   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.*/
                   11686:   bh=imatrix(1,lastpass-firstpass+2,1,imx);
                   11687:   mw=imatrix(1,lastpass-firstpass+2,1,imx);
1.126     brouard  11688:    
                   11689:   /* Concatenates waves */
1.214     brouard  11690:   /* Concatenates waves: wav[i] is the number of effective (useful waves) of individual i.
                   11691:      Death is a valid wave (if date is known).
                   11692:      mw[mi][i] is the number of (mi=1 to wav[i]) effective wave out of mi of individual i
                   11693:      dh[m][i] or dh[mw[mi][i]][i] is the delay between two effective waves m=mw[mi][i]
                   11694:      and mw[mi+1][i]. dh depends on stepm.
                   11695:   */
                   11696: 
1.126     brouard  11697:   concatwav(wav, dh, bh, mw, s, agedc, agev,  firstpass, lastpass, imx, nlstate, stepm);
1.248     brouard  11698:   /* Concatenates waves */
1.145     brouard  11699:  
1.290     brouard  11700:   free_vector(moisdc,firstobs,lastobs);
                   11701:   free_vector(andc,firstobs,lastobs);
1.215     brouard  11702: 
1.126     brouard  11703:   /* Routine tricode is to calculate cptcoveff (real number of unique covariates) and to associate covariable number and modality */
                   11704:   nbcode=imatrix(0,NCOVMAX,0,NCOVMAX); 
                   11705:   ncodemax[1]=1;
1.145     brouard  11706:   Ndum =ivector(-1,NCOVMAX);  
1.225     brouard  11707:   cptcoveff=0;
1.220     brouard  11708:   if (ncovmodel-nagesqr > 2 ){ /* That is if covariate other than cst, age and age*age */
                   11709:     tricode(&cptcoveff,Tvar,nbcode,imx, Ndum); /**< Fills nbcode[Tvar[j]][l]; */
1.227     brouard  11710:   }
                   11711:   
                   11712:   ncovcombmax=pow(2,cptcoveff);
                   11713:   invalidvarcomb=ivector(1, ncovcombmax); 
                   11714:   for(i=1;i<ncovcombmax;i++)
                   11715:     invalidvarcomb[i]=0;
                   11716:   
1.211     brouard  11717:   /* Nbcode gives the value of the lth modality (currently 1 to 2) of jth covariate, in
1.186     brouard  11718:      V2+V1*age, there are 3 covariates Tvar[2]=1 (V1).*/
1.211     brouard  11719:   /* 1 to ncodemax[j] which is the maximum value of this jth covariate */
1.227     brouard  11720:   
1.200     brouard  11721:   /*  codtab=imatrix(1,100,1,10);*/ /* codtab[h,k]=( (h-1) - mod(k-1,2**(k-1) )/2**(k-1) */
1.198     brouard  11722:   /*printf(" codtab[1,1],codtab[100,10]=%d,%d\n", codtab[1][1],codtabm(100,10));*/
1.186     brouard  11723:   /* codtab gives the value 1 or 2 of the hth combination of k covariates (1 or 2).*/
1.211     brouard  11724:   /* nbcode[Tvaraff[j]][codtabm(h,j)]) : if there are only 2 modalities for a covariate j, 
                   11725:    * codtabm(h,j) gives its value classified at position h and nbcode gives how it is coded 
                   11726:    * (currently 0 or 1) in the data.
                   11727:    * In a loop on h=1 to 2**k, and a loop on j (=1 to k), we get the value of 
                   11728:    * corresponding modality (h,j).
                   11729:    */
                   11730: 
1.145     brouard  11731:   h=0;
                   11732:   /*if (cptcovn > 0) */
1.126     brouard  11733:   m=pow(2,cptcoveff);
                   11734:  
1.144     brouard  11735:          /**< codtab(h,k)  k   = codtab[h,k]=( (h-1) - mod(k-1,2**(k-1) )/2**(k-1) + 1
1.211     brouard  11736:           * For k=4 covariates, h goes from 1 to m=2**k
                   11737:           * codtabm(h,k)=  (1 & (h-1) >> (k-1)) + 1;
                   11738:            * #define codtabm(h,k)  (1 & (h-1) >> (k-1))+1
1.186     brouard  11739:           *     h\k   1     2     3     4
1.143     brouard  11740:           *______________________________  
                   11741:           *     1 i=1 1 i=1 1 i=1 1 i=1 1
                   11742:           *     2     2     1     1     1
                   11743:           *     3 i=2 1     2     1     1
                   11744:           *     4     2     2     1     1
                   11745:           *     5 i=3 1 i=2 1     2     1
                   11746:           *     6     2     1     2     1
                   11747:           *     7 i=4 1     2     2     1
                   11748:           *     8     2     2     2     1
1.197     brouard  11749:           *     9 i=5 1 i=3 1 i=2 1     2
                   11750:           *    10     2     1     1     2
                   11751:           *    11 i=6 1     2     1     2
                   11752:           *    12     2     2     1     2
                   11753:           *    13 i=7 1 i=4 1     2     2    
                   11754:           *    14     2     1     2     2
                   11755:           *    15 i=8 1     2     2     2
                   11756:           *    16     2     2     2     2
1.143     brouard  11757:           */
1.212     brouard  11758:   /* How to do the opposite? From combination h (=1 to 2**k) how to get the value on the covariates? */
1.211     brouard  11759:      /* from h=5 and m, we get then number of covariates k=log(m)/log(2)=4
                   11760:      * and the value of each covariate?
                   11761:      * V1=1, V2=1, V3=2, V4=1 ?
                   11762:      * h-1=4 and 4 is 0100 or reverse 0010, and +1 is 1121 ok.
                   11763:      * h=6, 6-1=5, 5 is 0101, 1010, 2121, V1=2nd, V2=1st, V3=2nd, V4=1st.
                   11764:      * In order to get the real value in the data, we use nbcode
                   11765:      * nbcode[Tvar[3][2nd]]=1 and nbcode[Tvar[4][1]]=0
                   11766:      * We are keeping this crazy system in order to be able (in the future?) 
                   11767:      * to have more than 2 values (0 or 1) for a covariate.
                   11768:      * #define codtabm(h,k)  (1 & (h-1) >> (k-1))+1
                   11769:      * h=6, k=2? h-1=5=0101, reverse 1010, +1=2121, k=2nd position: value is 1: codtabm(6,2)=1
                   11770:      *              bbbbbbbb
                   11771:      *              76543210     
                   11772:      *   h-1        00000101 (6-1=5)
1.219     brouard  11773:      *(h-1)>>(k-1)= 00000010 >> (2-1) = 1 right shift
1.211     brouard  11774:      *           &
                   11775:      *     1        00000001 (1)
1.219     brouard  11776:      *              00000000        = 1 & ((h-1) >> (k-1))
                   11777:      *          +1= 00000001 =1 
1.211     brouard  11778:      *
                   11779:      * h=14, k=3 => h'=h-1=13, k'=k-1=2
                   11780:      *          h'      1101 =2^3+2^2+0x2^1+2^0
                   11781:      *    >>k'            11
                   11782:      *          &   00000001
                   11783:      *            = 00000001
                   11784:      *      +1    = 00000010=2    =  codtabm(14,3)   
                   11785:      * Reverse h=6 and m=16?
                   11786:      * cptcoveff=log(16)/log(2)=4 covariate: 6-1=5=0101 reversed=1010 +1=2121 =>V1=2, V2=1, V3=2, V4=1.
                   11787:      * for (j=1 to cptcoveff) Vj=decodtabm(j,h,cptcoveff)
                   11788:      * decodtabm(h,j,cptcoveff)= (((h-1) >> (j-1)) & 1) +1 
                   11789:      * decodtabm(h,j,cptcoveff)= (h <= (1<<cptcoveff)?(((h-1) >> (j-1)) & 1) +1 : -1)
                   11790:      * V3=decodtabm(14,3,2**4)=2
                   11791:      *          h'=13   1101 =2^3+2^2+0x2^1+2^0
                   11792:      *(h-1) >> (j-1)    0011 =13 >> 2
                   11793:      *          &1 000000001
                   11794:      *           = 000000001
                   11795:      *         +1= 000000010 =2
                   11796:      *                  2211
                   11797:      *                  V1=1+1, V2=0+1, V3=1+1, V4=1+1
                   11798:      *                  V3=2
1.220     brouard  11799:                 * codtabm and decodtabm are identical
1.211     brouard  11800:      */
                   11801: 
1.145     brouard  11802: 
                   11803:  free_ivector(Ndum,-1,NCOVMAX);
                   11804: 
                   11805: 
1.126     brouard  11806:     
1.186     brouard  11807:   /* Initialisation of ----------- gnuplot -------------*/
1.126     brouard  11808:   strcpy(optionfilegnuplot,optionfilefiname);
                   11809:   if(mle==-3)
1.201     brouard  11810:     strcat(optionfilegnuplot,"-MORT_");
1.126     brouard  11811:   strcat(optionfilegnuplot,".gp");
                   11812: 
                   11813:   if((ficgp=fopen(optionfilegnuplot,"w"))==NULL) {
                   11814:     printf("Problem with file %s",optionfilegnuplot);
                   11815:   }
                   11816:   else{
1.204     brouard  11817:     fprintf(ficgp,"\n# IMaCh-%s\n", version); 
1.126     brouard  11818:     fprintf(ficgp,"# %s\n", optionfilegnuplot); 
1.141     brouard  11819:     //fprintf(ficgp,"set missing 'NaNq'\n");
                   11820:     fprintf(ficgp,"set datafile missing 'NaNq'\n");
1.126     brouard  11821:   }
                   11822:   /*  fclose(ficgp);*/
1.186     brouard  11823: 
                   11824: 
                   11825:   /* Initialisation of --------- index.htm --------*/
1.126     brouard  11826: 
                   11827:   strcpy(optionfilehtm,optionfilefiname); /* Main html file */
                   11828:   if(mle==-3)
1.201     brouard  11829:     strcat(optionfilehtm,"-MORT_");
1.126     brouard  11830:   strcat(optionfilehtm,".htm");
                   11831:   if((fichtm=fopen(optionfilehtm,"w"))==NULL)    {
1.131     brouard  11832:     printf("Problem with %s \n",optionfilehtm);
                   11833:     exit(0);
1.126     brouard  11834:   }
                   11835: 
                   11836:   strcpy(optionfilehtmcov,optionfilefiname); /* Only for matrix of covariance */
                   11837:   strcat(optionfilehtmcov,"-cov.htm");
                   11838:   if((fichtmcov=fopen(optionfilehtmcov,"w"))==NULL)    {
                   11839:     printf("Problem with %s \n",optionfilehtmcov), exit(0);
                   11840:   }
                   11841:   else{
                   11842:   fprintf(fichtmcov,"<html><head>\n<title>IMaCh Cov %s</title></head>\n <body><font size=\"2\">%s <br> %s</font> \
                   11843: <hr size=\"2\" color=\"#EC5E5E\"> \n\
1.204     brouard  11844: Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=1+age+%s<br>\n",\
1.126     brouard  11845:          optionfilehtmcov,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model);
                   11846:   }
                   11847: 
1.213     brouard  11848:   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  11849: <hr size=\"2\" color=\"#EC5E5E\"> \n\
                   11850: <font size=\"2\">IMaCh-%s <br> %s</font> \
1.126     brouard  11851: <hr size=\"2\" color=\"#EC5E5E\"> \n\
1.204     brouard  11852: Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=1+age+%s<br>\n\
1.126     brouard  11853: \n\
                   11854: <hr  size=\"2\" color=\"#EC5E5E\">\
                   11855:  <ul><li><h4>Parameter files</h4>\n\
                   11856:  - Parameter file: <a href=\"%s.%s\">%s.%s</a><br>\n\
                   11857:  - Copy of the parameter file: <a href=\"o%s\">o%s</a><br>\n\
                   11858:  - Log file of the run: <a href=\"%s\">%s</a><br>\n\
                   11859:  - Gnuplot file name: <a href=\"%s\">%s</a><br>\n\
                   11860:  - Date and time at start: %s</ul>\n",\
                   11861:          optionfilehtm,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model,\
                   11862:          optionfilefiname,optionfilext,optionfilefiname,optionfilext,\
                   11863:          fileres,fileres,\
                   11864:          filelog,filelog,optionfilegnuplot,optionfilegnuplot,strstart);
                   11865:   fflush(fichtm);
                   11866: 
                   11867:   strcpy(pathr,path);
                   11868:   strcat(pathr,optionfilefiname);
1.184     brouard  11869: #ifdef WIN32
                   11870:   _chdir(optionfilefiname); /* Move to directory named optionfile */
                   11871: #else
1.126     brouard  11872:   chdir(optionfilefiname); /* Move to directory named optionfile */
1.184     brouard  11873: #endif
                   11874:          
1.126     brouard  11875:   
1.220     brouard  11876:   /* Calculates basic frequencies. Computes observed prevalence at single age 
                   11877:                 and for any valid combination of covariates
1.126     brouard  11878:      and prints on file fileres'p'. */
1.251     brouard  11879:   freqsummary(fileres, p, pstart, agemin, agemax, s, agev, nlstate, imx, Tvaraff, invalidvarcomb, nbcode, ncodemax,mint,anint,strstart, \
1.227     brouard  11880:              firstpass, lastpass,  stepm,  weightopt, model);
1.126     brouard  11881: 
                   11882:   fprintf(fichtm,"\n");
1.286     brouard  11883:   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  11884:          ftol, stepm);
                   11885:   fprintf(fichtm,"\n<li>Number of fixed dummy covariates: ncovcol=%d ", ncovcol);
                   11886:   ncurrv=1;
                   11887:   for(i=ncurrv; i <=ncovcol; i++) fprintf(fichtm,"V%d ", i);
                   11888:   fprintf(fichtm,"\n<li> Number of fixed quantitative variables: nqv=%d ", nqv); 
                   11889:   ncurrv=i;
                   11890:   for(i=ncurrv; i <=ncurrv-1+nqv; i++) fprintf(fichtm,"V%d ", i);
1.290     brouard  11891:   fprintf(fichtm,"\n<li> Number of time varying (wave varying) dummy covariates: ntv=%d ", ntv);
1.274     brouard  11892:   ncurrv=i;
                   11893:   for(i=ncurrv; i <=ncurrv-1+ntv; i++) fprintf(fichtm,"V%d ", i);
1.290     brouard  11894:   fprintf(fichtm,"\n<li>Number of time varying  quantitative covariates: nqtv=%d ", nqtv);
1.274     brouard  11895:   ncurrv=i;
                   11896:   for(i=ncurrv; i <=ncurrv-1+nqtv; i++) fprintf(fichtm,"V%d ", i);
                   11897:   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", \
                   11898:           nlstate, ndeath, maxwav, mle, weightopt);
                   11899: 
                   11900:   fprintf(fichtm,"<h4> Diagram of states <a href=\"%s_.svg\">%s_.svg</a></h4> \n\
                   11901: <img src=\"%s_.svg\">", subdirf2(optionfilefiname,"D_"),subdirf2(optionfilefiname,"D_"),subdirf2(optionfilefiname,"D_"));
                   11902: 
                   11903:   
                   11904:   fprintf(fichtm,"\n<h4>Some descriptive statistics </h4>\n<br>Total number of observations=%d <br>\n\
1.126     brouard  11905: Youngest age at first (selected) pass %.2f, oldest age %.2f<br>\n\
                   11906: Interval (in months) between two waves: Min=%d Max=%d Mean=%.2lf<br>\n",\
1.274     brouard  11907:   imx,agemin,agemax,jmin,jmax,jmean);
1.126     brouard  11908:   pmmij= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
1.268     brouard  11909:   oldms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
                   11910:   newms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
                   11911:   savms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
                   11912:   oldm=oldms; newm=newms; savm=savms; /* Keeps fixed addresses to free */
1.218     brouard  11913: 
1.126     brouard  11914:   /* For Powell, parameters are in a vector p[] starting at p[1]
                   11915:      so we point p on param[1][1] so that p[1] maps on param[1][1][1] */
                   11916:   p=param[1][1]; /* *(*(*(param +1)+1)+0) */
                   11917: 
                   11918:   globpr=0; /* To get the number ipmx of contributions and the sum of weights*/
1.186     brouard  11919:   /* For mortality only */
1.126     brouard  11920:   if (mle==-3){
1.136     brouard  11921:     ximort=matrix(1,NDIM,1,NDIM); 
1.248     brouard  11922:     for(i=1;i<=NDIM;i++)
                   11923:       for(j=1;j<=NDIM;j++)
                   11924:        ximort[i][j]=0.;
1.186     brouard  11925:     /*     ximort=gsl_matrix_alloc(1,NDIM,1,NDIM); */
1.290     brouard  11926:     cens=ivector(firstobs,lastobs);
                   11927:     ageexmed=vector(firstobs,lastobs);
                   11928:     agecens=vector(firstobs,lastobs);
                   11929:     dcwave=ivector(firstobs,lastobs);
1.223     brouard  11930:                
1.126     brouard  11931:     for (i=1; i<=imx; i++){
                   11932:       dcwave[i]=-1;
                   11933:       for (m=firstpass; m<=lastpass; m++)
1.226     brouard  11934:        if (s[m][i]>nlstate) {
                   11935:          dcwave[i]=m;
                   11936:          /*    printf("i=%d j=%d s=%d dcwave=%d\n",i,j, s[j][i],dcwave[i]);*/
                   11937:          break;
                   11938:        }
1.126     brouard  11939:     }
1.226     brouard  11940:     
1.126     brouard  11941:     for (i=1; i<=imx; i++) {
                   11942:       if (wav[i]>0){
1.226     brouard  11943:        ageexmed[i]=agev[mw[1][i]][i];
                   11944:        j=wav[i];
                   11945:        agecens[i]=1.; 
                   11946:        
                   11947:        if (ageexmed[i]> 1 && wav[i] > 0){
                   11948:          agecens[i]=agev[mw[j][i]][i];
                   11949:          cens[i]= 1;
                   11950:        }else if (ageexmed[i]< 1) 
                   11951:          cens[i]= -1;
                   11952:        if (agedc[i]< AGESUP && agedc[i]>1 && dcwave[i]>firstpass && dcwave[i]<=lastpass)
                   11953:          cens[i]=0 ;
1.126     brouard  11954:       }
                   11955:       else cens[i]=-1;
                   11956:     }
                   11957:     
                   11958:     for (i=1;i<=NDIM;i++) {
                   11959:       for (j=1;j<=NDIM;j++)
1.226     brouard  11960:        ximort[i][j]=(i == j ? 1.0 : 0.0);
1.126     brouard  11961:     }
                   11962:     
1.302     brouard  11963:     p[1]=0.0268; p[NDIM]=0.083;
                   11964:     /* printf("%lf %lf", p[1], p[2]); */
1.126     brouard  11965:     
                   11966:     
1.136     brouard  11967: #ifdef GSL
                   11968:     printf("GSL optimization\n");  fprintf(ficlog,"Powell\n");
1.162     brouard  11969: #else
1.126     brouard  11970:     printf("Powell\n");  fprintf(ficlog,"Powell\n");
1.136     brouard  11971: #endif
1.201     brouard  11972:     strcpy(filerespow,"POW-MORT_"); 
                   11973:     strcat(filerespow,fileresu);
1.126     brouard  11974:     if((ficrespow=fopen(filerespow,"w"))==NULL) {
                   11975:       printf("Problem with resultfile: %s\n", filerespow);
                   11976:       fprintf(ficlog,"Problem with resultfile: %s\n", filerespow);
                   11977:     }
1.136     brouard  11978: #ifdef GSL
                   11979:     fprintf(ficrespow,"# GSL optimization\n# iter -2*LL");
1.162     brouard  11980: #else
1.126     brouard  11981:     fprintf(ficrespow,"# Powell\n# iter -2*LL");
1.136     brouard  11982: #endif
1.126     brouard  11983:     /*  for (i=1;i<=nlstate;i++)
                   11984:        for(j=1;j<=nlstate+ndeath;j++)
                   11985:        if(j!=i)fprintf(ficrespow," p%1d%1d",i,j);
                   11986:     */
                   11987:     fprintf(ficrespow,"\n");
1.136     brouard  11988: #ifdef GSL
                   11989:     /* gsl starts here */ 
                   11990:     T = gsl_multimin_fminimizer_nmsimplex;
                   11991:     gsl_multimin_fminimizer *sfm = NULL;
                   11992:     gsl_vector *ss, *x;
                   11993:     gsl_multimin_function minex_func;
                   11994: 
                   11995:     /* Initial vertex size vector */
                   11996:     ss = gsl_vector_alloc (NDIM);
                   11997:     
                   11998:     if (ss == NULL){
                   11999:       GSL_ERROR_VAL ("failed to allocate space for ss", GSL_ENOMEM, 0);
                   12000:     }
                   12001:     /* Set all step sizes to 1 */
                   12002:     gsl_vector_set_all (ss, 0.001);
                   12003: 
                   12004:     /* Starting point */
1.126     brouard  12005:     
1.136     brouard  12006:     x = gsl_vector_alloc (NDIM);
                   12007:     
                   12008:     if (x == NULL){
                   12009:       gsl_vector_free(ss);
                   12010:       GSL_ERROR_VAL ("failed to allocate space for x", GSL_ENOMEM, 0);
                   12011:     }
                   12012:   
                   12013:     /* Initialize method and iterate */
                   12014:     /*     p[1]=0.0268; p[NDIM]=0.083; */
1.186     brouard  12015:     /*     gsl_vector_set(x, 0, 0.0268); */
                   12016:     /*     gsl_vector_set(x, 1, 0.083); */
1.136     brouard  12017:     gsl_vector_set(x, 0, p[1]);
                   12018:     gsl_vector_set(x, 1, p[2]);
                   12019: 
                   12020:     minex_func.f = &gompertz_f;
                   12021:     minex_func.n = NDIM;
                   12022:     minex_func.params = (void *)&p; /* ??? */
                   12023:     
                   12024:     sfm = gsl_multimin_fminimizer_alloc (T, NDIM);
                   12025:     gsl_multimin_fminimizer_set (sfm, &minex_func, x, ss);
                   12026:     
                   12027:     printf("Iterations beginning .....\n\n");
                   12028:     printf("Iter. #    Intercept       Slope     -Log Likelihood     Simplex size\n");
                   12029: 
                   12030:     iteri=0;
                   12031:     while (rval == GSL_CONTINUE){
                   12032:       iteri++;
                   12033:       status = gsl_multimin_fminimizer_iterate(sfm);
                   12034:       
                   12035:       if (status) printf("error: %s\n", gsl_strerror (status));
                   12036:       fflush(0);
                   12037:       
                   12038:       if (status) 
                   12039:         break;
                   12040:       
                   12041:       rval = gsl_multimin_test_size (gsl_multimin_fminimizer_size (sfm), 1e-6);
                   12042:       ssval = gsl_multimin_fminimizer_size (sfm);
                   12043:       
                   12044:       if (rval == GSL_SUCCESS)
                   12045:         printf ("converged to a local maximum at\n");
                   12046:       
                   12047:       printf("%5d ", iteri);
                   12048:       for (it = 0; it < NDIM; it++){
                   12049:        printf ("%10.5f ", gsl_vector_get (sfm->x, it));
                   12050:       }
                   12051:       printf("f() = %-10.5f ssize = %.7f\n", sfm->fval, ssval);
                   12052:     }
                   12053:     
                   12054:     printf("\n\n Please note: Program should be run many times with varying starting points to detemine global maximum\n\n");
                   12055:     
                   12056:     gsl_vector_free(x); /* initial values */
                   12057:     gsl_vector_free(ss); /* inital step size */
                   12058:     for (it=0; it<NDIM; it++){
                   12059:       p[it+1]=gsl_vector_get(sfm->x,it);
                   12060:       fprintf(ficrespow," %.12lf", p[it]);
                   12061:     }
                   12062:     gsl_multimin_fminimizer_free (sfm); /* p *(sfm.x.data) et p *(sfm.x.data+1)  */
                   12063: #endif
                   12064: #ifdef POWELL
                   12065:      powell(p,ximort,NDIM,ftol,&iter,&fret,gompertz);
                   12066: #endif  
1.126     brouard  12067:     fclose(ficrespow);
                   12068:     
1.203     brouard  12069:     hesscov(matcov, hess, p, NDIM, delti, 1e-4, gompertz); 
1.126     brouard  12070: 
                   12071:     for(i=1; i <=NDIM; i++)
                   12072:       for(j=i+1;j<=NDIM;j++)
1.220     brouard  12073:                                matcov[i][j]=matcov[j][i];
1.126     brouard  12074:     
                   12075:     printf("\nCovariance matrix\n ");
1.203     brouard  12076:     fprintf(ficlog,"\nCovariance matrix\n ");
1.126     brouard  12077:     for(i=1; i <=NDIM; i++) {
                   12078:       for(j=1;j<=NDIM;j++){ 
1.220     brouard  12079:                                printf("%f ",matcov[i][j]);
                   12080:                                fprintf(ficlog,"%f ",matcov[i][j]);
1.126     brouard  12081:       }
1.203     brouard  12082:       printf("\n ");  fprintf(ficlog,"\n ");
1.126     brouard  12083:     }
                   12084:     
                   12085:     printf("iter=%d MLE=%f Eq=%lf*exp(%lf*(age-%d))\n",iter,-gompertz(p),p[1],p[2],agegomp);
1.193     brouard  12086:     for (i=1;i<=NDIM;i++) {
1.126     brouard  12087:       printf("%f [%f ; %f]\n",p[i],p[i]-2*sqrt(matcov[i][i]),p[i]+2*sqrt(matcov[i][i]));
1.193     brouard  12088:       fprintf(ficlog,"%f [%f ; %f]\n",p[i],p[i]-2*sqrt(matcov[i][i]),p[i]+2*sqrt(matcov[i][i]));
                   12089:     }
1.302     brouard  12090:     lsurv=vector(agegomp,AGESUP);
                   12091:     lpop=vector(agegomp,AGESUP);
                   12092:     tpop=vector(agegomp,AGESUP);
1.126     brouard  12093:     lsurv[agegomp]=100000;
                   12094:     
                   12095:     for (k=agegomp;k<=AGESUP;k++) {
                   12096:       agemortsup=k;
                   12097:       if (p[1]*exp(p[2]*(k-agegomp))>1) break;
                   12098:     }
                   12099:     
                   12100:     for (k=agegomp;k<agemortsup;k++)
                   12101:       lsurv[k+1]=lsurv[k]-lsurv[k]*(p[1]*exp(p[2]*(k-agegomp)));
                   12102:     
                   12103:     for (k=agegomp;k<agemortsup;k++){
                   12104:       lpop[k]=(lsurv[k]+lsurv[k+1])/2.;
                   12105:       sumlpop=sumlpop+lpop[k];
                   12106:     }
                   12107:     
                   12108:     tpop[agegomp]=sumlpop;
                   12109:     for (k=agegomp;k<(agemortsup-3);k++){
                   12110:       /*  tpop[k+1]=2;*/
                   12111:       tpop[k+1]=tpop[k]-lpop[k];
                   12112:     }
                   12113:     
                   12114:     
                   12115:     printf("\nAge   lx     qx    dx    Lx     Tx     e(x)\n");
                   12116:     for (k=agegomp;k<(agemortsup-2);k++) 
                   12117:       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]);
                   12118:     
                   12119:     
                   12120:     replace_back_to_slash(pathc,pathcd); /* Even gnuplot wants a / */
1.220     brouard  12121:                ageminpar=50;
                   12122:                agemaxpar=100;
1.194     brouard  12123:     if(ageminpar == AGEOVERFLOW ||agemaxpar == AGEOVERFLOW){
                   12124:        printf("Warning! Error in gnuplot file with ageminpar %f or agemaxpar %f overflow\n\
                   12125: This is probably because your parameter file doesn't \n  contain the exact number of lines (or columns) corresponding to your model line.\n\
                   12126: Please run with mle=-1 to get a correct covariance matrix.\n",ageminpar,agemaxpar);
                   12127:        fprintf(ficlog,"Warning! Error in gnuplot file with ageminpar %f or agemaxpar %f overflow\n\
                   12128: This is probably because your parameter file doesn't \n  contain the exact number of lines (or columns) corresponding to your model line.\n\
                   12129: Please run with mle=-1 to get a correct covariance matrix.\n",ageminpar,agemaxpar);
1.220     brouard  12130:     }else{
                   12131:                        printf("Warning! ageminpar %f and agemaxpar %f have been fixed because for simplification until it is fixed...\n\n",ageminpar,agemaxpar);
                   12132:                        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  12133:       printinggnuplotmort(fileresu, optionfilefiname,ageminpar,agemaxpar,fage, pathc,p);
1.220     brouard  12134:                }
1.201     brouard  12135:     printinghtmlmort(fileresu,title,datafile, firstpass, lastpass, \
1.126     brouard  12136:                     stepm, weightopt,\
                   12137:                     model,imx,p,matcov,agemortsup);
                   12138:     
1.302     brouard  12139:     free_vector(lsurv,agegomp,AGESUP);
                   12140:     free_vector(lpop,agegomp,AGESUP);
                   12141:     free_vector(tpop,agegomp,AGESUP);
1.220     brouard  12142:     free_matrix(ximort,1,NDIM,1,NDIM);
1.290     brouard  12143:     free_ivector(dcwave,firstobs,lastobs);
                   12144:     free_vector(agecens,firstobs,lastobs);
                   12145:     free_vector(ageexmed,firstobs,lastobs);
                   12146:     free_ivector(cens,firstobs,lastobs);
1.220     brouard  12147: #ifdef GSL
1.136     brouard  12148: #endif
1.186     brouard  12149:   } /* Endof if mle==-3 mortality only */
1.205     brouard  12150:   /* Standard  */
                   12151:   else{ /* For mle !=- 3, could be 0 or 1 or 4 etc. */
                   12152:     globpr=0;/* Computes sum of likelihood for globpr=1 and funcone */
                   12153:     /* Computes likelihood for initial parameters, uses funcone to compute gpimx and gsw */
1.132     brouard  12154:     likelione(ficres, p, npar, nlstate, &globpr, &ipmx, &sw, &fretone, funcone); /* Prints the contributions to the likelihood */
1.126     brouard  12155:     printf("First Likeli=%12.6f ipmx=%ld sw=%12.6f",fretone,ipmx,sw);
                   12156:     for (k=1; k<=npar;k++)
                   12157:       printf(" %d %8.5f",k,p[k]);
                   12158:     printf("\n");
1.205     brouard  12159:     if(mle>=1){ /* Could be 1 or 2, Real Maximization */
                   12160:       /* mlikeli uses func not funcone */
1.247     brouard  12161:       /* for(i=1;i<nlstate;i++){ */
                   12162:       /*       /\*reducing xi for 1 to npar to 1 to ncovmodel; *\/ */
                   12163:       /*    mlikeli(ficres,p, ncovmodel, ncovmodel, nlstate, ftol, funcnoprod); */
                   12164:       /* } */
1.205     brouard  12165:       mlikeli(ficres,p, npar, ncovmodel, nlstate, ftol, func);
                   12166:     }
                   12167:     if(mle==0) {/* No optimization, will print the likelihoods for the datafile */
                   12168:       globpr=0;/* Computes sum of likelihood for globpr=1 and funcone */
                   12169:       /* Computes likelihood for initial parameters, uses funcone to compute gpimx and gsw */
                   12170:       likelione(ficres, p, npar, nlstate, &globpr, &ipmx, &sw, &fretone, funcone); /* Prints the contributions to the likelihood */
                   12171:     }
                   12172:     globpr=1; /* again, to print the individual contributions using computed gpimx and gsw */
1.126     brouard  12173:     likelione(ficres, p, npar, nlstate, &globpr, &ipmx, &sw, &fretone, funcone); /* Prints the contributions to the likelihood */
                   12174:     printf("Second Likeli=%12.6f ipmx=%ld sw=%12.6f",fretone,ipmx,sw);
                   12175:     for (k=1; k<=npar;k++)
                   12176:       printf(" %d %8.5f",k,p[k]);
                   12177:     printf("\n");
                   12178:     
                   12179:     /*--------- results files --------------*/
1.283     brouard  12180:     /* 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  12181:     
                   12182:     
                   12183:     fprintf(ficres,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
                   12184:     printf("# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
                   12185:     fprintf(ficlog,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
                   12186:     for(i=1,jk=1; i <=nlstate; i++){
                   12187:       for(k=1; k <=(nlstate+ndeath); k++){
1.225     brouard  12188:        if (k != i) {
                   12189:          printf("%d%d ",i,k);
                   12190:          fprintf(ficlog,"%d%d ",i,k);
                   12191:          fprintf(ficres,"%1d%1d ",i,k);
                   12192:          for(j=1; j <=ncovmodel; j++){
                   12193:            printf("%12.7f ",p[jk]);
                   12194:            fprintf(ficlog,"%12.7f ",p[jk]);
                   12195:            fprintf(ficres,"%12.7f ",p[jk]);
                   12196:            jk++; 
                   12197:          }
                   12198:          printf("\n");
                   12199:          fprintf(ficlog,"\n");
                   12200:          fprintf(ficres,"\n");
                   12201:        }
1.126     brouard  12202:       }
                   12203:     }
1.203     brouard  12204:     if(mle != 0){
                   12205:       /* Computing hessian and covariance matrix only at a peak of the Likelihood, that is after optimization */
1.126     brouard  12206:       ftolhess=ftol; /* Usually correct */
1.203     brouard  12207:       hesscov(matcov, hess, p, npar, delti, ftolhess, func);
                   12208:       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");
                   12209:       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");
                   12210:       for(i=1,jk=1; i <=nlstate; i++){
1.225     brouard  12211:        for(k=1; k <=(nlstate+ndeath); k++){
                   12212:          if (k != i) {
                   12213:            printf("%d%d ",i,k);
                   12214:            fprintf(ficlog,"%d%d ",i,k);
                   12215:            for(j=1; j <=ncovmodel; j++){
                   12216:              printf("%12.7f W=%8.3f CI=[%12.7f ; %12.7f] ",p[jk], p[jk]/sqrt(matcov[jk][jk]), p[jk]-1.96*sqrt(matcov[jk][jk]),p[jk]+1.96*sqrt(matcov[jk][jk]));
                   12217:              fprintf(ficlog,"%12.7f W=%8.3f CI=[%12.7f ; %12.7f] ",p[jk], p[jk]/sqrt(matcov[jk][jk]), p[jk]-1.96*sqrt(matcov[jk][jk]),p[jk]+1.96*sqrt(matcov[jk][jk]));
                   12218:              jk++; 
                   12219:            }
                   12220:            printf("\n");
                   12221:            fprintf(ficlog,"\n");
                   12222:          }
                   12223:        }
1.193     brouard  12224:       }
1.203     brouard  12225:     } /* end of hesscov and Wald tests */
1.225     brouard  12226:     
1.203     brouard  12227:     /*  */
1.126     brouard  12228:     fprintf(ficres,"# Scales (for hessian or gradient estimation)\n");
                   12229:     printf("# Scales (for hessian or gradient estimation)\n");
                   12230:     fprintf(ficlog,"# Scales (for hessian or gradient estimation)\n");
                   12231:     for(i=1,jk=1; i <=nlstate; i++){
                   12232:       for(j=1; j <=nlstate+ndeath; j++){
1.225     brouard  12233:        if (j!=i) {
                   12234:          fprintf(ficres,"%1d%1d",i,j);
                   12235:          printf("%1d%1d",i,j);
                   12236:          fprintf(ficlog,"%1d%1d",i,j);
                   12237:          for(k=1; k<=ncovmodel;k++){
                   12238:            printf(" %.5e",delti[jk]);
                   12239:            fprintf(ficlog," %.5e",delti[jk]);
                   12240:            fprintf(ficres," %.5e",delti[jk]);
                   12241:            jk++;
                   12242:          }
                   12243:          printf("\n");
                   12244:          fprintf(ficlog,"\n");
                   12245:          fprintf(ficres,"\n");
                   12246:        }
1.126     brouard  12247:       }
                   12248:     }
                   12249:     
                   12250:     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  12251:     if(mle >= 1) /* To big for the screen */
1.126     brouard  12252:       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");
                   12253:     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");
                   12254:     /* # 121 Var(a12)\n\ */
                   12255:     /* # 122 Cov(b12,a12) Var(b12)\n\ */
                   12256:     /* # 131 Cov(a13,a12) Cov(a13,b12, Var(a13)\n\ */
                   12257:     /* # 132 Cov(b13,a12) Cov(b13,b12, Cov(b13,a13) Var(b13)\n\ */
                   12258:     /* # 212 Cov(a21,a12) Cov(a21,b12, Cov(a21,a13) Cov(a21,b13) Var(a21)\n\ */
                   12259:     /* # 212 Cov(b21,a12) Cov(b21,b12, Cov(b21,a13) Cov(b21,b13) Cov(b21,a21) Var(b21)\n\ */
                   12260:     /* # 232 Cov(a23,a12) Cov(a23,b12, Cov(a23,a13) Cov(a23,b13) Cov(a23,a21) Cov(a23,b21) Var(a23)\n\ */
                   12261:     /* # 232 Cov(b23,a12) Cov(b23,b12) ... Var (b23)\n" */
                   12262:     
                   12263:     
                   12264:     /* Just to have a covariance matrix which will be more understandable
                   12265:        even is we still don't want to manage dictionary of variables
                   12266:     */
                   12267:     for(itimes=1;itimes<=2;itimes++){
                   12268:       jj=0;
                   12269:       for(i=1; i <=nlstate; i++){
1.225     brouard  12270:        for(j=1; j <=nlstate+ndeath; j++){
                   12271:          if(j==i) continue;
                   12272:          for(k=1; k<=ncovmodel;k++){
                   12273:            jj++;
                   12274:            ca[0]= k+'a'-1;ca[1]='\0';
                   12275:            if(itimes==1){
                   12276:              if(mle>=1)
                   12277:                printf("#%1d%1d%d",i,j,k);
                   12278:              fprintf(ficlog,"#%1d%1d%d",i,j,k);
                   12279:              fprintf(ficres,"#%1d%1d%d",i,j,k);
                   12280:            }else{
                   12281:              if(mle>=1)
                   12282:                printf("%1d%1d%d",i,j,k);
                   12283:              fprintf(ficlog,"%1d%1d%d",i,j,k);
                   12284:              fprintf(ficres,"%1d%1d%d",i,j,k);
                   12285:            }
                   12286:            ll=0;
                   12287:            for(li=1;li <=nlstate; li++){
                   12288:              for(lj=1;lj <=nlstate+ndeath; lj++){
                   12289:                if(lj==li) continue;
                   12290:                for(lk=1;lk<=ncovmodel;lk++){
                   12291:                  ll++;
                   12292:                  if(ll<=jj){
                   12293:                    cb[0]= lk +'a'-1;cb[1]='\0';
                   12294:                    if(ll<jj){
                   12295:                      if(itimes==1){
                   12296:                        if(mle>=1)
                   12297:                          printf(" Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
                   12298:                        fprintf(ficlog," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
                   12299:                        fprintf(ficres," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
                   12300:                      }else{
                   12301:                        if(mle>=1)
                   12302:                          printf(" %.5e",matcov[jj][ll]); 
                   12303:                        fprintf(ficlog," %.5e",matcov[jj][ll]); 
                   12304:                        fprintf(ficres," %.5e",matcov[jj][ll]); 
                   12305:                      }
                   12306:                    }else{
                   12307:                      if(itimes==1){
                   12308:                        if(mle>=1)
                   12309:                          printf(" Var(%s%1d%1d)",ca,i,j);
                   12310:                        fprintf(ficlog," Var(%s%1d%1d)",ca,i,j);
                   12311:                        fprintf(ficres," Var(%s%1d%1d)",ca,i,j);
                   12312:                      }else{
                   12313:                        if(mle>=1)
                   12314:                          printf(" %.7e",matcov[jj][ll]); 
                   12315:                        fprintf(ficlog," %.7e",matcov[jj][ll]); 
                   12316:                        fprintf(ficres," %.7e",matcov[jj][ll]); 
                   12317:                      }
                   12318:                    }
                   12319:                  }
                   12320:                } /* end lk */
                   12321:              } /* end lj */
                   12322:            } /* end li */
                   12323:            if(mle>=1)
                   12324:              printf("\n");
                   12325:            fprintf(ficlog,"\n");
                   12326:            fprintf(ficres,"\n");
                   12327:            numlinepar++;
                   12328:          } /* end k*/
                   12329:        } /*end j */
1.126     brouard  12330:       } /* end i */
                   12331:     } /* end itimes */
                   12332:     
                   12333:     fflush(ficlog);
                   12334:     fflush(ficres);
1.225     brouard  12335:     while(fgets(line, MAXLINE, ficpar)) {
                   12336:       /* If line starts with a # it is a comment */
                   12337:       if (line[0] == '#') {
                   12338:        numlinepar++;
                   12339:        fputs(line,stdout);
                   12340:        fputs(line,ficparo);
                   12341:        fputs(line,ficlog);
1.299     brouard  12342:        fputs(line,ficres);
1.225     brouard  12343:        continue;
                   12344:       }else
                   12345:        break;
                   12346:     }
                   12347:     
1.209     brouard  12348:     /* while((c=getc(ficpar))=='#' && c!= EOF){ */
                   12349:     /*   ungetc(c,ficpar); */
                   12350:     /*   fgets(line, MAXLINE, ficpar); */
                   12351:     /*   fputs(line,stdout); */
                   12352:     /*   fputs(line,ficparo); */
                   12353:     /* } */
                   12354:     /* ungetc(c,ficpar); */
1.126     brouard  12355:     
                   12356:     estepm=0;
1.209     brouard  12357:     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  12358:       
                   12359:       if (num_filled != 6) {
                   12360:        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);
                   12361:        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);
                   12362:        goto end;
                   12363:       }
                   12364:       printf("agemin=%lf agemax=%lf bage=%lf fage=%lf estepm=%d ftolpl=%lf\n",ageminpar,agemaxpar, bage, fage, estepm, ftolpl);
                   12365:     }
                   12366:     /* ftolpl=6*ftol*1.e5; /\* 6.e-3 make convergences in less than 80 loops for the prevalence limit *\/ */
                   12367:     /*ftolpl=6.e-4;*/ /* 6.e-3 make convergences in less than 80 loops for the prevalence limit */
                   12368:     
1.209     brouard  12369:     /* fscanf(ficpar,"agemin=%lf agemax=%lf bage=%lf fage=%lf estepm=%d ftolpl=%\n",&ageminpar,&agemaxpar, &bage, &fage, &estepm); */
1.126     brouard  12370:     if (estepm==0 || estepm < stepm) estepm=stepm;
                   12371:     if (fage <= 2) {
                   12372:       bage = ageminpar;
                   12373:       fage = agemaxpar;
                   12374:     }
                   12375:     
                   12376:     fprintf(ficres,"# agemin agemax for life expectancy, bage fage (if mle==0 ie no data nor Max likelihood).\n");
1.211     brouard  12377:     fprintf(ficres,"agemin=%.0f agemax=%.0f bage=%.0f fage=%.0f estepm=%d ftolpl=%e\n",ageminpar,agemaxpar,bage,fage, estepm, ftolpl);
                   12378:     fprintf(ficparo,"agemin=%.0f agemax=%.0f bage=%.0f fage=%.0f estepm=%d, ftolpl=%e\n",ageminpar,agemaxpar,bage,fage, estepm, ftolpl);
1.220     brouard  12379:                
1.186     brouard  12380:     /* Other stuffs, more or less useful */    
1.254     brouard  12381:     while(fgets(line, MAXLINE, ficpar)) {
                   12382:       /* If line starts with a # it is a comment */
                   12383:       if (line[0] == '#') {
                   12384:        numlinepar++;
                   12385:        fputs(line,stdout);
                   12386:        fputs(line,ficparo);
                   12387:        fputs(line,ficlog);
1.299     brouard  12388:        fputs(line,ficres);
1.254     brouard  12389:        continue;
                   12390:       }else
                   12391:        break;
                   12392:     }
                   12393: 
                   12394:     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){
                   12395:       
                   12396:       if (num_filled != 7) {
                   12397:        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);
                   12398:        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);
                   12399:        goto end;
                   12400:       }
                   12401:       printf("begin-prev-date=%.lf/%.lf/%.lf end-prev-date=%.lf/%.lf/%.lf mov_average=%d\n",jprev1, mprev1,anprev1,jprev2, mprev2,anprev2,mobilav);
                   12402:       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);
                   12403:       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);
                   12404:       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  12405:     }
1.254     brouard  12406: 
                   12407:     while(fgets(line, MAXLINE, ficpar)) {
                   12408:       /* If line starts with a # it is a comment */
                   12409:       if (line[0] == '#') {
                   12410:        numlinepar++;
                   12411:        fputs(line,stdout);
                   12412:        fputs(line,ficparo);
                   12413:        fputs(line,ficlog);
1.299     brouard  12414:        fputs(line,ficres);
1.254     brouard  12415:        continue;
                   12416:       }else
                   12417:        break;
1.126     brouard  12418:     }
                   12419:     
                   12420:     
                   12421:     dateprev1=anprev1+(mprev1-1)/12.+(jprev1-1)/365.;
                   12422:     dateprev2=anprev2+(mprev2-1)/12.+(jprev2-1)/365.;
                   12423:     
1.254     brouard  12424:     if((num_filled=sscanf(line,"pop_based=%d\n",&popbased)) !=EOF){
                   12425:       if (num_filled != 1) {
                   12426:        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);
                   12427:        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);
                   12428:        goto end;
                   12429:       }
                   12430:       printf("pop_based=%d\n",popbased);
                   12431:       fprintf(ficlog,"pop_based=%d\n",popbased);
                   12432:       fprintf(ficparo,"pop_based=%d\n",popbased);   
                   12433:       fprintf(ficres,"pop_based=%d\n",popbased);   
                   12434:     }
                   12435:      
1.258     brouard  12436:     /* Results */
1.307     brouard  12437:     endishere=0;
1.258     brouard  12438:     nresult=0;
1.308     brouard  12439:     parameterline=0;
1.258     brouard  12440:     do{
                   12441:       if(!fgets(line, MAXLINE, ficpar)){
                   12442:        endishere=1;
1.308     brouard  12443:        parameterline=15;
1.258     brouard  12444:       }else if (line[0] == '#') {
                   12445:        /* If line starts with a # it is a comment */
1.254     brouard  12446:        numlinepar++;
                   12447:        fputs(line,stdout);
                   12448:        fputs(line,ficparo);
                   12449:        fputs(line,ficlog);
1.299     brouard  12450:        fputs(line,ficres);
1.254     brouard  12451:        continue;
1.258     brouard  12452:       }else if(sscanf(line,"prevforecast=%[^\n]\n",modeltemp))
                   12453:        parameterline=11;
1.296     brouard  12454:       else if(sscanf(line,"prevbackcast=%[^\n]\n",modeltemp))
1.258     brouard  12455:        parameterline=12;
1.307     brouard  12456:       else if(sscanf(line,"result:%[^\n]\n",modeltemp)){
1.258     brouard  12457:        parameterline=13;
1.307     brouard  12458:       }
1.258     brouard  12459:       else{
                   12460:        parameterline=14;
1.254     brouard  12461:       }
1.308     brouard  12462:       switch (parameterline){ /* =0 only if only comments */
1.258     brouard  12463:       case 11:
1.296     brouard  12464:        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)){
                   12465:                  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  12466:          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);
                   12467:          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);
                   12468:          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);
                   12469:          /* day and month of proj2 are not used but only year anproj2.*/
1.273     brouard  12470:          dateproj1=anproj1+(mproj1-1)/12.+(jproj1-1)/365.;
                   12471:          dateproj2=anproj2+(mproj2-1)/12.+(jproj2-1)/365.;
1.296     brouard  12472:           prvforecast = 1;
                   12473:        } 
                   12474:        else if((num_filled=sscanf(line,"prevforecast=%d yearsfproj=%lf mobil_average=%d\n",&prevfcast,&yrfproj,&mobilavproj)) !=EOF){/* && (num_filled == 3))*/
1.302     brouard  12475:          printf("prevforecast=%d yearsfproj=%lf.2 mobil_average=%d\n",prevfcast,yrfproj,mobilavproj);
                   12476:          fprintf(ficlog,"prevforecast=%d yearsfproj=%lf.2 mobil_average=%d\n",prevfcast,yrfproj,mobilavproj);
                   12477:          fprintf(ficres,"prevforecast=%d yearsfproj=%lf.2 mobil_average=%d\n",prevfcast,yrfproj,mobilavproj);
1.296     brouard  12478:           prvforecast = 2;
                   12479:        }
                   12480:        else {
                   12481:          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);
                   12482:          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);
                   12483:          goto end;
1.258     brouard  12484:        }
1.254     brouard  12485:        break;
1.258     brouard  12486:       case 12:
1.296     brouard  12487:        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)){
                   12488:           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);
                   12489:          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);
                   12490:          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);
                   12491:          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);
                   12492:          /* day and month of back2 are not used but only year anback2.*/
1.273     brouard  12493:          dateback1=anback1+(mback1-1)/12.+(jback1-1)/365.;
                   12494:          dateback2=anback2+(mback2-1)/12.+(jback2-1)/365.;
1.296     brouard  12495:           prvbackcast = 1;
                   12496:        } 
                   12497:        else if((num_filled=sscanf(line,"prevbackcast=%d yearsbproj=%lf mobil_average=%d\n",&prevbcast,&yrbproj,&mobilavproj)) ==3){/* && (num_filled == 3))*/
1.302     brouard  12498:          printf("prevbackcast=%d yearsbproj=%lf.2 mobil_average=%d\n",prevbcast,yrbproj,mobilavproj);
                   12499:          fprintf(ficlog,"prevbackcast=%d yearsbproj=%lf.2 mobil_average=%d\n",prevbcast,yrbproj,mobilavproj);
                   12500:          fprintf(ficres,"prevbackcast=%d yearsbproj=%lf.2 mobil_average=%d\n",prevbcast,yrbproj,mobilavproj);
1.296     brouard  12501:           prvbackcast = 2;
                   12502:        }
                   12503:        else {
                   12504:          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);
                   12505:          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);
                   12506:          goto end;
1.258     brouard  12507:        }
1.230     brouard  12508:        break;
1.258     brouard  12509:       case 13:
1.307     brouard  12510:        num_filled=sscanf(line,"result:%[^\n]\n",resultline);
                   12511:        nresult++; /* Sum of resultlines */
                   12512:        printf("Result %d: result:%s\n",nresult, resultline);
                   12513:        if(nresult > MAXRESULTLINES){
                   12514:          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. ",MAXRESULTLINES,nresult,rfileres);
                   12515:          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. ",MAXRESULTLINES,nresult,rfileres);
                   12516:          goto end;
                   12517:        }
1.310   ! brouard  12518:        if(!decoderesult(resultline, nresult)){ /* Fills TKresult[nresult] combination and Tresult[nresult][k4+1] combination values */
1.307     brouard  12519:        fprintf(ficparo,"result: %s\n",resultline);
                   12520:        fprintf(ficres,"result: %s\n",resultline);
                   12521:        fprintf(ficlog,"result: %s\n",resultline);
1.310   ! brouard  12522:        } else
        !          12523:          goto end;
1.307     brouard  12524:        break;
                   12525:       case 14:
                   12526:        printf("Error: Unknown command '%s'\n",line);
                   12527:        fprintf(ficlog,"Error: Unknown command '%s'\n",line);
                   12528:        if(ncovmodel >=2 && nresult==0 ){
                   12529:          printf("ERROR: no result lines! It should be at minimum 'result: V2=0 V1=1 or result:.' %s\n",line);
                   12530:          fprintf(ficlog,"ERROR: no result lines! It should be at minimum 'result: V2=0 V1=1 or result:.' %s\n",line);
1.258     brouard  12531:        }
1.307     brouard  12532:        /* goto end; */
                   12533:        break;
1.308     brouard  12534:       case 15:
                   12535:        printf("End of resultlines.\n");
                   12536:        fprintf(ficlog,"End of resultlines.\n");
                   12537:        break;
                   12538:       default: /* parameterline =0 */
1.307     brouard  12539:        nresult=1;
                   12540:        decoderesult(".",nresult ); /* No covariate */
1.258     brouard  12541:       } /* End switch parameterline */
                   12542:     }while(endishere==0); /* End do */
1.126     brouard  12543:     
1.230     brouard  12544:     /* freqsummary(fileres, agemin, agemax, s, agev, nlstate, imx,Tvaraff,nbcode, ncodemax,mint,anint); */
1.145     brouard  12545:     /* ,dateprev1,dateprev2,jprev1, mprev1,anprev1,jprev2, mprev2,anprev2); */
1.126     brouard  12546:     
                   12547:     replace_back_to_slash(pathc,pathcd); /* Even gnuplot wants a / */
1.194     brouard  12548:     if(ageminpar == AGEOVERFLOW ||agemaxpar == -AGEOVERFLOW){
1.230     brouard  12549:       printf("Warning! Error in gnuplot file with ageminpar %f or agemaxpar %f overflow\n\
1.194     brouard  12550: This is probably because your parameter file doesn't \n  contain the exact number of lines (or columns) corresponding to your model line.\n\
                   12551: Please run with mle=-1 to get a correct covariance matrix.\n",ageminpar,agemaxpar);
1.230     brouard  12552:       fprintf(ficlog,"Warning! Error in gnuplot file with ageminpar %f or agemaxpar %f overflow\n\
1.194     brouard  12553: This is probably because your parameter file doesn't \n  contain the exact number of lines (or columns) corresponding to your model line.\n\
                   12554: Please run with mle=-1 to get a correct covariance matrix.\n",ageminpar,agemaxpar);
1.220     brouard  12555:     }else{
1.270     brouard  12556:       /* printinggnuplot(fileresu, optionfilefiname,ageminpar,agemaxpar,fage, prevfcast, backcast, pathc,p, (int)anproj1-(int)agemin, (int)anback1-(int)agemax+1); */
1.296     brouard  12557:       /* It seems that anprojd which is computed from the mean year at interview which is known yet because of freqsummary */
                   12558:       /* date2dmy(dateintmean,&jintmean,&mintmean,&aintmean); */ /* Done in freqsummary */
                   12559:       if(prvforecast==1){
                   12560:         dateprojd=(jproj1+12*mproj1+365*anproj1)/365;
                   12561:         jprojd=jproj1;
                   12562:         mprojd=mproj1;
                   12563:         anprojd=anproj1;
                   12564:         dateprojf=(jproj2+12*mproj2+365*anproj2)/365;
                   12565:         jprojf=jproj2;
                   12566:         mprojf=mproj2;
                   12567:         anprojf=anproj2;
                   12568:       } else if(prvforecast == 2){
                   12569:         dateprojd=dateintmean;
                   12570:         date2dmy(dateprojd,&jprojd, &mprojd, &anprojd);
                   12571:         dateprojf=dateintmean+yrfproj;
                   12572:         date2dmy(dateprojf,&jprojf, &mprojf, &anprojf);
                   12573:       }
                   12574:       if(prvbackcast==1){
                   12575:         datebackd=(jback1+12*mback1+365*anback1)/365;
                   12576:         jbackd=jback1;
                   12577:         mbackd=mback1;
                   12578:         anbackd=anback1;
                   12579:         datebackf=(jback2+12*mback2+365*anback2)/365;
                   12580:         jbackf=jback2;
                   12581:         mbackf=mback2;
                   12582:         anbackf=anback2;
                   12583:       } else if(prvbackcast == 2){
                   12584:         datebackd=dateintmean;
                   12585:         date2dmy(datebackd,&jbackd, &mbackd, &anbackd);
                   12586:         datebackf=dateintmean-yrbproj;
                   12587:         date2dmy(datebackf,&jbackf, &mbackf, &anbackf);
                   12588:       }
                   12589:       
                   12590:       printinggnuplot(fileresu, optionfilefiname,ageminpar,agemaxpar,bage, fage, prevfcast, prevbcast, pathc,p, (int)anprojd-bage, (int)anbackd-fage);
1.220     brouard  12591:     }
                   12592:     printinghtml(fileresu,title,datafile, firstpass, lastpass, stepm, weightopt, \
1.296     brouard  12593:                 model,imx,jmin,jmax,jmean,rfileres,popforecast,mobilav,prevfcast,mobilavproj,prevbcast, estepm, \
                   12594:                 jprev1,mprev1,anprev1,dateprev1, dateprojd, datebackd,jprev2,mprev2,anprev2,dateprev2,dateprojf, datebackf);
1.220     brouard  12595:                
1.225     brouard  12596:     /*------------ free_vector  -------------*/
                   12597:     /*  chdir(path); */
1.220     brouard  12598:                
1.215     brouard  12599:     /* free_ivector(wav,1,imx); */  /* Moved after last prevalence call */
                   12600:     /* free_imatrix(dh,1,lastpass-firstpass+2,1,imx); */
                   12601:     /* free_imatrix(bh,1,lastpass-firstpass+2,1,imx); */
                   12602:     /* free_imatrix(mw,1,lastpass-firstpass+2,1,imx);    */
1.290     brouard  12603:     free_lvector(num,firstobs,lastobs);
                   12604:     free_vector(agedc,firstobs,lastobs);
1.126     brouard  12605:     /*free_matrix(covar,0,NCOVMAX,1,n);*/
                   12606:     /*free_matrix(covar,1,NCOVMAX,1,n);*/
                   12607:     fclose(ficparo);
                   12608:     fclose(ficres);
1.220     brouard  12609:                
                   12610:                
1.186     brouard  12611:     /* Other results (useful)*/
1.220     brouard  12612:                
                   12613:                
1.126     brouard  12614:     /*--------------- Prevalence limit  (period or stable prevalence) --------------*/
1.180     brouard  12615:     /*#include "prevlim.h"*/  /* Use ficrespl, ficlog */
                   12616:     prlim=matrix(1,nlstate,1,nlstate);
1.209     brouard  12617:     prevalence_limit(p, prlim,  ageminpar, agemaxpar, ftolpl, &ncvyear);
1.126     brouard  12618:     fclose(ficrespl);
                   12619: 
                   12620:     /*------------- h Pij x at various ages ------------*/
1.180     brouard  12621:     /*#include "hpijx.h"*/
                   12622:     hPijx(p, bage, fage);
1.145     brouard  12623:     fclose(ficrespij);
1.227     brouard  12624:     
1.220     brouard  12625:     /* ncovcombmax=  pow(2,cptcoveff); */
1.219     brouard  12626:     /*-------------- Variance of one-step probabilities---*/
1.145     brouard  12627:     k=1;
1.126     brouard  12628:     varprob(optionfilefiname, matcov, p, delti, nlstate, bage, fage,k,Tvar,nbcode, ncodemax,strstart);
1.227     brouard  12629:     
1.269     brouard  12630:     /* Prevalence for each covariate combination in probs[age][status][cov] */
                   12631:     probs= ma3x(AGEINF,AGESUP,1,nlstate+ndeath, 1,ncovcombmax);
                   12632:     for(i=AGEINF;i<=AGESUP;i++)
1.219     brouard  12633:       for(j=1;j<=nlstate+ndeath;j++) /* ndeath is useless but a necessity to be compared with mobaverages */
1.225     brouard  12634:        for(k=1;k<=ncovcombmax;k++)
                   12635:          probs[i][j][k]=0.;
1.269     brouard  12636:     prevalence(probs, ageminpar, agemaxpar, s, agev, nlstate, imx, Tvar, nbcode, 
                   12637:               ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass);
1.219     brouard  12638:     if (mobilav!=0 ||mobilavproj !=0 ) {
1.269     brouard  12639:       mobaverages= ma3x(AGEINF, AGESUP,1,nlstate+ndeath, 1,ncovcombmax);
                   12640:       for(i=AGEINF;i<=AGESUP;i++)
1.268     brouard  12641:        for(j=1;j<=nlstate+ndeath;j++)
1.227     brouard  12642:          for(k=1;k<=ncovcombmax;k++)
                   12643:            mobaverages[i][j][k]=0.;
1.219     brouard  12644:       mobaverage=mobaverages;
                   12645:       if (mobilav!=0) {
1.235     brouard  12646:        printf("Movingaveraging observed prevalence\n");
1.258     brouard  12647:        fprintf(ficlog,"Movingaveraging observed prevalence\n");
1.227     brouard  12648:        if (movingaverage(probs, ageminpar, agemaxpar, mobaverage, mobilav)!=0){
                   12649:          fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);
                   12650:          printf(" Error in movingaverage mobilav=%d\n",mobilav);
                   12651:        }
1.269     brouard  12652:       } else if (mobilavproj !=0) {
1.235     brouard  12653:        printf("Movingaveraging projected observed prevalence\n");
1.258     brouard  12654:        fprintf(ficlog,"Movingaveraging projected observed prevalence\n");
1.227     brouard  12655:        if (movingaverage(probs, ageminpar, agemaxpar, mobaverage, mobilavproj)!=0){
                   12656:          fprintf(ficlog," Error in movingaverage mobilavproj=%d\n",mobilavproj);
                   12657:          printf(" Error in movingaverage mobilavproj=%d\n",mobilavproj);
                   12658:        }
1.269     brouard  12659:       }else{
                   12660:        printf("Internal error moving average\n");
                   12661:        fflush(stdout);
                   12662:        exit(1);
1.219     brouard  12663:       }
                   12664:     }/* end if moving average */
1.227     brouard  12665:     
1.126     brouard  12666:     /*---------- Forecasting ------------------*/
1.296     brouard  12667:     if(prevfcast==1){ 
                   12668:       /*   /\*    if(stepm ==1){*\/ */
                   12669:       /*   /\*  anproj1, mproj1, jproj1 either read explicitly or yrfproj *\/ */
                   12670:       /*This done previously after freqsummary.*/
                   12671:       /*   dateprojd=(jproj1+12*mproj1+365*anproj1)/365; */
                   12672:       /*   dateprojf=(jproj2+12*mproj2+365*anproj2)/365; */
                   12673:       
                   12674:       /* } else if (prvforecast==2){ */
                   12675:       /*   /\*    if(stepm ==1){*\/ */
                   12676:       /*   /\*  anproj1, mproj1, jproj1 either read explicitly or yrfproj *\/ */
                   12677:       /* } */
                   12678:       /*prevforecast(fileresu, dateintmean, anproj1, mproj1, jproj1, agemin, agemax, dateprev1, dateprev2, mobilavproj, mobaverage, bage, fage, firstpass, lastpass, anproj2, p, cptcoveff);*/
                   12679:       prevforecast(fileresu,dateintmean, dateprojd, dateprojf, agemin, agemax, dateprev1, dateprev2, mobilavproj, mobaverage, bage, fage, firstpass, lastpass, p, cptcoveff);
1.126     brouard  12680:     }
1.269     brouard  12681: 
1.296     brouard  12682:     /* Prevbcasting */
                   12683:     if(prevbcast==1){
1.219     brouard  12684:       ddnewms=matrix(1,nlstate+ndeath,1,nlstate+ndeath);       
                   12685:       ddoldms=matrix(1,nlstate+ndeath,1,nlstate+ndeath);       
                   12686:       ddsavms=matrix(1,nlstate+ndeath,1,nlstate+ndeath);
                   12687: 
                   12688:       /*--------------- Back Prevalence limit  (period or stable prevalence) --------------*/
                   12689: 
                   12690:       bprlim=matrix(1,nlstate,1,nlstate);
1.269     brouard  12691: 
1.219     brouard  12692:       back_prevalence_limit(p, bprlim,  ageminpar, agemaxpar, ftolpl, &ncvyear, dateprev1, dateprev2, firstpass, lastpass, mobilavproj);
                   12693:       fclose(ficresplb);
                   12694: 
1.222     brouard  12695:       hBijx(p, bage, fage, mobaverage);
                   12696:       fclose(ficrespijb);
1.219     brouard  12697: 
1.296     brouard  12698:       /* /\* prevbackforecast(fileresu, mobaverage, anback1, mback1, jback1, agemin, agemax, dateprev1, dateprev2, *\/ */
                   12699:       /* /\*                  mobilavproj, bage, fage, firstpass, lastpass, anback2, p, cptcoveff); *\/ */
                   12700:       /* prevbackforecast(fileresu, mobaverage, anback1, mback1, jback1, agemin, agemax, dateprev1, dateprev2, */
                   12701:       /*                      mobilavproj, bage, fage, firstpass, lastpass, anback2, p, cptcoveff); */
                   12702:       prevbackforecast(fileresu, mobaverage, dateintmean, dateprojd, dateprojf, agemin, agemax, dateprev1, dateprev2,
                   12703:                       mobilavproj, bage, fage, firstpass, lastpass, p, cptcoveff);
                   12704: 
                   12705:       
1.269     brouard  12706:       varbprlim(fileresu, nresult, mobaverage, mobilavproj, bage, fage, bprlim, &ncvyear, ftolpl, p, matcov, delti, stepm, cptcoveff);
1.268     brouard  12707: 
                   12708:       
1.269     brouard  12709:       free_matrix(bprlim,1,nlstate,1,nlstate); /*here or after loop ? */
1.219     brouard  12710:       free_matrix(ddnewms, 1, nlstate+ndeath, 1, nlstate+ndeath);
                   12711:       free_matrix(ddsavms, 1, nlstate+ndeath, 1, nlstate+ndeath);
                   12712:       free_matrix(ddoldms, 1, nlstate+ndeath, 1, nlstate+ndeath);
1.296     brouard  12713:     }    /* end  Prevbcasting */
1.268     brouard  12714:  
1.186     brouard  12715:  
                   12716:     /* ------ Other prevalence ratios------------ */
1.126     brouard  12717: 
1.215     brouard  12718:     free_ivector(wav,1,imx);
                   12719:     free_imatrix(dh,1,lastpass-firstpass+2,1,imx);
                   12720:     free_imatrix(bh,1,lastpass-firstpass+2,1,imx);
                   12721:     free_imatrix(mw,1,lastpass-firstpass+2,1,imx);   
1.218     brouard  12722:                
                   12723:                
1.127     brouard  12724:     /*---------- Health expectancies, no variances ------------*/
1.218     brouard  12725:                
1.201     brouard  12726:     strcpy(filerese,"E_");
                   12727:     strcat(filerese,fileresu);
1.126     brouard  12728:     if((ficreseij=fopen(filerese,"w"))==NULL) {
                   12729:       printf("Problem with Health Exp. resultfile: %s\n", filerese); exit(0);
                   12730:       fprintf(ficlog,"Problem with Health Exp. resultfile: %s\n", filerese); exit(0);
                   12731:     }
1.208     brouard  12732:     printf("Computing Health Expectancies: result on file '%s' ...", filerese);fflush(stdout);
                   12733:     fprintf(ficlog,"Computing Health Expectancies: result on file '%s' ...", filerese);fflush(ficlog);
1.238     brouard  12734: 
                   12735:     pstamp(ficreseij);
1.219     brouard  12736:                
1.235     brouard  12737:     i1=pow(2,cptcoveff); /* Number of combination of dummy covariates */
                   12738:     if (cptcovn < 1){i1=1;}
                   12739:     
                   12740:     for(nres=1; nres <= nresult; nres++) /* For each resultline */
                   12741:     for(k=1; k<=i1;k++){ /* For any combination of dummy covariates, fixed and varying */
1.253     brouard  12742:       if(i1 != 1 && TKresult[nres]!= k)
1.235     brouard  12743:        continue;
1.219     brouard  12744:       fprintf(ficreseij,"\n#****** ");
1.235     brouard  12745:       printf("\n#****** ");
1.225     brouard  12746:       for(j=1;j<=cptcoveff;j++) {
1.227     brouard  12747:        fprintf(ficreseij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
1.235     brouard  12748:        printf("V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   12749:       }
                   12750:       for (j=1; j<= nsq; j++){ /* For each selected (single) quantitative value */
                   12751:        printf(" V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]);
                   12752:        fprintf(ficreseij," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]);
1.219     brouard  12753:       }
                   12754:       fprintf(ficreseij,"******\n");
1.235     brouard  12755:       printf("******\n");
1.219     brouard  12756:       
                   12757:       eij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
                   12758:       oldm=oldms;savm=savms;
1.235     brouard  12759:       evsij(eij, p, nlstate, stepm, (int) bage, (int)fage, oldm, savm, k, estepm, strstart, nres);  
1.127     brouard  12760:       
1.219     brouard  12761:       free_ma3x(eij,1,nlstate,1,nlstate,(int) bage, (int)fage);
1.127     brouard  12762:     }
                   12763:     fclose(ficreseij);
1.208     brouard  12764:     printf("done evsij\n");fflush(stdout);
                   12765:     fprintf(ficlog,"done evsij\n");fflush(ficlog);
1.269     brouard  12766: 
1.218     brouard  12767:                
1.227     brouard  12768:     /*---------- State-specific expectancies and variances ------------*/
1.218     brouard  12769:                
1.201     brouard  12770:     strcpy(filerest,"T_");
                   12771:     strcat(filerest,fileresu);
1.127     brouard  12772:     if((ficrest=fopen(filerest,"w"))==NULL) {
                   12773:       printf("Problem with total LE resultfile: %s\n", filerest);goto end;
                   12774:       fprintf(ficlog,"Problem with total LE resultfile: %s\n", filerest);goto end;
                   12775:     }
1.208     brouard  12776:     printf("Computing Total Life expectancies with their standard errors: file '%s' ...\n", filerest); fflush(stdout);
                   12777:     fprintf(ficlog,"Computing Total Life expectancies with their standard errors: file '%s' ...\n", filerest); fflush(ficlog);
1.201     brouard  12778:     strcpy(fileresstde,"STDE_");
                   12779:     strcat(fileresstde,fileresu);
1.126     brouard  12780:     if((ficresstdeij=fopen(fileresstde,"w"))==NULL) {
1.227     brouard  12781:       printf("Problem with State specific Exp. and std errors resultfile: %s\n", fileresstde); exit(0);
                   12782:       fprintf(ficlog,"Problem with State specific Exp. and std errors resultfile: %s\n", fileresstde); exit(0);
1.126     brouard  12783:     }
1.227     brouard  12784:     printf("  Computing State-specific Expectancies and standard errors: result on file '%s' \n", fileresstde);
                   12785:     fprintf(ficlog,"  Computing State-specific Expectancies and standard errors: result on file '%s' \n", fileresstde);
1.126     brouard  12786: 
1.201     brouard  12787:     strcpy(filerescve,"CVE_");
                   12788:     strcat(filerescve,fileresu);
1.126     brouard  12789:     if((ficrescveij=fopen(filerescve,"w"))==NULL) {
1.227     brouard  12790:       printf("Problem with Covar. State-specific Exp. resultfile: %s\n", filerescve); exit(0);
                   12791:       fprintf(ficlog,"Problem with Covar. State-specific Exp. resultfile: %s\n", filerescve); exit(0);
1.126     brouard  12792:     }
1.227     brouard  12793:     printf("    Computing Covar. of State-specific Expectancies: result on file '%s' \n", filerescve);
                   12794:     fprintf(ficlog,"    Computing Covar. of State-specific Expectancies: result on file '%s' \n", filerescve);
1.126     brouard  12795: 
1.201     brouard  12796:     strcpy(fileresv,"V_");
                   12797:     strcat(fileresv,fileresu);
1.126     brouard  12798:     if((ficresvij=fopen(fileresv,"w"))==NULL) {
                   12799:       printf("Problem with variance resultfile: %s\n", fileresv);exit(0);
                   12800:       fprintf(ficlog,"Problem with variance resultfile: %s\n", fileresv);exit(0);
                   12801:     }
1.227     brouard  12802:     printf("      Computing Variance-covariance of State-specific Expectancies: file '%s' ... ", fileresv);fflush(stdout);
                   12803:     fprintf(ficlog,"      Computing Variance-covariance of State-specific Expectancies: file '%s' ... ", fileresv);fflush(ficlog);
1.126     brouard  12804: 
1.235     brouard  12805:     i1=pow(2,cptcoveff); /* Number of combination of dummy covariates */
                   12806:     if (cptcovn < 1){i1=1;}
                   12807:     
                   12808:     for(nres=1; nres <= nresult; nres++) /* For each resultline */
                   12809:     for(k=1; k<=i1;k++){ /* For any combination of dummy covariates, fixed and varying */
1.253     brouard  12810:       if(i1 != 1 && TKresult[nres]!= k)
1.235     brouard  12811:        continue;
1.242     brouard  12812:       printf("\n#****** Result for:");
                   12813:       fprintf(ficrest,"\n#****** Result for:");
                   12814:       fprintf(ficlog,"\n#****** Result for:");
1.227     brouard  12815:       for(j=1;j<=cptcoveff;j++){ 
                   12816:        printf("V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   12817:        fprintf(ficrest,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   12818:        fprintf(ficlog,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   12819:       }
1.235     brouard  12820:       for (j=1; j<= nsq; j++){ /* For each selected (single) quantitative value */
                   12821:        printf(" V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]);
                   12822:        fprintf(ficrest," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]);
                   12823:        fprintf(ficlog," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]);
                   12824:       }        
1.208     brouard  12825:       fprintf(ficrest,"******\n");
1.227     brouard  12826:       fprintf(ficlog,"******\n");
                   12827:       printf("******\n");
1.208     brouard  12828:       
                   12829:       fprintf(ficresstdeij,"\n#****** ");
                   12830:       fprintf(ficrescveij,"\n#****** ");
1.225     brouard  12831:       for(j=1;j<=cptcoveff;j++) {
1.227     brouard  12832:        fprintf(ficresstdeij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   12833:        fprintf(ficrescveij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
1.208     brouard  12834:       }
1.235     brouard  12835:       for (j=1; j<= nsq; j++){ /* For each selected (single) quantitative value */
                   12836:        fprintf(ficresstdeij," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]);
                   12837:        fprintf(ficrescveij," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]);
                   12838:       }        
1.208     brouard  12839:       fprintf(ficresstdeij,"******\n");
                   12840:       fprintf(ficrescveij,"******\n");
                   12841:       
                   12842:       fprintf(ficresvij,"\n#****** ");
1.238     brouard  12843:       /* pstamp(ficresvij); */
1.225     brouard  12844:       for(j=1;j<=cptcoveff;j++) 
1.227     brouard  12845:        fprintf(ficresvij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
1.235     brouard  12846:       for (j=1; j<= nsq; j++){ /* For each selected (single) quantitative value */
                   12847:        fprintf(ficresvij," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]);
                   12848:       }        
1.208     brouard  12849:       fprintf(ficresvij,"******\n");
                   12850:       
                   12851:       eij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
                   12852:       oldm=oldms;savm=savms;
1.235     brouard  12853:       printf(" cvevsij ");
                   12854:       fprintf(ficlog, " cvevsij ");
                   12855:       cvevsij(eij, p, nlstate, stepm, (int) bage, (int)fage, oldm, savm, k, estepm, delti, matcov, strstart, nres);
1.208     brouard  12856:       printf(" end cvevsij \n ");
                   12857:       fprintf(ficlog, " end cvevsij \n ");
                   12858:       
                   12859:       /*
                   12860:        */
                   12861:       /* goto endfree; */
                   12862:       
                   12863:       vareij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
                   12864:       pstamp(ficrest);
                   12865:       
1.269     brouard  12866:       epj=vector(1,nlstate+1);
1.208     brouard  12867:       for(vpopbased=0; vpopbased <= popbased; vpopbased++){ /* Done for vpopbased=0 and vpopbased=1 if popbased==1*/
1.227     brouard  12868:        oldm=oldms;savm=savms; /* ZZ Segmentation fault */
                   12869:        cptcod= 0; /* To be deleted */
                   12870:        printf("varevsij vpopbased=%d \n",vpopbased);
                   12871:        fprintf(ficlog, "varevsij vpopbased=%d \n",vpopbased);
1.235     brouard  12872:        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  12873:        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 ");
                   12874:        if(vpopbased==1)
                   12875:          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);
                   12876:        else
1.288     brouard  12877:          fprintf(ficrest,"the age specific forward period (stable) prevalences in each health state \n");
1.227     brouard  12878:        fprintf(ficrest,"# Age popbased mobilav e.. (std) ");
                   12879:        for (i=1;i<=nlstate;i++) fprintf(ficrest,"e.%d (std) ",i);
                   12880:        fprintf(ficrest,"\n");
                   12881:        /* printf("Which p?\n"); for(i=1;i<=npar;i++)printf("p[i=%d]=%lf,",i,p[i]);printf("\n"); */
1.288     brouard  12882:        printf("Computing age specific forward period (stable) prevalences in each health state \n");
                   12883:        fprintf(ficlog,"Computing age specific forward period (stable) prevalences in each health state \n");
1.227     brouard  12884:        for(age=bage; age <=fage ;age++){
1.235     brouard  12885:          prevalim(prlim, nlstate, p, age, oldm, savm, ftolpl, &ncvyear, k, nres); /*ZZ Is it the correct prevalim */
1.227     brouard  12886:          if (vpopbased==1) {
                   12887:            if(mobilav ==0){
                   12888:              for(i=1; i<=nlstate;i++)
                   12889:                prlim[i][i]=probs[(int)age][i][k];
                   12890:            }else{ /* mobilav */ 
                   12891:              for(i=1; i<=nlstate;i++)
                   12892:                prlim[i][i]=mobaverage[(int)age][i][k];
                   12893:            }
                   12894:          }
1.219     brouard  12895:          
1.227     brouard  12896:          fprintf(ficrest," %4.0f %d %d",age, vpopbased, mobilav);
                   12897:          /* fprintf(ficrest," %4.0f %d %d %d %d",age, vpopbased, mobilav,Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]); */ /* to be done */
                   12898:          /* printf(" age %4.0f ",age); */
                   12899:          for(j=1, epj[nlstate+1]=0.;j <=nlstate;j++){
                   12900:            for(i=1, epj[j]=0.;i <=nlstate;i++) {
                   12901:              epj[j] += prlim[i][i]*eij[i][j][(int)age];
                   12902:              /*ZZZ  printf("%lf %lf ", prlim[i][i] ,eij[i][j][(int)age]);*/
                   12903:              /* printf("%lf %lf ", prlim[i][i] ,eij[i][j][(int)age]); */
                   12904:            }
                   12905:            epj[nlstate+1] +=epj[j];
                   12906:          }
                   12907:          /* printf(" age %4.0f \n",age); */
1.219     brouard  12908:          
1.227     brouard  12909:          for(i=1, vepp=0.;i <=nlstate;i++)
                   12910:            for(j=1;j <=nlstate;j++)
                   12911:              vepp += vareij[i][j][(int)age];
                   12912:          fprintf(ficrest," %7.3f (%7.3f)", epj[nlstate+1],sqrt(vepp));
                   12913:          for(j=1;j <=nlstate;j++){
                   12914:            fprintf(ficrest," %7.3f (%7.3f)", epj[j],sqrt(vareij[j][j][(int)age]));
                   12915:          }
                   12916:          fprintf(ficrest,"\n");
                   12917:        }
1.208     brouard  12918:       } /* End vpopbased */
1.269     brouard  12919:       free_vector(epj,1,nlstate+1);
1.208     brouard  12920:       free_ma3x(eij,1,nlstate,1,nlstate,(int) bage, (int)fage);
                   12921:       free_ma3x(vareij,1,nlstate,1,nlstate,(int) bage, (int)fage);
1.235     brouard  12922:       printf("done selection\n");fflush(stdout);
                   12923:       fprintf(ficlog,"done selection\n");fflush(ficlog);
1.208     brouard  12924:       
1.235     brouard  12925:     } /* End k selection */
1.227     brouard  12926: 
                   12927:     printf("done State-specific expectancies\n");fflush(stdout);
                   12928:     fprintf(ficlog,"done State-specific expectancies\n");fflush(ficlog);
                   12929: 
1.288     brouard  12930:     /* variance-covariance of forward period prevalence*/
1.269     brouard  12931:     varprlim(fileresu, nresult, mobaverage, mobilavproj, bage, fage, prlim, &ncvyear, ftolpl, p, matcov, delti, stepm, cptcoveff);
1.268     brouard  12932: 
1.227     brouard  12933:     
1.290     brouard  12934:     free_vector(weight,firstobs,lastobs);
1.227     brouard  12935:     free_imatrix(Tvard,1,NCOVMAX,1,2);
1.290     brouard  12936:     free_imatrix(s,1,maxwav+1,firstobs,lastobs);
                   12937:     free_matrix(anint,1,maxwav,firstobs,lastobs); 
                   12938:     free_matrix(mint,1,maxwav,firstobs,lastobs);
                   12939:     free_ivector(cod,firstobs,lastobs);
1.227     brouard  12940:     free_ivector(tab,1,NCOVMAX);
                   12941:     fclose(ficresstdeij);
                   12942:     fclose(ficrescveij);
                   12943:     fclose(ficresvij);
                   12944:     fclose(ficrest);
                   12945:     fclose(ficpar);
                   12946:     
                   12947:     
1.126     brouard  12948:     /*---------- End : free ----------------*/
1.219     brouard  12949:     if (mobilav!=0 ||mobilavproj !=0)
1.269     brouard  12950:       free_ma3x(mobaverages,AGEINF, AGESUP,1,nlstate+ndeath, 1,ncovcombmax); /* We need to have a squared matrix with prevalence of the dead! */
                   12951:     free_ma3x(probs,AGEINF,AGESUP,1,nlstate+ndeath, 1,ncovcombmax);
1.220     brouard  12952:     free_matrix(prlim,1,nlstate,1,nlstate); /*here or after loop ? */
                   12953:     free_matrix(pmmij,1,nlstate+ndeath,1,nlstate+ndeath);
1.126     brouard  12954:   }  /* mle==-3 arrives here for freeing */
1.227     brouard  12955:   /* endfree:*/
                   12956:   free_matrix(oldms, 1,nlstate+ndeath,1,nlstate+ndeath);
                   12957:   free_matrix(newms, 1,nlstate+ndeath,1,nlstate+ndeath);
                   12958:   free_matrix(savms, 1,nlstate+ndeath,1,nlstate+ndeath);
1.290     brouard  12959:   if(ntv+nqtv>=1)free_ma3x(cotvar,1,maxwav,1,ntv+nqtv,firstobs,lastobs);
                   12960:   if(nqtv>=1)free_ma3x(cotqvar,1,maxwav,1,nqtv,firstobs,lastobs);
                   12961:   if(nqv>=1)free_matrix(coqvar,1,nqv,firstobs,lastobs);
                   12962:   free_matrix(covar,0,NCOVMAX,firstobs,lastobs);
1.227     brouard  12963:   free_matrix(matcov,1,npar,1,npar);
                   12964:   free_matrix(hess,1,npar,1,npar);
                   12965:   /*free_vector(delti,1,npar);*/
                   12966:   free_ma3x(delti3,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel); 
                   12967:   free_matrix(agev,1,maxwav,1,imx);
1.269     brouard  12968:   free_ma3x(paramstart,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel);
1.227     brouard  12969:   free_ma3x(param,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel);
                   12970:   
                   12971:   free_ivector(ncodemax,1,NCOVMAX);
                   12972:   free_ivector(ncodemaxwundef,1,NCOVMAX);
                   12973:   free_ivector(Dummy,-1,NCOVMAX);
                   12974:   free_ivector(Fixed,-1,NCOVMAX);
1.238     brouard  12975:   free_ivector(DummyV,1,NCOVMAX);
                   12976:   free_ivector(FixedV,1,NCOVMAX);
1.227     brouard  12977:   free_ivector(Typevar,-1,NCOVMAX);
                   12978:   free_ivector(Tvar,1,NCOVMAX);
1.234     brouard  12979:   free_ivector(TvarsQ,1,NCOVMAX);
                   12980:   free_ivector(TvarsQind,1,NCOVMAX);
                   12981:   free_ivector(TvarsD,1,NCOVMAX);
                   12982:   free_ivector(TvarsDind,1,NCOVMAX);
1.231     brouard  12983:   free_ivector(TvarFD,1,NCOVMAX);
                   12984:   free_ivector(TvarFDind,1,NCOVMAX);
1.232     brouard  12985:   free_ivector(TvarF,1,NCOVMAX);
                   12986:   free_ivector(TvarFind,1,NCOVMAX);
                   12987:   free_ivector(TvarV,1,NCOVMAX);
                   12988:   free_ivector(TvarVind,1,NCOVMAX);
                   12989:   free_ivector(TvarA,1,NCOVMAX);
                   12990:   free_ivector(TvarAind,1,NCOVMAX);
1.231     brouard  12991:   free_ivector(TvarFQ,1,NCOVMAX);
                   12992:   free_ivector(TvarFQind,1,NCOVMAX);
                   12993:   free_ivector(TvarVD,1,NCOVMAX);
                   12994:   free_ivector(TvarVDind,1,NCOVMAX);
                   12995:   free_ivector(TvarVQ,1,NCOVMAX);
                   12996:   free_ivector(TvarVQind,1,NCOVMAX);
1.230     brouard  12997:   free_ivector(Tvarsel,1,NCOVMAX);
                   12998:   free_vector(Tvalsel,1,NCOVMAX);
1.227     brouard  12999:   free_ivector(Tposprod,1,NCOVMAX);
                   13000:   free_ivector(Tprod,1,NCOVMAX);
                   13001:   free_ivector(Tvaraff,1,NCOVMAX);
                   13002:   free_ivector(invalidvarcomb,1,ncovcombmax);
                   13003:   free_ivector(Tage,1,NCOVMAX);
                   13004:   free_ivector(Tmodelind,1,NCOVMAX);
1.228     brouard  13005:   free_ivector(TmodelInvind,1,NCOVMAX);
                   13006:   free_ivector(TmodelInvQind,1,NCOVMAX);
1.227     brouard  13007:   
                   13008:   free_imatrix(nbcode,0,NCOVMAX,0,NCOVMAX);
                   13009:   /* free_imatrix(codtab,1,100,1,10); */
1.126     brouard  13010:   fflush(fichtm);
                   13011:   fflush(ficgp);
                   13012:   
1.227     brouard  13013:   
1.126     brouard  13014:   if((nberr >0) || (nbwarn>0)){
1.216     brouard  13015:     printf("End of Imach with %d errors and/or %d warnings. Please look at the log file for details.\n",nberr,nbwarn);
                   13016:     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  13017:   }else{
                   13018:     printf("End of Imach\n");
                   13019:     fprintf(ficlog,"End of Imach\n");
                   13020:   }
                   13021:   printf("See log file on %s\n",filelog);
                   13022:   /*  gettimeofday(&end_time, (struct timezone*)0);*/  /* after time */
1.157     brouard  13023:   /*(void) gettimeofday(&end_time,&tzp);*/
                   13024:   rend_time = time(NULL);  
                   13025:   end_time = *localtime(&rend_time);
                   13026:   /* tml = *localtime(&end_time.tm_sec); */
                   13027:   strcpy(strtend,asctime(&end_time));
1.126     brouard  13028:   printf("Local time at start %s\nLocal time at end   %s",strstart, strtend); 
                   13029:   fprintf(ficlog,"Local time at start %s\nLocal time at end   %s\n",strstart, strtend); 
1.157     brouard  13030:   printf("Total time used %s\n", asc_diff_time(rend_time -rstart_time,tmpout));
1.227     brouard  13031:   
1.157     brouard  13032:   printf("Total time was %.0lf Sec.\n", difftime(rend_time,rstart_time));
                   13033:   fprintf(ficlog,"Total time used %s\n", asc_diff_time(rend_time -rstart_time,tmpout));
                   13034:   fprintf(ficlog,"Total time was %.0lf Sec.\n", difftime(rend_time,rstart_time));
1.126     brouard  13035:   /*  printf("Total time was %d uSec.\n", total_usecs);*/
                   13036: /*   if(fileappend(fichtm,optionfilehtm)){ */
                   13037:   fprintf(fichtm,"<br>Local time at start %s<br>Local time at end   %s<br>\n</body></html>",strstart, strtend);
                   13038:   fclose(fichtm);
                   13039:   fprintf(fichtmcov,"<br>Local time at start %s<br>Local time at end   %s<br>\n</body></html>",strstart, strtend);
                   13040:   fclose(fichtmcov);
                   13041:   fclose(ficgp);
                   13042:   fclose(ficlog);
                   13043:   /*------ End -----------*/
1.227     brouard  13044:   
1.281     brouard  13045: 
                   13046: /* Executes gnuplot */
1.227     brouard  13047:   
                   13048:   printf("Before Current directory %s!\n",pathcd);
1.184     brouard  13049: #ifdef WIN32
1.227     brouard  13050:   if (_chdir(pathcd) != 0)
                   13051:     printf("Can't move to directory %s!\n",path);
                   13052:   if(_getcwd(pathcd,MAXLINE) > 0)
1.184     brouard  13053: #else
1.227     brouard  13054:     if(chdir(pathcd) != 0)
                   13055:       printf("Can't move to directory %s!\n", path);
                   13056:   if (getcwd(pathcd, MAXLINE) > 0)
1.184     brouard  13057: #endif 
1.126     brouard  13058:     printf("Current directory %s!\n",pathcd);
                   13059:   /*strcat(plotcmd,CHARSEPARATOR);*/
                   13060:   sprintf(plotcmd,"gnuplot");
1.157     brouard  13061: #ifdef _WIN32
1.126     brouard  13062:   sprintf(plotcmd,"\"%sgnuplot.exe\"",pathimach);
                   13063: #endif
                   13064:   if(!stat(plotcmd,&info)){
1.158     brouard  13065:     printf("Error or gnuplot program not found: '%s'\n",plotcmd);fflush(stdout);
1.126     brouard  13066:     if(!stat(getenv("GNUPLOTBIN"),&info)){
1.158     brouard  13067:       printf("Error or gnuplot program not found: '%s' Environment GNUPLOTBIN not set.\n",plotcmd);fflush(stdout);
1.126     brouard  13068:     }else
                   13069:       strcpy(pplotcmd,plotcmd);
1.157     brouard  13070: #ifdef __unix
1.126     brouard  13071:     strcpy(plotcmd,GNUPLOTPROGRAM);
                   13072:     if(!stat(plotcmd,&info)){
1.158     brouard  13073:       printf("Error gnuplot program not found: '%s'\n",plotcmd);fflush(stdout);
1.126     brouard  13074:     }else
                   13075:       strcpy(pplotcmd,plotcmd);
                   13076: #endif
                   13077:   }else
                   13078:     strcpy(pplotcmd,plotcmd);
                   13079:   
                   13080:   sprintf(plotcmd,"%s %s",pplotcmd, optionfilegnuplot);
1.158     brouard  13081:   printf("Starting graphs with: '%s'\n",plotcmd);fflush(stdout);
1.292     brouard  13082:   strcpy(pplotcmd,plotcmd);
1.227     brouard  13083:   
1.126     brouard  13084:   if((outcmd=system(plotcmd)) != 0){
1.292     brouard  13085:     printf("Error in gnuplot, command might not be in your path: '%s', err=%d\n", plotcmd, outcmd);
1.154     brouard  13086:     printf("\n Trying if gnuplot resides on the same directory that IMaCh\n");
1.152     brouard  13087:     sprintf(plotcmd,"%sgnuplot %s", pathimach, optionfilegnuplot);
1.292     brouard  13088:     if((outcmd=system(plotcmd)) != 0){
1.153     brouard  13089:       printf("\n Still a problem with gnuplot command %s, err=%d\n", plotcmd, outcmd);
1.292     brouard  13090:       strcpy(plotcmd,pplotcmd);
                   13091:     }
1.126     brouard  13092:   }
1.158     brouard  13093:   printf(" Successful, please wait...");
1.126     brouard  13094:   while (z[0] != 'q') {
                   13095:     /* chdir(path); */
1.154     brouard  13096:     printf("\nType e to edit results with your browser, g to graph again and q for exit: ");
1.126     brouard  13097:     scanf("%s",z);
                   13098: /*     if (z[0] == 'c') system("./imach"); */
                   13099:     if (z[0] == 'e') {
1.158     brouard  13100: #ifdef __APPLE__
1.152     brouard  13101:       sprintf(pplotcmd, "open %s", optionfilehtm);
1.157     brouard  13102: #elif __linux
                   13103:       sprintf(pplotcmd, "xdg-open %s", optionfilehtm);
1.153     brouard  13104: #else
1.152     brouard  13105:       sprintf(pplotcmd, "%s", optionfilehtm);
1.153     brouard  13106: #endif
                   13107:       printf("Starting browser with: %s",pplotcmd);fflush(stdout);
                   13108:       system(pplotcmd);
1.126     brouard  13109:     }
                   13110:     else if (z[0] == 'g') system(plotcmd);
                   13111:     else if (z[0] == 'q') exit(0);
                   13112:   }
1.227     brouard  13113: end:
1.126     brouard  13114:   while (z[0] != 'q') {
1.195     brouard  13115:     printf("\nType  q for exiting: "); fflush(stdout);
1.126     brouard  13116:     scanf("%s",z);
                   13117:   }
1.283     brouard  13118:   printf("End\n");
1.282     brouard  13119:   exit(0);
1.126     brouard  13120: }

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