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

1.307   ! brouard     1: /* $Id: imach.c,v 1.306 2021/02/20 15:44:02 brouard Exp $
1.126     brouard     2:   $State: Exp $
1.163     brouard     3:   $Log: imach.c,v $
1.307   ! brouard     4:   Revision 1.306  2021/02/20 15:44:02  brouard
        !             5:   Summary: Version 0.99r21
        !             6: 
        !             7:   * imach.c (Module): Fix bug on quitting after result lines!
        !             8:   (Module): Version 0.99r21
        !             9: 
1.306     brouard    10:   Revision 1.305  2021/02/20 15:28:30  brouard
                     11:   * imach.c (Module): Fix bug on quitting after result lines!
                     12: 
1.305     brouard    13:   Revision 1.304  2021/02/12 11:34:20  brouard
                     14:   * imach.c (Module): The use of a Windows BOM (huge) file is now an error
                     15: 
1.304     brouard    16:   Revision 1.303  2021/02/11 19:50:15  brouard
                     17:   *  (Module): imach.c Someone entered 'results:' instead of 'result:'. Now it is an error which is printed.
                     18: 
1.303     brouard    19:   Revision 1.302  2020/02/22 21:00:05  brouard
                     20:   *  (Module): imach.c Update mle=-3 (for computing Life expectancy
                     21:   and life table from the data without any state)
                     22: 
1.302     brouard    23:   Revision 1.301  2019/06/04 13:51:20  brouard
                     24:   Summary: Error in 'r'parameter file backcast yearsbproj instead of yearsfproj
                     25: 
1.301     brouard    26:   Revision 1.300  2019/05/22 19:09:45  brouard
                     27:   Summary: version 0.99r19 of May 2019
                     28: 
1.300     brouard    29:   Revision 1.299  2019/05/22 18:37:08  brouard
                     30:   Summary: Cleaned 0.99r19
                     31: 
1.299     brouard    32:   Revision 1.298  2019/05/22 18:19:56  brouard
                     33:   *** empty log message ***
                     34: 
1.298     brouard    35:   Revision 1.297  2019/05/22 17:56:10  brouard
                     36:   Summary: Fix bug by moving date2dmy and nhstepm which gaefin=-1
                     37: 
1.297     brouard    38:   Revision 1.296  2019/05/20 13:03:18  brouard
                     39:   Summary: Projection syntax simplified
                     40: 
                     41: 
                     42:   We can now start projections, forward or backward, from the mean date
                     43:   of inteviews up to or down to a number of years of projection:
                     44:   prevforecast=1 yearsfproj=15.3 mobil_average=0
                     45:   or
                     46:   prevforecast=1 starting-proj-date=1/1/2007 final-proj-date=12/31/2017 mobil_average=0
                     47:   or
                     48:   prevbackcast=1 yearsbproj=12.3 mobil_average=1
                     49:   or
                     50:   prevbackcast=1 starting-back-date=1/10/1999 final-back-date=1/1/1985 mobil_average=1
                     51: 
1.296     brouard    52:   Revision 1.295  2019/05/18 09:52:50  brouard
                     53:   Summary: doxygen tex bug
                     54: 
1.295     brouard    55:   Revision 1.294  2019/05/16 14:54:33  brouard
                     56:   Summary: There was some wrong lines added
                     57: 
1.294     brouard    58:   Revision 1.293  2019/05/09 15:17:34  brouard
                     59:   *** empty log message ***
                     60: 
1.293     brouard    61:   Revision 1.292  2019/05/09 14:17:20  brouard
                     62:   Summary: Some updates
                     63: 
1.292     brouard    64:   Revision 1.291  2019/05/09 13:44:18  brouard
                     65:   Summary: Before ncovmax
                     66: 
1.291     brouard    67:   Revision 1.290  2019/05/09 13:39:37  brouard
                     68:   Summary: 0.99r18 unlimited number of individuals
                     69: 
                     70:   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.
                     71: 
1.290     brouard    72:   Revision 1.289  2018/12/13 09:16:26  brouard
                     73:   Summary: Bug for young ages (<-30) will be in r17
                     74: 
1.289     brouard    75:   Revision 1.288  2018/05/02 20:58:27  brouard
                     76:   Summary: Some bugs fixed
                     77: 
1.288     brouard    78:   Revision 1.287  2018/05/01 17:57:25  brouard
                     79:   Summary: Bug fixed by providing frequencies only for non missing covariates
                     80: 
1.287     brouard    81:   Revision 1.286  2018/04/27 14:27:04  brouard
                     82:   Summary: some minor bugs
                     83: 
1.286     brouard    84:   Revision 1.285  2018/04/21 21:02:16  brouard
                     85:   Summary: Some bugs fixed, valgrind tested
                     86: 
1.285     brouard    87:   Revision 1.284  2018/04/20 05:22:13  brouard
                     88:   Summary: Computing mean and stdeviation of fixed quantitative variables
                     89: 
1.284     brouard    90:   Revision 1.283  2018/04/19 14:49:16  brouard
                     91:   Summary: Some minor bugs fixed
                     92: 
1.283     brouard    93:   Revision 1.282  2018/02/27 22:50:02  brouard
                     94:   *** empty log message ***
                     95: 
1.282     brouard    96:   Revision 1.281  2018/02/27 19:25:23  brouard
                     97:   Summary: Adding second argument for quitting
                     98: 
1.281     brouard    99:   Revision 1.280  2018/02/21 07:58:13  brouard
                    100:   Summary: 0.99r15
                    101: 
                    102:   New Makefile with recent VirtualBox 5.26. Bug in sqrt negatve in imach.c
                    103: 
1.280     brouard   104:   Revision 1.279  2017/07/20 13:35:01  brouard
                    105:   Summary: temporary working
                    106: 
1.279     brouard   107:   Revision 1.278  2017/07/19 14:09:02  brouard
                    108:   Summary: Bug for mobil_average=0 and prevforecast fixed(?)
                    109: 
1.278     brouard   110:   Revision 1.277  2017/07/17 08:53:49  brouard
                    111:   Summary: BOM files can be read now
                    112: 
1.277     brouard   113:   Revision 1.276  2017/06/30 15:48:31  brouard
                    114:   Summary: Graphs improvements
                    115: 
1.276     brouard   116:   Revision 1.275  2017/06/30 13:39:33  brouard
                    117:   Summary: Saito's color
                    118: 
1.275     brouard   119:   Revision 1.274  2017/06/29 09:47:08  brouard
                    120:   Summary: Version 0.99r14
                    121: 
1.274     brouard   122:   Revision 1.273  2017/06/27 11:06:02  brouard
                    123:   Summary: More documentation on projections
                    124: 
1.273     brouard   125:   Revision 1.272  2017/06/27 10:22:40  brouard
                    126:   Summary: Color of backprojection changed from 6 to 5(yellow)
                    127: 
1.272     brouard   128:   Revision 1.271  2017/06/27 10:17:50  brouard
                    129:   Summary: Some bug with rint
                    130: 
1.271     brouard   131:   Revision 1.270  2017/05/24 05:45:29  brouard
                    132:   *** empty log message ***
                    133: 
1.270     brouard   134:   Revision 1.269  2017/05/23 08:39:25  brouard
                    135:   Summary: Code into subroutine, cleanings
                    136: 
1.269     brouard   137:   Revision 1.268  2017/05/18 20:09:32  brouard
                    138:   Summary: backprojection and confidence intervals of backprevalence
                    139: 
1.268     brouard   140:   Revision 1.267  2017/05/13 10:25:05  brouard
                    141:   Summary: temporary save for backprojection
                    142: 
1.267     brouard   143:   Revision 1.266  2017/05/13 07:26:12  brouard
                    144:   Summary: Version 0.99r13 (improvements and bugs fixed)
                    145: 
1.266     brouard   146:   Revision 1.265  2017/04/26 16:22:11  brouard
                    147:   Summary: imach 0.99r13 Some bugs fixed
                    148: 
1.265     brouard   149:   Revision 1.264  2017/04/26 06:01:29  brouard
                    150:   Summary: Labels in graphs
                    151: 
1.264     brouard   152:   Revision 1.263  2017/04/24 15:23:15  brouard
                    153:   Summary: to save
                    154: 
1.263     brouard   155:   Revision 1.262  2017/04/18 16:48:12  brouard
                    156:   *** empty log message ***
                    157: 
1.262     brouard   158:   Revision 1.261  2017/04/05 10:14:09  brouard
                    159:   Summary: Bug in E_ as well as in T_ fixed nres-1 vs k1-1
                    160: 
1.261     brouard   161:   Revision 1.260  2017/04/04 17:46:59  brouard
                    162:   Summary: Gnuplot indexations fixed (humm)
                    163: 
1.260     brouard   164:   Revision 1.259  2017/04/04 13:01:16  brouard
                    165:   Summary: Some errors to warnings only if date of death is unknown but status is death we could set to pi3
                    166: 
1.259     brouard   167:   Revision 1.258  2017/04/03 10:17:47  brouard
                    168:   Summary: Version 0.99r12
                    169: 
                    170:   Some cleanings, conformed with updated documentation.
                    171: 
1.258     brouard   172:   Revision 1.257  2017/03/29 16:53:30  brouard
                    173:   Summary: Temp
                    174: 
1.257     brouard   175:   Revision 1.256  2017/03/27 05:50:23  brouard
                    176:   Summary: Temporary
                    177: 
1.256     brouard   178:   Revision 1.255  2017/03/08 16:02:28  brouard
                    179:   Summary: IMaCh version 0.99r10 bugs in gnuplot fixed
                    180: 
1.255     brouard   181:   Revision 1.254  2017/03/08 07:13:00  brouard
                    182:   Summary: Fixing data parameter line
                    183: 
1.254     brouard   184:   Revision 1.253  2016/12/15 11:59:41  brouard
                    185:   Summary: 0.99 in progress
                    186: 
1.253     brouard   187:   Revision 1.252  2016/09/15 21:15:37  brouard
                    188:   *** empty log message ***
                    189: 
1.252     brouard   190:   Revision 1.251  2016/09/15 15:01:13  brouard
                    191:   Summary: not working
                    192: 
1.251     brouard   193:   Revision 1.250  2016/09/08 16:07:27  brouard
                    194:   Summary: continue
                    195: 
1.250     brouard   196:   Revision 1.249  2016/09/07 17:14:18  brouard
                    197:   Summary: Starting values from frequencies
                    198: 
1.249     brouard   199:   Revision 1.248  2016/09/07 14:10:18  brouard
                    200:   *** empty log message ***
                    201: 
1.248     brouard   202:   Revision 1.247  2016/09/02 11:11:21  brouard
                    203:   *** empty log message ***
                    204: 
1.247     brouard   205:   Revision 1.246  2016/09/02 08:49:22  brouard
                    206:   *** empty log message ***
                    207: 
1.246     brouard   208:   Revision 1.245  2016/09/02 07:25:01  brouard
                    209:   *** empty log message ***
                    210: 
1.245     brouard   211:   Revision 1.244  2016/09/02 07:17:34  brouard
                    212:   *** empty log message ***
                    213: 
1.244     brouard   214:   Revision 1.243  2016/09/02 06:45:35  brouard
                    215:   *** empty log message ***
                    216: 
1.243     brouard   217:   Revision 1.242  2016/08/30 15:01:20  brouard
                    218:   Summary: Fixing a lots
                    219: 
1.242     brouard   220:   Revision 1.241  2016/08/29 17:17:25  brouard
                    221:   Summary: gnuplot problem in Back projection to fix
                    222: 
1.241     brouard   223:   Revision 1.240  2016/08/29 07:53:18  brouard
                    224:   Summary: Better
                    225: 
1.240     brouard   226:   Revision 1.239  2016/08/26 15:51:03  brouard
                    227:   Summary: Improvement in Powell output in order to copy and paste
                    228: 
                    229:   Author:
                    230: 
1.239     brouard   231:   Revision 1.238  2016/08/26 14:23:35  brouard
                    232:   Summary: Starting tests of 0.99
                    233: 
1.238     brouard   234:   Revision 1.237  2016/08/26 09:20:19  brouard
                    235:   Summary: to valgrind
                    236: 
1.237     brouard   237:   Revision 1.236  2016/08/25 10:50:18  brouard
                    238:   *** empty log message ***
                    239: 
1.236     brouard   240:   Revision 1.235  2016/08/25 06:59:23  brouard
                    241:   *** empty log message ***
                    242: 
1.235     brouard   243:   Revision 1.234  2016/08/23 16:51:20  brouard
                    244:   *** empty log message ***
                    245: 
1.234     brouard   246:   Revision 1.233  2016/08/23 07:40:50  brouard
                    247:   Summary: not working
                    248: 
1.233     brouard   249:   Revision 1.232  2016/08/22 14:20:21  brouard
                    250:   Summary: not working
                    251: 
1.232     brouard   252:   Revision 1.231  2016/08/22 07:17:15  brouard
                    253:   Summary: not working
                    254: 
1.231     brouard   255:   Revision 1.230  2016/08/22 06:55:53  brouard
                    256:   Summary: Not working
                    257: 
1.230     brouard   258:   Revision 1.229  2016/07/23 09:45:53  brouard
                    259:   Summary: Completing for func too
                    260: 
1.229     brouard   261:   Revision 1.228  2016/07/22 17:45:30  brouard
                    262:   Summary: Fixing some arrays, still debugging
                    263: 
1.227     brouard   264:   Revision 1.226  2016/07/12 18:42:34  brouard
                    265:   Summary: temp
                    266: 
1.226     brouard   267:   Revision 1.225  2016/07/12 08:40:03  brouard
                    268:   Summary: saving but not running
                    269: 
1.225     brouard   270:   Revision 1.224  2016/07/01 13:16:01  brouard
                    271:   Summary: Fixes
                    272: 
1.224     brouard   273:   Revision 1.223  2016/02/19 09:23:35  brouard
                    274:   Summary: temporary
                    275: 
1.223     brouard   276:   Revision 1.222  2016/02/17 08:14:50  brouard
                    277:   Summary: Probably last 0.98 stable version 0.98r6
                    278: 
1.222     brouard   279:   Revision 1.221  2016/02/15 23:35:36  brouard
                    280:   Summary: minor bug
                    281: 
1.220     brouard   282:   Revision 1.219  2016/02/15 00:48:12  brouard
                    283:   *** empty log message ***
                    284: 
1.219     brouard   285:   Revision 1.218  2016/02/12 11:29:23  brouard
                    286:   Summary: 0.99 Back projections
                    287: 
1.218     brouard   288:   Revision 1.217  2015/12/23 17:18:31  brouard
                    289:   Summary: Experimental backcast
                    290: 
1.217     brouard   291:   Revision 1.216  2015/12/18 17:32:11  brouard
                    292:   Summary: 0.98r4 Warning and status=-2
                    293: 
                    294:   Version 0.98r4 is now:
                    295:    - displaying an error when status is -1, date of interview unknown and date of death known;
                    296:    - permitting a status -2 when the vital status is unknown at a known date of right truncation.
                    297:   Older changes concerning s=-2, dating from 2005 have been supersed.
                    298: 
1.216     brouard   299:   Revision 1.215  2015/12/16 08:52:24  brouard
                    300:   Summary: 0.98r4 working
                    301: 
1.215     brouard   302:   Revision 1.214  2015/12/16 06:57:54  brouard
                    303:   Summary: temporary not working
                    304: 
1.214     brouard   305:   Revision 1.213  2015/12/11 18:22:17  brouard
                    306:   Summary: 0.98r4
                    307: 
1.213     brouard   308:   Revision 1.212  2015/11/21 12:47:24  brouard
                    309:   Summary: minor typo
                    310: 
1.212     brouard   311:   Revision 1.211  2015/11/21 12:41:11  brouard
                    312:   Summary: 0.98r3 with some graph of projected cross-sectional
                    313: 
                    314:   Author: Nicolas Brouard
                    315: 
1.211     brouard   316:   Revision 1.210  2015/11/18 17:41:20  brouard
1.252     brouard   317:   Summary: Start working on projected prevalences  Revision 1.209  2015/11/17 22:12:03  brouard
1.210     brouard   318:   Summary: Adding ftolpl parameter
                    319:   Author: N Brouard
                    320: 
                    321:   We had difficulties to get smoothed confidence intervals. It was due
                    322:   to the period prevalence which wasn't computed accurately. The inner
                    323:   parameter ftolpl is now an outer parameter of the .imach parameter
                    324:   file after estepm. If ftolpl is small 1.e-4 and estepm too,
                    325:   computation are long.
                    326: 
1.209     brouard   327:   Revision 1.208  2015/11/17 14:31:57  brouard
                    328:   Summary: temporary
                    329: 
1.208     brouard   330:   Revision 1.207  2015/10/27 17:36:57  brouard
                    331:   *** empty log message ***
                    332: 
1.207     brouard   333:   Revision 1.206  2015/10/24 07:14:11  brouard
                    334:   *** empty log message ***
                    335: 
1.206     brouard   336:   Revision 1.205  2015/10/23 15:50:53  brouard
                    337:   Summary: 0.98r3 some clarification for graphs on likelihood contributions
                    338: 
1.205     brouard   339:   Revision 1.204  2015/10/01 16:20:26  brouard
                    340:   Summary: Some new graphs of contribution to likelihood
                    341: 
1.204     brouard   342:   Revision 1.203  2015/09/30 17:45:14  brouard
                    343:   Summary: looking at better estimation of the hessian
                    344: 
                    345:   Also a better criteria for convergence to the period prevalence And
                    346:   therefore adding the number of years needed to converge. (The
                    347:   prevalence in any alive state shold sum to one
                    348: 
1.203     brouard   349:   Revision 1.202  2015/09/22 19:45:16  brouard
                    350:   Summary: Adding some overall graph on contribution to likelihood. Might change
                    351: 
1.202     brouard   352:   Revision 1.201  2015/09/15 17:34:58  brouard
                    353:   Summary: 0.98r0
                    354: 
                    355:   - Some new graphs like suvival functions
                    356:   - Some bugs fixed like model=1+age+V2.
                    357: 
1.201     brouard   358:   Revision 1.200  2015/09/09 16:53:55  brouard
                    359:   Summary: Big bug thanks to Flavia
                    360: 
                    361:   Even model=1+age+V2. did not work anymore
                    362: 
1.200     brouard   363:   Revision 1.199  2015/09/07 14:09:23  brouard
                    364:   Summary: 0.98q6 changing default small png format for graph to vectorized svg.
                    365: 
1.199     brouard   366:   Revision 1.198  2015/09/03 07:14:39  brouard
                    367:   Summary: 0.98q5 Flavia
                    368: 
1.198     brouard   369:   Revision 1.197  2015/09/01 18:24:39  brouard
                    370:   *** empty log message ***
                    371: 
1.197     brouard   372:   Revision 1.196  2015/08/18 23:17:52  brouard
                    373:   Summary: 0.98q5
                    374: 
1.196     brouard   375:   Revision 1.195  2015/08/18 16:28:39  brouard
                    376:   Summary: Adding a hack for testing purpose
                    377: 
                    378:   After reading the title, ftol and model lines, if the comment line has
                    379:   a q, starting with #q, the answer at the end of the run is quit. It
                    380:   permits to run test files in batch with ctest. The former workaround was
                    381:   $ echo q | imach foo.imach
                    382: 
1.195     brouard   383:   Revision 1.194  2015/08/18 13:32:00  brouard
                    384:   Summary:  Adding error when the covariance matrix doesn't contain the exact number of lines required by the model line.
                    385: 
1.194     brouard   386:   Revision 1.193  2015/08/04 07:17:42  brouard
                    387:   Summary: 0.98q4
                    388: 
1.193     brouard   389:   Revision 1.192  2015/07/16 16:49:02  brouard
                    390:   Summary: Fixing some outputs
                    391: 
1.192     brouard   392:   Revision 1.191  2015/07/14 10:00:33  brouard
                    393:   Summary: Some fixes
                    394: 
1.191     brouard   395:   Revision 1.190  2015/05/05 08:51:13  brouard
                    396:   Summary: Adding digits in output parameters (7 digits instead of 6)
                    397: 
                    398:   Fix 1+age+.
                    399: 
1.190     brouard   400:   Revision 1.189  2015/04/30 14:45:16  brouard
                    401:   Summary: 0.98q2
                    402: 
1.189     brouard   403:   Revision 1.188  2015/04/30 08:27:53  brouard
                    404:   *** empty log message ***
                    405: 
1.188     brouard   406:   Revision 1.187  2015/04/29 09:11:15  brouard
                    407:   *** empty log message ***
                    408: 
1.187     brouard   409:   Revision 1.186  2015/04/23 12:01:52  brouard
                    410:   Summary: V1*age is working now, version 0.98q1
                    411: 
                    412:   Some codes had been disabled in order to simplify and Vn*age was
                    413:   working in the optimization phase, ie, giving correct MLE parameters,
                    414:   but, as usual, outputs were not correct and program core dumped.
                    415: 
1.186     brouard   416:   Revision 1.185  2015/03/11 13:26:42  brouard
                    417:   Summary: Inclusion of compile and links command line for Intel Compiler
                    418: 
1.185     brouard   419:   Revision 1.184  2015/03/11 11:52:39  brouard
                    420:   Summary: Back from Windows 8. Intel Compiler
                    421: 
1.184     brouard   422:   Revision 1.183  2015/03/10 20:34:32  brouard
                    423:   Summary: 0.98q0, trying with directest, mnbrak fixed
                    424: 
                    425:   We use directest instead of original Powell test; probably no
                    426:   incidence on the results, but better justifications;
                    427:   We fixed Numerical Recipes mnbrak routine which was wrong and gave
                    428:   wrong results.
                    429: 
1.183     brouard   430:   Revision 1.182  2015/02/12 08:19:57  brouard
                    431:   Summary: Trying to keep directest which seems simpler and more general
                    432:   Author: Nicolas Brouard
                    433: 
1.182     brouard   434:   Revision 1.181  2015/02/11 23:22:24  brouard
                    435:   Summary: Comments on Powell added
                    436: 
                    437:   Author:
                    438: 
1.181     brouard   439:   Revision 1.180  2015/02/11 17:33:45  brouard
                    440:   Summary: Finishing move from main to function (hpijx and prevalence_limit)
                    441: 
1.180     brouard   442:   Revision 1.179  2015/01/04 09:57:06  brouard
                    443:   Summary: back to OS/X
                    444: 
1.179     brouard   445:   Revision 1.178  2015/01/04 09:35:48  brouard
                    446:   *** empty log message ***
                    447: 
1.178     brouard   448:   Revision 1.177  2015/01/03 18:40:56  brouard
                    449:   Summary: Still testing ilc32 on OSX
                    450: 
1.177     brouard   451:   Revision 1.176  2015/01/03 16:45:04  brouard
                    452:   *** empty log message ***
                    453: 
1.176     brouard   454:   Revision 1.175  2015/01/03 16:33:42  brouard
                    455:   *** empty log message ***
                    456: 
1.175     brouard   457:   Revision 1.174  2015/01/03 16:15:49  brouard
                    458:   Summary: Still in cross-compilation
                    459: 
1.174     brouard   460:   Revision 1.173  2015/01/03 12:06:26  brouard
                    461:   Summary: trying to detect cross-compilation
                    462: 
1.173     brouard   463:   Revision 1.172  2014/12/27 12:07:47  brouard
                    464:   Summary: Back from Visual Studio and Intel, options for compiling for Windows XP
                    465: 
1.172     brouard   466:   Revision 1.171  2014/12/23 13:26:59  brouard
                    467:   Summary: Back from Visual C
                    468: 
                    469:   Still problem with utsname.h on Windows
                    470: 
1.171     brouard   471:   Revision 1.170  2014/12/23 11:17:12  brouard
                    472:   Summary: Cleaning some \%% back to %%
                    473: 
                    474:   The escape was mandatory for a specific compiler (which one?), but too many warnings.
                    475: 
1.170     brouard   476:   Revision 1.169  2014/12/22 23:08:31  brouard
                    477:   Summary: 0.98p
                    478: 
                    479:   Outputs some informations on compiler used, OS etc. Testing on different platforms.
                    480: 
1.169     brouard   481:   Revision 1.168  2014/12/22 15:17:42  brouard
1.170     brouard   482:   Summary: update
1.169     brouard   483: 
1.168     brouard   484:   Revision 1.167  2014/12/22 13:50:56  brouard
                    485:   Summary: Testing uname and compiler version and if compiled 32 or 64
                    486: 
                    487:   Testing on Linux 64
                    488: 
1.167     brouard   489:   Revision 1.166  2014/12/22 11:40:47  brouard
                    490:   *** empty log message ***
                    491: 
1.166     brouard   492:   Revision 1.165  2014/12/16 11:20:36  brouard
                    493:   Summary: After compiling on Visual C
                    494: 
                    495:   * imach.c (Module): Merging 1.61 to 1.162
                    496: 
1.165     brouard   497:   Revision 1.164  2014/12/16 10:52:11  brouard
                    498:   Summary: Merging with Visual C after suppressing some warnings for unused variables. Also fixing Saito's bug 0.98Xn
                    499: 
                    500:   * imach.c (Module): Merging 1.61 to 1.162
                    501: 
1.164     brouard   502:   Revision 1.163  2014/12/16 10:30:11  brouard
                    503:   * imach.c (Module): Merging 1.61 to 1.162
                    504: 
1.163     brouard   505:   Revision 1.162  2014/09/25 11:43:39  brouard
                    506:   Summary: temporary backup 0.99!
                    507: 
1.162     brouard   508:   Revision 1.1  2014/09/16 11:06:58  brouard
                    509:   Summary: With some code (wrong) for nlopt
                    510: 
                    511:   Author:
                    512: 
                    513:   Revision 1.161  2014/09/15 20:41:41  brouard
                    514:   Summary: Problem with macro SQR on Intel compiler
                    515: 
1.161     brouard   516:   Revision 1.160  2014/09/02 09:24:05  brouard
                    517:   *** empty log message ***
                    518: 
1.160     brouard   519:   Revision 1.159  2014/09/01 10:34:10  brouard
                    520:   Summary: WIN32
                    521:   Author: Brouard
                    522: 
1.159     brouard   523:   Revision 1.158  2014/08/27 17:11:51  brouard
                    524:   *** empty log message ***
                    525: 
1.158     brouard   526:   Revision 1.157  2014/08/27 16:26:55  brouard
                    527:   Summary: Preparing windows Visual studio version
                    528:   Author: Brouard
                    529: 
                    530:   In order to compile on Visual studio, time.h is now correct and time_t
                    531:   and tm struct should be used. difftime should be used but sometimes I
                    532:   just make the differences in raw time format (time(&now).
                    533:   Trying to suppress #ifdef LINUX
                    534:   Add xdg-open for __linux in order to open default browser.
                    535: 
1.157     brouard   536:   Revision 1.156  2014/08/25 20:10:10  brouard
                    537:   *** empty log message ***
                    538: 
1.156     brouard   539:   Revision 1.155  2014/08/25 18:32:34  brouard
                    540:   Summary: New compile, minor changes
                    541:   Author: Brouard
                    542: 
1.155     brouard   543:   Revision 1.154  2014/06/20 17:32:08  brouard
                    544:   Summary: Outputs now all graphs of convergence to period prevalence
                    545: 
1.154     brouard   546:   Revision 1.153  2014/06/20 16:45:46  brouard
                    547:   Summary: If 3 live state, convergence to period prevalence on same graph
                    548:   Author: Brouard
                    549: 
1.153     brouard   550:   Revision 1.152  2014/06/18 17:54:09  brouard
                    551:   Summary: open browser, use gnuplot on same dir than imach if not found in the path
                    552: 
1.152     brouard   553:   Revision 1.151  2014/06/18 16:43:30  brouard
                    554:   *** empty log message ***
                    555: 
1.151     brouard   556:   Revision 1.150  2014/06/18 16:42:35  brouard
                    557:   Summary: If gnuplot is not in the path try on same directory than imach binary (OSX)
                    558:   Author: brouard
                    559: 
1.150     brouard   560:   Revision 1.149  2014/06/18 15:51:14  brouard
                    561:   Summary: Some fixes in parameter files errors
                    562:   Author: Nicolas Brouard
                    563: 
1.149     brouard   564:   Revision 1.148  2014/06/17 17:38:48  brouard
                    565:   Summary: Nothing new
                    566:   Author: Brouard
                    567: 
                    568:   Just a new packaging for OS/X version 0.98nS
                    569: 
1.148     brouard   570:   Revision 1.147  2014/06/16 10:33:11  brouard
                    571:   *** empty log message ***
                    572: 
1.147     brouard   573:   Revision 1.146  2014/06/16 10:20:28  brouard
                    574:   Summary: Merge
                    575:   Author: Brouard
                    576: 
                    577:   Merge, before building revised version.
                    578: 
1.146     brouard   579:   Revision 1.145  2014/06/10 21:23:15  brouard
                    580:   Summary: Debugging with valgrind
                    581:   Author: Nicolas Brouard
                    582: 
                    583:   Lot of changes in order to output the results with some covariates
                    584:   After the Edimburgh REVES conference 2014, it seems mandatory to
                    585:   improve the code.
                    586:   No more memory valgrind error but a lot has to be done in order to
                    587:   continue the work of splitting the code into subroutines.
                    588:   Also, decodemodel has been improved. Tricode is still not
                    589:   optimal. nbcode should be improved. Documentation has been added in
                    590:   the source code.
                    591: 
1.144     brouard   592:   Revision 1.143  2014/01/26 09:45:38  brouard
                    593:   Summary: Version 0.98nR (to be improved, but gives same optimization results as 0.98k. Nice, promising
                    594: 
                    595:   * imach.c (Module): Trying to merge old staffs together while being at Tokyo. Not tested...
                    596:   (Module): Version 0.98nR Running ok, but output format still only works for three covariates.
                    597: 
1.143     brouard   598:   Revision 1.142  2014/01/26 03:57:36  brouard
                    599:   Summary: gnuplot changed plot w l 1 has to be changed to plot w l lt 2
                    600: 
                    601:   * imach.c (Module): Trying to merge old staffs together while being at Tokyo. Not tested...
                    602: 
1.142     brouard   603:   Revision 1.141  2014/01/26 02:42:01  brouard
                    604:   * imach.c (Module): Trying to merge old staffs together while being at Tokyo. Not tested...
                    605: 
1.141     brouard   606:   Revision 1.140  2011/09/02 10:37:54  brouard
                    607:   Summary: times.h is ok with mingw32 now.
                    608: 
1.140     brouard   609:   Revision 1.139  2010/06/14 07:50:17  brouard
                    610:   After the theft of my laptop, I probably lost some lines of codes which were not uploaded to the CVS tree.
                    611:   I remember having already fixed agemin agemax which are pointers now but not cvs saved.
                    612: 
1.139     brouard   613:   Revision 1.138  2010/04/30 18:19:40  brouard
                    614:   *** empty log message ***
                    615: 
1.138     brouard   616:   Revision 1.137  2010/04/29 18:11:38  brouard
                    617:   (Module): Checking covariates for more complex models
                    618:   than V1+V2. A lot of change to be done. Unstable.
                    619: 
1.137     brouard   620:   Revision 1.136  2010/04/26 20:30:53  brouard
                    621:   (Module): merging some libgsl code. Fixing computation
                    622:   of likelione (using inter/intrapolation if mle = 0) in order to
                    623:   get same likelihood as if mle=1.
                    624:   Some cleaning of code and comments added.
                    625: 
1.136     brouard   626:   Revision 1.135  2009/10/29 15:33:14  brouard
                    627:   (Module): Now imach stops if date of birth, at least year of birth, is not given. Some cleaning of the code.
                    628: 
1.135     brouard   629:   Revision 1.134  2009/10/29 13:18:53  brouard
                    630:   (Module): Now imach stops if date of birth, at least year of birth, is not given. Some cleaning of the code.
                    631: 
1.134     brouard   632:   Revision 1.133  2009/07/06 10:21:25  brouard
                    633:   just nforces
                    634: 
1.133     brouard   635:   Revision 1.132  2009/07/06 08:22:05  brouard
                    636:   Many tings
                    637: 
1.132     brouard   638:   Revision 1.131  2009/06/20 16:22:47  brouard
                    639:   Some dimensions resccaled
                    640: 
1.131     brouard   641:   Revision 1.130  2009/05/26 06:44:34  brouard
                    642:   (Module): Max Covariate is now set to 20 instead of 8. A
                    643:   lot of cleaning with variables initialized to 0. Trying to make
                    644:   V2+V3*age+V1+V4 strb=V3*age+V1+V4 working better.
                    645: 
1.130     brouard   646:   Revision 1.129  2007/08/31 13:49:27  lievre
                    647:   Modification of the way of exiting when the covariate is not binary in order to see on the window the error message before exiting
                    648: 
1.129     lievre    649:   Revision 1.128  2006/06/30 13:02:05  brouard
                    650:   (Module): Clarifications on computing e.j
                    651: 
1.128     brouard   652:   Revision 1.127  2006/04/28 18:11:50  brouard
                    653:   (Module): Yes the sum of survivors was wrong since
                    654:   imach-114 because nhstepm was no more computed in the age
                    655:   loop. Now we define nhstepma in the age loop.
                    656:   (Module): In order to speed up (in case of numerous covariates) we
                    657:   compute health expectancies (without variances) in a first step
                    658:   and then all the health expectancies with variances or standard
                    659:   deviation (needs data from the Hessian matrices) which slows the
                    660:   computation.
                    661:   In the future we should be able to stop the program is only health
                    662:   expectancies and graph are needed without standard deviations.
                    663: 
1.127     brouard   664:   Revision 1.126  2006/04/28 17:23:28  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:   Version 0.98h
                    669: 
1.126     brouard   670:   Revision 1.125  2006/04/04 15:20:31  lievre
                    671:   Errors in calculation of health expectancies. Age was not initialized.
                    672:   Forecasting file added.
                    673: 
                    674:   Revision 1.124  2006/03/22 17:13:53  lievre
                    675:   Parameters are printed with %lf instead of %f (more numbers after the comma).
                    676:   The log-likelihood is printed in the log file
                    677: 
                    678:   Revision 1.123  2006/03/20 10:52:43  brouard
                    679:   * imach.c (Module): <title> changed, corresponds to .htm file
                    680:   name. <head> headers where missing.
                    681: 
                    682:   * imach.c (Module): Weights can have a decimal point as for
                    683:   English (a comma might work with a correct LC_NUMERIC environment,
                    684:   otherwise the weight is truncated).
                    685:   Modification of warning when the covariates values are not 0 or
                    686:   1.
                    687:   Version 0.98g
                    688: 
                    689:   Revision 1.122  2006/03/20 09:45:41  brouard
                    690:   (Module): Weights can have a decimal point as for
                    691:   English (a comma might work with a correct LC_NUMERIC environment,
                    692:   otherwise the weight is truncated).
                    693:   Modification of warning when the covariates values are not 0 or
                    694:   1.
                    695:   Version 0.98g
                    696: 
                    697:   Revision 1.121  2006/03/16 17:45:01  lievre
                    698:   * imach.c (Module): Comments concerning covariates added
                    699: 
                    700:   * imach.c (Module): refinements in the computation of lli if
                    701:   status=-2 in order to have more reliable computation if stepm is
                    702:   not 1 month. Version 0.98f
                    703: 
                    704:   Revision 1.120  2006/03/16 15:10:38  lievre
                    705:   (Module): refinements in the computation of lli if
                    706:   status=-2 in order to have more reliable computation if stepm is
                    707:   not 1 month. Version 0.98f
                    708: 
                    709:   Revision 1.119  2006/03/15 17:42:26  brouard
                    710:   (Module): Bug if status = -2, the loglikelihood was
                    711:   computed as likelihood omitting the logarithm. Version O.98e
                    712: 
                    713:   Revision 1.118  2006/03/14 18:20:07  brouard
                    714:   (Module): varevsij Comments added explaining the second
                    715:   table of variances if popbased=1 .
                    716:   (Module): Covariances of eij, ekl added, graphs fixed, new html link.
                    717:   (Module): Function pstamp added
                    718:   (Module): Version 0.98d
                    719: 
                    720:   Revision 1.117  2006/03/14 17:16:22  brouard
                    721:   (Module): varevsij Comments added explaining the second
                    722:   table of variances if popbased=1 .
                    723:   (Module): Covariances of eij, ekl added, graphs fixed, new html link.
                    724:   (Module): Function pstamp added
                    725:   (Module): Version 0.98d
                    726: 
                    727:   Revision 1.116  2006/03/06 10:29:27  brouard
                    728:   (Module): Variance-covariance wrong links and
                    729:   varian-covariance of ej. is needed (Saito).
                    730: 
                    731:   Revision 1.115  2006/02/27 12:17:45  brouard
                    732:   (Module): One freematrix added in mlikeli! 0.98c
                    733: 
                    734:   Revision 1.114  2006/02/26 12:57:58  brouard
                    735:   (Module): Some improvements in processing parameter
                    736:   filename with strsep.
                    737: 
                    738:   Revision 1.113  2006/02/24 14:20:24  brouard
                    739:   (Module): Memory leaks checks with valgrind and:
                    740:   datafile was not closed, some imatrix were not freed and on matrix
                    741:   allocation too.
                    742: 
                    743:   Revision 1.112  2006/01/30 09:55:26  brouard
                    744:   (Module): Back to gnuplot.exe instead of wgnuplot.exe
                    745: 
                    746:   Revision 1.111  2006/01/25 20:38:18  brouard
                    747:   (Module): Lots of cleaning and bugs added (Gompertz)
                    748:   (Module): Comments can be added in data file. Missing date values
                    749:   can be a simple dot '.'.
                    750: 
                    751:   Revision 1.110  2006/01/25 00:51:50  brouard
                    752:   (Module): Lots of cleaning and bugs added (Gompertz)
                    753: 
                    754:   Revision 1.109  2006/01/24 19:37:15  brouard
                    755:   (Module): Comments (lines starting with a #) are allowed in data.
                    756: 
                    757:   Revision 1.108  2006/01/19 18:05:42  lievre
                    758:   Gnuplot problem appeared...
                    759:   To be fixed
                    760: 
                    761:   Revision 1.107  2006/01/19 16:20:37  brouard
                    762:   Test existence of gnuplot in imach path
                    763: 
                    764:   Revision 1.106  2006/01/19 13:24:36  brouard
                    765:   Some cleaning and links added in html output
                    766: 
                    767:   Revision 1.105  2006/01/05 20:23:19  lievre
                    768:   *** empty log message ***
                    769: 
                    770:   Revision 1.104  2005/09/30 16:11:43  lievre
                    771:   (Module): sump fixed, loop imx fixed, and simplifications.
                    772:   (Module): If the status is missing at the last wave but we know
                    773:   that the person is alive, then we can code his/her status as -2
                    774:   (instead of missing=-1 in earlier versions) and his/her
                    775:   contributions to the likelihood is 1 - Prob of dying from last
                    776:   health status (= 1-p13= p11+p12 in the easiest case of somebody in
                    777:   the healthy state at last known wave). Version is 0.98
                    778: 
                    779:   Revision 1.103  2005/09/30 15:54:49  lievre
                    780:   (Module): sump fixed, loop imx fixed, and simplifications.
                    781: 
                    782:   Revision 1.102  2004/09/15 17:31:30  brouard
                    783:   Add the possibility to read data file including tab characters.
                    784: 
                    785:   Revision 1.101  2004/09/15 10:38:38  brouard
                    786:   Fix on curr_time
                    787: 
                    788:   Revision 1.100  2004/07/12 18:29:06  brouard
                    789:   Add version for Mac OS X. Just define UNIX in Makefile
                    790: 
                    791:   Revision 1.99  2004/06/05 08:57:40  brouard
                    792:   *** empty log message ***
                    793: 
                    794:   Revision 1.98  2004/05/16 15:05:56  brouard
                    795:   New version 0.97 . First attempt to estimate force of mortality
                    796:   directly from the data i.e. without the need of knowing the health
                    797:   state at each age, but using a Gompertz model: log u =a + b*age .
                    798:   This is the basic analysis of mortality and should be done before any
                    799:   other analysis, in order to test if the mortality estimated from the
                    800:   cross-longitudinal survey is different from the mortality estimated
                    801:   from other sources like vital statistic data.
                    802: 
                    803:   The same imach parameter file can be used but the option for mle should be -3.
                    804: 
1.133     brouard   805:   Agnès, who wrote this part of the code, tried to keep most of the
1.126     brouard   806:   former routines in order to include the new code within the former code.
                    807: 
                    808:   The output is very simple: only an estimate of the intercept and of
                    809:   the slope with 95% confident intervals.
                    810: 
                    811:   Current limitations:
                    812:   A) Even if you enter covariates, i.e. with the
                    813:   model= V1+V2 equation for example, the programm does only estimate a unique global model without covariates.
                    814:   B) There is no computation of Life Expectancy nor Life Table.
                    815: 
                    816:   Revision 1.97  2004/02/20 13:25:42  lievre
                    817:   Version 0.96d. Population forecasting command line is (temporarily)
                    818:   suppressed.
                    819: 
                    820:   Revision 1.96  2003/07/15 15:38:55  brouard
                    821:   * imach.c (Repository): Errors in subdirf, 2, 3 while printing tmpout is
                    822:   rewritten within the same printf. Workaround: many printfs.
                    823: 
                    824:   Revision 1.95  2003/07/08 07:54:34  brouard
                    825:   * imach.c (Repository):
                    826:   (Repository): Using imachwizard code to output a more meaningful covariance
                    827:   matrix (cov(a12,c31) instead of numbers.
                    828: 
                    829:   Revision 1.94  2003/06/27 13:00:02  brouard
                    830:   Just cleaning
                    831: 
                    832:   Revision 1.93  2003/06/25 16:33:55  brouard
                    833:   (Module): On windows (cygwin) function asctime_r doesn't
                    834:   exist so I changed back to asctime which exists.
                    835:   (Module): Version 0.96b
                    836: 
                    837:   Revision 1.92  2003/06/25 16:30:45  brouard
                    838:   (Module): On windows (cygwin) function asctime_r doesn't
                    839:   exist so I changed back to asctime which exists.
                    840: 
                    841:   Revision 1.91  2003/06/25 15:30:29  brouard
                    842:   * imach.c (Repository): Duplicated warning errors corrected.
                    843:   (Repository): Elapsed time after each iteration is now output. It
                    844:   helps to forecast when convergence will be reached. Elapsed time
                    845:   is stamped in powell.  We created a new html file for the graphs
                    846:   concerning matrix of covariance. It has extension -cov.htm.
                    847: 
                    848:   Revision 1.90  2003/06/24 12:34:15  brouard
                    849:   (Module): Some bugs corrected for windows. Also, when
                    850:   mle=-1 a template is output in file "or"mypar.txt with the design
                    851:   of the covariance matrix to be input.
                    852: 
                    853:   Revision 1.89  2003/06/24 12:30:52  brouard
                    854:   (Module): Some bugs corrected for windows. Also, when
                    855:   mle=-1 a template is output in file "or"mypar.txt with the design
                    856:   of the covariance matrix to be input.
                    857: 
                    858:   Revision 1.88  2003/06/23 17:54:56  brouard
                    859:   * 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.
                    860: 
                    861:   Revision 1.87  2003/06/18 12:26:01  brouard
                    862:   Version 0.96
                    863: 
                    864:   Revision 1.86  2003/06/17 20:04:08  brouard
                    865:   (Module): Change position of html and gnuplot routines and added
                    866:   routine fileappend.
                    867: 
                    868:   Revision 1.85  2003/06/17 13:12:43  brouard
                    869:   * imach.c (Repository): Check when date of death was earlier that
                    870:   current date of interview. It may happen when the death was just
                    871:   prior to the death. In this case, dh was negative and likelihood
                    872:   was wrong (infinity). We still send an "Error" but patch by
                    873:   assuming that the date of death was just one stepm after the
                    874:   interview.
                    875:   (Repository): Because some people have very long ID (first column)
                    876:   we changed int to long in num[] and we added a new lvector for
                    877:   memory allocation. But we also truncated to 8 characters (left
                    878:   truncation)
                    879:   (Repository): No more line truncation errors.
                    880: 
                    881:   Revision 1.84  2003/06/13 21:44:43  brouard
                    882:   * imach.c (Repository): Replace "freqsummary" at a correct
                    883:   place. It differs from routine "prevalence" which may be called
                    884:   many times. Probs is memory consuming and must be used with
                    885:   parcimony.
                    886:   Version 0.95a3 (should output exactly the same maximization than 0.8a2)
                    887: 
                    888:   Revision 1.83  2003/06/10 13:39:11  lievre
                    889:   *** empty log message ***
                    890: 
                    891:   Revision 1.82  2003/06/05 15:57:20  brouard
                    892:   Add log in  imach.c and  fullversion number is now printed.
                    893: 
                    894: */
                    895: /*
                    896:    Interpolated Markov Chain
                    897: 
                    898:   Short summary of the programme:
                    899:   
1.227     brouard   900:   This program computes Healthy Life Expectancies or State-specific
                    901:   (if states aren't health statuses) Expectancies from
                    902:   cross-longitudinal data. Cross-longitudinal data consist in: 
                    903: 
                    904:   -1- a first survey ("cross") where individuals from different ages
                    905:   are interviewed on their health status or degree of disability (in
                    906:   the case of a health survey which is our main interest)
                    907: 
                    908:   -2- at least a second wave of interviews ("longitudinal") which
                    909:   measure each change (if any) in individual health status.  Health
                    910:   expectancies are computed from the time spent in each health state
                    911:   according to a model. More health states you consider, more time is
                    912:   necessary to reach the Maximum Likelihood of the parameters involved
                    913:   in the model.  The simplest model is the multinomial logistic model
                    914:   where pij is the probability to be observed in state j at the second
                    915:   wave conditional to be observed in state i at the first
                    916:   wave. Therefore the model is: log(pij/pii)= aij + bij*age+ cij*sex +
                    917:   etc , where 'age' is age and 'sex' is a covariate. If you want to
                    918:   have a more complex model than "constant and age", you should modify
                    919:   the program where the markup *Covariates have to be included here
                    920:   again* invites you to do it.  More covariates you add, slower the
1.126     brouard   921:   convergence.
                    922: 
                    923:   The advantage of this computer programme, compared to a simple
                    924:   multinomial logistic model, is clear when the delay between waves is not
                    925:   identical for each individual. Also, if a individual missed an
                    926:   intermediate interview, the information is lost, but taken into
                    927:   account using an interpolation or extrapolation.  
                    928: 
                    929:   hPijx is the probability to be observed in state i at age x+h
                    930:   conditional to the observed state i at age x. The delay 'h' can be
                    931:   split into an exact number (nh*stepm) of unobserved intermediate
                    932:   states. This elementary transition (by month, quarter,
                    933:   semester or year) is modelled as a multinomial logistic.  The hPx
                    934:   matrix is simply the matrix product of nh*stepm elementary matrices
                    935:   and the contribution of each individual to the likelihood is simply
                    936:   hPijx.
                    937: 
                    938:   Also this programme outputs the covariance matrix of the parameters but also
1.218     brouard   939:   of the life expectancies. It also computes the period (stable) prevalence.
                    940: 
                    941: Back prevalence and projections:
1.227     brouard   942: 
                    943:  - back_prevalence_limit(double *p, double **bprlim, double ageminpar,
                    944:    double agemaxpar, double ftolpl, int *ncvyearp, double
                    945:    dateprev1,double dateprev2, int firstpass, int lastpass, int
                    946:    mobilavproj)
                    947: 
                    948:     Computes the back prevalence limit for any combination of
                    949:     covariate values k at any age between ageminpar and agemaxpar and
                    950:     returns it in **bprlim. In the loops,
                    951: 
                    952:    - **bprevalim(**bprlim, ***mobaverage, nlstate, *p, age, **oldm,
                    953:        **savm, **dnewm, **doldm, **dsavm, ftolpl, ncvyearp, k);
                    954: 
                    955:    - hBijx Back Probability to be in state i at age x-h being in j at x
1.218     brouard   956:    Computes for any combination of covariates k and any age between bage and fage 
                    957:    p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                    958:                        oldm=oldms;savm=savms;
1.227     brouard   959: 
1.267     brouard   960:    - hbxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k, nres);
1.218     brouard   961:      Computes the transition matrix starting at age 'age' over
                    962:      'nhstepm*hstepm*stepm' months (i.e. until
                    963:      age (in years)  age+nhstepm*hstepm*stepm/12) by multiplying
1.227     brouard   964:      nhstepm*hstepm matrices. 
                    965: 
                    966:      Returns p3mat[i][j][h] after calling
                    967:      p3mat[i][j][h]=matprod2(newm,
                    968:      bmij(pmmij,cov,ncovmodel,x,nlstate,prevacurrent, dnewm, doldm,
                    969:      dsavm,ij),\ 1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath,
                    970:      oldm);
1.226     brouard   971: 
                    972: Important routines
                    973: 
                    974: - func (or funcone), computes logit (pij) distinguishing
                    975:   o fixed variables (single or product dummies or quantitative);
                    976:   o varying variables by:
                    977:    (1) wave (single, product dummies, quantitative), 
                    978:    (2) by age (can be month) age (done), age*age (done), age*Vn where Vn can be:
                    979:        % fixed dummy (treated) or quantitative (not done because time-consuming);
                    980:        % varying dummy (not done) or quantitative (not done);
                    981: - Tricode which tests the modality of dummy variables (in order to warn with wrong or empty modalities)
                    982:   and returns the number of efficient covariates cptcoveff and modalities nbcode[Tvar[k]][1]= 0 and nbcode[Tvar[k]][2]= 1 usually.
                    983: - printinghtml which outputs results like life expectancy in and from a state for a combination of modalities of dummy variables
                    984:   o There are 2*cptcoveff combinations of (0,1) for cptcoveff variables. Outputting only combinations with people, éliminating 1 1 if
                    985:     race White (0 0), Black vs White (1 0), Hispanic (0 1) and 1 1 being meaningless.
1.218     brouard   986: 
1.226     brouard   987: 
                    988:   
1.133     brouard   989:   Authors: Nicolas Brouard (brouard@ined.fr) and Agnès Lièvre (lievre@ined.fr).
                    990:            Institut national d'études démographiques, Paris.
1.126     brouard   991:   This software have been partly granted by Euro-REVES, a concerted action
                    992:   from the European Union.
                    993:   It is copyrighted identically to a GNU software product, ie programme and
                    994:   software can be distributed freely for non commercial use. Latest version
                    995:   can be accessed at http://euroreves.ined.fr/imach .
                    996: 
                    997:   Help to debug: LD_PRELOAD=/usr/local/lib/libnjamd.so ./imach foo.imach
                    998:   or better on gdb : set env LD_PRELOAD=/usr/local/lib/libnjamd.so
                    999:   
                   1000:   **********************************************************************/
                   1001: /*
                   1002:   main
                   1003:   read parameterfile
                   1004:   read datafile
                   1005:   concatwav
                   1006:   freqsummary
                   1007:   if (mle >= 1)
                   1008:     mlikeli
                   1009:   print results files
                   1010:   if mle==1 
                   1011:      computes hessian
                   1012:   read end of parameter file: agemin, agemax, bage, fage, estepm
                   1013:       begin-prev-date,...
                   1014:   open gnuplot file
                   1015:   open html file
1.145     brouard  1016:   period (stable) prevalence      | pl_nom    1-1 2-2 etc by covariate
                   1017:    for age prevalim()             | #****** V1=0  V2=1  V3=1  V4=0 ******
                   1018:                                   | 65 1 0 2 1 3 1 4 0  0.96326 0.03674
                   1019:     freexexit2 possible for memory heap.
                   1020: 
                   1021:   h Pij x                         | pij_nom  ficrestpij
                   1022:    # Cov Agex agex+h hpijx with i,j= 1-1 1-2     1-3     2-1     2-2     2-3
                   1023:        1  85   85    1.00000             0.00000 0.00000 0.00000 1.00000 0.00000
                   1024:        1  85   86    0.68299             0.22291 0.09410 0.71093 0.00000 0.28907
                   1025: 
                   1026:        1  65   99    0.00364             0.00322 0.99314 0.00350 0.00310 0.99340
                   1027:        1  65  100    0.00214             0.00204 0.99581 0.00206 0.00196 0.99597
                   1028:   variance of p one-step probabilities varprob  | prob_nom   ficresprob #One-step probabilities and stand. devi in ()
                   1029:    Standard deviation of one-step probabilities | probcor_nom   ficresprobcor #One-step probabilities and correlation matrix
                   1030:    Matrix of variance covariance of one-step probabilities |  probcov_nom ficresprobcov #One-step probabilities and covariance matrix
                   1031: 
1.126     brouard  1032:   forecasting if prevfcast==1 prevforecast call prevalence()
                   1033:   health expectancies
                   1034:   Variance-covariance of DFLE
                   1035:   prevalence()
                   1036:    movingaverage()
                   1037:   varevsij() 
                   1038:   if popbased==1 varevsij(,popbased)
                   1039:   total life expectancies
                   1040:   Variance of period (stable) prevalence
                   1041:  end
                   1042: */
                   1043: 
1.187     brouard  1044: /* #define DEBUG */
                   1045: /* #define DEBUGBRENT */
1.203     brouard  1046: /* #define DEBUGLINMIN */
                   1047: /* #define DEBUGHESS */
                   1048: #define DEBUGHESSIJ
1.224     brouard  1049: /* #define LINMINORIGINAL  /\* Don't use loop on scale in linmin (accepting nan) *\/ */
1.165     brouard  1050: #define POWELL /* Instead of NLOPT */
1.224     brouard  1051: #define POWELLNOF3INFF1TEST /* Skip test */
1.186     brouard  1052: /* #define POWELLORIGINAL /\* Don't use Directest to decide new direction but original Powell test *\/ */
                   1053: /* #define MNBRAKORIGINAL /\* Don't use mnbrak fix *\/ */
1.126     brouard  1054: 
                   1055: #include <math.h>
                   1056: #include <stdio.h>
                   1057: #include <stdlib.h>
                   1058: #include <string.h>
1.226     brouard  1059: #include <ctype.h>
1.159     brouard  1060: 
                   1061: #ifdef _WIN32
                   1062: #include <io.h>
1.172     brouard  1063: #include <windows.h>
                   1064: #include <tchar.h>
1.159     brouard  1065: #else
1.126     brouard  1066: #include <unistd.h>
1.159     brouard  1067: #endif
1.126     brouard  1068: 
                   1069: #include <limits.h>
                   1070: #include <sys/types.h>
1.171     brouard  1071: 
                   1072: #if defined(__GNUC__)
                   1073: #include <sys/utsname.h> /* Doesn't work on Windows */
                   1074: #endif
                   1075: 
1.126     brouard  1076: #include <sys/stat.h>
                   1077: #include <errno.h>
1.159     brouard  1078: /* extern int errno; */
1.126     brouard  1079: 
1.157     brouard  1080: /* #ifdef LINUX */
                   1081: /* #include <time.h> */
                   1082: /* #include "timeval.h" */
                   1083: /* #else */
                   1084: /* #include <sys/time.h> */
                   1085: /* #endif */
                   1086: 
1.126     brouard  1087: #include <time.h>
                   1088: 
1.136     brouard  1089: #ifdef GSL
                   1090: #include <gsl/gsl_errno.h>
                   1091: #include <gsl/gsl_multimin.h>
                   1092: #endif
                   1093: 
1.167     brouard  1094: 
1.162     brouard  1095: #ifdef NLOPT
                   1096: #include <nlopt.h>
                   1097: typedef struct {
                   1098:   double (* function)(double [] );
                   1099: } myfunc_data ;
                   1100: #endif
                   1101: 
1.126     brouard  1102: /* #include <libintl.h> */
                   1103: /* #define _(String) gettext (String) */
                   1104: 
1.251     brouard  1105: #define MAXLINE 2048 /* Was 256 and 1024. Overflow with 312 with 2 states and 4 covariates. Should be ok */
1.126     brouard  1106: 
                   1107: #define GNUPLOTPROGRAM "gnuplot"
                   1108: /*#define GNUPLOTPROGRAM "..\\gp37mgw\\wgnuplot"*/
                   1109: #define FILENAMELENGTH 132
                   1110: 
                   1111: #define        GLOCK_ERROR_NOPATH              -1      /* empty path */
                   1112: #define        GLOCK_ERROR_GETCWD              -2      /* cannot get cwd */
                   1113: 
1.144     brouard  1114: #define MAXPARM 128 /**< Maximum number of parameters for the optimization */
                   1115: #define NPARMAX 64 /**< (nlstate+ndeath-1)*nlstate*ncovmodel */
1.126     brouard  1116: 
                   1117: #define NINTERVMAX 8
1.144     brouard  1118: #define NLSTATEMAX 8 /**< Maximum number of live states (for func) */
                   1119: #define NDEATHMAX 8 /**< Maximum number of dead states (for func) */
1.291     brouard  1120: #define NCOVMAX 20  /**< Maximum number of covariates, including generated covariates V1*V2 */
1.197     brouard  1121: #define codtabm(h,k)  (1 & (h-1) >> (k-1))+1
1.211     brouard  1122: /*#define decodtabm(h,k,cptcoveff)= (h <= (1<<cptcoveff)?(((h-1) >> (k-1)) & 1) +1 : -1)*/
                   1123: #define decodtabm(h,k,cptcoveff) (((h-1) >> (k-1)) & 1) +1 
1.290     brouard  1124: /*#define MAXN 20000 */ /* Should by replaced by nobs, real number of observations and unlimited */
1.144     brouard  1125: #define YEARM 12. /**< Number of months per year */
1.218     brouard  1126: /* #define AGESUP 130 */
1.288     brouard  1127: /* #define AGESUP 150 */
                   1128: #define AGESUP 200
1.268     brouard  1129: #define AGEINF 0
1.218     brouard  1130: #define AGEMARGE 25 /* Marge for agemin and agemax for(iage=agemin-AGEMARGE; iage <= agemax+3+AGEMARGE; iage++) */
1.126     brouard  1131: #define AGEBASE 40
1.194     brouard  1132: #define AGEOVERFLOW 1.e20
1.164     brouard  1133: #define AGEGOMP 10 /**< Minimal age for Gompertz adjustment */
1.157     brouard  1134: #ifdef _WIN32
                   1135: #define DIRSEPARATOR '\\'
                   1136: #define CHARSEPARATOR "\\"
                   1137: #define ODIRSEPARATOR '/'
                   1138: #else
1.126     brouard  1139: #define DIRSEPARATOR '/'
                   1140: #define CHARSEPARATOR "/"
                   1141: #define ODIRSEPARATOR '\\'
                   1142: #endif
                   1143: 
1.307   ! brouard  1144: /* $Id: imach.c,v 1.306 2021/02/20 15:44:02 brouard Exp $ */
1.126     brouard  1145: /* $State: Exp $ */
1.196     brouard  1146: #include "version.h"
                   1147: char version[]=__IMACH_VERSION__;
1.306     brouard  1148: char copyright[]="Feb 2021,INED-EUROREVES-Institut de longevite-Japan Society for the Promotion of Science (Grant-in-Aid for Scientific Research 25293121), Intel Software 2015-2020, INED 2000-2021";
1.307   ! brouard  1149: char fullversion[]="$Revision: 1.306 $ $Date: 2021/02/20 15:44:02 $"; 
1.126     brouard  1150: char strstart[80];
                   1151: char optionfilext[10], optionfilefiname[FILENAMELENGTH];
1.130     brouard  1152: int erreur=0, nberr=0, nbwarn=0; /* Error number, number of errors number of warnings  */
1.187     brouard  1153: int nagesqr=0, nforce=0; /* nagesqr=1 if model is including age*age, number of forces */
1.145     brouard  1154: /* Number of covariates model=V2+V1+ V3*age+V2*V4 */
                   1155: int cptcovn=0; /**< cptcovn number of covariates added in the model (excepting constant and age and age*product) */
                   1156: int cptcovt=0; /**< cptcovt number of covariates added in the model (excepting constant and age) */
1.225     brouard  1157: int cptcovs=0; /**< cptcovs number of simple covariates in the model V2+V1 =2 */
                   1158: int cptcovsnq=0; /**< cptcovsnq number of simple covariates in the model but non quantitative V2+V1 =2 */
1.145     brouard  1159: int cptcovage=0; /**< Number of covariates with age: V3*age only =1 */
                   1160: int cptcovprodnoage=0; /**< Number of covariate products without age */   
                   1161: int cptcoveff=0; /* Total number of covariates to vary for printing results */
1.233     brouard  1162: int ncovf=0; /* Total number of effective fixed covariates (dummy or quantitative) in the model */
                   1163: int ncovv=0; /* Total number of effective (wave) varying covariates (dummy or quantitative) in the model */
1.232     brouard  1164: int ncova=0; /* Total number of effective (wave and stepm) varying with age covariates (dummy of quantitative) in the model */
1.234     brouard  1165: int nsd=0; /**< Total number of single dummy variables (output) */
                   1166: int nsq=0; /**< Total number of single quantitative variables (output) */
1.232     brouard  1167: int ncoveff=0; /* Total number of effective fixed dummy covariates in the model */
1.225     brouard  1168: int nqfveff=0; /**< nqfveff Number of Quantitative Fixed Variables Effective */
1.224     brouard  1169: int ntveff=0; /**< ntveff number of effective time varying variables */
                   1170: int nqtveff=0; /**< ntqveff number of effective time varying quantitative variables */
1.145     brouard  1171: int cptcov=0; /* Working variable */
1.290     brouard  1172: int nobs=10;  /* Number of observations in the data lastobs-firstobs */
1.218     brouard  1173: int ncovcombmax=NCOVMAX; /* Maximum calculated number of covariate combination = pow(2, cptcoveff) */
1.302     brouard  1174: int npar=NPARMAX; /* Number of parameters (nlstate+ndeath-1)*nlstate*ncovmodel; */
1.126     brouard  1175: int nlstate=2; /* Number of live states */
                   1176: int ndeath=1; /* Number of dead states */
1.130     brouard  1177: int ncovmodel=0, ncovcol=0;     /* Total number of covariables including constant a12*1 +b12*x ncovmodel=2 */
1.223     brouard  1178: int  nqv=0, ntv=0, nqtv=0;    /* Total number of quantitative variables, time variable (dummy), quantitative and time variable */ 
1.126     brouard  1179: int popbased=0;
                   1180: 
                   1181: int *wav; /* Number of waves for this individuual 0 is possible */
1.130     brouard  1182: int maxwav=0; /* Maxim number of waves */
                   1183: int jmin=0, jmax=0; /* min, max spacing between 2 waves */
                   1184: int ijmin=0, ijmax=0; /* Individuals having jmin and jmax */ 
                   1185: int gipmx=0, gsw=0; /* Global variables on the number of contributions 
1.126     brouard  1186:                   to the likelihood and the sum of weights (done by funcone)*/
1.130     brouard  1187: int mle=1, weightopt=0;
1.126     brouard  1188: int **mw; /* mw[mi][i] is number of the mi wave for this individual */
                   1189: int **dh; /* dh[mi][i] is number of steps between mi,mi+1 for this individual */
                   1190: int **bh; /* bh[mi][i] is the bias (+ or -) for this individual if the delay between
                   1191:           * wave mi and wave mi+1 is not an exact multiple of stepm. */
1.162     brouard  1192: int countcallfunc=0;  /* Count the number of calls to func */
1.230     brouard  1193: int selected(int kvar); /* Is covariate kvar selected for printing results */
                   1194: 
1.130     brouard  1195: double jmean=1; /* Mean space between 2 waves */
1.145     brouard  1196: double **matprod2(); /* test */
1.126     brouard  1197: double **oldm, **newm, **savm; /* Working pointers to matrices */
                   1198: double **oldms, **newms, **savms; /* Fixed working pointers to matrices */
1.218     brouard  1199: double  **ddnewms, **ddoldms, **ddsavms; /* for freeing later */
                   1200: 
1.136     brouard  1201: /*FILE *fic ; */ /* Used in readdata only */
1.217     brouard  1202: FILE *ficpar, *ficparo,*ficres, *ficresp, *ficresphtm, *ficresphtmfr, *ficrespl, *ficresplb,*ficrespij, *ficrespijb, *ficrest,*ficresf, *ficresfb,*ficrespop;
1.126     brouard  1203: FILE *ficlog, *ficrespow;
1.130     brouard  1204: int globpr=0; /* Global variable for printing or not */
1.126     brouard  1205: double fretone; /* Only one call to likelihood */
1.130     brouard  1206: long ipmx=0; /* Number of contributions */
1.126     brouard  1207: double sw; /* Sum of weights */
                   1208: char filerespow[FILENAMELENGTH];
                   1209: char fileresilk[FILENAMELENGTH]; /* File of individual contributions to the likelihood */
                   1210: FILE *ficresilk;
                   1211: FILE *ficgp,*ficresprob,*ficpop, *ficresprobcov, *ficresprobcor;
                   1212: FILE *ficresprobmorprev;
                   1213: FILE *fichtm, *fichtmcov; /* Html File */
                   1214: FILE *ficreseij;
                   1215: char filerese[FILENAMELENGTH];
                   1216: FILE *ficresstdeij;
                   1217: char fileresstde[FILENAMELENGTH];
                   1218: FILE *ficrescveij;
                   1219: char filerescve[FILENAMELENGTH];
                   1220: FILE  *ficresvij;
                   1221: char fileresv[FILENAMELENGTH];
1.269     brouard  1222: 
1.126     brouard  1223: char title[MAXLINE];
1.234     brouard  1224: char model[MAXLINE]; /**< The model line */
1.217     brouard  1225: char optionfile[FILENAMELENGTH], datafile[FILENAMELENGTH],  filerespl[FILENAMELENGTH],  fileresplb[FILENAMELENGTH];
1.126     brouard  1226: char plotcmd[FILENAMELENGTH], pplotcmd[FILENAMELENGTH];
                   1227: char tmpout[FILENAMELENGTH],  tmpout2[FILENAMELENGTH]; 
                   1228: char command[FILENAMELENGTH];
                   1229: int  outcmd=0;
                   1230: 
1.217     brouard  1231: char fileres[FILENAMELENGTH], filerespij[FILENAMELENGTH], filerespijb[FILENAMELENGTH], filereso[FILENAMELENGTH], rfileres[FILENAMELENGTH];
1.202     brouard  1232: char fileresu[FILENAMELENGTH]; /* fileres without r in front */
1.126     brouard  1233: char filelog[FILENAMELENGTH]; /* Log file */
                   1234: char filerest[FILENAMELENGTH];
                   1235: char fileregp[FILENAMELENGTH];
                   1236: char popfile[FILENAMELENGTH];
                   1237: 
                   1238: char optionfilegnuplot[FILENAMELENGTH], optionfilehtm[FILENAMELENGTH], optionfilehtmcov[FILENAMELENGTH] ;
                   1239: 
1.157     brouard  1240: /* struct timeval start_time, end_time, curr_time, last_time, forecast_time; */
                   1241: /* struct timezone tzp; */
                   1242: /* extern int gettimeofday(); */
                   1243: struct tm tml, *gmtime(), *localtime();
                   1244: 
                   1245: extern time_t time();
                   1246: 
                   1247: struct tm start_time, end_time, curr_time, last_time, forecast_time;
                   1248: time_t  rstart_time, rend_time, rcurr_time, rlast_time, rforecast_time; /* raw time */
                   1249: struct tm tm;
                   1250: 
1.126     brouard  1251: char strcurr[80], strfor[80];
                   1252: 
                   1253: char *endptr;
                   1254: long lval;
                   1255: double dval;
                   1256: 
                   1257: #define NR_END 1
                   1258: #define FREE_ARG char*
                   1259: #define FTOL 1.0e-10
                   1260: 
                   1261: #define NRANSI 
1.240     brouard  1262: #define ITMAX 200
                   1263: #define ITPOWMAX 20 /* This is now multiplied by the number of parameters */ 
1.126     brouard  1264: 
                   1265: #define TOL 2.0e-4 
                   1266: 
                   1267: #define CGOLD 0.3819660 
                   1268: #define ZEPS 1.0e-10 
                   1269: #define SHFT(a,b,c,d) (a)=(b);(b)=(c);(c)=(d); 
                   1270: 
                   1271: #define GOLD 1.618034 
                   1272: #define GLIMIT 100.0 
                   1273: #define TINY 1.0e-20 
                   1274: 
                   1275: static double maxarg1,maxarg2;
                   1276: #define FMAX(a,b) (maxarg1=(a),maxarg2=(b),(maxarg1)>(maxarg2)? (maxarg1):(maxarg2))
                   1277: #define FMIN(a,b) (maxarg1=(a),maxarg2=(b),(maxarg1)<(maxarg2)? (maxarg1):(maxarg2))
                   1278:   
                   1279: #define SIGN(a,b) ((b)>0.0 ? fabs(a) : -fabs(a))
                   1280: #define rint(a) floor(a+0.5)
1.166     brouard  1281: /* http://www.thphys.uni-heidelberg.de/~robbers/cmbeasy/doc/html/myutils_8h-source.html */
1.183     brouard  1282: #define mytinydouble 1.0e-16
1.166     brouard  1283: /* #define DEQUAL(a,b) (fabs((a)-(b))<mytinydouble) */
                   1284: /* http://www.thphys.uni-heidelberg.de/~robbers/cmbeasy/doc/html/mynrutils_8h-source.html */
                   1285: /* static double dsqrarg; */
                   1286: /* #define DSQR(a) (DEQUAL((dsqrarg=(a)),0.0) ? 0.0 : dsqrarg*dsqrarg) */
1.126     brouard  1287: static double sqrarg;
                   1288: #define SQR(a) ((sqrarg=(a)) == 0.0 ? 0.0 :sqrarg*sqrarg)
                   1289: #define SWAP(a,b) {temp=(a);(a)=(b);(b)=temp;} 
                   1290: int agegomp= AGEGOMP;
                   1291: 
                   1292: int imx; 
                   1293: int stepm=1;
                   1294: /* Stepm, step in month: minimum step interpolation*/
                   1295: 
                   1296: int estepm;
                   1297: /* Estepm, step in month to interpolate survival function in order to approximate Life Expectancy*/
                   1298: 
                   1299: int m,nb;
                   1300: long *num;
1.197     brouard  1301: int firstpass=0, lastpass=4,*cod, *cens;
1.192     brouard  1302: int *ncodemax;  /* ncodemax[j]= Number of modalities of the j th
                   1303:                   covariate for which somebody answered excluding 
                   1304:                   undefined. Usually 2: 0 and 1. */
                   1305: int *ncodemaxwundef;  /* ncodemax[j]= Number of modalities of the j th
                   1306:                             covariate for which somebody answered including 
                   1307:                             undefined. Usually 3: -1, 0 and 1. */
1.126     brouard  1308: double **agev,*moisnais, *annais, *moisdc, *andc,**mint, **anint;
1.218     brouard  1309: double **pmmij, ***probs; /* Global pointer */
1.219     brouard  1310: double ***mobaverage, ***mobaverages; /* New global variable */
1.126     brouard  1311: double *ageexmed,*agecens;
                   1312: double dateintmean=0;
1.296     brouard  1313:   double anprojd, mprojd, jprojd; /* For eventual projections */
                   1314:   double anprojf, mprojf, jprojf;
1.126     brouard  1315: 
1.296     brouard  1316:   double anbackd, mbackd, jbackd; /* For eventual backprojections */
                   1317:   double anbackf, mbackf, jbackf;
                   1318:   double jintmean,mintmean,aintmean;  
1.126     brouard  1319: double *weight;
                   1320: int **s; /* Status */
1.141     brouard  1321: double *agedc;
1.145     brouard  1322: double  **covar; /**< covar[j,i], value of jth covariate for individual i,
1.141     brouard  1323:                  * covar=matrix(0,NCOVMAX,1,n); 
1.187     brouard  1324:                  * cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*age; */
1.268     brouard  1325: double **coqvar; /* Fixed quantitative covariate nqv */
                   1326: double ***cotvar; /* Time varying covariate ntv */
1.225     brouard  1327: double ***cotqvar; /* Time varying quantitative covariate itqv */
1.141     brouard  1328: double  idx; 
                   1329: int **nbcode, *Tvar; /**< model=V2 => Tvar[1]= 2 */
1.234     brouard  1330: /*           V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
                   1331: /*k          1  2   3   4     5    6    7     8    9 */
                   1332: /*Tvar[k]=   5  4   3   6     5    2    7     1    1 */
                   1333: /* Tndvar[k]    1   2   3               4          5 */
                   1334: /*TDvar         4   3   6               7          1 */ /* For outputs only; combination of dummies fixed or varying */
                   1335: /* Tns[k]    1  2   2              4               5 */ /* Number of single cova */
                   1336: /* TvarsD[k]    1   2                              3 */ /* Number of single dummy cova */
                   1337: /* TvarsDind    2   3                              9 */ /* position K of single dummy cova */
                   1338: /* TvarsQ[k] 1                     2                 */ /* Number of single quantitative cova */
                   1339: /* TvarsQind 1                     6                 */ /* position K of single quantitative cova */
                   1340: /* Tprod[i]=k           4               7            */
                   1341: /* Tage[i]=k                  5               8      */
                   1342: /* */
                   1343: /* Type                    */
                   1344: /* V         1  2  3  4  5 */
                   1345: /*           F  F  V  V  V */
                   1346: /*           D  Q  D  D  Q */
                   1347: /*                         */
                   1348: int *TvarsD;
                   1349: int *TvarsDind;
                   1350: int *TvarsQ;
                   1351: int *TvarsQind;
                   1352: 
1.235     brouard  1353: #define MAXRESULTLINES 10
                   1354: int nresult=0;
1.258     brouard  1355: int parameterline=0; /* # of the parameter (type) line */
1.235     brouard  1356: int TKresult[MAXRESULTLINES];
1.237     brouard  1357: int Tresult[MAXRESULTLINES][NCOVMAX];/* For dummy variable , value (output) */
                   1358: int Tinvresult[MAXRESULTLINES][NCOVMAX];/* For dummy variable , value (output) */
1.235     brouard  1359: int Tvresult[MAXRESULTLINES][NCOVMAX]; /* For dummy variable , variable # (output) */
                   1360: double Tqresult[MAXRESULTLINES][NCOVMAX]; /* For quantitative variable , value (output) */
1.237     brouard  1361: double Tqinvresult[MAXRESULTLINES][NCOVMAX]; /* For quantitative variable , value (output) */
1.235     brouard  1362: int Tvqresult[MAXRESULTLINES][NCOVMAX]; /* For quantitative variable , variable # (output) */
                   1363: 
1.234     brouard  1364: /* 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  1365: 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 */
                   1366: 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 */
                   1367: 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 */
                   1368: int *TvarVind; /**< TvarVind[1]=1, TvarVind[2]=2  in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
                   1369: 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 */
                   1370: 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  1371: int *TvarFD; /**< TvarFD[1]=V1 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
                   1372: int *TvarFDind; /* TvarFDind[1]=9 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
                   1373: int *TvarFQ; /* TvarFQ[1]=V2 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */ /* Only simple fixed quantitative variable */
                   1374: int *TvarFQind; /* TvarFQind[1]=6 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */ /* Only simple fixed quantitative variable */
                   1375: int *TvarVD; /* TvarVD[1]=V5 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */ /* Only simple fixed quantitative variable */
                   1376: int *TvarVDind; /* TvarVDind[1]=1 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */ /* Only simple fixed quantitative variable */
                   1377: 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 */
                   1378: 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 */
                   1379: 
1.230     brouard  1380: int *Tvarsel; /**< Selected covariates for output */
                   1381: double *Tvalsel; /**< Selected modality value of covariate for output */
1.226     brouard  1382: int *Typevar; /**< 0 for simple covariate (dummy, quantitative, fixed or varying), 1 for age product, 2 for  product */
1.227     brouard  1383: int *Fixed; /** Fixed[k] 0=fixed, 1 varying, 2 fixed with age product, 3 varying with age product */ 
                   1384: 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  1385: int *DummyV; /** Dummy[v] 0=dummy (0 1), 1 quantitative */
                   1386: int *FixedV; /** FixedV[v] 0 fixed, 1 varying */
1.197     brouard  1387: int *Tage;
1.227     brouard  1388: int anyvaryingduminmodel=0; /**< Any varying dummy in Model=1 yes, 0 no, to avoid a loop on waves in freq */ 
1.228     brouard  1389: 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  1390: 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*/ 
                   1391: 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  1392: int *Ndum; /** Freq of modality (tricode */
1.200     brouard  1393: /* int **codtab;*/ /**< codtab=imatrix(1,100,1,10); */
1.227     brouard  1394: int **Tvard;
                   1395: int *Tprod;/**< Gives the k position of the k1 product */
1.238     brouard  1396: /* Tprod[k1=1]=3(=V1*V4) for V2+V1+V1*V4+age*V3  */
1.227     brouard  1397: int *Tposprod; /**< Gives the k1 product from the k position */
1.238     brouard  1398:    /* if  V2+V1+V1*V4+age*V3+V3*V2   TProd[k1=2]=5 (V3*V2) */
                   1399:    /* Tposprod[k]=k1 , Tposprod[3]=1, Tposprod[5(V3*V2)]=2 (2nd product without age) */
1.227     brouard  1400: int cptcovprod, *Tvaraff, *invalidvarcomb;
1.126     brouard  1401: double *lsurv, *lpop, *tpop;
                   1402: 
1.231     brouard  1403: #define FD 1; /* Fixed dummy covariate */
                   1404: #define FQ 2; /* Fixed quantitative covariate */
                   1405: #define FP 3; /* Fixed product covariate */
                   1406: #define FPDD 7; /* Fixed product dummy*dummy covariate */
                   1407: #define FPDQ 8; /* Fixed product dummy*quantitative covariate */
                   1408: #define FPQQ 9; /* Fixed product quantitative*quantitative covariate */
                   1409: #define VD 10; /* Varying dummy covariate */
                   1410: #define VQ 11; /* Varying quantitative covariate */
                   1411: #define VP 12; /* Varying product covariate */
                   1412: #define VPDD 13; /* Varying product dummy*dummy covariate */
                   1413: #define VPDQ 14; /* Varying product dummy*quantitative covariate */
                   1414: #define VPQQ 15; /* Varying product quantitative*quantitative covariate */
                   1415: #define APFD 16; /* Age product * fixed dummy covariate */
                   1416: #define APFQ 17; /* Age product * fixed quantitative covariate */
                   1417: #define APVD 18; /* Age product * varying dummy covariate */
                   1418: #define APVQ 19; /* Age product * varying quantitative covariate */
                   1419: 
                   1420: #define FTYPE 1; /* Fixed covariate */
                   1421: #define VTYPE 2; /* Varying covariate (loop in wave) */
                   1422: #define ATYPE 2; /* Age product covariate (loop in dh within wave)*/
                   1423: 
                   1424: struct kmodel{
                   1425:        int maintype; /* main type */
                   1426:        int subtype; /* subtype */
                   1427: };
                   1428: struct kmodel modell[NCOVMAX];
                   1429: 
1.143     brouard  1430: double ftol=FTOL; /**< Tolerance for computing Max Likelihood */
                   1431: double ftolhess; /**< Tolerance for computing hessian */
1.126     brouard  1432: 
                   1433: /**************** split *************************/
                   1434: static int split( char *path, char *dirc, char *name, char *ext, char *finame )
                   1435: {
                   1436:   /* From a file name with (full) path (either Unix or Windows) we extract the directory (dirc)
                   1437:      the name of the file (name), its extension only (ext) and its first part of the name (finame)
                   1438:   */ 
                   1439:   char *ss;                            /* pointer */
1.186     brouard  1440:   int  l1=0, l2=0;                             /* length counters */
1.126     brouard  1441: 
                   1442:   l1 = strlen(path );                  /* length of path */
                   1443:   if ( l1 == 0 ) return( GLOCK_ERROR_NOPATH );
                   1444:   ss= strrchr( path, DIRSEPARATOR );           /* find last / */
                   1445:   if ( ss == NULL ) {                  /* no directory, so determine current directory */
                   1446:     strcpy( name, path );              /* we got the fullname name because no directory */
                   1447:     /*if(strrchr(path, ODIRSEPARATOR )==NULL)
                   1448:       printf("Warning you should use %s as a separator\n",DIRSEPARATOR);*/
                   1449:     /* get current working directory */
                   1450:     /*    extern  char* getcwd ( char *buf , int len);*/
1.184     brouard  1451: #ifdef WIN32
                   1452:     if (_getcwd( dirc, FILENAME_MAX ) == NULL ) {
                   1453: #else
                   1454:        if (getcwd(dirc, FILENAME_MAX) == NULL) {
                   1455: #endif
1.126     brouard  1456:       return( GLOCK_ERROR_GETCWD );
                   1457:     }
                   1458:     /* got dirc from getcwd*/
                   1459:     printf(" DIRC = %s \n",dirc);
1.205     brouard  1460:   } else {                             /* strip directory from path */
1.126     brouard  1461:     ss++;                              /* after this, the filename */
                   1462:     l2 = strlen( ss );                 /* length of filename */
                   1463:     if ( l2 == 0 ) return( GLOCK_ERROR_NOPATH );
                   1464:     strcpy( name, ss );                /* save file name */
                   1465:     strncpy( dirc, path, l1 - l2 );    /* now the directory */
1.186     brouard  1466:     dirc[l1-l2] = '\0';                        /* add zero */
1.126     brouard  1467:     printf(" DIRC2 = %s \n",dirc);
                   1468:   }
                   1469:   /* We add a separator at the end of dirc if not exists */
                   1470:   l1 = strlen( dirc );                 /* length of directory */
                   1471:   if( dirc[l1-1] != DIRSEPARATOR ){
                   1472:     dirc[l1] =  DIRSEPARATOR;
                   1473:     dirc[l1+1] = 0; 
                   1474:     printf(" DIRC3 = %s \n",dirc);
                   1475:   }
                   1476:   ss = strrchr( name, '.' );           /* find last / */
                   1477:   if (ss >0){
                   1478:     ss++;
                   1479:     strcpy(ext,ss);                    /* save extension */
                   1480:     l1= strlen( name);
                   1481:     l2= strlen(ss)+1;
                   1482:     strncpy( finame, name, l1-l2);
                   1483:     finame[l1-l2]= 0;
                   1484:   }
                   1485: 
                   1486:   return( 0 );                         /* we're done */
                   1487: }
                   1488: 
                   1489: 
                   1490: /******************************************/
                   1491: 
                   1492: void replace_back_to_slash(char *s, char*t)
                   1493: {
                   1494:   int i;
                   1495:   int lg=0;
                   1496:   i=0;
                   1497:   lg=strlen(t);
                   1498:   for(i=0; i<= lg; i++) {
                   1499:     (s[i] = t[i]);
                   1500:     if (t[i]== '\\') s[i]='/';
                   1501:   }
                   1502: }
                   1503: 
1.132     brouard  1504: char *trimbb(char *out, char *in)
1.137     brouard  1505: { /* Trim multiple blanks in line but keeps first blanks if line starts with blanks */
1.132     brouard  1506:   char *s;
                   1507:   s=out;
                   1508:   while (*in != '\0'){
1.137     brouard  1509:     while( *in == ' ' && *(in+1) == ' '){ /* && *(in+1) != '\0'){*/
1.132     brouard  1510:       in++;
                   1511:     }
                   1512:     *out++ = *in++;
                   1513:   }
                   1514:   *out='\0';
                   1515:   return s;
                   1516: }
                   1517: 
1.187     brouard  1518: /* char *substrchaine(char *out, char *in, char *chain) */
                   1519: /* { */
                   1520: /*   /\* Substract chain 'chain' from 'in', return and output 'out' *\/ */
                   1521: /*   char *s, *t; */
                   1522: /*   t=in;s=out; */
                   1523: /*   while ((*in != *chain) && (*in != '\0')){ */
                   1524: /*     *out++ = *in++; */
                   1525: /*   } */
                   1526: 
                   1527: /*   /\* *in matches *chain *\/ */
                   1528: /*   while ((*in++ == *chain++) && (*in != '\0')){ */
                   1529: /*     printf("*in = %c, *out= %c *chain= %c \n", *in, *out, *chain);  */
                   1530: /*   } */
                   1531: /*   in--; chain--; */
                   1532: /*   while ( (*in != '\0')){ */
                   1533: /*     printf("Bef *in = %c, *out= %c *chain= %c \n", *in, *out, *chain);  */
                   1534: /*     *out++ = *in++; */
                   1535: /*     printf("Aft *in = %c, *out= %c *chain= %c \n", *in, *out, *chain);  */
                   1536: /*   } */
                   1537: /*   *out='\0'; */
                   1538: /*   out=s; */
                   1539: /*   return out; */
                   1540: /* } */
                   1541: char *substrchaine(char *out, char *in, char *chain)
                   1542: {
                   1543:   /* Substract chain 'chain' from 'in', return and output 'out' */
                   1544:   /* in="V1+V1*age+age*age+V2", chain="age*age" */
                   1545: 
                   1546:   char *strloc;
                   1547: 
                   1548:   strcpy (out, in); 
                   1549:   strloc = strstr(out, chain); /* strloc points to out at age*age+V2 */
                   1550:   printf("Bef strloc=%s chain=%s out=%s \n", strloc, chain, out);
                   1551:   if(strloc != NULL){ 
                   1552:     /* will affect out */ /* strloc+strlenc(chain)=+V2 */ /* Will also work in Unicode */
                   1553:     memmove(strloc,strloc+strlen(chain), strlen(strloc+strlen(chain))+1);
                   1554:     /* strcpy (strloc, strloc +strlen(chain));*/
                   1555:   }
                   1556:   printf("Aft strloc=%s chain=%s in=%s out=%s \n", strloc, chain, in, out);
                   1557:   return out;
                   1558: }
                   1559: 
                   1560: 
1.145     brouard  1561: char *cutl(char *blocc, char *alocc, char *in, char occ)
                   1562: {
1.187     brouard  1563:   /* cuts string in into blocc and alocc where blocc ends before FIRST occurence of char 'occ' 
1.145     brouard  1564:      and alocc starts after first occurence of char 'occ' : ex cutv(blocc,alocc,"abcdef2ghi2j",'2')
1.187     brouard  1565:      gives blocc="abcdef" and alocc="ghi2j".
1.145     brouard  1566:      If occ is not found blocc is null and alocc is equal to in. Returns blocc
                   1567:   */
1.160     brouard  1568:   char *s, *t;
1.145     brouard  1569:   t=in;s=in;
                   1570:   while ((*in != occ) && (*in != '\0')){
                   1571:     *alocc++ = *in++;
                   1572:   }
                   1573:   if( *in == occ){
                   1574:     *(alocc)='\0';
                   1575:     s=++in;
                   1576:   }
                   1577:  
                   1578:   if (s == t) {/* occ not found */
                   1579:     *(alocc-(in-s))='\0';
                   1580:     in=s;
                   1581:   }
                   1582:   while ( *in != '\0'){
                   1583:     *blocc++ = *in++;
                   1584:   }
                   1585: 
                   1586:   *blocc='\0';
                   1587:   return t;
                   1588: }
1.137     brouard  1589: char *cutv(char *blocc, char *alocc, char *in, char occ)
                   1590: {
1.187     brouard  1591:   /* cuts string in into blocc and alocc where blocc ends before LAST occurence of char 'occ' 
1.137     brouard  1592:      and alocc starts after last occurence of char 'occ' : ex cutv(blocc,alocc,"abcdef2ghi2j",'2')
                   1593:      gives blocc="abcdef2ghi" and alocc="j".
                   1594:      If occ is not found blocc is null and alocc is equal to in. Returns alocc
                   1595:   */
                   1596:   char *s, *t;
                   1597:   t=in;s=in;
                   1598:   while (*in != '\0'){
                   1599:     while( *in == occ){
                   1600:       *blocc++ = *in++;
                   1601:       s=in;
                   1602:     }
                   1603:     *blocc++ = *in++;
                   1604:   }
                   1605:   if (s == t) /* occ not found */
                   1606:     *(blocc-(in-s))='\0';
                   1607:   else
                   1608:     *(blocc-(in-s)-1)='\0';
                   1609:   in=s;
                   1610:   while ( *in != '\0'){
                   1611:     *alocc++ = *in++;
                   1612:   }
                   1613: 
                   1614:   *alocc='\0';
                   1615:   return s;
                   1616: }
                   1617: 
1.126     brouard  1618: int nbocc(char *s, char occ)
                   1619: {
                   1620:   int i,j=0;
                   1621:   int lg=20;
                   1622:   i=0;
                   1623:   lg=strlen(s);
                   1624:   for(i=0; i<= lg; i++) {
1.234     brouard  1625:     if  (s[i] == occ ) j++;
1.126     brouard  1626:   }
                   1627:   return j;
                   1628: }
                   1629: 
1.137     brouard  1630: /* void cutv(char *u,char *v, char*t, char occ) */
                   1631: /* { */
                   1632: /*   /\* cuts string t into u and v where u ends before last occurence of char 'occ'  */
                   1633: /*      and v starts after last occurence of char 'occ' : ex cutv(u,v,"abcdef2ghi2j",'2') */
                   1634: /*      gives u="abcdef2ghi" and v="j" *\/ */
                   1635: /*   int i,lg,j,p=0; */
                   1636: /*   i=0; */
                   1637: /*   lg=strlen(t); */
                   1638: /*   for(j=0; j<=lg-1; j++) { */
                   1639: /*     if((t[j]!= occ) && (t[j+1]== occ)) p=j+1; */
                   1640: /*   } */
1.126     brouard  1641: 
1.137     brouard  1642: /*   for(j=0; j<p; j++) { */
                   1643: /*     (u[j] = t[j]); */
                   1644: /*   } */
                   1645: /*      u[p]='\0'; */
1.126     brouard  1646: 
1.137     brouard  1647: /*    for(j=0; j<= lg; j++) { */
                   1648: /*     if (j>=(p+1))(v[j-p-1] = t[j]); */
                   1649: /*   } */
                   1650: /* } */
1.126     brouard  1651: 
1.160     brouard  1652: #ifdef _WIN32
                   1653: char * strsep(char **pp, const char *delim)
                   1654: {
                   1655:   char *p, *q;
                   1656:          
                   1657:   if ((p = *pp) == NULL)
                   1658:     return 0;
                   1659:   if ((q = strpbrk (p, delim)) != NULL)
                   1660:   {
                   1661:     *pp = q + 1;
                   1662:     *q = '\0';
                   1663:   }
                   1664:   else
                   1665:     *pp = 0;
                   1666:   return p;
                   1667: }
                   1668: #endif
                   1669: 
1.126     brouard  1670: /********************** nrerror ********************/
                   1671: 
                   1672: void nrerror(char error_text[])
                   1673: {
                   1674:   fprintf(stderr,"ERREUR ...\n");
                   1675:   fprintf(stderr,"%s\n",error_text);
                   1676:   exit(EXIT_FAILURE);
                   1677: }
                   1678: /*********************** vector *******************/
                   1679: double *vector(int nl, int nh)
                   1680: {
                   1681:   double *v;
                   1682:   v=(double *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(double)));
                   1683:   if (!v) nrerror("allocation failure in vector");
                   1684:   return v-nl+NR_END;
                   1685: }
                   1686: 
                   1687: /************************ free vector ******************/
                   1688: void free_vector(double*v, int nl, int nh)
                   1689: {
                   1690:   free((FREE_ARG)(v+nl-NR_END));
                   1691: }
                   1692: 
                   1693: /************************ivector *******************************/
                   1694: int *ivector(long nl,long nh)
                   1695: {
                   1696:   int *v;
                   1697:   v=(int *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(int)));
                   1698:   if (!v) nrerror("allocation failure in ivector");
                   1699:   return v-nl+NR_END;
                   1700: }
                   1701: 
                   1702: /******************free ivector **************************/
                   1703: void free_ivector(int *v, long nl, long nh)
                   1704: {
                   1705:   free((FREE_ARG)(v+nl-NR_END));
                   1706: }
                   1707: 
                   1708: /************************lvector *******************************/
                   1709: long *lvector(long nl,long nh)
                   1710: {
                   1711:   long *v;
                   1712:   v=(long *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(long)));
                   1713:   if (!v) nrerror("allocation failure in ivector");
                   1714:   return v-nl+NR_END;
                   1715: }
                   1716: 
                   1717: /******************free lvector **************************/
                   1718: void free_lvector(long *v, long nl, long nh)
                   1719: {
                   1720:   free((FREE_ARG)(v+nl-NR_END));
                   1721: }
                   1722: 
                   1723: /******************* imatrix *******************************/
                   1724: int **imatrix(long nrl, long nrh, long ncl, long nch) 
                   1725:      /* allocate a int matrix with subscript range m[nrl..nrh][ncl..nch] */ 
                   1726: { 
                   1727:   long i, nrow=nrh-nrl+1,ncol=nch-ncl+1; 
                   1728:   int **m; 
                   1729:   
                   1730:   /* allocate pointers to rows */ 
                   1731:   m=(int **) malloc((size_t)((nrow+NR_END)*sizeof(int*))); 
                   1732:   if (!m) nrerror("allocation failure 1 in matrix()"); 
                   1733:   m += NR_END; 
                   1734:   m -= nrl; 
                   1735:   
                   1736:   
                   1737:   /* allocate rows and set pointers to them */ 
                   1738:   m[nrl]=(int *) malloc((size_t)((nrow*ncol+NR_END)*sizeof(int))); 
                   1739:   if (!m[nrl]) nrerror("allocation failure 2 in matrix()"); 
                   1740:   m[nrl] += NR_END; 
                   1741:   m[nrl] -= ncl; 
                   1742:   
                   1743:   for(i=nrl+1;i<=nrh;i++) m[i]=m[i-1]+ncol; 
                   1744:   
                   1745:   /* return pointer to array of pointers to rows */ 
                   1746:   return m; 
                   1747: } 
                   1748: 
                   1749: /****************** free_imatrix *************************/
                   1750: void free_imatrix(m,nrl,nrh,ncl,nch)
                   1751:       int **m;
                   1752:       long nch,ncl,nrh,nrl; 
                   1753:      /* free an int matrix allocated by imatrix() */ 
                   1754: { 
                   1755:   free((FREE_ARG) (m[nrl]+ncl-NR_END)); 
                   1756:   free((FREE_ARG) (m+nrl-NR_END)); 
                   1757: } 
                   1758: 
                   1759: /******************* matrix *******************************/
                   1760: double **matrix(long nrl, long nrh, long ncl, long nch)
                   1761: {
                   1762:   long i, nrow=nrh-nrl+1, ncol=nch-ncl+1;
                   1763:   double **m;
                   1764: 
                   1765:   m=(double **) malloc((size_t)((nrow+NR_END)*sizeof(double*)));
                   1766:   if (!m) nrerror("allocation failure 1 in matrix()");
                   1767:   m += NR_END;
                   1768:   m -= nrl;
                   1769: 
                   1770:   m[nrl]=(double *) malloc((size_t)((nrow*ncol+NR_END)*sizeof(double)));
                   1771:   if (!m[nrl]) nrerror("allocation failure 2 in matrix()");
                   1772:   m[nrl] += NR_END;
                   1773:   m[nrl] -= ncl;
                   1774: 
                   1775:   for (i=nrl+1; i<=nrh; i++) m[i]=m[i-1]+ncol;
                   1776:   return m;
1.145     brouard  1777:   /* print *(*(m+1)+70) or print m[1][70]; print m+1 or print &(m[1]) or &(m[1][0])
                   1778: m[i] = address of ith row of the table. &(m[i]) is its value which is another adress
                   1779: that of m[i][0]. In order to get the value p m[i][0] but it is unitialized.
1.126     brouard  1780:    */
                   1781: }
                   1782: 
                   1783: /*************************free matrix ************************/
                   1784: void free_matrix(double **m, long nrl, long nrh, long ncl, long nch)
                   1785: {
                   1786:   free((FREE_ARG)(m[nrl]+ncl-NR_END));
                   1787:   free((FREE_ARG)(m+nrl-NR_END));
                   1788: }
                   1789: 
                   1790: /******************* ma3x *******************************/
                   1791: double ***ma3x(long nrl, long nrh, long ncl, long nch, long nll, long nlh)
                   1792: {
                   1793:   long i, j, nrow=nrh-nrl+1, ncol=nch-ncl+1, nlay=nlh-nll+1;
                   1794:   double ***m;
                   1795: 
                   1796:   m=(double ***) malloc((size_t)((nrow+NR_END)*sizeof(double*)));
                   1797:   if (!m) nrerror("allocation failure 1 in matrix()");
                   1798:   m += NR_END;
                   1799:   m -= nrl;
                   1800: 
                   1801:   m[nrl]=(double **) malloc((size_t)((nrow*ncol+NR_END)*sizeof(double)));
                   1802:   if (!m[nrl]) nrerror("allocation failure 2 in matrix()");
                   1803:   m[nrl] += NR_END;
                   1804:   m[nrl] -= ncl;
                   1805: 
                   1806:   for (i=nrl+1; i<=nrh; i++) m[i]=m[i-1]+ncol;
                   1807: 
                   1808:   m[nrl][ncl]=(double *) malloc((size_t)((nrow*ncol*nlay+NR_END)*sizeof(double)));
                   1809:   if (!m[nrl][ncl]) nrerror("allocation failure 3 in matrix()");
                   1810:   m[nrl][ncl] += NR_END;
                   1811:   m[nrl][ncl] -= nll;
                   1812:   for (j=ncl+1; j<=nch; j++) 
                   1813:     m[nrl][j]=m[nrl][j-1]+nlay;
                   1814:   
                   1815:   for (i=nrl+1; i<=nrh; i++) {
                   1816:     m[i][ncl]=m[i-1l][ncl]+ncol*nlay;
                   1817:     for (j=ncl+1; j<=nch; j++) 
                   1818:       m[i][j]=m[i][j-1]+nlay;
                   1819:   }
                   1820:   return m; 
                   1821:   /*  gdb: p *(m+1) <=> p m[1] and p (m+1) <=> p (m+1) <=> p &(m[1])
                   1822:            &(m[i][j][k]) <=> *((*(m+i) + j)+k)
                   1823:   */
                   1824: }
                   1825: 
                   1826: /*************************free ma3x ************************/
                   1827: void free_ma3x(double ***m, long nrl, long nrh, long ncl, long nch,long nll, long nlh)
                   1828: {
                   1829:   free((FREE_ARG)(m[nrl][ncl]+ nll-NR_END));
                   1830:   free((FREE_ARG)(m[nrl]+ncl-NR_END));
                   1831:   free((FREE_ARG)(m+nrl-NR_END));
                   1832: }
                   1833: 
                   1834: /*************** function subdirf ***********/
                   1835: char *subdirf(char fileres[])
                   1836: {
                   1837:   /* Caution optionfilefiname is hidden */
                   1838:   strcpy(tmpout,optionfilefiname);
                   1839:   strcat(tmpout,"/"); /* Add to the right */
                   1840:   strcat(tmpout,fileres);
                   1841:   return tmpout;
                   1842: }
                   1843: 
                   1844: /*************** function subdirf2 ***********/
                   1845: char *subdirf2(char fileres[], char *preop)
                   1846: {
                   1847:   
                   1848:   /* Caution optionfilefiname is hidden */
                   1849:   strcpy(tmpout,optionfilefiname);
                   1850:   strcat(tmpout,"/");
                   1851:   strcat(tmpout,preop);
                   1852:   strcat(tmpout,fileres);
                   1853:   return tmpout;
                   1854: }
                   1855: 
                   1856: /*************** function subdirf3 ***********/
                   1857: char *subdirf3(char fileres[], char *preop, char *preop2)
                   1858: {
                   1859:   
                   1860:   /* Caution optionfilefiname is hidden */
                   1861:   strcpy(tmpout,optionfilefiname);
                   1862:   strcat(tmpout,"/");
                   1863:   strcat(tmpout,preop);
                   1864:   strcat(tmpout,preop2);
                   1865:   strcat(tmpout,fileres);
                   1866:   return tmpout;
                   1867: }
1.213     brouard  1868:  
                   1869: /*************** function subdirfext ***********/
                   1870: char *subdirfext(char fileres[], char *preop, char *postop)
                   1871: {
                   1872:   
                   1873:   strcpy(tmpout,preop);
                   1874:   strcat(tmpout,fileres);
                   1875:   strcat(tmpout,postop);
                   1876:   return tmpout;
                   1877: }
1.126     brouard  1878: 
1.213     brouard  1879: /*************** function subdirfext3 ***********/
                   1880: char *subdirfext3(char fileres[], char *preop, char *postop)
                   1881: {
                   1882:   
                   1883:   /* Caution optionfilefiname is hidden */
                   1884:   strcpy(tmpout,optionfilefiname);
                   1885:   strcat(tmpout,"/");
                   1886:   strcat(tmpout,preop);
                   1887:   strcat(tmpout,fileres);
                   1888:   strcat(tmpout,postop);
                   1889:   return tmpout;
                   1890: }
                   1891:  
1.162     brouard  1892: char *asc_diff_time(long time_sec, char ascdiff[])
                   1893: {
                   1894:   long sec_left, days, hours, minutes;
                   1895:   days = (time_sec) / (60*60*24);
                   1896:   sec_left = (time_sec) % (60*60*24);
                   1897:   hours = (sec_left) / (60*60) ;
                   1898:   sec_left = (sec_left) %(60*60);
                   1899:   minutes = (sec_left) /60;
                   1900:   sec_left = (sec_left) % (60);
                   1901:   sprintf(ascdiff,"%ld day(s) %ld hour(s) %ld minute(s) %ld second(s)",days, hours, minutes, sec_left);  
                   1902:   return ascdiff;
                   1903: }
                   1904: 
1.126     brouard  1905: /***************** f1dim *************************/
                   1906: extern int ncom; 
                   1907: extern double *pcom,*xicom;
                   1908: extern double (*nrfunc)(double []); 
                   1909:  
                   1910: double f1dim(double x) 
                   1911: { 
                   1912:   int j; 
                   1913:   double f;
                   1914:   double *xt; 
                   1915:  
                   1916:   xt=vector(1,ncom); 
                   1917:   for (j=1;j<=ncom;j++) xt[j]=pcom[j]+x*xicom[j]; 
                   1918:   f=(*nrfunc)(xt); 
                   1919:   free_vector(xt,1,ncom); 
                   1920:   return f; 
                   1921: } 
                   1922: 
                   1923: /*****************brent *************************/
                   1924: double brent(double ax, double bx, double cx, double (*f)(double), double tol,         double *xmin) 
1.187     brouard  1925: {
                   1926:   /* Given a function f, and given a bracketing triplet of abscissas ax, bx, cx (such that bx is
                   1927:    * between ax and cx, and f(bx) is less than both f(ax) and f(cx) ), this routine isolates
                   1928:    * the minimum to a fractional precision of about tol using Brent’s method. The abscissa of
                   1929:    * the minimum is returned as xmin, and the minimum function value is returned as brent , the
                   1930:    * returned function value. 
                   1931:   */
1.126     brouard  1932:   int iter; 
                   1933:   double a,b,d,etemp;
1.159     brouard  1934:   double fu=0,fv,fw,fx;
1.164     brouard  1935:   double ftemp=0.;
1.126     brouard  1936:   double p,q,r,tol1,tol2,u,v,w,x,xm; 
                   1937:   double e=0.0; 
                   1938:  
                   1939:   a=(ax < cx ? ax : cx); 
                   1940:   b=(ax > cx ? ax : cx); 
                   1941:   x=w=v=bx; 
                   1942:   fw=fv=fx=(*f)(x); 
                   1943:   for (iter=1;iter<=ITMAX;iter++) { 
                   1944:     xm=0.5*(a+b); 
                   1945:     tol2=2.0*(tol1=tol*fabs(x)+ZEPS); 
                   1946:     /*         if (2.0*fabs(fp-(*fret)) <= ftol*(fabs(fp)+fabs(*fret)))*/
                   1947:     printf(".");fflush(stdout);
                   1948:     fprintf(ficlog,".");fflush(ficlog);
1.162     brouard  1949: #ifdef DEBUGBRENT
1.126     brouard  1950:     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);
                   1951:     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);
                   1952:     /*         if ((fabs(x-xm) <= (tol2-0.5*(b-a)))||(2.0*fabs(fu-ftemp) <= ftol*1.e-2*(fabs(fu)+fabs(ftemp)))) { */
                   1953: #endif
                   1954:     if (fabs(x-xm) <= (tol2-0.5*(b-a))){ 
                   1955:       *xmin=x; 
                   1956:       return fx; 
                   1957:     } 
                   1958:     ftemp=fu;
                   1959:     if (fabs(e) > tol1) { 
                   1960:       r=(x-w)*(fx-fv); 
                   1961:       q=(x-v)*(fx-fw); 
                   1962:       p=(x-v)*q-(x-w)*r; 
                   1963:       q=2.0*(q-r); 
                   1964:       if (q > 0.0) p = -p; 
                   1965:       q=fabs(q); 
                   1966:       etemp=e; 
                   1967:       e=d; 
                   1968:       if (fabs(p) >= fabs(0.5*q*etemp) || p <= q*(a-x) || p >= q*(b-x)) 
1.224     brouard  1969:                                d=CGOLD*(e=(x >= xm ? a-x : b-x)); 
1.126     brouard  1970:       else { 
1.224     brouard  1971:                                d=p/q; 
                   1972:                                u=x+d; 
                   1973:                                if (u-a < tol2 || b-u < tol2) 
                   1974:                                        d=SIGN(tol1,xm-x); 
1.126     brouard  1975:       } 
                   1976:     } else { 
                   1977:       d=CGOLD*(e=(x >= xm ? a-x : b-x)); 
                   1978:     } 
                   1979:     u=(fabs(d) >= tol1 ? x+d : x+SIGN(tol1,d)); 
                   1980:     fu=(*f)(u); 
                   1981:     if (fu <= fx) { 
                   1982:       if (u >= x) a=x; else b=x; 
                   1983:       SHFT(v,w,x,u) 
1.183     brouard  1984:       SHFT(fv,fw,fx,fu) 
                   1985:     } else { 
                   1986:       if (u < x) a=u; else b=u; 
                   1987:       if (fu <= fw || w == x) { 
1.224     brouard  1988:                                v=w; 
                   1989:                                w=u; 
                   1990:                                fv=fw; 
                   1991:                                fw=fu; 
1.183     brouard  1992:       } else if (fu <= fv || v == x || v == w) { 
1.224     brouard  1993:                                v=u; 
                   1994:                                fv=fu; 
1.183     brouard  1995:       } 
                   1996:     } 
1.126     brouard  1997:   } 
                   1998:   nrerror("Too many iterations in brent"); 
                   1999:   *xmin=x; 
                   2000:   return fx; 
                   2001: } 
                   2002: 
                   2003: /****************** mnbrak ***********************/
                   2004: 
                   2005: void mnbrak(double *ax, double *bx, double *cx, double *fa, double *fb, double *fc, 
                   2006:            double (*func)(double)) 
1.183     brouard  2007: { /* Given a function func , and given distinct initial points ax and bx , this routine searches in
                   2008: the downhill direction (defined by the function as evaluated at the initial points) and returns
                   2009: new points ax , bx , cx that bracket a minimum of the function. Also returned are the function
                   2010: values at the three points, fa, fb , and fc such that fa > fb and fb < fc.
                   2011:    */
1.126     brouard  2012:   double ulim,u,r,q, dum;
                   2013:   double fu; 
1.187     brouard  2014: 
                   2015:   double scale=10.;
                   2016:   int iterscale=0;
                   2017: 
                   2018:   *fa=(*func)(*ax); /*  xta[j]=pcom[j]+(*ax)*xicom[j]; fa=f(xta[j])*/
                   2019:   *fb=(*func)(*bx); /*  xtb[j]=pcom[j]+(*bx)*xicom[j]; fb=f(xtb[j]) */
                   2020: 
                   2021: 
                   2022:   /* while(*fb != *fb){ /\* *ax should be ok, reducing distance to *ax *\/ */
                   2023:   /*   printf("Warning mnbrak *fb = %lf, *bx=%lf *ax=%lf *fa==%lf iter=%d\n",*fb, *bx, *ax, *fa, iterscale++); */
                   2024:   /*   *bx = *ax - (*ax - *bx)/scale; */
                   2025:   /*   *fb=(*func)(*bx);  /\*  xtb[j]=pcom[j]+(*bx)*xicom[j]; fb=f(xtb[j]) *\/ */
                   2026:   /* } */
                   2027: 
1.126     brouard  2028:   if (*fb > *fa) { 
                   2029:     SHFT(dum,*ax,*bx,dum) 
1.183     brouard  2030:     SHFT(dum,*fb,*fa,dum) 
                   2031:   } 
1.126     brouard  2032:   *cx=(*bx)+GOLD*(*bx-*ax); 
                   2033:   *fc=(*func)(*cx); 
1.183     brouard  2034: #ifdef DEBUG
1.224     brouard  2035:   printf("mnbrak0 a=%lf *fa=%lf, b=%lf *fb=%lf, c=%lf *fc=%lf\n",*ax,*fa,*bx,*fb,*cx, *fc);
                   2036:   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  2037: #endif
1.224     brouard  2038:   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  2039:     r=(*bx-*ax)*(*fb-*fc); 
1.224     brouard  2040:     q=(*bx-*cx)*(*fb-*fa); /* What if fa=inf */
1.126     brouard  2041:     u=(*bx)-((*bx-*cx)*q-(*bx-*ax)*r)/ 
1.183     brouard  2042:       (2.0*SIGN(FMAX(fabs(q-r),TINY),q-r)); /* Minimum abscissa of a parabolic estimated from (a,fa), (b,fb) and (c,fc). */
                   2043:     ulim=(*bx)+GLIMIT*(*cx-*bx); /* Maximum abscissa where function should be evaluated */
                   2044:     if ((*bx-u)*(u-*cx) > 0.0) { /* if u_p is between b and c */
1.126     brouard  2045:       fu=(*func)(u); 
1.163     brouard  2046: #ifdef DEBUG
                   2047:       /* f(x)=A(x-u)**2+f(u) */
                   2048:       double A, fparabu; 
                   2049:       A= (*fb - *fa)/(*bx-*ax)/(*bx+*ax-2*u);
                   2050:       fparabu= *fa - A*(*ax-u)*(*ax-u);
1.224     brouard  2051:       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);
                   2052:       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  2053:       /* And thus,it can be that fu > *fc even if fparabu < *fc */
                   2054:       /* mnbrak (*ax=7.666299858533, *fa=299039.693133272231), (*bx=8.595447774979, *fb=298976.598289369489),
                   2055:         (*cx=10.098840694817, *fc=298946.631474258087),  (*u=9.852501168332, fu=298948.773013752128, fparabu=298945.434711494134) */
                   2056:       /* In that case, there is no bracket in the output! Routine is wrong with many consequences.*/
1.163     brouard  2057: #endif 
1.184     brouard  2058: #ifdef MNBRAKORIGINAL
1.183     brouard  2059: #else
1.191     brouard  2060: /*       if (fu > *fc) { */
                   2061: /* #ifdef DEBUG */
                   2062: /*       printf("mnbrak4  fu > fc \n"); */
                   2063: /*       fprintf(ficlog, "mnbrak4 fu > fc\n"); */
                   2064: /* #endif */
                   2065: /*     /\* 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 *\\/  *\/ */
                   2066: /*     /\* SHFT(*fa,*fc,fu,*fc) /\\* (b, u, c) is a bracket while test fb > fc will be fu > fc  will exit *\\/ *\/ */
                   2067: /*     dum=u; /\* Shifting c and u *\/ */
                   2068: /*     u = *cx; */
                   2069: /*     *cx = dum; */
                   2070: /*     dum = fu; */
                   2071: /*     fu = *fc; */
                   2072: /*     *fc =dum; */
                   2073: /*       } else { /\* end *\/ */
                   2074: /* #ifdef DEBUG */
                   2075: /*       printf("mnbrak3  fu < fc \n"); */
                   2076: /*       fprintf(ficlog, "mnbrak3 fu < fc\n"); */
                   2077: /* #endif */
                   2078: /*     dum=u; /\* Shifting c and u *\/ */
                   2079: /*     u = *cx; */
                   2080: /*     *cx = dum; */
                   2081: /*     dum = fu; */
                   2082: /*     fu = *fc; */
                   2083: /*     *fc =dum; */
                   2084: /*       } */
1.224     brouard  2085: #ifdef DEBUGMNBRAK
                   2086:                 double A, fparabu; 
                   2087:      A= (*fb - *fa)/(*bx-*ax)/(*bx+*ax-2*u);
                   2088:      fparabu= *fa - A*(*ax-u)*(*ax-u);
                   2089:      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);
                   2090:      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  2091: #endif
1.191     brouard  2092:       dum=u; /* Shifting c and u */
                   2093:       u = *cx;
                   2094:       *cx = dum;
                   2095:       dum = fu;
                   2096:       fu = *fc;
                   2097:       *fc =dum;
1.183     brouard  2098: #endif
1.162     brouard  2099:     } else if ((*cx-u)*(u-ulim) > 0.0) { /* u is after c but before ulim */
1.183     brouard  2100: #ifdef DEBUG
1.224     brouard  2101:       printf("\nmnbrak2  u=%lf after c=%lf but before ulim\n",u,*cx);
                   2102:       fprintf(ficlog,"\nmnbrak2  u=%lf after c=%lf but before ulim\n",u,*cx);
1.183     brouard  2103: #endif
1.126     brouard  2104:       fu=(*func)(u); 
                   2105:       if (fu < *fc) { 
1.183     brouard  2106: #ifdef DEBUG
1.224     brouard  2107:                                printf("\nmnbrak2  u=%lf after c=%lf but before ulim=%lf AND fu=%lf < %lf=fc\n",u,*cx,ulim,fu, *fc);
                   2108:                          fprintf(ficlog,"\nmnbrak2  u=%lf after c=%lf but before ulim=%lf AND fu=%lf < %lf=fc\n",u,*cx,ulim,fu, *fc);
                   2109: #endif
                   2110:                          SHFT(*bx,*cx,u,*cx+GOLD*(*cx-*bx)) 
                   2111:                                SHFT(*fb,*fc,fu,(*func)(u)) 
                   2112: #ifdef DEBUG
                   2113:                                        printf("\nmnbrak2 shift GOLD c=%lf",*cx+GOLD*(*cx-*bx));
1.183     brouard  2114: #endif
                   2115:       } 
1.162     brouard  2116:     } else if ((u-ulim)*(ulim-*cx) >= 0.0) { /* u outside ulim (verifying that ulim is beyond c) */
1.183     brouard  2117: #ifdef DEBUG
1.224     brouard  2118:       printf("\nmnbrak2  u=%lf outside ulim=%lf (verifying that ulim is beyond c=%lf)\n",u,ulim,*cx);
                   2119:       fprintf(ficlog,"\nmnbrak2  u=%lf outside ulim=%lf (verifying that ulim is beyond c=%lf)\n",u,ulim,*cx);
1.183     brouard  2120: #endif
1.126     brouard  2121:       u=ulim; 
                   2122:       fu=(*func)(u); 
1.183     brouard  2123:     } else { /* u could be left to b (if r > q parabola has a maximum) */
                   2124: #ifdef DEBUG
1.224     brouard  2125:       printf("\nmnbrak2  u=%lf could be left to b=%lf (if r=%lf > q=%lf parabola has a maximum)\n",u,*bx,r,q);
                   2126:       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  2127: #endif
1.126     brouard  2128:       u=(*cx)+GOLD*(*cx-*bx); 
                   2129:       fu=(*func)(u); 
1.224     brouard  2130: #ifdef DEBUG
                   2131:       printf("\nmnbrak2 new u=%lf fu=%lf shifted gold left from c=%lf and b=%lf \n",u,fu,*cx,*bx);
                   2132:       fprintf(ficlog,"\nmnbrak2 new u=%lf fu=%lf shifted gold left from c=%lf and b=%lf \n",u,fu,*cx,*bx);
                   2133: #endif
1.183     brouard  2134:     } /* end tests */
1.126     brouard  2135:     SHFT(*ax,*bx,*cx,u) 
1.183     brouard  2136:     SHFT(*fa,*fb,*fc,fu) 
                   2137: #ifdef DEBUG
1.224     brouard  2138:       printf("\nmnbrak2 shift (*ax=%.12f, *fa=%.12lf), (*bx=%.12f, *fb=%.12lf), (*cx=%.12f, *fc=%.12lf)\n",*ax,*fa,*bx,*fb,*cx,*fc);
                   2139:       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  2140: #endif
                   2141:   } /* 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  2142: } 
                   2143: 
                   2144: /*************** linmin ************************/
1.162     brouard  2145: /* Given an n -dimensional point p[1..n] and an n -dimensional direction xi[1..n] , moves and
                   2146: resets p to where the function func(p) takes on a minimum along the direction xi from p ,
                   2147: and replaces xi by the actual vector displacement that p was moved. Also returns as fret
                   2148: the value of func at the returned location p . This is actually all accomplished by calling the
                   2149: routines mnbrak and brent .*/
1.126     brouard  2150: int ncom; 
                   2151: double *pcom,*xicom;
                   2152: double (*nrfunc)(double []); 
                   2153:  
1.224     brouard  2154: #ifdef LINMINORIGINAL
1.126     brouard  2155: void linmin(double p[], double xi[], int n, double *fret,double (*func)(double [])) 
1.224     brouard  2156: #else
                   2157: void linmin(double p[], double xi[], int n, double *fret,double (*func)(double []), int *flat) 
                   2158: #endif
1.126     brouard  2159: { 
                   2160:   double brent(double ax, double bx, double cx, 
                   2161:               double (*f)(double), double tol, double *xmin); 
                   2162:   double f1dim(double x); 
                   2163:   void mnbrak(double *ax, double *bx, double *cx, double *fa, double *fb, 
                   2164:              double *fc, double (*func)(double)); 
                   2165:   int j; 
                   2166:   double xx,xmin,bx,ax; 
                   2167:   double fx,fb,fa;
1.187     brouard  2168: 
1.203     brouard  2169: #ifdef LINMINORIGINAL
                   2170: #else
                   2171:   double scale=10., axs, xxs; /* Scale added for infinity */
                   2172: #endif
                   2173:   
1.126     brouard  2174:   ncom=n; 
                   2175:   pcom=vector(1,n); 
                   2176:   xicom=vector(1,n); 
                   2177:   nrfunc=func; 
                   2178:   for (j=1;j<=n;j++) { 
                   2179:     pcom[j]=p[j]; 
1.202     brouard  2180:     xicom[j]=xi[j]; /* Former scale xi[j] of currrent direction i */
1.126     brouard  2181:   } 
1.187     brouard  2182: 
1.203     brouard  2183: #ifdef LINMINORIGINAL
                   2184:   xx=1.;
                   2185: #else
                   2186:   axs=0.0;
                   2187:   xxs=1.;
                   2188:   do{
                   2189:     xx= xxs;
                   2190: #endif
1.187     brouard  2191:     ax=0.;
                   2192:     mnbrak(&ax,&xx,&bx,&fa,&fx,&fb,f1dim);  /* Outputs: xtx[j]=pcom[j]+(*xx)*xicom[j]; fx=f(xtx[j]) */
                   2193:     /* brackets with inputs ax=0 and xx=1, but points, pcom=p, and directions values, xicom=xi, are sent via f1dim(x) */
                   2194:     /* 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))   */
                   2195:     /* Outputs: fa=f(p(j)) and fx=f(p(j) + xxs * xi(j) ) and f(bx)= f(p(j)+ bx* xi(j)) */
                   2196:     /* Given input ax=axs and xx=xxs, xx might be too far from ax to get a finite f(xx) */
                   2197:     /* Searches on line, outputs (ax, xx, bx) such that fx < min(fa and fb) */
                   2198:     /* 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  2199: #ifdef LINMINORIGINAL
                   2200: #else
                   2201:     if (fx != fx){
1.224     brouard  2202:                        xxs=xxs/scale; /* Trying a smaller xx, closer to initial ax=0 */
                   2203:                        printf("|");
                   2204:                        fprintf(ficlog,"|");
1.203     brouard  2205: #ifdef DEBUGLINMIN
1.224     brouard  2206:                        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  2207: #endif
                   2208:     }
1.224     brouard  2209:   }while(fx != fx && xxs > 1.e-5);
1.203     brouard  2210: #endif
                   2211:   
1.191     brouard  2212: #ifdef DEBUGLINMIN
                   2213:   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  2214:   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  2215: #endif
1.224     brouard  2216: #ifdef LINMINORIGINAL
                   2217: #else
                   2218:        if(fb == fx){ /* Flat function in the direction */
                   2219:                xmin=xx;
                   2220:     *flat=1;
                   2221:        }else{
                   2222:     *flat=0;
                   2223: #endif
                   2224:                /*Flat mnbrak2 shift (*ax=0.000000000000, *fa=51626.272983130431), (*bx=-1.618034000000, *fb=51590.149499362531), (*cx=-4.236068025156, *fc=51590.149499362531) */
1.187     brouard  2225:   *fret=brent(ax,xx,bx,f1dim,TOL,&xmin); /* Giving a bracketting triplet (ax, xx, bx), find a minimum, xmin, according to f1dim, *fret(xmin),*/
                   2226:   /* fa = f(p[j] + ax * xi[j]), fx = f(p[j] + xx * xi[j]), fb = f(p[j] + bx * xi[j]) */
                   2227:   /* fmin = f(p[j] + xmin * xi[j]) */
                   2228:   /* P+lambda n in that direction (lambdamin), with TOL between abscisses */
                   2229:   /* f1dim(xmin): for (j=1;j<=ncom;j++) xt[j]=pcom[j]+xmin*xicom[j]; */
1.126     brouard  2230: #ifdef DEBUG
1.224     brouard  2231:   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);
                   2232:   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);
                   2233: #endif
                   2234: #ifdef LINMINORIGINAL
                   2235: #else
                   2236:                        }
1.126     brouard  2237: #endif
1.191     brouard  2238: #ifdef DEBUGLINMIN
                   2239:   printf("linmin end ");
1.202     brouard  2240:   fprintf(ficlog,"linmin end ");
1.191     brouard  2241: #endif
1.126     brouard  2242:   for (j=1;j<=n;j++) { 
1.203     brouard  2243: #ifdef LINMINORIGINAL
                   2244:     xi[j] *= xmin; 
                   2245: #else
                   2246: #ifdef DEBUGLINMIN
                   2247:     if(xxs <1.0)
                   2248:       printf(" before xi[%d]=%12.8f", j,xi[j]);
                   2249: #endif
                   2250:     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) */
                   2251: #ifdef DEBUGLINMIN
                   2252:     if(xxs <1.0)
                   2253:       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 );
                   2254: #endif
                   2255: #endif
1.187     brouard  2256:     p[j] += xi[j]; /* Parameters values are updated accordingly */
1.126     brouard  2257:   } 
1.191     brouard  2258: #ifdef DEBUGLINMIN
1.203     brouard  2259:   printf("\n");
1.191     brouard  2260:   printf("Comparing last *frec(xmin=%12.8f)=%12.8f from Brent and frec(0.)=%12.8f \n", xmin, *fret, (*func)(p));
1.202     brouard  2261:   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  2262:   for (j=1;j<=n;j++) { 
1.202     brouard  2263:     printf(" xi[%d]= %14.10f p[%d]= %12.7f",j,xi[j],j,p[j]);
                   2264:     fprintf(ficlog," xi[%d]= %14.10f p[%d]= %12.7f",j,xi[j],j,p[j]);
                   2265:     if(j % ncovmodel == 0){
1.191     brouard  2266:       printf("\n");
1.202     brouard  2267:       fprintf(ficlog,"\n");
                   2268:     }
1.191     brouard  2269:   }
1.203     brouard  2270: #else
1.191     brouard  2271: #endif
1.126     brouard  2272:   free_vector(xicom,1,n); 
                   2273:   free_vector(pcom,1,n); 
                   2274: } 
                   2275: 
                   2276: 
                   2277: /*************** powell ************************/
1.162     brouard  2278: /*
                   2279: Minimization of a function func of n variables. Input consists of an initial starting point
                   2280: p[1..n] ; an initial matrix xi[1..n][1..n] , whose columns contain the initial set of di-
                   2281: rections (usually the n unit vectors); and ftol , the fractional tolerance in the function value
                   2282: such that failure to decrease by more than this amount on one iteration signals doneness. On
                   2283: output, p is set to the best point found, xi is the then-current direction set, fret is the returned
                   2284: function value at p , and iter is the number of iterations taken. The routine linmin is used.
                   2285:  */
1.224     brouard  2286: #ifdef LINMINORIGINAL
                   2287: #else
                   2288:        int *flatdir; /* Function is vanishing in that direction */
1.225     brouard  2289:        int flat=0, flatd=0; /* Function is vanishing in that direction */
1.224     brouard  2290: #endif
1.126     brouard  2291: void powell(double p[], double **xi, int n, double ftol, int *iter, double *fret, 
                   2292:            double (*func)(double [])) 
                   2293: { 
1.224     brouard  2294: #ifdef LINMINORIGINAL
                   2295:  void linmin(double p[], double xi[], int n, double *fret, 
1.126     brouard  2296:              double (*func)(double [])); 
1.224     brouard  2297: #else 
1.241     brouard  2298:  void linmin(double p[], double xi[], int n, double *fret,
                   2299:             double (*func)(double []),int *flat); 
1.224     brouard  2300: #endif
1.239     brouard  2301:  int i,ibig,j,jk,k; 
1.126     brouard  2302:   double del,t,*pt,*ptt,*xit;
1.181     brouard  2303:   double directest;
1.126     brouard  2304:   double fp,fptt;
                   2305:   double *xits;
                   2306:   int niterf, itmp;
1.224     brouard  2307: #ifdef LINMINORIGINAL
                   2308: #else
                   2309: 
                   2310:   flatdir=ivector(1,n); 
                   2311:   for (j=1;j<=n;j++) flatdir[j]=0; 
                   2312: #endif
1.126     brouard  2313: 
                   2314:   pt=vector(1,n); 
                   2315:   ptt=vector(1,n); 
                   2316:   xit=vector(1,n); 
                   2317:   xits=vector(1,n); 
                   2318:   *fret=(*func)(p); 
                   2319:   for (j=1;j<=n;j++) pt[j]=p[j]; 
1.202     brouard  2320:   rcurr_time = time(NULL);  
1.126     brouard  2321:   for (*iter=1;;++(*iter)) { 
1.187     brouard  2322:     fp=(*fret); /* From former iteration or initial value */
1.126     brouard  2323:     ibig=0; 
                   2324:     del=0.0; 
1.157     brouard  2325:     rlast_time=rcurr_time;
                   2326:     /* (void) gettimeofday(&curr_time,&tzp); */
                   2327:     rcurr_time = time(NULL);  
                   2328:     curr_time = *localtime(&rcurr_time);
                   2329:     printf("\nPowell iter=%d -2*LL=%.12f %ld sec. %ld sec.",*iter,*fret, rcurr_time-rlast_time, rcurr_time-rstart_time);fflush(stdout);
                   2330:     fprintf(ficlog,"\nPowell iter=%d -2*LL=%.12f %ld sec. %ld sec.",*iter,*fret,rcurr_time-rlast_time, rcurr_time-rstart_time); fflush(ficlog);
                   2331: /*     fprintf(ficrespow,"%d %.12f %ld",*iter,*fret,curr_time.tm_sec-start_time.tm_sec); */
1.192     brouard  2332:     for (i=1;i<=n;i++) {
1.126     brouard  2333:       fprintf(ficrespow," %.12lf", p[i]);
                   2334:     }
1.239     brouard  2335:     fprintf(ficrespow,"\n");fflush(ficrespow);
                   2336:     printf("\n#model=  1      +     age ");
                   2337:     fprintf(ficlog,"\n#model=  1      +     age ");
                   2338:     if(nagesqr==1){
1.241     brouard  2339:        printf("  + age*age  ");
                   2340:        fprintf(ficlog,"  + age*age  ");
1.239     brouard  2341:     }
                   2342:     for(j=1;j <=ncovmodel-2;j++){
                   2343:       if(Typevar[j]==0) {
                   2344:        printf("  +      V%d  ",Tvar[j]);
                   2345:        fprintf(ficlog,"  +      V%d  ",Tvar[j]);
                   2346:       }else if(Typevar[j]==1) {
                   2347:        printf("  +    V%d*age ",Tvar[j]);
                   2348:        fprintf(ficlog,"  +    V%d*age ",Tvar[j]);
                   2349:       }else if(Typevar[j]==2) {
                   2350:        printf("  +    V%d*V%d ",Tvard[Tposprod[j]][1],Tvard[Tposprod[j]][2]);
                   2351:        fprintf(ficlog,"  +    V%d*V%d ",Tvard[Tposprod[j]][1],Tvard[Tposprod[j]][2]);
                   2352:       }
                   2353:     }
1.126     brouard  2354:     printf("\n");
1.239     brouard  2355: /*     printf("12   47.0114589    0.0154322   33.2424412    0.3279905    2.3731903  */
                   2356: /* 13  -21.5392400    0.1118147    1.2680506    1.2973408   -1.0663662  */
1.126     brouard  2357:     fprintf(ficlog,"\n");
1.239     brouard  2358:     for(i=1,jk=1; i <=nlstate; i++){
                   2359:       for(k=1; k <=(nlstate+ndeath); k++){
                   2360:        if (k != i) {
                   2361:          printf("%d%d ",i,k);
                   2362:          fprintf(ficlog,"%d%d ",i,k);
                   2363:          for(j=1; j <=ncovmodel; j++){
                   2364:            printf("%12.7f ",p[jk]);
                   2365:            fprintf(ficlog,"%12.7f ",p[jk]);
                   2366:            jk++; 
                   2367:          }
                   2368:          printf("\n");
                   2369:          fprintf(ficlog,"\n");
                   2370:        }
                   2371:       }
                   2372:     }
1.241     brouard  2373:     if(*iter <=3 && *iter >1){
1.157     brouard  2374:       tml = *localtime(&rcurr_time);
                   2375:       strcpy(strcurr,asctime(&tml));
                   2376:       rforecast_time=rcurr_time; 
1.126     brouard  2377:       itmp = strlen(strcurr);
                   2378:       if(strcurr[itmp-1]=='\n')  /* Windows outputs with a new line */
1.241     brouard  2379:        strcurr[itmp-1]='\0';
1.162     brouard  2380:       printf("\nConsidering the time needed for the last iteration #%d: %ld seconds,\n",*iter,rcurr_time-rlast_time);
1.157     brouard  2381:       fprintf(ficlog,"\nConsidering the time needed for this last iteration #%d: %ld seconds,\n",*iter,rcurr_time-rlast_time);
1.126     brouard  2382:       for(niterf=10;niterf<=30;niterf+=10){
1.241     brouard  2383:        rforecast_time=rcurr_time+(niterf-*iter)*(rcurr_time-rlast_time);
                   2384:        forecast_time = *localtime(&rforecast_time);
                   2385:        strcpy(strfor,asctime(&forecast_time));
                   2386:        itmp = strlen(strfor);
                   2387:        if(strfor[itmp-1]=='\n')
                   2388:          strfor[itmp-1]='\0';
                   2389:        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);
                   2390:        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  2391:       }
                   2392:     }
1.187     brouard  2393:     for (i=1;i<=n;i++) { /* For each direction i */
                   2394:       for (j=1;j<=n;j++) xit[j]=xi[j][i]; /* Directions stored from previous iteration with previous scales */
1.126     brouard  2395:       fptt=(*fret); 
                   2396: #ifdef DEBUG
1.203     brouard  2397:       printf("fret=%lf, %lf, %lf \n", *fret, *fret, *fret);
                   2398:       fprintf(ficlog, "fret=%lf, %lf, %lf \n", *fret, *fret, *fret);
1.126     brouard  2399: #endif
1.203     brouard  2400:       printf("%d",i);fflush(stdout); /* print direction (parameter) i */
1.126     brouard  2401:       fprintf(ficlog,"%d",i);fflush(ficlog);
1.224     brouard  2402: #ifdef LINMINORIGINAL
1.188     brouard  2403:       linmin(p,xit,n,fret,func); /* Point p[n]. xit[n] has been loaded for direction i as input.*/
1.224     brouard  2404: #else
                   2405:       linmin(p,xit,n,fret,func,&flat); /* Point p[n]. xit[n] has been loaded for direction i as input.*/
                   2406:                        flatdir[i]=flat; /* Function is vanishing in that direction i */
                   2407: #endif
                   2408:                        /* Outputs are fret(new point p) p is updated and xit rescaled */
1.188     brouard  2409:       if (fabs(fptt-(*fret)) > del) { /* We are keeping the max gain on each of the n directions */
1.224     brouard  2410:                                /* because that direction will be replaced unless the gain del is small */
                   2411:                                /* in comparison with the 'probable' gain, mu^2, with the last average direction. */
                   2412:                                /* Unless the n directions are conjugate some gain in the determinant may be obtained */
                   2413:                                /* with the new direction. */
                   2414:                                del=fabs(fptt-(*fret)); 
                   2415:                                ibig=i; 
1.126     brouard  2416:       } 
                   2417: #ifdef DEBUG
                   2418:       printf("%d %.12e",i,(*fret));
                   2419:       fprintf(ficlog,"%d %.12e",i,(*fret));
                   2420:       for (j=1;j<=n;j++) {
1.224     brouard  2421:                                xits[j]=FMAX(fabs(p[j]-pt[j]),1.e-5);
                   2422:                                printf(" x(%d)=%.12e",j,xit[j]);
                   2423:                                fprintf(ficlog," x(%d)=%.12e",j,xit[j]);
1.126     brouard  2424:       }
                   2425:       for(j=1;j<=n;j++) {
1.225     brouard  2426:                                printf(" p(%d)=%.12e",j,p[j]);
                   2427:                                fprintf(ficlog," p(%d)=%.12e",j,p[j]);
1.126     brouard  2428:       }
                   2429:       printf("\n");
                   2430:       fprintf(ficlog,"\n");
                   2431: #endif
1.187     brouard  2432:     } /* end loop on each direction i */
                   2433:     /* Convergence test will use last linmin estimation (fret) and compare former iteration (fp) */ 
1.188     brouard  2434:     /* But p and xit have been updated at the end of linmin, *fret corresponds to new p, xit  */
1.187     brouard  2435:     /* New value of last point Pn is not computed, P(n-1) */
1.224     brouard  2436:       for(j=1;j<=n;j++) {
1.302     brouard  2437:        if(flatdir[j] >0){
                   2438:          printf(" p(%d)=%lf flat=%d ",j,p[j],flatdir[j]);
                   2439:          fprintf(ficlog," p(%d)=%lf flat=%d ",j,p[j],flatdir[j]);
                   2440:        }
                   2441:        /* printf("\n"); */
                   2442:        /* fprintf(ficlog,"\n"); */
                   2443:       }
1.243     brouard  2444:     /* if (2.0*fabs(fp-(*fret)) <= ftol*(fabs(fp)+fabs(*fret))) { /\* Did we reach enough precision? *\/ */
                   2445:     if (2.0*fabs(fp-(*fret)) <= ftol) { /* Did we reach enough precision? */
1.188     brouard  2446:       /* We could compare with a chi^2. chisquare(0.95,ddl=1)=3.84 */
                   2447:       /* By adding age*age in a model, the new -2LL should be lower and the difference follows a */
                   2448:       /* a chisquare statistics with 1 degree. To be significant at the 95% level, it should have */
                   2449:       /* decreased of more than 3.84  */
                   2450:       /* By adding age*age and V1*age the gain (-2LL) should be more than 5.99 (ddl=2) */
                   2451:       /* By using V1+V2+V3, the gain should be  7.82, compared with basic 1+age. */
                   2452:       /* By adding 10 parameters more the gain should be 18.31 */
1.224     brouard  2453:                        
1.188     brouard  2454:       /* Starting the program with initial values given by a former maximization will simply change */
                   2455:       /* the scales of the directions and the directions, because the are reset to canonical directions */
                   2456:       /* Thus the first calls to linmin will give new points and better maximizations until fp-(*fret) is */
                   2457:       /* under the tolerance value. If the tolerance is very small 1.e-9, it could last long.  */
1.126     brouard  2458: #ifdef DEBUG
                   2459:       int k[2],l;
                   2460:       k[0]=1;
                   2461:       k[1]=-1;
                   2462:       printf("Max: %.12e",(*func)(p));
                   2463:       fprintf(ficlog,"Max: %.12e",(*func)(p));
                   2464:       for (j=1;j<=n;j++) {
                   2465:        printf(" %.12e",p[j]);
                   2466:        fprintf(ficlog," %.12e",p[j]);
                   2467:       }
                   2468:       printf("\n");
                   2469:       fprintf(ficlog,"\n");
                   2470:       for(l=0;l<=1;l++) {
                   2471:        for (j=1;j<=n;j++) {
                   2472:          ptt[j]=p[j]+(p[j]-pt[j])*k[l];
                   2473:          printf("l=%d j=%d ptt=%.12e, xits=%.12e, p=%.12e, xit=%.12e", l,j,ptt[j],xits[j],p[j],xit[j]);
                   2474:          fprintf(ficlog,"l=%d j=%d ptt=%.12e, xits=%.12e, p=%.12e, xit=%.12e", l,j,ptt[j],xits[j],p[j],xit[j]);
                   2475:        }
                   2476:        printf("func(ptt)=%.12e, deriv=%.12e\n",(*func)(ptt),(ptt[j]-p[j])/((*func)(ptt)-(*func)(p)));
                   2477:        fprintf(ficlog,"func(ptt)=%.12e, deriv=%.12e\n",(*func)(ptt),(ptt[j]-p[j])/((*func)(ptt)-(*func)(p)));
                   2478:       }
                   2479: #endif
                   2480: 
1.224     brouard  2481: #ifdef LINMINORIGINAL
                   2482: #else
                   2483:       free_ivector(flatdir,1,n); 
                   2484: #endif
1.126     brouard  2485:       free_vector(xit,1,n); 
                   2486:       free_vector(xits,1,n); 
                   2487:       free_vector(ptt,1,n); 
                   2488:       free_vector(pt,1,n); 
                   2489:       return; 
1.192     brouard  2490:     } /* enough precision */ 
1.240     brouard  2491:     if (*iter == ITMAX*n) nrerror("powell exceeding maximum iterations."); 
1.181     brouard  2492:     for (j=1;j<=n;j++) { /* Computes the extrapolated point P_0 + 2 (P_n-P_0) */
1.126     brouard  2493:       ptt[j]=2.0*p[j]-pt[j]; 
                   2494:       xit[j]=p[j]-pt[j]; 
                   2495:       pt[j]=p[j]; 
                   2496:     } 
1.181     brouard  2497:     fptt=(*func)(ptt); /* f_3 */
1.224     brouard  2498: #ifdef NODIRECTIONCHANGEDUNTILNITER  /* No change in drections until some iterations are done */
                   2499:                if (*iter <=4) {
1.225     brouard  2500: #else
                   2501: #endif
1.224     brouard  2502: #ifdef POWELLNOF3INFF1TEST    /* skips test F3 <F1 */
1.192     brouard  2503: #else
1.161     brouard  2504:     if (fptt < fp) { /* If extrapolated point is better, decide if we keep that new direction or not */
1.192     brouard  2505: #endif
1.162     brouard  2506:       /* (x1 f1=fp), (x2 f2=*fret), (x3 f3=fptt), (xm fm) */
1.161     brouard  2507:       /* From x1 (P0) distance of x2 is at h and x3 is 2h */
1.162     brouard  2508:       /* Let f"(x2) be the 2nd derivative equal everywhere.  */
                   2509:       /* Then the parabolic through (x1,f1), (x2,f2) and (x3,f3) */
                   2510:       /* will reach at f3 = fm + h^2/2 f"m  ; f" = (f1 -2f2 +f3 ) / h**2 */
1.224     brouard  2511:       /* Conditional for using this new direction is that mu^2 = (f1-2f2+f3)^2 /2 < del or directest <0 */
                   2512:       /* also  lamda^2=(f1-f2)^2/mu² is a parasite solution of powell */
                   2513:       /* For powell, inclusion of this average direction is only if t(del)<0 or del inbetween mu^2 and lambda^2 */
1.161     brouard  2514:       /* t=2.0*(fp-2.0*(*fret)+fptt)*SQR(fp-(*fret)-del)-del*SQR(fp-fptt); */
1.224     brouard  2515:       /*  Even if f3 <f1, directest can be negative and t >0 */
                   2516:       /* mu² and del² are equal when f3=f1 */
                   2517:                        /* f3 < f1 : mu² < del <= lambda^2 both test are equivalent */
                   2518:                        /* f3 < f1 : mu² < lambda^2 < del then directtest is negative and powell t is positive */
                   2519:                        /* f3 > f1 : lambda² < mu^2 < del then t is negative and directest >0  */
                   2520:                        /* f3 > f1 : lambda² < del < mu^2 then t is positive and directest >0  */
1.183     brouard  2521: #ifdef NRCORIGINAL
                   2522:       t=2.0*(fp-2.0*(*fret)+fptt)*SQR(fp-(*fret)-del)- del*SQR(fp-fptt); /* Original Numerical Recipes in C*/
                   2523: #else
                   2524:       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  2525:       t= t- del*SQR(fp-fptt);
1.183     brouard  2526: #endif
1.202     brouard  2527:       directest = fp-2.0*(*fret)+fptt - 2.0 * del; /* If delta was big enough we change it for a new direction */
1.161     brouard  2528: #ifdef DEBUG
1.181     brouard  2529:       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);
                   2530:       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  2531:       printf("t3= %.12lf, t4= %.12lf, t3*= %.12lf, t4*= %.12lf\n",SQR(fp-(*fret)-del),SQR(fp-fptt),
                   2532:             (fp-(*fret)-del)*(fp-(*fret)-del),(fp-fptt)*(fp-fptt));
                   2533:       fprintf(ficlog,"t3= %.12lf, t4= %.12lf, t3*= %.12lf, t4*= %.12lf\n",SQR(fp-(*fret)-del),SQR(fp-fptt),
                   2534:             (fp-(*fret)-del)*(fp-(*fret)-del),(fp-fptt)*(fp-fptt));
                   2535:       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);
                   2536:       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);
                   2537: #endif
1.183     brouard  2538: #ifdef POWELLORIGINAL
                   2539:       if (t < 0.0) { /* Then we use it for new direction */
                   2540: #else
1.182     brouard  2541:       if (directest*t < 0.0) { /* Contradiction between both tests */
1.224     brouard  2542:                                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  2543:         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  2544:         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  2545:         fprintf(ficlog,"f1-2f2+f3= %.12lf, f1-f2-del= %.12lf, f1-f3= %.12lf\n",fp-2.0*(*fret)+fptt, fp -(*fret) -del, fp-fptt);
                   2546:       } 
1.181     brouard  2547:       if (directest < 0.0) { /* Then we use it for new direction */
                   2548: #endif
1.191     brouard  2549: #ifdef DEBUGLINMIN
1.234     brouard  2550:        printf("Before linmin in direction P%d-P0\n",n);
                   2551:        for (j=1;j<=n;j++) {
                   2552:          printf(" Before xit[%d]= %12.7f p[%d]= %12.7f",j,xit[j],j,p[j]);
                   2553:          fprintf(ficlog," Before xit[%d]= %12.7f p[%d]= %12.7f",j,xit[j],j,p[j]);
                   2554:          if(j % ncovmodel == 0){
                   2555:            printf("\n");
                   2556:            fprintf(ficlog,"\n");
                   2557:          }
                   2558:        }
1.224     brouard  2559: #endif
                   2560: #ifdef LINMINORIGINAL
1.234     brouard  2561:        linmin(p,xit,n,fret,func); /* computes minimum on the extrapolated direction: changes p and rescales xit.*/
1.224     brouard  2562: #else
1.234     brouard  2563:        linmin(p,xit,n,fret,func,&flat); /* computes minimum on the extrapolated direction: changes p and rescales xit.*/
                   2564:        flatdir[i]=flat; /* Function is vanishing in that direction i */
1.191     brouard  2565: #endif
1.234     brouard  2566:        
1.191     brouard  2567: #ifdef DEBUGLINMIN
1.234     brouard  2568:        for (j=1;j<=n;j++) { 
                   2569:          printf("After xit[%d]= %12.7f p[%d]= %12.7f",j,xit[j],j,p[j]);
                   2570:          fprintf(ficlog,"After xit[%d]= %12.7f p[%d]= %12.7f",j,xit[j],j,p[j]);
                   2571:          if(j % ncovmodel == 0){
                   2572:            printf("\n");
                   2573:            fprintf(ficlog,"\n");
                   2574:          }
                   2575:        }
1.224     brouard  2576: #endif
1.234     brouard  2577:        for (j=1;j<=n;j++) { 
                   2578:          xi[j][ibig]=xi[j][n]; /* Replace direction with biggest decrease by last direction n */
                   2579:          xi[j][n]=xit[j];      /* and this nth direction by the by the average p_0 p_n */
                   2580:        }
1.224     brouard  2581: #ifdef LINMINORIGINAL
                   2582: #else
1.234     brouard  2583:        for (j=1, flatd=0;j<=n;j++) {
                   2584:          if(flatdir[j]>0)
                   2585:            flatd++;
                   2586:        }
                   2587:        if(flatd >0){
1.255     brouard  2588:          printf("%d flat directions: ",flatd);
                   2589:          fprintf(ficlog,"%d flat directions :",flatd);
1.234     brouard  2590:          for (j=1;j<=n;j++) { 
                   2591:            if(flatdir[j]>0){
                   2592:              printf("%d ",j);
                   2593:              fprintf(ficlog,"%d ",j);
                   2594:            }
                   2595:          }
                   2596:          printf("\n");
                   2597:          fprintf(ficlog,"\n");
                   2598:        }
1.191     brouard  2599: #endif
1.234     brouard  2600:        printf("Gaining to use new average direction of P0 P%d instead of biggest increase direction %d :\n",n,ibig);
                   2601:        fprintf(ficlog,"Gaining to use new average direction of P0 P%d instead of biggest increase direction %d :\n",n,ibig);
                   2602:        
1.126     brouard  2603: #ifdef DEBUG
1.234     brouard  2604:        printf("Direction changed  last moved %d in place of ibig=%d, new last is the average:\n",n,ibig);
                   2605:        fprintf(ficlog,"Direction changed  last moved %d in place of ibig=%d, new last is the average:\n",n,ibig);
                   2606:        for(j=1;j<=n;j++){
                   2607:          printf(" %lf",xit[j]);
                   2608:          fprintf(ficlog," %lf",xit[j]);
                   2609:        }
                   2610:        printf("\n");
                   2611:        fprintf(ficlog,"\n");
1.126     brouard  2612: #endif
1.192     brouard  2613:       } /* end of t or directest negative */
1.224     brouard  2614: #ifdef POWELLNOF3INFF1TEST
1.192     brouard  2615: #else
1.234     brouard  2616:       } /* end if (fptt < fp)  */
1.192     brouard  2617: #endif
1.225     brouard  2618: #ifdef NODIRECTIONCHANGEDUNTILNITER  /* No change in drections until some iterations are done */
1.234     brouard  2619:     } /*NODIRECTIONCHANGEDUNTILNITER  No change in drections until some iterations are done */
1.225     brouard  2620: #else
1.224     brouard  2621: #endif
1.234     brouard  2622:                } /* loop iteration */ 
1.126     brouard  2623: } 
1.234     brouard  2624:   
1.126     brouard  2625: /**** Prevalence limit (stable or period prevalence)  ****************/
1.234     brouard  2626:   
1.235     brouard  2627:   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  2628:   {
1.279     brouard  2629:     /**< Computes the prevalence limit in each live state at age x and for covariate combination ij 
                   2630:      *   (and selected quantitative values in nres)
                   2631:      *  by left multiplying the unit
                   2632:      *  matrix by transitions matrix until convergence is reached with precision ftolpl 
                   2633:      * Wx= Wx-1 Px-1= Wx-2 Px-2 Px-1  = Wx-n Px-n ... Px-2 Px-1 I
                   2634:      * Wx is row vector: population in state 1, population in state 2, population dead
                   2635:      * or prevalence in state 1, prevalence in state 2, 0
                   2636:      * newm is the matrix after multiplications, its rows are identical at a factor.
                   2637:      * Inputs are the parameter, age, a tolerance for the prevalence limit ftolpl.
                   2638:      * Output is prlim.
                   2639:      * Initial matrix pimij 
                   2640:      */
1.206     brouard  2641:   /* {0.85204250825084937, 0.13044499163996345, 0.017512500109187184, */
                   2642:   /* 0.090851990222114765, 0.88271245433047185, 0.026435555447413338, */
                   2643:   /*  0,                   0                  , 1} */
                   2644:   /*
                   2645:    * and after some iteration: */
                   2646:   /* {0.45504275246439968, 0.42731458730878791, 0.11764266022681241, */
                   2647:   /*  0.45201005341706885, 0.42865420071559901, 0.11933574586733192, */
                   2648:   /*  0,                   0                  , 1} */
                   2649:   /* And prevalence by suppressing the deaths are close to identical rows in prlim: */
                   2650:   /* {0.51571254859325999, 0.4842874514067399, */
                   2651:   /*  0.51326036147820708, 0.48673963852179264} */
                   2652:   /* If we start from prlim again, prlim tends to a constant matrix */
1.234     brouard  2653:     
1.126     brouard  2654:   int i, ii,j,k;
1.209     brouard  2655:   double *min, *max, *meandiff, maxmax,sumnew=0.;
1.145     brouard  2656:   /* double **matprod2(); */ /* test */
1.218     brouard  2657:   double **out, cov[NCOVMAX+1], **pmij(); /* **pmmij is a global variable feeded with oldms etc */
1.126     brouard  2658:   double **newm;
1.209     brouard  2659:   double agefin, delaymax=200. ; /* 100 Max number of years to converge */
1.203     brouard  2660:   int ncvloop=0;
1.288     brouard  2661:   int first=0;
1.169     brouard  2662:   
1.209     brouard  2663:   min=vector(1,nlstate);
                   2664:   max=vector(1,nlstate);
                   2665:   meandiff=vector(1,nlstate);
                   2666: 
1.218     brouard  2667:        /* Starting with matrix unity */
1.126     brouard  2668:   for (ii=1;ii<=nlstate+ndeath;ii++)
                   2669:     for (j=1;j<=nlstate+ndeath;j++){
                   2670:       oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   2671:     }
1.169     brouard  2672:   
                   2673:   cov[1]=1.;
                   2674:   
                   2675:   /* Even if hstepm = 1, at least one multiplication by the unit matrix */
1.202     brouard  2676:   /* Start at agefin= age, computes the matrix of passage and loops decreasing agefin until convergence is reached */
1.126     brouard  2677:   for(agefin=age-stepm/YEARM; agefin>=age-delaymax; agefin=agefin-stepm/YEARM){
1.202     brouard  2678:     ncvloop++;
1.126     brouard  2679:     newm=savm;
                   2680:     /* Covariates have to be included here again */
1.138     brouard  2681:     cov[2]=agefin;
1.187     brouard  2682:     if(nagesqr==1)
                   2683:       cov[3]= agefin*agefin;;
1.234     brouard  2684:     for (k=1; k<=nsd;k++) { /* For single dummy covariates only */
                   2685:                        /* Here comes the value of the covariate 'ij' after renumbering k with single dummy covariates */
                   2686:       cov[2+nagesqr+TvarsDind[k]]=nbcode[TvarsD[k]][codtabm(ij,k)];
1.235     brouard  2687:       /* 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  2688:     }
                   2689:     for (k=1; k<=nsq;k++) { /* For single varying covariates only */
                   2690:                        /* Here comes the value of quantitative after renumbering k with single quantitative covariates */
1.235     brouard  2691:       cov[2+nagesqr+TvarsQind[k]]=Tqresult[nres][k]; 
                   2692:       /* 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  2693:     }
1.237     brouard  2694:     for (k=1; k<=cptcovage;k++){  /* For product with age */
1.234     brouard  2695:       if(Dummy[Tvar[Tage[k]]]){
                   2696:        cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,k)]*cov[2];
                   2697:       } else{
1.235     brouard  2698:        cov[2+nagesqr+Tage[k]]=Tqresult[nres][k]; 
1.234     brouard  2699:       }
1.235     brouard  2700:       /* 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  2701:     }
1.237     brouard  2702:     for (k=1; k<=cptcovprod;k++){ /* For product without age */
1.235     brouard  2703:       /* 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  2704:       if(Dummy[Tvard[k][1]==0]){
                   2705:        if(Dummy[Tvard[k][2]==0]){
                   2706:          cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)] * nbcode[Tvard[k][2]][codtabm(ij,k)];
                   2707:        }else{
                   2708:          cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)] * Tqresult[nres][k];
                   2709:        }
                   2710:       }else{
                   2711:        if(Dummy[Tvard[k][2]==0]){
                   2712:          cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][2]][codtabm(ij,k)] * Tqinvresult[nres][Tvard[k][1]];
                   2713:        }else{
                   2714:          cov[2+nagesqr+Tprod[k]]=Tqinvresult[nres][Tvard[k][1]]*  Tqinvresult[nres][Tvard[k][2]];
                   2715:        }
                   2716:       }
1.234     brouard  2717:     }
1.138     brouard  2718:     /*printf("ij=%d cptcovprod=%d tvar=%d ", ij, cptcovprod, Tvar[1]);*/
                   2719:     /*printf("ij=%d cov[3]=%lf cov[4]=%lf \n",ij, cov[3],cov[4]);*/
                   2720:     /*printf("ij=%d cov[3]=%lf \n",ij, cov[3]);*/
1.145     brouard  2721:     /* savm=pmij(pmmij,cov,ncovmodel,x,nlstate); */
                   2722:     /* out=matprod2(newm, pmij(pmmij,cov,ncovmodel,x,nlstate),1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm); /\* Bug Valgrind *\/ */
1.218     brouard  2723:                /* age and covariate values of ij are in 'cov' */
1.142     brouard  2724:     out=matprod2(newm, pmij(pmmij,cov,ncovmodel,x,nlstate),1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm); /* Bug Valgrind */
1.138     brouard  2725:     
1.126     brouard  2726:     savm=oldm;
                   2727:     oldm=newm;
1.209     brouard  2728: 
                   2729:     for(j=1; j<=nlstate; j++){
                   2730:       max[j]=0.;
                   2731:       min[j]=1.;
                   2732:     }
                   2733:     for(i=1;i<=nlstate;i++){
                   2734:       sumnew=0;
                   2735:       for(k=1; k<=ndeath; k++) sumnew+=newm[i][nlstate+k];
                   2736:       for(j=1; j<=nlstate; j++){ 
                   2737:        prlim[i][j]= newm[i][j]/(1-sumnew);
                   2738:        max[j]=FMAX(max[j],prlim[i][j]);
                   2739:        min[j]=FMIN(min[j],prlim[i][j]);
                   2740:       }
                   2741:     }
                   2742: 
1.126     brouard  2743:     maxmax=0.;
1.209     brouard  2744:     for(j=1; j<=nlstate; j++){
                   2745:       meandiff[j]=(max[j]-min[j])/(max[j]+min[j])*2.; /* mean difference for each column */
                   2746:       maxmax=FMAX(maxmax,meandiff[j]);
                   2747:       /* 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  2748:     } /* j loop */
1.203     brouard  2749:     *ncvyear= (int)age- (int)agefin;
1.208     brouard  2750:     /* 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  2751:     if(maxmax < ftolpl){
1.209     brouard  2752:       /* printf("maxmax=%lf ncvloop=%ld, age=%d, agefin=%d ncvyear=%d \n", maxmax, ncvloop, (int)age, (int)agefin, *ncvyear); */
                   2753:       free_vector(min,1,nlstate);
                   2754:       free_vector(max,1,nlstate);
                   2755:       free_vector(meandiff,1,nlstate);
1.126     brouard  2756:       return prlim;
                   2757:     }
1.288     brouard  2758:   } /* agefin loop */
1.208     brouard  2759:     /* After some age loop it doesn't converge */
1.288     brouard  2760:   if(!first){
                   2761:     first=1;
                   2762:     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);
                   2763:   }
                   2764:   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);
                   2765: 
1.209     brouard  2766:   /* 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); */
                   2767:   free_vector(min,1,nlstate);
                   2768:   free_vector(max,1,nlstate);
                   2769:   free_vector(meandiff,1,nlstate);
1.208     brouard  2770:   
1.169     brouard  2771:   return prlim; /* should not reach here */
1.126     brouard  2772: }
                   2773: 
1.217     brouard  2774: 
                   2775:  /**** Back Prevalence limit (stable or period prevalence)  ****************/
                   2776: 
1.218     brouard  2777:  /* 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) */
                   2778:  /* 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  2779:   double **bprevalim(double **bprlim, double ***prevacurrent, int nlstate, double x[], double age, double ftolpl, int *ncvyear, int ij, int nres)
1.217     brouard  2780: {
1.264     brouard  2781:   /* 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  2782:      matrix by transitions matrix until convergence is reached with precision ftolpl */
                   2783:   /* Wx= Wx-1 Px-1= Wx-2 Px-2 Px-1  = Wx-n Px-n ... Px-2 Px-1 I */
                   2784:   /* Wx is row vector: population in state 1, population in state 2, population dead */
                   2785:   /* or prevalence in state 1, prevalence in state 2, 0 */
                   2786:   /* newm is the matrix after multiplications, its rows are identical at a factor */
                   2787:   /* Initial matrix pimij */
                   2788:   /* {0.85204250825084937, 0.13044499163996345, 0.017512500109187184, */
                   2789:   /* 0.090851990222114765, 0.88271245433047185, 0.026435555447413338, */
                   2790:   /*  0,                   0                  , 1} */
                   2791:   /*
                   2792:    * and after some iteration: */
                   2793:   /* {0.45504275246439968, 0.42731458730878791, 0.11764266022681241, */
                   2794:   /*  0.45201005341706885, 0.42865420071559901, 0.11933574586733192, */
                   2795:   /*  0,                   0                  , 1} */
                   2796:   /* And prevalence by suppressing the deaths are close to identical rows in prlim: */
                   2797:   /* {0.51571254859325999, 0.4842874514067399, */
                   2798:   /*  0.51326036147820708, 0.48673963852179264} */
                   2799:   /* If we start from prlim again, prlim tends to a constant matrix */
                   2800: 
                   2801:   int i, ii,j,k;
1.247     brouard  2802:   int first=0;
1.217     brouard  2803:   double *min, *max, *meandiff, maxmax,sumnew=0.;
                   2804:   /* double **matprod2(); */ /* test */
                   2805:   double **out, cov[NCOVMAX+1], **bmij();
                   2806:   double **newm;
1.218     brouard  2807:   double        **dnewm, **doldm, **dsavm;  /* for use */
                   2808:   double        **oldm, **savm;  /* for use */
                   2809: 
1.217     brouard  2810:   double agefin, delaymax=200. ; /* 100 Max number of years to converge */
                   2811:   int ncvloop=0;
                   2812:   
                   2813:   min=vector(1,nlstate);
                   2814:   max=vector(1,nlstate);
                   2815:   meandiff=vector(1,nlstate);
                   2816: 
1.266     brouard  2817:   dnewm=ddnewms; doldm=ddoldms; dsavm=ddsavms;
                   2818:   oldm=oldms; savm=savms;
                   2819:   
                   2820:   /* Starting with matrix unity */
                   2821:   for (ii=1;ii<=nlstate+ndeath;ii++)
                   2822:     for (j=1;j<=nlstate+ndeath;j++){
1.217     brouard  2823:       oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   2824:     }
                   2825:   
                   2826:   cov[1]=1.;
                   2827:   
                   2828:   /* Even if hstepm = 1, at least one multiplication by the unit matrix */
                   2829:   /* Start at agefin= age, computes the matrix of passage and loops decreasing agefin until convergence is reached */
1.218     brouard  2830:   /* for(agefin=age+stepm/YEARM; agefin<=age+delaymax; agefin=agefin+stepm/YEARM){ /\* A changer en age *\/ */
1.288     brouard  2831:   /* for(agefin=age; agefin<AGESUP; agefin=agefin+stepm/YEARM){ /\* A changer en age *\/ */
                   2832:   for(agefin=age; agefin<FMIN(AGESUP,age+delaymax); agefin=agefin+stepm/YEARM){ /* A changer en age */
1.217     brouard  2833:     ncvloop++;
1.218     brouard  2834:     newm=savm; /* oldm should be kept from previous iteration or unity at start */
                   2835:                /* newm points to the allocated table savm passed by the function it can be written, savm could be reallocated */
1.217     brouard  2836:     /* Covariates have to be included here again */
                   2837:     cov[2]=agefin;
                   2838:     if(nagesqr==1)
                   2839:       cov[3]= agefin*agefin;;
1.242     brouard  2840:     for (k=1; k<=nsd;k++) { /* For single dummy covariates only */
                   2841:                        /* Here comes the value of the covariate 'ij' after renumbering k with single dummy covariates */
                   2842:       cov[2+nagesqr+TvarsDind[k]]=nbcode[TvarsD[k]][codtabm(ij,k)];
1.264     brouard  2843:       /* 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  2844:     }
                   2845:     /* for (k=1; k<=cptcovn;k++) { */
                   2846:     /*   /\* cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,Tvar[k])]; *\/ */
                   2847:     /*   cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,k)]; */
                   2848:     /*   /\* 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])]); *\/ */
                   2849:     /* } */
                   2850:     for (k=1; k<=nsq;k++) { /* For single varying covariates only */
                   2851:                        /* Here comes the value of quantitative after renumbering k with single quantitative covariates */
                   2852:       cov[2+nagesqr+TvarsQind[k]]=Tqresult[nres][k]; 
                   2853:       /* 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]); */
                   2854:     }
                   2855:     /* for (k=1; k<=cptcovage;k++) cov[2+nagesqr+Tage[k]]=nbcode[Tvar[k]][codtabm(ij,k)]*cov[2]; */
                   2856:     /* for (k=1; k<=cptcovprod;k++) /\* Useless *\/ */
                   2857:     /*   /\* cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,Tvard[k][1])] * nbcode[Tvard[k][2]][codtabm(ij,Tvard[k][2])]; *\/ */
                   2858:     /*   cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)] * nbcode[Tvard[k][2]][codtabm(ij,k)]; */
                   2859:     for (k=1; k<=cptcovage;k++){  /* For product with age */
                   2860:       if(Dummy[Tvar[Tage[k]]]){
                   2861:        cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,k)]*cov[2];
                   2862:       } else{
                   2863:        cov[2+nagesqr+Tage[k]]=Tqresult[nres][k]; 
                   2864:       }
                   2865:       /* 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]); */
                   2866:     }
                   2867:     for (k=1; k<=cptcovprod;k++){ /* For product without age */
                   2868:       /* 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]); */
                   2869:       if(Dummy[Tvard[k][1]==0]){
                   2870:        if(Dummy[Tvard[k][2]==0]){
                   2871:          cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)] * nbcode[Tvard[k][2]][codtabm(ij,k)];
                   2872:        }else{
                   2873:          cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)] * Tqresult[nres][k];
                   2874:        }
                   2875:       }else{
                   2876:        if(Dummy[Tvard[k][2]==0]){
                   2877:          cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][2]][codtabm(ij,k)] * Tqinvresult[nres][Tvard[k][1]];
                   2878:        }else{
                   2879:          cov[2+nagesqr+Tprod[k]]=Tqinvresult[nres][Tvard[k][1]]*  Tqinvresult[nres][Tvard[k][2]];
                   2880:        }
                   2881:       }
1.217     brouard  2882:     }
                   2883:     
                   2884:     /*printf("ij=%d cptcovprod=%d tvar=%d ", ij, cptcovprod, Tvar[1]);*/
                   2885:     /*printf("ij=%d cov[3]=%lf cov[4]=%lf \n",ij, cov[3],cov[4]);*/
                   2886:     /*printf("ij=%d cov[3]=%lf \n",ij, cov[3]);*/
                   2887:     /* savm=pmij(pmmij,cov,ncovmodel,x,nlstate); */
                   2888:     /* out=matprod2(newm, pmij(pmmij,cov,ncovmodel,x,nlstate),1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm); /\* Bug Valgrind *\/ */
1.218     brouard  2889:                /* ij should be linked to the correct index of cov */
                   2890:                /* age and covariate values ij are in 'cov', but we need to pass
                   2891:                 * ij for the observed prevalence at age and status and covariate
                   2892:                 * number:  prevacurrent[(int)agefin][ii][ij]
                   2893:                 */
                   2894:     /* 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 *\/ */
                   2895:     /* 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 *\/ */
                   2896:     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  2897:     /* if((int)age == 86 || (int)age == 87){ */
1.266     brouard  2898:     /*   printf(" Backward prevalim age=%d agefin=%d \n", (int) age, (int) agefin); */
                   2899:     /*   for(i=1; i<=nlstate+ndeath; i++) { */
                   2900:     /*         printf("%d newm= ",i); */
                   2901:     /*         for(j=1;j<=nlstate+ndeath;j++) { */
                   2902:     /*           printf("%f ",newm[i][j]); */
                   2903:     /*         } */
                   2904:     /*         printf("oldm * "); */
                   2905:     /*         for(j=1;j<=nlstate+ndeath;j++) { */
                   2906:     /*           printf("%f ",oldm[i][j]); */
                   2907:     /*         } */
1.268     brouard  2908:     /*         printf(" bmmij "); */
1.266     brouard  2909:     /*         for(j=1;j<=nlstate+ndeath;j++) { */
                   2910:     /*           printf("%f ",pmmij[i][j]); */
                   2911:     /*         } */
                   2912:     /*         printf("\n"); */
                   2913:     /*   } */
                   2914:     /* } */
1.217     brouard  2915:     savm=oldm;
                   2916:     oldm=newm;
1.266     brouard  2917: 
1.217     brouard  2918:     for(j=1; j<=nlstate; j++){
                   2919:       max[j]=0.;
                   2920:       min[j]=1.;
                   2921:     }
                   2922:     for(j=1; j<=nlstate; j++){ 
                   2923:       for(i=1;i<=nlstate;i++){
1.234     brouard  2924:        /* bprlim[i][j]= newm[i][j]/(1-sumnew); */
                   2925:        bprlim[i][j]= newm[i][j];
                   2926:        max[i]=FMAX(max[i],bprlim[i][j]); /* Max in line */
                   2927:        min[i]=FMIN(min[i],bprlim[i][j]);
1.217     brouard  2928:       }
                   2929:     }
1.218     brouard  2930:                
1.217     brouard  2931:     maxmax=0.;
                   2932:     for(i=1; i<=nlstate; i++){
                   2933:       meandiff[i]=(max[i]-min[i])/(max[i]+min[i])*2.; /* mean difference for each column */
                   2934:       maxmax=FMAX(maxmax,meandiff[i]);
                   2935:       /* 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  2936:     } /* i loop */
1.217     brouard  2937:     *ncvyear= -( (int)age- (int)agefin);
1.268     brouard  2938:     /* printf("Back maxmax=%lf ncvloop=%d, age=%d, agefin=%d ncvyear=%d \n", maxmax, ncvloop, (int)age, (int)agefin, *ncvyear); */
1.217     brouard  2939:     if(maxmax < ftolpl){
1.220     brouard  2940:       /* printf("OK Back maxmax=%lf ncvloop=%d, age=%d, agefin=%d ncvyear=%d \n", maxmax, ncvloop, (int)age, (int)agefin, *ncvyear); */
1.217     brouard  2941:       free_vector(min,1,nlstate);
                   2942:       free_vector(max,1,nlstate);
                   2943:       free_vector(meandiff,1,nlstate);
                   2944:       return bprlim;
                   2945:     }
1.288     brouard  2946:   } /* agefin loop */
1.217     brouard  2947:     /* After some age loop it doesn't converge */
1.288     brouard  2948:   if(!first){
1.247     brouard  2949:     first=1;
                   2950:     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\
                   2951: 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);
                   2952:   }
                   2953:   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  2954: 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);
                   2955:   /* 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); */
                   2956:   free_vector(min,1,nlstate);
                   2957:   free_vector(max,1,nlstate);
                   2958:   free_vector(meandiff,1,nlstate);
                   2959:   
                   2960:   return bprlim; /* should not reach here */
                   2961: }
                   2962: 
1.126     brouard  2963: /*************** transition probabilities ***************/ 
                   2964: 
                   2965: double **pmij(double **ps, double *cov, int ncovmodel, double *x, int nlstate )
                   2966: {
1.138     brouard  2967:   /* According to parameters values stored in x and the covariate's values stored in cov,
1.266     brouard  2968:      computes the probability to be observed in state j (after stepm years) being in state i by appying the
1.138     brouard  2969:      model to the ncovmodel covariates (including constant and age).
                   2970:      lnpijopii=ln(pij/pii)= aij+bij*age+cij*v1+dij*v2+... = sum_nc=1^ncovmodel xij(nc)*cov[nc]
                   2971:      and, according on how parameters are entered, the position of the coefficient xij(nc) of the
                   2972:      ncth covariate in the global vector x is given by the formula:
                   2973:      j<i nc+((i-1)*(nlstate+ndeath-1)+j-1)*ncovmodel
                   2974:      j>=i nc + ((i-1)*(nlstate+ndeath-1)+(j-2))*ncovmodel
                   2975:      Computes ln(pij/pii) (lnpijopii), deduces pij/pii by exponentiation,
                   2976:      sums on j different of i to get 1-pii/pii, deduces pii, and then all pij.
1.266     brouard  2977:      Outputs ps[i][j] or probability to be observed in j being in i according to
1.138     brouard  2978:      the values of the covariates cov[nc] and corresponding parameter values x[nc+shiftij]
1.266     brouard  2979:      Sum on j ps[i][j] should equal to 1.
1.138     brouard  2980:   */
                   2981:   double s1, lnpijopii;
1.126     brouard  2982:   /*double t34;*/
1.164     brouard  2983:   int i,j, nc, ii, jj;
1.126     brouard  2984: 
1.223     brouard  2985:   for(i=1; i<= nlstate; i++){
                   2986:     for(j=1; j<i;j++){
                   2987:       for (nc=1, lnpijopii=0.;nc <=ncovmodel; nc++){
                   2988:        /*lnpijopii += param[i][j][nc]*cov[nc];*/
                   2989:        lnpijopii += x[nc+((i-1)*(nlstate+ndeath-1)+j-1)*ncovmodel]*cov[nc];
                   2990:        /*       printf("Int j<i s1=%.17e, lnpijopii=%.17e\n",s1,lnpijopii); */
                   2991:       }
                   2992:       ps[i][j]=lnpijopii; /* In fact ln(pij/pii) */
                   2993:       /*       printf("s1=%.17e, lnpijopii=%.17e\n",s1,lnpijopii); */
                   2994:     }
                   2995:     for(j=i+1; j<=nlstate+ndeath;j++){
                   2996:       for (nc=1, lnpijopii=0.;nc <=ncovmodel; nc++){
                   2997:        /*lnpijopii += x[(i-1)*nlstate*ncovmodel+(j-2)*ncovmodel+nc+(i-1)*(ndeath-1)*ncovmodel]*cov[nc];*/
                   2998:        lnpijopii += x[nc + ((i-1)*(nlstate+ndeath-1)+(j-2))*ncovmodel]*cov[nc];
                   2999:        /*        printf("Int j>i s1=%.17e, lnpijopii=%.17e %lx %lx\n",s1,lnpijopii,s1,lnpijopii); */
                   3000:       }
                   3001:       ps[i][j]=lnpijopii; /* In fact ln(pij/pii) */
                   3002:     }
                   3003:   }
1.218     brouard  3004:   
1.223     brouard  3005:   for(i=1; i<= nlstate; i++){
                   3006:     s1=0;
                   3007:     for(j=1; j<i; j++){
                   3008:       s1+=exp(ps[i][j]); /* In fact sums pij/pii */
                   3009:       /*printf("debug1 %d %d ps=%lf exp(ps)=%lf s1+=%lf\n",i,j,ps[i][j],exp(ps[i][j]),s1); */
                   3010:     }
                   3011:     for(j=i+1; j<=nlstate+ndeath; j++){
                   3012:       s1+=exp(ps[i][j]); /* In fact sums pij/pii */
                   3013:       /*printf("debug2 %d %d ps=%lf exp(ps)=%lf s1+=%lf\n",i,j,ps[i][j],exp(ps[i][j]),s1); */
                   3014:     }
                   3015:     /* s1= sum_{j<>i} pij/pii=(1-pii)/pii and thus pii is known from s1 */
                   3016:     ps[i][i]=1./(s1+1.);
                   3017:     /* Computing other pijs */
                   3018:     for(j=1; j<i; j++)
                   3019:       ps[i][j]= exp(ps[i][j])*ps[i][i];
                   3020:     for(j=i+1; j<=nlstate+ndeath; j++)
                   3021:       ps[i][j]= exp(ps[i][j])*ps[i][i];
                   3022:     /* ps[i][nlstate+1]=1.-s1- ps[i][i];*/ /* Sum should be 1 */
                   3023:   } /* end i */
1.218     brouard  3024:   
1.223     brouard  3025:   for(ii=nlstate+1; ii<= nlstate+ndeath; ii++){
                   3026:     for(jj=1; jj<= nlstate+ndeath; jj++){
                   3027:       ps[ii][jj]=0;
                   3028:       ps[ii][ii]=1;
                   3029:     }
                   3030:   }
1.294     brouard  3031: 
                   3032: 
1.223     brouard  3033:   /* for(ii=1; ii<= nlstate+ndeath; ii++){ */
                   3034:   /*   for(jj=1; jj<= nlstate+ndeath; jj++){ */
                   3035:   /*   printf(" pmij  ps[%d][%d]=%lf ",ii,jj,ps[ii][jj]); */
                   3036:   /*   } */
                   3037:   /*   printf("\n "); */
                   3038:   /* } */
                   3039:   /* printf("\n ");printf("%lf ",cov[2]);*/
                   3040:   /*
                   3041:     for(i=1; i<= npar; i++) printf("%f ",x[i]);
1.218     brouard  3042:                goto end;*/
1.266     brouard  3043:   return ps; /* Pointer is unchanged since its call */
1.126     brouard  3044: }
                   3045: 
1.218     brouard  3046: /*************** backward transition probabilities ***************/ 
                   3047: 
                   3048:  /* 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 ) */
                   3049: /* double **bmij(double **ps, double *cov, int ncovmodel, double *x, int nlstate,  double ***prevacurrent, double ***dnewm, double **doldm, double **dsavm, int ij ) */
                   3050:  double **bmij(double **ps, double *cov, int ncovmodel, double *x, int nlstate,  double ***prevacurrent, int ij )
                   3051: {
1.302     brouard  3052:   /* 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  3053:    * 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  3054:    */
1.218     brouard  3055:   int i, ii, j,k;
1.222     brouard  3056:   
                   3057:   double **out, **pmij();
                   3058:   double sumnew=0.;
1.218     brouard  3059:   double agefin;
1.292     brouard  3060:   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  3061:   double **dnewm, **dsavm, **doldm;
                   3062:   double **bbmij;
                   3063:   
1.218     brouard  3064:   doldm=ddoldms; /* global pointers */
1.222     brouard  3065:   dnewm=ddnewms;
                   3066:   dsavm=ddsavms;
                   3067:   
                   3068:   agefin=cov[2];
1.268     brouard  3069:   /* Bx = Diag(w_x) P_x Diag(Sum_i w^i_x p^ij_x */
1.222     brouard  3070:   /* bmij *//* age is cov[2], ij is included in cov, but we need for
1.266     brouard  3071:      the observed prevalence (with this covariate ij) at beginning of transition */
                   3072:   /* dsavm=pmij(pmmij,cov,ncovmodel,x,nlstate); */
1.268     brouard  3073: 
                   3074:   /* P_x */
1.266     brouard  3075:   pmmij=pmij(pmmij,cov,ncovmodel,x,nlstate); /*This is forward probability from agefin to agefin + stepm */
1.268     brouard  3076:   /* outputs pmmij which is a stochastic matrix in row */
                   3077: 
                   3078:   /* Diag(w_x) */
1.292     brouard  3079:   /* Rescaling the cross-sectional prevalence: Problem with prevacurrent which can be zero */
1.268     brouard  3080:   sumnew=0.;
1.269     brouard  3081:   /*for (ii=1;ii<=nlstate+ndeath;ii++){*/
1.268     brouard  3082:   for (ii=1;ii<=nlstate;ii++){ /* Only on live states */
1.297     brouard  3083:     /* printf(" agefin=%d, ii=%d, ij=%d, prev=%f\n",(int)agefin,ii, ij, prevacurrent[(int)agefin][ii][ij]); */
1.268     brouard  3084:     sumnew+=prevacurrent[(int)agefin][ii][ij];
                   3085:   }
                   3086:   if(sumnew >0.01){  /* At least some value in the prevalence */
                   3087:     for (ii=1;ii<=nlstate+ndeath;ii++){
                   3088:       for (j=1;j<=nlstate+ndeath;j++)
1.269     brouard  3089:        doldm[ii][j]=(ii==j ? prevacurrent[(int)agefin][ii][ij]/sumnew : 0.0);
1.268     brouard  3090:     }
                   3091:   }else{
                   3092:     for (ii=1;ii<=nlstate+ndeath;ii++){
                   3093:       for (j=1;j<=nlstate+ndeath;j++)
                   3094:       doldm[ii][j]=(ii==j ? 1./nlstate : 0.0);
                   3095:     }
                   3096:     /* if(sumnew <0.9){ */
                   3097:     /*   printf("Problem internal bmij B: sum on i wi <0.9: j=%d, sum_i wi=%lf,agefin=%d\n",j,sumnew, (int)agefin); */
                   3098:     /* } */
                   3099:   }
                   3100:   k3=0.0;  /* We put the last diagonal to 0 */
                   3101:   for (ii=nlstate+1;ii<=nlstate+ndeath;ii++){
                   3102:       doldm[ii][ii]= k3;
                   3103:   }
                   3104:   /* End doldm, At the end doldm is diag[(w_i)] */
                   3105:   
1.292     brouard  3106:   /* Left product of this diag matrix by pmmij=Px (dnewm=dsavm*doldm): diag[(w_i)*Px */
                   3107:   bbmij=matprod2(dnewm, doldm,1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, pmmij); /* was a Bug Valgrind */
1.268     brouard  3108: 
1.292     brouard  3109:   /* Diag(Sum_i w^i_x p^ij_x, should be the prevalence at age x+stepm */
1.268     brouard  3110:   /* 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  3111:   for (j=1;j<=nlstate+ndeath;j++){
1.268     brouard  3112:     sumnew=0.;
1.222     brouard  3113:     for (ii=1;ii<=nlstate;ii++){
1.266     brouard  3114:       /* sumnew+=dsavm[ii][j]*prevacurrent[(int)agefin][ii][ij]; */
1.268     brouard  3115:       sumnew+=pmmij[ii][j]*doldm[ii][ii]; /* Yes prevalence at beginning of transition */
1.222     brouard  3116:     } /* sumnew is (N11+N21)/N..= N.1/N.. = sum on i of w_i pij */
1.268     brouard  3117:     for (ii=1;ii<=nlstate+ndeath;ii++){
1.222     brouard  3118:        /* if(agefin >= agemaxpar && agefin <= agemaxpar+stepm/YEARM){ */
1.268     brouard  3119:        /*      dsavm[ii][j]=(ii==j ? 1./sumnew : 0.0); */
1.222     brouard  3120:        /* }else if(agefin >= agemaxpar+stepm/YEARM){ */
1.268     brouard  3121:        /*      dsavm[ii][j]=(ii==j ? 1./sumnew : 0.0); */
1.222     brouard  3122:        /* }else */
1.268     brouard  3123:       dsavm[ii][j]=(ii==j ? 1./sumnew : 0.0);
                   3124:     } /*End ii */
                   3125:   } /* 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 */
                   3126: 
1.292     brouard  3127:   ps=matprod2(ps, dnewm,1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, dsavm); /* was a Bug Valgrind */
1.268     brouard  3128:   /* ps is now diag[w_i] * Px * diag [1/(w_1p1i+w_2 p2i)] */
1.222     brouard  3129:   /* end bmij */
1.266     brouard  3130:   return ps; /*pointer is unchanged */
1.218     brouard  3131: }
1.217     brouard  3132: /*************** transition probabilities ***************/ 
                   3133: 
1.218     brouard  3134: double **bpmij(double **ps, double *cov, int ncovmodel, double *x, int nlstate )
1.217     brouard  3135: {
                   3136:   /* According to parameters values stored in x and the covariate's values stored in cov,
                   3137:      computes the probability to be observed in state j being in state i by appying the
                   3138:      model to the ncovmodel covariates (including constant and age).
                   3139:      lnpijopii=ln(pij/pii)= aij+bij*age+cij*v1+dij*v2+... = sum_nc=1^ncovmodel xij(nc)*cov[nc]
                   3140:      and, according on how parameters are entered, the position of the coefficient xij(nc) of the
                   3141:      ncth covariate in the global vector x is given by the formula:
                   3142:      j<i nc+((i-1)*(nlstate+ndeath-1)+j-1)*ncovmodel
                   3143:      j>=i nc + ((i-1)*(nlstate+ndeath-1)+(j-2))*ncovmodel
                   3144:      Computes ln(pij/pii) (lnpijopii), deduces pij/pii by exponentiation,
                   3145:      sums on j different of i to get 1-pii/pii, deduces pii, and then all pij.
                   3146:      Outputs ps[i][j] the probability to be observed in j being in j according to
                   3147:      the values of the covariates cov[nc] and corresponding parameter values x[nc+shiftij]
                   3148:   */
                   3149:   double s1, lnpijopii;
                   3150:   /*double t34;*/
                   3151:   int i,j, nc, ii, jj;
                   3152: 
1.234     brouard  3153:   for(i=1; i<= nlstate; i++){
                   3154:     for(j=1; j<i;j++){
                   3155:       for (nc=1, lnpijopii=0.;nc <=ncovmodel; nc++){
                   3156:        /*lnpijopii += param[i][j][nc]*cov[nc];*/
                   3157:        lnpijopii += x[nc+((i-1)*(nlstate+ndeath-1)+j-1)*ncovmodel]*cov[nc];
                   3158:        /*       printf("Int j<i s1=%.17e, lnpijopii=%.17e\n",s1,lnpijopii); */
                   3159:       }
                   3160:       ps[i][j]=lnpijopii; /* In fact ln(pij/pii) */
                   3161:       /*       printf("s1=%.17e, lnpijopii=%.17e\n",s1,lnpijopii); */
                   3162:     }
                   3163:     for(j=i+1; j<=nlstate+ndeath;j++){
                   3164:       for (nc=1, lnpijopii=0.;nc <=ncovmodel; nc++){
                   3165:        /*lnpijopii += x[(i-1)*nlstate*ncovmodel+(j-2)*ncovmodel+nc+(i-1)*(ndeath-1)*ncovmodel]*cov[nc];*/
                   3166:        lnpijopii += x[nc + ((i-1)*(nlstate+ndeath-1)+(j-2))*ncovmodel]*cov[nc];
                   3167:        /*        printf("Int j>i s1=%.17e, lnpijopii=%.17e %lx %lx\n",s1,lnpijopii,s1,lnpijopii); */
                   3168:       }
                   3169:       ps[i][j]=lnpijopii; /* In fact ln(pij/pii) */
                   3170:     }
                   3171:   }
                   3172:   
                   3173:   for(i=1; i<= nlstate; i++){
                   3174:     s1=0;
                   3175:     for(j=1; j<i; j++){
                   3176:       s1+=exp(ps[i][j]); /* In fact sums pij/pii */
                   3177:       /*printf("debug1 %d %d ps=%lf exp(ps)=%lf s1+=%lf\n",i,j,ps[i][j],exp(ps[i][j]),s1); */
                   3178:     }
                   3179:     for(j=i+1; j<=nlstate+ndeath; j++){
                   3180:       s1+=exp(ps[i][j]); /* In fact sums pij/pii */
                   3181:       /*printf("debug2 %d %d ps=%lf exp(ps)=%lf s1+=%lf\n",i,j,ps[i][j],exp(ps[i][j]),s1); */
                   3182:     }
                   3183:     /* s1= sum_{j<>i} pij/pii=(1-pii)/pii and thus pii is known from s1 */
                   3184:     ps[i][i]=1./(s1+1.);
                   3185:     /* Computing other pijs */
                   3186:     for(j=1; j<i; j++)
                   3187:       ps[i][j]= exp(ps[i][j])*ps[i][i];
                   3188:     for(j=i+1; j<=nlstate+ndeath; j++)
                   3189:       ps[i][j]= exp(ps[i][j])*ps[i][i];
                   3190:     /* ps[i][nlstate+1]=1.-s1- ps[i][i];*/ /* Sum should be 1 */
                   3191:   } /* end i */
                   3192:   
                   3193:   for(ii=nlstate+1; ii<= nlstate+ndeath; ii++){
                   3194:     for(jj=1; jj<= nlstate+ndeath; jj++){
                   3195:       ps[ii][jj]=0;
                   3196:       ps[ii][ii]=1;
                   3197:     }
                   3198:   }
1.296     brouard  3199:   /* Added for prevbcast */ /* Transposed matrix too */
1.234     brouard  3200:   for(jj=1; jj<= nlstate+ndeath; jj++){
                   3201:     s1=0.;
                   3202:     for(ii=1; ii<= nlstate+ndeath; ii++){
                   3203:       s1+=ps[ii][jj];
                   3204:     }
                   3205:     for(ii=1; ii<= nlstate; ii++){
                   3206:       ps[ii][jj]=ps[ii][jj]/s1;
                   3207:     }
                   3208:   }
                   3209:   /* Transposition */
                   3210:   for(jj=1; jj<= nlstate+ndeath; jj++){
                   3211:     for(ii=jj; ii<= nlstate+ndeath; ii++){
                   3212:       s1=ps[ii][jj];
                   3213:       ps[ii][jj]=ps[jj][ii];
                   3214:       ps[jj][ii]=s1;
                   3215:     }
                   3216:   }
                   3217:   /* for(ii=1; ii<= nlstate+ndeath; ii++){ */
                   3218:   /*   for(jj=1; jj<= nlstate+ndeath; jj++){ */
                   3219:   /*   printf(" pmij  ps[%d][%d]=%lf ",ii,jj,ps[ii][jj]); */
                   3220:   /*   } */
                   3221:   /*   printf("\n "); */
                   3222:   /* } */
                   3223:   /* printf("\n ");printf("%lf ",cov[2]);*/
                   3224:   /*
                   3225:     for(i=1; i<= npar; i++) printf("%f ",x[i]);
                   3226:     goto end;*/
                   3227:   return ps;
1.217     brouard  3228: }
                   3229: 
                   3230: 
1.126     brouard  3231: /**************** Product of 2 matrices ******************/
                   3232: 
1.145     brouard  3233: double **matprod2(double **out, double **in,int nrl, int nrh, int ncl, int nch, int ncolol, int ncoloh, double **b)
1.126     brouard  3234: {
                   3235:   /* Computes the matrix product of in(1,nrh-nrl+1)(1,nch-ncl+1) times
                   3236:      b(1,nch-ncl+1)(1,ncoloh-ncolol+1) into out(...) */
                   3237:   /* in, b, out are matrice of pointers which should have been initialized 
                   3238:      before: only the contents of out is modified. The function returns
                   3239:      a pointer to pointers identical to out */
1.145     brouard  3240:   int i, j, k;
1.126     brouard  3241:   for(i=nrl; i<= nrh; i++)
1.145     brouard  3242:     for(k=ncolol; k<=ncoloh; k++){
                   3243:       out[i][k]=0.;
                   3244:       for(j=ncl; j<=nch; j++)
                   3245:        out[i][k] +=in[i][j]*b[j][k];
                   3246:     }
1.126     brouard  3247:   return out;
                   3248: }
                   3249: 
                   3250: 
                   3251: /************* Higher Matrix Product ***************/
                   3252: 
1.235     brouard  3253: 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  3254: {
1.218     brouard  3255:   /* Computes the transition matrix starting at age 'age' and combination of covariate values corresponding to ij over 
1.126     brouard  3256:      'nhstepm*hstepm*stepm' months (i.e. until
                   3257:      age (in years)  age+nhstepm*hstepm*stepm/12) by multiplying 
                   3258:      nhstepm*hstepm matrices. 
                   3259:      Output is stored in matrix po[i][j][h] for h every 'hstepm' step 
                   3260:      (typically every 2 years instead of every month which is too big 
                   3261:      for the memory).
                   3262:      Model is determined by parameters x and covariates have to be 
                   3263:      included manually here. 
                   3264: 
                   3265:      */
                   3266: 
                   3267:   int i, j, d, h, k;
1.131     brouard  3268:   double **out, cov[NCOVMAX+1];
1.126     brouard  3269:   double **newm;
1.187     brouard  3270:   double agexact;
1.214     brouard  3271:   double agebegin, ageend;
1.126     brouard  3272: 
                   3273:   /* Hstepm could be zero and should return the unit matrix */
                   3274:   for (i=1;i<=nlstate+ndeath;i++)
                   3275:     for (j=1;j<=nlstate+ndeath;j++){
                   3276:       oldm[i][j]=(i==j ? 1.0 : 0.0);
                   3277:       po[i][j][0]=(i==j ? 1.0 : 0.0);
                   3278:     }
                   3279:   /* Even if hstepm = 1, at least one multiplication by the unit matrix */
                   3280:   for(h=1; h <=nhstepm; h++){
                   3281:     for(d=1; d <=hstepm; d++){
                   3282:       newm=savm;
                   3283:       /* Covariates have to be included here again */
                   3284:       cov[1]=1.;
1.214     brouard  3285:       agexact=age+((h-1)*hstepm + (d-1))*stepm/YEARM; /* age just before transition */
1.187     brouard  3286:       cov[2]=agexact;
                   3287:       if(nagesqr==1)
1.227     brouard  3288:        cov[3]= agexact*agexact;
1.235     brouard  3289:       for (k=1; k<=nsd;k++) { /* For single dummy covariates only */
                   3290:                        /* Here comes the value of the covariate 'ij' after renumbering k with single dummy covariates */
                   3291:        cov[2+nagesqr+TvarsDind[k]]=nbcode[TvarsD[k]][codtabm(ij,k)];
                   3292:        /* 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)); */
                   3293:       }
                   3294:       for (k=1; k<=nsq;k++) { /* For single varying covariates only */
                   3295:        /* Here comes the value of quantitative after renumbering k with single quantitative covariates */
                   3296:        cov[2+nagesqr+TvarsQind[k]]=Tqresult[nres][k]; 
                   3297:        /* 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]); */
                   3298:       }
                   3299:       for (k=1; k<=cptcovage;k++){
                   3300:        if(Dummy[Tvar[Tage[k]]]){
                   3301:          cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,k)]*cov[2];
                   3302:        } else{
                   3303:          cov[2+nagesqr+Tage[k]]=Tqresult[nres][k]; 
                   3304:        }
                   3305:        /* 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]); */
                   3306:       }
                   3307:       for (k=1; k<=cptcovprod;k++){ /*  */
                   3308:        /* 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]); */
                   3309:        cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)] * nbcode[Tvard[k][2]][codtabm(ij,k)];
                   3310:       }
                   3311:       /* for (k=1; k<=cptcovn;k++)  */
                   3312:       /*       cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,k)]; */
                   3313:       /* for (k=1; k<=cptcovage;k++) /\* Should start at cptcovn+1 *\/ */
                   3314:       /*       cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,k)]*cov[2]; */
                   3315:       /* for (k=1; k<=cptcovprod;k++) /\* Useless because included in cptcovn *\/ */
                   3316:       /*       cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)]*nbcode[Tvard[k][2]][codtabm(ij,k)]; */
1.227     brouard  3317:       
                   3318:       
1.126     brouard  3319:       /*printf("hxi cptcov=%d cptcode=%d\n",cptcov,cptcode);*/
                   3320:       /*printf("h=%d d=%d age=%f cov=%f\n",h,d,age,cov[2]);*/
1.218     brouard  3321:                        /* right multiplication of oldm by the current matrix */
1.126     brouard  3322:       out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, 
                   3323:                   pmij(pmmij,cov,ncovmodel,x,nlstate));
1.217     brouard  3324:       /* if((int)age == 70){ */
                   3325:       /*       printf(" Forward hpxij age=%d agexact=%f d=%d nhstepm=%d hstepm=%d\n", (int) age, agexact, d, nhstepm, hstepm); */
                   3326:       /*       for(i=1; i<=nlstate+ndeath; i++) { */
                   3327:       /*         printf("%d pmmij ",i); */
                   3328:       /*         for(j=1;j<=nlstate+ndeath;j++) { */
                   3329:       /*           printf("%f ",pmmij[i][j]); */
                   3330:       /*         } */
                   3331:       /*         printf(" oldm "); */
                   3332:       /*         for(j=1;j<=nlstate+ndeath;j++) { */
                   3333:       /*           printf("%f ",oldm[i][j]); */
                   3334:       /*         } */
                   3335:       /*         printf("\n"); */
                   3336:       /*       } */
                   3337:       /* } */
1.126     brouard  3338:       savm=oldm;
                   3339:       oldm=newm;
                   3340:     }
                   3341:     for(i=1; i<=nlstate+ndeath; i++)
                   3342:       for(j=1;j<=nlstate+ndeath;j++) {
1.267     brouard  3343:        po[i][j][h]=newm[i][j];
                   3344:        /*if(h==nhstepm) printf("po[%d][%d][%d]=%f ",i,j,h,po[i][j][h]);*/
1.126     brouard  3345:       }
1.128     brouard  3346:     /*printf("h=%d ",h);*/
1.126     brouard  3347:   } /* end h */
1.267     brouard  3348:   /*     printf("\n H=%d \n",h); */
1.126     brouard  3349:   return po;
                   3350: }
                   3351: 
1.217     brouard  3352: /************* Higher Back Matrix Product ***************/
1.218     brouard  3353: /* 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  3354: 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  3355: {
1.266     brouard  3356:   /* For a combination of dummy covariate ij, computes the transition matrix starting at age 'age' over
1.217     brouard  3357:      'nhstepm*hstepm*stepm' months (i.e. until
1.218     brouard  3358:      age (in years)  age+nhstepm*hstepm*stepm/12) by multiplying
                   3359:      nhstepm*hstepm matrices.
                   3360:      Output is stored in matrix po[i][j][h] for h every 'hstepm' step
                   3361:      (typically every 2 years instead of every month which is too big
1.217     brouard  3362:      for the memory).
1.218     brouard  3363:      Model is determined by parameters x and covariates have to be
1.266     brouard  3364:      included manually here. Then we use a call to bmij(x and cov)
                   3365:      The addresss of po (p3mat allocated to the dimension of nhstepm) should be stored for output
1.222     brouard  3366:   */
1.217     brouard  3367: 
                   3368:   int i, j, d, h, k;
1.266     brouard  3369:   double **out, cov[NCOVMAX+1], **bmij();
                   3370:   double **newm, ***newmm;
1.217     brouard  3371:   double agexact;
                   3372:   double agebegin, ageend;
1.222     brouard  3373:   double **oldm, **savm;
1.217     brouard  3374: 
1.266     brouard  3375:   newmm=po; /* To be saved */
                   3376:   oldm=oldms;savm=savms; /* Global pointers */
1.217     brouard  3377:   /* Hstepm could be zero and should return the unit matrix */
                   3378:   for (i=1;i<=nlstate+ndeath;i++)
                   3379:     for (j=1;j<=nlstate+ndeath;j++){
                   3380:       oldm[i][j]=(i==j ? 1.0 : 0.0);
                   3381:       po[i][j][0]=(i==j ? 1.0 : 0.0);
                   3382:     }
                   3383:   /* Even if hstepm = 1, at least one multiplication by the unit matrix */
                   3384:   for(h=1; h <=nhstepm; h++){
                   3385:     for(d=1; d <=hstepm; d++){
                   3386:       newm=savm;
                   3387:       /* Covariates have to be included here again */
                   3388:       cov[1]=1.;
1.271     brouard  3389:       agexact=age-( (h-1)*hstepm + (d)  )*stepm/YEARM; /* age just before transition, d or d-1? */
1.217     brouard  3390:       /* agexact=age+((h-1)*hstepm + (d-1))*stepm/YEARM; /\* age just before transition *\/ */
                   3391:       cov[2]=agexact;
                   3392:       if(nagesqr==1)
1.222     brouard  3393:        cov[3]= agexact*agexact;
1.266     brouard  3394:       for (k=1; k<=cptcovn;k++){
                   3395:       /*       cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,k)]; */
                   3396:       /* /\* cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,Tvar[k])]; *\/ */
                   3397:        cov[2+nagesqr+TvarsDind[k]]=nbcode[TvarsD[k]][codtabm(ij,k)];
                   3398:         /* 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)); */
                   3399:       }
1.267     brouard  3400:       for (k=1; k<=nsq;k++) { /* For single varying covariates only */
                   3401:        /* Here comes the value of quantitative after renumbering k with single quantitative covariates */
                   3402:        cov[2+nagesqr+TvarsQind[k]]=Tqresult[nres][k]; 
                   3403:        /* 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]); */
                   3404:       }
                   3405:       for (k=1; k<=cptcovage;k++){ /* Should start at cptcovn+1 */
                   3406:        if(Dummy[Tvar[Tage[k]]]){
                   3407:          cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,k)]*cov[2];
                   3408:        } else{
                   3409:          cov[2+nagesqr+Tage[k]]=Tqresult[nres][k]; 
                   3410:        }
                   3411:        /* 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]); */
                   3412:       }
                   3413:       for (k=1; k<=cptcovprod;k++){ /* Useless because included in cptcovn */
1.222     brouard  3414:        cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)]*nbcode[Tvard[k][2]][codtabm(ij,k)];
1.267     brouard  3415:       }                        
1.217     brouard  3416:       /*printf("hxi cptcov=%d cptcode=%d\n",cptcov,cptcode);*/
                   3417:       /*printf("h=%d d=%d age=%f cov=%f\n",h,d,age,cov[2]);*/
1.267     brouard  3418: 
1.218     brouard  3419:       /* Careful transposed matrix */
1.266     brouard  3420:       /* age is in cov[2], prevacurrent at beginning of transition. */
1.218     brouard  3421:       /* out=matprod2(newm, bmij(pmmij,cov,ncovmodel,x,nlstate,prevacurrent, dnewm, doldm, dsavm,ij),\ */
1.222     brouard  3422:       /*                                                1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm); */
1.218     brouard  3423:       out=matprod2(newm, bmij(pmmij,cov,ncovmodel,x,nlstate,prevacurrent,ij),\
1.222     brouard  3424:                   1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm);
1.217     brouard  3425:       /* if((int)age == 70){ */
                   3426:       /*       printf(" Backward hbxij age=%d agexact=%f d=%d nhstepm=%d hstepm=%d\n", (int) age, agexact, d, nhstepm, hstepm); */
                   3427:       /*       for(i=1; i<=nlstate+ndeath; i++) { */
                   3428:       /*         printf("%d pmmij ",i); */
                   3429:       /*         for(j=1;j<=nlstate+ndeath;j++) { */
                   3430:       /*           printf("%f ",pmmij[i][j]); */
                   3431:       /*         } */
                   3432:       /*         printf(" oldm "); */
                   3433:       /*         for(j=1;j<=nlstate+ndeath;j++) { */
                   3434:       /*           printf("%f ",oldm[i][j]); */
                   3435:       /*         } */
                   3436:       /*         printf("\n"); */
                   3437:       /*       } */
                   3438:       /* } */
                   3439:       savm=oldm;
                   3440:       oldm=newm;
                   3441:     }
                   3442:     for(i=1; i<=nlstate+ndeath; i++)
                   3443:       for(j=1;j<=nlstate+ndeath;j++) {
1.222     brouard  3444:        po[i][j][h]=newm[i][j];
1.268     brouard  3445:        /* if(h==nhstepm) */
                   3446:        /*   printf("po[%d][%d][%d]=%f ",i,j,h,po[i][j][h]); */
1.217     brouard  3447:       }
1.268     brouard  3448:     /* printf("h=%d %.1f ",h, agexact); */
1.217     brouard  3449:   } /* end h */
1.268     brouard  3450:   /* printf("\n H=%d nhs=%d \n",h, nhstepm); */
1.217     brouard  3451:   return po;
                   3452: }
                   3453: 
                   3454: 
1.162     brouard  3455: #ifdef NLOPT
                   3456:   double  myfunc(unsigned n, const double *p1, double *grad, void *pd){
                   3457:   double fret;
                   3458:   double *xt;
                   3459:   int j;
                   3460:   myfunc_data *d2 = (myfunc_data *) pd;
                   3461: /* xt = (p1-1); */
                   3462:   xt=vector(1,n); 
                   3463:   for (j=1;j<=n;j++)   xt[j]=p1[j-1]; /* xt[1]=p1[0] */
                   3464: 
                   3465:   fret=(d2->function)(xt); /*  p xt[1]@8 is fine */
                   3466:   /* fret=(*func)(xt); /\*  p xt[1]@8 is fine *\/ */
                   3467:   printf("Function = %.12lf ",fret);
                   3468:   for (j=1;j<=n;j++) printf(" %d %.8lf", j, xt[j]); 
                   3469:   printf("\n");
                   3470:  free_vector(xt,1,n);
                   3471:   return fret;
                   3472: }
                   3473: #endif
1.126     brouard  3474: 
                   3475: /*************** log-likelihood *************/
                   3476: double func( double *x)
                   3477: {
1.226     brouard  3478:   int i, ii, j, k, mi, d, kk;
                   3479:   int ioffset=0;
                   3480:   double l, ll[NLSTATEMAX+1], cov[NCOVMAX+1];
                   3481:   double **out;
                   3482:   double lli; /* Individual log likelihood */
                   3483:   int s1, s2;
1.228     brouard  3484:   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  3485:   double bbh, survp;
                   3486:   long ipmx;
                   3487:   double agexact;
                   3488:   /*extern weight */
                   3489:   /* We are differentiating ll according to initial status */
                   3490:   /*  for (i=1;i<=npar;i++) printf("%f ", x[i]);*/
                   3491:   /*for(i=1;i<imx;i++) 
                   3492:     printf(" %d\n",s[4][i]);
                   3493:   */
1.162     brouard  3494: 
1.226     brouard  3495:   ++countcallfunc;
1.162     brouard  3496: 
1.226     brouard  3497:   cov[1]=1.;
1.126     brouard  3498: 
1.226     brouard  3499:   for(k=1; k<=nlstate; k++) ll[k]=0.;
1.224     brouard  3500:   ioffset=0;
1.226     brouard  3501:   if(mle==1){
                   3502:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
                   3503:       /* Computes the values of the ncovmodel covariates of the model
                   3504:         depending if the covariates are fixed or varying (age dependent) and stores them in cov[]
                   3505:         Then computes with function pmij which return a matrix p[i][j] giving the elementary probability
                   3506:         to be observed in j being in i according to the model.
                   3507:       */
1.243     brouard  3508:       ioffset=2+nagesqr ;
1.233     brouard  3509:    /* Fixed */
1.234     brouard  3510:       for (k=1; k<=ncovf;k++){ /* Simple and product fixed covariates without age* products */
                   3511:        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)*/
                   3512:       }
1.226     brouard  3513:       /* In model V2+V1*V4+age*V3+V3*V2 Tvar[1] is V2, Tvar[2=V1*V4] 
                   3514:         is 6, Tvar[3=age*V3] should not be computed because of age Tvar[4=V3*V2] 
                   3515:         has been calculated etc */
                   3516:       /* For an individual i, wav[i] gives the number of effective waves */
                   3517:       /* We compute the contribution to Likelihood of each effective transition
                   3518:         mw[mi][i] is real wave of the mi th effectve wave */
                   3519:       /* Then statuses are computed at each begin and end of an effective wave s1=s[ mw[mi][i] ][i];
                   3520:         s2=s[mw[mi+1][i]][i];
                   3521:         And the iv th varying covariate is the cotvar[mw[mi+1][i]][iv][i]
                   3522:         But if the variable is not in the model TTvar[iv] is the real variable effective in the model:
                   3523:         meaning that decodemodel should be used cotvar[mw[mi+1][i]][TTvar[iv]][i]
                   3524:       */
                   3525:       for(mi=1; mi<= wav[i]-1; mi++){
1.234     brouard  3526:        for(k=1; k <= ncovv ; k++){ /* Varying  covariates (single and product but no age )*/
1.242     brouard  3527:          /* cov[ioffset+TvarVind[k]]=cotvar[mw[mi][i]][Tvar[TvarVind[k]]][i]; */
                   3528:          cov[ioffset+TvarVind[k]]=cotvar[mw[mi][i]][Tvar[TvarVind[k]]-ncovcol-nqv][i];
1.234     brouard  3529:        }
                   3530:        for (ii=1;ii<=nlstate+ndeath;ii++)
                   3531:          for (j=1;j<=nlstate+ndeath;j++){
                   3532:            oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   3533:            savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   3534:          }
                   3535:        for(d=0; d<dh[mi][i]; d++){
                   3536:          newm=savm;
                   3537:          agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
                   3538:          cov[2]=agexact;
                   3539:          if(nagesqr==1)
                   3540:            cov[3]= agexact*agexact;  /* Should be changed here */
                   3541:          for (kk=1; kk<=cptcovage;kk++) {
1.242     brouard  3542:          if(!FixedV[Tvar[Tage[kk]]])
1.234     brouard  3543:            cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact; /* Tage[kk] gives the data-covariate associated with age */
1.242     brouard  3544:          else
                   3545:            cov[Tage[kk]+2+nagesqr]=cotvar[mw[mi][i]][Tvar[Tage[kk]]-ncovcol-nqv][i]*agexact;
1.234     brouard  3546:          }
                   3547:          out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   3548:                       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   3549:          savm=oldm;
                   3550:          oldm=newm;
                   3551:        } /* end mult */
                   3552:        
                   3553:        /*lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]);*/ /* Original formula */
                   3554:        /* But now since version 0.9 we anticipate for bias at large stepm.
                   3555:         * If stepm is larger than one month (smallest stepm) and if the exact delay 
                   3556:         * (in months) between two waves is not a multiple of stepm, we rounded to 
                   3557:         * the nearest (and in case of equal distance, to the lowest) interval but now
                   3558:         * we keep into memory the bias bh[mi][i] and also the previous matrix product
                   3559:         * (i.e to dh[mi][i]-1) saved in 'savm'. Then we inter(extra)polate the
                   3560:         * probability in order to take into account the bias as a fraction of the way
1.231     brouard  3561:                                 * from savm to out if bh is negative or even beyond if bh is positive. bh varies
                   3562:                                 * -stepm/2 to stepm/2 .
                   3563:                                 * For stepm=1 the results are the same as for previous versions of Imach.
                   3564:                                 * For stepm > 1 the results are less biased than in previous versions. 
                   3565:                                 */
1.234     brouard  3566:        s1=s[mw[mi][i]][i];
                   3567:        s2=s[mw[mi+1][i]][i];
                   3568:        bbh=(double)bh[mi][i]/(double)stepm; 
                   3569:        /* bias bh is positive if real duration
                   3570:         * is higher than the multiple of stepm and negative otherwise.
                   3571:         */
                   3572:        /* lli= (savm[s1][s2]>1.e-8 ?(1.+bbh)*log(out[s1][s2])- bbh*log(savm[s1][s2]):log((1.+bbh)*out[s1][s2]));*/
                   3573:        if( s2 > nlstate){ 
                   3574:          /* i.e. if s2 is a death state and if the date of death is known 
                   3575:             then the contribution to the likelihood is the probability to 
                   3576:             die between last step unit time and current  step unit time, 
                   3577:             which is also equal to probability to die before dh 
                   3578:             minus probability to die before dh-stepm . 
                   3579:             In version up to 0.92 likelihood was computed
                   3580:             as if date of death was unknown. Death was treated as any other
                   3581:             health state: the date of the interview describes the actual state
                   3582:             and not the date of a change in health state. The former idea was
                   3583:             to consider that at each interview the state was recorded
                   3584:             (healthy, disable or death) and IMaCh was corrected; but when we
                   3585:             introduced the exact date of death then we should have modified
                   3586:             the contribution of an exact death to the likelihood. This new
                   3587:             contribution is smaller and very dependent of the step unit
                   3588:             stepm. It is no more the probability to die between last interview
                   3589:             and month of death but the probability to survive from last
                   3590:             interview up to one month before death multiplied by the
                   3591:             probability to die within a month. Thanks to Chris
                   3592:             Jackson for correcting this bug.  Former versions increased
                   3593:             mortality artificially. The bad side is that we add another loop
                   3594:             which slows down the processing. The difference can be up to 10%
                   3595:             lower mortality.
                   3596:          */
                   3597:          /* If, at the beginning of the maximization mostly, the
                   3598:             cumulative probability or probability to be dead is
                   3599:             constant (ie = 1) over time d, the difference is equal to
                   3600:             0.  out[s1][3] = savm[s1][3]: probability, being at state
                   3601:             s1 at precedent wave, to be dead a month before current
                   3602:             wave is equal to probability, being at state s1 at
                   3603:             precedent wave, to be dead at mont of the current
                   3604:             wave. Then the observed probability (that this person died)
                   3605:             is null according to current estimated parameter. In fact,
                   3606:             it should be very low but not zero otherwise the log go to
                   3607:             infinity.
                   3608:          */
1.183     brouard  3609: /* #ifdef INFINITYORIGINAL */
                   3610: /*         lli=log(out[s1][s2] - savm[s1][s2]); */
                   3611: /* #else */
                   3612: /*       if ((out[s1][s2] - savm[s1][s2]) < mytinydouble)  */
                   3613: /*         lli=log(mytinydouble); */
                   3614: /*       else */
                   3615: /*         lli=log(out[s1][s2] - savm[s1][s2]); */
                   3616: /* #endif */
1.226     brouard  3617:          lli=log(out[s1][s2] - savm[s1][s2]);
1.216     brouard  3618:          
1.226     brouard  3619:        } else if  ( s2==-1 ) { /* alive */
                   3620:          for (j=1,survp=0. ; j<=nlstate; j++) 
                   3621:            survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
                   3622:          /*survp += out[s1][j]; */
                   3623:          lli= log(survp);
                   3624:        }
                   3625:        else if  (s2==-4) { 
                   3626:          for (j=3,survp=0. ; j<=nlstate; j++)  
                   3627:            survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
                   3628:          lli= log(survp); 
                   3629:        } 
                   3630:        else if  (s2==-5) { 
                   3631:          for (j=1,survp=0. ; j<=2; j++)  
                   3632:            survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
                   3633:          lli= log(survp); 
                   3634:        } 
                   3635:        else{
                   3636:          lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */
                   3637:          /*  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 */
                   3638:        } 
                   3639:        /*lli=(1.+bbh)*log(out[s1][s2])- bbh*log(savm[s1][s2]);*/
                   3640:        /*if(lli ==000.0)*/
                   3641:        /*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); */
                   3642:        ipmx +=1;
                   3643:        sw += weight[i];
                   3644:        ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
                   3645:        /* if (lli < log(mytinydouble)){ */
                   3646:        /*   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); */
                   3647:        /*   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]); */
                   3648:        /* } */
                   3649:       } /* end of wave */
                   3650:     } /* end of individual */
                   3651:   }  else if(mle==2){
                   3652:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
                   3653:       for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i];
                   3654:       for(mi=1; mi<= wav[i]-1; mi++){
                   3655:        for (ii=1;ii<=nlstate+ndeath;ii++)
                   3656:          for (j=1;j<=nlstate+ndeath;j++){
                   3657:            oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   3658:            savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   3659:          }
                   3660:        for(d=0; d<=dh[mi][i]; d++){
                   3661:          newm=savm;
                   3662:          agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
                   3663:          cov[2]=agexact;
                   3664:          if(nagesqr==1)
                   3665:            cov[3]= agexact*agexact;
                   3666:          for (kk=1; kk<=cptcovage;kk++) {
                   3667:            cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact;
                   3668:          }
                   3669:          out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   3670:                       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   3671:          savm=oldm;
                   3672:          oldm=newm;
                   3673:        } /* end mult */
                   3674:       
                   3675:        s1=s[mw[mi][i]][i];
                   3676:        s2=s[mw[mi+1][i]][i];
                   3677:        bbh=(double)bh[mi][i]/(double)stepm; 
                   3678:        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 */
                   3679:        ipmx +=1;
                   3680:        sw += weight[i];
                   3681:        ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
                   3682:       } /* end of wave */
                   3683:     } /* end of individual */
                   3684:   }  else if(mle==3){  /* exponential inter-extrapolation */
                   3685:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
                   3686:       for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i];
                   3687:       for(mi=1; mi<= wav[i]-1; mi++){
                   3688:        for (ii=1;ii<=nlstate+ndeath;ii++)
                   3689:          for (j=1;j<=nlstate+ndeath;j++){
                   3690:            oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   3691:            savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   3692:          }
                   3693:        for(d=0; d<dh[mi][i]; d++){
                   3694:          newm=savm;
                   3695:          agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
                   3696:          cov[2]=agexact;
                   3697:          if(nagesqr==1)
                   3698:            cov[3]= agexact*agexact;
                   3699:          for (kk=1; kk<=cptcovage;kk++) {
                   3700:            cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact;
                   3701:          }
                   3702:          out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   3703:                       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   3704:          savm=oldm;
                   3705:          oldm=newm;
                   3706:        } /* end mult */
                   3707:       
                   3708:        s1=s[mw[mi][i]][i];
                   3709:        s2=s[mw[mi+1][i]][i];
                   3710:        bbh=(double)bh[mi][i]/(double)stepm; 
                   3711:        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 */
                   3712:        ipmx +=1;
                   3713:        sw += weight[i];
                   3714:        ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
                   3715:       } /* end of wave */
                   3716:     } /* end of individual */
                   3717:   }else if (mle==4){  /* ml=4 no inter-extrapolation */
                   3718:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
                   3719:       for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i];
                   3720:       for(mi=1; mi<= wav[i]-1; mi++){
                   3721:        for (ii=1;ii<=nlstate+ndeath;ii++)
                   3722:          for (j=1;j<=nlstate+ndeath;j++){
                   3723:            oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   3724:            savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   3725:          }
                   3726:        for(d=0; d<dh[mi][i]; d++){
                   3727:          newm=savm;
                   3728:          agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
                   3729:          cov[2]=agexact;
                   3730:          if(nagesqr==1)
                   3731:            cov[3]= agexact*agexact;
                   3732:          for (kk=1; kk<=cptcovage;kk++) {
                   3733:            cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact;
                   3734:          }
1.126     brouard  3735:        
1.226     brouard  3736:          out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   3737:                       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   3738:          savm=oldm;
                   3739:          oldm=newm;
                   3740:        } /* end mult */
                   3741:       
                   3742:        s1=s[mw[mi][i]][i];
                   3743:        s2=s[mw[mi+1][i]][i];
                   3744:        if( s2 > nlstate){ 
                   3745:          lli=log(out[s1][s2] - savm[s1][s2]);
                   3746:        } else if  ( s2==-1 ) { /* alive */
                   3747:          for (j=1,survp=0. ; j<=nlstate; j++) 
                   3748:            survp += out[s1][j];
                   3749:          lli= log(survp);
                   3750:        }else{
                   3751:          lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]); /* Original formula */
                   3752:        }
                   3753:        ipmx +=1;
                   3754:        sw += weight[i];
                   3755:        ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
1.126     brouard  3756: /*     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  3757:       } /* end of wave */
                   3758:     } /* end of individual */
                   3759:   }else{  /* ml=5 no inter-extrapolation no jackson =0.8a */
                   3760:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
                   3761:       for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i];
                   3762:       for(mi=1; mi<= wav[i]-1; mi++){
                   3763:        for (ii=1;ii<=nlstate+ndeath;ii++)
                   3764:          for (j=1;j<=nlstate+ndeath;j++){
                   3765:            oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   3766:            savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   3767:          }
                   3768:        for(d=0; d<dh[mi][i]; d++){
                   3769:          newm=savm;
                   3770:          agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
                   3771:          cov[2]=agexact;
                   3772:          if(nagesqr==1)
                   3773:            cov[3]= agexact*agexact;
                   3774:          for (kk=1; kk<=cptcovage;kk++) {
                   3775:            cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact;
                   3776:          }
1.126     brouard  3777:        
1.226     brouard  3778:          out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   3779:                       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   3780:          savm=oldm;
                   3781:          oldm=newm;
                   3782:        } /* end mult */
                   3783:       
                   3784:        s1=s[mw[mi][i]][i];
                   3785:        s2=s[mw[mi+1][i]][i];
                   3786:        lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]); /* Original formula */
                   3787:        ipmx +=1;
                   3788:        sw += weight[i];
                   3789:        ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
                   3790:        /*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]);*/
                   3791:       } /* end of wave */
                   3792:     } /* end of individual */
                   3793:   } /* End of if */
                   3794:   for(k=1,l=0.; k<=nlstate; k++) l += ll[k];
                   3795:   /* printf("l1=%f l2=%f ",ll[1],ll[2]); */
                   3796:   l= l*ipmx/sw; /* To get the same order of magnitude as if weight=1 for every body */
                   3797:   return -l;
1.126     brouard  3798: }
                   3799: 
                   3800: /*************** log-likelihood *************/
                   3801: double funcone( double *x)
                   3802: {
1.228     brouard  3803:   /* Same as func but slower because of a lot of printf and if */
1.126     brouard  3804:   int i, ii, j, k, mi, d, kk;
1.228     brouard  3805:   int ioffset=0;
1.131     brouard  3806:   double l, ll[NLSTATEMAX+1], cov[NCOVMAX+1];
1.126     brouard  3807:   double **out;
                   3808:   double lli; /* Individual log likelihood */
                   3809:   double llt;
                   3810:   int s1, s2;
1.228     brouard  3811:   int iv=0, iqv=0, itv=0, iqtv=0 ; /* Index of varying covariate, fixed quantitative cov, time varying covariate, quantitative time varying covariate */
                   3812: 
1.126     brouard  3813:   double bbh, survp;
1.187     brouard  3814:   double agexact;
1.214     brouard  3815:   double agebegin, ageend;
1.126     brouard  3816:   /*extern weight */
                   3817:   /* We are differentiating ll according to initial status */
                   3818:   /*  for (i=1;i<=npar;i++) printf("%f ", x[i]);*/
                   3819:   /*for(i=1;i<imx;i++) 
                   3820:     printf(" %d\n",s[4][i]);
                   3821:   */
                   3822:   cov[1]=1.;
                   3823: 
                   3824:   for(k=1; k<=nlstate; k++) ll[k]=0.;
1.224     brouard  3825:   ioffset=0;
                   3826:   for (i=1,ipmx=0, sw=0.; i<=imx; i++){
1.243     brouard  3827:     /* ioffset=2+nagesqr+cptcovage; */
                   3828:     ioffset=2+nagesqr;
1.232     brouard  3829:     /* Fixed */
1.224     brouard  3830:     /* for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i]; */
1.232     brouard  3831:     /* for (k=1; k<=ncoveff;k++){ /\* Simple and product fixed Dummy covariates without age* products *\/ */
                   3832:     for (k=1; k<=ncovf;k++){ /* Simple and product fixed covariates without age* products */
                   3833:       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)*/
                   3834: /*    cov[ioffset+TvarFind[1]]=covar[Tvar[TvarFind[1]]][i];  */
                   3835: /*    cov[2+6]=covar[Tvar[6]][i];  */
                   3836: /*    cov[2+6]=covar[2][i]; V2  */
                   3837: /*    cov[TvarFind[2]]=covar[Tvar[TvarFind[2]]][i];  */
                   3838: /*    cov[2+7]=covar[Tvar[7]][i];  */
                   3839: /*    cov[2+7]=covar[7][i]; V7=V1*V2  */
                   3840: /*    cov[TvarFind[3]]=covar[Tvar[TvarFind[3]]][i];  */
                   3841: /*    cov[2+9]=covar[Tvar[9]][i];  */
                   3842: /*    cov[2+9]=covar[1][i]; V1  */
1.225     brouard  3843:     }
1.232     brouard  3844:     /* for (k=1; k<=nqfveff;k++){ /\* Simple and product fixed Quantitative covariates without age* products *\/ */
                   3845:     /*   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?)*\/ */
                   3846:     /* } */
1.231     brouard  3847:     /* for(iqv=1; iqv <= nqfveff; iqv++){ /\* Quantitative fixed covariates *\/ */
                   3848:     /*   cov[++ioffset]=coqvar[Tvar[iqv]][i]; /\* Only V2 k=6 and V1*V2 7 *\/ */
                   3849:     /* } */
1.225     brouard  3850:     
1.233     brouard  3851: 
                   3852:     for(mi=1; mi<= wav[i]-1; mi++){  /* Varying with waves */
1.232     brouard  3853:     /* Wave varying (but not age varying) */
                   3854:       for(k=1; k <= ncovv ; k++){ /* Varying  covariates (single and product but no age )*/
1.242     brouard  3855:        /* cov[ioffset+TvarVind[k]]=cotvar[mw[mi][i]][Tvar[TvarVind[k]]][i]; */
                   3856:        cov[ioffset+TvarVind[k]]=cotvar[mw[mi][i]][Tvar[TvarVind[k]]-ncovcol-nqv][i];
                   3857:       }
1.232     brouard  3858:       /* for(itv=1; itv <= ntveff; itv++){ /\* Varying dummy covariates (single??)*\/ */
1.242     brouard  3859:       /* iv= Tvar[Tmodelind[ioffset-2-nagesqr-cptcovage+itv]]-ncovcol-nqv; /\* Counting the # varying covariate from 1 to ntveff *\/ */
                   3860:       /* cov[ioffset+iv]=cotvar[mw[mi][i]][iv][i]; */
                   3861:       /* k=ioffset-2-nagesqr-cptcovage+itv; /\* position in simple model *\/ */
                   3862:       /* cov[ioffset+itv]=cotvar[mw[mi][i]][TmodelInvind[itv]][i]; */
                   3863:       /* 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  3864:       /* for(iqtv=1; iqtv <= nqtveff; iqtv++){ /\* Varying quantitatives covariates *\/ */
1.242     brouard  3865:       /*       iv=TmodelInvQind[iqtv]; /\* Counting the # varying covariate from 1 to ntveff *\/ */
                   3866:       /*       /\* 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]); *\/ */
                   3867:       /*       cov[ioffset+ntveff+iqtv]=cotqvar[mw[mi][i]][TmodelInvQind[iqtv]][i]; */
1.232     brouard  3868:       /* } */
1.126     brouard  3869:       for (ii=1;ii<=nlstate+ndeath;ii++)
1.242     brouard  3870:        for (j=1;j<=nlstate+ndeath;j++){
                   3871:          oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   3872:          savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   3873:        }
1.214     brouard  3874:       
                   3875:       agebegin=agev[mw[mi][i]][i]; /* Age at beginning of effective wave */
                   3876:       ageend=agev[mw[mi][i]][i] + (dh[mi][i])*stepm/YEARM; /* Age at end of effective wave and at the end of transition */
                   3877:       for(d=0; d<dh[mi][i]; d++){  /* Delay between two effective waves */
1.247     brouard  3878:       /* for(d=0; d<=0; d++){  /\* Delay between two effective waves Only one matrix to speed up*\/ */
1.242     brouard  3879:        /*dh[m][i] or dh[mw[mi][i]][i] is the delay between two effective waves m=mw[mi][i]
                   3880:          and mw[mi+1][i]. dh depends on stepm.*/
                   3881:        newm=savm;
1.247     brouard  3882:        agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;  /* Here d is needed */
1.242     brouard  3883:        cov[2]=agexact;
                   3884:        if(nagesqr==1)
                   3885:          cov[3]= agexact*agexact;
                   3886:        for (kk=1; kk<=cptcovage;kk++) {
                   3887:          if(!FixedV[Tvar[Tage[kk]]])
                   3888:            cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact;
                   3889:          else
                   3890:            cov[Tage[kk]+2+nagesqr]=cotvar[mw[mi][i]][Tvar[Tage[kk]]-ncovcol-nqv][i]*agexact;
                   3891:        }
                   3892:        /* printf("i=%d,mi=%d,d=%d,mw[mi][i]=%d\n",i, mi,d,mw[mi][i]); */
                   3893:        /* savm=pmij(pmmij,cov,ncovmodel,x,nlstate); */
                   3894:        out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   3895:                     1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   3896:        /* out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath, */
                   3897:        /*           1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate)); */
                   3898:        savm=oldm;
                   3899:        oldm=newm;
1.126     brouard  3900:       } /* end mult */
                   3901:       
                   3902:       s1=s[mw[mi][i]][i];
                   3903:       s2=s[mw[mi+1][i]][i];
1.217     brouard  3904:       /* if(s2==-1){ */
1.268     brouard  3905:       /*       printf(" ERROR s1=%d, s2=%d i=%d \n", s1, s2, i); */
1.217     brouard  3906:       /*       /\* exit(1); *\/ */
                   3907:       /* } */
1.126     brouard  3908:       bbh=(double)bh[mi][i]/(double)stepm; 
                   3909:       /* bias is positive if real duration
                   3910:        * is higher than the multiple of stepm and negative otherwise.
                   3911:        */
                   3912:       if( s2 > nlstate && (mle <5) ){  /* Jackson */
1.242     brouard  3913:        lli=log(out[s1][s2] - savm[s1][s2]);
1.216     brouard  3914:       } else if  ( s2==-1 ) { /* alive */
1.242     brouard  3915:        for (j=1,survp=0. ; j<=nlstate; j++) 
                   3916:          survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
                   3917:        lli= log(survp);
1.126     brouard  3918:       }else if (mle==1){
1.242     brouard  3919:        lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */
1.126     brouard  3920:       } else if(mle==2){
1.242     brouard  3921:        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  3922:       } else if(mle==3){  /* exponential inter-extrapolation */
1.242     brouard  3923:        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  3924:       } else if (mle==4){  /* mle=4 no inter-extrapolation */
1.242     brouard  3925:        lli=log(out[s1][s2]); /* Original formula */
1.136     brouard  3926:       } else{  /* mle=0 back to 1 */
1.242     brouard  3927:        lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */
                   3928:        /*lli=log(out[s1][s2]); */ /* Original formula */
1.126     brouard  3929:       } /* End of if */
                   3930:       ipmx +=1;
                   3931:       sw += weight[i];
                   3932:       ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
1.132     brouard  3933:       /*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  3934:       if(globpr){
1.246     brouard  3935:        fprintf(ficresilk,"%09ld %6.1f %6.1f %6d %2d %2d %2d %2d %3d %15.6f %8.4f %8.3f\
1.126     brouard  3936:  %11.6f %11.6f %11.6f ", \
1.242     brouard  3937:                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  3938:                2*weight[i]*lli,(s2==-1? -1: out[s1][s2]),(s2==-1? -1: savm[s1][s2]));
1.242     brouard  3939:        for(k=1,llt=0.,l=0.; k<=nlstate; k++){
                   3940:          llt +=ll[k]*gipmx/gsw;
                   3941:          fprintf(ficresilk," %10.6f",-ll[k]*gipmx/gsw);
                   3942:        }
                   3943:        fprintf(ficresilk," %10.6f\n", -llt);
1.126     brouard  3944:       }
1.232     brouard  3945:        } /* end of wave */
                   3946: } /* end of individual */
                   3947: for(k=1,l=0.; k<=nlstate; k++) l += ll[k];
                   3948: /* printf("l1=%f l2=%f ",ll[1],ll[2]); */
                   3949: l= l*ipmx/sw; /* To get the same order of magnitude as if weight=1 for every body */
                   3950: if(globpr==0){ /* First time we count the contributions and weights */
                   3951:        gipmx=ipmx;
                   3952:        gsw=sw;
                   3953: }
                   3954: return -l;
1.126     brouard  3955: }
                   3956: 
                   3957: 
                   3958: /*************** function likelione ***********/
1.292     brouard  3959: void likelione(FILE *ficres,double p[], int npar, int nlstate, int *globpri, long *ipmx, double *sw, double *fretone, double (*func)(double []))
1.126     brouard  3960: {
                   3961:   /* This routine should help understanding what is done with 
                   3962:      the selection of individuals/waves and
                   3963:      to check the exact contribution to the likelihood.
                   3964:      Plotting could be done.
                   3965:    */
                   3966:   int k;
                   3967: 
                   3968:   if(*globpri !=0){ /* Just counts and sums, no printings */
1.201     brouard  3969:     strcpy(fileresilk,"ILK_"); 
1.202     brouard  3970:     strcat(fileresilk,fileresu);
1.126     brouard  3971:     if((ficresilk=fopen(fileresilk,"w"))==NULL) {
                   3972:       printf("Problem with resultfile: %s\n", fileresilk);
                   3973:       fprintf(ficlog,"Problem with resultfile: %s\n", fileresilk);
                   3974:     }
1.214     brouard  3975:     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");
                   3976:     fprintf(ficresilk, "#num_i ageb agend i s1 s2 mi mw dh likeli weight %%weight 2wlli out sav ");
1.126     brouard  3977:     /*         i,s1,s2,mi,mw[mi][i],dh[mi][i],exp(lli),weight[i],2*weight[i]*lli,out[s1][s2],savm[s1][s2]); */
                   3978:     for(k=1; k<=nlstate; k++) 
                   3979:       fprintf(ficresilk," -2*gipw/gsw*weight*ll[%d]++",k);
                   3980:     fprintf(ficresilk," -2*gipw/gsw*weight*ll(total)\n");
                   3981:   }
                   3982: 
1.292     brouard  3983:   *fretone=(*func)(p);
1.126     brouard  3984:   if(*globpri !=0){
                   3985:     fclose(ficresilk);
1.205     brouard  3986:     if (mle ==0)
                   3987:       fprintf(fichtm,"\n<br>File of contributions to the likelihood computed with initial parameters and mle = %d.",mle);
                   3988:     else if(mle >=1)
                   3989:       fprintf(fichtm,"\n<br>File of contributions to the likelihood computed with optimized parameters mle = %d.",mle);
                   3990:     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  3991:     fprintf(fichtm,"\n<br>Equation of the model: <b>model=1+age+%s</b><br>\n",model); 
1.208     brouard  3992:       
                   3993:     for (k=1; k<= nlstate ; k++) {
1.211     brouard  3994:       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  3995: <img src=\"%s-p%dj.png\">",k,k,subdirf2(optionfilefiname,"ILK_"),k,subdirf2(optionfilefiname,"ILK_"),k,subdirf2(optionfilefiname,"ILK_"),k);
                   3996:     }
1.207     brouard  3997:     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  3998: <img src=\"%s-ori.png\">",subdirf2(optionfilefiname,"ILK_"),subdirf2(optionfilefiname,"ILK_"),subdirf2(optionfilefiname,"ILK_"));
1.207     brouard  3999:     fprintf(fichtm,"<br>- and by state of destination <a href=\"%s-dest.png\">%s-dest.png</a><br> \
1.204     brouard  4000: <img src=\"%s-dest.png\">",subdirf2(optionfilefiname,"ILK_"),subdirf2(optionfilefiname,"ILK_"),subdirf2(optionfilefiname,"ILK_"));
1.207     brouard  4001:     fflush(fichtm);
1.205     brouard  4002:   }
1.126     brouard  4003:   return;
                   4004: }
                   4005: 
                   4006: 
                   4007: /*********** Maximum Likelihood Estimation ***************/
                   4008: 
                   4009: void mlikeli(FILE *ficres,double p[], int npar, int ncovmodel, int nlstate, double ftol, double (*func)(double []))
                   4010: {
1.165     brouard  4011:   int i,j, iter=0;
1.126     brouard  4012:   double **xi;
                   4013:   double fret;
                   4014:   double fretone; /* Only one call to likelihood */
                   4015:   /*  char filerespow[FILENAMELENGTH];*/
1.162     brouard  4016: 
                   4017: #ifdef NLOPT
                   4018:   int creturn;
                   4019:   nlopt_opt opt;
                   4020:   /* double lb[9] = { -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL }; /\* lower bounds *\/ */
                   4021:   double *lb;
                   4022:   double minf; /* the minimum objective value, upon return */
                   4023:   double * p1; /* Shifted parameters from 0 instead of 1 */
                   4024:   myfunc_data dinst, *d = &dinst;
                   4025: #endif
                   4026: 
                   4027: 
1.126     brouard  4028:   xi=matrix(1,npar,1,npar);
                   4029:   for (i=1;i<=npar;i++)
                   4030:     for (j=1;j<=npar;j++)
                   4031:       xi[i][j]=(i==j ? 1.0 : 0.0);
                   4032:   printf("Powell\n");  fprintf(ficlog,"Powell\n");
1.201     brouard  4033:   strcpy(filerespow,"POW_"); 
1.126     brouard  4034:   strcat(filerespow,fileres);
                   4035:   if((ficrespow=fopen(filerespow,"w"))==NULL) {
                   4036:     printf("Problem with resultfile: %s\n", filerespow);
                   4037:     fprintf(ficlog,"Problem with resultfile: %s\n", filerespow);
                   4038:   }
                   4039:   fprintf(ficrespow,"# Powell\n# iter -2*LL");
                   4040:   for (i=1;i<=nlstate;i++)
                   4041:     for(j=1;j<=nlstate+ndeath;j++)
                   4042:       if(j!=i)fprintf(ficrespow," p%1d%1d",i,j);
                   4043:   fprintf(ficrespow,"\n");
1.162     brouard  4044: #ifdef POWELL
1.126     brouard  4045:   powell(p,xi,npar,ftol,&iter,&fret,func);
1.162     brouard  4046: #endif
1.126     brouard  4047: 
1.162     brouard  4048: #ifdef NLOPT
                   4049: #ifdef NEWUOA
                   4050:   opt = nlopt_create(NLOPT_LN_NEWUOA,npar);
                   4051: #else
                   4052:   opt = nlopt_create(NLOPT_LN_BOBYQA,npar);
                   4053: #endif
                   4054:   lb=vector(0,npar-1);
                   4055:   for (i=0;i<npar;i++) lb[i]= -HUGE_VAL;
                   4056:   nlopt_set_lower_bounds(opt, lb);
                   4057:   nlopt_set_initial_step1(opt, 0.1);
                   4058:   
                   4059:   p1= (p+1); /*  p *(p+1)@8 and p *(p1)@8 are equal p1[0]=p[1] */
                   4060:   d->function = func;
                   4061:   printf(" Func %.12lf \n",myfunc(npar,p1,NULL,d));
                   4062:   nlopt_set_min_objective(opt, myfunc, d);
                   4063:   nlopt_set_xtol_rel(opt, ftol);
                   4064:   if ((creturn=nlopt_optimize(opt, p1, &minf)) < 0) {
                   4065:     printf("nlopt failed! %d\n",creturn); 
                   4066:   }
                   4067:   else {
                   4068:     printf("found minimum after %d evaluations (NLOPT=%d)\n", countcallfunc ,NLOPT);
                   4069:     printf("found minimum at f(%g,%g) = %0.10g\n", p[0], p[1], minf);
                   4070:     iter=1; /* not equal */
                   4071:   }
                   4072:   nlopt_destroy(opt);
                   4073: #endif
1.126     brouard  4074:   free_matrix(xi,1,npar,1,npar);
                   4075:   fclose(ficrespow);
1.203     brouard  4076:   printf("\n#Number of iterations & function calls = %d & %d, -2 Log likelihood = %.12f\n",iter, countcallfunc,func(p));
                   4077:   fprintf(ficlog,"\n#Number of iterations & function calls = %d & %d, -2 Log likelihood = %.12f\n",iter, countcallfunc,func(p));
1.180     brouard  4078:   fprintf(ficres,"#Number of iterations & function calls = %d & %d, -2 Log likelihood = %.12f\n",iter, countcallfunc,func(p));
1.126     brouard  4079: 
                   4080: }
                   4081: 
                   4082: /**** Computes Hessian and covariance matrix ***/
1.203     brouard  4083: void hesscov(double **matcov, double **hess, double p[], int npar, double delti[], double ftolhess, double (*func)(double []))
1.126     brouard  4084: {
                   4085:   double  **a,**y,*x,pd;
1.203     brouard  4086:   /* double **hess; */
1.164     brouard  4087:   int i, j;
1.126     brouard  4088:   int *indx;
                   4089: 
                   4090:   double hessii(double p[], double delta, int theta, double delti[],double (*func)(double []),int npar);
1.203     brouard  4091:   double hessij(double p[], double **hess, double delti[], int i, int j,double (*func)(double []),int npar);
1.126     brouard  4092:   void lubksb(double **a, int npar, int *indx, double b[]) ;
                   4093:   void ludcmp(double **a, int npar, int *indx, double *d) ;
                   4094:   double gompertz(double p[]);
1.203     brouard  4095:   /* hess=matrix(1,npar,1,npar); */
1.126     brouard  4096: 
                   4097:   printf("\nCalculation of the hessian matrix. Wait...\n");
                   4098:   fprintf(ficlog,"\nCalculation of the hessian matrix. Wait...\n");
                   4099:   for (i=1;i<=npar;i++){
1.203     brouard  4100:     printf("%d-",i);fflush(stdout);
                   4101:     fprintf(ficlog,"%d-",i);fflush(ficlog);
1.126     brouard  4102:    
                   4103:      hess[i][i]=hessii(p,ftolhess,i,delti,func,npar);
                   4104:     
                   4105:     /*  printf(" %f ",p[i]);
                   4106:        printf(" %lf %lf %lf",hess[i][i],ftolhess,delti[i]);*/
                   4107:   }
                   4108:   
                   4109:   for (i=1;i<=npar;i++) {
                   4110:     for (j=1;j<=npar;j++)  {
                   4111:       if (j>i) { 
1.203     brouard  4112:        printf(".%d-%d",i,j);fflush(stdout);
                   4113:        fprintf(ficlog,".%d-%d",i,j);fflush(ficlog);
                   4114:        hess[i][j]=hessij(p,hess, delti,i,j,func,npar);
1.126     brouard  4115:        
                   4116:        hess[j][i]=hess[i][j];    
                   4117:        /*printf(" %lf ",hess[i][j]);*/
                   4118:       }
                   4119:     }
                   4120:   }
                   4121:   printf("\n");
                   4122:   fprintf(ficlog,"\n");
                   4123: 
                   4124:   printf("\nInverting the hessian to get the covariance matrix. Wait...\n");
                   4125:   fprintf(ficlog,"\nInverting the hessian to get the covariance matrix. Wait...\n");
                   4126:   
                   4127:   a=matrix(1,npar,1,npar);
                   4128:   y=matrix(1,npar,1,npar);
                   4129:   x=vector(1,npar);
                   4130:   indx=ivector(1,npar);
                   4131:   for (i=1;i<=npar;i++)
                   4132:     for (j=1;j<=npar;j++) a[i][j]=hess[i][j];
                   4133:   ludcmp(a,npar,indx,&pd);
                   4134: 
                   4135:   for (j=1;j<=npar;j++) {
                   4136:     for (i=1;i<=npar;i++) x[i]=0;
                   4137:     x[j]=1;
                   4138:     lubksb(a,npar,indx,x);
                   4139:     for (i=1;i<=npar;i++){ 
                   4140:       matcov[i][j]=x[i];
                   4141:     }
                   4142:   }
                   4143: 
                   4144:   printf("\n#Hessian matrix#\n");
                   4145:   fprintf(ficlog,"\n#Hessian matrix#\n");
                   4146:   for (i=1;i<=npar;i++) { 
                   4147:     for (j=1;j<=npar;j++) { 
1.203     brouard  4148:       printf("%.6e ",hess[i][j]);
                   4149:       fprintf(ficlog,"%.6e ",hess[i][j]);
1.126     brouard  4150:     }
                   4151:     printf("\n");
                   4152:     fprintf(ficlog,"\n");
                   4153:   }
                   4154: 
1.203     brouard  4155:   /* printf("\n#Covariance matrix#\n"); */
                   4156:   /* fprintf(ficlog,"\n#Covariance matrix#\n"); */
                   4157:   /* for (i=1;i<=npar;i++) {  */
                   4158:   /*   for (j=1;j<=npar;j++) {  */
                   4159:   /*     printf("%.6e ",matcov[i][j]); */
                   4160:   /*     fprintf(ficlog,"%.6e ",matcov[i][j]); */
                   4161:   /*   } */
                   4162:   /*   printf("\n"); */
                   4163:   /*   fprintf(ficlog,"\n"); */
                   4164:   /* } */
                   4165: 
1.126     brouard  4166:   /* Recompute Inverse */
1.203     brouard  4167:   /* for (i=1;i<=npar;i++) */
                   4168:   /*   for (j=1;j<=npar;j++) a[i][j]=matcov[i][j]; */
                   4169:   /* ludcmp(a,npar,indx,&pd); */
                   4170: 
                   4171:   /*  printf("\n#Hessian matrix recomputed#\n"); */
                   4172: 
                   4173:   /* for (j=1;j<=npar;j++) { */
                   4174:   /*   for (i=1;i<=npar;i++) x[i]=0; */
                   4175:   /*   x[j]=1; */
                   4176:   /*   lubksb(a,npar,indx,x); */
                   4177:   /*   for (i=1;i<=npar;i++){  */
                   4178:   /*     y[i][j]=x[i]; */
                   4179:   /*     printf("%.3e ",y[i][j]); */
                   4180:   /*     fprintf(ficlog,"%.3e ",y[i][j]); */
                   4181:   /*   } */
                   4182:   /*   printf("\n"); */
                   4183:   /*   fprintf(ficlog,"\n"); */
                   4184:   /* } */
                   4185: 
                   4186:   /* Verifying the inverse matrix */
                   4187: #ifdef DEBUGHESS
                   4188:   y=matprod2(y,hess,1,npar,1,npar,1,npar,matcov);
1.126     brouard  4189: 
1.203     brouard  4190:    printf("\n#Verification: multiplying the matrix of covariance by the Hessian matrix, should be unity:#\n");
                   4191:    fprintf(ficlog,"\n#Verification: multiplying the matrix of covariance by the Hessian matrix. Should be unity:#\n");
1.126     brouard  4192: 
                   4193:   for (j=1;j<=npar;j++) {
                   4194:     for (i=1;i<=npar;i++){ 
1.203     brouard  4195:       printf("%.2f ",y[i][j]);
                   4196:       fprintf(ficlog,"%.2f ",y[i][j]);
1.126     brouard  4197:     }
                   4198:     printf("\n");
                   4199:     fprintf(ficlog,"\n");
                   4200:   }
1.203     brouard  4201: #endif
1.126     brouard  4202: 
                   4203:   free_matrix(a,1,npar,1,npar);
                   4204:   free_matrix(y,1,npar,1,npar);
                   4205:   free_vector(x,1,npar);
                   4206:   free_ivector(indx,1,npar);
1.203     brouard  4207:   /* free_matrix(hess,1,npar,1,npar); */
1.126     brouard  4208: 
                   4209: 
                   4210: }
                   4211: 
                   4212: /*************** hessian matrix ****************/
                   4213: double hessii(double x[], double delta, int theta, double delti[], double (*func)(double []), int npar)
1.203     brouard  4214: { /* Around values of x, computes the function func and returns the scales delti and hessian */
1.126     brouard  4215:   int i;
                   4216:   int l=1, lmax=20;
1.203     brouard  4217:   double k1,k2, res, fx;
1.132     brouard  4218:   double p2[MAXPARM+1]; /* identical to x */
1.126     brouard  4219:   double delt=0.0001, delts, nkhi=10.,nkhif=1., khi=1.e-4;
                   4220:   int k=0,kmax=10;
                   4221:   double l1;
                   4222: 
                   4223:   fx=func(x);
                   4224:   for (i=1;i<=npar;i++) p2[i]=x[i];
1.145     brouard  4225:   for(l=0 ; l <=lmax; l++){  /* Enlarging the zone around the Maximum */
1.126     brouard  4226:     l1=pow(10,l);
                   4227:     delts=delt;
                   4228:     for(k=1 ; k <kmax; k=k+1){
                   4229:       delt = delta*(l1*k);
                   4230:       p2[theta]=x[theta] +delt;
1.145     brouard  4231:       k1=func(p2)-fx;   /* Might be negative if too close to the theoretical maximum */
1.126     brouard  4232:       p2[theta]=x[theta]-delt;
                   4233:       k2=func(p2)-fx;
                   4234:       /*res= (k1-2.0*fx+k2)/delt/delt; */
1.203     brouard  4235:       res= (k1+k2)/delt/delt/2.; /* Divided by 2 because L and not 2*L */
1.126     brouard  4236:       
1.203     brouard  4237: #ifdef DEBUGHESSII
1.126     brouard  4238:       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);
                   4239:       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);
                   4240: #endif
                   4241:       /*if(fabs(k1-2.0*fx+k2) <1.e-13){ */
                   4242:       if((k1 <khi/nkhi/2.) || (k2 <khi/nkhi/2.)){
                   4243:        k=kmax;
                   4244:       }
                   4245:       else if((k1 >khi/nkhif) || (k2 >khi/nkhif)){ /* Keeps lastvalue before 3.84/2 KHI2 5% 1d.f. */
1.164     brouard  4246:        k=kmax; l=lmax*10;
1.126     brouard  4247:       }
                   4248:       else if((k1 >khi/nkhi) || (k2 >khi/nkhi)){ 
                   4249:        delts=delt;
                   4250:       }
1.203     brouard  4251:     } /* End loop k */
1.126     brouard  4252:   }
                   4253:   delti[theta]=delts;
                   4254:   return res; 
                   4255:   
                   4256: }
                   4257: 
1.203     brouard  4258: double hessij( double x[], double **hess, double delti[], int thetai,int thetaj,double (*func)(double []),int npar)
1.126     brouard  4259: {
                   4260:   int i;
1.164     brouard  4261:   int l=1, lmax=20;
1.126     brouard  4262:   double k1,k2,k3,k4,res,fx;
1.132     brouard  4263:   double p2[MAXPARM+1];
1.203     brouard  4264:   int k, kmax=1;
                   4265:   double v1, v2, cv12, lc1, lc2;
1.208     brouard  4266: 
                   4267:   int firstime=0;
1.203     brouard  4268:   
1.126     brouard  4269:   fx=func(x);
1.203     brouard  4270:   for (k=1; k<=kmax; k=k+10) {
1.126     brouard  4271:     for (i=1;i<=npar;i++) p2[i]=x[i];
1.203     brouard  4272:     p2[thetai]=x[thetai]+delti[thetai]*k;
                   4273:     p2[thetaj]=x[thetaj]+delti[thetaj]*k;
1.126     brouard  4274:     k1=func(p2)-fx;
                   4275:   
1.203     brouard  4276:     p2[thetai]=x[thetai]+delti[thetai]*k;
                   4277:     p2[thetaj]=x[thetaj]-delti[thetaj]*k;
1.126     brouard  4278:     k2=func(p2)-fx;
                   4279:   
1.203     brouard  4280:     p2[thetai]=x[thetai]-delti[thetai]*k;
                   4281:     p2[thetaj]=x[thetaj]+delti[thetaj]*k;
1.126     brouard  4282:     k3=func(p2)-fx;
                   4283:   
1.203     brouard  4284:     p2[thetai]=x[thetai]-delti[thetai]*k;
                   4285:     p2[thetaj]=x[thetaj]-delti[thetaj]*k;
1.126     brouard  4286:     k4=func(p2)-fx;
1.203     brouard  4287:     res=(k1-k2-k3+k4)/4.0/delti[thetai]/k/delti[thetaj]/k/2.; /* Because of L not 2*L */
                   4288:     if(k1*k2*k3*k4 <0.){
1.208     brouard  4289:       firstime=1;
1.203     brouard  4290:       kmax=kmax+10;
1.208     brouard  4291:     }
                   4292:     if(kmax >=10 || firstime ==1){
1.246     brouard  4293:       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);
                   4294:       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  4295:       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);
                   4296:       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);
                   4297:     }
                   4298: #ifdef DEBUGHESSIJ
                   4299:     v1=hess[thetai][thetai];
                   4300:     v2=hess[thetaj][thetaj];
                   4301:     cv12=res;
                   4302:     /* Computing eigen value of Hessian matrix */
                   4303:     lc1=((v1+v2)+sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
                   4304:     lc2=((v1+v2)-sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
                   4305:     if ((lc2 <0) || (lc1 <0) ){
                   4306:       printf("Warning: sub Hessian matrix '%d%d' does not have positive eigen values \n",thetai,thetaj);
                   4307:       fprintf(ficlog, "Warning: sub Hessian matrix '%d%d' does not have positive eigen values \n",thetai,thetaj);
                   4308:       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);
                   4309:       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);
                   4310:     }
1.126     brouard  4311: #endif
                   4312:   }
                   4313:   return res;
                   4314: }
                   4315: 
1.203     brouard  4316:     /* Not done yet: Was supposed to fix if not exactly at the maximum */
                   4317: /* double hessij( double x[], double delti[], int thetai,int thetaj,double (*func)(double []),int npar) */
                   4318: /* { */
                   4319: /*   int i; */
                   4320: /*   int l=1, lmax=20; */
                   4321: /*   double k1,k2,k3,k4,res,fx; */
                   4322: /*   double p2[MAXPARM+1]; */
                   4323: /*   double delt=0.0001, delts, nkhi=10.,nkhif=1., khi=1.e-4; */
                   4324: /*   int k=0,kmax=10; */
                   4325: /*   double l1; */
                   4326:   
                   4327: /*   fx=func(x); */
                   4328: /*   for(l=0 ; l <=lmax; l++){  /\* Enlarging the zone around the Maximum *\/ */
                   4329: /*     l1=pow(10,l); */
                   4330: /*     delts=delt; */
                   4331: /*     for(k=1 ; k <kmax; k=k+1){ */
                   4332: /*       delt = delti*(l1*k); */
                   4333: /*       for (i=1;i<=npar;i++) p2[i]=x[i]; */
                   4334: /*       p2[thetai]=x[thetai]+delti[thetai]/k; */
                   4335: /*       p2[thetaj]=x[thetaj]+delti[thetaj]/k; */
                   4336: /*       k1=func(p2)-fx; */
                   4337:       
                   4338: /*       p2[thetai]=x[thetai]+delti[thetai]/k; */
                   4339: /*       p2[thetaj]=x[thetaj]-delti[thetaj]/k; */
                   4340: /*       k2=func(p2)-fx; */
                   4341:       
                   4342: /*       p2[thetai]=x[thetai]-delti[thetai]/k; */
                   4343: /*       p2[thetaj]=x[thetaj]+delti[thetaj]/k; */
                   4344: /*       k3=func(p2)-fx; */
                   4345:       
                   4346: /*       p2[thetai]=x[thetai]-delti[thetai]/k; */
                   4347: /*       p2[thetaj]=x[thetaj]-delti[thetaj]/k; */
                   4348: /*       k4=func(p2)-fx; */
                   4349: /*       res=(k1-k2-k3+k4)/4.0/delti[thetai]*k/delti[thetaj]*k/2.; /\* Because of L not 2*L *\/ */
                   4350: /* #ifdef DEBUGHESSIJ */
                   4351: /*       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); */
                   4352: /*       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); */
                   4353: /* #endif */
                   4354: /*       if((k1 <khi/nkhi/2.) || (k2 <khi/nkhi/2.)|| (k4 <khi/nkhi/2.)|| (k4 <khi/nkhi/2.)){ */
                   4355: /*     k=kmax; */
                   4356: /*       } */
                   4357: /*       else if((k1 >khi/nkhif) || (k2 >khi/nkhif) || (k4 >khi/nkhif) || (k4 >khi/nkhif)){ /\* Keeps lastvalue before 3.84/2 KHI2 5% 1d.f. *\/ */
                   4358: /*     k=kmax; l=lmax*10; */
                   4359: /*       } */
                   4360: /*       else if((k1 >khi/nkhi) || (k2 >khi/nkhi)){  */
                   4361: /*     delts=delt; */
                   4362: /*       } */
                   4363: /*     } /\* End loop k *\/ */
                   4364: /*   } */
                   4365: /*   delti[theta]=delts; */
                   4366: /*   return res;  */
                   4367: /* } */
                   4368: 
                   4369: 
1.126     brouard  4370: /************** Inverse of matrix **************/
                   4371: void ludcmp(double **a, int n, int *indx, double *d) 
                   4372: { 
                   4373:   int i,imax,j,k; 
                   4374:   double big,dum,sum,temp; 
                   4375:   double *vv; 
                   4376:  
                   4377:   vv=vector(1,n); 
                   4378:   *d=1.0; 
                   4379:   for (i=1;i<=n;i++) { 
                   4380:     big=0.0; 
                   4381:     for (j=1;j<=n;j++) 
                   4382:       if ((temp=fabs(a[i][j])) > big) big=temp; 
1.256     brouard  4383:     if (big == 0.0){
                   4384:       printf(" Singular Hessian matrix at row %d:\n",i);
                   4385:       for (j=1;j<=n;j++) {
                   4386:        printf(" a[%d][%d]=%f,",i,j,a[i][j]);
                   4387:        fprintf(ficlog," a[%d][%d]=%f,",i,j,a[i][j]);
                   4388:       }
                   4389:       fflush(ficlog);
                   4390:       fclose(ficlog);
                   4391:       nrerror("Singular matrix in routine ludcmp"); 
                   4392:     }
1.126     brouard  4393:     vv[i]=1.0/big; 
                   4394:   } 
                   4395:   for (j=1;j<=n;j++) { 
                   4396:     for (i=1;i<j;i++) { 
                   4397:       sum=a[i][j]; 
                   4398:       for (k=1;k<i;k++) sum -= a[i][k]*a[k][j]; 
                   4399:       a[i][j]=sum; 
                   4400:     } 
                   4401:     big=0.0; 
                   4402:     for (i=j;i<=n;i++) { 
                   4403:       sum=a[i][j]; 
                   4404:       for (k=1;k<j;k++) 
                   4405:        sum -= a[i][k]*a[k][j]; 
                   4406:       a[i][j]=sum; 
                   4407:       if ( (dum=vv[i]*fabs(sum)) >= big) { 
                   4408:        big=dum; 
                   4409:        imax=i; 
                   4410:       } 
                   4411:     } 
                   4412:     if (j != imax) { 
                   4413:       for (k=1;k<=n;k++) { 
                   4414:        dum=a[imax][k]; 
                   4415:        a[imax][k]=a[j][k]; 
                   4416:        a[j][k]=dum; 
                   4417:       } 
                   4418:       *d = -(*d); 
                   4419:       vv[imax]=vv[j]; 
                   4420:     } 
                   4421:     indx[j]=imax; 
                   4422:     if (a[j][j] == 0.0) a[j][j]=TINY; 
                   4423:     if (j != n) { 
                   4424:       dum=1.0/(a[j][j]); 
                   4425:       for (i=j+1;i<=n;i++) a[i][j] *= dum; 
                   4426:     } 
                   4427:   } 
                   4428:   free_vector(vv,1,n);  /* Doesn't work */
                   4429: ;
                   4430: } 
                   4431: 
                   4432: void lubksb(double **a, int n, int *indx, double b[]) 
                   4433: { 
                   4434:   int i,ii=0,ip,j; 
                   4435:   double sum; 
                   4436:  
                   4437:   for (i=1;i<=n;i++) { 
                   4438:     ip=indx[i]; 
                   4439:     sum=b[ip]; 
                   4440:     b[ip]=b[i]; 
                   4441:     if (ii) 
                   4442:       for (j=ii;j<=i-1;j++) sum -= a[i][j]*b[j]; 
                   4443:     else if (sum) ii=i; 
                   4444:     b[i]=sum; 
                   4445:   } 
                   4446:   for (i=n;i>=1;i--) { 
                   4447:     sum=b[i]; 
                   4448:     for (j=i+1;j<=n;j++) sum -= a[i][j]*b[j]; 
                   4449:     b[i]=sum/a[i][i]; 
                   4450:   } 
                   4451: } 
                   4452: 
                   4453: void pstamp(FILE *fichier)
                   4454: {
1.196     brouard  4455:   fprintf(fichier,"# %s.%s\n#IMaCh version %s, %s\n#%s\n# %s", optionfilefiname,optionfilext,version,copyright, fullversion, strstart);
1.126     brouard  4456: }
                   4457: 
1.297     brouard  4458: void date2dmy(double date,double *day, double *month, double *year){
                   4459:   double yp=0., yp1=0., yp2=0.;
                   4460:   
                   4461:   yp1=modf(date,&yp);/* extracts integral of date in yp  and
                   4462:                        fractional in yp1 */
                   4463:   *year=yp;
                   4464:   yp2=modf((yp1*12),&yp);
                   4465:   *month=yp;
                   4466:   yp1=modf((yp2*30.5),&yp);
                   4467:   *day=yp;
                   4468:   if(*day==0) *day=1;
                   4469:   if(*month==0) *month=1;
                   4470: }
                   4471: 
1.253     brouard  4472: 
                   4473: 
1.126     brouard  4474: /************ Frequencies ********************/
1.251     brouard  4475: void  freqsummary(char fileres[], double p[], double pstart[], int iagemin, int iagemax, int **s, double **agev, int nlstate, int imx, \
1.226     brouard  4476:                  int *Tvaraff, int *invalidvarcomb, int **nbcode, int *ncodemax,double **mint,double **anint, char strstart[], \
                   4477:                  int firstpass,  int lastpass, int stepm, int weightopt, char model[])
1.250     brouard  4478: {  /* Some frequencies as well as proposing some starting values */
1.226     brouard  4479:   
1.265     brouard  4480:   int i, m, jk, j1, bool, z1,j, nj, nl, k, iv, jj=0, s1=1, s2=1;
1.226     brouard  4481:   int iind=0, iage=0;
                   4482:   int mi; /* Effective wave */
                   4483:   int first;
                   4484:   double ***freq; /* Frequencies */
1.268     brouard  4485:   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 */
                   4486:   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  4487:   double *meanq, *stdq, *idq;
1.226     brouard  4488:   double **meanqt;
                   4489:   double *pp, **prop, *posprop, *pospropt;
                   4490:   double pos=0., posproptt=0., pospropta=0., k2, dateintsum=0,k2cpt=0;
                   4491:   char fileresp[FILENAMELENGTH], fileresphtm[FILENAMELENGTH], fileresphtmfr[FILENAMELENGTH];
                   4492:   double agebegin, ageend;
                   4493:     
                   4494:   pp=vector(1,nlstate);
1.251     brouard  4495:   prop=matrix(1,nlstate,iagemin-AGEMARGE,iagemax+4+AGEMARGE); 
1.226     brouard  4496:   posprop=vector(1,nlstate); /* Counting the number of transition starting from a live state per age */ 
                   4497:   pospropt=vector(1,nlstate); /* Counting the number of transition starting from a live state */ 
                   4498:   /* prop=matrix(1,nlstate,iagemin,iagemax+3); */
                   4499:   meanq=vector(1,nqfveff); /* Number of Quantitative Fixed Variables Effective */
1.284     brouard  4500:   stdq=vector(1,nqfveff); /* Number of Quantitative Fixed Variables Effective */
1.283     brouard  4501:   idq=vector(1,nqfveff); /* Number of Quantitative Fixed Variables Effective */
1.226     brouard  4502:   meanqt=matrix(1,lastpass,1,nqtveff);
                   4503:   strcpy(fileresp,"P_");
                   4504:   strcat(fileresp,fileresu);
                   4505:   /*strcat(fileresphtm,fileresu);*/
                   4506:   if((ficresp=fopen(fileresp,"w"))==NULL) {
                   4507:     printf("Problem with prevalence resultfile: %s\n", fileresp);
                   4508:     fprintf(ficlog,"Problem with prevalence resultfile: %s\n", fileresp);
                   4509:     exit(0);
                   4510:   }
1.240     brouard  4511:   
1.226     brouard  4512:   strcpy(fileresphtm,subdirfext(optionfilefiname,"PHTM_",".htm"));
                   4513:   if((ficresphtm=fopen(fileresphtm,"w"))==NULL) {
                   4514:     printf("Problem with prevalence HTM resultfile '%s' with errno='%s'\n",fileresphtm,strerror(errno));
                   4515:     fprintf(ficlog,"Problem with prevalence HTM resultfile '%s' with errno='%s'\n",fileresphtm,strerror(errno));
                   4516:     fflush(ficlog);
                   4517:     exit(70); 
                   4518:   }
                   4519:   else{
                   4520:     fprintf(ficresphtm,"<html><head>\n<title>IMaCh PHTM_ %s</title></head>\n <body><font size=\"2\">%s <br> %s</font> \
1.240     brouard  4521: <hr size=\"2\" color=\"#EC5E5E\"> \n                                   \
1.214     brouard  4522: Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=1+age+%s<br>\n",\
1.226     brouard  4523:            fileresphtm,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model);
                   4524:   }
1.237     brouard  4525:   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  4526:   
1.226     brouard  4527:   strcpy(fileresphtmfr,subdirfext(optionfilefiname,"PHTMFR_",".htm"));
                   4528:   if((ficresphtmfr=fopen(fileresphtmfr,"w"))==NULL) {
                   4529:     printf("Problem with frequency table HTM resultfile '%s' with errno='%s'\n",fileresphtmfr,strerror(errno));
                   4530:     fprintf(ficlog,"Problem with frequency table HTM resultfile '%s' with errno='%s'\n",fileresphtmfr,strerror(errno));
                   4531:     fflush(ficlog);
                   4532:     exit(70); 
1.240     brouard  4533:   } else{
1.226     brouard  4534:     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  4535: <hr size=\"2\" color=\"#EC5E5E\"> \n                                   \
1.214     brouard  4536: Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=1+age+%s<br>\n",\
1.226     brouard  4537:            fileresphtmfr,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model);
                   4538:   }
1.240     brouard  4539:   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);
                   4540:   
1.253     brouard  4541:   y= vector(iagemin-AGEMARGE,iagemax+4+AGEMARGE);
                   4542:   x= vector(iagemin-AGEMARGE,iagemax+4+AGEMARGE);
1.251     brouard  4543:   freq= ma3x(-5,nlstate+ndeath,-5,nlstate+ndeath,iagemin-AGEMARGE,iagemax+4+AGEMARGE);
1.226     brouard  4544:   j1=0;
1.126     brouard  4545:   
1.227     brouard  4546:   /* j=ncoveff;  /\* Only fixed dummy covariates *\/ */
                   4547:   j=cptcoveff;  /* Only dummy covariates of the model */
1.226     brouard  4548:   if (cptcovn<1) {j=1;ncodemax[1]=1;}
1.240     brouard  4549:   
                   4550:   
1.226     brouard  4551:   /* Detects if a combination j1 is empty: for a multinomial variable like 3 education levels:
                   4552:      reference=low_education V1=0,V2=0
                   4553:      med_educ                V1=1 V2=0, 
                   4554:      high_educ               V1=0 V2=1
                   4555:      Then V1=1 and V2=1 is a noisy combination that we want to exclude for the list 2**cptcoveff 
                   4556:   */
1.249     brouard  4557:   dateintsum=0;
                   4558:   k2cpt=0;
                   4559: 
1.253     brouard  4560:   if(cptcoveff == 0 )
1.265     brouard  4561:     nl=1;  /* Constant and age model only */
1.253     brouard  4562:   else
                   4563:     nl=2;
1.265     brouard  4564: 
                   4565:   /* if a constant only model, one pass to compute frequency tables and to write it on ficresp */
                   4566:   /* Loop on nj=1 or 2 if dummy covariates j!=0
                   4567:    *   Loop on j1(1 to 2**cptcoveff) covariate combination
                   4568:    *     freq[s1][s2][iage] =0.
                   4569:    *     Loop on iind
                   4570:    *       ++freq[s1][s2][iage] weighted
                   4571:    *     end iind
                   4572:    *     if covariate and j!0
                   4573:    *       headers Variable on one line
                   4574:    *     endif cov j!=0
                   4575:    *     header of frequency table by age
                   4576:    *     Loop on age
                   4577:    *       pp[s1]+=freq[s1][s2][iage] weighted
                   4578:    *       pos+=freq[s1][s2][iage] weighted
                   4579:    *       Loop on s1 initial state
                   4580:    *         fprintf(ficresp
                   4581:    *       end s1
                   4582:    *     end age
                   4583:    *     if j!=0 computes starting values
                   4584:    *     end compute starting values
                   4585:    *   end j1
                   4586:    * end nl 
                   4587:    */
1.253     brouard  4588:   for (nj = 1; nj <= nl; nj++){   /* nj= 1 constant model, nl number of loops. */
                   4589:     if(nj==1)
                   4590:       j=0;  /* First pass for the constant */
1.265     brouard  4591:     else{
1.253     brouard  4592:       j=cptcoveff; /* Other passes for the covariate values */
1.265     brouard  4593:     }
1.251     brouard  4594:     first=1;
1.265     brouard  4595:     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  4596:       posproptt=0.;
                   4597:       /*printf("cptcoveff=%d Tvaraff=%d", cptcoveff,Tvaraff[1]);
                   4598:        scanf("%d", i);*/
                   4599:       for (i=-5; i<=nlstate+ndeath; i++)  
1.265     brouard  4600:        for (s2=-5; s2<=nlstate+ndeath; s2++)  
1.251     brouard  4601:          for(m=iagemin; m <= iagemax+3; m++)
1.265     brouard  4602:            freq[i][s2][m]=0;
1.251     brouard  4603:       
                   4604:       for (i=1; i<=nlstate; i++)  {
1.240     brouard  4605:        for(m=iagemin; m <= iagemax+3; m++)
1.251     brouard  4606:          prop[i][m]=0;
                   4607:        posprop[i]=0;
                   4608:        pospropt[i]=0;
                   4609:       }
1.283     brouard  4610:       for (z1=1; z1<= nqfveff; z1++) { /* zeroing for each combination j1 as well as for the total */
1.284     brouard  4611:         idq[z1]=0.;
                   4612:         meanq[z1]=0.;
                   4613:         stdq[z1]=0.;
1.283     brouard  4614:       }
                   4615:       /* for (z1=1; z1<= nqtveff; z1++) { */
1.251     brouard  4616:       /*   for(m=1;m<=lastpass;m++){ */
1.283     brouard  4617:       /*         meanqt[m][z1]=0.; */
                   4618:       /*       } */
                   4619:       /* }       */
1.251     brouard  4620:       /* dateintsum=0; */
                   4621:       /* k2cpt=0; */
                   4622:       
1.265     brouard  4623:       /* For that combination of covariates j1 (V4=1 V3=0 for example), we count and print the frequencies in one pass */
1.251     brouard  4624:       for (iind=1; iind<=imx; iind++) { /* For each individual iind */
                   4625:        bool=1;
                   4626:        if(j !=0){
                   4627:          if(anyvaryingduminmodel==0){ /* If All fixed covariates */
                   4628:            if (cptcoveff >0) { /* Filter is here: Must be looked at for model=V1+V2+V3+V4 */
                   4629:              for (z1=1; z1<=cptcoveff; z1++) { /* loops on covariates in the model */
                   4630:                /* if(Tvaraff[z1] ==-20){ */
                   4631:                /*       /\* sumnew+=cotvar[mw[mi][iind]][z1][iind]; *\/ */
                   4632:                /* }else  if(Tvaraff[z1] ==-10){ */
                   4633:                /*       /\* sumnew+=coqvar[z1][iind]; *\/ */
                   4634:                /* }else  */
                   4635:                if (covar[Tvaraff[z1]][iind]!= nbcode[Tvaraff[z1]][codtabm(j1,z1)]){ /* for combination j1 of covariates */
1.265     brouard  4636:                  /* Tests if the value of the covariate z1 for this individual iind responded to combination j1 (V4=1 V3=0) */
1.251     brouard  4637:                  bool=0; /* bool should be equal to 1 to be selected, one covariate value failed */
                   4638:                  /* 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", 
                   4639:                     bool,i,z1, z1, Tvaraff[z1],i,covar[Tvaraff[z1]][i],j1,z1,codtabm(j1,z1),
                   4640:                     j1,z1,nbcode[Tvaraff[z1]][codtabm(j1,z1)],j1);*/
                   4641:                  /* For j1=7 in V1+V2+V3+V4 = 0 1 1 0 and codtabm(7,3)=1 and nbcde[3][?]=1*/
                   4642:                } /* Onlyf fixed */
                   4643:              } /* end z1 */
                   4644:            } /* cptcovn > 0 */
                   4645:          } /* end any */
                   4646:        }/* end j==0 */
1.265     brouard  4647:        if (bool==1){ /* We selected an individual iind satisfying combination j1 (V4=1 V3=0) or all fixed covariates */
1.251     brouard  4648:          /* for(m=firstpass; m<=lastpass; m++){ */
1.284     brouard  4649:          for(mi=1; mi<wav[iind];mi++){ /* For each wave */
1.251     brouard  4650:            m=mw[mi][iind];
                   4651:            if(j!=0){
                   4652:              if(anyvaryingduminmodel==1){ /* Some are varying covariates */
                   4653:                for (z1=1; z1<=cptcoveff; z1++) {
                   4654:                  if( Fixed[Tmodelind[z1]]==1){
                   4655:                    iv= Tvar[Tmodelind[z1]]-ncovcol-nqv;
                   4656:                    if (cotvar[m][iv][iind]!= nbcode[Tvaraff[z1]][codtabm(j1,z1)]) /* iv=1 to ntv, right modality. If covariate's 
                   4657:                                                                                      value is -1, we don't select. It differs from the 
                   4658:                                                                                      constant and age model which counts them. */
                   4659:                      bool=0; /* not selected */
                   4660:                  }else if( Fixed[Tmodelind[z1]]== 0) { /* fixed */
                   4661:                    if (covar[Tvaraff[z1]][iind]!= nbcode[Tvaraff[z1]][codtabm(j1,z1)]) {
                   4662:                      bool=0;
                   4663:                    }
                   4664:                  }
                   4665:                }
                   4666:              }/* Some are varying covariates, we tried to speed up if all fixed covariates in the model, avoiding waves loop  */
                   4667:            } /* end j==0 */
                   4668:            /* bool =0 we keep that guy which corresponds to the combination of dummy values */
1.284     brouard  4669:            if(bool==1){ /*Selected */
1.251     brouard  4670:              /* dh[m][iind] or dh[mw[mi][iind]][iind] is the delay between two effective (mi) waves m=mw[mi][iind]
                   4671:                 and mw[mi+1][iind]. dh depends on stepm. */
                   4672:              agebegin=agev[m][iind]; /* Age at beginning of wave before transition*/
                   4673:              ageend=agev[m][iind]+(dh[m][iind])*stepm/YEARM; /* Age at end of wave and transition */
                   4674:              if(m >=firstpass && m <=lastpass){
                   4675:                k2=anint[m][iind]+(mint[m][iind]/12.);
                   4676:                /*if ((k2>=dateprev1) && (k2<=dateprev2)) {*/
                   4677:                if(agev[m][iind]==0) agev[m][iind]=iagemax+1;  /* All ages equal to 0 are in iagemax+1 */
                   4678:                if(agev[m][iind]==1) agev[m][iind]=iagemax+2;  /* All ages equal to 1 are in iagemax+2 */
                   4679:                if (s[m][iind]>0 && s[m][iind]<=nlstate)  /* If status at wave m is known and a live state */
                   4680:                  prop[s[m][iind]][(int)agev[m][iind]] += weight[iind];  /* At age of beginning of transition, where status is known */
                   4681:                if (m<lastpass) {
                   4682:                  /* if(s[m][iind]==4 && s[m+1][iind]==4) */
                   4683:                  /*   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]); */
                   4684:                  if(s[m][iind]==-1)
                   4685:                    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.));
                   4686:                  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  4687:                  for (z1=1; z1<= nqfveff; z1++) { /* Quantitative variables, calculating mean */
                   4688:                    idq[z1]=idq[z1]+weight[iind];
                   4689:                    meanq[z1]+=covar[ncovcol+z1][iind]*weight[iind];  /* Computes mean of quantitative with selected filter */
                   4690:                    stdq[z1]+=covar[ncovcol+z1][iind]*covar[ncovcol+z1][iind]*weight[iind]*weight[iind]; /* *weight[iind];*/  /* Computes mean of quantitative with selected filter */
                   4691:                  }
1.251     brouard  4692:                  /* if((int)agev[m][iind] == 55) */
                   4693:                  /*   printf("j=%d, j1=%d Age %d, iind=%d, num=%09ld m=%d\n",j,j1,(int)agev[m][iind],iind, num[iind],m); */
                   4694:                  /* freq[s[m][iind]][s[m+1][iind]][(int)((agebegin+ageend)/2.)] += weight[iind]; */
                   4695:                  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  4696:                }
1.251     brouard  4697:              } /* end if between passes */  
                   4698:              if ((agev[m][iind]>1) && (agev[m][iind]< (iagemax+3)) && (anint[m][iind]!=9999) && (mint[m][iind]!=99) && (j==0)) {
                   4699:                dateintsum=dateintsum+k2; /* on all covariates ?*/
                   4700:                k2cpt++;
                   4701:                /* printf("iind=%ld dateintmean = %lf dateintsum=%lf k2cpt=%lf k2=%lf\n",iind, dateintsum/k2cpt, dateintsum,k2cpt, k2); */
1.234     brouard  4702:              }
1.251     brouard  4703:            }else{
                   4704:              bool=1;
                   4705:            }/* end bool 2 */
                   4706:          } /* end m */
1.284     brouard  4707:          /* for (z1=1; z1<= nqfveff; z1++) { /\* Quantitative variables, calculating mean *\/ */
                   4708:          /*   idq[z1]=idq[z1]+weight[iind]; */
                   4709:          /*   meanq[z1]+=covar[ncovcol+z1][iind]*weight[iind];  /\* Computes mean of quantitative with selected filter *\/ */
                   4710:          /*   stdq[z1]+=covar[ncovcol+z1][iind]*covar[ncovcol+z1][iind]*weight[iind]*weight[iind]; /\* *weight[iind];*\/  /\* Computes mean of quantitative with selected filter *\/ */
                   4711:          /* } */
1.251     brouard  4712:        } /* end bool */
                   4713:       } /* end iind = 1 to imx */
                   4714:       /* prop[s][age] is feeded for any initial and valid live state as well as
                   4715:         freq[s1][s2][age] at single age of beginning the transition, for a combination j1 */
                   4716:       
                   4717:       
                   4718:       /*      fprintf(ficresp, "#Count between %.lf/%.lf/%.lf and %.lf/%.lf/%.lf\n",jprev1, mprev1,anprev1,jprev2, mprev2,anprev2);*/
1.265     brouard  4719:       if(cptcoveff==0 && nj==1) /* no covariate and first pass */
                   4720:         pstamp(ficresp);
1.251     brouard  4721:       if  (cptcoveff>0 && j!=0){
1.265     brouard  4722:         pstamp(ficresp);
1.251     brouard  4723:        printf( "\n#********** Variable "); 
                   4724:        fprintf(ficresp, "\n#********** Variable "); 
                   4725:        fprintf(ficresphtm, "\n<br/><br/><h3>********** Variable "); 
                   4726:        fprintf(ficresphtmfr, "\n<br/><br/><h3>********** Variable "); 
                   4727:        fprintf(ficlog, "\n#********** Variable "); 
                   4728:        for (z1=1; z1<=cptcoveff; z1++){
                   4729:          if(!FixedV[Tvaraff[z1]]){
                   4730:            printf( "V%d(fixed)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
                   4731:            fprintf(ficresp, "V%d(fixed)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
                   4732:            fprintf(ficresphtm, "V%d(fixed)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
                   4733:            fprintf(ficresphtmfr, "V%d(fixed)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
                   4734:            fprintf(ficlog, "V%d(fixed)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
1.250     brouard  4735:          }else{
1.251     brouard  4736:            printf( "V%d(varying)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
                   4737:            fprintf(ficresp, "V%d(varying)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
                   4738:            fprintf(ficresphtm, "V%d(varying)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
                   4739:            fprintf(ficresphtmfr, "V%d(varying)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
                   4740:            fprintf(ficlog, "V%d(varying)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
                   4741:          }
                   4742:        }
                   4743:        printf( "**********\n#");
                   4744:        fprintf(ficresp, "**********\n#");
                   4745:        fprintf(ficresphtm, "**********</h3>\n");
                   4746:        fprintf(ficresphtmfr, "**********</h3>\n");
                   4747:        fprintf(ficlog, "**********\n");
                   4748:       }
1.284     brouard  4749:       /*
                   4750:        Printing means of quantitative variables if any
                   4751:       */
                   4752:       for (z1=1; z1<= nqfveff; z1++) {
1.285     brouard  4753:        fprintf(ficlog,"Mean of fixed quantitative variable V%d on %.0f individuals sum=%f", ncovcol+z1, idq[z1], meanq[z1]);
1.284     brouard  4754:        fprintf(ficlog,", mean=%.3g\n",meanq[z1]/idq[z1]);
                   4755:        if(weightopt==1){
                   4756:          printf(" Weighted mean and standard deviation of");
                   4757:          fprintf(ficlog," Weighted mean and standard deviation of");
                   4758:          fprintf(ficresphtmfr," Weighted mean and standard deviation of");
                   4759:        }
1.285     brouard  4760:        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]));
                   4761:        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]));
                   4762:        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  4763:       }
                   4764:       /* for (z1=1; z1<= nqtveff; z1++) { */
                   4765:       /*       for(m=1;m<=lastpass;m++){ */
                   4766:       /*         fprintf(ficresphtmfr,"V quantitative id %d, pass id=%d, mean=%f<p>\n", z1, m, meanqt[m][z1]); */
                   4767:       /*   } */
                   4768:       /* } */
1.283     brouard  4769: 
1.251     brouard  4770:       fprintf(ficresphtm,"<table style=\"text-align:center; border: 1px solid\">");
1.265     brouard  4771:       if((cptcoveff==0 && nj==1)|| nj==2 ) /* no covariate and first pass */
                   4772:         fprintf(ficresp, " Age");
                   4773:       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  4774:       for(i=1; i<=nlstate;i++) {
1.265     brouard  4775:        if((cptcoveff==0 && nj==1)|| nj==2 ) fprintf(ficresp," Prev(%d)  N(%d)  N  ",i,i);
1.251     brouard  4776:        fprintf(ficresphtm, "<th>Age</th><th>Prev(%d)</th><th>N(%d)</th><th>N</th>",i,i);
                   4777:       }
1.265     brouard  4778:       if((cptcoveff==0 && nj==1)|| nj==2 ) fprintf(ficresp, "\n");
1.251     brouard  4779:       fprintf(ficresphtm, "\n");
                   4780:       
                   4781:       /* Header of frequency table by age */
                   4782:       fprintf(ficresphtmfr,"<table style=\"text-align:center; border: 1px solid\">");
                   4783:       fprintf(ficresphtmfr,"<th>Age</th> ");
1.265     brouard  4784:       for(s2=-1; s2 <=nlstate+ndeath; s2++){
1.251     brouard  4785:        for(m=-1; m <=nlstate+ndeath; m++){
1.265     brouard  4786:          if(s2!=0 && m!=0)
                   4787:            fprintf(ficresphtmfr,"<th>%d%d</th> ",s2,m);
1.240     brouard  4788:        }
1.226     brouard  4789:       }
1.251     brouard  4790:       fprintf(ficresphtmfr, "\n");
                   4791:     
                   4792:       /* For each age */
                   4793:       for(iage=iagemin; iage <= iagemax+3; iage++){
                   4794:        fprintf(ficresphtm,"<tr>");
                   4795:        if(iage==iagemax+1){
                   4796:          fprintf(ficlog,"1");
                   4797:          fprintf(ficresphtmfr,"<tr><th>0</th> ");
                   4798:        }else if(iage==iagemax+2){
                   4799:          fprintf(ficlog,"0");
                   4800:          fprintf(ficresphtmfr,"<tr><th>Unknown</th> ");
                   4801:        }else if(iage==iagemax+3){
                   4802:          fprintf(ficlog,"Total");
                   4803:          fprintf(ficresphtmfr,"<tr><th>Total</th> ");
                   4804:        }else{
1.240     brouard  4805:          if(first==1){
1.251     brouard  4806:            first=0;
                   4807:            printf("See log file for details...\n");
                   4808:          }
                   4809:          fprintf(ficresphtmfr,"<tr><th>%d</th> ",iage);
                   4810:          fprintf(ficlog,"Age %d", iage);
                   4811:        }
1.265     brouard  4812:        for(s1=1; s1 <=nlstate ; s1++){
                   4813:          for(m=-1, pp[s1]=0; m <=nlstate+ndeath ; m++)
                   4814:            pp[s1] += freq[s1][m][iage]; 
1.251     brouard  4815:        }
1.265     brouard  4816:        for(s1=1; s1 <=nlstate ; s1++){
1.251     brouard  4817:          for(m=-1, pos=0; m <=0 ; m++)
1.265     brouard  4818:            pos += freq[s1][m][iage];
                   4819:          if(pp[s1]>=1.e-10){
1.251     brouard  4820:            if(first==1){
1.265     brouard  4821:              printf(" %d.=%.0f loss[%d]=%.1f%%",s1,pp[s1],s1,100*pos/pp[s1]);
1.251     brouard  4822:            }
1.265     brouard  4823:            fprintf(ficlog," %d.=%.0f loss[%d]=%.1f%%",s1,pp[s1],s1,100*pos/pp[s1]);
1.251     brouard  4824:          }else{
                   4825:            if(first==1)
1.265     brouard  4826:              printf(" %d.=%.0f loss[%d]=NaNQ%%",s1,pp[s1],s1);
                   4827:            fprintf(ficlog," %d.=%.0f loss[%d]=NaNQ%%",s1,pp[s1],s1);
1.240     brouard  4828:          }
                   4829:        }
                   4830:       
1.265     brouard  4831:        for(s1=1; s1 <=nlstate ; s1++){ 
                   4832:          /* posprop[s1]=0; */
                   4833:          for(m=0, pp[s1]=0; m <=nlstate+ndeath; m++)/* Summing on all ages */
                   4834:            pp[s1] += freq[s1][m][iage];
                   4835:        }       /* pp[s1] is the total number of transitions starting from state s1 and any ending status until this age */
                   4836:       
                   4837:        for(s1=1,pos=0, pospropta=0.; s1 <=nlstate ; s1++){
                   4838:          pos += pp[s1]; /* pos is the total number of transitions until this age */
                   4839:          posprop[s1] += prop[s1][iage]; /* prop is the number of transitions from a live state
                   4840:                                            from s1 at age iage prop[s[m][iind]][(int)agev[m][iind]] += weight[iind] */
                   4841:          pospropta += prop[s1][iage]; /* prop is the number of transitions from a live state
                   4842:                                          from s1 at age iage prop[s[m][iind]][(int)agev[m][iind]] += weight[iind] */
                   4843:        }
                   4844:        
                   4845:        /* Writing ficresp */
                   4846:        if(cptcoveff==0 && nj==1){ /* no covariate and first pass */
                   4847:           if( iage <= iagemax){
                   4848:            fprintf(ficresp," %d",iage);
                   4849:           }
                   4850:         }else if( nj==2){
                   4851:           if( iage <= iagemax){
                   4852:            fprintf(ficresp," %d",iage);
                   4853:             for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresp, " %d %d",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
                   4854:           }
1.240     brouard  4855:        }
1.265     brouard  4856:        for(s1=1; s1 <=nlstate ; s1++){
1.240     brouard  4857:          if(pos>=1.e-5){
1.251     brouard  4858:            if(first==1)
1.265     brouard  4859:              printf(" %d.=%.0f prev[%d]=%.1f%%",s1,pp[s1],s1,100*pp[s1]/pos);
                   4860:            fprintf(ficlog," %d.=%.0f prev[%d]=%.1f%%",s1,pp[s1],s1,100*pp[s1]/pos);
1.251     brouard  4861:          }else{
                   4862:            if(first==1)
1.265     brouard  4863:              printf(" %d.=%.0f prev[%d]=NaNQ%%",s1,pp[s1],s1);
                   4864:            fprintf(ficlog," %d.=%.0f prev[%d]=NaNQ%%",s1,pp[s1],s1);
1.251     brouard  4865:          }
                   4866:          if( iage <= iagemax){
                   4867:            if(pos>=1.e-5){
1.265     brouard  4868:              if(cptcoveff==0 && nj==1){ /* no covariate and first pass */
                   4869:                fprintf(ficresp," %.5f %.0f %.0f",prop[s1][iage]/pospropta, prop[s1][iage],pospropta);
                   4870:               }else if( nj==2){
                   4871:                fprintf(ficresp," %.5f %.0f %.0f",prop[s1][iage]/pospropta, prop[s1][iage],pospropta);
                   4872:               }
                   4873:              fprintf(ficresphtm,"<th>%d</th><td>%.5f</td><td>%.0f</td><td>%.0f</td>",iage,prop[s1][iage]/pospropta, prop[s1][iage],pospropta);
                   4874:              /*probs[iage][s1][j1]= pp[s1]/pos;*/
                   4875:              /*printf("\niage=%d s1=%d j1=%d %.5f %.0f %.0f %f",iage,s1,j1,pp[s1]/pos, pp[s1],pos,probs[iage][s1][j1]);*/
                   4876:            } else{
                   4877:              if((cptcoveff==0 && nj==1)|| nj==2 ) fprintf(ficresp," NaNq %.0f %.0f",prop[s1][iage],pospropta);
                   4878:              fprintf(ficresphtm,"<th>%d</th><td>NaNq</td><td>%.0f</td><td>%.0f</td>",iage, prop[s1][iage],pospropta);
1.251     brouard  4879:            }
1.240     brouard  4880:          }
1.265     brouard  4881:          pospropt[s1] +=posprop[s1];
                   4882:        } /* end loop s1 */
1.251     brouard  4883:        /* pospropt=0.; */
1.265     brouard  4884:        for(s1=-1; s1 <=nlstate+ndeath; s1++){
1.251     brouard  4885:          for(m=-1; m <=nlstate+ndeath; m++){
1.265     brouard  4886:            if(freq[s1][m][iage] !=0 ) { /* minimizing output */
1.251     brouard  4887:              if(first==1){
1.265     brouard  4888:                printf(" %d%d=%.0f",s1,m,freq[s1][m][iage]);
1.251     brouard  4889:              }
1.265     brouard  4890:              /* printf(" %d%d=%.0f",s1,m,freq[s1][m][iage]); */
                   4891:              fprintf(ficlog," %d%d=%.0f",s1,m,freq[s1][m][iage]);
1.251     brouard  4892:            }
1.265     brouard  4893:            if(s1!=0 && m!=0)
                   4894:              fprintf(ficresphtmfr,"<td>%.0f</td> ",freq[s1][m][iage]);
1.240     brouard  4895:          }
1.265     brouard  4896:        } /* end loop s1 */
1.251     brouard  4897:        posproptt=0.; 
1.265     brouard  4898:        for(s1=1; s1 <=nlstate; s1++){
                   4899:          posproptt += pospropt[s1];
1.251     brouard  4900:        }
                   4901:        fprintf(ficresphtmfr,"</tr>\n ");
1.265     brouard  4902:        fprintf(ficresphtm,"</tr>\n");
                   4903:        if((cptcoveff==0 && nj==1)|| nj==2 ) {
                   4904:          if(iage <= iagemax)
                   4905:            fprintf(ficresp,"\n");
1.240     brouard  4906:        }
1.251     brouard  4907:        if(first==1)
                   4908:          printf("Others in log...\n");
                   4909:        fprintf(ficlog,"\n");
                   4910:       } /* end loop age iage */
1.265     brouard  4911:       
1.251     brouard  4912:       fprintf(ficresphtm,"<tr><th>Tot</th>");
1.265     brouard  4913:       for(s1=1; s1 <=nlstate ; s1++){
1.251     brouard  4914:        if(posproptt < 1.e-5){
1.265     brouard  4915:          fprintf(ficresphtm,"<td>Nanq</td><td>%.0f</td><td>%.0f</td>",pospropt[s1],posproptt); 
1.251     brouard  4916:        }else{
1.265     brouard  4917:          fprintf(ficresphtm,"<td>%.5f</td><td>%.0f</td><td>%.0f</td>",pospropt[s1]/posproptt,pospropt[s1],posproptt);  
1.240     brouard  4918:        }
1.226     brouard  4919:       }
1.251     brouard  4920:       fprintf(ficresphtm,"</tr>\n");
                   4921:       fprintf(ficresphtm,"</table>\n");
                   4922:       fprintf(ficresphtmfr,"</table>\n");
1.226     brouard  4923:       if(posproptt < 1.e-5){
1.251     brouard  4924:        fprintf(ficresphtm,"\n <p><b> This combination (%d) is not valid and no result will be produced</b></p>",j1);
                   4925:        fprintf(ficresphtmfr,"\n <p><b> This combination (%d) is not valid and no result will be produced</b></p>",j1);
1.260     brouard  4926:        fprintf(ficlog,"#  This combination (%d) is not valid and no result will be produced\n",j1);
                   4927:        printf("#  This combination (%d) is not valid and no result will be produced\n",j1);
1.251     brouard  4928:        invalidvarcomb[j1]=1;
1.226     brouard  4929:       }else{
1.251     brouard  4930:        fprintf(ficresphtm,"\n <p> This combination (%d) is valid and result will be produced.</p>",j1);
                   4931:        invalidvarcomb[j1]=0;
1.226     brouard  4932:       }
1.251     brouard  4933:       fprintf(ficresphtmfr,"</table>\n");
                   4934:       fprintf(ficlog,"\n");
                   4935:       if(j!=0){
                   4936:        printf("#Freqsummary: Starting values for combination j1=%d:\n", j1);
1.265     brouard  4937:        for(i=1,s1=1; i <=nlstate; i++){
1.251     brouard  4938:          for(k=1; k <=(nlstate+ndeath); k++){
                   4939:            if (k != i) {
1.265     brouard  4940:              for(jj=1; jj <=ncovmodel; jj++){ /* For counting s1 */
1.253     brouard  4941:                if(jj==1){  /* Constant case (in fact cste + age) */
1.251     brouard  4942:                  if(j1==1){ /* All dummy covariates to zero */
                   4943:                    freq[i][k][iagemax+4]=freq[i][k][iagemax+3]; /* Stores case 0 0 0 */
                   4944:                    freq[i][i][iagemax+4]=freq[i][i][iagemax+3]; /* Stores case 0 0 0 */
1.252     brouard  4945:                    printf("%d%d ",i,k);
                   4946:                    fprintf(ficlog,"%d%d ",i,k);
1.265     brouard  4947:                    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]));
                   4948:                    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]));
                   4949:                    pstart[s1]= log(freq[i][k][iagemax+3]/freq[i][i][iagemax+3]);
1.251     brouard  4950:                  }
1.253     brouard  4951:                }else if((j1==1) && (jj==2 || nagesqr==1)){ /* age or age*age parameter without covariate V4*age (to be done later) */
                   4952:                  for(iage=iagemin; iage <= iagemax+3; iage++){
                   4953:                    x[iage]= (double)iage;
                   4954:                    y[iage]= log(freq[i][k][iage]/freq[i][i][iage]);
1.265     brouard  4955:                    /* 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  4956:                  }
1.268     brouard  4957:                  /* Some are not finite, but linreg will ignore these ages */
                   4958:                  no=0;
1.253     brouard  4959:                  linreg(iagemin,iagemax,&no,x,y,&a,&b,&r, &sa, &sb ); /* y= a+b*x with standard errors */
1.265     brouard  4960:                  pstart[s1]=b;
                   4961:                  pstart[s1-1]=a;
1.252     brouard  4962:                }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 */ 
                   4963:                  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]);
                   4964:                  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  4965:                  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  4966:                  printf("%d%d ",i,k);
                   4967:                  fprintf(ficlog,"%d%d ",i,k);
1.265     brouard  4968:                  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  4969:                }else{ /* Other cases, like quantitative fixed or varying covariates */
                   4970:                  ;
                   4971:                }
                   4972:                /* printf("%12.7f )", param[i][jj][k]); */
                   4973:                /* fprintf(ficlog,"%12.7f )", param[i][jj][k]); */
1.265     brouard  4974:                s1++; 
1.251     brouard  4975:              } /* end jj */
                   4976:            } /* end k!= i */
                   4977:          } /* end k */
1.265     brouard  4978:        } /* end i, s1 */
1.251     brouard  4979:       } /* end j !=0 */
                   4980:     } /* end selected combination of covariate j1 */
                   4981:     if(j==0){ /* We can estimate starting values from the occurences in each case */
                   4982:       printf("#Freqsummary: Starting values for the constants:\n");
                   4983:       fprintf(ficlog,"\n");
1.265     brouard  4984:       for(i=1,s1=1; i <=nlstate; i++){
1.251     brouard  4985:        for(k=1; k <=(nlstate+ndeath); k++){
                   4986:          if (k != i) {
                   4987:            printf("%d%d ",i,k);
                   4988:            fprintf(ficlog,"%d%d ",i,k);
                   4989:            for(jj=1; jj <=ncovmodel; jj++){
1.265     brouard  4990:              pstart[s1]=p[s1]; /* Setting pstart to p values by default */
1.253     brouard  4991:              if(jj==1){ /* Age has to be done */
1.265     brouard  4992:                pstart[s1]= log(freq[i][k][iagemax+3]/freq[i][i][iagemax+3]);
                   4993:                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]));
                   4994:                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  4995:              }
                   4996:              /* printf("%12.7f )", param[i][jj][k]); */
                   4997:              /* fprintf(ficlog,"%12.7f )", param[i][jj][k]); */
1.265     brouard  4998:              s1++; 
1.250     brouard  4999:            }
1.251     brouard  5000:            printf("\n");
                   5001:            fprintf(ficlog,"\n");
1.250     brouard  5002:          }
                   5003:        }
1.284     brouard  5004:       } /* end of state i */
1.251     brouard  5005:       printf("#Freqsummary\n");
                   5006:       fprintf(ficlog,"\n");
1.265     brouard  5007:       for(s1=-1; s1 <=nlstate+ndeath; s1++){
                   5008:        for(s2=-1; s2 <=nlstate+ndeath; s2++){
                   5009:          /* param[i]|j][k]= freq[s1][s2][iagemax+3] */
                   5010:          printf(" %d%d=%.0f",s1,s2,freq[s1][s2][iagemax+3]);
                   5011:          fprintf(ficlog," %d%d=%.0f",s1,s2,freq[s1][s2][iagemax+3]);
                   5012:          /* if(freq[s1][s2][iage] !=0 ) { /\* minimizing output *\/ */
                   5013:          /*   printf(" %d%d=%.0f",s1,s2,freq[s1][s2][iagemax+3]); */
                   5014:          /*   fprintf(ficlog," %d%d=%.0f",s1,s2,freq[s1][s2][iagemax+3]); */
1.251     brouard  5015:          /* } */
                   5016:        }
1.265     brouard  5017:       } /* end loop s1 */
1.251     brouard  5018:       
                   5019:       printf("\n");
                   5020:       fprintf(ficlog,"\n");
                   5021:     } /* end j=0 */
1.249     brouard  5022:   } /* end j */
1.252     brouard  5023: 
1.253     brouard  5024:   if(mle == -2){  /* We want to use these values as starting values */
1.252     brouard  5025:     for(i=1, jk=1; i <=nlstate; i++){
                   5026:       for(j=1; j <=nlstate+ndeath; j++){
                   5027:        if(j!=i){
                   5028:          /*ca[0]= k+'a'-1;ca[1]='\0';*/
                   5029:          printf("%1d%1d",i,j);
                   5030:          fprintf(ficparo,"%1d%1d",i,j);
                   5031:          for(k=1; k<=ncovmodel;k++){
                   5032:            /*    printf(" %lf",param[i][j][k]); */
                   5033:            /*    fprintf(ficparo," %lf",param[i][j][k]); */
                   5034:            p[jk]=pstart[jk];
                   5035:            printf(" %f ",pstart[jk]);
                   5036:            fprintf(ficparo," %f ",pstart[jk]);
                   5037:            jk++;
                   5038:          }
                   5039:          printf("\n");
                   5040:          fprintf(ficparo,"\n");
                   5041:        }
                   5042:       }
                   5043:     }
                   5044:   } /* end mle=-2 */
1.226     brouard  5045:   dateintmean=dateintsum/k2cpt; 
1.296     brouard  5046:   date2dmy(dateintmean,&jintmean,&mintmean,&aintmean);
1.240     brouard  5047:   
1.226     brouard  5048:   fclose(ficresp);
                   5049:   fclose(ficresphtm);
                   5050:   fclose(ficresphtmfr);
1.283     brouard  5051:   free_vector(idq,1,nqfveff);
1.226     brouard  5052:   free_vector(meanq,1,nqfveff);
1.284     brouard  5053:   free_vector(stdq,1,nqfveff);
1.226     brouard  5054:   free_matrix(meanqt,1,lastpass,1,nqtveff);
1.253     brouard  5055:   free_vector(x, iagemin-AGEMARGE, iagemax+4+AGEMARGE);
                   5056:   free_vector(y, iagemin-AGEMARGE, iagemax+4+AGEMARGE);
1.251     brouard  5057:   free_ma3x(freq,-5,nlstate+ndeath,-5,nlstate+ndeath, iagemin-AGEMARGE, iagemax+4+AGEMARGE);
1.226     brouard  5058:   free_vector(pospropt,1,nlstate);
                   5059:   free_vector(posprop,1,nlstate);
1.251     brouard  5060:   free_matrix(prop,1,nlstate,iagemin-AGEMARGE, iagemax+4+AGEMARGE);
1.226     brouard  5061:   free_vector(pp,1,nlstate);
                   5062:   /* End of freqsummary */
                   5063: }
1.126     brouard  5064: 
1.268     brouard  5065: /* Simple linear regression */
                   5066: int linreg(int ifi, int ila, int *no, const double x[], const double y[], double* a, double* b, double* r, double* sa, double * sb) {
                   5067: 
                   5068:   /* y=a+bx regression */
                   5069:   double   sumx = 0.0;                        /* sum of x                      */
                   5070:   double   sumx2 = 0.0;                       /* sum of x**2                   */
                   5071:   double   sumxy = 0.0;                       /* sum of x * y                  */
                   5072:   double   sumy = 0.0;                        /* sum of y                      */
                   5073:   double   sumy2 = 0.0;                       /* sum of y**2                   */
                   5074:   double   sume2 = 0.0;                       /* sum of square or residuals */
                   5075:   double yhat;
                   5076:   
                   5077:   double denom=0;
                   5078:   int i;
                   5079:   int ne=*no;
                   5080:   
                   5081:   for ( i=ifi, ne=0;i<=ila;i++) {
                   5082:     if(!isfinite(x[i]) || !isfinite(y[i])){
                   5083:       /* printf(" x[%d]=%f, y[%d]=%f\n",i,x[i],i,y[i]); */
                   5084:       continue;
                   5085:     }
                   5086:     ne=ne+1;
                   5087:     sumx  += x[i];       
                   5088:     sumx2 += x[i]*x[i];  
                   5089:     sumxy += x[i] * y[i];
                   5090:     sumy  += y[i];      
                   5091:     sumy2 += y[i]*y[i]; 
                   5092:     denom = (ne * sumx2 - sumx*sumx);
                   5093:     /* 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); */
                   5094:   } 
                   5095:   
                   5096:   denom = (ne * sumx2 - sumx*sumx);
                   5097:   if (denom == 0) {
                   5098:     // vertical, slope m is infinity
                   5099:     *b = INFINITY;
                   5100:     *a = 0;
                   5101:     if (r) *r = 0;
                   5102:     return 1;
                   5103:   }
                   5104:   
                   5105:   *b = (ne * sumxy  -  sumx * sumy) / denom;
                   5106:   *a = (sumy * sumx2  -  sumx * sumxy) / denom;
                   5107:   if (r!=NULL) {
                   5108:     *r = (sumxy - sumx * sumy / ne) /          /* compute correlation coeff     */
                   5109:       sqrt((sumx2 - sumx*sumx/ne) *
                   5110:           (sumy2 - sumy*sumy/ne));
                   5111:   }
                   5112:   *no=ne;
                   5113:   for ( i=ifi, ne=0;i<=ila;i++) {
                   5114:     if(!isfinite(x[i]) || !isfinite(y[i])){
                   5115:       /* printf(" x[%d]=%f, y[%d]=%f\n",i,x[i],i,y[i]); */
                   5116:       continue;
                   5117:     }
                   5118:     ne=ne+1;
                   5119:     yhat = y[i] - *a -*b* x[i];
                   5120:     sume2  += yhat * yhat ;       
                   5121:     
                   5122:     denom = (ne * sumx2 - sumx*sumx);
                   5123:     /* 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); */
                   5124:   } 
                   5125:   *sb = sqrt(sume2/(double)(ne-2)/(sumx2 - sumx * sumx /(double)ne));
                   5126:   *sa= *sb * sqrt(sumx2/ne);
                   5127:   
                   5128:   return 0; 
                   5129: }
                   5130: 
1.126     brouard  5131: /************ Prevalence ********************/
1.227     brouard  5132: 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)
                   5133: {  
                   5134:   /* Compute observed prevalence between dateprev1 and dateprev2 by counting the number of people
                   5135:      in each health status at the date of interview (if between dateprev1 and dateprev2).
                   5136:      We still use firstpass and lastpass as another selection.
                   5137:   */
1.126     brouard  5138:  
1.227     brouard  5139:   int i, m, jk, j1, bool, z1,j, iv;
                   5140:   int mi; /* Effective wave */
                   5141:   int iage;
                   5142:   double agebegin, ageend;
                   5143: 
                   5144:   double **prop;
                   5145:   double posprop; 
                   5146:   double  y2; /* in fractional years */
                   5147:   int iagemin, iagemax;
                   5148:   int first; /** to stop verbosity which is redirected to log file */
                   5149: 
                   5150:   iagemin= (int) agemin;
                   5151:   iagemax= (int) agemax;
                   5152:   /*pp=vector(1,nlstate);*/
1.251     brouard  5153:   prop=matrix(1,nlstate,iagemin-AGEMARGE,iagemax+4+AGEMARGE); 
1.227     brouard  5154:   /*  freq=ma3x(-1,nlstate+ndeath,-1,nlstate+ndeath,iagemin,iagemax+3);*/
                   5155:   j1=0;
1.222     brouard  5156:   
1.227     brouard  5157:   /*j=cptcoveff;*/
                   5158:   if (cptcovn<1) {j=1;ncodemax[1]=1;}
1.222     brouard  5159:   
1.288     brouard  5160:   first=0;
1.227     brouard  5161:   for(j1=1; j1<= (int) pow(2,cptcoveff);j1++){ /* For each combination of covariate */
                   5162:     for (i=1; i<=nlstate; i++)  
1.251     brouard  5163:       for(iage=iagemin-AGEMARGE; iage <= iagemax+4+AGEMARGE; iage++)
1.227     brouard  5164:        prop[i][iage]=0.0;
                   5165:     printf("Prevalence combination of varying and fixed dummies %d\n",j1);
                   5166:     /* fprintf(ficlog," V%d=%d ",Tvaraff[j1],nbcode[Tvaraff[j1]][codtabm(k,j1)]); */
                   5167:     fprintf(ficlog,"Prevalence combination of varying and fixed dummies %d\n",j1);
                   5168:     
                   5169:     for (i=1; i<=imx; i++) { /* Each individual */
                   5170:       bool=1;
                   5171:       /* for(m=firstpass; m<=lastpass; m++){/\* Other selection (we can limit to certain interviews*\/ */
                   5172:       for(mi=1; mi<wav[i];mi++){ /* For this wave too look where individual can be counted V4=0 V3=0 */
                   5173:        m=mw[mi][i];
                   5174:        /* Tmodelind[z1]=k is the position of the varying covariate in the model, but which # within 1 to ntv? */
                   5175:        /* Tvar[Tmodelind[z1]] is the n of Vn; n-ncovcol-nqv is the first time varying covariate or iv */
                   5176:        for (z1=1; z1<=cptcoveff; z1++){
                   5177:          if( Fixed[Tmodelind[z1]]==1){
                   5178:            iv= Tvar[Tmodelind[z1]]-ncovcol-nqv;
                   5179:            if (cotvar[m][iv][i]!= nbcode[Tvaraff[z1]][codtabm(j1,z1)]) /* iv=1 to ntv, right modality */
                   5180:              bool=0;
                   5181:          }else if( Fixed[Tmodelind[z1]]== 0)  /* fixed */
                   5182:            if (covar[Tvaraff[z1]][i]!= nbcode[Tvaraff[z1]][codtabm(j1,z1)]) {
                   5183:              bool=0;
                   5184:            }
                   5185:        }
                   5186:        if(bool==1){ /* Otherwise we skip that wave/person */
                   5187:          agebegin=agev[m][i]; /* Age at beginning of wave before transition*/
                   5188:          /* ageend=agev[m][i]+(dh[m][i])*stepm/YEARM; /\* Age at end of wave and transition *\/ */
                   5189:          if(m >=firstpass && m <=lastpass){
                   5190:            y2=anint[m][i]+(mint[m][i]/12.); /* Fractional date in year */
                   5191:            if ((y2>=dateprev1) && (y2<=dateprev2)) { /* Here is the main selection (fractional years) */
                   5192:              if(agev[m][i]==0) agev[m][i]=iagemax+1;
                   5193:              if(agev[m][i]==1) agev[m][i]=iagemax+2;
1.251     brouard  5194:              if((int)agev[m][i] <iagemin-AGEMARGE || (int)agev[m][i] >iagemax+4+AGEMARGE){
1.227     brouard  5195:                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); 
                   5196:                exit(1);
                   5197:              }
                   5198:              if (s[m][i]>0 && s[m][i]<=nlstate) { 
                   5199:                /*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]]);*/
                   5200:                prop[s[m][i]][(int)agev[m][i]] += weight[i];/* At age of beginning of transition, where status is known */
                   5201:                prop[s[m][i]][iagemax+3] += weight[i]; 
                   5202:              } /* end valid statuses */ 
                   5203:            } /* end selection of dates */
                   5204:          } /* end selection of waves */
                   5205:        } /* end bool */
                   5206:       } /* end wave */
                   5207:     } /* end individual */
                   5208:     for(i=iagemin; i <= iagemax+3; i++){  
                   5209:       for(jk=1,posprop=0; jk <=nlstate ; jk++) { 
                   5210:        posprop += prop[jk][i]; 
                   5211:       } 
                   5212:       
                   5213:       for(jk=1; jk <=nlstate ; jk++){      
                   5214:        if( i <=  iagemax){ 
                   5215:          if(posprop>=1.e-5){ 
                   5216:            probs[i][jk][j1]= prop[jk][i]/posprop;
                   5217:          } else{
1.288     brouard  5218:            if(!first){
                   5219:              first=1;
1.266     brouard  5220:              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]);
                   5221:            }else{
1.288     brouard  5222:              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  5223:            }
                   5224:          }
                   5225:        } 
                   5226:       }/* end jk */ 
                   5227:     }/* end i */ 
1.222     brouard  5228:      /*} *//* end i1 */
1.227     brouard  5229:   } /* end j1 */
1.222     brouard  5230:   
1.227     brouard  5231:   /*  free_ma3x(freq,-1,nlstate+ndeath,-1,nlstate+ndeath, iagemin, iagemax+3);*/
                   5232:   /*free_vector(pp,1,nlstate);*/
1.251     brouard  5233:   free_matrix(prop,1,nlstate, iagemin-AGEMARGE,iagemax+4+AGEMARGE);
1.227     brouard  5234: }  /* End of prevalence */
1.126     brouard  5235: 
                   5236: /************* Waves Concatenation ***************/
                   5237: 
                   5238: 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)
                   5239: {
1.298     brouard  5240:   /* 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  5241:      Death is a valid wave (if date is known).
                   5242:      mw[mi][i] is the mi (mi=1 to wav[i])  effective wave of individual i
                   5243:      dh[m][i] or dh[mw[mi][i]][i] is the delay between two effective waves m=mw[mi][i]
1.298     brouard  5244:      and mw[mi+1][i]. dh depends on stepm. s[m][i] exists for any wave from firstpass to lastpass
1.227     brouard  5245:   */
1.126     brouard  5246: 
1.224     brouard  5247:   int i=0, mi=0, m=0, mli=0;
1.126     brouard  5248:   /* int j, k=0,jk, ju, jl,jmin=1e+5, jmax=-1;
                   5249:      double sum=0., jmean=0.;*/
1.224     brouard  5250:   int first=0, firstwo=0, firsthree=0, firstfour=0, firstfiv=0;
1.126     brouard  5251:   int j, k=0,jk, ju, jl;
                   5252:   double sum=0.;
                   5253:   first=0;
1.214     brouard  5254:   firstwo=0;
1.217     brouard  5255:   firsthree=0;
1.218     brouard  5256:   firstfour=0;
1.164     brouard  5257:   jmin=100000;
1.126     brouard  5258:   jmax=-1;
                   5259:   jmean=0.;
1.224     brouard  5260: 
                   5261: /* Treating live states */
1.214     brouard  5262:   for(i=1; i<=imx; i++){  /* For simple cases and if state is death */
1.224     brouard  5263:     mi=0;  /* First valid wave */
1.227     brouard  5264:     mli=0; /* Last valid wave */
1.126     brouard  5265:     m=firstpass;
1.214     brouard  5266:     while(s[m][i] <= nlstate){  /* a live state */
1.227     brouard  5267:       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 */
                   5268:        mli=m-1;/* mw[++mi][i]=m-1; */
                   5269:       }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 */
                   5270:        mw[++mi][i]=m;
                   5271:        mli=m;
1.224     brouard  5272:       } /* else might be a useless wave  -1 and mi is not incremented and mw[mi] not updated */
                   5273:       if(m < lastpass){ /* m < lastpass, standard case */
1.227     brouard  5274:        m++; /* mi gives the "effective" current wave, m the current wave, go to next wave by incrementing m */
1.216     brouard  5275:       }
1.227     brouard  5276:       else{ /* m >= lastpass, eventual special issue with warning */
1.224     brouard  5277: #ifdef UNKNOWNSTATUSNOTCONTRIBUTING
1.227     brouard  5278:        break;
1.224     brouard  5279: #else
1.227     brouard  5280:        if(s[m][i]==-1 && (int) andc[i] == 9999 && (int)anint[m][i] != 9999){
                   5281:          if(firsthree == 0){
1.302     brouard  5282:            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  5283:            firsthree=1;
                   5284:          }
1.302     brouard  5285:          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.227     brouard  5286:          mw[++mi][i]=m;
                   5287:          mli=m;
                   5288:        }
                   5289:        if(s[m][i]==-2){ /* Vital status is really unknown */
                   5290:          nbwarn++;
                   5291:          if((int)anint[m][i] == 9999){  /*  Has the vital status really been verified? */
                   5292:            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);
                   5293:            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);
                   5294:          }
                   5295:          break;
                   5296:        }
                   5297:        break;
1.224     brouard  5298: #endif
1.227     brouard  5299:       }/* End m >= lastpass */
1.126     brouard  5300:     }/* end while */
1.224     brouard  5301: 
1.227     brouard  5302:     /* 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  5303:     /* After last pass */
1.224     brouard  5304: /* Treating death states */
1.214     brouard  5305:     if (s[m][i] > nlstate){  /* In a death state */
1.227     brouard  5306:       /* if( mint[m][i]==mdc[m][i] && anint[m][i]==andc[m][i]){ /\* same date of death and date of interview *\/ */
                   5307:       /* } */
1.126     brouard  5308:       mi++;    /* Death is another wave */
                   5309:       /* if(mi==0)  never been interviewed correctly before death */
1.227     brouard  5310:       /* Only death is a correct wave */
1.126     brouard  5311:       mw[mi][i]=m;
1.257     brouard  5312:     } /* else not in a death state */
1.224     brouard  5313: #ifndef DISPATCHINGKNOWNDEATHAFTERLASTWAVE
1.257     brouard  5314:     else if ((int) andc[i] != 9999) {  /* Date of death is known */
1.218     brouard  5315:       if ((int)anint[m][i]!= 9999) { /* date of last interview is known */
1.227     brouard  5316:        if((andc[i]+moisdc[i]/12.) <=(anint[m][i]+mint[m][i]/12.)){ /* death occured before last wave and status should have been death instead of -1 */
                   5317:          nbwarn++;
                   5318:          if(firstfiv==0){
                   5319:            printf("Warning! Death for individual %ld line=%d occurred at %d/%d before last wave %d interviewed at %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 );
                   5320:            firstfiv=1;
                   5321:          }else{
                   5322:            fprintf(ficlog,"Warning! Death for individual %ld line=%d occurred at %d/%d before last wave %d interviewed at %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 );
                   5323:          }
                   5324:        }else{ /* Death occured afer last wave potential bias */
                   5325:          nberr++;
                   5326:          if(firstwo==0){
1.257     brouard  5327:            printf("Error! Death for individual %ld line=%d occurred at %d/%d after last wave %d interviewed at %d/%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. Please add a new fictive wave at the date of last vital status scan, with a dead status or alive but unknown state status (-1). 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], i,m );
1.227     brouard  5328:            firstwo=1;
                   5329:          }
1.257     brouard  5330:          fprintf(ficlog,"Error! Death for individual %ld line=%d occurred at %d/%d after last wave %d interviewed at %d/%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. Please add a new fictive wave at the date of last vital status scan, with a dead status or alive but unknown state status (-1). See documentation\n\n",num[i],i,(int) moisdc[i], (int) andc[i], lastpass,(int)mint[m][i],(int)anint[m][i], i,m );
1.227     brouard  5331:        }
1.257     brouard  5332:       }else{ /* if date of interview is unknown */
1.227     brouard  5333:        /* death is known but not confirmed by death status at any wave */
                   5334:        if(firstfour==0){
                   5335:          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. 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], i,m );
                   5336:          firstfour=1;
                   5337:        }
                   5338:        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. 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], i,m );
1.214     brouard  5339:       }
1.224     brouard  5340:     } /* end if date of death is known */
                   5341: #endif
                   5342:     wav[i]=mi; /* mi should be the last effective wave (or mli) */
                   5343:     /* wav[i]=mw[mi][i]; */
1.126     brouard  5344:     if(mi==0){
                   5345:       nbwarn++;
                   5346:       if(first==0){
1.227     brouard  5347:        printf("Warning! No valid information for individual %ld line=%d (skipped) and may be others, see log file\n",num[i],i);
                   5348:        first=1;
1.126     brouard  5349:       }
                   5350:       if(first==1){
1.227     brouard  5351:        fprintf(ficlog,"Warning! No valid information for individual %ld line=%d (skipped)\n",num[i],i);
1.126     brouard  5352:       }
                   5353:     } /* end mi==0 */
                   5354:   } /* End individuals */
1.214     brouard  5355:   /* wav and mw are no more changed */
1.223     brouard  5356:        
1.214     brouard  5357:   
1.126     brouard  5358:   for(i=1; i<=imx; i++){
                   5359:     for(mi=1; mi<wav[i];mi++){
                   5360:       if (stepm <=0)
1.227     brouard  5361:        dh[mi][i]=1;
1.126     brouard  5362:       else{
1.260     brouard  5363:        if (s[mw[mi+1][i]][i] > nlstate) { /* A death, but what if date is unknown? */
1.227     brouard  5364:          if (agedc[i] < 2*AGESUP) {
                   5365:            j= rint(agedc[i]*12-agev[mw[mi][i]][i]*12); 
                   5366:            if(j==0) j=1;  /* Survives at least one month after exam */
                   5367:            else if(j<0){
                   5368:              nberr++;
                   5369:              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]);
                   5370:              j=1; /* Temporary Dangerous patch */
                   5371:              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);
                   5372:              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]);
                   5373:              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);
                   5374:            }
                   5375:            k=k+1;
                   5376:            if (j >= jmax){
                   5377:              jmax=j;
                   5378:              ijmax=i;
                   5379:            }
                   5380:            if (j <= jmin){
                   5381:              jmin=j;
                   5382:              ijmin=i;
                   5383:            }
                   5384:            sum=sum+j;
                   5385:            /*if (j<0) printf("j=%d num=%d \n",j,i);*/
                   5386:            /*    printf("%d %d %d %d\n", s[mw[mi][i]][i] ,s[mw[mi+1][i]][i],j,i);*/
                   5387:          }
                   5388:        }
                   5389:        else{
                   5390:          j= rint( (agev[mw[mi+1][i]][i]*12 - agev[mw[mi][i]][i]*12));
1.126     brouard  5391: /*       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  5392:                                        
1.227     brouard  5393:          k=k+1;
                   5394:          if (j >= jmax) {
                   5395:            jmax=j;
                   5396:            ijmax=i;
                   5397:          }
                   5398:          else if (j <= jmin){
                   5399:            jmin=j;
                   5400:            ijmin=i;
                   5401:          }
                   5402:          /*        if (j<10) printf("j=%d jmin=%d num=%d ",j,jmin,i); */
                   5403:          /*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]);*/
                   5404:          if(j<0){
                   5405:            nberr++;
                   5406:            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]);
                   5407:            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]);
                   5408:          }
                   5409:          sum=sum+j;
                   5410:        }
                   5411:        jk= j/stepm;
                   5412:        jl= j -jk*stepm;
                   5413:        ju= j -(jk+1)*stepm;
                   5414:        if(mle <=1){ /* only if we use a the linear-interpoloation pseudo-likelihood */
                   5415:          if(jl==0){
                   5416:            dh[mi][i]=jk;
                   5417:            bh[mi][i]=0;
                   5418:          }else{ /* We want a negative bias in order to only have interpolation ie
                   5419:                  * to avoid the price of an extra matrix product in likelihood */
                   5420:            dh[mi][i]=jk+1;
                   5421:            bh[mi][i]=ju;
                   5422:          }
                   5423:        }else{
                   5424:          if(jl <= -ju){
                   5425:            dh[mi][i]=jk;
                   5426:            bh[mi][i]=jl;       /* bias is positive if real duration
                   5427:                                 * is higher than the multiple of stepm and negative otherwise.
                   5428:                                 */
                   5429:          }
                   5430:          else{
                   5431:            dh[mi][i]=jk+1;
                   5432:            bh[mi][i]=ju;
                   5433:          }
                   5434:          if(dh[mi][i]==0){
                   5435:            dh[mi][i]=1; /* At least one step */
                   5436:            bh[mi][i]=ju; /* At least one step */
                   5437:            /*  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);*/
                   5438:          }
                   5439:        } /* end if mle */
1.126     brouard  5440:       }
                   5441:     } /* end wave */
                   5442:   }
                   5443:   jmean=sum/k;
                   5444:   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  5445:   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  5446: }
1.126     brouard  5447: 
                   5448: /*********** Tricode ****************************/
1.220     brouard  5449:  void tricode(int *cptcov, int *Tvar, int **nbcode, int imx, int *Ndum)
1.242     brouard  5450:  {
                   5451:    /**< Uses cptcovn+2*cptcovprod as the number of covariates */
                   5452:    /*    Tvar[i]=atoi(stre);  find 'n' in Vn and stores in Tvar. If model=V2+V1 Tvar[1]=2 and Tvar[2]=1 
                   5453:     * Boring subroutine which should only output nbcode[Tvar[j]][k]
                   5454:     * Tvar[5] in V2+V1+V3*age+V2*V4 is 4 (V4) even it is a time varying or quantitative variable
                   5455:     * nbcode[Tvar[5]][1]= nbcode[4][1]=0, nbcode[4][2]=1 (usually);
                   5456:     */
1.130     brouard  5457: 
1.242     brouard  5458:    int ij=1, k=0, j=0, i=0, maxncov=NCOVMAX;
                   5459:    int modmaxcovj=0; /* Modality max of covariates j */
                   5460:    int cptcode=0; /* Modality max of covariates j */
                   5461:    int modmincovj=0; /* Modality min of covariates j */
1.145     brouard  5462: 
                   5463: 
1.242     brouard  5464:    /* cptcoveff=0;  */
                   5465:    /* *cptcov=0; */
1.126     brouard  5466:  
1.242     brouard  5467:    for (k=1; k <= maxncov; k++) ncodemax[k]=0; /* Horrible constant again replaced by NCOVMAX */
1.285     brouard  5468:    for (k=1; k <= maxncov; k++)
                   5469:      for(j=1; j<=2; j++)
                   5470:        nbcode[k][j]=0; /* Valgrind */
1.126     brouard  5471: 
1.242     brouard  5472:    /* Loop on covariates without age and products and no quantitative variable */
                   5473:    for (k=1; k<=cptcovt; k++) { /* From model V1 + V2*age + V3 + V3*V4 keeps V1 + V3 = 2 only */
                   5474:      for (j=-1; (j < maxncov); j++) Ndum[j]=0;
                   5475:      if(Dummy[k]==0 && Typevar[k] !=1){ /* Dummy covariate and not age product */ 
                   5476:        switch(Fixed[k]) {
                   5477:        case 0: /* Testing on fixed dummy covariate, simple or product of fixed */
                   5478:         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*/
                   5479:           ij=(int)(covar[Tvar[k]][i]);
                   5480:           /* ij=0 or 1 or -1. Value of the covariate Tvar[j] for individual i
                   5481:            * If product of Vn*Vm, still boolean *:
                   5482:            * If it was coded 1, 2, 3, 4 should be splitted into 3 boolean variables
                   5483:            * 1 => 0 0 0, 2 => 0 0 1, 3 => 0 1 1, 4=1 0 0   */
                   5484:           /* Finds for covariate j, n=Tvar[j] of Vn . ij is the
                   5485:              modality of the nth covariate of individual i. */
                   5486:           if (ij > modmaxcovj)
                   5487:             modmaxcovj=ij; 
                   5488:           else if (ij < modmincovj) 
                   5489:             modmincovj=ij; 
1.287     brouard  5490:           if (ij <0 || ij >1 ){
                   5491:             printf("Information, IMaCh doesn't treat covariate with missing values (-1), individual %d will be skipped.\n",i);
                   5492:             fprintf(ficlog,"Information, currently IMaCh doesn't treat covariate with missing values (-1), individual %d will be skipped.\n",i);
                   5493:           }
                   5494:           if ((ij < -1) || (ij > NCOVMAX)){
1.242     brouard  5495:             printf( "Error: minimal is less than -1 or maximal is bigger than %d. Exiting. \n", NCOVMAX );
                   5496:             exit(1);
                   5497:           }else
                   5498:             Ndum[ij]++; /*counts and stores the occurence of this modality 0, 1, -1*/
                   5499:           /*  If coded 1, 2, 3 , counts the number of 1 Ndum[1], number of 2, Ndum[2], etc */
                   5500:           /*printf("i=%d ij=%d Ndum[ij]=%d imx=%d",i,ij,Ndum[ij],imx);*/
                   5501:           /* getting the maximum value of the modality of the covariate
                   5502:              (should be 0 or 1 now) Tvar[j]. If V=sex and male is coded 0 and
                   5503:              female ies 1, then modmaxcovj=1.
                   5504:           */
                   5505:         } /* end for loop on individuals i */
                   5506:         printf(" Minimal and maximal values of %d th (fixed) covariate V%d: min=%d max=%d \n", k, Tvar[k], modmincovj, modmaxcovj);
                   5507:         fprintf(ficlog," Minimal and maximal values of %d th (fixed) covariate V%d: min=%d max=%d \n", k, Tvar[k], modmincovj, modmaxcovj);
                   5508:         cptcode=modmaxcovj;
                   5509:         /* Ndum[0] = frequency of 0 for model-covariate j, Ndum[1] frequency of 1 etc. */
                   5510:         /*for (i=0; i<=cptcode; i++) {*/
                   5511:         for (j=modmincovj;  j<=modmaxcovj; j++) { /* j=-1 ? 0 and 1*//* For each value j of the modality of model-cov k */
                   5512:           printf("Frequencies of (fixed) covariate %d ie V%d with value %d: %d\n", k, Tvar[k], j, Ndum[j]);
                   5513:           fprintf(ficlog, "Frequencies of (fixed) covariate %d ie V%d with value %d: %d\n", k, Tvar[k], j, Ndum[j]);
                   5514:           if( Ndum[j] != 0 ){ /* Counts if nobody answered modality j ie empty modality, we skip it and reorder */
                   5515:             if( j != -1){
                   5516:               ncodemax[k]++;  /* ncodemax[k]= Number of modalities of the k th
                   5517:                                  covariate for which somebody answered excluding 
                   5518:                                  undefined. Usually 2: 0 and 1. */
                   5519:             }
                   5520:             ncodemaxwundef[k]++; /* ncodemax[j]= Number of modalities of the k th
                   5521:                                     covariate for which somebody answered including 
                   5522:                                     undefined. Usually 3: -1, 0 and 1. */
                   5523:           }    /* In fact  ncodemax[k]=2 (dichotom. variables only) but it could be more for
                   5524:                 * historical reasons: 3 if coded 1, 2, 3 and 4 and Ndum[2]=0 */
                   5525:         } /* Ndum[-1] number of undefined modalities */
1.231     brouard  5526:                        
1.242     brouard  5527:         /* j is a covariate, n=Tvar[j] of Vn; Fills nbcode */
                   5528:         /* For covariate j, modalities could be 1, 2, 3, 4, 5, 6, 7. */
                   5529:         /* If Ndum[1]=0, Ndum[2]=0, Ndum[3]= 635, Ndum[4]=0, Ndum[5]=0, Ndum[6]=27, Ndum[7]=125; */
                   5530:         /* modmincovj=3; modmaxcovj = 7; */
                   5531:         /* There are only 3 modalities non empty 3, 6, 7 (or 2 if 27 is too few) : ncodemax[j]=3; */
                   5532:         /* which will be coded 0, 1, 2 which in binary on 2=3-1 digits are 0=00 1=01, 2=10; */
                   5533:         /*              defining two dummy variables: variables V1_1 and V1_2.*/
                   5534:         /* nbcode[Tvar[j]][ij]=k; */
                   5535:         /* nbcode[Tvar[j]][1]=0; */
                   5536:         /* nbcode[Tvar[j]][2]=1; */
                   5537:         /* nbcode[Tvar[j]][3]=2; */
                   5538:         /* To be continued (not working yet). */
                   5539:         ij=0; /* ij is similar to i but can jump over null modalities */
1.287     brouard  5540: 
                   5541:         /* 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*/
                   5542:         /* Skipping the case of missing values by reducing nbcode to 0 and 1 and not -1, 0, 1 */
                   5543:         /* model=V1+V2+V3, if V2=-1, 0 or 1, then nbcode[2][1]=0 and nbcode[2][2]=1 instead of
                   5544:          * nbcode[2][1]=-1, nbcode[2][2]=0 and nbcode[2][3]=1 */
                   5545:         /*, could be restored in the future */
                   5546:         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  5547:           if (Ndum[i] == 0) { /* If nobody responded to this modality k */
                   5548:             break;
                   5549:           }
                   5550:           ij++;
1.287     brouard  5551:           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  5552:           cptcode = ij; /* New max modality for covar j */
                   5553:         } /* end of loop on modality i=-1 to 1 or more */
                   5554:         break;
                   5555:        case 1: /* Testing on varying covariate, could be simple and
                   5556:                * should look at waves or product of fixed *
                   5557:                * varying. No time to test -1, assuming 0 and 1 only */
                   5558:         ij=0;
                   5559:         for(i=0; i<=1;i++){
                   5560:           nbcode[Tvar[k]][++ij]=i;
                   5561:         }
                   5562:         break;
                   5563:        default:
                   5564:         break;
                   5565:        } /* end switch */
                   5566:      } /* end dummy test */
1.287     brouard  5567:    } /* 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  5568:   
                   5569:    for (k=-1; k< maxncov; k++) Ndum[k]=0; 
                   5570:    /* Look at fixed dummy (single or product) covariates to check empty modalities */
                   5571:    for (i=1; i<=ncovmodel-2-nagesqr; i++) { /* -2, cste and age and eventually age*age */ 
                   5572:      /* Listing of all covariables in statement model to see if some covariates appear twice. For example, V1 appears twice in V1+V1*V2.*/ 
                   5573:      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 */ 
                   5574:      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 */
                   5575:      /* V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1,  {2, 1, 1, 1, 2, 1, 1, 0, 0} */
                   5576:    } /* V4+V3+V5, Ndum[1]@5={0, 0, 1, 1, 1} */
                   5577:   
                   5578:    ij=0;
                   5579:    /* for (i=0; i<=  maxncov-1; i++) { /\* modmaxcovj is unknown here. Only Ndum[2(V2),3(age*V3), 5(V3*V2) 6(V1*V4) *\/ */
                   5580:    for (k=1; k<=  cptcovt; k++) { /* modmaxcovj is unknown here. Only Ndum[2(V2),3(age*V3), 5(V3*V2) 6(V1*V4) */
                   5581:      /*printf("Ndum[%d]=%d\n",i, Ndum[i]);*/
                   5582:      /* if((Ndum[i]!=0) && (i<=ncovcol)){  /\* Tvar[i] <= ncovmodel ? *\/ */
                   5583:      if(Ndum[Tvar[k]]!=0 && Dummy[k] == 0 && Typevar[k]==0){  /* Only Dummy and non empty in the model */
                   5584:        /* If product not in single variable we don't print results */
                   5585:        /*printf("diff Ndum[%d]=%d\n",i, Ndum[i]);*/
                   5586:        ++ij;/* V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1, */
                   5587:        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*/
                   5588:        Tmodelind[ij]=k; /* Tmodelind: index in model of dummies Tmodelind[1]=2 V4: pos=2; V3: pos=3, V1=9 {2, 3, 9, ?, ?,} */
                   5589:        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 */
                   5590:        if(Fixed[k]!=0)
                   5591:         anyvaryingduminmodel=1;
                   5592:        /* }else if((Ndum[i]!=0) && (i<=ncovcol+nqv)){ */
                   5593:        /*   Tvaraff[++ij]=-10; /\* Dont'n know how to treat quantitative variables yet *\/ */
                   5594:        /* }else if((Ndum[i]!=0) && (i<=ncovcol+nqv+ntv)){ */
                   5595:        /*   Tvaraff[++ij]=i; /\*For printing (unclear) *\/ */
                   5596:        /* }else if((Ndum[i]!=0) && (i<=ncovcol+nqv+ntv+nqtv)){ */
                   5597:        /*   Tvaraff[++ij]=-20; /\* Dont'n know how to treat quantitative variables yet *\/ */
                   5598:      } 
                   5599:    } /* Tvaraff[1]@5 {3, 4, -20, 0, 0} Very strange */
                   5600:    /* ij--; */
                   5601:    /* cptcoveff=ij; /\*Number of total covariates*\/ */
                   5602:    *cptcov=ij; /*Number of total real effective covariates: effective
                   5603:                * because they can be excluded from the model and real
                   5604:                * if in the model but excluded because missing values, but how to get k from ij?*/
                   5605:    for(j=ij+1; j<= cptcovt; j++){
                   5606:      Tvaraff[j]=0;
                   5607:      Tmodelind[j]=0;
                   5608:    }
                   5609:    for(j=ntveff+1; j<= cptcovt; j++){
                   5610:      TmodelInvind[j]=0;
                   5611:    }
                   5612:    /* To be sorted */
                   5613:    ;
                   5614:  }
1.126     brouard  5615: 
1.145     brouard  5616: 
1.126     brouard  5617: /*********** Health Expectancies ****************/
                   5618: 
1.235     brouard  5619:  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  5620: 
                   5621: {
                   5622:   /* Health expectancies, no variances */
1.164     brouard  5623:   int i, j, nhstepm, hstepm, h, nstepm;
1.126     brouard  5624:   int nhstepma, nstepma; /* Decreasing with age */
                   5625:   double age, agelim, hf;
                   5626:   double ***p3mat;
                   5627:   double eip;
                   5628: 
1.238     brouard  5629:   /* pstamp(ficreseij); */
1.126     brouard  5630:   fprintf(ficreseij,"# (a) Life expectancies by health status at initial age and (b) health expectancies by health status at initial age\n");
                   5631:   fprintf(ficreseij,"# Age");
                   5632:   for(i=1; i<=nlstate;i++){
                   5633:     for(j=1; j<=nlstate;j++){
                   5634:       fprintf(ficreseij," e%1d%1d ",i,j);
                   5635:     }
                   5636:     fprintf(ficreseij," e%1d. ",i);
                   5637:   }
                   5638:   fprintf(ficreseij,"\n");
                   5639: 
                   5640:   
                   5641:   if(estepm < stepm){
                   5642:     printf ("Problem %d lower than %d\n",estepm, stepm);
                   5643:   }
                   5644:   else  hstepm=estepm;   
                   5645:   /* We compute the life expectancy from trapezoids spaced every estepm months
                   5646:    * This is mainly to measure the difference between two models: for example
                   5647:    * if stepm=24 months pijx are given only every 2 years and by summing them
                   5648:    * we are calculating an estimate of the Life Expectancy assuming a linear 
                   5649:    * progression in between and thus overestimating or underestimating according
                   5650:    * to the curvature of the survival function. If, for the same date, we 
                   5651:    * estimate the model with stepm=1 month, we can keep estepm to 24 months
                   5652:    * to compare the new estimate of Life expectancy with the same linear 
                   5653:    * hypothesis. A more precise result, taking into account a more precise
                   5654:    * curvature will be obtained if estepm is as small as stepm. */
                   5655: 
                   5656:   /* For example we decided to compute the life expectancy with the smallest unit */
                   5657:   /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm. 
                   5658:      nhstepm is the number of hstepm from age to agelim 
                   5659:      nstepm is the number of stepm from age to agelin. 
1.270     brouard  5660:      Look at hpijx to understand the reason which relies in memory size consideration
1.126     brouard  5661:      and note for a fixed period like estepm months */
                   5662:   /* We decided (b) to get a life expectancy respecting the most precise curvature of the
                   5663:      survival function given by stepm (the optimization length). Unfortunately it
                   5664:      means that if the survival funtion is printed only each two years of age and if
                   5665:      you sum them up and add 1 year (area under the trapezoids) you won't get the same 
                   5666:      results. So we changed our mind and took the option of the best precision.
                   5667:   */
                   5668:   hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */ 
                   5669: 
                   5670:   agelim=AGESUP;
                   5671:   /* If stepm=6 months */
                   5672:     /* Computed by stepm unit matrices, product of hstepm matrices, stored
                   5673:        in an array of nhstepm length: nhstepm=10, hstepm=4, stepm=6 months */
                   5674:     
                   5675: /* nhstepm age range expressed in number of stepm */
                   5676:   nstepm=(int) rint((agelim-bage)*YEARM/stepm); /* Biggest nstepm */
                   5677:   /* Typically if 20 years nstepm = 20*12/6=40 stepm */ 
                   5678:   /* if (stepm >= YEARM) hstepm=1;*/
                   5679:   nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
                   5680:   p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   5681: 
                   5682:   for (age=bage; age<=fage; age ++){ 
                   5683:     nstepma=(int) rint((agelim-bage)*YEARM/stepm); /* Biggest nstepm */
                   5684:     /* Typically if 20 years nstepm = 20*12/6=40 stepm */ 
                   5685:     /* if (stepm >= YEARM) hstepm=1;*/
                   5686:     nhstepma = nstepma/hstepm;/* Expressed in hstepm, typically nhstepma=40/4=10 */
                   5687: 
                   5688:     /* If stepm=6 months */
                   5689:     /* Computed by stepm unit matrices, product of hstepma matrices, stored
                   5690:        in an array of nhstepma length: nhstepma=10, hstepm=4, stepm=6 months */
                   5691:     
1.235     brouard  5692:     hpxij(p3mat,nhstepma,age,hstepm,x,nlstate,stepm,oldm, savm, cij, nres);  
1.126     brouard  5693:     
                   5694:     hf=hstepm*stepm/YEARM;  /* Duration of hstepm expressed in year unit. */
                   5695:     
                   5696:     printf("%d|",(int)age);fflush(stdout);
                   5697:     fprintf(ficlog,"%d|",(int)age);fflush(ficlog);
                   5698:     
                   5699:     /* Computing expectancies */
                   5700:     for(i=1; i<=nlstate;i++)
                   5701:       for(j=1; j<=nlstate;j++)
                   5702:        for (h=0, eij[i][j][(int)age]=0; h<=nhstepm-1; h++){
                   5703:          eij[i][j][(int)age] += (p3mat[i][j][h]+p3mat[i][j][h+1])/2.0*hf;
                   5704:          
                   5705:          /* 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]);*/
                   5706: 
                   5707:        }
                   5708: 
                   5709:     fprintf(ficreseij,"%3.0f",age );
                   5710:     for(i=1; i<=nlstate;i++){
                   5711:       eip=0;
                   5712:       for(j=1; j<=nlstate;j++){
                   5713:        eip +=eij[i][j][(int)age];
                   5714:        fprintf(ficreseij,"%9.4f", eij[i][j][(int)age] );
                   5715:       }
                   5716:       fprintf(ficreseij,"%9.4f", eip );
                   5717:     }
                   5718:     fprintf(ficreseij,"\n");
                   5719:     
                   5720:   }
                   5721:   free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   5722:   printf("\n");
                   5723:   fprintf(ficlog,"\n");
                   5724:   
                   5725: }
                   5726: 
1.235     brouard  5727:  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  5728: 
                   5729: {
                   5730:   /* Covariances of health expectancies eij and of total life expectancies according
1.222     brouard  5731:      to initial status i, ei. .
1.126     brouard  5732:   */
                   5733:   int i, j, nhstepm, hstepm, h, nstepm, k, cptj, cptj2, i2, j2, ij, ji;
                   5734:   int nhstepma, nstepma; /* Decreasing with age */
                   5735:   double age, agelim, hf;
                   5736:   double ***p3matp, ***p3matm, ***varhe;
                   5737:   double **dnewm,**doldm;
                   5738:   double *xp, *xm;
                   5739:   double **gp, **gm;
                   5740:   double ***gradg, ***trgradg;
                   5741:   int theta;
                   5742: 
                   5743:   double eip, vip;
                   5744: 
                   5745:   varhe=ma3x(1,nlstate*nlstate,1,nlstate*nlstate,(int) bage, (int) fage);
                   5746:   xp=vector(1,npar);
                   5747:   xm=vector(1,npar);
                   5748:   dnewm=matrix(1,nlstate*nlstate,1,npar);
                   5749:   doldm=matrix(1,nlstate*nlstate,1,nlstate*nlstate);
                   5750:   
                   5751:   pstamp(ficresstdeij);
                   5752:   fprintf(ficresstdeij,"# Health expectancies with standard errors\n");
                   5753:   fprintf(ficresstdeij,"# Age");
                   5754:   for(i=1; i<=nlstate;i++){
                   5755:     for(j=1; j<=nlstate;j++)
                   5756:       fprintf(ficresstdeij," e%1d%1d (SE)",i,j);
                   5757:     fprintf(ficresstdeij," e%1d. ",i);
                   5758:   }
                   5759:   fprintf(ficresstdeij,"\n");
                   5760: 
                   5761:   pstamp(ficrescveij);
                   5762:   fprintf(ficrescveij,"# Subdiagonal matrix of covariances of health expectancies by age: cov(eij,ekl)\n");
                   5763:   fprintf(ficrescveij,"# Age");
                   5764:   for(i=1; i<=nlstate;i++)
                   5765:     for(j=1; j<=nlstate;j++){
                   5766:       cptj= (j-1)*nlstate+i;
                   5767:       for(i2=1; i2<=nlstate;i2++)
                   5768:        for(j2=1; j2<=nlstate;j2++){
                   5769:          cptj2= (j2-1)*nlstate+i2;
                   5770:          if(cptj2 <= cptj)
                   5771:            fprintf(ficrescveij,"  %1d%1d,%1d%1d",i,j,i2,j2);
                   5772:        }
                   5773:     }
                   5774:   fprintf(ficrescveij,"\n");
                   5775:   
                   5776:   if(estepm < stepm){
                   5777:     printf ("Problem %d lower than %d\n",estepm, stepm);
                   5778:   }
                   5779:   else  hstepm=estepm;   
                   5780:   /* We compute the life expectancy from trapezoids spaced every estepm months
                   5781:    * This is mainly to measure the difference between two models: for example
                   5782:    * if stepm=24 months pijx are given only every 2 years and by summing them
                   5783:    * we are calculating an estimate of the Life Expectancy assuming a linear 
                   5784:    * progression in between and thus overestimating or underestimating according
                   5785:    * to the curvature of the survival function. If, for the same date, we 
                   5786:    * estimate the model with stepm=1 month, we can keep estepm to 24 months
                   5787:    * to compare the new estimate of Life expectancy with the same linear 
                   5788:    * hypothesis. A more precise result, taking into account a more precise
                   5789:    * curvature will be obtained if estepm is as small as stepm. */
                   5790: 
                   5791:   /* For example we decided to compute the life expectancy with the smallest unit */
                   5792:   /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm. 
                   5793:      nhstepm is the number of hstepm from age to agelim 
                   5794:      nstepm is the number of stepm from age to agelin. 
                   5795:      Look at hpijx to understand the reason of that which relies in memory size
                   5796:      and note for a fixed period like estepm months */
                   5797:   /* We decided (b) to get a life expectancy respecting the most precise curvature of the
                   5798:      survival function given by stepm (the optimization length). Unfortunately it
                   5799:      means that if the survival funtion is printed only each two years of age and if
                   5800:      you sum them up and add 1 year (area under the trapezoids) you won't get the same 
                   5801:      results. So we changed our mind and took the option of the best precision.
                   5802:   */
                   5803:   hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */ 
                   5804: 
                   5805:   /* If stepm=6 months */
                   5806:   /* nhstepm age range expressed in number of stepm */
                   5807:   agelim=AGESUP;
                   5808:   nstepm=(int) rint((agelim-bage)*YEARM/stepm); 
                   5809:   /* Typically if 20 years nstepm = 20*12/6=40 stepm */ 
                   5810:   /* if (stepm >= YEARM) hstepm=1;*/
                   5811:   nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
                   5812:   
                   5813:   p3matp=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   5814:   p3matm=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   5815:   gradg=ma3x(0,nhstepm,1,npar,1,nlstate*nlstate);
                   5816:   trgradg =ma3x(0,nhstepm,1,nlstate*nlstate,1,npar);
                   5817:   gp=matrix(0,nhstepm,1,nlstate*nlstate);
                   5818:   gm=matrix(0,nhstepm,1,nlstate*nlstate);
                   5819: 
                   5820:   for (age=bage; age<=fage; age ++){ 
                   5821:     nstepma=(int) rint((agelim-bage)*YEARM/stepm); /* Biggest nstepm */
                   5822:     /* Typically if 20 years nstepm = 20*12/6=40 stepm */ 
                   5823:     /* if (stepm >= YEARM) hstepm=1;*/
                   5824:     nhstepma = nstepma/hstepm;/* Expressed in hstepm, typically nhstepma=40/4=10 */
1.218     brouard  5825:                
1.126     brouard  5826:     /* If stepm=6 months */
                   5827:     /* Computed by stepm unit matrices, product of hstepma matrices, stored
                   5828:        in an array of nhstepma length: nhstepma=10, hstepm=4, stepm=6 months */
                   5829:     
                   5830:     hf=hstepm*stepm/YEARM;  /* Duration of hstepm expressed in year unit. */
1.218     brouard  5831:                
1.126     brouard  5832:     /* Computing  Variances of health expectancies */
                   5833:     /* Gradient is computed with plus gp and minus gm. Code is duplicated in order to
                   5834:        decrease memory allocation */
                   5835:     for(theta=1; theta <=npar; theta++){
                   5836:       for(i=1; i<=npar; i++){ 
1.222     brouard  5837:        xp[i] = x[i] + (i==theta ?delti[theta]:0);
                   5838:        xm[i] = x[i] - (i==theta ?delti[theta]:0);
1.126     brouard  5839:       }
1.235     brouard  5840:       hpxij(p3matp,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, cij, nres);  
                   5841:       hpxij(p3matm,nhstepm,age,hstepm,xm,nlstate,stepm,oldm,savm, cij, nres);  
1.218     brouard  5842:                        
1.126     brouard  5843:       for(j=1; j<= nlstate; j++){
1.222     brouard  5844:        for(i=1; i<=nlstate; i++){
                   5845:          for(h=0; h<=nhstepm-1; h++){
                   5846:            gp[h][(j-1)*nlstate + i] = (p3matp[i][j][h]+p3matp[i][j][h+1])/2.;
                   5847:            gm[h][(j-1)*nlstate + i] = (p3matm[i][j][h]+p3matm[i][j][h+1])/2.;
                   5848:          }
                   5849:        }
1.126     brouard  5850:       }
1.218     brouard  5851:                        
1.126     brouard  5852:       for(ij=1; ij<= nlstate*nlstate; ij++)
1.222     brouard  5853:        for(h=0; h<=nhstepm-1; h++){
                   5854:          gradg[h][theta][ij]= (gp[h][ij]-gm[h][ij])/2./delti[theta];
                   5855:        }
1.126     brouard  5856:     }/* End theta */
                   5857:     
                   5858:     
                   5859:     for(h=0; h<=nhstepm-1; h++)
                   5860:       for(j=1; j<=nlstate*nlstate;j++)
1.222     brouard  5861:        for(theta=1; theta <=npar; theta++)
                   5862:          trgradg[h][j][theta]=gradg[h][theta][j];
1.126     brouard  5863:     
1.218     brouard  5864:                
1.222     brouard  5865:     for(ij=1;ij<=nlstate*nlstate;ij++)
1.126     brouard  5866:       for(ji=1;ji<=nlstate*nlstate;ji++)
1.222     brouard  5867:        varhe[ij][ji][(int)age] =0.;
1.218     brouard  5868:                
1.222     brouard  5869:     printf("%d|",(int)age);fflush(stdout);
                   5870:     fprintf(ficlog,"%d|",(int)age);fflush(ficlog);
                   5871:     for(h=0;h<=nhstepm-1;h++){
1.126     brouard  5872:       for(k=0;k<=nhstepm-1;k++){
1.222     brouard  5873:        matprod2(dnewm,trgradg[h],1,nlstate*nlstate,1,npar,1,npar,matcov);
                   5874:        matprod2(doldm,dnewm,1,nlstate*nlstate,1,npar,1,nlstate*nlstate,gradg[k]);
                   5875:        for(ij=1;ij<=nlstate*nlstate;ij++)
                   5876:          for(ji=1;ji<=nlstate*nlstate;ji++)
                   5877:            varhe[ij][ji][(int)age] += doldm[ij][ji]*hf*hf;
1.126     brouard  5878:       }
                   5879:     }
1.218     brouard  5880:                
1.126     brouard  5881:     /* Computing expectancies */
1.235     brouard  5882:     hpxij(p3matm,nhstepm,age,hstepm,x,nlstate,stepm,oldm, savm, cij,nres);  
1.126     brouard  5883:     for(i=1; i<=nlstate;i++)
                   5884:       for(j=1; j<=nlstate;j++)
1.222     brouard  5885:        for (h=0, eij[i][j][(int)age]=0; h<=nhstepm-1; h++){
                   5886:          eij[i][j][(int)age] += (p3matm[i][j][h]+p3matm[i][j][h+1])/2.0*hf;
1.218     brouard  5887:                                        
1.222     brouard  5888:          /* 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  5889:                                        
1.222     brouard  5890:        }
1.269     brouard  5891: 
                   5892:     /* Standard deviation of expectancies ij */                
1.126     brouard  5893:     fprintf(ficresstdeij,"%3.0f",age );
                   5894:     for(i=1; i<=nlstate;i++){
                   5895:       eip=0.;
                   5896:       vip=0.;
                   5897:       for(j=1; j<=nlstate;j++){
1.222     brouard  5898:        eip += eij[i][j][(int)age];
                   5899:        for(k=1; k<=nlstate;k++) /* Sum on j and k of cov(eij,eik) */
                   5900:          vip += varhe[(j-1)*nlstate+i][(k-1)*nlstate+i][(int)age];
                   5901:        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  5902:       }
                   5903:       fprintf(ficresstdeij," %9.4f (%.4f)", eip, sqrt(vip));
                   5904:     }
                   5905:     fprintf(ficresstdeij,"\n");
1.218     brouard  5906:                
1.269     brouard  5907:     /* Variance of expectancies ij */          
1.126     brouard  5908:     fprintf(ficrescveij,"%3.0f",age );
                   5909:     for(i=1; i<=nlstate;i++)
                   5910:       for(j=1; j<=nlstate;j++){
1.222     brouard  5911:        cptj= (j-1)*nlstate+i;
                   5912:        for(i2=1; i2<=nlstate;i2++)
                   5913:          for(j2=1; j2<=nlstate;j2++){
                   5914:            cptj2= (j2-1)*nlstate+i2;
                   5915:            if(cptj2 <= cptj)
                   5916:              fprintf(ficrescveij," %.4f", varhe[cptj][cptj2][(int)age]);
                   5917:          }
1.126     brouard  5918:       }
                   5919:     fprintf(ficrescveij,"\n");
1.218     brouard  5920:                
1.126     brouard  5921:   }
                   5922:   free_matrix(gm,0,nhstepm,1,nlstate*nlstate);
                   5923:   free_matrix(gp,0,nhstepm,1,nlstate*nlstate);
                   5924:   free_ma3x(gradg,0,nhstepm,1,npar,1,nlstate*nlstate);
                   5925:   free_ma3x(trgradg,0,nhstepm,1,nlstate*nlstate,1,npar);
                   5926:   free_ma3x(p3matm,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   5927:   free_ma3x(p3matp,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   5928:   printf("\n");
                   5929:   fprintf(ficlog,"\n");
1.218     brouard  5930:        
1.126     brouard  5931:   free_vector(xm,1,npar);
                   5932:   free_vector(xp,1,npar);
                   5933:   free_matrix(dnewm,1,nlstate*nlstate,1,npar);
                   5934:   free_matrix(doldm,1,nlstate*nlstate,1,nlstate*nlstate);
                   5935:   free_ma3x(varhe,1,nlstate*nlstate,1,nlstate*nlstate,(int) bage, (int)fage);
                   5936: }
1.218     brouard  5937:  
1.126     brouard  5938: /************ Variance ******************/
1.235     brouard  5939:  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  5940:  {
1.279     brouard  5941:    /** Variance of health expectancies 
                   5942:     *  double **prevalim(double **prlim, int nlstate, double *xp, double age, double **oldm, double ** savm,double ftolpl);
                   5943:     * double **newm;
                   5944:     * int movingaverage(double ***probs, double bage,double fage, double ***mobaverage, int mobilav) 
                   5945:     */
1.218     brouard  5946:   
                   5947:    /* int movingaverage(); */
                   5948:    double **dnewm,**doldm;
                   5949:    double **dnewmp,**doldmp;
                   5950:    int i, j, nhstepm, hstepm, h, nstepm ;
1.288     brouard  5951:    int first=0;
1.218     brouard  5952:    int k;
                   5953:    double *xp;
1.279     brouard  5954:    double **gp, **gm;  /**< for var eij */
                   5955:    double ***gradg, ***trgradg; /**< for var eij */
                   5956:    double **gradgp, **trgradgp; /**< for var p point j */
                   5957:    double *gpp, *gmp; /**< for var p point j */
                   5958:    double **varppt; /**< for var p point j nlstate to nlstate+ndeath */
1.218     brouard  5959:    double ***p3mat;
                   5960:    double age,agelim, hf;
                   5961:    /* double ***mobaverage; */
                   5962:    int theta;
                   5963:    char digit[4];
                   5964:    char digitp[25];
                   5965: 
                   5966:    char fileresprobmorprev[FILENAMELENGTH];
                   5967: 
                   5968:    if(popbased==1){
                   5969:      if(mobilav!=0)
                   5970:        strcpy(digitp,"-POPULBASED-MOBILAV_");
                   5971:      else strcpy(digitp,"-POPULBASED-NOMOBIL_");
                   5972:    }
                   5973:    else 
                   5974:      strcpy(digitp,"-STABLBASED_");
1.126     brouard  5975: 
1.218     brouard  5976:    /* if (mobilav!=0) { */
                   5977:    /*   mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX); */
                   5978:    /*   if (movingaverage(probs, bage, fage, mobaverage,mobilav)!=0){ */
                   5979:    /*     fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav); */
                   5980:    /*     printf(" Error in movingaverage mobilav=%d\n",mobilav); */
                   5981:    /*   } */
                   5982:    /* } */
                   5983: 
                   5984:    strcpy(fileresprobmorprev,"PRMORPREV-"); 
                   5985:    sprintf(digit,"%-d",ij);
                   5986:    /*printf("DIGIT=%s, ij=%d ijr=%-d|\n",digit, ij,ij);*/
                   5987:    strcat(fileresprobmorprev,digit); /* Tvar to be done */
                   5988:    strcat(fileresprobmorprev,digitp); /* Popbased or not, mobilav or not */
                   5989:    strcat(fileresprobmorprev,fileresu);
                   5990:    if((ficresprobmorprev=fopen(fileresprobmorprev,"w"))==NULL) {
                   5991:      printf("Problem with resultfile: %s\n", fileresprobmorprev);
                   5992:      fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobmorprev);
                   5993:    }
                   5994:    printf("Computing total mortality p.j=w1*p1j+w2*p2j+..: result on file '%s' \n",fileresprobmorprev);
                   5995:    fprintf(ficlog,"Computing total mortality p.j=w1*p1j+w2*p2j+..: result on file '%s' \n",fileresprobmorprev);
                   5996:    pstamp(ficresprobmorprev);
                   5997:    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  5998:    fprintf(ficresprobmorprev,"# Selected quantitative variables and dummies");
                   5999:    for (j=1; j<= nsq; j++){ /* For each selected (single) quantitative value */
                   6000:      fprintf(ficresprobmorprev," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]);
                   6001:    }
                   6002:    for(j=1;j<=cptcoveff;j++) 
                   6003:      fprintf(ficresprobmorprev,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(ij,j)]);
                   6004:    fprintf(ficresprobmorprev,"\n");
                   6005: 
1.218     brouard  6006:    fprintf(ficresprobmorprev,"# Age cov=%-d",ij);
                   6007:    for(j=nlstate+1; j<=(nlstate+ndeath);j++){
                   6008:      fprintf(ficresprobmorprev," p.%-d SE",j);
                   6009:      for(i=1; i<=nlstate;i++)
                   6010:        fprintf(ficresprobmorprev," w%1d p%-d%-d",i,i,j);
                   6011:    }  
                   6012:    fprintf(ficresprobmorprev,"\n");
                   6013:   
                   6014:    fprintf(ficgp,"\n# Routine varevsij");
                   6015:    fprintf(ficgp,"\nunset title \n");
                   6016:    /* fprintf(fichtm, "#Local time at start: %s", strstart);*/
                   6017:    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");
                   6018:    fprintf(fichtm,"\n<br>%s  <br>\n",digitp);
1.279     brouard  6019: 
1.218     brouard  6020:    varppt = matrix(nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
                   6021:    pstamp(ficresvij);
                   6022:    fprintf(ficresvij,"# Variance and covariance of health expectancies e.j \n#  (weighted average of eij where weights are ");
                   6023:    if(popbased==1)
                   6024:      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);
                   6025:    else
                   6026:      fprintf(ficresvij,"the age specific period (stable) prevalences in each health state \n");
                   6027:    fprintf(ficresvij,"# Age");
                   6028:    for(i=1; i<=nlstate;i++)
                   6029:      for(j=1; j<=nlstate;j++)
                   6030:        fprintf(ficresvij," Cov(e.%1d, e.%1d)",i,j);
                   6031:    fprintf(ficresvij,"\n");
                   6032: 
                   6033:    xp=vector(1,npar);
                   6034:    dnewm=matrix(1,nlstate,1,npar);
                   6035:    doldm=matrix(1,nlstate,1,nlstate);
                   6036:    dnewmp= matrix(nlstate+1,nlstate+ndeath,1,npar);
                   6037:    doldmp= matrix(nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
                   6038: 
                   6039:    gradgp=matrix(1,npar,nlstate+1,nlstate+ndeath);
                   6040:    gpp=vector(nlstate+1,nlstate+ndeath);
                   6041:    gmp=vector(nlstate+1,nlstate+ndeath);
                   6042:    trgradgp =matrix(nlstate+1,nlstate+ndeath,1,npar); /* mu or p point j*/
1.126     brouard  6043:   
1.218     brouard  6044:    if(estepm < stepm){
                   6045:      printf ("Problem %d lower than %d\n",estepm, stepm);
                   6046:    }
                   6047:    else  hstepm=estepm;   
                   6048:    /* For example we decided to compute the life expectancy with the smallest unit */
                   6049:    /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm. 
                   6050:       nhstepm is the number of hstepm from age to agelim 
                   6051:       nstepm is the number of stepm from age to agelim. 
                   6052:       Look at function hpijx to understand why because of memory size limitations, 
                   6053:       we decided (b) to get a life expectancy respecting the most precise curvature of the
                   6054:       survival function given by stepm (the optimization length). Unfortunately it
                   6055:       means that if the survival funtion is printed every two years of age and if
                   6056:       you sum them up and add 1 year (area under the trapezoids) you won't get the same 
                   6057:       results. So we changed our mind and took the option of the best precision.
                   6058:    */
                   6059:    hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */ 
                   6060:    agelim = AGESUP;
                   6061:    for (age=bage; age<=fage; age ++){ /* If stepm=6 months */
                   6062:      nstepm=(int) rint((agelim-age)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */ 
                   6063:      nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
                   6064:      p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   6065:      gradg=ma3x(0,nhstepm,1,npar,1,nlstate);
                   6066:      gp=matrix(0,nhstepm,1,nlstate);
                   6067:      gm=matrix(0,nhstepm,1,nlstate);
                   6068:                
                   6069:                
                   6070:      for(theta=1; theta <=npar; theta++){
                   6071:        for(i=1; i<=npar; i++){ /* Computes gradient x + delta*/
                   6072:         xp[i] = x[i] + (i==theta ?delti[theta]:0);
                   6073:        }
1.279     brouard  6074:        /**< Computes the prevalence limit with parameter theta shifted of delta up to ftolpl precision and 
                   6075:        * returns into prlim .
1.288     brouard  6076:        */
1.242     brouard  6077:        prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp,ij, nres);
1.279     brouard  6078: 
                   6079:        /* If popbased = 1 we use crossection prevalences. Previous step is useless but prlim is created */
1.218     brouard  6080:        if (popbased==1) {
                   6081:         if(mobilav ==0){
                   6082:           for(i=1; i<=nlstate;i++)
                   6083:             prlim[i][i]=probs[(int)age][i][ij];
                   6084:         }else{ /* mobilav */ 
                   6085:           for(i=1; i<=nlstate;i++)
                   6086:             prlim[i][i]=mobaverage[(int)age][i][ij];
                   6087:         }
                   6088:        }
1.295     brouard  6089:        /**< Computes the shifted transition matrix \f$ {}{h}_p^{ij}x\f$ at horizon h.
1.279     brouard  6090:        */                      
                   6091:        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  6092:        /**< 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  6093:        * at horizon h in state j including mortality.
                   6094:        */
1.218     brouard  6095:        for(j=1; j<= nlstate; j++){
                   6096:         for(h=0; h<=nhstepm; h++){
                   6097:           for(i=1, gp[h][j]=0.;i<=nlstate;i++)
                   6098:             gp[h][j] += prlim[i][i]*p3mat[i][j][h];
                   6099:         }
                   6100:        }
1.279     brouard  6101:        /* Next for computing shifted+ probability of death (h=1 means
1.218     brouard  6102:          computed over hstepm matrices product = hstepm*stepm months) 
1.279     brouard  6103:          as a weighted average of prlim(i) * p(i,j) p.3=w1*p13 + w2*p23 .
1.218     brouard  6104:        */
                   6105:        for(j=nlstate+1;j<=nlstate+ndeath;j++){
                   6106:         for(i=1,gpp[j]=0.; i<= nlstate; i++)
                   6107:           gpp[j] += prlim[i][i]*p3mat[i][j][1];
1.279     brouard  6108:        }
                   6109:        
                   6110:        /* Again with minus shift */
1.218     brouard  6111:                        
                   6112:        for(i=1; i<=npar; i++) /* Computes gradient x - delta */
                   6113:         xp[i] = x[i] - (i==theta ?delti[theta]:0);
1.288     brouard  6114: 
1.242     brouard  6115:        prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp, ij, nres);
1.218     brouard  6116:                        
                   6117:        if (popbased==1) {
                   6118:         if(mobilav ==0){
                   6119:           for(i=1; i<=nlstate;i++)
                   6120:             prlim[i][i]=probs[(int)age][i][ij];
                   6121:         }else{ /* mobilav */ 
                   6122:           for(i=1; i<=nlstate;i++)
                   6123:             prlim[i][i]=mobaverage[(int)age][i][ij];
                   6124:         }
                   6125:        }
                   6126:                        
1.235     brouard  6127:        hpxij(p3mat,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, ij,nres);  
1.218     brouard  6128:                        
                   6129:        for(j=1; j<= nlstate; j++){  /* Sum of wi * eij = e.j */
                   6130:         for(h=0; h<=nhstepm; h++){
                   6131:           for(i=1, gm[h][j]=0.;i<=nlstate;i++)
                   6132:             gm[h][j] += prlim[i][i]*p3mat[i][j][h];
                   6133:         }
                   6134:        }
                   6135:        /* This for computing probability of death (h=1 means
                   6136:          computed over hstepm matrices product = hstepm*stepm months) 
                   6137:          as a weighted average of prlim.
                   6138:        */
                   6139:        for(j=nlstate+1;j<=nlstate+ndeath;j++){
                   6140:         for(i=1,gmp[j]=0.; i<= nlstate; i++)
                   6141:           gmp[j] += prlim[i][i]*p3mat[i][j][1];
                   6142:        }    
1.279     brouard  6143:        /* end shifting computations */
                   6144: 
                   6145:        /**< Computing gradient matrix at horizon h 
                   6146:        */
1.218     brouard  6147:        for(j=1; j<= nlstate; j++) /* vareij */
                   6148:         for(h=0; h<=nhstepm; h++){
                   6149:           gradg[h][theta][j]= (gp[h][j]-gm[h][j])/2./delti[theta];
                   6150:         }
1.279     brouard  6151:        /**< Gradient of overall mortality p.3 (or p.j) 
                   6152:        */
                   6153:        for(j=nlstate+1; j<= nlstate+ndeath; j++){ /* var mu mortality from j */
1.218     brouard  6154:         gradgp[theta][j]= (gpp[j]-gmp[j])/2./delti[theta];
                   6155:        }
                   6156:                        
                   6157:      } /* End theta */
1.279     brouard  6158:      
                   6159:      /* We got the gradient matrix for each theta and state j */               
1.218     brouard  6160:      trgradg =ma3x(0,nhstepm,1,nlstate,1,npar); /* veij */
                   6161:                
                   6162:      for(h=0; h<=nhstepm; h++) /* veij */
                   6163:        for(j=1; j<=nlstate;j++)
                   6164:         for(theta=1; theta <=npar; theta++)
                   6165:           trgradg[h][j][theta]=gradg[h][theta][j];
                   6166:                
                   6167:      for(j=nlstate+1; j<=nlstate+ndeath;j++) /* mu */
                   6168:        for(theta=1; theta <=npar; theta++)
                   6169:         trgradgp[j][theta]=gradgp[theta][j];
1.279     brouard  6170:      /**< as well as its transposed matrix 
                   6171:       */               
1.218     brouard  6172:                
                   6173:      hf=hstepm*stepm/YEARM;  /* Duration of hstepm expressed in year unit. */
                   6174:      for(i=1;i<=nlstate;i++)
                   6175:        for(j=1;j<=nlstate;j++)
                   6176:         vareij[i][j][(int)age] =0.;
1.279     brouard  6177: 
                   6178:      /* Computing trgradg by matcov by gradg at age and summing over h
                   6179:       * and k (nhstepm) formula 15 of article
                   6180:       * Lievre-Brouard-Heathcote
                   6181:       */
                   6182:      
1.218     brouard  6183:      for(h=0;h<=nhstepm;h++){
                   6184:        for(k=0;k<=nhstepm;k++){
                   6185:         matprod2(dnewm,trgradg[h],1,nlstate,1,npar,1,npar,matcov);
                   6186:         matprod2(doldm,dnewm,1,nlstate,1,npar,1,nlstate,gradg[k]);
                   6187:         for(i=1;i<=nlstate;i++)
                   6188:           for(j=1;j<=nlstate;j++)
                   6189:             vareij[i][j][(int)age] += doldm[i][j]*hf*hf;
                   6190:        }
                   6191:      }
                   6192:                
1.279     brouard  6193:      /* pptj is p.3 or p.j = trgradgp by cov by gradgp, variance of
                   6194:       * p.j overall mortality formula 49 but computed directly because
                   6195:       * we compute the grad (wix pijx) instead of grad (pijx),even if
                   6196:       * wix is independent of theta.
                   6197:       */
1.218     brouard  6198:      matprod2(dnewmp,trgradgp,nlstate+1,nlstate+ndeath,1,npar,1,npar,matcov);
                   6199:      matprod2(doldmp,dnewmp,nlstate+1,nlstate+ndeath,1,npar,nlstate+1,nlstate+ndeath,gradgp);
                   6200:      for(j=nlstate+1;j<=nlstate+ndeath;j++)
                   6201:        for(i=nlstate+1;i<=nlstate+ndeath;i++)
                   6202:         varppt[j][i]=doldmp[j][i];
                   6203:      /* end ppptj */
                   6204:      /*  x centered again */
                   6205:                
1.242     brouard  6206:      prevalim(prlim,nlstate,x,age,oldm,savm,ftolpl,ncvyearp,ij, nres);
1.218     brouard  6207:                
                   6208:      if (popbased==1) {
                   6209:        if(mobilav ==0){
                   6210:         for(i=1; i<=nlstate;i++)
                   6211:           prlim[i][i]=probs[(int)age][i][ij];
                   6212:        }else{ /* mobilav */ 
                   6213:         for(i=1; i<=nlstate;i++)
                   6214:           prlim[i][i]=mobaverage[(int)age][i][ij];
                   6215:        }
                   6216:      }
                   6217:                
                   6218:      /* This for computing probability of death (h=1 means
                   6219:        computed over hstepm (estepm) matrices product = hstepm*stepm months) 
                   6220:        as a weighted average of prlim.
                   6221:      */
1.235     brouard  6222:      hpxij(p3mat,nhstepm,age,hstepm,x,nlstate,stepm,oldm,savm, ij, nres);  
1.218     brouard  6223:      for(j=nlstate+1;j<=nlstate+ndeath;j++){
                   6224:        for(i=1,gmp[j]=0.;i<= nlstate; i++) 
                   6225:         gmp[j] += prlim[i][i]*p3mat[i][j][1]; 
                   6226:      }    
                   6227:      /* end probability of death */
                   6228:                
                   6229:      fprintf(ficresprobmorprev,"%3d %d ",(int) age, ij);
                   6230:      for(j=nlstate+1; j<=(nlstate+ndeath);j++){
                   6231:        fprintf(ficresprobmorprev," %11.3e %11.3e",gmp[j], sqrt(varppt[j][j]));
                   6232:        for(i=1; i<=nlstate;i++){
                   6233:         fprintf(ficresprobmorprev," %11.3e %11.3e ",prlim[i][i],p3mat[i][j][1]);
                   6234:        }
                   6235:      } 
                   6236:      fprintf(ficresprobmorprev,"\n");
                   6237:                
                   6238:      fprintf(ficresvij,"%.0f ",age );
                   6239:      for(i=1; i<=nlstate;i++)
                   6240:        for(j=1; j<=nlstate;j++){
                   6241:         fprintf(ficresvij," %.4f", vareij[i][j][(int)age]);
                   6242:        }
                   6243:      fprintf(ficresvij,"\n");
                   6244:      free_matrix(gp,0,nhstepm,1,nlstate);
                   6245:      free_matrix(gm,0,nhstepm,1,nlstate);
                   6246:      free_ma3x(gradg,0,nhstepm,1,npar,1,nlstate);
                   6247:      free_ma3x(trgradg,0,nhstepm,1,nlstate,1,npar);
                   6248:      free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   6249:    } /* End age */
                   6250:    free_vector(gpp,nlstate+1,nlstate+ndeath);
                   6251:    free_vector(gmp,nlstate+1,nlstate+ndeath);
                   6252:    free_matrix(gradgp,1,npar,nlstate+1,nlstate+ndeath);
                   6253:    free_matrix(trgradgp,nlstate+1,nlstate+ndeath,1,npar); /* mu or p point j*/
                   6254:    /* fprintf(ficgp,"\nunset parametric;unset label; set ter png small size 320, 240"); */
                   6255:    fprintf(ficgp,"\nunset parametric;unset label; set ter svg size 640, 480");
                   6256:    /* for(j=nlstate+1; j<= nlstate+ndeath; j++){ *//* Only the first actually */
                   6257:    fprintf(ficgp,"\n set log y; unset log x;set xlabel \"Age\"; set ylabel \"Force of mortality (year-1)\";");
                   6258:    fprintf(ficgp,"\nset out \"%s%s.svg\";",subdirf3(optionfilefiname,"VARMUPTJGR-",digitp),digit);
                   6259:    /*   fprintf(ficgp,"\n plot \"%s\"  u 1:($3*%6.3f) not w l 1 ",fileresprobmorprev,YEARM/estepm); */
                   6260:    /*   fprintf(ficgp,"\n replot \"%s\"  u 1:(($3+1.96*$4)*%6.3f) t \"95\%% interval\" w l 2 ",fileresprobmorprev,YEARM/estepm); */
                   6261:    /*   fprintf(ficgp,"\n replot \"%s\"  u 1:(($3-1.96*$4)*%6.3f) not w l 2 ",fileresprobmorprev,YEARM/estepm); */
                   6262:    fprintf(ficgp,"\n plot \"%s\"  u 1:($3) not w l lt 1 ",subdirf(fileresprobmorprev));
                   6263:    fprintf(ficgp,"\n replot \"%s\"  u 1:(($3+1.96*$4)) t \"95%% interval\" w l lt 2 ",subdirf(fileresprobmorprev));
                   6264:    fprintf(ficgp,"\n replot \"%s\"  u 1:(($3-1.96*$4)) not w l lt 2 ",subdirf(fileresprobmorprev));
                   6265:    fprintf(fichtm,"\n<br> File (multiple files are possible if covariates are present): <A href=\"%s\">%s</a>\n",subdirf(fileresprobmorprev),subdirf(fileresprobmorprev));
                   6266:    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);
                   6267:    /*  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  6268:     */
1.218     brouard  6269:    /*   fprintf(ficgp,"\nset out \"varmuptjgr%s%s%s.svg\";replot;",digitp,optionfilefiname,digit); */
                   6270:    fprintf(ficgp,"\nset out;\nset out \"%s%s.svg\";replot;set out;\n",subdirf3(optionfilefiname,"VARMUPTJGR-",digitp),digit);
1.126     brouard  6271: 
1.218     brouard  6272:    free_vector(xp,1,npar);
                   6273:    free_matrix(doldm,1,nlstate,1,nlstate);
                   6274:    free_matrix(dnewm,1,nlstate,1,npar);
                   6275:    free_matrix(doldmp,nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
                   6276:    free_matrix(dnewmp,nlstate+1,nlstate+ndeath,1,npar);
                   6277:    free_matrix(varppt,nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
                   6278:    /* if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX); */
                   6279:    fclose(ficresprobmorprev);
                   6280:    fflush(ficgp);
                   6281:    fflush(fichtm); 
                   6282:  }  /* end varevsij */
1.126     brouard  6283: 
                   6284: /************ Variance of prevlim ******************/
1.269     brouard  6285:  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  6286: {
1.205     brouard  6287:   /* Variance of prevalence limit  for each state ij using current parameters x[] and estimates of neighbourhood give by delti*/
1.126     brouard  6288:   /*  double **prevalim(double **prlim, int nlstate, double *xp, double age, double **oldm, double **savm,double ftolpl);*/
1.164     brouard  6289: 
1.268     brouard  6290:   double **dnewmpar,**doldm;
1.126     brouard  6291:   int i, j, nhstepm, hstepm;
                   6292:   double *xp;
                   6293:   double *gp, *gm;
                   6294:   double **gradg, **trgradg;
1.208     brouard  6295:   double **mgm, **mgp;
1.126     brouard  6296:   double age,agelim;
                   6297:   int theta;
                   6298:   
                   6299:   pstamp(ficresvpl);
1.288     brouard  6300:   fprintf(ficresvpl,"# Standard deviation of period (forward stable) prevalences \n");
1.241     brouard  6301:   fprintf(ficresvpl,"# Age ");
                   6302:   if(nresult >=1)
                   6303:     fprintf(ficresvpl," Result# ");
1.126     brouard  6304:   for(i=1; i<=nlstate;i++)
                   6305:       fprintf(ficresvpl," %1d-%1d",i,i);
                   6306:   fprintf(ficresvpl,"\n");
                   6307: 
                   6308:   xp=vector(1,npar);
1.268     brouard  6309:   dnewmpar=matrix(1,nlstate,1,npar);
1.126     brouard  6310:   doldm=matrix(1,nlstate,1,nlstate);
                   6311:   
                   6312:   hstepm=1*YEARM; /* Every year of age */
                   6313:   hstepm=hstepm/stepm; /* Typically in stepm units, if j= 2 years, = 2/6 months = 4 */ 
                   6314:   agelim = AGESUP;
                   6315:   for (age=bage; age<=fage; age ++){ /* If stepm=6 months */
                   6316:     nhstepm=(int) rint((agelim-age)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */ 
                   6317:     if (stepm >= YEARM) hstepm=1;
                   6318:     nhstepm = nhstepm/hstepm; /* Typically 40/4=10 */
                   6319:     gradg=matrix(1,npar,1,nlstate);
1.208     brouard  6320:     mgp=matrix(1,npar,1,nlstate);
                   6321:     mgm=matrix(1,npar,1,nlstate);
1.126     brouard  6322:     gp=vector(1,nlstate);
                   6323:     gm=vector(1,nlstate);
                   6324: 
                   6325:     for(theta=1; theta <=npar; theta++){
                   6326:       for(i=1; i<=npar; i++){ /* Computes gradient */
                   6327:        xp[i] = x[i] + (i==theta ?delti[theta]:0);
                   6328:       }
1.288     brouard  6329:       /* if((int)age==79 ||(int)age== 80 ||(int)age== 81 ) */
                   6330:       /*       prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp,ij,nres); */
                   6331:       /* else */
                   6332:       prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp,ij,nres);
1.208     brouard  6333:       for(i=1;i<=nlstate;i++){
1.126     brouard  6334:        gp[i] = prlim[i][i];
1.208     brouard  6335:        mgp[theta][i] = prlim[i][i];
                   6336:       }
1.126     brouard  6337:       for(i=1; i<=npar; i++) /* Computes gradient */
                   6338:        xp[i] = x[i] - (i==theta ?delti[theta]:0);
1.288     brouard  6339:       /* if((int)age==79 ||(int)age== 80 ||(int)age== 81 ) */
                   6340:       /*       prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp,ij,nres); */
                   6341:       /* else */
                   6342:       prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp,ij,nres);
1.208     brouard  6343:       for(i=1;i<=nlstate;i++){
1.126     brouard  6344:        gm[i] = prlim[i][i];
1.208     brouard  6345:        mgm[theta][i] = prlim[i][i];
                   6346:       }
1.126     brouard  6347:       for(i=1;i<=nlstate;i++)
                   6348:        gradg[theta][i]= (gp[i]-gm[i])/2./delti[theta];
1.209     brouard  6349:       /* gradg[theta][2]= -gradg[theta][1]; */ /* For testing if nlstate=2 */
1.126     brouard  6350:     } /* End theta */
                   6351: 
                   6352:     trgradg =matrix(1,nlstate,1,npar);
                   6353: 
                   6354:     for(j=1; j<=nlstate;j++)
                   6355:       for(theta=1; theta <=npar; theta++)
                   6356:        trgradg[j][theta]=gradg[theta][j];
1.209     brouard  6357:     /* if((int)age==79 ||(int)age== 80 ||(int)age== 81 ){ */
                   6358:     /*   printf("\nmgm mgp %d ",(int)age); */
                   6359:     /*   for(j=1; j<=nlstate;j++){ */
                   6360:     /*         printf(" %d ",j); */
                   6361:     /*         for(theta=1; theta <=npar; theta++) */
                   6362:     /*           printf(" %d %lf %lf",theta,mgm[theta][j],mgp[theta][j]); */
                   6363:     /*         printf("\n "); */
                   6364:     /*   } */
                   6365:     /* } */
                   6366:     /* if((int)age==79 ||(int)age== 80 ||(int)age== 81 ){ */
                   6367:     /*   printf("\n gradg %d ",(int)age); */
                   6368:     /*   for(j=1; j<=nlstate;j++){ */
                   6369:     /*         printf("%d ",j); */
                   6370:     /*         for(theta=1; theta <=npar; theta++) */
                   6371:     /*           printf("%d %lf ",theta,gradg[theta][j]); */
                   6372:     /*         printf("\n "); */
                   6373:     /*   } */
                   6374:     /* } */
1.126     brouard  6375: 
                   6376:     for(i=1;i<=nlstate;i++)
                   6377:       varpl[i][(int)age] =0.;
1.209     brouard  6378:     if((int)age==79 ||(int)age== 80  ||(int)age== 81){
1.268     brouard  6379:     matprod2(dnewmpar,trgradg,1,nlstate,1,npar,1,npar,matcov);
                   6380:     matprod2(doldm,dnewmpar,1,nlstate,1,npar,1,nlstate,gradg);
1.205     brouard  6381:     }else{
1.268     brouard  6382:     matprod2(dnewmpar,trgradg,1,nlstate,1,npar,1,npar,matcov);
                   6383:     matprod2(doldm,dnewmpar,1,nlstate,1,npar,1,nlstate,gradg);
1.205     brouard  6384:     }
1.126     brouard  6385:     for(i=1;i<=nlstate;i++)
                   6386:       varpl[i][(int)age] = doldm[i][i]; /* Covariances are useless */
                   6387: 
                   6388:     fprintf(ficresvpl,"%.0f ",age );
1.241     brouard  6389:     if(nresult >=1)
                   6390:       fprintf(ficresvpl,"%d ",nres );
1.288     brouard  6391:     for(i=1; i<=nlstate;i++){
1.126     brouard  6392:       fprintf(ficresvpl," %.5f (%.5f)",prlim[i][i],sqrt(varpl[i][(int)age]));
1.288     brouard  6393:       /* for(j=1;j<=nlstate;j++) */
                   6394:       /*       fprintf(ficresvpl," %d %.5f ",j,prlim[j][i]); */
                   6395:     }
1.126     brouard  6396:     fprintf(ficresvpl,"\n");
                   6397:     free_vector(gp,1,nlstate);
                   6398:     free_vector(gm,1,nlstate);
1.208     brouard  6399:     free_matrix(mgm,1,npar,1,nlstate);
                   6400:     free_matrix(mgp,1,npar,1,nlstate);
1.126     brouard  6401:     free_matrix(gradg,1,npar,1,nlstate);
                   6402:     free_matrix(trgradg,1,nlstate,1,npar);
                   6403:   } /* End age */
                   6404: 
                   6405:   free_vector(xp,1,npar);
                   6406:   free_matrix(doldm,1,nlstate,1,npar);
1.268     brouard  6407:   free_matrix(dnewmpar,1,nlstate,1,nlstate);
                   6408: 
                   6409: }
                   6410: 
                   6411: 
                   6412: /************ Variance of backprevalence limit ******************/
1.269     brouard  6413:  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  6414: {
                   6415:   /* Variance of backward prevalence limit  for each state ij using current parameters x[] and estimates of neighbourhood give by delti*/
                   6416:   /*  double **prevalim(double **prlim, int nlstate, double *xp, double age, double **oldm, double **savm,double ftolpl);*/
                   6417: 
                   6418:   double **dnewmpar,**doldm;
                   6419:   int i, j, nhstepm, hstepm;
                   6420:   double *xp;
                   6421:   double *gp, *gm;
                   6422:   double **gradg, **trgradg;
                   6423:   double **mgm, **mgp;
                   6424:   double age,agelim;
                   6425:   int theta;
                   6426:   
                   6427:   pstamp(ficresvbl);
                   6428:   fprintf(ficresvbl,"# Standard deviation of back (stable) prevalences \n");
                   6429:   fprintf(ficresvbl,"# Age ");
                   6430:   if(nresult >=1)
                   6431:     fprintf(ficresvbl," Result# ");
                   6432:   for(i=1; i<=nlstate;i++)
                   6433:       fprintf(ficresvbl," %1d-%1d",i,i);
                   6434:   fprintf(ficresvbl,"\n");
                   6435: 
                   6436:   xp=vector(1,npar);
                   6437:   dnewmpar=matrix(1,nlstate,1,npar);
                   6438:   doldm=matrix(1,nlstate,1,nlstate);
                   6439:   
                   6440:   hstepm=1*YEARM; /* Every year of age */
                   6441:   hstepm=hstepm/stepm; /* Typically in stepm units, if j= 2 years, = 2/6 months = 4 */ 
                   6442:   agelim = AGEINF;
                   6443:   for (age=fage; age>=bage; age --){ /* If stepm=6 months */
                   6444:     nhstepm=(int) rint((age-agelim)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */ 
                   6445:     if (stepm >= YEARM) hstepm=1;
                   6446:     nhstepm = nhstepm/hstepm; /* Typically 40/4=10 */
                   6447:     gradg=matrix(1,npar,1,nlstate);
                   6448:     mgp=matrix(1,npar,1,nlstate);
                   6449:     mgm=matrix(1,npar,1,nlstate);
                   6450:     gp=vector(1,nlstate);
                   6451:     gm=vector(1,nlstate);
                   6452: 
                   6453:     for(theta=1; theta <=npar; theta++){
                   6454:       for(i=1; i<=npar; i++){ /* Computes gradient */
                   6455:        xp[i] = x[i] + (i==theta ?delti[theta]:0);
                   6456:       }
                   6457:       if(mobilavproj > 0 )
                   6458:        bprevalim(bprlim, mobaverage,nlstate,xp,age,ftolpl,ncvyearp,ij,nres);
                   6459:       else
                   6460:        bprevalim(bprlim, mobaverage,nlstate,xp,age,ftolpl,ncvyearp,ij,nres);
                   6461:       for(i=1;i<=nlstate;i++){
                   6462:        gp[i] = bprlim[i][i];
                   6463:        mgp[theta][i] = bprlim[i][i];
                   6464:       }
                   6465:      for(i=1; i<=npar; i++) /* Computes gradient */
                   6466:        xp[i] = x[i] - (i==theta ?delti[theta]:0);
                   6467:        if(mobilavproj > 0 )
                   6468:        bprevalim(bprlim, mobaverage,nlstate,xp,age,ftolpl,ncvyearp,ij,nres);
                   6469:        else
                   6470:        bprevalim(bprlim, mobaverage,nlstate,xp,age,ftolpl,ncvyearp,ij,nres);
                   6471:       for(i=1;i<=nlstate;i++){
                   6472:        gm[i] = bprlim[i][i];
                   6473:        mgm[theta][i] = bprlim[i][i];
                   6474:       }
                   6475:       for(i=1;i<=nlstate;i++)
                   6476:        gradg[theta][i]= (gp[i]-gm[i])/2./delti[theta];
                   6477:       /* gradg[theta][2]= -gradg[theta][1]; */ /* For testing if nlstate=2 */
                   6478:     } /* End theta */
                   6479: 
                   6480:     trgradg =matrix(1,nlstate,1,npar);
                   6481: 
                   6482:     for(j=1; j<=nlstate;j++)
                   6483:       for(theta=1; theta <=npar; theta++)
                   6484:        trgradg[j][theta]=gradg[theta][j];
                   6485:     /* if((int)age==79 ||(int)age== 80 ||(int)age== 81 ){ */
                   6486:     /*   printf("\nmgm mgp %d ",(int)age); */
                   6487:     /*   for(j=1; j<=nlstate;j++){ */
                   6488:     /*         printf(" %d ",j); */
                   6489:     /*         for(theta=1; theta <=npar; theta++) */
                   6490:     /*           printf(" %d %lf %lf",theta,mgm[theta][j],mgp[theta][j]); */
                   6491:     /*         printf("\n "); */
                   6492:     /*   } */
                   6493:     /* } */
                   6494:     /* if((int)age==79 ||(int)age== 80 ||(int)age== 81 ){ */
                   6495:     /*   printf("\n gradg %d ",(int)age); */
                   6496:     /*   for(j=1; j<=nlstate;j++){ */
                   6497:     /*         printf("%d ",j); */
                   6498:     /*         for(theta=1; theta <=npar; theta++) */
                   6499:     /*           printf("%d %lf ",theta,gradg[theta][j]); */
                   6500:     /*         printf("\n "); */
                   6501:     /*   } */
                   6502:     /* } */
                   6503: 
                   6504:     for(i=1;i<=nlstate;i++)
                   6505:       varbpl[i][(int)age] =0.;
                   6506:     if((int)age==79 ||(int)age== 80  ||(int)age== 81){
                   6507:     matprod2(dnewmpar,trgradg,1,nlstate,1,npar,1,npar,matcov);
                   6508:     matprod2(doldm,dnewmpar,1,nlstate,1,npar,1,nlstate,gradg);
                   6509:     }else{
                   6510:     matprod2(dnewmpar,trgradg,1,nlstate,1,npar,1,npar,matcov);
                   6511:     matprod2(doldm,dnewmpar,1,nlstate,1,npar,1,nlstate,gradg);
                   6512:     }
                   6513:     for(i=1;i<=nlstate;i++)
                   6514:       varbpl[i][(int)age] = doldm[i][i]; /* Covariances are useless */
                   6515: 
                   6516:     fprintf(ficresvbl,"%.0f ",age );
                   6517:     if(nresult >=1)
                   6518:       fprintf(ficresvbl,"%d ",nres );
                   6519:     for(i=1; i<=nlstate;i++)
                   6520:       fprintf(ficresvbl," %.5f (%.5f)",bprlim[i][i],sqrt(varbpl[i][(int)age]));
                   6521:     fprintf(ficresvbl,"\n");
                   6522:     free_vector(gp,1,nlstate);
                   6523:     free_vector(gm,1,nlstate);
                   6524:     free_matrix(mgm,1,npar,1,nlstate);
                   6525:     free_matrix(mgp,1,npar,1,nlstate);
                   6526:     free_matrix(gradg,1,npar,1,nlstate);
                   6527:     free_matrix(trgradg,1,nlstate,1,npar);
                   6528:   } /* End age */
                   6529: 
                   6530:   free_vector(xp,1,npar);
                   6531:   free_matrix(doldm,1,nlstate,1,npar);
                   6532:   free_matrix(dnewmpar,1,nlstate,1,nlstate);
1.126     brouard  6533: 
                   6534: }
                   6535: 
                   6536: /************ Variance of one-step probabilities  ******************/
                   6537: 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  6538:  {
                   6539:    int i, j=0,  k1, l1, tj;
                   6540:    int k2, l2, j1,  z1;
                   6541:    int k=0, l;
                   6542:    int first=1, first1, first2;
                   6543:    double cv12, mu1, mu2, lc1, lc2, v12, v21, v11, v22,v1,v2, c12, tnalp;
                   6544:    double **dnewm,**doldm;
                   6545:    double *xp;
                   6546:    double *gp, *gm;
                   6547:    double **gradg, **trgradg;
                   6548:    double **mu;
                   6549:    double age, cov[NCOVMAX+1];
                   6550:    double std=2.0; /* Number of standard deviation wide of confidence ellipsoids */
                   6551:    int theta;
                   6552:    char fileresprob[FILENAMELENGTH];
                   6553:    char fileresprobcov[FILENAMELENGTH];
                   6554:    char fileresprobcor[FILENAMELENGTH];
                   6555:    double ***varpij;
                   6556: 
                   6557:    strcpy(fileresprob,"PROB_"); 
                   6558:    strcat(fileresprob,fileres);
                   6559:    if((ficresprob=fopen(fileresprob,"w"))==NULL) {
                   6560:      printf("Problem with resultfile: %s\n", fileresprob);
                   6561:      fprintf(ficlog,"Problem with resultfile: %s\n", fileresprob);
                   6562:    }
                   6563:    strcpy(fileresprobcov,"PROBCOV_"); 
                   6564:    strcat(fileresprobcov,fileresu);
                   6565:    if((ficresprobcov=fopen(fileresprobcov,"w"))==NULL) {
                   6566:      printf("Problem with resultfile: %s\n", fileresprobcov);
                   6567:      fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobcov);
                   6568:    }
                   6569:    strcpy(fileresprobcor,"PROBCOR_"); 
                   6570:    strcat(fileresprobcor,fileresu);
                   6571:    if((ficresprobcor=fopen(fileresprobcor,"w"))==NULL) {
                   6572:      printf("Problem with resultfile: %s\n", fileresprobcor);
                   6573:      fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobcor);
                   6574:    }
                   6575:    printf("Computing standard deviation of one-step probabilities: result on file '%s' \n",fileresprob);
                   6576:    fprintf(ficlog,"Computing standard deviation of one-step probabilities: result on file '%s' \n",fileresprob);
                   6577:    printf("Computing matrix of variance covariance of one-step probabilities: result on file '%s' \n",fileresprobcov);
                   6578:    fprintf(ficlog,"Computing matrix of variance covariance of one-step probabilities: result on file '%s' \n",fileresprobcov);
                   6579:    printf("and correlation matrix of one-step probabilities: result on file '%s' \n",fileresprobcor);
                   6580:    fprintf(ficlog,"and correlation matrix of one-step probabilities: result on file '%s' \n",fileresprobcor);
                   6581:    pstamp(ficresprob);
                   6582:    fprintf(ficresprob,"#One-step probabilities and stand. devi in ()\n");
                   6583:    fprintf(ficresprob,"# Age");
                   6584:    pstamp(ficresprobcov);
                   6585:    fprintf(ficresprobcov,"#One-step probabilities and covariance matrix\n");
                   6586:    fprintf(ficresprobcov,"# Age");
                   6587:    pstamp(ficresprobcor);
                   6588:    fprintf(ficresprobcor,"#One-step probabilities and correlation matrix\n");
                   6589:    fprintf(ficresprobcor,"# Age");
1.126     brouard  6590: 
                   6591: 
1.222     brouard  6592:    for(i=1; i<=nlstate;i++)
                   6593:      for(j=1; j<=(nlstate+ndeath);j++){
                   6594:        fprintf(ficresprob," p%1d-%1d (SE)",i,j);
                   6595:        fprintf(ficresprobcov," p%1d-%1d ",i,j);
                   6596:        fprintf(ficresprobcor," p%1d-%1d ",i,j);
                   6597:      }  
                   6598:    /* fprintf(ficresprob,"\n");
                   6599:       fprintf(ficresprobcov,"\n");
                   6600:       fprintf(ficresprobcor,"\n");
                   6601:    */
                   6602:    xp=vector(1,npar);
                   6603:    dnewm=matrix(1,(nlstate)*(nlstate+ndeath),1,npar);
                   6604:    doldm=matrix(1,(nlstate)*(nlstate+ndeath),1,(nlstate)*(nlstate+ndeath));
                   6605:    mu=matrix(1,(nlstate)*(nlstate+ndeath), (int) bage, (int)fage);
                   6606:    varpij=ma3x(1,nlstate*(nlstate+ndeath),1,nlstate*(nlstate+ndeath),(int) bage, (int) fage);
                   6607:    first=1;
                   6608:    fprintf(ficgp,"\n# Routine varprob");
                   6609:    fprintf(fichtm,"\n<li><h4> Computing and drawing one step probabilities with their confidence intervals</h4></li>\n");
                   6610:    fprintf(fichtm,"\n");
                   6611: 
1.288     brouard  6612:    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  6613:    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);
                   6614:    fprintf(fichtmcov,"\nEllipsoids of confidence centered on point (p<inf>ij</inf>, p<inf>kl</inf>) are estimated \
1.126     brouard  6615: and drawn. It helps understanding how is the covariance between two incidences.\
                   6616:  They are expressed in year<sup>-1</sup> in order to be less dependent of stepm.<br>\n");
1.222     brouard  6617:    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  6618: It can be understood this way: if pij and pkl where uncorrelated the (2x2) matrix of covariance \
                   6619: would have been (1/(var pij), 0 , 0, 1/(var pkl)), and the confidence interval would be 2 \
                   6620: standard deviations wide on each axis. <br>\
                   6621:  Now, if both incidences are correlated (usual case) we diagonalised the inverse of the covariance matrix\
                   6622:  and made the appropriate rotation to look at the uncorrelated principal directions.<br>\
                   6623: To be simple, these graphs help to understand the significativity of each parameter in relation to a second other one.<br> \n");
                   6624: 
1.222     brouard  6625:    cov[1]=1;
                   6626:    /* tj=cptcoveff; */
1.225     brouard  6627:    tj = (int) pow(2,cptcoveff);
1.222     brouard  6628:    if (cptcovn<1) {tj=1;ncodemax[1]=1;}
                   6629:    j1=0;
1.224     brouard  6630:    for(j1=1; j1<=tj;j1++){  /* For each valid combination of covariates or only once*/
1.222     brouard  6631:      if  (cptcovn>0) {
                   6632:        fprintf(ficresprob, "\n#********** Variable "); 
1.225     brouard  6633:        for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresprob, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
1.222     brouard  6634:        fprintf(ficresprob, "**********\n#\n");
                   6635:        fprintf(ficresprobcov, "\n#********** Variable "); 
1.225     brouard  6636:        for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresprobcov, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
1.222     brouard  6637:        fprintf(ficresprobcov, "**********\n#\n");
1.220     brouard  6638:                        
1.222     brouard  6639:        fprintf(ficgp, "\n#********** Variable "); 
1.225     brouard  6640:        for (z1=1; z1<=cptcoveff; z1++) fprintf(ficgp, " V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
1.222     brouard  6641:        fprintf(ficgp, "**********\n#\n");
1.220     brouard  6642:                        
                   6643:                        
1.222     brouard  6644:        fprintf(fichtmcov, "\n<hr  size=\"2\" color=\"#EC5E5E\">********** Variable "); 
1.225     brouard  6645:        for (z1=1; z1<=cptcoveff; z1++) fprintf(fichtm, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
1.222     brouard  6646:        fprintf(fichtmcov, "**********\n<hr size=\"2\" color=\"#EC5E5E\">");
1.220     brouard  6647:                        
1.222     brouard  6648:        fprintf(ficresprobcor, "\n#********** Variable ");    
1.225     brouard  6649:        for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresprobcor, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
1.222     brouard  6650:        fprintf(ficresprobcor, "**********\n#");    
                   6651:        if(invalidvarcomb[j1]){
                   6652:         fprintf(ficgp,"\n#Combination (%d) ignored because no cases \n",j1); 
                   6653:         fprintf(fichtmcov,"\n<h3>Combination (%d) ignored because no cases </h3>\n",j1); 
                   6654:         continue;
                   6655:        }
                   6656:      }
                   6657:      gradg=matrix(1,npar,1,(nlstate)*(nlstate+ndeath));
                   6658:      trgradg=matrix(1,(nlstate)*(nlstate+ndeath),1,npar);
                   6659:      gp=vector(1,(nlstate)*(nlstate+ndeath));
                   6660:      gm=vector(1,(nlstate)*(nlstate+ndeath));
                   6661:      for (age=bage; age<=fage; age ++){ 
                   6662:        cov[2]=age;
                   6663:        if(nagesqr==1)
                   6664:         cov[3]= age*age;
                   6665:        for (k=1; k<=cptcovn;k++) {
                   6666:         cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(j1,k)];
                   6667:         /*cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(j1,Tvar[k])];*//* j1 1 2 3 4
                   6668:                                                                    * 1  1 1 1 1
                   6669:                                                                    * 2  2 1 1 1
                   6670:                                                                    * 3  1 2 1 1
                   6671:                                                                    */
                   6672:         /* nbcode[1][1]=0 nbcode[1][2]=1;*/
                   6673:        }
                   6674:        /* for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2]; */
                   6675:        for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,k)]*cov[2];
                   6676:        for (k=1; k<=cptcovprod;k++)
                   6677:         cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)]*nbcode[Tvard[k][2]][codtabm(ij,k)];
1.220     brouard  6678:                        
                   6679:                        
1.222     brouard  6680:        for(theta=1; theta <=npar; theta++){
                   6681:         for(i=1; i<=npar; i++)
                   6682:           xp[i] = x[i] + (i==theta ?delti[theta]:(double)0);
1.220     brouard  6683:                                
1.222     brouard  6684:         pmij(pmmij,cov,ncovmodel,xp,nlstate);
1.220     brouard  6685:                                
1.222     brouard  6686:         k=0;
                   6687:         for(i=1; i<= (nlstate); i++){
                   6688:           for(j=1; j<=(nlstate+ndeath);j++){
                   6689:             k=k+1;
                   6690:             gp[k]=pmmij[i][j];
                   6691:           }
                   6692:         }
1.220     brouard  6693:                                
1.222     brouard  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);
                   6698:         k=0;
                   6699:         for(i=1; i<=(nlstate); i++){
                   6700:           for(j=1; j<=(nlstate+ndeath);j++){
                   6701:             k=k+1;
                   6702:             gm[k]=pmmij[i][j];
                   6703:           }
                   6704:         }
1.220     brouard  6705:                                
1.222     brouard  6706:         for(i=1; i<= (nlstate)*(nlstate+ndeath); i++) 
                   6707:           gradg[theta][i]=(gp[i]-gm[i])/(double)2./delti[theta];  
                   6708:        }
1.126     brouard  6709: 
1.222     brouard  6710:        for(j=1; j<=(nlstate)*(nlstate+ndeath);j++)
                   6711:         for(theta=1; theta <=npar; theta++)
                   6712:           trgradg[j][theta]=gradg[theta][j];
1.220     brouard  6713:                        
1.222     brouard  6714:        matprod2(dnewm,trgradg,1,(nlstate)*(nlstate+ndeath),1,npar,1,npar,matcov); 
                   6715:        matprod2(doldm,dnewm,1,(nlstate)*(nlstate+ndeath),1,npar,1,(nlstate)*(nlstate+ndeath),gradg);
1.220     brouard  6716:                        
1.222     brouard  6717:        pmij(pmmij,cov,ncovmodel,x,nlstate);
1.220     brouard  6718:                        
1.222     brouard  6719:        k=0;
                   6720:        for(i=1; i<=(nlstate); i++){
                   6721:         for(j=1; j<=(nlstate+ndeath);j++){
                   6722:           k=k+1;
                   6723:           mu[k][(int) age]=pmmij[i][j];
                   6724:         }
                   6725:        }
                   6726:        for(i=1;i<=(nlstate)*(nlstate+ndeath);i++)
                   6727:         for(j=1;j<=(nlstate)*(nlstate+ndeath);j++)
                   6728:           varpij[i][j][(int)age] = doldm[i][j];
1.220     brouard  6729:                        
1.222     brouard  6730:        /*printf("\n%d ",(int)age);
                   6731:         for (i=1; i<=(nlstate)*(nlstate+ndeath);i++){
                   6732:         printf("%e [%e ;%e] ",gm[i],gm[i]-2*sqrt(doldm[i][i]),gm[i]+2*sqrt(doldm[i][i]));
                   6733:         fprintf(ficlog,"%e [%e ;%e] ",gm[i],gm[i]-2*sqrt(doldm[i][i]),gm[i]+2*sqrt(doldm[i][i]));
                   6734:         }*/
1.220     brouard  6735:                        
1.222     brouard  6736:        fprintf(ficresprob,"\n%d ",(int)age);
                   6737:        fprintf(ficresprobcov,"\n%d ",(int)age);
                   6738:        fprintf(ficresprobcor,"\n%d ",(int)age);
1.220     brouard  6739:                        
1.222     brouard  6740:        for (i=1; i<=(nlstate)*(nlstate+ndeath);i++)
                   6741:         fprintf(ficresprob,"%11.3e (%11.3e) ",mu[i][(int) age],sqrt(varpij[i][i][(int)age]));
                   6742:        for (i=1; i<=(nlstate)*(nlstate+ndeath);i++){
                   6743:         fprintf(ficresprobcov,"%11.3e ",mu[i][(int) age]);
                   6744:         fprintf(ficresprobcor,"%11.3e ",mu[i][(int) age]);
                   6745:        }
                   6746:        i=0;
                   6747:        for (k=1; k<=(nlstate);k++){
                   6748:         for (l=1; l<=(nlstate+ndeath);l++){ 
                   6749:           i++;
                   6750:           fprintf(ficresprobcov,"\n%d %d-%d",(int)age,k,l);
                   6751:           fprintf(ficresprobcor,"\n%d %d-%d",(int)age,k,l);
                   6752:           for (j=1; j<=i;j++){
                   6753:             /* printf(" k=%d l=%d i=%d j=%d\n",k,l,i,j);fflush(stdout); */
                   6754:             fprintf(ficresprobcov," %11.3e",varpij[i][j][(int)age]);
                   6755:             fprintf(ficresprobcor," %11.3e",varpij[i][j][(int) age]/sqrt(varpij[i][i][(int) age])/sqrt(varpij[j][j][(int)age]));
                   6756:           }
                   6757:         }
                   6758:        }/* end of loop for state */
                   6759:      } /* end of loop for age */
                   6760:      free_vector(gp,1,(nlstate+ndeath)*(nlstate+ndeath));
                   6761:      free_vector(gm,1,(nlstate+ndeath)*(nlstate+ndeath));
                   6762:      free_matrix(trgradg,1,(nlstate+ndeath)*(nlstate+ndeath),1,npar);
                   6763:      free_matrix(gradg,1,(nlstate+ndeath)*(nlstate+ndeath),1,npar);
                   6764:     
                   6765:      /* Confidence intervalle of pij  */
                   6766:      /*
                   6767:        fprintf(ficgp,"\nunset parametric;unset label");
                   6768:        fprintf(ficgp,"\nset log y;unset log x; set xlabel \"Age\";set ylabel \"probability (year-1)\"");
                   6769:        fprintf(ficgp,"\nset ter png small\nset size 0.65,0.65");
                   6770:        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);
                   6771:        fprintf(fichtm,"\n<br><img src=\"pijgr%s.png\"> ",optionfilefiname);
                   6772:        fprintf(ficgp,"\nset out \"pijgr%s.png\"",optionfilefiname);
                   6773:        fprintf(ficgp,"\nplot \"%s\" every :::%d::%d u 1:2 \"\%%lf",k1,k2,xfilevarprob);
                   6774:      */
                   6775:                
                   6776:      /* Drawing ellipsoids of confidence of two variables p(k1-l1,k2-l2)*/
                   6777:      first1=1;first2=2;
                   6778:      for (k2=1; k2<=(nlstate);k2++){
                   6779:        for (l2=1; l2<=(nlstate+ndeath);l2++){ 
                   6780:         if(l2==k2) continue;
                   6781:         j=(k2-1)*(nlstate+ndeath)+l2;
                   6782:         for (k1=1; k1<=(nlstate);k1++){
                   6783:           for (l1=1; l1<=(nlstate+ndeath);l1++){ 
                   6784:             if(l1==k1) continue;
                   6785:             i=(k1-1)*(nlstate+ndeath)+l1;
                   6786:             if(i<=j) continue;
                   6787:             for (age=bage; age<=fage; age ++){ 
                   6788:               if ((int)age %5==0){
                   6789:                 v1=varpij[i][i][(int)age]/stepm*YEARM/stepm*YEARM;
                   6790:                 v2=varpij[j][j][(int)age]/stepm*YEARM/stepm*YEARM;
                   6791:                 cv12=varpij[i][j][(int)age]/stepm*YEARM/stepm*YEARM;
                   6792:                 mu1=mu[i][(int) age]/stepm*YEARM ;
                   6793:                 mu2=mu[j][(int) age]/stepm*YEARM;
                   6794:                 c12=cv12/sqrt(v1*v2);
                   6795:                 /* Computing eigen value of matrix of covariance */
                   6796:                 lc1=((v1+v2)+sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
                   6797:                 lc2=((v1+v2)-sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
                   6798:                 if ((lc2 <0) || (lc1 <0) ){
                   6799:                   if(first2==1){
                   6800:                     first1=0;
                   6801:                     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);
                   6802:                   }
                   6803:                   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);
                   6804:                   /* lc1=fabs(lc1); */ /* If we want to have them positive */
                   6805:                   /* lc2=fabs(lc2); */
                   6806:                 }
1.220     brouard  6807:                                                                
1.222     brouard  6808:                 /* Eigen vectors */
1.280     brouard  6809:                 if(1+(v1-lc1)*(v1-lc1)/cv12/cv12 <1.e-5){
                   6810:                   printf(" Error sqrt of a negative number: %lf\n",1+(v1-lc1)*(v1-lc1)/cv12/cv12);
                   6811:                   fprintf(ficlog," Error sqrt of a negative number: %lf\n",1+(v1-lc1)*(v1-lc1)/cv12/cv12);
                   6812:                   v11=(1./sqrt(fabs(1+(v1-lc1)*(v1-lc1)/cv12/cv12)));
                   6813:                 }else
                   6814:                   v11=(1./sqrt(1+(v1-lc1)*(v1-lc1)/cv12/cv12));
1.222     brouard  6815:                 /*v21=sqrt(1.-v11*v11); *//* error */
                   6816:                 v21=(lc1-v1)/cv12*v11;
                   6817:                 v12=-v21;
                   6818:                 v22=v11;
                   6819:                 tnalp=v21/v11;
                   6820:                 if(first1==1){
                   6821:                   first1=0;
                   6822:                   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);
                   6823:                 }
                   6824:                 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);
                   6825:                 /*printf(fignu*/
                   6826:                 /* mu1+ v11*lc1*cost + v12*lc2*sin(t) */
                   6827:                 /* mu2+ v21*lc1*cost + v22*lc2*sin(t) */
                   6828:                 if(first==1){
                   6829:                   first=0;
                   6830:                   fprintf(ficgp,"\n# Ellipsoids of confidence\n#\n");
                   6831:                   fprintf(ficgp,"\nset parametric;unset label");
                   6832:                   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);
                   6833:                   fprintf(ficgp,"\nset ter svg size 640, 480");
1.266     brouard  6834:                   fprintf(fichtmcov,"\n<p><br>Ellipsoids of confidence cov(p%1d%1d,p%1d%1d) expressed in year<sup>-1</sup>\
1.220     brouard  6835:  :<a href=\"%s_%d%1d%1d-%1d%1d.svg\">                                                                                                                                          \
1.201     brouard  6836: %s_%d%1d%1d-%1d%1d.svg</A>, ",k1,l1,k2,l2,\
1.222     brouard  6837:                           subdirf2(optionfilefiname,"VARPIJGR_"), j1,k1,l1,k2,l2,      \
                   6838:                           subdirf2(optionfilefiname,"VARPIJGR_"), j1,k1,l1,k2,l2);
                   6839:                   fprintf(fichtmcov,"\n<br><img src=\"%s_%d%1d%1d-%1d%1d.svg\"> ",subdirf2(optionfilefiname,"VARPIJGR_"), j1,k1,l1,k2,l2);
                   6840:                   fprintf(fichtmcov,"\n<br> Correlation at age %d (%.3f),",(int) age, c12);
                   6841:                   fprintf(ficgp,"\nset out \"%s_%d%1d%1d-%1d%1d.svg\"",subdirf2(optionfilefiname,"VARPIJGR_"), j1,k1,l1,k2,l2);
                   6842:                   fprintf(ficgp,"\nset label \"%d\" at %11.3e,%11.3e center",(int) age, mu1,mu2);
                   6843:                   fprintf(ficgp,"\n# Age %d, p%1d%1d - p%1d%1d",(int) age, k1,l1,k2,l2);
                   6844:                   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  6845:                           mu1,std,v11,sqrt(fabs(lc1)),v12,sqrt(fabs(lc2)), \
                   6846:                           mu2,std,v21,sqrt(fabs(lc1)),v22,sqrt(fabs(lc2))); /* For gnuplot only */
1.222     brouard  6847:                 }else{
                   6848:                   first=0;
                   6849:                   fprintf(fichtmcov," %d (%.3f),",(int) age, c12);
                   6850:                   fprintf(ficgp,"\n# Age %d, p%1d%1d - p%1d%1d",(int) age, k1,l1,k2,l2);
                   6851:                   fprintf(ficgp,"\nset label \"%d\" at %11.3e,%11.3e center",(int) age, mu1,mu2);
                   6852:                   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  6853:                           mu1,std,v11,sqrt(lc1),v12,sqrt(fabs(lc2)),   \
                   6854:                           mu2,std,v21,sqrt(lc1),v22,sqrt(fabs(lc2)));
1.222     brouard  6855:                 }/* if first */
                   6856:               } /* age mod 5 */
                   6857:             } /* end loop age */
                   6858:             fprintf(ficgp,"\nset out;\nset out \"%s_%d%1d%1d-%1d%1d.svg\";replot;set out;",subdirf2(optionfilefiname,"VARPIJGR_"), j1,k1,l1,k2,l2);
                   6859:             first=1;
                   6860:           } /*l12 */
                   6861:         } /* k12 */
                   6862:        } /*l1 */
                   6863:      }/* k1 */
                   6864:    }  /* loop on combination of covariates j1 */
                   6865:    free_ma3x(varpij,1,nlstate,1,nlstate+ndeath,(int) bage, (int)fage);
                   6866:    free_matrix(mu,1,(nlstate+ndeath)*(nlstate+ndeath),(int) bage, (int)fage);
                   6867:    free_matrix(doldm,1,(nlstate)*(nlstate+ndeath),1,(nlstate)*(nlstate+ndeath));
                   6868:    free_matrix(dnewm,1,(nlstate)*(nlstate+ndeath),1,npar);
                   6869:    free_vector(xp,1,npar);
                   6870:    fclose(ficresprob);
                   6871:    fclose(ficresprobcov);
                   6872:    fclose(ficresprobcor);
                   6873:    fflush(ficgp);
                   6874:    fflush(fichtmcov);
                   6875:  }
1.126     brouard  6876: 
                   6877: 
                   6878: /******************* Printing html file ***********/
1.201     brouard  6879: void printinghtml(char fileresu[], char title[], char datafile[], int firstpass, \
1.126     brouard  6880:                  int lastpass, int stepm, int weightopt, char model[],\
                   6881:                  int imx,int jmin, int jmax, double jmeanint,char rfileres[],\
1.296     brouard  6882:                  int popforecast, int mobilav, int prevfcast, int mobilavproj, int prevbcast, int estepm , \
                   6883:                  double jprev1, double mprev1,double anprev1, double dateprev1, double dateprojd, double dateback1, \
                   6884:                  double jprev2, double mprev2,double anprev2, double dateprev2, double dateprojf, double dateback2){
1.237     brouard  6885:   int jj1, k1, i1, cpt, k4, nres;
1.126     brouard  6886: 
                   6887:    fprintf(fichtm,"<ul><li><a href='#firstorder'>Result files (first order: no variance)</a>\n \
                   6888:    <li><a href='#secondorder'>Result files (second order (variance)</a>\n \
                   6889: </ul>");
1.237     brouard  6890:    fprintf(fichtm,"<ul><li> model=1+age+%s\n \
                   6891: </ul>", model);
1.214     brouard  6892:    fprintf(fichtm,"<ul><li><h4><a name='firstorder'>Result files (first order: no variance)</a></h4>\n");
                   6893:    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",
                   6894:           jprev1, mprev1,anprev1,jprev2, mprev2,anprev2,subdirfext3(optionfilefiname,"PHTMFR_",".htm"),subdirfext3(optionfilefiname,"PHTMFR_",".htm"));
                   6895:    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  6896:           jprev1, mprev1,anprev1,jprev2, mprev2,anprev2,subdirfext3(optionfilefiname,"PHTM_",".htm"),subdirfext3(optionfilefiname,"PHTM_",".htm"));
                   6897:    fprintf(fichtm,",  <a href=\"%s\">%s</a> (text file) <br>\n",subdirf2(fileresu,"P_"),subdirf2(fileresu,"P_"));
1.126     brouard  6898:    fprintf(fichtm,"\
                   6899:  - Estimated transition probabilities over %d (stepm) months: <a href=\"%s\">%s</a><br>\n ",
1.201     brouard  6900:           stepm,subdirf2(fileresu,"PIJ_"),subdirf2(fileresu,"PIJ_"));
1.126     brouard  6901:    fprintf(fichtm,"\
1.217     brouard  6902:  - Estimated back transition probabilities over %d (stepm) months: <a href=\"%s\">%s</a><br>\n ",
                   6903:           stepm,subdirf2(fileresu,"PIJB_"),subdirf2(fileresu,"PIJB_"));
                   6904:    fprintf(fichtm,"\
1.288     brouard  6905:  - Period (forward) prevalence in each health state: <a href=\"%s\">%s</a> <br>\n",
1.201     brouard  6906:           subdirf2(fileresu,"PL_"),subdirf2(fileresu,"PL_"));
1.126     brouard  6907:    fprintf(fichtm,"\
1.288     brouard  6908:  - Backward prevalence in each health state: <a href=\"%s\">%s</a> <br>\n",
1.217     brouard  6909:           subdirf2(fileresu,"PLB_"),subdirf2(fileresu,"PLB_"));
                   6910:    fprintf(fichtm,"\
1.211     brouard  6911:  - (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  6912:    <a href=\"%s\">%s</a> <br>\n",
1.201     brouard  6913:           estepm,subdirf2(fileresu,"E_"),subdirf2(fileresu,"E_"));
1.211     brouard  6914:    if(prevfcast==1){
                   6915:      fprintf(fichtm,"\
                   6916:  - Prevalence projections by age and states:                           \
1.201     brouard  6917:    <a href=\"%s\">%s</a> <br>\n</li>", subdirf2(fileresu,"F_"),subdirf2(fileresu,"F_"));
1.211     brouard  6918:    }
1.126     brouard  6919: 
                   6920: 
1.225     brouard  6921:    m=pow(2,cptcoveff);
1.222     brouard  6922:    if (cptcovn < 1) {m=1;ncodemax[1]=1;}
1.126     brouard  6923: 
1.264     brouard  6924:    fprintf(fichtm," \n<ul><li><b>Graphs</b></li><p>");
                   6925: 
                   6926:    jj1=0;
                   6927: 
                   6928:    fprintf(fichtm," \n<ul>");
                   6929:    for(nres=1; nres <= nresult; nres++) /* For each resultline */
                   6930:    for(k1=1; k1<=m;k1++){ /* For each combination of covariate */
                   6931:      if(m != 1 && TKresult[nres]!= k1)
                   6932:        continue;
                   6933:      jj1++;
                   6934:      if (cptcovn > 0) {
                   6935:        fprintf(fichtm,"\n<li><a  size=\"1\" color=\"#EC5E5E\" href=\"#rescov");
                   6936:        for (cpt=1; cpt<=cptcoveff;cpt++){ 
                   6937:         fprintf(fichtm,"_V%d=%d_",Tvresult[nres][cpt],(int)Tresult[nres][cpt]);
                   6938:        }
                   6939:        for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
                   6940:         fprintf(fichtm,"_V%d=%f_",Tvqresult[nres][k4],Tqresult[nres][k4]);
                   6941:        }
                   6942:        fprintf(fichtm,"\">");
                   6943:        
                   6944:        /* if(nqfveff+nqtveff 0) */ /* Test to be done */
                   6945:        fprintf(fichtm,"************ Results for covariates");
                   6946:        for (cpt=1; cpt<=cptcoveff;cpt++){ 
                   6947:         fprintf(fichtm," V%d=%d ",Tvresult[nres][cpt],(int)Tresult[nres][cpt]);
                   6948:        }
                   6949:        for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
                   6950:         fprintf(fichtm," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
                   6951:        }
                   6952:        if(invalidvarcomb[k1]){
                   6953:         fprintf(fichtm," Warning Combination (%d) ignored because no cases ",k1); 
                   6954:         continue;
                   6955:        }
                   6956:        fprintf(fichtm,"</a></li>");
                   6957:      } /* cptcovn >0 */
                   6958:    }
                   6959:      fprintf(fichtm," \n</ul>");
                   6960: 
1.222     brouard  6961:    jj1=0;
1.237     brouard  6962: 
                   6963:    for(nres=1; nres <= nresult; nres++) /* For each resultline */
1.241     brouard  6964:    for(k1=1; k1<=m;k1++){ /* For each combination of covariate */
1.253     brouard  6965:      if(m != 1 && TKresult[nres]!= k1)
1.237     brouard  6966:        continue;
1.220     brouard  6967: 
1.222     brouard  6968:      /* for(i1=1; i1<=ncodemax[k1];i1++){ */
                   6969:      jj1++;
                   6970:      if (cptcovn > 0) {
1.264     brouard  6971:        fprintf(fichtm,"\n<p><a name=\"rescov");
                   6972:        for (cpt=1; cpt<=cptcoveff;cpt++){ 
                   6973:         fprintf(fichtm,"_V%d=%d_",Tvresult[nres][cpt],(int)Tresult[nres][cpt]);
                   6974:        }
                   6975:        for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
                   6976:         fprintf(fichtm,"_V%d=%f_",Tvqresult[nres][k4],Tqresult[nres][k4]);
                   6977:        }
                   6978:        fprintf(fichtm,"\"</a>");
                   6979:  
1.222     brouard  6980:        fprintf(fichtm,"<hr  size=\"2\" color=\"#EC5E5E\">************ Results for covariates");
1.225     brouard  6981:        for (cpt=1; cpt<=cptcoveff;cpt++){ 
1.237     brouard  6982:         fprintf(fichtm," V%d=%d ",Tvresult[nres][cpt],(int)Tresult[nres][cpt]);
                   6983:         printf(" V%d=%d ",Tvresult[nres][cpt],Tresult[nres][cpt]);fflush(stdout);
                   6984:         /* fprintf(fichtm," V%d=%d ",Tvaraff[cpt],nbcode[Tvaraff[cpt]][codtabm(jj1,cpt)]); */
                   6985:         /* printf(" V%d=%d ",Tvaraff[cpt],nbcode[Tvaraff[cpt]][codtabm(jj1,cpt)]);fflush(stdout); */
1.222     brouard  6986:        }
1.237     brouard  6987:        for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
                   6988:        fprintf(fichtm," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
                   6989:        printf(" V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);fflush(stdout);
                   6990:       }
                   6991:        
1.230     brouard  6992:        /* if(nqfveff+nqtveff 0) */ /* Test to be done */
1.222     brouard  6993:        fprintf(fichtm," ************\n<hr size=\"2\" color=\"#EC5E5E\">");
                   6994:        if(invalidvarcomb[k1]){
                   6995:         fprintf(fichtm,"\n<h3>Combination (%d) ignored because no cases </h3>\n",k1); 
                   6996:         printf("\nCombination (%d) ignored because no cases \n",k1); 
                   6997:         continue;
                   6998:        }
                   6999:      }
                   7000:      /* aij, bij */
1.259     brouard  7001:      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  7002: <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  7003:      /* Pij */
1.241     brouard  7004:      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> \
                   7005: <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  7006:      /* Quasi-incidences */
                   7007:      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  7008:  before but expressed in per year i.e. quasi incidences if stepm is small and probabilities too, \
1.211     brouard  7009:  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  7010: 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> \
                   7011: <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  7012:      /* Survival functions (period) in state j */
                   7013:      for(cpt=1; cpt<=nlstate;cpt++){
1.292     brouard  7014:        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  7015: <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  7016:      }
                   7017:      /* State specific survival functions (period) */
                   7018:      for(cpt=1; cpt<=nlstate;cpt++){
1.292     brouard  7019:        fprintf(fichtm,"<br>\n- Survival functions in state %d and in any other live state (total).\
                   7020:  And probability to be observed in various states (up to %d) being in state %d at different ages.      \
1.283     brouard  7021:  <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  7022:      }
1.288     brouard  7023:      /* Period (forward stable) prevalence in each health state */
1.222     brouard  7024:      for(cpt=1; cpt<=nlstate;cpt++){
1.264     brouard  7025:        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> \
                   7026: <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  7027:      }
1.296     brouard  7028:      if(prevbcast==1){
1.288     brouard  7029:        /* Backward prevalence in each health state */
1.222     brouard  7030:        for(cpt=1; cpt<=nlstate;cpt++){
1.264     brouard  7031:         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  7032: <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  7033:        }
1.217     brouard  7034:      }
1.222     brouard  7035:      if(prevfcast==1){
1.288     brouard  7036:        /* Projection of prevalence up to period (forward stable) prevalence in each health state */
1.222     brouard  7037:        for(cpt=1; cpt<=nlstate;cpt++){
1.288     brouard  7038:         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  7039: <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  7040:        }
                   7041:      }
1.296     brouard  7042:      if(prevbcast==1){
1.268     brouard  7043:       /* Back projection of prevalence up to stable (mixed) back-prevalence in each health state */
                   7044:        for(cpt=1; cpt<=nlstate;cpt++){
1.273     brouard  7045:         fprintf(fichtm,"<br>\n- Back projection of cross-sectional prevalence (estimated with cases observed from %.1f to %.1f and mobil_average=%d), \
                   7046:  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 \
                   7047:  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) \
                   7048: with weights corresponding to observed prevalence at different ages. <a href=\"%s_%d-%d-%d.svg\">%s_%d-%d-%d.svg</a><br> \
                   7049:  <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  7050:        }
                   7051:      }
1.220     brouard  7052:         
1.222     brouard  7053:      for(cpt=1; cpt<=nlstate;cpt++) {
1.241     brouard  7054:        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> \
                   7055: <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  7056:      }
                   7057:      /* } /\* end i1 *\/ */
                   7058:    }/* End k1 */
                   7059:    fprintf(fichtm,"</ul>");
1.126     brouard  7060: 
1.222     brouard  7061:    fprintf(fichtm,"\
1.126     brouard  7062: \n<br><li><h4> <a name='secondorder'>Result files (second order: variances)</a></h4>\n\
1.193     brouard  7063:  - Parameter file with estimated parameters and covariance matrix: <a href=\"%s\">%s</a> <br> \
1.203     brouard  7064:  - 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  7065: But because parameters are usually highly correlated (a higher incidence of disability \
                   7066: and a higher incidence of recovery can give very close observed transition) it might \
                   7067: be very useful to look not only at linear confidence intervals estimated from the \
                   7068: variances but at the covariance matrix. And instead of looking at the estimated coefficients \
                   7069: (parameters) of the logistic regression, it might be more meaningful to visualize the \
                   7070: covariance matrix of the one-step probabilities. \
                   7071: See page 'Matrix of variance-covariance of one-step probabilities' below. \n", rfileres,rfileres);
1.126     brouard  7072: 
1.222     brouard  7073:    fprintf(fichtm," - Standard deviation of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
                   7074:           subdirf2(fileresu,"PROB_"),subdirf2(fileresu,"PROB_"));
                   7075:    fprintf(fichtm,"\
1.126     brouard  7076:  - Variance-covariance of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
1.222     brouard  7077:           subdirf2(fileresu,"PROBCOV_"),subdirf2(fileresu,"PROBCOV_"));
1.126     brouard  7078: 
1.222     brouard  7079:    fprintf(fichtm,"\
1.126     brouard  7080:  - Correlation matrix of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
1.222     brouard  7081:           subdirf2(fileresu,"PROBCOR_"),subdirf2(fileresu,"PROBCOR_"));
                   7082:    fprintf(fichtm,"\
1.126     brouard  7083:  - 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): \
                   7084:    <a href=\"%s\">%s</a> <br>\n</li>",
1.201     brouard  7085:           estepm,subdirf2(fileresu,"CVE_"),subdirf2(fileresu,"CVE_"));
1.222     brouard  7086:    fprintf(fichtm,"\
1.126     brouard  7087:  - (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): \
                   7088:    <a href=\"%s\">%s</a> <br>\n</li>",
1.201     brouard  7089:           estepm,subdirf2(fileresu,"STDE_"),subdirf2(fileresu,"STDE_"));
1.222     brouard  7090:    fprintf(fichtm,"\
1.288     brouard  7091:  - 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  7092:           estepm, subdirf2(fileresu,"V_"),subdirf2(fileresu,"V_"));
                   7093:    fprintf(fichtm,"\
1.128     brouard  7094:  - 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  7095:           estepm, subdirf2(fileresu,"T_"),subdirf2(fileresu,"T_"));
                   7096:    fprintf(fichtm,"\
1.288     brouard  7097:  - Standard deviation of forward (period) prevalences: <a href=\"%s\">%s</a> <br>\n",\
1.222     brouard  7098:           subdirf2(fileresu,"VPL_"),subdirf2(fileresu,"VPL_"));
1.126     brouard  7099: 
                   7100: /*  if(popforecast==1) fprintf(fichtm,"\n */
                   7101: /*  - Prevalences forecasting: <a href=\"f%s\">f%s</a> <br>\n */
                   7102: /*  - Population forecasting (if popforecast=1): <a href=\"pop%s\">pop%s</a> <br>\n */
                   7103: /*     <br>",fileres,fileres,fileres,fileres); */
                   7104: /*  else  */
                   7105: /*    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  7106:    fflush(fichtm);
                   7107:    fprintf(fichtm," <ul><li><b>Graphs</b></li><p>");
1.126     brouard  7108: 
1.225     brouard  7109:    m=pow(2,cptcoveff);
1.222     brouard  7110:    if (cptcovn < 1) {m=1;ncodemax[1]=1;}
1.126     brouard  7111: 
1.222     brouard  7112:    jj1=0;
1.237     brouard  7113: 
1.241     brouard  7114:    for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.222     brouard  7115:    for(k1=1; k1<=m;k1++){
1.253     brouard  7116:      if(m != 1 && TKresult[nres]!= k1)
1.237     brouard  7117:        continue;
1.222     brouard  7118:      /* for(i1=1; i1<=ncodemax[k1];i1++){ */
                   7119:      jj1++;
1.126     brouard  7120:      if (cptcovn > 0) {
                   7121:        fprintf(fichtm,"<hr  size=\"2\" color=\"#EC5E5E\">************ Results for covariates");
1.225     brouard  7122:        for (cpt=1; cpt<=cptcoveff;cpt++)  /**< cptcoveff number of variables */
1.237     brouard  7123:         fprintf(fichtm," V%d=%d ",Tvresult[nres][cpt],Tresult[nres][cpt]);
                   7124:         /* fprintf(fichtm," V%d=%d ",Tvaraff[cpt],nbcode[Tvaraff[cpt]][codtabm(jj1,cpt)]); */
                   7125:        for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
                   7126:        fprintf(fichtm," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
                   7127:       }
                   7128: 
1.126     brouard  7129:        fprintf(fichtm," ************\n<hr size=\"2\" color=\"#EC5E5E\">");
1.220     brouard  7130: 
1.222     brouard  7131:        if(invalidvarcomb[k1]){
                   7132:         fprintf(fichtm,"\n<h4>Combination (%d) ignored because no cases </h4>\n",k1); 
                   7133:         continue;
                   7134:        }
1.126     brouard  7135:      }
                   7136:      for(cpt=1; cpt<=nlstate;cpt++) {
1.258     brouard  7137:        fprintf(fichtm,"\n<br>- Observed (cross-sectional with mov_average=%d) and period (incidence based) \
1.241     brouard  7138: 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  7139: <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  7140:      }
                   7141:      fprintf(fichtm,"\n<br>- Total life expectancy by age and \
1.128     brouard  7142: health expectancies in states (1) and (2). If popbased=1 the smooth (due to the model) \
                   7143: true period expectancies (those weighted with period prevalences are also\
                   7144:  drawn in addition to the population based expectancies computed using\
1.241     brouard  7145:  observed and cahotic prevalences:  <a href=\"%s_%d-%d.svg\">%s_%d-%d.svg</a>\n<br>\
                   7146: <img src=\"%s_%d-%d.svg\">",subdirf2(optionfilefiname,"E_"),k1,nres,subdirf2(optionfilefiname,"E_"),k1,nres,subdirf2(optionfilefiname,"E_"),k1,nres);
1.222     brouard  7147:      /* } /\* end i1 *\/ */
                   7148:    }/* End k1 */
1.241     brouard  7149:   }/* End nres */
1.222     brouard  7150:    fprintf(fichtm,"</ul>");
                   7151:    fflush(fichtm);
1.126     brouard  7152: }
                   7153: 
                   7154: /******************* Gnuplot file **************/
1.296     brouard  7155: 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  7156: 
                   7157:   char dirfileres[132],optfileres[132];
1.264     brouard  7158:   char gplotcondition[132], gplotlabel[132];
1.237     brouard  7159:   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  7160:   int lv=0, vlv=0, kl=0;
1.130     brouard  7161:   int ng=0;
1.201     brouard  7162:   int vpopbased;
1.223     brouard  7163:   int ioffset; /* variable offset for columns */
1.270     brouard  7164:   int iyearc=1; /* variable column for year of projection  */
                   7165:   int iagec=1; /* variable column for age of projection  */
1.235     brouard  7166:   int nres=0; /* Index of resultline */
1.266     brouard  7167:   int istart=1; /* For starting graphs in projections */
1.219     brouard  7168: 
1.126     brouard  7169: /*   if((ficgp=fopen(optionfilegnuplot,"a"))==NULL) { */
                   7170: /*     printf("Problem with file %s",optionfilegnuplot); */
                   7171: /*     fprintf(ficlog,"Problem with file %s",optionfilegnuplot); */
                   7172: /*   } */
                   7173: 
                   7174:   /*#ifdef windows */
                   7175:   fprintf(ficgp,"cd \"%s\" \n",pathc);
1.223     brouard  7176:   /*#endif */
1.225     brouard  7177:   m=pow(2,cptcoveff);
1.126     brouard  7178: 
1.274     brouard  7179:   /* diagram of the model */
                   7180:   fprintf(ficgp,"\n#Diagram of the model \n");
                   7181:   fprintf(ficgp,"\ndelta=0.03;delta2=0.07;unset arrow;\n");
                   7182:   fprintf(ficgp,"yoff=(%d > 2? 0:1);\n",nlstate);
                   7183:   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);
                   7184: 
                   7185:   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);
                   7186:   fprintf(ficgp,"\n#show arrow\nunset label\n");
                   7187:   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);
                   7188:   fprintf(ficgp,"\nset label %d+1 sprintf(\"State %%d\",%d+1) center at 0.,0.  font \"helvetica, 16\" tc rgbcolor \"red\"\n",nlstate,nlstate);
                   7189:   fprintf(ficgp,"\n#show label\nunset border;unset xtics; unset ytics;\n");
                   7190:   fprintf(ficgp,"\n\nset ter svg size 640, 480;set out \"%s_.svg\" \n",subdirf2(optionfilefiname,"D_"));
                   7191:   fprintf(ficgp,"unset log y; plot [-1.2:1.2][yoff-1.2:1.2] 1/0 not; set out;reset;\n");
                   7192: 
1.202     brouard  7193:   /* Contribution to likelihood */
                   7194:   /* Plot the probability implied in the likelihood */
1.223     brouard  7195:   fprintf(ficgp,"\n# Contributions to the Likelihood, mle >=1. For mle=4 no interpolation, pure matrix products.\n#\n");
                   7196:   fprintf(ficgp,"\n set log y; unset log x;set xlabel \"Age\"; set ylabel \"Likelihood (-2Log(L))\";");
                   7197:   /* fprintf(ficgp,"\nset ter svg size 640, 480"); */ /* Too big for svg */
                   7198:   fprintf(ficgp,"\nset ter pngcairo size 640, 480");
1.204     brouard  7199: /* nice for mle=4 plot by number of matrix products.
1.202     brouard  7200:    replot  "rrtest1/toto.txt" u 2:($4 == 1 && $5==2 ? $9 : 1/0):5 t "p12" with point lc 1 */
                   7201: /* replot exp(p1+p2*x)/(1+exp(p1+p2*x)+exp(p3+p4*x)+exp(p5+p6*x)) t "p12(x)"  */
1.223     brouard  7202:   /* fprintf(ficgp,"\nset out \"%s.svg\";",subdirf2(optionfilefiname,"ILK_")); */
                   7203:   fprintf(ficgp,"\nset out \"%s-dest.png\";",subdirf2(optionfilefiname,"ILK_"));
                   7204:   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));
                   7205:   fprintf(ficgp,"\nset out \"%s-ori.png\";",subdirf2(optionfilefiname,"ILK_"));
                   7206:   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));
                   7207:   for (i=1; i<= nlstate ; i ++) {
                   7208:     fprintf(ficgp,"\nset out \"%s-p%dj.png\";set ylabel \"Probability for each individual/wave\";",subdirf2(optionfilefiname,"ILK_"),i);
                   7209:     fprintf(ficgp,"unset log;\n# plot weighted, mean weight should have point size of 0.5\n plot  \"%s\"",subdirf(fileresilk));
                   7210:     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);
                   7211:     for (j=2; j<= nlstate+ndeath ; j ++) {
                   7212:       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);
                   7213:     }
                   7214:     fprintf(ficgp,";\nset out; unset ylabel;\n"); 
                   7215:   }
                   7216:   /* 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 */               
                   7217:   /* fprintf(ficgp,"\nset log y;plot  \"%s\" u 2:(-$11):3 t \"All sample, all transitions\" with dots lc variable",subdirf(fileresilk)); */
                   7218:   /* fprintf(ficgp,"\nreplot  \"%s\" u 2:($3 <= 3 ? -$11 : 1/0):3 t \"First 3 individuals\" with line lc variable", subdirf(fileresilk)); */
                   7219:   fprintf(ficgp,"\nset out;unset log\n");
                   7220:   /* fprintf(ficgp,"\nset out \"%s.svg\"; replot; set out; # bug gnuplot",subdirf2(optionfilefiname,"ILK_")); */
1.202     brouard  7221: 
1.126     brouard  7222:   strcpy(dirfileres,optionfilefiname);
                   7223:   strcpy(optfileres,"vpl");
1.223     brouard  7224:   /* 1eme*/
1.238     brouard  7225:   for (cpt=1; cpt<= nlstate ; cpt ++){ /* For each live state */
                   7226:     for (k1=1; k1<= m ; k1 ++){ /* For each valid combination of covariate */
1.236     brouard  7227:       for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.238     brouard  7228:        /* plot [100000000000000000000:-100000000000000000000] "mysbiaspar/vplrmysbiaspar.txt to check */
1.253     brouard  7229:        if(m != 1 && TKresult[nres]!= k1)
1.238     brouard  7230:          continue;
                   7231:        /* We are interested in selected combination by the resultline */
1.246     brouard  7232:        /* printf("\n# 1st: Period (stable) prevalence with CI: 'VPL_' files and live state =%d ", cpt); */
1.288     brouard  7233:        fprintf(ficgp,"\n# 1st: Forward (stable period) prevalence with CI: 'VPL_' files  and live state =%d ", cpt);
1.264     brouard  7234:        strcpy(gplotlabel,"(");
1.238     brouard  7235:        for (k=1; k<=cptcoveff; k++){    /* For each covariate k get corresponding value lv for combination k1 */
                   7236:          lv= decodtabm(k1,k,cptcoveff); /* Should be the value of the covariate corresponding to k1 combination */
                   7237:          /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   7238:          /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   7239:          /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
                   7240:          vlv= nbcode[Tvaraff[k]][lv]; /* vlv is the value of the covariate lv, 0 or 1 */
                   7241:          /* For each combination of covariate k1 (V1=1, V3=0), we printed the current covariate k and its value vlv */
1.246     brouard  7242:          /* printf(" V%d=%d ",Tvaraff[k],vlv); */
1.238     brouard  7243:          fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv);
1.264     brouard  7244:          sprintf(gplotlabel+strlen(gplotlabel)," V%d=%d ",Tvaraff[k],vlv);
1.238     brouard  7245:        }
                   7246:        for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
1.246     brouard  7247:          /* printf(" V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]); */
1.238     brouard  7248:          fprintf(ficgp," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
1.264     brouard  7249:          sprintf(gplotlabel+strlen(gplotlabel)," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
                   7250:        }
                   7251:        strcpy(gplotlabel+strlen(gplotlabel),")");
1.246     brouard  7252:        /* printf("\n#\n"); */
1.238     brouard  7253:        fprintf(ficgp,"\n#\n");
                   7254:        if(invalidvarcomb[k1]){
1.260     brouard  7255:           /*k1=k1-1;*/ /* To be checked */
1.238     brouard  7256:          fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   7257:          continue;
                   7258:        }
1.235     brouard  7259:       
1.241     brouard  7260:        fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" \n",subdirf2(optionfilefiname,"V_"),cpt,k1,nres);
                   7261:        fprintf(ficgp,"\n#set out \"V_%s_%d-%d-%d.svg\" \n",optionfilefiname,cpt,k1,nres);
1.276     brouard  7262:        /* fprintf(ficgp,"set label \"Alive state %d %s\" at graph 0.98,0.5 center rotate font \"Helvetica,12\"\n",cpt,gplotlabel); */
                   7263:        fprintf(ficgp,"set title \"Alive state %d %s\" font \"Helvetica,12\"\n",cpt,gplotlabel);
1.260     brouard  7264:        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);
                   7265:        /* 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); */
                   7266:       /* k1-1 error should be nres-1*/
1.238     brouard  7267:        for (i=1; i<= nlstate ; i ++) {
                   7268:          if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
                   7269:          else        fprintf(ficgp," %%*lf (%%*lf)");
                   7270:        }
1.288     brouard  7271:        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  7272:        for (i=1; i<= nlstate ; i ++) {
                   7273:          if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
                   7274:          else fprintf(ficgp," %%*lf (%%*lf)");
                   7275:        } 
1.260     brouard  7276:        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  7277:        for (i=1; i<= nlstate ; i ++) {
                   7278:          if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
                   7279:          else fprintf(ficgp," %%*lf (%%*lf)");
                   7280:        }  
1.265     brouard  7281:        /* 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)); */
                   7282:        
                   7283:        fprintf(ficgp,"\" t\"\" w l lt 1,\"%s\" u 1:((",subdirf2(fileresu,"P_"));
                   7284:         if(cptcoveff ==0){
1.271     brouard  7285:          fprintf(ficgp,"$%d)) t 'Observed prevalence in state %d' with line lt 3",      2+3*(cpt-1),  cpt );
1.265     brouard  7286:        }else{
                   7287:          kl=0;
                   7288:          for (k=1; k<=cptcoveff; k++){    /* For each combination of covariate  */
                   7289:            lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate value corresponding to k1 combination and kth covariate */
                   7290:            /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   7291:            /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   7292:            /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
                   7293:            vlv= nbcode[Tvaraff[k]][lv];
                   7294:            kl++;
                   7295:            /* 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 *\/ */
                   7296:            /*6+(cpt-1)*(nlstate+1)+1+(i-1)+(nlstate+1)*nlstate; 6+(1-1)*(2+1)+1+(1-1) +(2+1)*2=13 */ 
                   7297:            /*6+1+(i-1)+(nlstate+1)*nlstate; 6+1+(1-1) +(2+1)*2=13 */ 
                   7298:            /* ''  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*/
                   7299:            if(k==cptcoveff){
                   7300:              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], \
                   7301:                      2+cptcoveff*2+3*(cpt-1),  cpt );  /* 4 or 6 ?*/
                   7302:            }else{
                   7303:              fprintf(ficgp,"$%d==%d && $%d==%d && ",kl+1, Tvaraff[k],kl+1+1,nbcode[Tvaraff[k]][lv]);
                   7304:              kl++;
                   7305:            }
                   7306:          } /* end covariate */
                   7307:        } /* end if no covariate */
                   7308: 
1.296     brouard  7309:        if(prevbcast==1){ /* We need to get the corresponding values of the covariates involved in this combination k1 */
1.238     brouard  7310:          /* 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  7311:          fprintf(ficgp,",\"%s\" u 1:((",subdirf2(fileresu,"PLB_")); /* Age is in 1, nres in 2 to be fixed */
1.238     brouard  7312:          if(cptcoveff ==0){
1.245     brouard  7313:            fprintf(ficgp,"$%d)) t 'Backward prevalence in state %d' with line lt 3",    2+(cpt-1),  cpt );
1.238     brouard  7314:          }else{
                   7315:            kl=0;
                   7316:            for (k=1; k<=cptcoveff; k++){    /* For each combination of covariate  */
                   7317:              lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate value corresponding to k1 combination and kth covariate */
                   7318:              /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   7319:              /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   7320:              /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
                   7321:              vlv= nbcode[Tvaraff[k]][lv];
1.223     brouard  7322:              kl++;
1.238     brouard  7323:              /* 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 *\/ */
                   7324:              /*6+(cpt-1)*(nlstate+1)+1+(i-1)+(nlstate+1)*nlstate; 6+(1-1)*(2+1)+1+(1-1) +(2+1)*2=13 */ 
                   7325:              /*6+1+(i-1)+(nlstate+1)*nlstate; 6+1+(1-1) +(2+1)*2=13 */ 
                   7326:              /* ''  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*/
                   7327:              if(k==cptcoveff){
1.245     brouard  7328:                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  7329:                        2+cptcoveff*2+(cpt-1),  cpt );  /* 4 or 6 ?*/
1.238     brouard  7330:              }else{
                   7331:                fprintf(ficgp,"$%d==%d && $%d==%d && ",kl+1, Tvaraff[k],kl+1+1,nbcode[Tvaraff[k]][lv]);
                   7332:                kl++;
                   7333:              }
                   7334:            } /* end covariate */
                   7335:          } /* end if no covariate */
1.296     brouard  7336:          if(prevbcast == 1){
1.268     brouard  7337:            fprintf(ficgp,", \"%s\" every :::%d::%d u 1:($2==%d ? $3:1/0) \"%%lf %%lf",subdirf2(fileresu,"VBL_"),nres-1,nres-1,nres);
                   7338:            /* k1-1 error should be nres-1*/
                   7339:            for (i=1; i<= nlstate ; i ++) {
                   7340:              if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
                   7341:              else        fprintf(ficgp," %%*lf (%%*lf)");
                   7342:            }
1.271     brouard  7343:            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  7344:            for (i=1; i<= nlstate ; i ++) {
                   7345:              if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
                   7346:              else fprintf(ficgp," %%*lf (%%*lf)");
                   7347:            } 
1.276     brouard  7348:            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  7349:            for (i=1; i<= nlstate ; i ++) {
                   7350:              if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
                   7351:              else fprintf(ficgp," %%*lf (%%*lf)");
                   7352:            } 
1.274     brouard  7353:            fprintf(ficgp,"\" t\"\" w l lt 4");
1.268     brouard  7354:          } /* end if backprojcast */
1.296     brouard  7355:        } /* end if prevbcast */
1.276     brouard  7356:        /* fprintf(ficgp,"\nset out ;unset label;\n"); */
                   7357:        fprintf(ficgp,"\nset out ;unset title;\n");
1.238     brouard  7358:       } /* nres */
1.201     brouard  7359:     } /* k1 */
                   7360:   } /* cpt */
1.235     brouard  7361: 
                   7362:   
1.126     brouard  7363:   /*2 eme*/
1.238     brouard  7364:   for (k1=1; k1<= m ; k1 ++){  
                   7365:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.253     brouard  7366:       if(m != 1 && TKresult[nres]!= k1)
1.238     brouard  7367:        continue;
                   7368:       fprintf(ficgp,"\n# 2nd: Total life expectancy with CI: 't' files ");
1.264     brouard  7369:       strcpy(gplotlabel,"(");
1.238     brouard  7370:       for (k=1; k<=cptcoveff; k++){    /* For each covariate and each value */
1.225     brouard  7371:        lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate number corresponding to k1 combination */
1.223     brouard  7372:        /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   7373:        /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   7374:        /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
                   7375:        vlv= nbcode[Tvaraff[k]][lv];
                   7376:        fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv);
1.264     brouard  7377:        sprintf(gplotlabel+strlen(gplotlabel)," V%d=%d ",Tvaraff[k],vlv);
1.211     brouard  7378:       }
1.237     brouard  7379:       /* for(k=1; k <= ncovds; k++){ */
1.236     brouard  7380:       for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
1.238     brouard  7381:        printf(" V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
1.236     brouard  7382:        fprintf(ficgp," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
1.264     brouard  7383:        sprintf(gplotlabel+strlen(gplotlabel)," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
1.238     brouard  7384:       }
1.264     brouard  7385:       strcpy(gplotlabel+strlen(gplotlabel),")");
1.211     brouard  7386:       fprintf(ficgp,"\n#\n");
1.223     brouard  7387:       if(invalidvarcomb[k1]){
                   7388:        fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   7389:        continue;
                   7390:       }
1.219     brouard  7391:                        
1.241     brouard  7392:       fprintf(ficgp,"\nset out \"%s_%d-%d.svg\" \n",subdirf2(optionfilefiname,"E_"),k1,nres);
1.238     brouard  7393:       for(vpopbased=0; vpopbased <= popbased; vpopbased++){ /* Done for vpopbased=0 and vpopbased=1 if popbased==1*/
1.264     brouard  7394:        fprintf(ficgp,"\nset label \"popbased %d %s\" at graph 0.98,0.5 center rotate font \"Helvetica,12\"\n",vpopbased,gplotlabel);
                   7395:        if(vpopbased==0){
1.238     brouard  7396:          fprintf(ficgp,"set ylabel \"Years\" \nset ter svg size 640, 480\nplot [%.f:%.f] ",ageminpar,fage);
1.264     brouard  7397:        }else
1.238     brouard  7398:          fprintf(ficgp,"\nreplot ");
                   7399:        for (i=1; i<= nlstate+1 ; i ++) {
                   7400:          k=2*i;
1.261     brouard  7401:          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  7402:          for (j=1; j<= nlstate+1 ; j ++) {
                   7403:            if (j==i) fprintf(ficgp," %%lf (%%lf)");
                   7404:            else fprintf(ficgp," %%*lf (%%*lf)");
                   7405:          }   
                   7406:          if (i== 1) fprintf(ficgp,"\" t\"TLE\" w l lt %d, \\\n",i);
                   7407:          else fprintf(ficgp,"\" t\"LE in state (%d)\" w l lt %d, \\\n",i-1,i+1);
1.261     brouard  7408:          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  7409:          for (j=1; j<= nlstate+1 ; j ++) {
                   7410:            if (j==i) fprintf(ficgp," %%lf (%%lf)");
                   7411:            else fprintf(ficgp," %%*lf (%%*lf)");
                   7412:          }   
                   7413:          fprintf(ficgp,"\" t\"\" w l lt 0,");
1.261     brouard  7414:          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  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== (nlstate+1)) fprintf(ficgp,"\" t\"\" w l lt 0");
                   7420:          else fprintf(ficgp,"\" t\"\" w l lt 0,\\\n");
                   7421:        } /* state */
                   7422:       } /* vpopbased */
1.264     brouard  7423:       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  7424:     } /* end nres */
                   7425:   } /* k1 end 2 eme*/
                   7426:        
                   7427:        
                   7428:   /*3eme*/
                   7429:   for (k1=1; k1<= m ; k1 ++){
                   7430:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.253     brouard  7431:       if(m != 1 && TKresult[nres]!= k1)
1.238     brouard  7432:        continue;
                   7433: 
                   7434:       for (cpt=1; cpt<= nlstate ; cpt ++) {
1.261     brouard  7435:        fprintf(ficgp,"\n\n# 3d: Life expectancy with EXP_ files:  combination=%d state=%d",k1, cpt);
1.264     brouard  7436:        strcpy(gplotlabel,"(");
1.238     brouard  7437:        for (k=1; k<=cptcoveff; k++){    /* For each covariate and each value */
                   7438:          lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate number corresponding to k1 combination */
                   7439:          /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   7440:          /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   7441:          /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
                   7442:          vlv= nbcode[Tvaraff[k]][lv];
                   7443:          fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv);
1.264     brouard  7444:          sprintf(gplotlabel+strlen(gplotlabel)," V%d=%d ",Tvaraff[k],vlv);
1.238     brouard  7445:        }
                   7446:        for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
                   7447:          fprintf(ficgp," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
1.264     brouard  7448:          sprintf(gplotlabel+strlen(gplotlabel)," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
1.238     brouard  7449:        }       
1.264     brouard  7450:        strcpy(gplotlabel+strlen(gplotlabel),")");
1.238     brouard  7451:        fprintf(ficgp,"\n#\n");
                   7452:        if(invalidvarcomb[k1]){
                   7453:          fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   7454:          continue;
                   7455:        }
                   7456:                        
                   7457:        /*       k=2+nlstate*(2*cpt-2); */
                   7458:        k=2+(nlstate+1)*(cpt-1);
1.241     brouard  7459:        fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" \n",subdirf2(optionfilefiname,"EXP_"),cpt,k1,nres);
1.264     brouard  7460:        fprintf(ficgp,"set label \"%s\" at graph 0.98,0.5 center rotate font \"Helvetica,12\"\n",gplotlabel);
1.238     brouard  7461:        fprintf(ficgp,"set ter svg size 640, 480\n\
1.261     brouard  7462: 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  7463:        /*fprintf(ficgp,",\"e%s\" every :::%d::%d u 1:($%d-2*$%d) \"\%%lf ",fileres,k1-1,k1-1,k,k+1);
                   7464:          for (i=1; i<= nlstate*2 ; i ++) fprintf(ficgp,"\%%lf (\%%lf) ");
                   7465:          fprintf(ficgp,"\" t \"e%d1\" w l",cpt);
                   7466:          fprintf(ficgp,",\"e%s\" every :::%d::%d u 1:($%d+2*$%d) \"\%%lf ",fileres,k1-1,k1-1,k,k+1);
                   7467:          for (i=1; i<= nlstate*2 ; i ++) fprintf(ficgp,"\%%lf (\%%lf) ");
                   7468:          fprintf(ficgp,"\" t \"e%d1\" w l",cpt);
1.219     brouard  7469:                                
1.238     brouard  7470:        */
                   7471:        for (i=1; i< nlstate ; i ++) {
1.261     brouard  7472:          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  7473:          /*    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  7474:                                
1.238     brouard  7475:        } 
1.261     brouard  7476:        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  7477:       }
1.264     brouard  7478:       fprintf(ficgp,"\nunset label;\n");
1.238     brouard  7479:     } /* end nres */
                   7480:   } /* end kl 3eme */
1.126     brouard  7481:   
1.223     brouard  7482:   /* 4eme */
1.201     brouard  7483:   /* Survival functions (period) from state i in state j by initial state i */
1.238     brouard  7484:   for (k1=1; k1<=m; k1++){    /* For each covariate and each value */
                   7485:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.253     brouard  7486:       if(m != 1 && TKresult[nres]!= k1)
1.223     brouard  7487:        continue;
1.238     brouard  7488:       for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each life state cpt*/
1.264     brouard  7489:        strcpy(gplotlabel,"(");
1.238     brouard  7490:        fprintf(ficgp,"\n#\n#\n# Survival functions in state j : 'LIJ_' files, cov=%d state=%d",k1, cpt);
                   7491:        for (k=1; k<=cptcoveff; k++){    /* For each covariate and each value */
                   7492:          lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate number corresponding to k1 combination */
                   7493:          /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   7494:          /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   7495:          /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
                   7496:          vlv= nbcode[Tvaraff[k]][lv];
                   7497:          fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv);
1.264     brouard  7498:          sprintf(gplotlabel+strlen(gplotlabel)," V%d=%d ",Tvaraff[k],vlv);
1.238     brouard  7499:        }
                   7500:        for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
                   7501:          fprintf(ficgp," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
1.264     brouard  7502:          sprintf(gplotlabel+strlen(gplotlabel)," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
1.238     brouard  7503:        }       
1.264     brouard  7504:        strcpy(gplotlabel+strlen(gplotlabel),")");
1.238     brouard  7505:        fprintf(ficgp,"\n#\n");
                   7506:        if(invalidvarcomb[k1]){
                   7507:          fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   7508:          continue;
1.223     brouard  7509:        }
1.238     brouard  7510:       
1.241     brouard  7511:        fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" \n",subdirf2(optionfilefiname,"LIJ_"),cpt,k1,nres);
1.264     brouard  7512:        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  7513:        fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Probability to be alive\" \n\
                   7514: set ter svg size 640, 480\nunset log y\nplot [%.f:%.f]  ", ageminpar, agemaxpar);
                   7515:        k=3;
                   7516:        for (i=1; i<= nlstate ; i ++){
                   7517:          if(i==1){
                   7518:            fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"PIJ_"));
                   7519:          }else{
                   7520:            fprintf(ficgp,", '' ");
                   7521:          }
                   7522:          l=(nlstate+ndeath)*(i-1)+1;
                   7523:          fprintf(ficgp," u ($1==%d ? ($3):1/0):($%d/($%d",k1,k+l+(cpt-1),k+l);
                   7524:          for (j=2; j<= nlstate+ndeath ; j ++)
                   7525:            fprintf(ficgp,"+$%d",k+l+j-1);
                   7526:          fprintf(ficgp,")) t \"l(%d,%d)\" w l",i,cpt);
                   7527:        } /* nlstate */
1.264     brouard  7528:        fprintf(ficgp,"\nset out; unset label;\n");
1.238     brouard  7529:       } /* end cpt state*/ 
                   7530:     } /* end nres */
                   7531:   } /* end covariate k1 */  
                   7532: 
1.220     brouard  7533: /* 5eme */
1.201     brouard  7534:   /* Survival functions (period) from state i in state j by final state j */
1.238     brouard  7535:   for (k1=1; k1<= m ; k1++){ /* For each covariate combination if any */
                   7536:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.253     brouard  7537:       if(m != 1 && TKresult[nres]!= k1)
1.227     brouard  7538:        continue;
1.238     brouard  7539:       for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each inital state  */
1.264     brouard  7540:        strcpy(gplotlabel,"(");
1.238     brouard  7541:        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);
                   7542:        for (k=1; k<=cptcoveff; k++){    /* For each covariate and each value */
                   7543:          lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate number corresponding to k1 combination */
                   7544:          /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   7545:          /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   7546:          /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
                   7547:          vlv= nbcode[Tvaraff[k]][lv];
                   7548:          fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv);
1.264     brouard  7549:          sprintf(gplotlabel+strlen(gplotlabel)," V%d=%d ",Tvaraff[k],vlv);
1.238     brouard  7550:        }
                   7551:        for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
                   7552:          fprintf(ficgp," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
1.264     brouard  7553:          sprintf(gplotlabel+strlen(gplotlabel)," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
1.238     brouard  7554:        }       
1.264     brouard  7555:        strcpy(gplotlabel+strlen(gplotlabel),")");
1.238     brouard  7556:        fprintf(ficgp,"\n#\n");
                   7557:        if(invalidvarcomb[k1]){
                   7558:          fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   7559:          continue;
                   7560:        }
1.227     brouard  7561:       
1.241     brouard  7562:        fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" \n",subdirf2(optionfilefiname,"LIJT_"),cpt,k1,nres);
1.264     brouard  7563:        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  7564:        fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Probability to be alive\" \n\
                   7565: set ter svg size 640, 480\nunset log y\nplot [%.f:%.f]  ", ageminpar, agemaxpar);
                   7566:        k=3;
                   7567:        for (j=1; j<= nlstate ; j ++){ /* Lived in state j */
                   7568:          if(j==1)
                   7569:            fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"PIJ_"));
                   7570:          else
                   7571:            fprintf(ficgp,", '' ");
                   7572:          l=(nlstate+ndeath)*(cpt-1) +j;
                   7573:          fprintf(ficgp," u (($1==%d && (floor($2)%%5 == 0)) ? ($3):1/0):($%d",k1,k+l);
                   7574:          /* for (i=2; i<= nlstate+ndeath ; i ++) */
                   7575:          /*   fprintf(ficgp,"+$%d",k+l+i-1); */
                   7576:          fprintf(ficgp,") t \"l(%d,%d)\" w l",cpt,j);
                   7577:        } /* nlstate */
                   7578:        fprintf(ficgp,", '' ");
                   7579:        fprintf(ficgp," u (($1==%d && (floor($2)%%5 == 0)) ? ($3):1/0):(",k1);
                   7580:        for (j=1; j<= nlstate ; j ++){ /* Lived in state j */
                   7581:          l=(nlstate+ndeath)*(cpt-1) +j;
                   7582:          if(j < nlstate)
                   7583:            fprintf(ficgp,"$%d +",k+l);
                   7584:          else
                   7585:            fprintf(ficgp,"$%d) t\"l(%d,.)\" w l",k+l,cpt);
                   7586:        }
1.264     brouard  7587:        fprintf(ficgp,"\nset out; unset label;\n");
1.238     brouard  7588:       } /* end cpt state*/ 
                   7589:     } /* end covariate */  
                   7590:   } /* end nres */
1.227     brouard  7591:   
1.220     brouard  7592: /* 6eme */
1.202     brouard  7593:   /* CV preval stable (period) for each covariate */
1.237     brouard  7594:   for (k1=1; k1<= m ; k1 ++) /* For each covariate combination if any */
                   7595:   for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.253     brouard  7596:     if(m != 1 && TKresult[nres]!= k1)
1.237     brouard  7597:       continue;
1.255     brouard  7598:     for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each life state of arrival */
1.264     brouard  7599:       strcpy(gplotlabel,"(");      
1.288     brouard  7600:       fprintf(ficgp,"\n#\n#\n#CV preval stable (forward): 'pij' files, covariatecombination#=%d state=%d",k1, cpt);
1.225     brouard  7601:       for (k=1; k<=cptcoveff; k++){    /* For each covariate and each value */
1.227     brouard  7602:        lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate number corresponding to k1 combination */
                   7603:        /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   7604:        /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   7605:        /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
                   7606:        vlv= nbcode[Tvaraff[k]][lv];
                   7607:        fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv);
1.264     brouard  7608:        sprintf(gplotlabel+strlen(gplotlabel)," V%d=%d ",Tvaraff[k],vlv);
1.211     brouard  7609:       }
1.237     brouard  7610:       for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
                   7611:        fprintf(ficgp," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
1.264     brouard  7612:        sprintf(gplotlabel+strlen(gplotlabel)," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
1.237     brouard  7613:       }        
1.264     brouard  7614:       strcpy(gplotlabel+strlen(gplotlabel),")");
1.211     brouard  7615:       fprintf(ficgp,"\n#\n");
1.223     brouard  7616:       if(invalidvarcomb[k1]){
1.227     brouard  7617:        fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   7618:        continue;
1.223     brouard  7619:       }
1.227     brouard  7620:       
1.241     brouard  7621:       fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" \n",subdirf2(optionfilefiname,"P_"),cpt,k1,nres);
1.264     brouard  7622:       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  7623:       fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Probability\" \n\
1.238     brouard  7624: set ter svg size 640, 480\nunset log y\nplot [%.f:%.f]  ", ageminpar, agemaxpar);
1.211     brouard  7625:       k=3; /* Offset */
1.255     brouard  7626:       for (i=1; i<= nlstate ; i ++){ /* State of origin */
1.227     brouard  7627:        if(i==1)
                   7628:          fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"PIJ_"));
                   7629:        else
                   7630:          fprintf(ficgp,", '' ");
1.255     brouard  7631:        l=(nlstate+ndeath)*(i-1)+1; /* 1, 1+ nlstate+ndeath, 1+2*(nlstate+ndeath) */
1.227     brouard  7632:        fprintf(ficgp," u ($1==%d ? ($3):1/0):($%d/($%d",k1,k+l+(cpt-1),k+l);
                   7633:        for (j=2; j<= nlstate ; j ++)
                   7634:          fprintf(ficgp,"+$%d",k+l+j-1);
                   7635:        fprintf(ficgp,")) t \"prev(%d,%d)\" w l",i,cpt);
1.153     brouard  7636:       } /* nlstate */
1.264     brouard  7637:       fprintf(ficgp,"\nset out; unset label;\n");
1.153     brouard  7638:     } /* end cpt state*/ 
                   7639:   } /* end covariate */  
1.227     brouard  7640:   
                   7641:   
1.220     brouard  7642: /* 7eme */
1.296     brouard  7643:   if(prevbcast == 1){
1.288     brouard  7644:     /* CV backward prevalence  for each covariate */
1.237     brouard  7645:     for (k1=1; k1<= m ; k1 ++) /* For each covariate combination if any */
                   7646:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.253     brouard  7647:       if(m != 1 && TKresult[nres]!= k1)
1.237     brouard  7648:        continue;
1.268     brouard  7649:       for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each life origin state */
1.264     brouard  7650:        strcpy(gplotlabel,"(");      
1.288     brouard  7651:        fprintf(ficgp,"\n#\n#\n#CV Backward stable prevalence: 'pijb' files, covariatecombination#=%d state=%d",k1, cpt);
1.227     brouard  7652:        for (k=1; k<=cptcoveff; k++){    /* For each covariate and each value */
                   7653:          lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate number corresponding to k1 combination */
                   7654:          /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   7655:          /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
1.223     brouard  7656:          /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
1.227     brouard  7657:          vlv= nbcode[Tvaraff[k]][lv];
                   7658:          fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv);
1.264     brouard  7659:          sprintf(gplotlabel+strlen(gplotlabel)," V%d=%d ",Tvaraff[k],vlv);
1.227     brouard  7660:        }
1.237     brouard  7661:        for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
                   7662:          fprintf(ficgp," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
1.264     brouard  7663:          sprintf(gplotlabel+strlen(gplotlabel)," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
1.237     brouard  7664:        }       
1.264     brouard  7665:        strcpy(gplotlabel+strlen(gplotlabel),")");
1.227     brouard  7666:        fprintf(ficgp,"\n#\n");
                   7667:        if(invalidvarcomb[k1]){
                   7668:          fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   7669:          continue;
                   7670:        }
                   7671:        
1.241     brouard  7672:        fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" \n",subdirf2(optionfilefiname,"PB_"),cpt,k1,nres);
1.268     brouard  7673:        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  7674:        fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Probability\" \n\
1.238     brouard  7675: set ter svg size 640, 480\nunset log y\nplot [%.f:%.f]  ", ageminpar, agemaxpar);
1.227     brouard  7676:        k=3; /* Offset */
1.268     brouard  7677:        for (i=1; i<= nlstate ; i ++){ /* State of arrival */
1.227     brouard  7678:          if(i==1)
                   7679:            fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"PIJB_"));
                   7680:          else
                   7681:            fprintf(ficgp,", '' ");
                   7682:          /* l=(nlstate+ndeath)*(i-1)+1; */
1.255     brouard  7683:          l=(nlstate+ndeath)*(cpt-1)+1; /* fixed for i; cpt=1 1, cpt=2 1+ nlstate+ndeath, 1+2*(nlstate+ndeath) */
1.227     brouard  7684:          /* fprintf(ficgp," u ($1==%d ? ($3):1/0):($%d/($%d",k1,k+l+(cpt-1),k+l); /\* a vérifier *\/ */
                   7685:          /* 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  7686:          fprintf(ficgp," u ($1==%d ? ($3):1/0):($%d",k1,k+l+i-1); /* To be verified */
1.227     brouard  7687:          /* for (j=2; j<= nlstate ; j ++) */
                   7688:          /*    fprintf(ficgp,"+$%d",k+l+j-1); */
                   7689:          /*    /\* fprintf(ficgp,"+$%d",k+l+j-1); *\/ */
1.268     brouard  7690:          fprintf(ficgp,") t \"bprev(%d,%d)\" w l",cpt,i);
1.227     brouard  7691:        } /* nlstate */
1.264     brouard  7692:        fprintf(ficgp,"\nset out; unset label;\n");
1.218     brouard  7693:       } /* end cpt state*/ 
                   7694:     } /* end covariate */  
1.296     brouard  7695:   } /* End if prevbcast */
1.218     brouard  7696:   
1.223     brouard  7697:   /* 8eme */
1.218     brouard  7698:   if(prevfcast==1){
1.288     brouard  7699:     /* Projection from cross-sectional to forward stable (period) prevalence for each covariate */
1.218     brouard  7700:     
1.237     brouard  7701:     for (k1=1; k1<= m ; k1 ++) /* For each covariate combination if any */
                   7702:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.253     brouard  7703:       if(m != 1 && TKresult[nres]!= k1)
1.237     brouard  7704:        continue;
1.211     brouard  7705:       for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each life state */
1.264     brouard  7706:        strcpy(gplotlabel,"(");      
1.288     brouard  7707:        fprintf(ficgp,"\n#\n#\n#Projection of prevalence to forward stable prevalence (period): 'PROJ_' files, covariatecombination#=%d state=%d",k1, cpt);
1.227     brouard  7708:        for (k=1; k<=cptcoveff; k++){    /* For each correspondig covariate value  */
                   7709:          lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate value corresponding to k1 combination and kth covariate */
                   7710:          /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   7711:          /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   7712:          /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
                   7713:          vlv= nbcode[Tvaraff[k]][lv];
                   7714:          fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv);
1.264     brouard  7715:          sprintf(gplotlabel+strlen(gplotlabel)," V%d=%d ",Tvaraff[k],vlv);
1.227     brouard  7716:        }
1.237     brouard  7717:        for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
                   7718:          fprintf(ficgp," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
1.264     brouard  7719:          sprintf(gplotlabel+strlen(gplotlabel)," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
1.237     brouard  7720:        }       
1.264     brouard  7721:        strcpy(gplotlabel+strlen(gplotlabel),")");
1.227     brouard  7722:        fprintf(ficgp,"\n#\n");
                   7723:        if(invalidvarcomb[k1]){
                   7724:          fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   7725:          continue;
                   7726:        }
                   7727:        
                   7728:        fprintf(ficgp,"# hpijx=probability over h years, hp.jx is weighted by observed prev\n ");
1.241     brouard  7729:        fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" \n",subdirf2(optionfilefiname,"PROJ_"),cpt,k1,nres);
1.264     brouard  7730:        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  7731:        fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Prevalence\" \n\
1.238     brouard  7732: set ter svg size 640, 480\nunset log y\nplot [%.f:%.f]  ", ageminpar, agemaxpar);
1.266     brouard  7733: 
                   7734:        /* for (i=1; i<= nlstate+1 ; i ++){  /\* nlstate +1 p11 p21 p.1 *\/ */
                   7735:        istart=nlstate+1; /* Could be one if by state, but nlstate+1 is w.i projection only */
                   7736:        /*istart=1;*/ /* Could be one if by state, but nlstate+1 is w.i projection only */
                   7737:        for (i=istart; i<= nlstate+1 ; i ++){  /* nlstate +1 p11 p21 p.1 */
1.227     brouard  7738:          /*#  V1  = 1  V2 =  0 yearproj age p11 p21 p.1 p12 p22 p.2 p13 p23 p.3*/
                   7739:          /*#   1    2   3    4    5      6  7   8   9   10   11 12  13   14  15 */   
                   7740:          /*# yearproj age p11 p21 p.1 p12 p22 p.2 p13 p23 p.3*/
                   7741:          /*#   1       2   3    4    5      6  7   8   9   10   11 12  13   14  15 */   
1.266     brouard  7742:          if(i==istart){
1.227     brouard  7743:            fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"F_"));
                   7744:          }else{
                   7745:            fprintf(ficgp,",\\\n '' ");
                   7746:          }
                   7747:          if(cptcoveff ==0){ /* No covariate */
                   7748:            ioffset=2; /* Age is in 2 */
                   7749:            /*# yearproj age p11 p21 p31 p.1 p12 p22 p32 p.2 p13 p23 p33 p.3 p14 p24 p34 p.4*/
                   7750:            /*#   1       2   3   4   5  6    7  8   9   10  11  12  13  14  15  16  17  18 */
                   7751:            /*# V1  = 1 yearproj age p11 p21 p31 p.1 p12 p22 p32 p.2 p13 p23 p33 p.3 p14 p24 p34 p.4*/
                   7752:            /*#  1    2        3   4   5  6    7  8   9   10  11  12  13  14  15  16  17  18 */
                   7753:            fprintf(ficgp," u %d:(", ioffset); 
1.266     brouard  7754:            if(i==nlstate+1){
1.270     brouard  7755:              fprintf(ficgp," $%d/(1.-$%d)):1 t 'pw.%d' with line lc variable ",        \
1.266     brouard  7756:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1),  ioffset+1+(i-1)+(nlstate+1)*nlstate,cpt );
                   7757:              fprintf(ficgp,",\\\n '' ");
                   7758:              fprintf(ficgp," u %d:(",ioffset); 
1.270     brouard  7759:              fprintf(ficgp," (($1-$2) == %d ) ? $%d/(1.-$%d) : 1/0):1 with labels center not ", \
1.266     brouard  7760:                     offyear,                           \
1.268     brouard  7761:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1),  ioffset+1+(i-1)+(nlstate+1)*nlstate );
1.266     brouard  7762:            }else
1.227     brouard  7763:              fprintf(ficgp," $%d/(1.-$%d)) t 'p%d%d' with line ",      \
                   7764:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1),  ioffset+1+(i-1)+(nlstate+1)*nlstate,i,cpt );
                   7765:          }else{ /* more than 2 covariates */
1.270     brouard  7766:            ioffset=2*cptcoveff+2; /* Age is in 4 or 6 or etc.*/
                   7767:            /*#  V1  = 1  V2 =  0 yearproj age p11 p21 p.1 p12 p22 p.2 p13 p23 p.3*/
                   7768:            /*#   1    2   3    4    5      6  7   8   9   10   11 12  13   14  15 */
                   7769:            iyearc=ioffset-1;
                   7770:            iagec=ioffset;
1.227     brouard  7771:            fprintf(ficgp," u %d:(",ioffset); 
                   7772:            kl=0;
                   7773:            strcpy(gplotcondition,"(");
                   7774:            for (k=1; k<=cptcoveff; k++){    /* For each covariate writing the chain of conditions */
                   7775:              lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate value corresponding to combination k1 and covariate k */
                   7776:              /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   7777:              /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   7778:              /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
                   7779:              vlv= nbcode[Tvaraff[k]][lv]; /* Value of the modality of Tvaraff[k] */
                   7780:              kl++;
                   7781:              sprintf(gplotcondition+strlen(gplotcondition),"$%d==%d && $%d==%d " ,kl,Tvaraff[k], kl+1, nbcode[Tvaraff[k]][lv]);
                   7782:              kl++;
                   7783:              if(k <cptcoveff && cptcoveff>1)
                   7784:                sprintf(gplotcondition+strlen(gplotcondition)," && ");
                   7785:            }
                   7786:            strcpy(gplotcondition+strlen(gplotcondition),")");
                   7787:            /* 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 *\/ */
                   7788:            /*6+(cpt-1)*(nlstate+1)+1+(i-1)+(nlstate+1)*nlstate; 6+(1-1)*(2+1)+1+(1-1) +(2+1)*2=13 */ 
                   7789:            /*6+1+(i-1)+(nlstate+1)*nlstate; 6+1+(1-1) +(2+1)*2=13 */ 
                   7790:            /* ''  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*/
                   7791:            if(i==nlstate+1){
1.270     brouard  7792:              fprintf(ficgp,"%s ? $%d/(1.-$%d) : 1/0):%d t 'p.%d' with line lc variable", gplotcondition, \
                   7793:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1),  ioffset+1+(i-1)+(nlstate+1)*nlstate,iyearc, cpt );
1.266     brouard  7794:              fprintf(ficgp,",\\\n '' ");
1.270     brouard  7795:              fprintf(ficgp," u %d:(",iagec); 
                   7796:              fprintf(ficgp,"%s && (($%d-$%d) == %d ) ? $%d/(1.-$%d) : 1/0):%d with labels center not ", gplotcondition, \
                   7797:                      iyearc, iagec, offyear,                           \
                   7798:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1),  ioffset+1+(i-1)+(nlstate+1)*nlstate, iyearc );
1.266     brouard  7799: /*  '' 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  7800:            }else{
                   7801:              fprintf(ficgp,"%s ? $%d/(1.-$%d) : 1/0) t 'p%d%d' with line ", gplotcondition, \
                   7802:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1), ioffset +1+(i-1)+(nlstate+1)*nlstate,i,cpt );
                   7803:            }
                   7804:          } /* end if covariate */
                   7805:        } /* nlstate */
1.264     brouard  7806:        fprintf(ficgp,"\nset out; unset label;\n");
1.223     brouard  7807:       } /* end cpt state*/
                   7808:     } /* end covariate */
                   7809:   } /* End if prevfcast */
1.227     brouard  7810:   
1.296     brouard  7811:   if(prevbcast==1){
1.268     brouard  7812:     /* Back projection from cross-sectional to stable (mixed) for each covariate */
                   7813:     
                   7814:     for (k1=1; k1<= m ; k1 ++) /* For each covariate combination if any */
                   7815:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
                   7816:       if(m != 1 && TKresult[nres]!= k1)
                   7817:        continue;
                   7818:       for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each life state */
                   7819:        strcpy(gplotlabel,"(");      
                   7820:        fprintf(ficgp,"\n#\n#\n#Back projection of prevalence to stable (mixed) back prevalence: 'BPROJ_' files, covariatecombination#=%d originstate=%d",k1, cpt);
                   7821:        for (k=1; k<=cptcoveff; k++){    /* For each correspondig covariate value  */
                   7822:          lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate value corresponding to k1 combination and kth covariate */
                   7823:          /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   7824:          /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   7825:          /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
                   7826:          vlv= nbcode[Tvaraff[k]][lv];
                   7827:          fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv);
                   7828:          sprintf(gplotlabel+strlen(gplotlabel)," V%d=%d ",Tvaraff[k],vlv);
                   7829:        }
                   7830:        for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
                   7831:          fprintf(ficgp," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
                   7832:          sprintf(gplotlabel+strlen(gplotlabel)," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
                   7833:        }       
                   7834:        strcpy(gplotlabel+strlen(gplotlabel),")");
                   7835:        fprintf(ficgp,"\n#\n");
                   7836:        if(invalidvarcomb[k1]){
                   7837:          fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   7838:          continue;
                   7839:        }
                   7840:        
                   7841:        fprintf(ficgp,"# hbijx=backprobability over h years, hb.jx is weighted by observed prev at destination state\n ");
                   7842:        fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" \n",subdirf2(optionfilefiname,"PROJB_"),cpt,k1,nres);
                   7843:        fprintf(ficgp,"set label \"Origin alive state %d %s\" at graph 0.98,0.5 center rotate font \"Helvetica,12\"\n",cpt,gplotlabel);
                   7844:        fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Prevalence\" \n\
                   7845: set ter svg size 640, 480\nunset log y\nplot [%.f:%.f]  ", ageminpar, agemaxpar);
                   7846: 
                   7847:        /* for (i=1; i<= nlstate+1 ; i ++){  /\* nlstate +1 p11 p21 p.1 *\/ */
                   7848:        istart=nlstate+1; /* Could be one if by state, but nlstate+1 is w.i projection only */
                   7849:        /*istart=1;*/ /* Could be one if by state, but nlstate+1 is w.i projection only */
                   7850:        for (i=istart; i<= nlstate+1 ; i ++){  /* nlstate +1 p11 p21 p.1 */
                   7851:          /*#  V1  = 1  V2 =  0 yearproj age p11 p21 p.1 p12 p22 p.2 p13 p23 p.3*/
                   7852:          /*#   1    2   3    4    5      6  7   8   9   10   11 12  13   14  15 */   
                   7853:          /*# yearproj age p11 p21 p.1 p12 p22 p.2 p13 p23 p.3*/
                   7854:          /*#   1       2   3    4    5      6  7   8   9   10   11 12  13   14  15 */   
                   7855:          if(i==istart){
                   7856:            fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"FB_"));
                   7857:          }else{
                   7858:            fprintf(ficgp,",\\\n '' ");
                   7859:          }
                   7860:          if(cptcoveff ==0){ /* No covariate */
                   7861:            ioffset=2; /* Age is in 2 */
                   7862:            /*# yearproj age p11 p21 p31 p.1 p12 p22 p32 p.2 p13 p23 p33 p.3 p14 p24 p34 p.4*/
                   7863:            /*#   1       2   3   4   5  6    7  8   9   10  11  12  13  14  15  16  17  18 */
                   7864:            /*# V1  = 1 yearproj age p11 p21 p31 p.1 p12 p22 p32 p.2 p13 p23 p33 p.3 p14 p24 p34 p.4*/
                   7865:            /*#  1    2        3   4   5  6    7  8   9   10  11  12  13  14  15  16  17  18 */
                   7866:            fprintf(ficgp," u %d:(", ioffset); 
                   7867:            if(i==nlstate+1){
1.270     brouard  7868:              fprintf(ficgp," $%d/(1.-$%d)):1 t 'bw%d' with line lc variable ", \
1.268     brouard  7869:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1),  ioffset+1+(i-1)+(nlstate+1)*nlstate,cpt );
                   7870:              fprintf(ficgp,",\\\n '' ");
                   7871:              fprintf(ficgp," u %d:(",ioffset); 
1.270     brouard  7872:              fprintf(ficgp," (($1-$2) == %d ) ? $%d : 1/0):1 with labels center not ", \
1.268     brouard  7873:                     offbyear,                          \
                   7874:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1) );
                   7875:            }else
                   7876:              fprintf(ficgp," $%d/(1.-$%d)) t 'b%d%d' with line ",      \
                   7877:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1),  ioffset+1+(i-1)+(nlstate+1)*nlstate,cpt,i );
                   7878:          }else{ /* more than 2 covariates */
1.270     brouard  7879:            ioffset=2*cptcoveff+2; /* Age is in 4 or 6 or etc.*/
                   7880:            /*#  V1  = 1  V2 =  0 yearproj age p11 p21 p.1 p12 p22 p.2 p13 p23 p.3*/
                   7881:            /*#   1    2   3    4    5      6  7   8   9   10   11 12  13   14  15 */
                   7882:            iyearc=ioffset-1;
                   7883:            iagec=ioffset;
1.268     brouard  7884:            fprintf(ficgp," u %d:(",ioffset); 
                   7885:            kl=0;
                   7886:            strcpy(gplotcondition,"(");
                   7887:            for (k=1; k<=cptcoveff; k++){    /* For each covariate writing the chain of conditions */
                   7888:              lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate value corresponding to combination k1 and covariate k */
                   7889:              /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   7890:              /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   7891:              /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
                   7892:              vlv= nbcode[Tvaraff[k]][lv]; /* Value of the modality of Tvaraff[k] */
                   7893:              kl++;
                   7894:              sprintf(gplotcondition+strlen(gplotcondition),"$%d==%d && $%d==%d " ,kl,Tvaraff[k], kl+1, nbcode[Tvaraff[k]][lv]);
                   7895:              kl++;
                   7896:              if(k <cptcoveff && cptcoveff>1)
                   7897:                sprintf(gplotcondition+strlen(gplotcondition)," && ");
                   7898:            }
                   7899:            strcpy(gplotcondition+strlen(gplotcondition),")");
                   7900:            /* 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 *\/ */
                   7901:            /*6+(cpt-1)*(nlstate+1)+1+(i-1)+(nlstate+1)*nlstate; 6+(1-1)*(2+1)+1+(1-1) +(2+1)*2=13 */ 
                   7902:            /*6+1+(i-1)+(nlstate+1)*nlstate; 6+1+(1-1) +(2+1)*2=13 */ 
                   7903:            /* ''  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*/
                   7904:            if(i==nlstate+1){
1.270     brouard  7905:              fprintf(ficgp,"%s ? $%d : 1/0):%d t 'bw%d' with line lc variable", gplotcondition, \
                   7906:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1),iyearc,cpt );
1.268     brouard  7907:              fprintf(ficgp,",\\\n '' ");
1.270     brouard  7908:              fprintf(ficgp," u %d:(",iagec); 
1.268     brouard  7909:              /* fprintf(ficgp,"%s && (($5-$6) == %d ) ? $%d/(1.-$%d) : 1/0):5 with labels center not ", gplotcondition, \ */
1.270     brouard  7910:              fprintf(ficgp,"%s && (($%d-$%d) == %d ) ? $%d : 1/0):%d with labels center not ", gplotcondition, \
                   7911:                      iyearc,iagec,offbyear,                            \
                   7912:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1), iyearc );
1.268     brouard  7913: /*  '' u 6:(($1==1 && $2==0  && $3==2 && $4==0) && (($5-$6) == 1947) ? $10/(1.-$22) : 1/0):5 with labels center boxed not*/
                   7914:            }else{
                   7915:              /* fprintf(ficgp,"%s ? $%d/(1.-$%d) : 1/0) t 'p%d%d' with line ", gplotcondition, \ */
                   7916:              fprintf(ficgp,"%s ? $%d : 1/0) t 'b%d%d' with line ", gplotcondition, \
                   7917:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1), cpt,i );
                   7918:            }
                   7919:          } /* end if covariate */
                   7920:        } /* nlstate */
                   7921:        fprintf(ficgp,"\nset out; unset label;\n");
                   7922:       } /* end cpt state*/
                   7923:     } /* end covariate */
1.296     brouard  7924:   } /* End if prevbcast */
1.268     brouard  7925:   
1.227     brouard  7926:   
1.238     brouard  7927:   /* 9eme writing MLE parameters */
                   7928:   fprintf(ficgp,"\n##############\n#9eme MLE estimated parameters\n#############\n");
1.126     brouard  7929:   for(i=1,jk=1; i <=nlstate; i++){
1.187     brouard  7930:     fprintf(ficgp,"# initial state %d\n",i);
1.126     brouard  7931:     for(k=1; k <=(nlstate+ndeath); k++){
                   7932:       if (k != i) {
1.227     brouard  7933:        fprintf(ficgp,"#   current state %d\n",k);
                   7934:        for(j=1; j <=ncovmodel; j++){
                   7935:          fprintf(ficgp,"p%d=%f; ",jk,p[jk]);
                   7936:          jk++; 
                   7937:        }
                   7938:        fprintf(ficgp,"\n");
1.126     brouard  7939:       }
                   7940:     }
1.223     brouard  7941:   }
1.187     brouard  7942:   fprintf(ficgp,"##############\n#\n");
1.227     brouard  7943:   
1.145     brouard  7944:   /*goto avoid;*/
1.238     brouard  7945:   /* 10eme Graphics of probabilities or incidences using written MLE parameters */
                   7946:   fprintf(ficgp,"\n##############\n#10eme Graphics of probabilities or incidences\n#############\n");
1.187     brouard  7947:   fprintf(ficgp,"# logi(p12/p11)=a12+b12*age+c12age*age+d12*V1+e12*V1*age\n");
                   7948:   fprintf(ficgp,"# logi(p12/p11)=p1 +p2*age +p3*age*age+ p4*V1+ p5*V1*age\n");
                   7949:   fprintf(ficgp,"# logi(p13/p11)=a13+b13*age+c13age*age+d13*V1+e13*V1*age\n");
                   7950:   fprintf(ficgp,"# logi(p13/p11)=p6 +p7*age +p8*age*age+ p9*V1+ p10*V1*age\n");
                   7951:   fprintf(ficgp,"# p12+p13+p14+p11=1=p11(1+exp(a12+b12*age+c12age*age+d12*V1+e12*V1*age)\n");
                   7952:   fprintf(ficgp,"#                      +exp(a13+b13*age+c13age*age+d13*V1+e13*V1*age)+...)\n");
                   7953:   fprintf(ficgp,"# p11=1/(1+exp(a12+b12*age+c12age*age+d12*V1+e12*V1*age)\n");
                   7954:   fprintf(ficgp,"#                      +exp(a13+b13*age+c13age*age+d13*V1+e13*V1*age)+...)\n");
                   7955:   fprintf(ficgp,"# p12=exp(a12+b12*age+c12age*age+d12*V1+e12*V1*age)/\n");
                   7956:   fprintf(ficgp,"#     (1+exp(a12+b12*age+c12age*age+d12*V1+e12*V1*age)\n");
                   7957:   fprintf(ficgp,"#       +exp(a13+b13*age+c13age*age+d13*V1+e13*V1*age))\n");
                   7958:   fprintf(ficgp,"#       +exp(a14+b14*age+c14age*age+d14*V1+e14*V1*age)+...)\n");
                   7959:   fprintf(ficgp,"#\n");
1.223     brouard  7960:   for(ng=1; ng<=3;ng++){ /* Number of graphics: first is logit, 2nd is probabilities, third is incidences per year*/
1.238     brouard  7961:     fprintf(ficgp,"#Number of graphics: first is logit, 2nd is probabilities, third is incidences per year\n");
1.237     brouard  7962:     fprintf(ficgp,"#model=%s \n",model);
1.238     brouard  7963:     fprintf(ficgp,"# Type of graphic ng=%d\n",ng);
1.264     brouard  7964:     fprintf(ficgp,"#   k1=1 to 2^%d=%d\n",cptcoveff,m);/* to be checked */
                   7965:     for(k1=1; k1 <=m; k1++)  /* For each combination of covariate */
1.237     brouard  7966:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.264     brouard  7967:       if(m != 1 && TKresult[nres]!= k1)
1.237     brouard  7968:        continue;
1.264     brouard  7969:       fprintf(ficgp,"\n\n# Combination of dummy  k1=%d which is ",k1);
                   7970:       strcpy(gplotlabel,"(");
1.276     brouard  7971:       /*sprintf(gplotlabel+strlen(gplotlabel)," Dummy combination %d ",k1);*/
1.264     brouard  7972:       for (k=1; k<=cptcoveff; k++){    /* For each correspondig covariate value  */
                   7973:        lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate value corresponding to k1 combination and kth covariate */
                   7974:        /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   7975:        /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   7976:        /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
                   7977:        vlv= nbcode[Tvaraff[k]][lv];
                   7978:        fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv);
                   7979:        sprintf(gplotlabel+strlen(gplotlabel)," V%d=%d ",Tvaraff[k],vlv);
                   7980:       }
1.237     brouard  7981:       for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
                   7982:        fprintf(ficgp," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
1.264     brouard  7983:        sprintf(gplotlabel+strlen(gplotlabel)," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
1.237     brouard  7984:       }        
1.264     brouard  7985:       strcpy(gplotlabel+strlen(gplotlabel),")");
1.237     brouard  7986:       fprintf(ficgp,"\n#\n");
1.264     brouard  7987:       fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" ",subdirf2(optionfilefiname,"PE_"),k1,ng,nres);
1.276     brouard  7988:       fprintf(ficgp,"\nset key outside ");
                   7989:       /* fprintf(ficgp,"\nset label \"%s\" at graph 1.2,0.5 center rotate font \"Helvetica,12\"\n",gplotlabel); */
                   7990:       fprintf(ficgp,"\nset title \"%s\" font \"Helvetica,12\"\n",gplotlabel);
1.223     brouard  7991:       fprintf(ficgp,"\nset ter svg size 640, 480 ");
                   7992:       if (ng==1){
                   7993:        fprintf(ficgp,"\nset ylabel \"Value of the logit of the model\"\n"); /* exp(a12+b12*x) could be nice */
                   7994:        fprintf(ficgp,"\nunset log y");
                   7995:       }else if (ng==2){
                   7996:        fprintf(ficgp,"\nset ylabel \"Probability\"\n");
                   7997:        fprintf(ficgp,"\nset log y");
                   7998:       }else if (ng==3){
                   7999:        fprintf(ficgp,"\nset ylabel \"Quasi-incidence per year\"\n");
                   8000:        fprintf(ficgp,"\nset log y");
                   8001:       }else
                   8002:        fprintf(ficgp,"\nunset title ");
                   8003:       fprintf(ficgp,"\nplot  [%.f:%.f] ",ageminpar,agemaxpar);
                   8004:       i=1;
                   8005:       for(k2=1; k2<=nlstate; k2++) {
                   8006:        k3=i;
                   8007:        for(k=1; k<=(nlstate+ndeath); k++) {
                   8008:          if (k != k2){
                   8009:            switch( ng) {
                   8010:            case 1:
                   8011:              if(nagesqr==0)
                   8012:                fprintf(ficgp," p%d+p%d*x",i,i+1);
                   8013:              else /* nagesqr =1 */
                   8014:                fprintf(ficgp," p%d+p%d*x+p%d*x*x",i,i+1,i+1+nagesqr);
                   8015:              break;
                   8016:            case 2: /* ng=2 */
                   8017:              if(nagesqr==0)
                   8018:                fprintf(ficgp," exp(p%d+p%d*x",i,i+1);
                   8019:              else /* nagesqr =1 */
                   8020:                fprintf(ficgp," exp(p%d+p%d*x+p%d*x*x",i,i+1,i+1+nagesqr);
                   8021:              break;
                   8022:            case 3:
                   8023:              if(nagesqr==0)
                   8024:                fprintf(ficgp," %f*exp(p%d+p%d*x",YEARM/stepm,i,i+1);
                   8025:              else /* nagesqr =1 */
                   8026:                fprintf(ficgp," %f*exp(p%d+p%d*x+p%d*x*x",YEARM/stepm,i,i+1,i+1+nagesqr);
                   8027:              break;
                   8028:            }
                   8029:            ij=1;/* To be checked else nbcode[0][0] wrong */
1.237     brouard  8030:            ijp=1; /* product no age */
                   8031:            /* for(j=3; j <=ncovmodel-nagesqr; j++) { */
                   8032:            for(j=1; j <=cptcovt; j++) { /* For each covariate of the simplified model */
1.223     brouard  8033:              /* printf("Tage[%d]=%d, j=%d\n", ij, Tage[ij], j); */
1.268     brouard  8034:              if(cptcovage >0){ /* V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1, 2 V5 and V1 */
                   8035:                if(j==Tage[ij]) { /* Product by age  To be looked at!!*/
                   8036:                  if(ij <=cptcovage) { /* V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1, 2 V5 and V1 */
                   8037:                    if(DummyV[j]==0){
                   8038:                      fprintf(ficgp,"+p%d*%d*x",i+j+2+nagesqr-1,Tinvresult[nres][Tvar[j]]);;
                   8039:                    }else{ /* quantitative */
                   8040:                      fprintf(ficgp,"+p%d*%f*x",i+j+2+nagesqr-1,Tqinvresult[nres][Tvar[j]]); /* Tqinvresult in decoderesult */
                   8041:                      /* fprintf(ficgp,"+p%d*%d*x",i+j+nagesqr-1,nbcode[Tvar[j-2]][codtabm(k1,Tvar[j-2])]); */
                   8042:                    }
                   8043:                    ij++;
1.237     brouard  8044:                  }
1.268     brouard  8045:                } 
                   8046:              }else if(cptcovprod >0){
                   8047:                if(j==Tprod[ijp]) { /* */ 
                   8048:                  /* printf("Tprod[%d]=%d, j=%d\n", ij, Tprod[ijp], j); */
                   8049:                  if(ijp <=cptcovprod) { /* Product */
                   8050:                    if(DummyV[Tvard[ijp][1]]==0){/* Vn is dummy */
                   8051:                      if(DummyV[Tvard[ijp][2]]==0){/* Vn and Vm are dummy */
                   8052:                        /* 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)]); */
                   8053:                        fprintf(ficgp,"+p%d*%d*%d",i+j+2+nagesqr-1,Tinvresult[nres][Tvard[ijp][1]],Tinvresult[nres][Tvard[ijp][2]]);
                   8054:                      }else{ /* Vn is dummy and Vm is quanti */
                   8055:                        /* fprintf(ficgp,"+p%d*%d*%f",i+j+2+nagesqr-1,nbcode[Tvard[ijp][1]][codtabm(k1,j)],Tqinvresult[nres][Tvard[ijp][2]]); */
                   8056:                        fprintf(ficgp,"+p%d*%d*%f",i+j+2+nagesqr-1,Tinvresult[nres][Tvard[ijp][1]],Tqinvresult[nres][Tvard[ijp][2]]);
                   8057:                      }
                   8058:                    }else{ /* Vn*Vm Vn is quanti */
                   8059:                      if(DummyV[Tvard[ijp][2]]==0){
                   8060:                        fprintf(ficgp,"+p%d*%d*%f",i+j+2+nagesqr-1,Tinvresult[nres][Tvard[ijp][2]],Tqinvresult[nres][Tvard[ijp][1]]);
                   8061:                      }else{ /* Both quanti */
                   8062:                        fprintf(ficgp,"+p%d*%f*%f",i+j+2+nagesqr-1,Tqinvresult[nres][Tvard[ijp][1]],Tqinvresult[nres][Tvard[ijp][2]]);
                   8063:                      }
1.237     brouard  8064:                    }
1.268     brouard  8065:                    ijp++;
1.237     brouard  8066:                  }
1.268     brouard  8067:                } /* end Tprod */
1.237     brouard  8068:              } else{  /* simple covariate */
1.264     brouard  8069:                /* fprintf(ficgp,"+p%d*%d",i+j+2+nagesqr-1,nbcode[Tvar[j]][codtabm(k1,j)]); /\* Valgrind bug nbcode *\/ */
1.237     brouard  8070:                if(Dummy[j]==0){
                   8071:                  fprintf(ficgp,"+p%d*%d",i+j+2+nagesqr-1,Tinvresult[nres][Tvar[j]]); /*  */
                   8072:                }else{ /* quantitative */
                   8073:                  fprintf(ficgp,"+p%d*%f",i+j+2+nagesqr-1,Tqinvresult[nres][Tvar[j]]); /* */
1.264     brouard  8074:                  /* fprintf(ficgp,"+p%d*%d*x",i+j+nagesqr-1,nbcode[Tvar[j-2]][codtabm(k1,Tvar[j-2])]); */
1.223     brouard  8075:                }
1.237     brouard  8076:              } /* end simple */
                   8077:            } /* end j */
1.223     brouard  8078:          }else{
                   8079:            i=i-ncovmodel;
                   8080:            if(ng !=1 ) /* For logit formula of log p11 is more difficult to get */
                   8081:              fprintf(ficgp," (1.");
                   8082:          }
1.227     brouard  8083:          
1.223     brouard  8084:          if(ng != 1){
                   8085:            fprintf(ficgp,")/(1");
1.227     brouard  8086:            
1.264     brouard  8087:            for(cpt=1; cpt <=nlstate; cpt++){ 
1.223     brouard  8088:              if(nagesqr==0)
1.264     brouard  8089:                fprintf(ficgp,"+exp(p%d+p%d*x",k3+(cpt-1)*ncovmodel,k3+(cpt-1)*ncovmodel+1);
1.223     brouard  8090:              else /* nagesqr =1 */
1.264     brouard  8091:                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  8092:               
1.223     brouard  8093:              ij=1;
                   8094:              for(j=3; j <=ncovmodel-nagesqr; j++){
1.268     brouard  8095:                 if(cptcovage >0){ 
                   8096:                   if((j-2)==Tage[ij]) { /* Bug valgrind */
                   8097:                     if(ij <=cptcovage) { /* Bug valgrind */
                   8098:                       fprintf(ficgp,"+p%d*%d*x",k3+(cpt-1)*ncovmodel+1+j-2+nagesqr,nbcode[Tvar[j-2]][codtabm(k1,j-2)]);
                   8099:                       /* fprintf(ficgp,"+p%d*%d*x",k3+(cpt-1)*ncovmodel+1+j-2+nagesqr,nbcode[Tvar[j-2]][codtabm(k1,Tvar[j-2])]); */
                   8100:                       ij++;
                   8101:                     }
                   8102:                   }
                   8103:                 }else
                   8104:                   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  8105:              }
                   8106:              fprintf(ficgp,")");
                   8107:            }
                   8108:            fprintf(ficgp,")");
                   8109:            if(ng ==2)
1.276     brouard  8110:              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  8111:            else /* ng= 3 */
1.276     brouard  8112:              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  8113:          }else{ /* end ng <> 1 */
                   8114:            if( k !=k2) /* logit p11 is hard to draw */
1.276     brouard  8115:              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  8116:          }
                   8117:          if ((k+k2)!= (nlstate*2+ndeath) && ng != 1)
                   8118:            fprintf(ficgp,",");
                   8119:          if (ng == 1 && k!=k2 && (k+k2)!= (nlstate*2+ndeath))
                   8120:            fprintf(ficgp,",");
                   8121:          i=i+ncovmodel;
                   8122:        } /* end k */
                   8123:       } /* end k2 */
1.276     brouard  8124:       /* fprintf(ficgp,"\n set out; unset label;set key default;\n"); */
                   8125:       fprintf(ficgp,"\n set out; unset title;set key default;\n");
1.264     brouard  8126:     } /* end k1 */
1.223     brouard  8127:   } /* end ng */
                   8128:   /* avoid: */
                   8129:   fflush(ficgp); 
1.126     brouard  8130: }  /* end gnuplot */
                   8131: 
                   8132: 
                   8133: /*************** Moving average **************/
1.219     brouard  8134: /* int movingaverage(double ***probs, double bage, double fage, double ***mobaverage, int mobilav, double bageout, double fageout){ */
1.222     brouard  8135:  int movingaverage(double ***probs, double bage, double fage, double ***mobaverage, int mobilav){
1.218     brouard  8136:    
1.222     brouard  8137:    int i, cpt, cptcod;
                   8138:    int modcovmax =1;
                   8139:    int mobilavrange, mob;
                   8140:    int iage=0;
1.288     brouard  8141:    int firstA1=0, firstA2=0;
1.222     brouard  8142: 
1.266     brouard  8143:    double sum=0., sumr=0.;
1.222     brouard  8144:    double age;
1.266     brouard  8145:    double *sumnewp, *sumnewm, *sumnewmr;
                   8146:    double *agemingood, *agemaxgood; 
                   8147:    double *agemingoodr, *agemaxgoodr; 
1.222     brouard  8148:   
                   8149:   
1.278     brouard  8150:    /* modcovmax=2*cptcoveff;  Max number of modalities. We suppose  */
                   8151:    /*             a covariate has 2 modalities, should be equal to ncovcombmax   */
1.222     brouard  8152: 
                   8153:    sumnewp = vector(1,ncovcombmax);
                   8154:    sumnewm = vector(1,ncovcombmax);
1.266     brouard  8155:    sumnewmr = vector(1,ncovcombmax);
1.222     brouard  8156:    agemingood = vector(1,ncovcombmax); 
1.266     brouard  8157:    agemingoodr = vector(1,ncovcombmax);        
1.222     brouard  8158:    agemaxgood = vector(1,ncovcombmax);
1.266     brouard  8159:    agemaxgoodr = vector(1,ncovcombmax);
1.222     brouard  8160: 
                   8161:    for (cptcod=1;cptcod<=ncovcombmax;cptcod++){
1.266     brouard  8162:      sumnewm[cptcod]=0.; sumnewmr[cptcod]=0.;
1.222     brouard  8163:      sumnewp[cptcod]=0.;
1.266     brouard  8164:      agemingood[cptcod]=0, agemingoodr[cptcod]=0;
                   8165:      agemaxgood[cptcod]=0, agemaxgoodr[cptcod]=0;
1.222     brouard  8166:    }
                   8167:    if (cptcovn<1) ncovcombmax=1; /* At least 1 pass */
                   8168:   
1.266     brouard  8169:    if(mobilav==-1 || mobilav==1||mobilav ==3 ||mobilav==5 ||mobilav== 7){
                   8170:      if(mobilav==1 || mobilav==-1) mobilavrange=5; /* default */
1.222     brouard  8171:      else mobilavrange=mobilav;
                   8172:      for (age=bage; age<=fage; age++)
                   8173:        for (i=1; i<=nlstate;i++)
                   8174:         for (cptcod=1;cptcod<=ncovcombmax;cptcod++)
                   8175:           mobaverage[(int)age][i][cptcod]=probs[(int)age][i][cptcod];
                   8176:      /* We keep the original values on the extreme ages bage, fage and for 
                   8177:        fage+1 and bage-1 we use a 3 terms moving average; for fage+2 bage+2
                   8178:        we use a 5 terms etc. until the borders are no more concerned. 
                   8179:      */ 
                   8180:      for (mob=3;mob <=mobilavrange;mob=mob+2){
                   8181:        for (age=bage+(mob-1)/2; age<=fage-(mob-1)/2; age++){
1.266     brouard  8182:         for (cptcod=1;cptcod<=ncovcombmax;cptcod++){
                   8183:           sumnewm[cptcod]=0.;
                   8184:           for (i=1; i<=nlstate;i++){
1.222     brouard  8185:             mobaverage[(int)age][i][cptcod] =probs[(int)age][i][cptcod];
                   8186:             for (cpt=1;cpt<=(mob-1)/2;cpt++){
                   8187:               mobaverage[(int)age][i][cptcod] +=probs[(int)age-cpt][i][cptcod];
                   8188:               mobaverage[(int)age][i][cptcod] +=probs[(int)age+cpt][i][cptcod];
                   8189:             }
                   8190:             mobaverage[(int)age][i][cptcod]=mobaverage[(int)age][i][cptcod]/mob;
1.266     brouard  8191:             sumnewm[cptcod]+=mobaverage[(int)age][i][cptcod];
                   8192:           } /* end i */
                   8193:           if(sumnewm[cptcod] >1.e-3) mobaverage[(int)age][i][cptcod]=mobaverage[(int)age][i][cptcod]/sumnewm[cptcod]; /* Rescaling to sum one */
                   8194:         } /* end cptcod */
1.222     brouard  8195:        }/* end age */
                   8196:      }/* end mob */
1.266     brouard  8197:    }else{
                   8198:      printf("Error internal in movingaverage, mobilav=%d.\n",mobilav);
1.222     brouard  8199:      return -1;
1.266     brouard  8200:    }
                   8201: 
                   8202:    for (cptcod=1;cptcod<=ncovcombmax;cptcod++){ /* for each combination */
1.222     brouard  8203:      /* for (age=bage+(mob-1)/2; age<=fage-(mob-1)/2; age++){ */
                   8204:      if(invalidvarcomb[cptcod]){
                   8205:        printf("\nCombination (%d) ignored because no cases \n",cptcod); 
                   8206:        continue;
                   8207:      }
1.219     brouard  8208: 
1.266     brouard  8209:      for (age=fage-(mob-1)/2; age>=bage+(mob-1)/2; age--){ /*looking for the youngest and oldest good age */
                   8210:        sumnewm[cptcod]=0.;
                   8211:        sumnewmr[cptcod]=0.;
                   8212:        for (i=1; i<=nlstate;i++){
                   8213:         sumnewm[cptcod]+=mobaverage[(int)age][i][cptcod];
                   8214:         sumnewmr[cptcod]+=probs[(int)age][i][cptcod];
                   8215:        }
                   8216:        if(fabs(sumnewmr[cptcod] - 1.) <= 1.e-3) { /* good without smoothing */
                   8217:         agemingoodr[cptcod]=age;
                   8218:        }
                   8219:        if(fabs(sumnewm[cptcod] - 1.) <= 1.e-3) { /* good */
                   8220:           agemingood[cptcod]=age;
                   8221:        }
                   8222:      } /* age */
                   8223:      for (age=bage+(mob-1)/2; age<=fage-(mob-1)/2; age++){ /*looking for the youngest and oldest good age */
1.222     brouard  8224:        sumnewm[cptcod]=0.;
1.266     brouard  8225:        sumnewmr[cptcod]=0.;
1.222     brouard  8226:        for (i=1; i<=nlstate;i++){
                   8227:         sumnewm[cptcod]+=mobaverage[(int)age][i][cptcod];
1.266     brouard  8228:         sumnewmr[cptcod]+=probs[(int)age][i][cptcod];
                   8229:        }
                   8230:        if(fabs(sumnewmr[cptcod] - 1.) <= 1.e-3) { /* good without smoothing */
                   8231:         agemaxgoodr[cptcod]=age;
1.222     brouard  8232:        }
                   8233:        if(fabs(sumnewm[cptcod] - 1.) <= 1.e-3) { /* good */
1.266     brouard  8234:         agemaxgood[cptcod]=age;
                   8235:        }
                   8236:      } /* age */
                   8237:      /* Thus we have agemingood and agemaxgood as well as goodr for raw (preobs) */
                   8238:      /* but they will change */
1.288     brouard  8239:      firstA1=0;firstA2=0;
1.266     brouard  8240:      for (age=fage-(mob-1)/2; age>=bage; age--){/* From oldest to youngest, filling up to the youngest */
                   8241:        sumnewm[cptcod]=0.;
                   8242:        sumnewmr[cptcod]=0.;
                   8243:        for (i=1; i<=nlstate;i++){
                   8244:         sumnewm[cptcod]+=mobaverage[(int)age][i][cptcod];
                   8245:         sumnewmr[cptcod]+=probs[(int)age][i][cptcod];
                   8246:        }
                   8247:        if(mobilav==-1){ /* Forcing raw ages if good else agemingood */
                   8248:         if(fabs(sumnewmr[cptcod] - 1.) <= 1.e-3) { /* good without smoothing */
                   8249:           agemaxgoodr[cptcod]=age;  /* age min */
                   8250:           for (i=1; i<=nlstate;i++)
                   8251:             mobaverage[(int)age][i][cptcod]=probs[(int)age][i][cptcod];
                   8252:         }else{ /* bad we change the value with the values of good ages */
                   8253:           for (i=1; i<=nlstate;i++){
                   8254:             mobaverage[(int)age][i][cptcod]=mobaverage[(int)agemaxgoodr[cptcod]][i][cptcod];
                   8255:           } /* i */
                   8256:         } /* end bad */
                   8257:        }else{
                   8258:         if(fabs(sumnewm[cptcod] - 1.) <= 1.e-3) { /* good */
                   8259:           agemaxgood[cptcod]=age;
                   8260:         }else{ /* bad we change the value with the values of good ages */
                   8261:           for (i=1; i<=nlstate;i++){
                   8262:             mobaverage[(int)age][i][cptcod]=mobaverage[(int)agemaxgood[cptcod]][i][cptcod];
                   8263:           } /* i */
                   8264:         } /* end bad */
                   8265:        }/* end else */
                   8266:        sum=0.;sumr=0.;
                   8267:        for (i=1; i<=nlstate;i++){
                   8268:         sum+=mobaverage[(int)age][i][cptcod];
                   8269:         sumr+=probs[(int)age][i][cptcod];
                   8270:        }
                   8271:        if(fabs(sum - 1.) > 1.e-3) { /* bad */
1.288     brouard  8272:         if(!firstA1){
                   8273:           firstA1=1;
                   8274:           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);
                   8275:         }
                   8276:         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  8277:        } /* end bad */
                   8278:        /* else{ /\* We found some ages summing to one, we will smooth the oldest *\/ */
                   8279:        if(fabs(sumr - 1.) > 1.e-3) { /* bad */
1.288     brouard  8280:         if(!firstA2){
                   8281:           firstA2=1;
                   8282:           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);
                   8283:         }
                   8284:         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  8285:        } /* end bad */
                   8286:      }/* age */
1.266     brouard  8287: 
                   8288:      for (age=bage+(mob-1)/2; age<=fage; age++){/* From youngest, finding the oldest wrong */
1.222     brouard  8289:        sumnewm[cptcod]=0.;
1.266     brouard  8290:        sumnewmr[cptcod]=0.;
1.222     brouard  8291:        for (i=1; i<=nlstate;i++){
                   8292:         sumnewm[cptcod]+=mobaverage[(int)age][i][cptcod];
1.266     brouard  8293:         sumnewmr[cptcod]+=probs[(int)age][i][cptcod];
                   8294:        } 
                   8295:        if(mobilav==-1){ /* Forcing raw ages if good else agemingood */
                   8296:         if(fabs(sumnewmr[cptcod] - 1.) <= 1.e-3) { /* good */
                   8297:           agemingoodr[cptcod]=age;
                   8298:           for (i=1; i<=nlstate;i++)
                   8299:             mobaverage[(int)age][i][cptcod]=probs[(int)age][i][cptcod];
                   8300:         }else{ /* bad we change the value with the values of good ages */
                   8301:           for (i=1; i<=nlstate;i++){
                   8302:             mobaverage[(int)age][i][cptcod]=mobaverage[(int)agemingoodr[cptcod]][i][cptcod];
                   8303:           } /* i */
                   8304:         } /* end bad */
                   8305:        }else{
                   8306:         if(fabs(sumnewm[cptcod] - 1.) <= 1.e-3) { /* good */
                   8307:           agemingood[cptcod]=age;
                   8308:         }else{ /* bad */
                   8309:           for (i=1; i<=nlstate;i++){
                   8310:             mobaverage[(int)age][i][cptcod]=mobaverage[(int)agemingood[cptcod]][i][cptcod];
                   8311:           } /* i */
                   8312:         } /* end bad */
                   8313:        }/* end else */
                   8314:        sum=0.;sumr=0.;
                   8315:        for (i=1; i<=nlstate;i++){
                   8316:         sum+=mobaverage[(int)age][i][cptcod];
                   8317:         sumr+=mobaverage[(int)age][i][cptcod];
1.222     brouard  8318:        }
1.266     brouard  8319:        if(fabs(sum - 1.) > 1.e-3) { /* bad */
1.268     brouard  8320:         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  8321:        } /* end bad */
                   8322:        /* else{ /\* We found some ages summing to one, we will smooth the oldest *\/ */
                   8323:        if(fabs(sumr - 1.) > 1.e-3) { /* bad */
1.268     brouard  8324:         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  8325:        } /* end bad */
                   8326:      }/* age */
1.266     brouard  8327: 
1.222     brouard  8328:                
                   8329:      for (age=bage; age<=fage; age++){
1.235     brouard  8330:        /* printf("%d %d ", cptcod, (int)age); */
1.222     brouard  8331:        sumnewp[cptcod]=0.;
                   8332:        sumnewm[cptcod]=0.;
                   8333:        for (i=1; i<=nlstate;i++){
                   8334:         sumnewp[cptcod]+=probs[(int)age][i][cptcod];
                   8335:         sumnewm[cptcod]+=mobaverage[(int)age][i][cptcod];
                   8336:         /* printf("%.4f %.4f ",probs[(int)age][i][cptcod], mobaverage[(int)age][i][cptcod]); */
                   8337:        }
                   8338:        /* printf("%.4f %.4f \n",sumnewp[cptcod], sumnewm[cptcod]); */
                   8339:      }
                   8340:      /* printf("\n"); */
                   8341:      /* } */
1.266     brouard  8342: 
1.222     brouard  8343:      /* brutal averaging */
1.266     brouard  8344:      /* for (i=1; i<=nlstate;i++){ */
                   8345:      /*   for (age=1; age<=bage; age++){ */
                   8346:      /*         mobaverage[(int)age][i][cptcod]=mobaverage[(int)agemingood[cptcod]][i][cptcod]; */
                   8347:      /*         /\* printf("age=%d i=%d cptcod=%d mobaverage=%.4f \n",(int)age,i, cptcod, mobaverage[(int)age][i][cptcod]); *\/ */
                   8348:      /*   }     */
                   8349:      /*   for (age=fage; age<=AGESUP; age++){ */
                   8350:      /*         mobaverage[(int)age][i][cptcod]=mobaverage[(int)agemaxgood[cptcod]][i][cptcod]; */
                   8351:      /*         /\* printf("age=%d i=%d cptcod=%d mobaverage=%.4f \n",(int)age,i, cptcod, mobaverage[(int)age][i][cptcod]); *\/ */
                   8352:      /*   } */
                   8353:      /* } /\* end i status *\/ */
                   8354:      /* for (i=nlstate+1; i<=nlstate+ndeath;i++){ */
                   8355:      /*   for (age=1; age<=AGESUP; age++){ */
                   8356:      /*         /\*printf("i=%d, age=%d, cptcod=%d\n",i, (int)age, cptcod);*\/ */
                   8357:      /*         mobaverage[(int)age][i][cptcod]=0.; */
                   8358:      /*   } */
                   8359:      /* } */
1.222     brouard  8360:    }/* end cptcod */
1.266     brouard  8361:    free_vector(agemaxgoodr,1, ncovcombmax);
                   8362:    free_vector(agemaxgood,1, ncovcombmax);
                   8363:    free_vector(agemingood,1, ncovcombmax);
                   8364:    free_vector(agemingoodr,1, ncovcombmax);
                   8365:    free_vector(sumnewmr,1, ncovcombmax);
1.222     brouard  8366:    free_vector(sumnewm,1, ncovcombmax);
                   8367:    free_vector(sumnewp,1, ncovcombmax);
                   8368:    return 0;
                   8369:  }/* End movingaverage */
1.218     brouard  8370:  
1.126     brouard  8371: 
1.296     brouard  8372:  
1.126     brouard  8373: /************** Forecasting ******************/
1.296     brouard  8374: /* 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)*/
                   8375: 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){
                   8376:   /* dateintemean, mean date of interviews
                   8377:      dateprojd, year, month, day of starting projection 
                   8378:      dateprojf date of end of projection;year of end of projection (same day and month as proj1).
1.126     brouard  8379:      agemin, agemax range of age
                   8380:      dateprev1 dateprev2 range of dates during which prevalence is computed
                   8381:   */
1.296     brouard  8382:   /* double anprojd, mprojd, jprojd; */
                   8383:   /* double anprojf, mprojf, jprojf; */
1.267     brouard  8384:   int yearp, stepsize, hstepm, nhstepm, j, k, cptcod, i, h, i1, k4, nres=0;
1.126     brouard  8385:   double agec; /* generic age */
1.296     brouard  8386:   double agelim, ppij, yp,yp1,yp2;
1.126     brouard  8387:   double *popeffectif,*popcount;
                   8388:   double ***p3mat;
1.218     brouard  8389:   /* double ***mobaverage; */
1.126     brouard  8390:   char fileresf[FILENAMELENGTH];
                   8391: 
                   8392:   agelim=AGESUP;
1.211     brouard  8393:   /* Compute observed prevalence between dateprev1 and dateprev2 by counting the number of people
                   8394:      in each health status at the date of interview (if between dateprev1 and dateprev2).
                   8395:      We still use firstpass and lastpass as another selection.
                   8396:   */
1.214     brouard  8397:   /* freqsummary(fileres, agemin, agemax, s, agev, nlstate, imx,Tvaraff,nbcode, ncodemax,mint,anint,strstart,\ */
                   8398:   /*         firstpass, lastpass,  stepm,  weightopt, model); */
1.126     brouard  8399:  
1.201     brouard  8400:   strcpy(fileresf,"F_"); 
                   8401:   strcat(fileresf,fileresu);
1.126     brouard  8402:   if((ficresf=fopen(fileresf,"w"))==NULL) {
                   8403:     printf("Problem with forecast resultfile: %s\n", fileresf);
                   8404:     fprintf(ficlog,"Problem with forecast resultfile: %s\n", fileresf);
                   8405:   }
1.235     brouard  8406:   printf("\nComputing forecasting: result on file '%s', please wait... \n", fileresf);
                   8407:   fprintf(ficlog,"\nComputing forecasting: result on file '%s', please wait... \n", fileresf);
1.126     brouard  8408: 
1.225     brouard  8409:   if (cptcoveff==0) ncodemax[cptcoveff]=1;
1.126     brouard  8410: 
                   8411: 
                   8412:   stepsize=(int) (stepm+YEARM-1)/YEARM;
                   8413:   if (stepm<=12) stepsize=1;
                   8414:   if(estepm < stepm){
                   8415:     printf ("Problem %d lower than %d\n",estepm, stepm);
                   8416:   }
1.270     brouard  8417:   else{
                   8418:     hstepm=estepm;   
                   8419:   }
                   8420:   if(estepm > stepm){ /* Yes every two year */
                   8421:     stepsize=2;
                   8422:   }
1.296     brouard  8423:   hstepm=hstepm/stepm;
1.126     brouard  8424: 
1.296     brouard  8425:   
                   8426:   /* yp1=modf(dateintmean,&yp);/\* extracts integral of datemean in yp  and */
                   8427:   /*                              fractional in yp1 *\/ */
                   8428:   /* aintmean=yp; */
                   8429:   /* yp2=modf((yp1*12),&yp); */
                   8430:   /* mintmean=yp; */
                   8431:   /* yp1=modf((yp2*30.5),&yp); */
                   8432:   /* jintmean=yp; */
                   8433:   /* if(jintmean==0) jintmean=1; */
                   8434:   /* if(mintmean==0) mintmean=1; */
1.126     brouard  8435: 
1.296     brouard  8436: 
                   8437:   /* date2dmy(dateintmean,&jintmean,&mintmean,&aintmean); */
                   8438:   /* date2dmy(dateprojd,&jprojd, &mprojd, &anprojd); */
                   8439:   /* date2dmy(dateprojf,&jprojf, &mprojf, &anprojf); */
1.227     brouard  8440:   i1=pow(2,cptcoveff);
1.126     brouard  8441:   if (cptcovn < 1){i1=1;}
                   8442:   
1.296     brouard  8443:   fprintf(ficresf,"# Mean day of interviews %.lf/%.lf/%.lf (%.2f) between %.2f and %.2f \n",jintmean,mintmean,aintmean,dateintmean,dateprev1,dateprev2); 
1.126     brouard  8444:   
                   8445:   fprintf(ficresf,"#****** Routine prevforecast **\n");
1.227     brouard  8446:   
1.126     brouard  8447: /*           if (h==(int)(YEARM*yearp)){ */
1.235     brouard  8448:   for(nres=1; nres <= nresult; nres++) /* For each resultline */
                   8449:   for(k=1; k<=i1;k++){
1.253     brouard  8450:     if(i1 != 1 && TKresult[nres]!= k)
1.235     brouard  8451:       continue;
1.227     brouard  8452:     if(invalidvarcomb[k]){
                   8453:       printf("\nCombination (%d) projection ignored because no cases \n",k); 
                   8454:       continue;
                   8455:     }
                   8456:     fprintf(ficresf,"\n#****** hpijx=probability over h years, hp.jx is weighted by observed prev \n#");
                   8457:     for(j=1;j<=cptcoveff;j++) {
                   8458:       fprintf(ficresf," V%d (=) %d",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   8459:     }
1.235     brouard  8460:     for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
1.238     brouard  8461:       fprintf(ficresf," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
1.235     brouard  8462:     }
1.227     brouard  8463:     fprintf(ficresf," yearproj age");
                   8464:     for(j=1; j<=nlstate+ndeath;j++){ 
                   8465:       for(i=1; i<=nlstate;i++)               
                   8466:        fprintf(ficresf," p%d%d",i,j);
                   8467:       fprintf(ficresf," wp.%d",j);
                   8468:     }
1.296     brouard  8469:     for (yearp=0; yearp<=(anprojf-anprojd);yearp +=stepsize) {
1.227     brouard  8470:       fprintf(ficresf,"\n");
1.296     brouard  8471:       fprintf(ficresf,"\n# Forecasting at date %.lf/%.lf/%.lf ",jprojd,mprojd,anprojd+yearp);   
1.270     brouard  8472:       /* for (agec=fage; agec>=(ageminpar-1); agec--){  */
                   8473:       for (agec=fage; agec>=(bage); agec--){ 
1.227     brouard  8474:        nhstepm=(int) rint((agelim-agec)*YEARM/stepm); 
                   8475:        nhstepm = nhstepm/hstepm; 
                   8476:        p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   8477:        oldm=oldms;savm=savms;
1.268     brouard  8478:        /* We compute pii at age agec over nhstepm);*/
1.235     brouard  8479:        hpxij(p3mat,nhstepm,agec,hstepm,p,nlstate,stepm,oldm,savm, k,nres);
1.268     brouard  8480:        /* Then we print p3mat for h corresponding to the right agec+h*stepms=yearp */
1.227     brouard  8481:        for (h=0; h<=nhstepm; h++){
                   8482:          if (h*hstepm/YEARM*stepm ==yearp) {
1.268     brouard  8483:            break;
                   8484:          }
                   8485:        }
                   8486:        fprintf(ficresf,"\n");
                   8487:        for(j=1;j<=cptcoveff;j++) 
                   8488:          fprintf(ficresf,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
1.296     brouard  8489:        fprintf(ficresf,"%.f %.f ",anprojd+yearp,agec+h*hstepm/YEARM*stepm);
1.268     brouard  8490:        
                   8491:        for(j=1; j<=nlstate+ndeath;j++) {
                   8492:          ppij=0.;
                   8493:          for(i=1; i<=nlstate;i++) {
1.278     brouard  8494:            if (mobilav>=1)
                   8495:             ppij=ppij+p3mat[i][j][h]*prev[(int)agec][i][k];
                   8496:            else { /* even if mobilav==-1 we use mobaverage, probs may not sums to 1 */
                   8497:                ppij=ppij+p3mat[i][j][h]*probs[(int)(agec)][i][k];
                   8498:            }
1.268     brouard  8499:            fprintf(ficresf," %.3f", p3mat[i][j][h]);
                   8500:          } /* end i */
                   8501:          fprintf(ficresf," %.3f", ppij);
                   8502:        }/* end j */
1.227     brouard  8503:        free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   8504:       } /* end agec */
1.266     brouard  8505:       /* diffyear=(int) anproj1+yearp-ageminpar-1; */
                   8506:       /*printf("Prevforecast %d+%d-%d=diffyear=%d\n",(int) anproj1, (int)yearp,(int)ageminpar,(int) anproj1-(int)ageminpar);*/
1.227     brouard  8507:     } /* end yearp */
                   8508:   } /* end  k */
1.219     brouard  8509:        
1.126     brouard  8510:   fclose(ficresf);
1.215     brouard  8511:   printf("End of Computing forecasting \n");
                   8512:   fprintf(ficlog,"End of Computing forecasting\n");
                   8513: 
1.126     brouard  8514: }
                   8515: 
1.269     brouard  8516: /************** Back Forecasting ******************/
1.296     brouard  8517:  /* 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){ */
                   8518:  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){
                   8519:   /* back1, year, month, day of starting backprojection
1.267     brouard  8520:      agemin, agemax range of age
                   8521:      dateprev1 dateprev2 range of dates during which prevalence is computed
1.269     brouard  8522:      anback2 year of end of backprojection (same day and month as back1).
                   8523:      prevacurrent and prev are prevalences.
1.267     brouard  8524:   */
                   8525:   int yearp, stepsize, hstepm, nhstepm, j, k, cptcod, i, h, i1, k4, nres=0;
                   8526:   double agec; /* generic age */
1.302     brouard  8527:   double agelim, ppij, ppi, yp,yp1,yp2; /* ,jintmean,mintmean,aintmean;*/
1.267     brouard  8528:   double *popeffectif,*popcount;
                   8529:   double ***p3mat;
                   8530:   /* double ***mobaverage; */
                   8531:   char fileresfb[FILENAMELENGTH];
                   8532:  
1.268     brouard  8533:   agelim=AGEINF;
1.267     brouard  8534:   /* Compute observed prevalence between dateprev1 and dateprev2 by counting the number of people
                   8535:      in each health status at the date of interview (if between dateprev1 and dateprev2).
                   8536:      We still use firstpass and lastpass as another selection.
                   8537:   */
                   8538:   /* freqsummary(fileres, agemin, agemax, s, agev, nlstate, imx,Tvaraff,nbcode, ncodemax,mint,anint,strstart,\ */
                   8539:   /*         firstpass, lastpass,  stepm,  weightopt, model); */
                   8540: 
                   8541:   /*Do we need to compute prevalence again?*/
                   8542: 
                   8543:   /* prevalence(probs, ageminpar, agemax, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass); */
                   8544:   
                   8545:   strcpy(fileresfb,"FB_");
                   8546:   strcat(fileresfb,fileresu);
                   8547:   if((ficresfb=fopen(fileresfb,"w"))==NULL) {
                   8548:     printf("Problem with back forecast resultfile: %s\n", fileresfb);
                   8549:     fprintf(ficlog,"Problem with back forecast resultfile: %s\n", fileresfb);
                   8550:   }
                   8551:   printf("\nComputing back forecasting: result on file '%s', please wait... \n", fileresfb);
                   8552:   fprintf(ficlog,"\nComputing back forecasting: result on file '%s', please wait... \n", fileresfb);
                   8553:   
                   8554:   if (cptcoveff==0) ncodemax[cptcoveff]=1;
                   8555:   
                   8556:    
                   8557:   stepsize=(int) (stepm+YEARM-1)/YEARM;
                   8558:   if (stepm<=12) stepsize=1;
                   8559:   if(estepm < stepm){
                   8560:     printf ("Problem %d lower than %d\n",estepm, stepm);
                   8561:   }
1.270     brouard  8562:   else{
                   8563:     hstepm=estepm;   
                   8564:   }
                   8565:   if(estepm >= stepm){ /* Yes every two year */
                   8566:     stepsize=2;
                   8567:   }
1.267     brouard  8568:   
                   8569:   hstepm=hstepm/stepm;
1.296     brouard  8570:   /* yp1=modf(dateintmean,&yp);/\* extracts integral of datemean in yp  and */
                   8571:   /*                              fractional in yp1 *\/ */
                   8572:   /* aintmean=yp; */
                   8573:   /* yp2=modf((yp1*12),&yp); */
                   8574:   /* mintmean=yp; */
                   8575:   /* yp1=modf((yp2*30.5),&yp); */
                   8576:   /* jintmean=yp; */
                   8577:   /* if(jintmean==0) jintmean=1; */
                   8578:   /* if(mintmean==0) jintmean=1; */
1.267     brouard  8579:   
                   8580:   i1=pow(2,cptcoveff);
                   8581:   if (cptcovn < 1){i1=1;}
                   8582:   
1.296     brouard  8583:   fprintf(ficresfb,"# Mean day of interviews %.lf/%.lf/%.lf (%.2f) between %.2f and %.2f \n",jintmean,mintmean,aintmean,dateintmean,dateprev1,dateprev2);
                   8584:   printf("# Mean day of interviews %.lf/%.lf/%.lf (%.2f) between %.2f and %.2f \n",jintmean,mintmean,aintmean,dateintmean,dateprev1,dateprev2);
1.267     brouard  8585:   
                   8586:   fprintf(ficresfb,"#****** Routine prevbackforecast **\n");
                   8587:   
                   8588:   for(nres=1; nres <= nresult; nres++) /* For each resultline */
                   8589:   for(k=1; k<=i1;k++){
                   8590:     if(i1 != 1 && TKresult[nres]!= k)
                   8591:       continue;
                   8592:     if(invalidvarcomb[k]){
                   8593:       printf("\nCombination (%d) projection ignored because no cases \n",k); 
                   8594:       continue;
                   8595:     }
1.268     brouard  8596:     fprintf(ficresfb,"\n#****** hbijx=probability over h years, hb.jx is weighted by observed prev \n#");
1.267     brouard  8597:     for(j=1;j<=cptcoveff;j++) {
                   8598:       fprintf(ficresfb," V%d (=) %d",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   8599:     }
                   8600:     for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
                   8601:       fprintf(ficresf," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
                   8602:     }
                   8603:     fprintf(ficresfb," yearbproj age");
                   8604:     for(j=1; j<=nlstate+ndeath;j++){
                   8605:       for(i=1; i<=nlstate;i++)
1.268     brouard  8606:        fprintf(ficresfb," b%d%d",i,j);
                   8607:       fprintf(ficresfb," b.%d",j);
1.267     brouard  8608:     }
1.296     brouard  8609:     for (yearp=0; yearp>=(anbackf-anbackd);yearp -=stepsize) {
1.267     brouard  8610:       /* for (yearp=0; yearp<=(anproj2-anproj1);yearp +=stepsize) {  */
                   8611:       fprintf(ficresfb,"\n");
1.296     brouard  8612:       fprintf(ficresfb,"\n# Back Forecasting at date %.lf/%.lf/%.lf ",jbackd,mbackd,anbackd+yearp);
1.273     brouard  8613:       /* printf("\n# Back Forecasting at date %.lf/%.lf/%.lf ",jback1,mback1,anback1+yearp); */
1.270     brouard  8614:       /* for (agec=bage; agec<=agemax-1; agec++){  /\* testing *\/ */
                   8615:       for (agec=bage; agec<=fage; agec++){  /* testing */
1.268     brouard  8616:        /* We compute bij at age agec over nhstepm, nhstepm decreases when agec increases because of agemax;*/
1.271     brouard  8617:        nhstepm=(int) (agec-agelim) *YEARM/stepm;/*     nhstepm=(int) rint((agec-agelim)*YEARM/stepm);*/
1.267     brouard  8618:        nhstepm = nhstepm/hstepm;
                   8619:        p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   8620:        oldm=oldms;savm=savms;
1.268     brouard  8621:        /* computes hbxij at age agec over 1 to nhstepm */
1.271     brouard  8622:        /* printf("####prevbackforecast debug  agec=%.2f nhstepm=%d\n",agec, nhstepm);fflush(stdout); */
1.267     brouard  8623:        hbxij(p3mat,nhstepm,agec,hstepm,p,prevacurrent,nlstate,stepm, k, nres);
1.268     brouard  8624:        /* hpxij(p3mat,nhstepm,agec,hstepm,p,             nlstate,stepm,oldm,savm, k,nres); */
                   8625:        /* Then we print p3mat for h corresponding to the right agec+h*stepms=yearp */
                   8626:        /* printf(" agec=%.2f\n",agec);fflush(stdout); */
1.267     brouard  8627:        for (h=0; h<=nhstepm; h++){
1.268     brouard  8628:          if (h*hstepm/YEARM*stepm ==-yearp) {
                   8629:            break;
                   8630:          }
                   8631:        }
                   8632:        fprintf(ficresfb,"\n");
                   8633:        for(j=1;j<=cptcoveff;j++)
                   8634:          fprintf(ficresfb,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
1.296     brouard  8635:        fprintf(ficresfb,"%.f %.f ",anbackd+yearp,agec-h*hstepm/YEARM*stepm);
1.268     brouard  8636:        for(i=1; i<=nlstate+ndeath;i++) {
                   8637:          ppij=0.;ppi=0.;
                   8638:          for(j=1; j<=nlstate;j++) {
                   8639:            /* if (mobilav==1) */
1.269     brouard  8640:            ppij=ppij+p3mat[i][j][h]*prevacurrent[(int)agec][j][k];
                   8641:            ppi=ppi+prevacurrent[(int)agec][j][k];
                   8642:            /* ppij=ppij+p3mat[i][j][h]*mobaverage[(int)agec][j][k]; */
                   8643:            /* ppi=ppi+mobaverage[(int)agec][j][k]; */
1.267     brouard  8644:              /* else { */
                   8645:              /*        ppij=ppij+p3mat[i][j][h]*probs[(int)(agec)][i][k]; */
                   8646:              /* } */
1.268     brouard  8647:            fprintf(ficresfb," %.3f", p3mat[i][j][h]);
                   8648:          } /* end j */
                   8649:          if(ppi <0.99){
                   8650:            printf("Error in prevbackforecast, prevalence doesn't sum to 1 for state %d: %3f\n",i, ppi);
                   8651:            fprintf(ficlog,"Error in prevbackforecast, prevalence doesn't sum to 1 for state %d: %3f\n",i, ppi);
                   8652:          }
                   8653:          fprintf(ficresfb," %.3f", ppij);
                   8654:        }/* end j */
1.267     brouard  8655:        free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   8656:       } /* end agec */
                   8657:     } /* end yearp */
                   8658:   } /* end k */
1.217     brouard  8659:   
1.267     brouard  8660:   /* if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX); */
1.217     brouard  8661:   
1.267     brouard  8662:   fclose(ficresfb);
                   8663:   printf("End of Computing Back forecasting \n");
                   8664:   fprintf(ficlog,"End of Computing Back forecasting\n");
1.218     brouard  8665:        
1.267     brouard  8666: }
1.217     brouard  8667: 
1.269     brouard  8668: /* Variance of prevalence limit: varprlim */
                   8669:  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  8670:     /*------- Variance of forward period (stable) prevalence------*/   
1.269     brouard  8671:  
                   8672:    char fileresvpl[FILENAMELENGTH];  
                   8673:    FILE *ficresvpl;
                   8674:    double **oldm, **savm;
                   8675:    double **varpl; /* Variances of prevalence limits by age */   
                   8676:    int i1, k, nres, j ;
                   8677:    
                   8678:     strcpy(fileresvpl,"VPL_");
                   8679:     strcat(fileresvpl,fileresu);
                   8680:     if((ficresvpl=fopen(fileresvpl,"w"))==NULL) {
1.288     brouard  8681:       printf("Problem with variance of forward period (stable) prevalence  resultfile: %s\n", fileresvpl);
1.269     brouard  8682:       exit(0);
                   8683:     }
1.288     brouard  8684:     printf("Computing Variance-covariance of forward period (stable) prevalence: file '%s' ...", fileresvpl);fflush(stdout);
                   8685:     fprintf(ficlog, "Computing Variance-covariance of forward period (stable) prevalence: file '%s' ...", fileresvpl);fflush(ficlog);
1.269     brouard  8686:     
                   8687:     /*for(cptcov=1,k=0;cptcov<=i1;cptcov++){
                   8688:       for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*/
                   8689:     
                   8690:     i1=pow(2,cptcoveff);
                   8691:     if (cptcovn < 1){i1=1;}
                   8692: 
                   8693:     for(nres=1; nres <= nresult; nres++) /* For each resultline */
                   8694:     for(k=1; k<=i1;k++){
                   8695:       if(i1 != 1 && TKresult[nres]!= k)
                   8696:        continue;
                   8697:       fprintf(ficresvpl,"\n#****** ");
                   8698:       printf("\n#****** ");
                   8699:       fprintf(ficlog,"\n#****** ");
                   8700:       for(j=1;j<=cptcoveff;j++) {
                   8701:        fprintf(ficresvpl,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   8702:        fprintf(ficlog,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   8703:        printf("V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   8704:       }
                   8705:       for (j=1; j<= nsq; j++){ /* For each selected (single) quantitative value */
                   8706:        printf(" V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]);
                   8707:        fprintf(ficresvpl," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]);
                   8708:        fprintf(ficlog," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]);
                   8709:       }        
                   8710:       fprintf(ficresvpl,"******\n");
                   8711:       printf("******\n");
                   8712:       fprintf(ficlog,"******\n");
                   8713:       
                   8714:       varpl=matrix(1,nlstate,(int) bage, (int) fage);
                   8715:       oldm=oldms;savm=savms;
                   8716:       varprevlim(fileresvpl, ficresvpl, varpl, matcov, p, delti, nlstate, stepm, (int) bage, (int) fage, oldm, savm, prlim, ftolpl, ncvyearp, k, strstart, nres);
                   8717:       free_matrix(varpl,1,nlstate,(int) bage, (int)fage);
                   8718:       /*}*/
                   8719:     }
                   8720:     
                   8721:     fclose(ficresvpl);
1.288     brouard  8722:     printf("done variance-covariance of forward period prevalence\n");fflush(stdout);
                   8723:     fprintf(ficlog,"done variance-covariance of forward period prevalence\n");fflush(ficlog);
1.269     brouard  8724: 
                   8725:  }
                   8726: /* Variance of back prevalence: varbprlim */
                   8727:  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){
                   8728:       /*------- Variance of back (stable) prevalence------*/
                   8729: 
                   8730:    char fileresvbl[FILENAMELENGTH];  
                   8731:    FILE  *ficresvbl;
                   8732: 
                   8733:    double **oldm, **savm;
                   8734:    double **varbpl; /* Variances of back prevalence limits by age */   
                   8735:    int i1, k, nres, j ;
                   8736: 
                   8737:    strcpy(fileresvbl,"VBL_");
                   8738:    strcat(fileresvbl,fileresu);
                   8739:    if((ficresvbl=fopen(fileresvbl,"w"))==NULL) {
                   8740:      printf("Problem with variance of back (stable) prevalence  resultfile: %s\n", fileresvbl);
                   8741:      exit(0);
                   8742:    }
                   8743:    printf("Computing Variance-covariance of back (stable) prevalence: file '%s' ...", fileresvbl);fflush(stdout);
                   8744:    fprintf(ficlog, "Computing Variance-covariance of back (stable) prevalence: file '%s' ...", fileresvbl);fflush(ficlog);
                   8745:    
                   8746:    
                   8747:    i1=pow(2,cptcoveff);
                   8748:    if (cptcovn < 1){i1=1;}
                   8749:    
                   8750:    for(nres=1; nres <= nresult; nres++) /* For each resultline */
                   8751:      for(k=1; k<=i1;k++){
                   8752:        if(i1 != 1 && TKresult[nres]!= k)
                   8753:         continue;
                   8754:        fprintf(ficresvbl,"\n#****** ");
                   8755:        printf("\n#****** ");
                   8756:        fprintf(ficlog,"\n#****** ");
                   8757:        for(j=1;j<=cptcoveff;j++) {
                   8758:         fprintf(ficresvbl,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   8759:         fprintf(ficlog,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   8760:         printf("V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   8761:        }
                   8762:        for (j=1; j<= nsq; j++){ /* For each selected (single) quantitative value */
                   8763:         printf(" V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]);
                   8764:         fprintf(ficresvbl," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]);
                   8765:         fprintf(ficlog," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]);
                   8766:        }
                   8767:        fprintf(ficresvbl,"******\n");
                   8768:        printf("******\n");
                   8769:        fprintf(ficlog,"******\n");
                   8770:        
                   8771:        varbpl=matrix(1,nlstate,(int) bage, (int) fage);
                   8772:        oldm=oldms;savm=savms;
                   8773:        
                   8774:        varbrevlim(fileresvbl, ficresvbl, varbpl, matcov, p, delti, nlstate, stepm, (int) bage, (int) fage, oldm, savm, bprlim, ftolpl, mobilavproj, ncvyearp, k, strstart, nres);
                   8775:        free_matrix(varbpl,1,nlstate,(int) bage, (int)fage);
                   8776:        /*}*/
                   8777:      }
                   8778:    
                   8779:    fclose(ficresvbl);
                   8780:    printf("done variance-covariance of back prevalence\n");fflush(stdout);
                   8781:    fprintf(ficlog,"done variance-covariance of back prevalence\n");fflush(ficlog);
                   8782: 
                   8783:  } /* End of varbprlim */
                   8784: 
1.126     brouard  8785: /************** Forecasting *****not tested NB*************/
1.227     brouard  8786: /* 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  8787:   
1.227     brouard  8788: /*   int cpt, stepsize, hstepm, nhstepm, j,k,c, cptcod, i,h; */
                   8789: /*   int *popage; */
                   8790: /*   double calagedatem, agelim, kk1, kk2; */
                   8791: /*   double *popeffectif,*popcount; */
                   8792: /*   double ***p3mat,***tabpop,***tabpopprev; */
                   8793: /*   /\* double ***mobaverage; *\/ */
                   8794: /*   char filerespop[FILENAMELENGTH]; */
1.126     brouard  8795: 
1.227     brouard  8796: /*   tabpop= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX); */
                   8797: /*   tabpopprev= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX); */
                   8798: /*   agelim=AGESUP; */
                   8799: /*   calagedatem=(anpyram+mpyram/12.+jpyram/365.-dateintmean)*YEARM; */
1.126     brouard  8800:   
1.227     brouard  8801: /*   prevalence(probs, ageminpar, agemax, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass); */
1.126     brouard  8802:   
                   8803:   
1.227     brouard  8804: /*   strcpy(filerespop,"POP_");  */
                   8805: /*   strcat(filerespop,fileresu); */
                   8806: /*   if((ficrespop=fopen(filerespop,"w"))==NULL) { */
                   8807: /*     printf("Problem with forecast resultfile: %s\n", filerespop); */
                   8808: /*     fprintf(ficlog,"Problem with forecast resultfile: %s\n", filerespop); */
                   8809: /*   } */
                   8810: /*   printf("Computing forecasting: result on file '%s' \n", filerespop); */
                   8811: /*   fprintf(ficlog,"Computing forecasting: result on file '%s' \n", filerespop); */
1.126     brouard  8812: 
1.227     brouard  8813: /*   if (cptcoveff==0) ncodemax[cptcoveff]=1; */
1.126     brouard  8814: 
1.227     brouard  8815: /*   /\* if (mobilav!=0) { *\/ */
                   8816: /*   /\*   mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX); *\/ */
                   8817: /*   /\*   if (movingaverage(probs, ageminpar, fage, mobaverage,mobilav)!=0){ *\/ */
                   8818: /*   /\*     fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav); *\/ */
                   8819: /*   /\*     printf(" Error in movingaverage mobilav=%d\n",mobilav); *\/ */
                   8820: /*   /\*   } *\/ */
                   8821: /*   /\* } *\/ */
1.126     brouard  8822: 
1.227     brouard  8823: /*   stepsize=(int) (stepm+YEARM-1)/YEARM; */
                   8824: /*   if (stepm<=12) stepsize=1; */
1.126     brouard  8825:   
1.227     brouard  8826: /*   agelim=AGESUP; */
1.126     brouard  8827:   
1.227     brouard  8828: /*   hstepm=1; */
                   8829: /*   hstepm=hstepm/stepm;  */
1.218     brouard  8830:        
1.227     brouard  8831: /*   if (popforecast==1) { */
                   8832: /*     if((ficpop=fopen(popfile,"r"))==NULL) { */
                   8833: /*       printf("Problem with population file : %s\n",popfile);exit(0); */
                   8834: /*       fprintf(ficlog,"Problem with population file : %s\n",popfile);exit(0); */
                   8835: /*     }  */
                   8836: /*     popage=ivector(0,AGESUP); */
                   8837: /*     popeffectif=vector(0,AGESUP); */
                   8838: /*     popcount=vector(0,AGESUP); */
1.126     brouard  8839:     
1.227     brouard  8840: /*     i=1;    */
                   8841: /*     while ((c=fscanf(ficpop,"%d %lf\n",&popage[i],&popcount[i])) != EOF) i=i+1; */
1.218     brouard  8842:     
1.227     brouard  8843: /*     imx=i; */
                   8844: /*     for (i=1; i<imx;i++) popeffectif[popage[i]]=popcount[i]; */
                   8845: /*   } */
1.218     brouard  8846:   
1.227     brouard  8847: /*   for(cptcov=1,k=0;cptcov<=i2;cptcov++){ */
                   8848: /*     for(cptcod=1;cptcod<=ncodemax[cptcoveff];cptcod++){ */
                   8849: /*       k=k+1; */
                   8850: /*       fprintf(ficrespop,"\n#******"); */
                   8851: /*       for(j=1;j<=cptcoveff;j++) { */
                   8852: /*     fprintf(ficrespop," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]); */
                   8853: /*       } */
                   8854: /*       fprintf(ficrespop,"******\n"); */
                   8855: /*       fprintf(ficrespop,"# Age"); */
                   8856: /*       for(j=1; j<=nlstate+ndeath;j++) fprintf(ficrespop," P.%d",j); */
                   8857: /*       if (popforecast==1)  fprintf(ficrespop," [Population]"); */
1.126     brouard  8858:       
1.227     brouard  8859: /*       for (cpt=0; cpt<=0;cpt++) {  */
                   8860: /*     fprintf(ficrespop,"\n\n# Forecasting at date %.lf/%.lf/%.lf ",jpyram,mpyram,anpyram+cpt);    */
1.126     brouard  8861:        
1.227     brouard  8862: /*     for (agedeb=(fage-((int)calagedatem %12/12.)); agedeb>=(ageminpar-((int)calagedatem %12)/12.); agedeb--){  */
                   8863: /*       nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm);  */
                   8864: /*       nhstepm = nhstepm/hstepm;  */
1.126     brouard  8865:          
1.227     brouard  8866: /*       p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm); */
                   8867: /*       oldm=oldms;savm=savms; */
                   8868: /*       hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);   */
1.218     brouard  8869:          
1.227     brouard  8870: /*       for (h=0; h<=nhstepm; h++){ */
                   8871: /*         if (h==(int) (calagedatem+YEARM*cpt)) { */
                   8872: /*           fprintf(ficrespop,"\n %3.f ",agedeb+h*hstepm/YEARM*stepm); */
                   8873: /*         }  */
                   8874: /*         for(j=1; j<=nlstate+ndeath;j++) { */
                   8875: /*           kk1=0.;kk2=0; */
                   8876: /*           for(i=1; i<=nlstate;i++) {               */
                   8877: /*             if (mobilav==1)  */
                   8878: /*               kk1=kk1+p3mat[i][j][h]*mobaverage[(int)agedeb+1][i][cptcod]; */
                   8879: /*             else { */
                   8880: /*               kk1=kk1+p3mat[i][j][h]*probs[(int)(agedeb+1)][i][cptcod]; */
                   8881: /*             } */
                   8882: /*           } */
                   8883: /*           if (h==(int)(calagedatem+12*cpt)){ */
                   8884: /*             tabpop[(int)(agedeb)][j][cptcod]=kk1; */
                   8885: /*             /\*fprintf(ficrespop," %.3f", kk1); */
                   8886: /*               if (popforecast==1) fprintf(ficrespop," [%.f]", kk1*popeffectif[(int)agedeb+1]);*\/ */
                   8887: /*           } */
                   8888: /*         } */
                   8889: /*         for(i=1; i<=nlstate;i++){ */
                   8890: /*           kk1=0.; */
                   8891: /*           for(j=1; j<=nlstate;j++){ */
                   8892: /*             kk1= kk1+tabpop[(int)(agedeb)][j][cptcod];  */
                   8893: /*           } */
                   8894: /*           tabpopprev[(int)(agedeb)][i][cptcod]=tabpop[(int)(agedeb)][i][cptcod]/kk1*popeffectif[(int)(agedeb+(calagedatem+12*cpt)*hstepm/YEARM*stepm-1)]; */
                   8895: /*         } */
1.218     brouard  8896:            
1.227     brouard  8897: /*         if (h==(int)(calagedatem+12*cpt)) */
                   8898: /*           for(j=1; j<=nlstate;j++)  */
                   8899: /*             fprintf(ficrespop," %15.2f",tabpopprev[(int)(agedeb+1)][j][cptcod]); */
                   8900: /*       } */
                   8901: /*       free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm); */
                   8902: /*     } */
                   8903: /*       } */
1.218     brouard  8904:       
1.227     brouard  8905: /*       /\******\/ */
1.218     brouard  8906:       
1.227     brouard  8907: /*       for (cpt=1; cpt<=(anpyram1-anpyram);cpt++) {  */
                   8908: /*     fprintf(ficrespop,"\n\n# Forecasting at date %.lf/%.lf/%.lf ",jpyram,mpyram,anpyram+cpt);    */
                   8909: /*     for (agedeb=(fage-((int)calagedatem %12/12.)); agedeb>=(ageminpar-((int)calagedatem %12)/12.); agedeb--){  */
                   8910: /*       nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm);  */
                   8911: /*       nhstepm = nhstepm/hstepm;  */
1.126     brouard  8912:          
1.227     brouard  8913: /*       p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm); */
                   8914: /*       oldm=oldms;savm=savms; */
                   8915: /*       hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);   */
                   8916: /*       for (h=0; h<=nhstepm; h++){ */
                   8917: /*         if (h==(int) (calagedatem+YEARM*cpt)) { */
                   8918: /*           fprintf(ficresf,"\n %3.f ",agedeb+h*hstepm/YEARM*stepm); */
                   8919: /*         }  */
                   8920: /*         for(j=1; j<=nlstate+ndeath;j++) { */
                   8921: /*           kk1=0.;kk2=0; */
                   8922: /*           for(i=1; i<=nlstate;i++) {               */
                   8923: /*             kk1=kk1+p3mat[i][j][h]*tabpopprev[(int)agedeb+1][i][cptcod];     */
                   8924: /*           } */
                   8925: /*           if (h==(int)(calagedatem+12*cpt)) fprintf(ficresf," %15.2f", kk1);         */
                   8926: /*         } */
                   8927: /*       } */
                   8928: /*       free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm); */
                   8929: /*     } */
                   8930: /*       } */
                   8931: /*     }  */
                   8932: /*   } */
1.218     brouard  8933:   
1.227     brouard  8934: /*   /\* if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX); *\/ */
1.218     brouard  8935:   
1.227     brouard  8936: /*   if (popforecast==1) { */
                   8937: /*     free_ivector(popage,0,AGESUP); */
                   8938: /*     free_vector(popeffectif,0,AGESUP); */
                   8939: /*     free_vector(popcount,0,AGESUP); */
                   8940: /*   } */
                   8941: /*   free_ma3x(tabpop,1, AGESUP,1,NCOVMAX, 1,NCOVMAX); */
                   8942: /*   free_ma3x(tabpopprev,1, AGESUP,1,NCOVMAX, 1,NCOVMAX); */
                   8943: /*   fclose(ficrespop); */
                   8944: /* } /\* End of popforecast *\/ */
1.218     brouard  8945:  
1.126     brouard  8946: int fileappend(FILE *fichier, char *optionfich)
                   8947: {
                   8948:   if((fichier=fopen(optionfich,"a"))==NULL) {
                   8949:     printf("Problem with file: %s\n", optionfich);
                   8950:     fprintf(ficlog,"Problem with file: %s\n", optionfich);
                   8951:     return (0);
                   8952:   }
                   8953:   fflush(fichier);
                   8954:   return (1);
                   8955: }
                   8956: 
                   8957: 
                   8958: /**************** function prwizard **********************/
                   8959: void prwizard(int ncovmodel, int nlstate, int ndeath,  char model[], FILE *ficparo)
                   8960: {
                   8961: 
                   8962:   /* Wizard to print covariance matrix template */
                   8963: 
1.164     brouard  8964:   char ca[32], cb[32];
                   8965:   int i,j, k, li, lj, lk, ll, jj, npar, itimes;
1.126     brouard  8966:   int numlinepar;
                   8967: 
                   8968:   printf("# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
                   8969:   fprintf(ficparo,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
                   8970:   for(i=1; i <=nlstate; i++){
                   8971:     jj=0;
                   8972:     for(j=1; j <=nlstate+ndeath; j++){
                   8973:       if(j==i) continue;
                   8974:       jj++;
                   8975:       /*ca[0]= k+'a'-1;ca[1]='\0';*/
                   8976:       printf("%1d%1d",i,j);
                   8977:       fprintf(ficparo,"%1d%1d",i,j);
                   8978:       for(k=1; k<=ncovmodel;k++){
                   8979:        /*        printf(" %lf",param[i][j][k]); */
                   8980:        /*        fprintf(ficparo," %lf",param[i][j][k]); */
                   8981:        printf(" 0.");
                   8982:        fprintf(ficparo," 0.");
                   8983:       }
                   8984:       printf("\n");
                   8985:       fprintf(ficparo,"\n");
                   8986:     }
                   8987:   }
                   8988:   printf("# Scales (for hessian or gradient estimation)\n");
                   8989:   fprintf(ficparo,"# Scales (for hessian or gradient estimation)\n");
                   8990:   npar= (nlstate+ndeath-1)*nlstate*ncovmodel; /* Number of parameters*/ 
                   8991:   for(i=1; i <=nlstate; i++){
                   8992:     jj=0;
                   8993:     for(j=1; j <=nlstate+ndeath; j++){
                   8994:       if(j==i) continue;
                   8995:       jj++;
                   8996:       fprintf(ficparo,"%1d%1d",i,j);
                   8997:       printf("%1d%1d",i,j);
                   8998:       fflush(stdout);
                   8999:       for(k=1; k<=ncovmodel;k++){
                   9000:        /*      printf(" %le",delti3[i][j][k]); */
                   9001:        /*      fprintf(ficparo," %le",delti3[i][j][k]); */
                   9002:        printf(" 0.");
                   9003:        fprintf(ficparo," 0.");
                   9004:       }
                   9005:       numlinepar++;
                   9006:       printf("\n");
                   9007:       fprintf(ficparo,"\n");
                   9008:     }
                   9009:   }
                   9010:   printf("# Covariance matrix\n");
                   9011: /* # 121 Var(a12)\n\ */
                   9012: /* # 122 Cov(b12,a12) Var(b12)\n\ */
                   9013: /* # 131 Cov(a13,a12) Cov(a13,b12, Var(a13)\n\ */
                   9014: /* # 132 Cov(b13,a12) Cov(b13,b12, Cov(b13,a13) Var(b13)\n\ */
                   9015: /* # 212 Cov(a21,a12) Cov(a21,b12, Cov(a21,a13) Cov(a21,b13) Var(a21)\n\ */
                   9016: /* # 212 Cov(b21,a12) Cov(b21,b12, Cov(b21,a13) Cov(b21,b13) Cov(b21,a21) Var(b21)\n\ */
                   9017: /* # 232 Cov(a23,a12) Cov(a23,b12, Cov(a23,a13) Cov(a23,b13) Cov(a23,a21) Cov(a23,b21) Var(a23)\n\ */
                   9018: /* # 232 Cov(b23,a12) Cov(b23,b12) ... Var (b23)\n" */
                   9019:   fflush(stdout);
                   9020:   fprintf(ficparo,"# Covariance matrix\n");
                   9021:   /* # 121 Var(a12)\n\ */
                   9022:   /* # 122 Cov(b12,a12) Var(b12)\n\ */
                   9023:   /* #   ...\n\ */
                   9024:   /* # 232 Cov(b23,a12)  Cov(b23,b12) ... Var (b23)\n" */
                   9025:   
                   9026:   for(itimes=1;itimes<=2;itimes++){
                   9027:     jj=0;
                   9028:     for(i=1; i <=nlstate; i++){
                   9029:       for(j=1; j <=nlstate+ndeath; j++){
                   9030:        if(j==i) continue;
                   9031:        for(k=1; k<=ncovmodel;k++){
                   9032:          jj++;
                   9033:          ca[0]= k+'a'-1;ca[1]='\0';
                   9034:          if(itimes==1){
                   9035:            printf("#%1d%1d%d",i,j,k);
                   9036:            fprintf(ficparo,"#%1d%1d%d",i,j,k);
                   9037:          }else{
                   9038:            printf("%1d%1d%d",i,j,k);
                   9039:            fprintf(ficparo,"%1d%1d%d",i,j,k);
                   9040:            /*  printf(" %.5le",matcov[i][j]); */
                   9041:          }
                   9042:          ll=0;
                   9043:          for(li=1;li <=nlstate; li++){
                   9044:            for(lj=1;lj <=nlstate+ndeath; lj++){
                   9045:              if(lj==li) continue;
                   9046:              for(lk=1;lk<=ncovmodel;lk++){
                   9047:                ll++;
                   9048:                if(ll<=jj){
                   9049:                  cb[0]= lk +'a'-1;cb[1]='\0';
                   9050:                  if(ll<jj){
                   9051:                    if(itimes==1){
                   9052:                      printf(" Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
                   9053:                      fprintf(ficparo," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
                   9054:                    }else{
                   9055:                      printf(" 0.");
                   9056:                      fprintf(ficparo," 0.");
                   9057:                    }
                   9058:                  }else{
                   9059:                    if(itimes==1){
                   9060:                      printf(" Var(%s%1d%1d)",ca,i,j);
                   9061:                      fprintf(ficparo," Var(%s%1d%1d)",ca,i,j);
                   9062:                    }else{
                   9063:                      printf(" 0.");
                   9064:                      fprintf(ficparo," 0.");
                   9065:                    }
                   9066:                  }
                   9067:                }
                   9068:              } /* end lk */
                   9069:            } /* end lj */
                   9070:          } /* end li */
                   9071:          printf("\n");
                   9072:          fprintf(ficparo,"\n");
                   9073:          numlinepar++;
                   9074:        } /* end k*/
                   9075:       } /*end j */
                   9076:     } /* end i */
                   9077:   } /* end itimes */
                   9078: 
                   9079: } /* end of prwizard */
                   9080: /******************* Gompertz Likelihood ******************************/
                   9081: double gompertz(double x[])
                   9082: { 
1.302     brouard  9083:   double A=0.0,B=0.,L=0.0,sump=0.,num=0.;
1.126     brouard  9084:   int i,n=0; /* n is the size of the sample */
                   9085: 
1.220     brouard  9086:   for (i=1;i<=imx ; i++) {
1.126     brouard  9087:     sump=sump+weight[i];
                   9088:     /*    sump=sump+1;*/
                   9089:     num=num+1;
                   9090:   }
1.302     brouard  9091:   L=0.0;
                   9092:   /* agegomp=AGEGOMP; */
1.126     brouard  9093:   /* for (i=0; i<=imx; i++) 
                   9094:      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]);*/
                   9095: 
1.302     brouard  9096:   for (i=1;i<=imx ; i++) {
                   9097:     /* mu(a)=mu(agecomp)*exp(teta*(age-agegomp))
                   9098:        mu(a)=x[1]*exp(x[2]*(age-agegomp)); x[1] and x[2] are per year.
                   9099:      * L= Product mu(agedeces)exp(-\int_ageexam^agedc mu(u) du ) for a death between agedc (in month) 
                   9100:      *   and agedc +1 month, cens[i]=0: log(x[1]/YEARM)
                   9101:      * +
                   9102:      * exp(-\int_ageexam^agecens mu(u) du ) when censored, cens[i]=1
                   9103:      */
                   9104:      if (wav[i] > 1 || agedc[i] < AGESUP) {
                   9105:        if (cens[i] == 1){
                   9106:         A=-x[1]/(x[2])*(exp(x[2]*(agecens[i]-agegomp))-exp(x[2]*(ageexmed[i]-agegomp)));
                   9107:        } else if (cens[i] == 0){
1.126     brouard  9108:        A=-x[1]/(x[2])*(exp(x[2]*(agedc[i]-agegomp))-exp(x[2]*(ageexmed[i]-agegomp)))
1.302     brouard  9109:          +log(x[1]/YEARM) +x[2]*(agedc[i]-agegomp)+log(YEARM);
                   9110:       } else
                   9111:         printf("Gompertz cens[%d] neither 1 nor 0\n",i);
1.126     brouard  9112:       /*if (wav[i] > 1 && agecens[i] > 15) {*/ /* ??? */
1.302     brouard  9113:        L=L+A*weight[i];
1.126     brouard  9114:        /*      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  9115:      }
                   9116:   }
1.126     brouard  9117: 
1.302     brouard  9118:   /*printf("x1=%2.9f x2=%2.9f x3=%2.9f L=%f\n",x[1],x[2],x[3],L);*/
1.126     brouard  9119:  
                   9120:   return -2*L*num/sump;
                   9121: }
                   9122: 
1.136     brouard  9123: #ifdef GSL
                   9124: /******************* Gompertz_f Likelihood ******************************/
                   9125: double gompertz_f(const gsl_vector *v, void *params)
                   9126: { 
1.302     brouard  9127:   double A=0.,B=0.,LL=0.0,sump=0.,num=0.;
1.136     brouard  9128:   double *x= (double *) v->data;
                   9129:   int i,n=0; /* n is the size of the sample */
                   9130: 
                   9131:   for (i=0;i<=imx-1 ; i++) {
                   9132:     sump=sump+weight[i];
                   9133:     /*    sump=sump+1;*/
                   9134:     num=num+1;
                   9135:   }
                   9136:  
                   9137:  
                   9138:   /* for (i=0; i<=imx; i++) 
                   9139:      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]);*/
                   9140:   printf("x[0]=%lf x[1]=%lf\n",x[0],x[1]);
                   9141:   for (i=1;i<=imx ; i++)
                   9142:     {
                   9143:       if (cens[i] == 1 && wav[i]>1)
                   9144:        A=-x[0]/(x[1])*(exp(x[1]*(agecens[i]-agegomp))-exp(x[1]*(ageexmed[i]-agegomp)));
                   9145:       
                   9146:       if (cens[i] == 0 && wav[i]>1)
                   9147:        A=-x[0]/(x[1])*(exp(x[1]*(agedc[i]-agegomp))-exp(x[1]*(ageexmed[i]-agegomp)))
                   9148:             +log(x[0]/YEARM)+x[1]*(agedc[i]-agegomp)+log(YEARM);  
                   9149:       
                   9150:       /*if (wav[i] > 1 && agecens[i] > 15) {*/ /* ??? */
                   9151:       if (wav[i] > 1 ) { /* ??? */
                   9152:        LL=LL+A*weight[i];
                   9153:        /*      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]);*/
                   9154:       }
                   9155:     }
                   9156: 
                   9157:  /*printf("x1=%2.9f x2=%2.9f x3=%2.9f L=%f\n",x[1],x[2],x[3],L);*/
                   9158:   printf("x[0]=%lf x[1]=%lf -2*LL*num/sump=%lf\n",x[0],x[1],-2*LL*num/sump);
                   9159:  
                   9160:   return -2*LL*num/sump;
                   9161: }
                   9162: #endif
                   9163: 
1.126     brouard  9164: /******************* Printing html file ***********/
1.201     brouard  9165: void printinghtmlmort(char fileresu[], char title[], char datafile[], int firstpass, \
1.126     brouard  9166:                  int lastpass, int stepm, int weightopt, char model[],\
                   9167:                  int imx,  double p[],double **matcov,double agemortsup){
                   9168:   int i,k;
                   9169: 
                   9170:   fprintf(fichtm,"<ul><li><h4>Result files </h4>\n Force of mortality. Parameters of the Gompertz fit (with confidence interval in brackets):<br>");
                   9171:   fprintf(fichtm,"  mu(age) =%lf*exp(%lf*(age-%d)) per year<br><br>",p[1],p[2],agegomp);
                   9172:   for (i=1;i<=2;i++) 
                   9173:     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  9174:   fprintf(fichtm,"<br><br><img src=\"graphmort.svg\">");
1.126     brouard  9175:   fprintf(fichtm,"</ul>");
                   9176: 
                   9177: fprintf(fichtm,"<ul><li><h4>Life table</h4>\n <br>");
                   9178: 
                   9179:  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>");
                   9180: 
                   9181:  for (k=agegomp;k<(agemortsup-2);k++) 
                   9182:    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]);
                   9183: 
                   9184:  
                   9185:   fflush(fichtm);
                   9186: }
                   9187: 
                   9188: /******************* Gnuplot file **************/
1.201     brouard  9189: void printinggnuplotmort(char fileresu[], char optionfilefiname[], double ageminpar, double agemaxpar, double fage , char pathc[], double p[]){
1.126     brouard  9190: 
                   9191:   char dirfileres[132],optfileres[132];
1.164     brouard  9192: 
1.126     brouard  9193:   int ng;
                   9194: 
                   9195: 
                   9196:   /*#ifdef windows */
                   9197:   fprintf(ficgp,"cd \"%s\" \n",pathc);
                   9198:     /*#endif */
                   9199: 
                   9200: 
                   9201:   strcpy(dirfileres,optionfilefiname);
                   9202:   strcpy(optfileres,"vpl");
1.199     brouard  9203:   fprintf(ficgp,"set out \"graphmort.svg\"\n "); 
1.126     brouard  9204:   fprintf(ficgp,"set xlabel \"Age\"\n set ylabel \"Force of mortality (per year)\" \n "); 
1.199     brouard  9205:   fprintf(ficgp, "set ter svg size 640, 480\n set log y\n"); 
1.145     brouard  9206:   /* fprintf(ficgp, "set size 0.65,0.65\n"); */
1.126     brouard  9207:   fprintf(ficgp,"plot [%d:100] %lf*exp(%lf*(x-%d))",agegomp,p[1],p[2],agegomp);
                   9208: 
                   9209: } 
                   9210: 
1.136     brouard  9211: int readdata(char datafile[], int firstobs, int lastobs, int *imax)
                   9212: {
1.126     brouard  9213: 
1.136     brouard  9214:   /*-------- data file ----------*/
                   9215:   FILE *fic;
                   9216:   char dummy[]="                         ";
1.240     brouard  9217:   int i=0, j=0, n=0, iv=0, v;
1.223     brouard  9218:   int lstra;
1.136     brouard  9219:   int linei, month, year,iout;
1.302     brouard  9220:   int noffset=0; /* This is the offset if BOM data file */
1.136     brouard  9221:   char line[MAXLINE], linetmp[MAXLINE];
1.164     brouard  9222:   char stra[MAXLINE], strb[MAXLINE];
1.136     brouard  9223:   char *stratrunc;
1.223     brouard  9224: 
1.240     brouard  9225:   DummyV=ivector(1,NCOVMAX); /* 1 to 3 */
                   9226:   FixedV=ivector(1,NCOVMAX); /* 1 to 3 */
1.126     brouard  9227: 
1.240     brouard  9228:   for(v=1; v <=ncovcol;v++){
                   9229:     DummyV[v]=0;
                   9230:     FixedV[v]=0;
                   9231:   }
                   9232:   for(v=ncovcol+1; v <=ncovcol+nqv;v++){
                   9233:     DummyV[v]=1;
                   9234:     FixedV[v]=0;
                   9235:   }
                   9236:   for(v=ncovcol+nqv+1; v <=ncovcol+nqv+ntv;v++){
                   9237:     DummyV[v]=0;
                   9238:     FixedV[v]=1;
                   9239:   }
                   9240:   for(v=ncovcol+nqv+ntv+1; v <=ncovcol+nqv+ntv+nqtv;v++){
                   9241:     DummyV[v]=1;
                   9242:     FixedV[v]=1;
                   9243:   }
                   9244:   for(v=1; v <=ncovcol+nqv+ntv+nqtv;v++){
                   9245:     printf("Covariate type in the data: V%d, DummyV(V%d)=%d, FixedV(V%d)=%d\n",v,v,DummyV[v],v,FixedV[v]);
                   9246:     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]);
                   9247:   }
1.126     brouard  9248: 
1.136     brouard  9249:   if((fic=fopen(datafile,"r"))==NULL)    {
1.218     brouard  9250:     printf("Problem while opening datafile: %s with errno='%s'\n", datafile,strerror(errno));fflush(stdout);
                   9251:     fprintf(ficlog,"Problem while opening datafile: %s with errno='%s'\n", datafile,strerror(errno));fflush(ficlog);return 1;
1.136     brouard  9252:   }
1.126     brouard  9253: 
1.302     brouard  9254:     /* Is it a BOM UTF-8 Windows file? */
                   9255:   /* First data line */
                   9256:   linei=0;
                   9257:   while(fgets(line, MAXLINE, fic)) {
                   9258:     noffset=0;
                   9259:     if( line[0] == (char)0xEF && line[1] == (char)0xBB) /* EF BB BF */
                   9260:     {
                   9261:       noffset=noffset+3;
                   9262:       printf("# Data file '%s'  is an UTF8 BOM file, please convert to UTF8 or ascii file and rerun.\n",datafile);fflush(stdout);
                   9263:       fprintf(ficlog,"# Data file '%s'  is an UTF8 BOM file, please convert to UTF8 or ascii file and rerun.\n",datafile);
                   9264:       fflush(ficlog); return 1;
                   9265:     }
                   9266:     /*    else if( line[0] == (char)0xFE && line[1] == (char)0xFF)*/
                   9267:     else if( line[0] == (char)0xFF && line[1] == (char)0xFE)
                   9268:     {
                   9269:       noffset=noffset+2;
1.304     brouard  9270:       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);
                   9271:       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  9272:       fflush(ficlog); return 1;
                   9273:     }
                   9274:     else if( line[0] == 0 && line[1] == 0)
                   9275:     {
                   9276:       if( line[2] == (char)0xFE && line[3] == (char)0xFF){
                   9277:        noffset=noffset+4;
1.304     brouard  9278:        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);
                   9279:        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  9280:        fflush(ficlog); return 1;
                   9281:       }
                   9282:     } else{
                   9283:       ;/*printf(" Not a BOM file\n");*/
                   9284:     }
                   9285:         /* If line starts with a # it is a comment */
                   9286:     if (line[noffset] == '#') {
                   9287:       linei=linei+1;
                   9288:       break;
                   9289:     }else{
                   9290:       break;
                   9291:     }
                   9292:   }
                   9293:   fclose(fic);
                   9294:   if((fic=fopen(datafile,"r"))==NULL)    {
                   9295:     printf("Problem while opening datafile: %s with errno='%s'\n", datafile,strerror(errno));fflush(stdout);
                   9296:     fprintf(ficlog,"Problem while opening datafile: %s with errno='%s'\n", datafile,strerror(errno));fflush(ficlog);return 1;
                   9297:   }
                   9298:   /* Not a Bom file */
                   9299:   
1.136     brouard  9300:   i=1;
                   9301:   while ((fgets(line, MAXLINE, fic) != NULL) &&((i >= firstobs) && (i <=lastobs))) {
                   9302:     linei=linei+1;
                   9303:     for(j=strlen(line); j>=0;j--){  /* Untabifies line */
                   9304:       if(line[j] == '\t')
                   9305:        line[j] = ' ';
                   9306:     }
                   9307:     for(j=strlen(line)-1; (line[j]==' ')||(line[j]==10)||(line[j]==13);j--){
                   9308:       ;
                   9309:     };
                   9310:     line[j+1]=0;  /* Trims blanks at end of line */
                   9311:     if(line[0]=='#'){
                   9312:       fprintf(ficlog,"Comment line\n%s\n",line);
                   9313:       printf("Comment line\n%s\n",line);
                   9314:       continue;
                   9315:     }
                   9316:     trimbb(linetmp,line); /* Trims multiple blanks in line */
1.164     brouard  9317:     strcpy(line, linetmp);
1.223     brouard  9318:     
                   9319:     /* Loops on waves */
                   9320:     for (j=maxwav;j>=1;j--){
                   9321:       for (iv=nqtv;iv>=1;iv--){  /* Loop  on time varying quantitative variables */
1.238     brouard  9322:        cutv(stra, strb, line, ' '); 
                   9323:        if(strb[0]=='.') { /* Missing value */
                   9324:          lval=-1;
                   9325:          cotqvar[j][iv][i]=-1; /* 0.0/0.0 */
                   9326:          cotvar[j][ntv+iv][i]=-1; /* For performance reasons */
                   9327:          if(isalpha(strb[1])) { /* .m or .d Really Missing value */
                   9328:            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);
                   9329:            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);
                   9330:            return 1;
                   9331:          }
                   9332:        }else{
                   9333:          errno=0;
                   9334:          /* what_kind_of_number(strb); */
                   9335:          dval=strtod(strb,&endptr); 
                   9336:          /* if( strb[0]=='\0' || (*endptr != '\0')){ */
                   9337:          /* if(strb != endptr && *endptr == '\0') */
                   9338:          /*    dval=dlval; */
                   9339:          /* if (errno == ERANGE && (lval == LONG_MAX || lval == LONG_MIN)) */
                   9340:          if( strb[0]=='\0' || (*endptr != '\0')){
                   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. Setting maxwav=%d might be wrong.  Exiting.\n", strb, linei,i,line,iv, nqtv, j,maxwav);
                   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. Setting maxwav=%d might be wrong.  Exiting.\n", strb, linei,i,line, iv, nqtv, j,maxwav);fflush(ficlog);
                   9343:            return 1;
                   9344:          }
                   9345:          cotqvar[j][iv][i]=dval; 
                   9346:          cotvar[j][ntv+iv][i]=dval; 
                   9347:        }
                   9348:        strcpy(line,stra);
1.223     brouard  9349:       }/* end loop ntqv */
1.225     brouard  9350:       
1.223     brouard  9351:       for (iv=ntv;iv>=1;iv--){  /* Loop  on time varying dummies */
1.238     brouard  9352:        cutv(stra, strb, line, ' '); 
                   9353:        if(strb[0]=='.') { /* Missing value */
                   9354:          lval=-1;
                   9355:        }else{
                   9356:          errno=0;
                   9357:          lval=strtol(strb,&endptr,10); 
                   9358:          /*    if (errno == ERANGE && (lval == LONG_MAX || lval == LONG_MIN))*/
                   9359:          if( strb[0]=='\0' || (*endptr != '\0')){
                   9360:            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);
                   9361:            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);
                   9362:            return 1;
                   9363:          }
                   9364:        }
                   9365:        if(lval <-1 || lval >1){
                   9366:          printf("Error reading data around '%ld' at line number %d for individual %d, '%s'\n \
1.223     brouard  9367:  Should be a value of %d(nth) covariate (0 should be the value for the reference and 1\n \
                   9368:  for the alternative. IMaCh does not build design variables automatically, do it yourself.\n \
1.238     brouard  9369:  For example, for multinomial values like 1, 2 and 3,\n                        \
                   9370:  build V1=0 V2=0 for the reference value (1),\n                                \
                   9371:         V1=1 V2=0 for (2) \n                                           \
1.223     brouard  9372:  and V1=0 V2=1 for (3). V1=1 V2=1 should not exist and the corresponding\n \
1.238     brouard  9373:  output of IMaCh is often meaningless.\n                               \
1.223     brouard  9374:  Exiting.\n",lval,linei, i,line,j);
1.238     brouard  9375:          fprintf(ficlog,"Error reading data around '%ld' at line number %d for individual %d, '%s'\n \
1.223     brouard  9376:  Should be a value of %d(nth) covariate (0 should be the value for the reference and 1\n \
                   9377:  for the alternative. IMaCh does not build design variables automatically, do it yourself.\n \
1.238     brouard  9378:  For example, for multinomial values like 1, 2 and 3,\n                        \
                   9379:  build V1=0 V2=0 for the reference value (1),\n                                \
                   9380:         V1=1 V2=0 for (2) \n                                           \
1.223     brouard  9381:  and V1=0 V2=1 for (3). V1=1 V2=1 should not exist and the corresponding\n \
1.238     brouard  9382:  output of IMaCh is often meaningless.\n                               \
1.223     brouard  9383:  Exiting.\n",lval,linei, i,line,j);fflush(ficlog);
1.238     brouard  9384:          return 1;
                   9385:        }
                   9386:        cotvar[j][iv][i]=(double)(lval);
                   9387:        strcpy(line,stra);
1.223     brouard  9388:       }/* end loop ntv */
1.225     brouard  9389:       
1.223     brouard  9390:       /* Statuses  at wave */
1.137     brouard  9391:       cutv(stra, strb, line, ' '); 
1.223     brouard  9392:       if(strb[0]=='.') { /* Missing value */
1.238     brouard  9393:        lval=-1;
1.136     brouard  9394:       }else{
1.238     brouard  9395:        errno=0;
                   9396:        lval=strtol(strb,&endptr,10); 
                   9397:        /*      if (errno == ERANGE && (lval == LONG_MAX || lval == LONG_MIN))*/
                   9398:        if( strb[0]=='\0' || (*endptr != '\0')){
                   9399:          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);
                   9400:          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);
                   9401:          return 1;
                   9402:        }
1.136     brouard  9403:       }
1.225     brouard  9404:       
1.136     brouard  9405:       s[j][i]=lval;
1.225     brouard  9406:       
1.223     brouard  9407:       /* Date of Interview */
1.136     brouard  9408:       strcpy(line,stra);
                   9409:       cutv(stra, strb,line,' ');
1.169     brouard  9410:       if( (iout=sscanf(strb,"%d/%d",&month, &year)) != 0){
1.136     brouard  9411:       }
1.169     brouard  9412:       else  if( (iout=sscanf(strb,"%s.",dummy)) != 0){
1.225     brouard  9413:        month=99;
                   9414:        year=9999;
1.136     brouard  9415:       }else{
1.225     brouard  9416:        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);
                   9417:        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);
                   9418:        return 1;
1.136     brouard  9419:       }
                   9420:       anint[j][i]= (double) year; 
1.302     brouard  9421:       mint[j][i]= (double)month;
                   9422:       /* if( (int)anint[j][i]+ (int)(mint[j][i])/12. < (int) (moisnais[i]/12.+annais[i])){ */
                   9423:       /*       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]); */
                   9424:       /*       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]); */
                   9425:       /* } */
1.136     brouard  9426:       strcpy(line,stra);
1.223     brouard  9427:     } /* End loop on waves */
1.225     brouard  9428:     
1.223     brouard  9429:     /* Date of death */
1.136     brouard  9430:     cutv(stra, strb,line,' '); 
1.169     brouard  9431:     if( (iout=sscanf(strb,"%d/%d",&month, &year)) != 0){
1.136     brouard  9432:     }
1.169     brouard  9433:     else  if( (iout=sscanf(strb,"%s.",dummy)) != 0){
1.136     brouard  9434:       month=99;
                   9435:       year=9999;
                   9436:     }else{
1.141     brouard  9437:       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  9438:       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);
                   9439:       return 1;
1.136     brouard  9440:     }
                   9441:     andc[i]=(double) year; 
                   9442:     moisdc[i]=(double) month; 
                   9443:     strcpy(line,stra);
                   9444:     
1.223     brouard  9445:     /* Date of birth */
1.136     brouard  9446:     cutv(stra, strb,line,' '); 
1.169     brouard  9447:     if( (iout=sscanf(strb,"%d/%d",&month, &year)) != 0){
1.136     brouard  9448:     }
1.169     brouard  9449:     else  if( (iout=sscanf(strb,"%s.", dummy)) != 0){
1.136     brouard  9450:       month=99;
                   9451:       year=9999;
                   9452:     }else{
1.141     brouard  9453:       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);
                   9454:       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  9455:       return 1;
1.136     brouard  9456:     }
                   9457:     if (year==9999) {
1.141     brouard  9458:       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);
                   9459:       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  9460:       return 1;
                   9461:       
1.136     brouard  9462:     }
                   9463:     annais[i]=(double)(year);
1.302     brouard  9464:     moisnais[i]=(double)(month);
                   9465:     for (j=1;j<=maxwav;j++){
                   9466:       if( (int)anint[j][i]+ (int)(mint[j][i])/12. < (int) (moisnais[i]/12.+annais[i])){
                   9467:        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]);
                   9468:        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]);
                   9469:       }
                   9470:     }
                   9471: 
1.136     brouard  9472:     strcpy(line,stra);
1.225     brouard  9473:     
1.223     brouard  9474:     /* Sample weight */
1.136     brouard  9475:     cutv(stra, strb,line,' '); 
                   9476:     errno=0;
                   9477:     dval=strtod(strb,&endptr); 
                   9478:     if( strb[0]=='\0' || (*endptr != '\0')){
1.141     brouard  9479:       printf("Error reading data around '%f' at line number %d, \"%s\" for individual %d\nShould be a weight.  Exiting.\n",dval, i,line,linei);
                   9480:       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  9481:       fflush(ficlog);
                   9482:       return 1;
                   9483:     }
                   9484:     weight[i]=dval; 
                   9485:     strcpy(line,stra);
1.225     brouard  9486:     
1.223     brouard  9487:     for (iv=nqv;iv>=1;iv--){  /* Loop  on fixed quantitative variables */
                   9488:       cutv(stra, strb, line, ' '); 
                   9489:       if(strb[0]=='.') { /* Missing value */
1.225     brouard  9490:        lval=-1;
1.223     brouard  9491:       }else{
1.225     brouard  9492:        errno=0;
                   9493:        /* what_kind_of_number(strb); */
                   9494:        dval=strtod(strb,&endptr);
                   9495:        /* if(strb != endptr && *endptr == '\0') */
                   9496:        /*   dval=dlval; */
                   9497:        /* if (errno == ERANGE && (lval == LONG_MAX || lval == LONG_MIN)) */
                   9498:        if( strb[0]=='\0' || (*endptr != '\0')){
                   9499:          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);
                   9500:          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);
                   9501:          return 1;
                   9502:        }
                   9503:        coqvar[iv][i]=dval; 
1.226     brouard  9504:        covar[ncovcol+iv][i]=dval; /* including qvar in standard covar for performance reasons */ 
1.223     brouard  9505:       }
                   9506:       strcpy(line,stra);
                   9507:     }/* end loop nqv */
1.136     brouard  9508:     
1.223     brouard  9509:     /* Covariate values */
1.136     brouard  9510:     for (j=ncovcol;j>=1;j--){
                   9511:       cutv(stra, strb,line,' '); 
1.223     brouard  9512:       if(strb[0]=='.') { /* Missing covariate value */
1.225     brouard  9513:        lval=-1;
1.136     brouard  9514:       }else{
1.225     brouard  9515:        errno=0;
                   9516:        lval=strtol(strb,&endptr,10); 
                   9517:        if( strb[0]=='\0' || (*endptr != '\0')){
                   9518:          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);
                   9519:          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);
                   9520:          return 1;
                   9521:        }
1.136     brouard  9522:       }
                   9523:       if(lval <-1 || lval >1){
1.225     brouard  9524:        printf("Error reading data around '%ld' at line number %d for individual %d, '%s'\n \
1.136     brouard  9525:  Should be a value of %d(nth) covariate (0 should be the value for the reference and 1\n \
                   9526:  for the alternative. IMaCh does not build design variables automatically, do it yourself.\n \
1.225     brouard  9527:  For example, for multinomial values like 1, 2 and 3,\n                        \
                   9528:  build V1=0 V2=0 for the reference value (1),\n                                \
                   9529:         V1=1 V2=0 for (2) \n                                           \
1.136     brouard  9530:  and V1=0 V2=1 for (3). V1=1 V2=1 should not exist and the corresponding\n \
1.225     brouard  9531:  output of IMaCh is often meaningless.\n                               \
1.136     brouard  9532:  Exiting.\n",lval,linei, i,line,j);
1.225     brouard  9533:        fprintf(ficlog,"Error reading data around '%ld' at line number %d for individual %d, '%s'\n \
1.136     brouard  9534:  Should be a value of %d(nth) covariate (0 should be the value for the reference and 1\n \
                   9535:  for the alternative. IMaCh does not build design variables automatically, do it yourself.\n \
1.225     brouard  9536:  For example, for multinomial values like 1, 2 and 3,\n                        \
                   9537:  build V1=0 V2=0 for the reference value (1),\n                                \
                   9538:         V1=1 V2=0 for (2) \n                                           \
1.136     brouard  9539:  and V1=0 V2=1 for (3). V1=1 V2=1 should not exist and the corresponding\n \
1.225     brouard  9540:  output of IMaCh is often meaningless.\n                               \
1.136     brouard  9541:  Exiting.\n",lval,linei, i,line,j);fflush(ficlog);
1.225     brouard  9542:        return 1;
1.136     brouard  9543:       }
                   9544:       covar[j][i]=(double)(lval);
                   9545:       strcpy(line,stra);
                   9546:     }  
                   9547:     lstra=strlen(stra);
1.225     brouard  9548:     
1.136     brouard  9549:     if(lstra > 9){ /* More than 2**32 or max of what printf can write with %ld */
                   9550:       stratrunc = &(stra[lstra-9]);
                   9551:       num[i]=atol(stratrunc);
                   9552:     }
                   9553:     else
                   9554:       num[i]=atol(stra);
                   9555:     /*if((s[2][i]==2) && (s[3][i]==-1)&&(s[4][i]==9)){
                   9556:       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;}*/
                   9557:     
                   9558:     i=i+1;
                   9559:   } /* End loop reading  data */
1.225     brouard  9560:   
1.136     brouard  9561:   *imax=i-1; /* Number of individuals */
                   9562:   fclose(fic);
1.225     brouard  9563:   
1.136     brouard  9564:   return (0);
1.164     brouard  9565:   /* endread: */
1.225     brouard  9566:   printf("Exiting readdata: ");
                   9567:   fclose(fic);
                   9568:   return (1);
1.223     brouard  9569: }
1.126     brouard  9570: 
1.234     brouard  9571: void removefirstspace(char **stri){/*, char stro[]) {*/
1.230     brouard  9572:   char *p1 = *stri, *p2 = *stri;
1.235     brouard  9573:   while (*p2 == ' ')
1.234     brouard  9574:     p2++; 
                   9575:   /* while ((*p1++ = *p2++) !=0) */
                   9576:   /*   ; */
                   9577:   /* do */
                   9578:   /*   while (*p2 == ' ') */
                   9579:   /*     p2++; */
                   9580:   /* while (*p1++ == *p2++); */
                   9581:   *stri=p2; 
1.145     brouard  9582: }
                   9583: 
1.235     brouard  9584: int decoderesult ( char resultline[], int nres)
1.230     brouard  9585: /**< This routine decode one result line and returns the combination # of dummy covariates only **/
                   9586: {
1.235     brouard  9587:   int j=0, k=0, k1=0, k2=0, k3=0, k4=0, match=0, k2q=0, k3q=0, k4q=0;
1.230     brouard  9588:   char resultsav[MAXLINE];
1.234     brouard  9589:   int resultmodel[MAXLINE];
                   9590:   int modelresult[MAXLINE];
1.230     brouard  9591:   char stra[80], strb[80], strc[80], strd[80],stre[80];
                   9592: 
1.234     brouard  9593:   removefirstspace(&resultline);
1.230     brouard  9594: 
                   9595:   if (strstr(resultline,"v") !=0){
                   9596:     printf("Error. 'v' must be in upper case 'V' result: %s ",resultline);
                   9597:     fprintf(ficlog,"Error. 'v' must be in upper case result: %s ",resultline);fflush(ficlog);
                   9598:     return 1;
                   9599:   }
                   9600:   trimbb(resultsav, resultline);
                   9601:   if (strlen(resultsav) >1){
                   9602:     j=nbocc(resultsav,'='); /**< j=Number of covariate values'=' */
                   9603:   }
1.253     brouard  9604:   if(j == 0){ /* Resultline but no = */
                   9605:     TKresult[nres]=0; /* Combination for the nresult and the model */
                   9606:     return (0);
                   9607:   }
1.234     brouard  9608:   if( j != cptcovs ){ /* Be careful if a variable is in a product but not single */
                   9609:     printf("ERROR: the number of variable in the resultline, %d, differs from the number of variable used in the model line, %d.\n",j, cptcovs);
                   9610:     fprintf(ficlog,"ERROR: the number of variable in the resultline, %d, differs from the number of variable used in the model line, %d.\n",j, cptcovs);
                   9611:   }
                   9612:   for(k=1; k<=j;k++){ /* Loop on any covariate of the result line */
                   9613:     if(nbocc(resultsav,'=') >1){
                   9614:        cutl(stra,strb,resultsav,' '); /* keeps in strb after the first ' ' 
                   9615:                                      resultsav= V4=1 V5=25.1 V3=0 strb=V3=0 stra= V4=1 V5=25.1 */
                   9616:        cutl(strc,strd,strb,'=');  /* strb:V4=1 strc=1 strd=V4 */
                   9617:     }else
                   9618:       cutl(strc,strd,resultsav,'=');
1.230     brouard  9619:     Tvalsel[k]=atof(strc); /* 1 */
1.234     brouard  9620:     
1.230     brouard  9621:     cutl(strc,stre,strd,'V'); /* strd='V4' strc=4 stre='V' */;
                   9622:     Tvarsel[k]=atoi(strc);
                   9623:     /* Typevarsel[k]=1;  /\* 1 for age product *\/ */
                   9624:     /* cptcovsel++;     */
                   9625:     if (nbocc(stra,'=') >0)
                   9626:       strcpy(resultsav,stra); /* and analyzes it */
                   9627:   }
1.235     brouard  9628:   /* Checking for missing or useless values in comparison of current model needs */
1.236     brouard  9629:   for(k1=1; k1<= cptcovt ;k1++){ /* model line V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
                   9630:     if(Typevar[k1]==0){ /* Single covariate in model */
1.234     brouard  9631:       match=0;
1.236     brouard  9632:       for(k2=1; k2 <=j;k2++){/* result line V4=1 V5=24.1 V3=1  V2=8 V1=0 */
1.237     brouard  9633:        if(Tvar[k1]==Tvarsel[k2]) {/* Tvar[1]=5 == Tvarsel[2]=5   */
1.236     brouard  9634:          modelresult[k2]=k1;/* modelresult[2]=1 modelresult[1]=2  modelresult[3]=3  modelresult[6]=4 modelresult[9]=5 */
1.234     brouard  9635:          match=1;
                   9636:          break;
                   9637:        }
                   9638:       }
                   9639:       if(match == 0){
                   9640:        printf("Error in result line: %d value missing; result: %s, model=%s\n",k1, resultline, model);
                   9641:       }
                   9642:     }
                   9643:   }
1.235     brouard  9644:   /* Checking for missing or useless values in comparison of current model needs */
                   9645:   for(k2=1; k2 <=j;k2++){ /* result line V4=1 V5=24.1 V3=1  V2=8 V1=0 */
1.234     brouard  9646:     match=0;
1.235     brouard  9647:     for(k1=1; k1<= cptcovt ;k1++){ /* model line V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
                   9648:       if(Typevar[k1]==0){ /* Single */
1.237     brouard  9649:        if(Tvar[k1]==Tvarsel[k2]) { /* Tvar[2]=4 == Tvarsel[1]=4   */
1.235     brouard  9650:          resultmodel[k1]=k2;  /* resultmodel[2]=1 resultmodel[1]=2  resultmodel[3]=3  resultmodel[6]=4 resultmodel[9]=5 */
1.234     brouard  9651:          ++match;
                   9652:        }
                   9653:       }
                   9654:     }
                   9655:     if(match == 0){
                   9656:       printf("Error in result line: %d value missing; result: %s, model=%s\n",k1, resultline, model);
                   9657:     }else if(match > 1){
                   9658:       printf("Error in result line: %d doubled; result: %s, model=%s\n",k2, resultline, model);
                   9659:     }
                   9660:   }
1.235     brouard  9661:       
1.234     brouard  9662:   /* We need to deduce which combination number is chosen and save quantitative values */
1.235     brouard  9663:   /* model line V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
                   9664:   /* result line V4=1 V5=25.1 V3=0  V2=8 V1=1 */
                   9665:   /* should give a combination of dummy V4=1, V3=0, V1=1 => V4*2**(0) + V3*2**(1) + V1*2**(2) = 5 + (1offset) = 6*/
                   9666:   /* result line V4=1 V5=24.1 V3=1  V2=8 V1=0 */
                   9667:   /* should give a combination of dummy V4=1, V3=1, V1=0 => V4*2**(0) + V3*2**(1) + V1*2**(2) = 3 + (1offset) = 4*/
                   9668:   /*    1 0 0 0 */
                   9669:   /*    2 1 0 0 */
                   9670:   /*    3 0 1 0 */ 
                   9671:   /*    4 1 1 0 */ /* V4=1, V3=1, V1=0 */
                   9672:   /*    5 0 0 1 */
                   9673:   /*    6 1 0 1 */ /* V4=1, V3=0, V1=1 */
                   9674:   /*    7 0 1 1 */
                   9675:   /*    8 1 1 1 */
1.237     brouard  9676:   /* V(Tvresult)=Tresult V4=1 V3=0 V1=1 Tresult[nres=1][2]=0 */
                   9677:   /* V(Tvqresult)=Tqresult V5=25.1 V2=8 Tqresult[nres=1][1]=25.1 */
                   9678:   /* V5*age V5 known which value for nres?  */
                   9679:   /* Tqinvresult[2]=8 Tqinvresult[1]=25.1  */
1.235     brouard  9680:   for(k1=1, k=0, k4=0, k4q=0; k1 <=cptcovt;k1++){ /* model line */
                   9681:     if( Dummy[k1]==0 && Typevar[k1]==0 ){ /* Single dummy */
1.237     brouard  9682:       k3= resultmodel[k1]; /* resultmodel[2(V4)] = 1=k3 */
1.235     brouard  9683:       k2=(int)Tvarsel[k3]; /*  Tvarsel[resultmodel[2]]= Tvarsel[1] = 4=k2 */
                   9684:       k+=Tvalsel[k3]*pow(2,k4);  /*  Tvalsel[1]=1  */
1.237     brouard  9685:       Tresult[nres][k4+1]=Tvalsel[k3];/* Tresult[nres][1]=1(V4=1)  Tresult[nres][2]=0(V3=0) */
                   9686:       Tvresult[nres][k4+1]=(int)Tvarsel[k3];/* Tvresult[nres][1]=4 Tvresult[nres][3]=1 */
                   9687:       Tinvresult[nres][(int)Tvarsel[k3]]=Tvalsel[k3]; /* Tinvresult[nres][4]=1 */
1.235     brouard  9688:       printf("Decoderesult Dummy k=%d, V(k2=V%d)= Tvalsel[%d]=%d, 2**(%d)\n",k, k2, k3, (int)Tvalsel[k3], k4);
                   9689:       k4++;;
                   9690:     }  else if( Dummy[k1]==1 && Typevar[k1]==0 ){ /* Single quantitative */
                   9691:       k3q= resultmodel[k1]; /* resultmodel[2] = 1=k3 */
                   9692:       k2q=(int)Tvarsel[k3q]; /*  Tvarsel[resultmodel[2]]= Tvarsel[1] = 4=k2 */
1.237     brouard  9693:       Tqresult[nres][k4q+1]=Tvalsel[k3q]; /* Tqresult[nres][1]=25.1 */
                   9694:       Tvqresult[nres][k4q+1]=(int)Tvarsel[k3q]; /* Tvqresult[nres][1]=5 */
                   9695:       Tqinvresult[nres][(int)Tvarsel[k3q]]=Tvalsel[k3q]; /* Tqinvresult[nres][5]=25.1 */
1.235     brouard  9696:       printf("Decoderesult Quantitative nres=%d, V(k2q=V%d)= Tvalsel[%d]=%d, Tvarsel[%d]=%f\n",nres, k2q, k3q, Tvarsel[k3q], k3q, Tvalsel[k3q]);
                   9697:       k4q++;;
                   9698:     }
                   9699:   }
1.234     brouard  9700:   
1.235     brouard  9701:   TKresult[nres]=++k; /* Combination for the nresult and the model */
1.230     brouard  9702:   return (0);
                   9703: }
1.235     brouard  9704: 
1.230     brouard  9705: int decodemodel( char model[], int lastobs)
                   9706:  /**< This routine decodes the model and returns:
1.224     brouard  9707:        * Model  V1+V2+V3+V8+V7*V8+V5*V6+V8*age+V3*age+age*age
                   9708:        * - nagesqr = 1 if age*age in the model, otherwise 0.
                   9709:        * - cptcovt total number of covariates of the model nbocc(+)+1 = 8 excepting constant and age and age*age
                   9710:        * - cptcovn or number of covariates k of the models excluding age*products =6 and age*age
                   9711:        * - cptcovage number of covariates with age*products =2
                   9712:        * - cptcovs number of simple covariates
                   9713:        * - 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
                   9714:        *     which is a new column after the 9 (ncovcol) variables. 
                   9715:        * - if k is a product Vn*Vm covar[k][i] is filled with correct values for each individual
                   9716:        * - Tprod[l] gives the kth covariates of the product Vn*Vm l=1 to cptcovprod-cptcovage
                   9717:        *    Tprod[1]@2 {5, 6}: position of first product V7*V8 is 5, and second V5*V6 is 6.
                   9718:        * - Tvard[k]  p Tvard[1][1]@4 {7, 8, 5, 6} for V7*V8 and V5*V6 .
                   9719:        */
1.136     brouard  9720: {
1.238     brouard  9721:   int i, j, k, ks, v;
1.227     brouard  9722:   int  j1, k1, k2, k3, k4;
1.136     brouard  9723:   char modelsav[80];
1.145     brouard  9724:   char stra[80], strb[80], strc[80], strd[80],stre[80];
1.187     brouard  9725:   char *strpt;
1.136     brouard  9726: 
1.145     brouard  9727:   /*removespace(model);*/
1.136     brouard  9728:   if (strlen(model) >1){ /* If there is at least 1 covariate */
1.145     brouard  9729:     j=0, j1=0, k1=0, k2=-1, ks=0, cptcovn=0;
1.137     brouard  9730:     if (strstr(model,"AGE") !=0){
1.192     brouard  9731:       printf("Error. AGE must be in lower case 'age' model=1+age+%s. ",model);
                   9732:       fprintf(ficlog,"Error. AGE must be in lower case model=1+age+%s. ",model);fflush(ficlog);
1.136     brouard  9733:       return 1;
                   9734:     }
1.141     brouard  9735:     if (strstr(model,"v") !=0){
                   9736:       printf("Error. 'v' must be in upper case 'V' model=%s ",model);
                   9737:       fprintf(ficlog,"Error. 'v' must be in upper case model=%s ",model);fflush(ficlog);
                   9738:       return 1;
                   9739:     }
1.187     brouard  9740:     strcpy(modelsav,model); 
                   9741:     if ((strpt=strstr(model,"age*age")) !=0){
                   9742:       printf(" strpt=%s, model=%s\n",strpt, model);
                   9743:       if(strpt != model){
1.234     brouard  9744:        printf("Error in model: 'model=%s'; 'age*age' should in first place before other covariates\n \
1.192     brouard  9745:  'model=1+age+age*age+V1.' or 'model=1+age+age*age+V1+V1*age.', please swap as well as \n \
1.187     brouard  9746:  corresponding column of parameters.\n",model);
1.234     brouard  9747:        fprintf(ficlog,"Error in model: 'model=%s'; 'age*age' should in first place before other covariates\n \
1.192     brouard  9748:  'model=1+age+age*age+V1.' or 'model=1+age+age*age+V1+V1*age.', please swap as well as \n \
1.187     brouard  9749:  corresponding column of parameters.\n",model); fflush(ficlog);
1.234     brouard  9750:        return 1;
1.225     brouard  9751:       }
1.187     brouard  9752:       nagesqr=1;
                   9753:       if (strstr(model,"+age*age") !=0)
1.234     brouard  9754:        substrchaine(modelsav, model, "+age*age");
1.187     brouard  9755:       else if (strstr(model,"age*age+") !=0)
1.234     brouard  9756:        substrchaine(modelsav, model, "age*age+");
1.187     brouard  9757:       else 
1.234     brouard  9758:        substrchaine(modelsav, model, "age*age");
1.187     brouard  9759:     }else
                   9760:       nagesqr=0;
                   9761:     if (strlen(modelsav) >1){
                   9762:       j=nbocc(modelsav,'+'); /**< j=Number of '+' */
                   9763:       j1=nbocc(modelsav,'*'); /**< j1=Number of '*' */
1.224     brouard  9764:       cptcovs=j+1-j1; /**<  Number of simple covariates V1+V1*age+V3 +V3*V4+age*age=> V1 + V3 =5-3=2  */
1.187     brouard  9765:       cptcovt= j+1; /* Number of total covariates in the model, not including
1.225     brouard  9766:                     * cst, age and age*age 
                   9767:                     * V1+V1*age+ V3 + V3*V4+age*age=> 3+1=4*/
                   9768:       /* including age products which are counted in cptcovage.
                   9769:        * but the covariates which are products must be treated 
                   9770:        * separately: ncovn=4- 2=2 (V1+V3). */
1.187     brouard  9771:       cptcovprod=j1; /**< Number of products  V1*V2 +v3*age = 2 */
                   9772:       cptcovprodnoage=0; /**< Number of covariate products without age: V3*V4 =1  */
1.225     brouard  9773:       
                   9774:       
1.187     brouard  9775:       /*   Design
                   9776:        *  V1   V2   V3   V4  V5  V6  V7  V8  V9 Weight
                   9777:        *  <          ncovcol=8                >
                   9778:        * Model V2 + V1 + V3*age + V3 + V5*V6 + V7*V8 + V8*age + V8
                   9779:        *   k=  1    2      3       4     5       6      7        8
                   9780:        *  cptcovn number of covariates (not including constant and age ) = # of + plus 1 = 7+1=8
                   9781:        *  covar[k,i], value of kth covariate if not including age for individual i:
1.224     brouard  9782:        *       covar[1][i]= (V1), covar[4][i]=(V4), covar[8][i]=(V8)
                   9783:        *  Tvar[k] # of the kth covariate:  Tvar[1]=2  Tvar[2]=1 Tvar[4]=3 Tvar[8]=8
1.187     brouard  9784:        *       if multiplied by age: V3*age Tvar[3=V3*age]=3 (V3) Tvar[7]=8 and 
                   9785:        *  Tage[++cptcovage]=k
                   9786:        *       if products, new covar are created after ncovcol with k1
                   9787:        *  Tvar[k]=ncovcol+k1; # of the kth covariate product:  Tvar[5]=ncovcol+1=10  Tvar[6]=ncovcol+1=11
                   9788:        *  Tprod[k1]=k; Tprod[1]=5 Tprod[2]= 6; gives the position of the k1th product
                   9789:        *  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
                   9790:        *  Tvar[cptcovn+k2]=Tvard[k1][1];Tvar[cptcovn+k2+1]=Tvard[k1][2];
                   9791:        *  Tvar[8+1]=5;Tvar[8+2]=6;Tvar[8+3]=7;Tvar[8+4]=8 inverted
                   9792:        *  V1   V2   V3   V4  V5  V6  V7  V8  V9  V10  V11
                   9793:        *  <          ncovcol=8                >
                   9794:        *       Model V2 + V1 + V3*age + V3 + V5*V6 + V7*V8 + V8*age + V8    d1   d1   d2  d2
                   9795:        *          k=  1    2      3       4     5       6      7        8    9   10   11  12
                   9796:        *     Tvar[k]= 2    1      3       3    10      11      8        8    5    6    7   8
                   9797:        * p Tvar[1]@12={2,   1,     3,      3,   11,     10,     8,       8,   7,   8,   5,  6}
                   9798:        * p Tprod[1]@2={                         6, 5}
                   9799:        *p Tvard[1][1]@4= {7, 8, 5, 6}
                   9800:        * covar[k][i]= V2   V1      ?      V3    V5*V6?   V7*V8?  ?       V8   
                   9801:        *  cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];
                   9802:        *How to reorganize?
                   9803:        * Model V1 + V2 + V3 + V8 + V5*V6 + V7*V8 + V3*age + V8*age
                   9804:        * Tvars {2,   1,     3,      3,   11,     10,     8,       8,   7,   8,   5,  6}
                   9805:        *       {2,   1,     4,      8,    5,      6,     3,       7}
                   9806:        * Struct []
                   9807:        */
1.225     brouard  9808:       
1.187     brouard  9809:       /* This loop fills the array Tvar from the string 'model'.*/
                   9810:       /* j is the number of + signs in the model V1+V2+V3 j=2 i=3 to 1 */
                   9811:       /*   modelsav=V2+V1+V4+age*V3 strb=age*V3 stra=V2+V1+V4  */
                   9812:       /*       k=4 (age*V3) Tvar[k=4]= 3 (from V3) Tage[cptcovage=1]=4 */
                   9813:       /*       k=3 V4 Tvar[k=3]= 4 (from V4) */
                   9814:       /*       k=2 V1 Tvar[k=2]= 1 (from V1) */
                   9815:       /*       k=1 Tvar[1]=2 (from V2) */
                   9816:       /*       k=5 Tvar[5] */
                   9817:       /* for (k=1; k<=cptcovn;k++) { */
1.198     brouard  9818:       /*       cov[2+k]=nbcode[Tvar[k]][codtabm(ij,Tvar[k])]; */
1.187     brouard  9819:       /*       } */
1.198     brouard  9820:       /* for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,Tvar[Tage[k])]]*cov[2]; */
1.187     brouard  9821:       /*
                   9822:        * Treating invertedly V2+V1+V3*age+V2*V4 is as if written V2*V4 +V3*age + V1 + V2 */
1.227     brouard  9823:       for(k=cptcovt; k>=1;k--){ /**< Number of covariates not including constant and age, neither age*age*/
                   9824:         Tvar[k]=0; Tprod[k]=0; Tposprod[k]=0;
                   9825:       }
1.187     brouard  9826:       cptcovage=0;
                   9827:       for(k=1; k<=cptcovt;k++){ /* Loop on total covariates of the model */
1.234     brouard  9828:        cutl(stra,strb,modelsav,'+'); /* keeps in strb after the first '+' 
1.225     brouard  9829:                                         modelsav==V2+V1+V4+V3*age strb=V3*age stra=V2+V1+V4 */ 
1.234     brouard  9830:        if (nbocc(modelsav,'+')==0) strcpy(strb,modelsav); /* and analyzes it */
                   9831:        /*      printf("i=%d a=%s b=%s sav=%s\n",i, stra,strb,modelsav);*/
                   9832:        /*scanf("%d",i);*/
                   9833:        if (strchr(strb,'*')) {  /**< Model includes a product V2+V1+V4+V3*age strb=V3*age */
                   9834:          cutl(strc,strd,strb,'*'); /**< strd*strc  Vm*Vn: strb=V3*age(input) strc=age strd=V3 ; V3*V2 strc=V2, strd=V3 */
                   9835:          if (strcmp(strc,"age")==0) { /**< Model includes age: Vn*age */
                   9836:            /* covar is not filled and then is empty */
                   9837:            cptcovprod--;
                   9838:            cutl(stre,strb,strd,'V'); /* strd=V3(input): stre="3" */
                   9839:            Tvar[k]=atoi(stre);  /* V2+V1+V4+V3*age Tvar[4]=3 ; V1+V2*age Tvar[2]=2; V1+V1*age Tvar[2]=1 */
                   9840:            Typevar[k]=1;  /* 1 for age product */
                   9841:            cptcovage++; /* Sums the number of covariates which include age as a product */
                   9842:            Tage[cptcovage]=k;  /* Tvar[4]=3, Tage[1] = 4 or V1+V1*age Tvar[2]=1, Tage[1]=2 */
                   9843:            /*printf("stre=%s ", stre);*/
                   9844:          } else if (strcmp(strd,"age")==0) { /* or age*Vn */
                   9845:            cptcovprod--;
                   9846:            cutl(stre,strb,strc,'V');
                   9847:            Tvar[k]=atoi(stre);
                   9848:            Typevar[k]=1;  /* 1 for age product */
                   9849:            cptcovage++;
                   9850:            Tage[cptcovage]=k;
                   9851:          } else {  /* Age is not in the model product V2+V1+V1*V4+V3*age+V3*V2  strb=V3*V2*/
                   9852:            /* loops on k1=1 (V3*V2) and k1=2 V4*V3 */
                   9853:            cptcovn++;
                   9854:            cptcovprodnoage++;k1++;
                   9855:            cutl(stre,strb,strc,'V'); /* strc= Vn, stre is n; strb=V3*V2 stre=3 strc=*/
                   9856:            Tvar[k]=ncovcol+nqv+ntv+nqtv+k1; /* For model-covariate k tells which data-covariate to use but
                   9857:                                                because this model-covariate is a construction we invent a new column
                   9858:                                                which is after existing variables ncovcol+nqv+ntv+nqtv + k1
                   9859:                                                If already ncovcol=4 and model=V2+V1+V1*V4+age*V3+V3*V2
                   9860:                                                Tvar[3=V1*V4]=4+1 Tvar[5=V3*V2]=4 + 2= 6, etc */
                   9861:            Typevar[k]=2;  /* 2 for double fixed dummy covariates */
                   9862:            cutl(strc,strb,strd,'V'); /* strd was Vm, strc is m */
                   9863:            Tprod[k1]=k;  /* Tprod[1]=3(=V1*V4) for V2+V1+V1*V4+age*V3+V3*V2  */
                   9864:            Tposprod[k]=k1; /* Tpsprod[3]=1, Tposprod[2]=5 */
                   9865:            Tvard[k1][1] =atoi(strc); /* m 1 for V1*/
                   9866:            Tvard[k1][2] =atoi(stre); /* n 4 for V4*/
                   9867:            k2=k2+2;  /* k2 is initialize to -1, We want to store the n and m in Vn*Vm at the end of Tvar */
                   9868:            /* Tvar[cptcovt+k2]=Tvard[k1][1]; /\* Tvar[(cptcovt=4+k2=1)=5]= 1 (V1) *\/ */
                   9869:            /* Tvar[cptcovt+k2+1]=Tvard[k1][2];  /\* Tvar[(cptcovt=4+(k2=1)+1)=6]= 4 (V4) *\/ */
1.225     brouard  9870:             /*ncovcol=4 and model=V2+V1+V1*V4+age*V3+V3*V2, Tvar[3]=5, Tvar[4]=6, cptcovt=5 */
1.234     brouard  9871:            /*                     1  2   3      4     5 | Tvar[5+1)=1, Tvar[7]=2   */
                   9872:            for (i=1; i<=lastobs;i++){
                   9873:              /* Computes the new covariate which is a product of
                   9874:                 covar[n][i]* covar[m][i] and stores it at ncovol+k1 May not be defined */
                   9875:              covar[ncovcol+k1][i]=covar[atoi(stre)][i]*covar[atoi(strc)][i];
                   9876:            }
                   9877:          } /* End age is not in the model */
                   9878:        } /* End if model includes a product */
                   9879:        else { /* no more sum */
                   9880:          /*printf("d=%s c=%s b=%s\n", strd,strc,strb);*/
                   9881:          /*  scanf("%d",i);*/
                   9882:          cutl(strd,strc,strb,'V');
                   9883:          ks++; /**< Number of simple covariates dummy or quantitative, fixe or varying */
                   9884:          cptcovn++; /** V4+V3+V5: V4 and V3 timevarying dummy covariates, V5 timevarying quantitative */
                   9885:          Tvar[k]=atoi(strd);
                   9886:          Typevar[k]=0;  /* 0 for simple covariates */
                   9887:        }
                   9888:        strcpy(modelsav,stra);  /* modelsav=V2+V1+V4 stra=V2+V1+V4 */ 
1.223     brouard  9889:                                /*printf("a=%s b=%s sav=%s\n", stra,strb,modelsav);
1.225     brouard  9890:                                  scanf("%d",i);*/
1.187     brouard  9891:       } /* end of loop + on total covariates */
                   9892:     } /* end if strlen(modelsave == 0) age*age might exist */
                   9893:   } /* end if strlen(model == 0) */
1.136     brouard  9894:   
                   9895:   /*The number n of Vn is stored in Tvar. cptcovage =number of age covariate. Tage gives the position of age. cptcovprod= number of products.
                   9896:     If model=V1+V1*age then Tvar[1]=1 Tvar[2]=1 cptcovage=1 Tage[1]=2 cptcovprod=0*/
1.225     brouard  9897:   
1.136     brouard  9898:   /* printf("tvar1=%d tvar2=%d tvar3=%d cptcovage=%d Tage=%d",Tvar[1],Tvar[2],Tvar[3],cptcovage,Tage[1]);
1.225     brouard  9899:      printf("cptcovprod=%d ", cptcovprod);
                   9900:      fprintf(ficlog,"cptcovprod=%d ", cptcovprod);
                   9901:      scanf("%d ",i);*/
                   9902: 
                   9903: 
1.230     brouard  9904: /* Until here, decodemodel knows only the grammar (simple, product, age*) of the model but not what kind
                   9905:    of variable (dummy vs quantitative, fixed vs time varying) is behind. But we know the # of each. */
1.226     brouard  9906: /* ncovcol= 1, nqv=1 | ntv=2, nqtv= 1  = 5 possible variables data: 2 fixed 3, varying
                   9907:    model=        V5 + V4 +V3 + V4*V3 + V5*age + V2 + V1*V2 + V1*age + V5*age, V1 is not used saving its place
                   9908:    k =           1    2   3     4       5       6      7      8        9
                   9909:    Tvar[k]=      5    4   3 1+1+2+1+1=6 5       2      7      1        5
                   9910:    Typevar[k]=   0    0   0     2       1       0      2      1        1
1.227     brouard  9911:    Fixed[k]      1    1   1     1       3       0    0 or 2   2        3
                   9912:    Dummy[k]      1    0   0     0       3       1      1      2        3
                   9913:          Tmodelind[combination of covar]=k;
1.225     brouard  9914: */  
                   9915: /* Dispatching between quantitative and time varying covariates */
1.226     brouard  9916:   /* If Tvar[k] >ncovcol it is a product */
1.225     brouard  9917:   /* 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  9918:        /* Computing effective variables, ie used by the model, that is from the cptcovt variables */
1.227     brouard  9919:   printf("Model=%s\n\
                   9920: Typevar: 0 for simple covariate (dummy, quantitative, fixed or varying), 1 for age product, 2 for  product \n\
                   9921: Fixed[k] 0=fixed (product or simple), 1 varying, 2 fixed with age product, 3 varying with age product \n\
                   9922: 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);
                   9923:   fprintf(ficlog,"Model=%s\n\
                   9924: Typevar: 0 for simple covariate (dummy, quantitative, fixed or varying), 1 for age product, 2 for  product \n\
                   9925: Fixed[k] 0=fixed (product or simple), 1 varying, 2 fixed with age product, 3 varying with age product \n\
                   9926: 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  9927:   for(k=-1;k<=cptcovt; k++){ Fixed[k]=0; Dummy[k]=0;}
1.234     brouard  9928:   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 */
                   9929:     if (Tvar[k] <=ncovcol && Typevar[k]==0 ){ /* Simple fixed dummy (<=ncovcol) covariates */
1.227     brouard  9930:       Fixed[k]= 0;
                   9931:       Dummy[k]= 0;
1.225     brouard  9932:       ncoveff++;
1.232     brouard  9933:       ncovf++;
1.234     brouard  9934:       nsd++;
                   9935:       modell[k].maintype= FTYPE;
                   9936:       TvarsD[nsd]=Tvar[k];
                   9937:       TvarsDind[nsd]=k;
                   9938:       TvarF[ncovf]=Tvar[k];
                   9939:       TvarFind[ncovf]=k;
                   9940:       TvarFD[ncoveff]=Tvar[k]; /* TvarFD[1]=V1 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
                   9941:       TvarFDind[ncoveff]=k; /* TvarFDind[1]=9 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
                   9942:     }else if( Tvar[k] <=ncovcol &&  Typevar[k]==2){ /* Product of fixed dummy (<=ncovcol) covariates */
                   9943:       Fixed[k]= 0;
                   9944:       Dummy[k]= 0;
                   9945:       ncoveff++;
                   9946:       ncovf++;
                   9947:       modell[k].maintype= FTYPE;
                   9948:       TvarF[ncovf]=Tvar[k];
                   9949:       TvarFind[ncovf]=k;
1.230     brouard  9950:       TvarFD[ncoveff]=Tvar[k]; /* TvarFD[1]=V1 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
1.231     brouard  9951:       TvarFDind[ncoveff]=k; /* TvarFDind[1]=9 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
1.240     brouard  9952:     }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  9953:       Fixed[k]= 0;
                   9954:       Dummy[k]= 1;
1.230     brouard  9955:       nqfveff++;
1.234     brouard  9956:       modell[k].maintype= FTYPE;
                   9957:       modell[k].subtype= FQ;
                   9958:       nsq++;
                   9959:       TvarsQ[nsq]=Tvar[k];
                   9960:       TvarsQind[nsq]=k;
1.232     brouard  9961:       ncovf++;
1.234     brouard  9962:       TvarF[ncovf]=Tvar[k];
                   9963:       TvarFind[ncovf]=k;
1.231     brouard  9964:       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  9965:       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  9966:     }else if( Tvar[k] <=ncovcol+nqv+ntv && Typevar[k]==0){/* Only simple time varying dummy variables */
1.227     brouard  9967:       Fixed[k]= 1;
                   9968:       Dummy[k]= 0;
1.225     brouard  9969:       ntveff++; /* Only simple time varying dummy variable */
1.234     brouard  9970:       modell[k].maintype= VTYPE;
                   9971:       modell[k].subtype= VD;
                   9972:       nsd++;
                   9973:       TvarsD[nsd]=Tvar[k];
                   9974:       TvarsDind[nsd]=k;
                   9975:       ncovv++; /* Only simple time varying variables */
                   9976:       TvarV[ncovv]=Tvar[k];
1.242     brouard  9977:       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  9978:       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 */
                   9979:       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  9980:       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);
                   9981:       printf("Quasi TmodelInvind[%d]=%d\n",k,Tvar[k]- ncovcol-nqv);
1.231     brouard  9982:     }else if( Tvar[k] <=ncovcol+nqv+ntv+nqtv  && Typevar[k]==0){ /* Only simple time varying quantitative variable V5*/
1.234     brouard  9983:       Fixed[k]= 1;
                   9984:       Dummy[k]= 1;
                   9985:       nqtveff++;
                   9986:       modell[k].maintype= VTYPE;
                   9987:       modell[k].subtype= VQ;
                   9988:       ncovv++; /* Only simple time varying variables */
                   9989:       nsq++;
                   9990:       TvarsQ[nsq]=Tvar[k];
                   9991:       TvarsQind[nsq]=k;
                   9992:       TvarV[ncovv]=Tvar[k];
1.242     brouard  9993:       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  9994:       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 */
                   9995:       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  9996:       TmodelInvQind[nqtveff]=Tvar[k]- ncovcol-nqv-ntv;/* Only simple time varying quantitative variable */
                   9997:       /* Tmodeliqind[k]=nqtveff;/\* Only simple time varying quantitative variable *\/ */
                   9998:       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  9999:       printf("Quasi TmodelInvQind[%d]=%d\n",k,Tvar[k]- ncovcol-nqv-ntv);
1.227     brouard  10000:     }else if (Typevar[k] == 1) {  /* product with age */
1.234     brouard  10001:       ncova++;
                   10002:       TvarA[ncova]=Tvar[k];
                   10003:       TvarAind[ncova]=k;
1.231     brouard  10004:       if (Tvar[k] <=ncovcol ){ /* Product age with fixed dummy covariatee */
1.240     brouard  10005:        Fixed[k]= 2;
                   10006:        Dummy[k]= 2;
                   10007:        modell[k].maintype= ATYPE;
                   10008:        modell[k].subtype= APFD;
                   10009:        /* ncoveff++; */
1.227     brouard  10010:       }else if( Tvar[k] <=ncovcol+nqv) { /* Remind that product Vn*Vm are added in k*/
1.240     brouard  10011:        Fixed[k]= 2;
                   10012:        Dummy[k]= 3;
                   10013:        modell[k].maintype= ATYPE;
                   10014:        modell[k].subtype= APFQ;                /*      Product age * fixed quantitative */
                   10015:        /* nqfveff++;  /\* Only simple fixed quantitative variable *\/ */
1.227     brouard  10016:       }else if( Tvar[k] <=ncovcol+nqv+ntv ){
1.240     brouard  10017:        Fixed[k]= 3;
                   10018:        Dummy[k]= 2;
                   10019:        modell[k].maintype= ATYPE;
                   10020:        modell[k].subtype= APVD;                /*      Product age * varying dummy */
                   10021:        /* ntveff++; /\* Only simple time varying dummy variable *\/ */
1.227     brouard  10022:       }else if( Tvar[k] <=ncovcol+nqv+ntv+nqtv){
1.240     brouard  10023:        Fixed[k]= 3;
                   10024:        Dummy[k]= 3;
                   10025:        modell[k].maintype= ATYPE;
                   10026:        modell[k].subtype= APVQ;                /*      Product age * varying quantitative */
                   10027:        /* nqtveff++;/\* Only simple time varying quantitative variable *\/ */
1.227     brouard  10028:       }
                   10029:     }else if (Typevar[k] == 2) {  /* product without age */
                   10030:       k1=Tposprod[k];
                   10031:       if(Tvard[k1][1] <=ncovcol){
1.240     brouard  10032:        if(Tvard[k1][2] <=ncovcol){
                   10033:          Fixed[k]= 1;
                   10034:          Dummy[k]= 0;
                   10035:          modell[k].maintype= FTYPE;
                   10036:          modell[k].subtype= FPDD;              /*      Product fixed dummy * fixed dummy */
                   10037:          ncovf++; /* Fixed variables without age */
                   10038:          TvarF[ncovf]=Tvar[k];
                   10039:          TvarFind[ncovf]=k;
                   10040:        }else if(Tvard[k1][2] <=ncovcol+nqv){
                   10041:          Fixed[k]= 0;  /* or 2 ?*/
                   10042:          Dummy[k]= 1;
                   10043:          modell[k].maintype= FTYPE;
                   10044:          modell[k].subtype= FPDQ;              /*      Product fixed dummy * fixed quantitative */
                   10045:          ncovf++; /* Varying variables without age */
                   10046:          TvarF[ncovf]=Tvar[k];
                   10047:          TvarFind[ncovf]=k;
                   10048:        }else if(Tvard[k1][2] <=ncovcol+nqv+ntv){
                   10049:          Fixed[k]= 1;
                   10050:          Dummy[k]= 0;
                   10051:          modell[k].maintype= VTYPE;
                   10052:          modell[k].subtype= VPDD;              /*      Product fixed dummy * varying dummy */
                   10053:          ncovv++; /* Varying variables without age */
                   10054:          TvarV[ncovv]=Tvar[k];
                   10055:          TvarVind[ncovv]=k;
                   10056:        }else if(Tvard[k1][2] <=ncovcol+nqv+ntv+nqtv){
                   10057:          Fixed[k]= 1;
                   10058:          Dummy[k]= 1;
                   10059:          modell[k].maintype= VTYPE;
                   10060:          modell[k].subtype= VPDQ;              /*      Product fixed dummy * varying quantitative */
                   10061:          ncovv++; /* Varying variables without age */
                   10062:          TvarV[ncovv]=Tvar[k];
                   10063:          TvarVind[ncovv]=k;
                   10064:        }
1.227     brouard  10065:       }else if(Tvard[k1][1] <=ncovcol+nqv){
1.240     brouard  10066:        if(Tvard[k1][2] <=ncovcol){
                   10067:          Fixed[k]= 0;  /* or 2 ?*/
                   10068:          Dummy[k]= 1;
                   10069:          modell[k].maintype= FTYPE;
                   10070:          modell[k].subtype= FPDQ;              /*      Product fixed quantitative * fixed dummy */
                   10071:          ncovf++; /* Fixed variables without age */
                   10072:          TvarF[ncovf]=Tvar[k];
                   10073:          TvarFind[ncovf]=k;
                   10074:        }else if(Tvard[k1][2] <=ncovcol+nqv+ntv){
                   10075:          Fixed[k]= 1;
                   10076:          Dummy[k]= 1;
                   10077:          modell[k].maintype= VTYPE;
                   10078:          modell[k].subtype= VPDQ;              /*      Product fixed quantitative * varying dummy */
                   10079:          ncovv++; /* Varying variables without age */
                   10080:          TvarV[ncovv]=Tvar[k];
                   10081:          TvarVind[ncovv]=k;
                   10082:        }else if(Tvard[k1][2] <=ncovcol+nqv+ntv+nqtv){
                   10083:          Fixed[k]= 1;
                   10084:          Dummy[k]= 1;
                   10085:          modell[k].maintype= VTYPE;
                   10086:          modell[k].subtype= VPQQ;              /*      Product fixed quantitative * varying quantitative */
                   10087:          ncovv++; /* Varying variables without age */
                   10088:          TvarV[ncovv]=Tvar[k];
                   10089:          TvarVind[ncovv]=k;
                   10090:          ncovv++; /* Varying variables without age */
                   10091:          TvarV[ncovv]=Tvar[k];
                   10092:          TvarVind[ncovv]=k;
                   10093:        }
1.227     brouard  10094:       }else if(Tvard[k1][1] <=ncovcol+nqv+ntv){
1.240     brouard  10095:        if(Tvard[k1][2] <=ncovcol){
                   10096:          Fixed[k]= 1;
                   10097:          Dummy[k]= 1;
                   10098:          modell[k].maintype= VTYPE;
                   10099:          modell[k].subtype= VPDD;              /*      Product time varying dummy * fixed dummy */
                   10100:          ncovv++; /* Varying variables without age */
                   10101:          TvarV[ncovv]=Tvar[k];
                   10102:          TvarVind[ncovv]=k;
                   10103:        }else if(Tvard[k1][2] <=ncovcol+nqv){
                   10104:          Fixed[k]= 1;
                   10105:          Dummy[k]= 1;
                   10106:          modell[k].maintype= VTYPE;
                   10107:          modell[k].subtype= VPDQ;              /*      Product time varying dummy * fixed quantitative */
                   10108:          ncovv++; /* Varying variables without age */
                   10109:          TvarV[ncovv]=Tvar[k];
                   10110:          TvarVind[ncovv]=k;
                   10111:        }else if(Tvard[k1][2] <=ncovcol+nqv+ntv){
                   10112:          Fixed[k]= 1;
                   10113:          Dummy[k]= 0;
                   10114:          modell[k].maintype= VTYPE;
                   10115:          modell[k].subtype= VPDD;              /*      Product time varying dummy * time varying dummy */
                   10116:          ncovv++; /* Varying variables without age */
                   10117:          TvarV[ncovv]=Tvar[k];
                   10118:          TvarVind[ncovv]=k;
                   10119:        }else if(Tvard[k1][2] <=ncovcol+nqv+ntv+nqtv){
                   10120:          Fixed[k]= 1;
                   10121:          Dummy[k]= 1;
                   10122:          modell[k].maintype= VTYPE;
                   10123:          modell[k].subtype= VPDQ;              /*      Product time varying dummy * time varying quantitative */
                   10124:          ncovv++; /* Varying variables without age */
                   10125:          TvarV[ncovv]=Tvar[k];
                   10126:          TvarVind[ncovv]=k;
                   10127:        }
1.227     brouard  10128:       }else if(Tvard[k1][1] <=ncovcol+nqv+ntv+nqtv){
1.240     brouard  10129:        if(Tvard[k1][2] <=ncovcol){
                   10130:          Fixed[k]= 1;
                   10131:          Dummy[k]= 1;
                   10132:          modell[k].maintype= VTYPE;
                   10133:          modell[k].subtype= VPDQ;              /*      Product time varying quantitative * fixed dummy */
                   10134:          ncovv++; /* Varying variables without age */
                   10135:          TvarV[ncovv]=Tvar[k];
                   10136:          TvarVind[ncovv]=k;
                   10137:        }else if(Tvard[k1][2] <=ncovcol+nqv){
                   10138:          Fixed[k]= 1;
                   10139:          Dummy[k]= 1;
                   10140:          modell[k].maintype= VTYPE;
                   10141:          modell[k].subtype= VPQQ;              /*      Product time varying quantitative * fixed quantitative */
                   10142:          ncovv++; /* Varying variables without age */
                   10143:          TvarV[ncovv]=Tvar[k];
                   10144:          TvarVind[ncovv]=k;
                   10145:        }else if(Tvard[k1][2] <=ncovcol+nqv+ntv){
                   10146:          Fixed[k]= 1;
                   10147:          Dummy[k]= 1;
                   10148:          modell[k].maintype= VTYPE;
                   10149:          modell[k].subtype= VPDQ;              /*      Product time varying quantitative * time varying dummy */
                   10150:          ncovv++; /* Varying variables without age */
                   10151:          TvarV[ncovv]=Tvar[k];
                   10152:          TvarVind[ncovv]=k;
                   10153:        }else if(Tvard[k1][2] <=ncovcol+nqv+ntv+nqtv){
                   10154:          Fixed[k]= 1;
                   10155:          Dummy[k]= 1;
                   10156:          modell[k].maintype= VTYPE;
                   10157:          modell[k].subtype= VPQQ;              /*      Product time varying quantitative * time varying quantitative */
                   10158:          ncovv++; /* Varying variables without age */
                   10159:          TvarV[ncovv]=Tvar[k];
                   10160:          TvarVind[ncovv]=k;
                   10161:        }
1.227     brouard  10162:       }else{
1.240     brouard  10163:        printf("Error unknown type of covariate: Tvard[%d][1]=%d,Tvard[%d][2]=%d\n",k1,Tvard[k1][1],k1,Tvard[k1][2]);
                   10164:        fprintf(ficlog,"Error unknown type of covariate: Tvard[%d][1]=%d,Tvard[%d][2]=%d\n",k1,Tvard[k1][1],k1,Tvard[k1][2]);
                   10165:       } /*end k1*/
1.225     brouard  10166:     }else{
1.226     brouard  10167:       printf("Error, current version can't treat for performance reasons, Tvar[%d]=%d, Typevar[%d]=%d\n", k, Tvar[k], k, Typevar[k]);
                   10168:       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  10169:     }
1.227     brouard  10170:     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  10171:     printf("           modell[%d].maintype=%d, modell[%d].subtype=%d\n",k,modell[k].maintype,k,modell[k].subtype);
1.227     brouard  10172:     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]);
                   10173:   }
                   10174:   /* Searching for doublons in the model */
                   10175:   for(k1=1; k1<= cptcovt;k1++){
                   10176:     for(k2=1; k2 <k1;k2++){
1.285     brouard  10177:       /* if((Typevar[k1]==Typevar[k2]) && (Fixed[Tvar[k1]]==Fixed[Tvar[k2]]) && (Dummy[Tvar[k1]]==Dummy[Tvar[k2]] )){ */
                   10178:       if((Typevar[k1]==Typevar[k2]) && (Fixed[k1]==Fixed[k2]) && (Dummy[k1]==Dummy[k2] )){
1.234     brouard  10179:        if((Typevar[k1] == 0 || Typevar[k1] == 1)){ /* Simple or age product */
                   10180:          if(Tvar[k1]==Tvar[k2]){
1.285     brouard  10181:            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]);
                   10182:            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  10183:            return(1);
                   10184:          }
                   10185:        }else if (Typevar[k1] ==2){
                   10186:          k3=Tposprod[k1];
                   10187:          k4=Tposprod[k2];
                   10188:          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])) ){
                   10189:            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]]);
                   10190:            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);
                   10191:            return(1);
                   10192:          }
                   10193:        }
1.227     brouard  10194:       }
                   10195:     }
1.225     brouard  10196:   }
                   10197:   printf("ncoveff=%d, nqfveff=%d, ntveff=%d, nqtveff=%d, cptcovn=%d\n",ncoveff,nqfveff,ntveff,nqtveff,cptcovn);
                   10198:   fprintf(ficlog,"ncoveff=%d, nqfveff=%d, ntveff=%d, nqtveff=%d, cptcovn=%d\n",ncoveff,nqfveff,ntveff,nqtveff,cptcovn);
1.234     brouard  10199:   printf("ncovf=%d, ncovv=%d, ncova=%d, nsd=%d, nsq=%d\n",ncovf,ncovv,ncova,nsd,nsq);
                   10200:   fprintf(ficlog,"ncovf=%d, ncovv=%d, ncova=%d, nsd=%d, nsq=%d\n",ncovf,ncovv,ncova,nsd, nsq);
1.137     brouard  10201:   return (0); /* with covar[new additional covariate if product] and Tage if age */ 
1.164     brouard  10202:   /*endread:*/
1.225     brouard  10203:   printf("Exiting decodemodel: ");
                   10204:   return (1);
1.136     brouard  10205: }
                   10206: 
1.169     brouard  10207: int calandcheckages(int imx, int maxwav, double *agemin, double *agemax, int *nberr, int *nbwarn )
1.248     brouard  10208: {/* Check ages at death */
1.136     brouard  10209:   int i, m;
1.218     brouard  10210:   int firstone=0;
                   10211:   
1.136     brouard  10212:   for (i=1; i<=imx; i++) {
                   10213:     for(m=2; (m<= maxwav); m++) {
                   10214:       if (((int)mint[m][i]== 99) && (s[m][i] <= nlstate)){
                   10215:        anint[m][i]=9999;
1.216     brouard  10216:        if (s[m][i] != -2) /* Keeping initial status of unknown vital status */
                   10217:          s[m][i]=-1;
1.136     brouard  10218:       }
                   10219:       if((int)moisdc[i]==99 && (int)andc[i]==9999 && s[m][i]>nlstate){
1.260     brouard  10220:        *nberr = *nberr + 1;
1.218     brouard  10221:        if(firstone == 0){
                   10222:          firstone=1;
1.260     brouard  10223:        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  10224:        }
1.262     brouard  10225:        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  10226:        s[m][i]=-1;  /* Droping the death status */
1.136     brouard  10227:       }
                   10228:       if((int)moisdc[i]==99 && (int)andc[i]!=9999 && s[m][i]>nlstate){
1.169     brouard  10229:        (*nberr)++;
1.259     brouard  10230:        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  10231:        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  10232:        s[m][i]=-2; /* We prefer to skip it (and to skip it in version 0.8a1 too */
1.136     brouard  10233:       }
                   10234:     }
                   10235:   }
                   10236: 
                   10237:   for (i=1; i<=imx; i++)  {
                   10238:     agedc[i]=(moisdc[i]/12.+andc[i])-(moisnais[i]/12.+annais[i]);
                   10239:     for(m=firstpass; (m<= lastpass); m++){
1.214     brouard  10240:       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  10241:        if (s[m][i] >= nlstate+1) {
1.169     brouard  10242:          if(agedc[i]>0){
                   10243:            if((int)moisdc[i]!=99 && (int)andc[i]!=9999){
1.136     brouard  10244:              agev[m][i]=agedc[i];
1.214     brouard  10245:              /*if(moisdc[i]==99 && andc[i]==9999) s[m][i]=-1;*/
1.169     brouard  10246:            }else {
1.136     brouard  10247:              if ((int)andc[i]!=9999){
                   10248:                nbwarn++;
                   10249:                printf("Warning negative age at death: %ld line:%d\n",num[i],i);
                   10250:                fprintf(ficlog,"Warning negative age at death: %ld line:%d\n",num[i],i);
                   10251:                agev[m][i]=-1;
                   10252:              }
                   10253:            }
1.169     brouard  10254:          } /* agedc > 0 */
1.214     brouard  10255:        } /* end if */
1.136     brouard  10256:        else if(s[m][i] !=9){ /* Standard case, age in fractional
                   10257:                                 years but with the precision of a month */
                   10258:          agev[m][i]=(mint[m][i]/12.+1./24.+anint[m][i])-(moisnais[i]/12.+1./24.+annais[i]);
                   10259:          if((int)mint[m][i]==99 || (int)anint[m][i]==9999)
                   10260:            agev[m][i]=1;
                   10261:          else if(agev[m][i] < *agemin){ 
                   10262:            *agemin=agev[m][i];
                   10263:            printf(" Min anint[%d][%d]=%.2f annais[%d]=%.2f, agemin=%.2f\n",m,i,anint[m][i], i,annais[i], *agemin);
                   10264:          }
                   10265:          else if(agev[m][i] >*agemax){
                   10266:            *agemax=agev[m][i];
1.156     brouard  10267:            /* printf(" Max anint[%d][%d]=%.0f annais[%d]=%.0f, agemax=%.2f\n",m,i,anint[m][i], i,annais[i], *agemax);*/
1.136     brouard  10268:          }
                   10269:          /*agev[m][i]=anint[m][i]-annais[i];*/
                   10270:          /*     agev[m][i] = age[i]+2*m;*/
1.214     brouard  10271:        } /* en if 9*/
1.136     brouard  10272:        else { /* =9 */
1.214     brouard  10273:          /* printf("Debug num[%d]=%ld s[%d][%d]=%d\n",i,num[i], m,i, s[m][i]); */
1.136     brouard  10274:          agev[m][i]=1;
                   10275:          s[m][i]=-1;
                   10276:        }
                   10277:       }
1.214     brouard  10278:       else if(s[m][i]==0) /*= 0 Unknown */
1.136     brouard  10279:        agev[m][i]=1;
1.214     brouard  10280:       else{
                   10281:        printf("Warning, num[%d]=%ld, s[%d][%d]=%d\n", i, num[i], m, i,s[m][i]); 
                   10282:        fprintf(ficlog, "Warning, num[%d]=%ld, s[%d][%d]=%d\n", i, num[i], m, i,s[m][i]); 
                   10283:        agev[m][i]=0;
                   10284:       }
                   10285:     } /* End for lastpass */
                   10286:   }
1.136     brouard  10287:     
                   10288:   for (i=1; i<=imx; i++)  {
                   10289:     for(m=firstpass; (m<=lastpass); m++){
                   10290:       if (s[m][i] > (nlstate+ndeath)) {
1.169     brouard  10291:        (*nberr)++;
1.136     brouard  10292:        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);     
                   10293:        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);     
                   10294:        return 1;
                   10295:       }
                   10296:     }
                   10297:   }
                   10298: 
                   10299:   /*for (i=1; i<=imx; i++){
                   10300:   for (m=firstpass; (m<lastpass); m++){
                   10301:      printf("%ld %d %.lf %d %d\n", num[i],(covar[1][i]),agev[m][i],s[m][i],s[m+1][i]);
                   10302: }
                   10303: 
                   10304: }*/
                   10305: 
                   10306: 
1.139     brouard  10307:   printf("Total number of individuals= %d, Agemin = %.2f, Agemax= %.2f\n\n", imx, *agemin, *agemax);
                   10308:   fprintf(ficlog,"Total number of individuals= %d, Agemin = %.2f, Agemax= %.2f\n\n", imx, *agemin, *agemax); 
1.136     brouard  10309: 
                   10310:   return (0);
1.164     brouard  10311:  /* endread:*/
1.136     brouard  10312:     printf("Exiting calandcheckages: ");
                   10313:     return (1);
                   10314: }
                   10315: 
1.172     brouard  10316: #if defined(_MSC_VER)
                   10317: /*printf("Visual C++ compiler: %s \n;", _MSC_FULL_VER);*/
                   10318: /*fprintf(ficlog, "Visual C++ compiler: %s \n;", _MSC_FULL_VER);*/
                   10319: //#include "stdafx.h"
                   10320: //#include <stdio.h>
                   10321: //#include <tchar.h>
                   10322: //#include <windows.h>
                   10323: //#include <iostream>
                   10324: typedef BOOL(WINAPI *LPFN_ISWOW64PROCESS) (HANDLE, PBOOL);
                   10325: 
                   10326: LPFN_ISWOW64PROCESS fnIsWow64Process;
                   10327: 
                   10328: BOOL IsWow64()
                   10329: {
                   10330:        BOOL bIsWow64 = FALSE;
                   10331: 
                   10332:        //typedef BOOL (APIENTRY *LPFN_ISWOW64PROCESS)
                   10333:        //  (HANDLE, PBOOL);
                   10334: 
                   10335:        //LPFN_ISWOW64PROCESS fnIsWow64Process;
                   10336: 
                   10337:        HMODULE module = GetModuleHandle(_T("kernel32"));
                   10338:        const char funcName[] = "IsWow64Process";
                   10339:        fnIsWow64Process = (LPFN_ISWOW64PROCESS)
                   10340:                GetProcAddress(module, funcName);
                   10341: 
                   10342:        if (NULL != fnIsWow64Process)
                   10343:        {
                   10344:                if (!fnIsWow64Process(GetCurrentProcess(),
                   10345:                        &bIsWow64))
                   10346:                        //throw std::exception("Unknown error");
                   10347:                        printf("Unknown error\n");
                   10348:        }
                   10349:        return bIsWow64 != FALSE;
                   10350: }
                   10351: #endif
1.177     brouard  10352: 
1.191     brouard  10353: void syscompilerinfo(int logged)
1.292     brouard  10354: {
                   10355: #include <stdint.h>
                   10356: 
                   10357:   /* #include "syscompilerinfo.h"*/
1.185     brouard  10358:    /* command line Intel compiler 32bit windows, XP compatible:*/
                   10359:    /* /GS /W3 /Gy
                   10360:       /Zc:wchar_t /Zi /O2 /Fd"Release\vc120.pdb" /D "WIN32" /D "NDEBUG" /D
                   10361:       "_CONSOLE" /D "_LIB" /D "_USING_V110_SDK71_" /D "_UNICODE" /D
                   10362:       "UNICODE" /Qipo /Zc:forScope /Gd /Oi /MT /Fa"Release\" /EHsc /nologo
1.186     brouard  10363:       /Fo"Release\" /Qprof-dir "Release\" /Fp"Release\IMaCh.pch"
                   10364:    */ 
                   10365:    /* 64 bits */
1.185     brouard  10366:    /*
                   10367:      /GS /W3 /Gy
                   10368:      /Zc:wchar_t /Zi /O2 /Fd"x64\Release\vc120.pdb" /D "WIN32" /D "NDEBUG"
                   10369:      /D "_CONSOLE" /D "_LIB" /D "_UNICODE" /D "UNICODE" /Qipo /Zc:forScope
                   10370:      /Oi /MD /Fa"x64\Release\" /EHsc /nologo /Fo"x64\Release\" /Qprof-dir
                   10371:      "x64\Release\" /Fp"x64\Release\IMaCh.pch" */
                   10372:    /* Optimization are useless and O3 is slower than O2 */
                   10373:    /*
                   10374:      /GS /W3 /Gy /Zc:wchar_t /Zi /O3 /Fd"x64\Release\vc120.pdb" /D "WIN32" 
                   10375:      /D "NDEBUG" /D "_CONSOLE" /D "_LIB" /D "_UNICODE" /D "UNICODE" /Qipo 
                   10376:      /Zc:forScope /Oi /MD /Fa"x64\Release\" /EHsc /nologo /Qparallel 
                   10377:      /Fo"x64\Release\" /Qprof-dir "x64\Release\" /Fp"x64\Release\IMaCh.pch" 
                   10378:    */
1.186     brouard  10379:    /* Link is */ /* /OUT:"visual studio
1.185     brouard  10380:       2013\Projects\IMaCh\Release\IMaCh.exe" /MANIFEST /NXCOMPAT
                   10381:       /PDB:"visual studio
                   10382:       2013\Projects\IMaCh\Release\IMaCh.pdb" /DYNAMICBASE
                   10383:       "kernel32.lib" "user32.lib" "gdi32.lib" "winspool.lib"
                   10384:       "comdlg32.lib" "advapi32.lib" "shell32.lib" "ole32.lib"
                   10385:       "oleaut32.lib" "uuid.lib" "odbc32.lib" "odbccp32.lib"
                   10386:       /MACHINE:X86 /OPT:REF /SAFESEH /INCREMENTAL:NO
                   10387:       /SUBSYSTEM:CONSOLE",5.01" /MANIFESTUAC:"level='asInvoker'
                   10388:       uiAccess='false'"
                   10389:       /ManifestFile:"Release\IMaCh.exe.intermediate.manifest" /OPT:ICF
                   10390:       /NOLOGO /TLBID:1
                   10391:    */
1.292     brouard  10392: 
                   10393: 
1.177     brouard  10394: #if defined __INTEL_COMPILER
1.178     brouard  10395: #if defined(__GNUC__)
                   10396:        struct utsname sysInfo;  /* For Intel on Linux and OS/X */
                   10397: #endif
1.177     brouard  10398: #elif defined(__GNUC__) 
1.179     brouard  10399: #ifndef  __APPLE__
1.174     brouard  10400: #include <gnu/libc-version.h>  /* Only on gnu */
1.179     brouard  10401: #endif
1.177     brouard  10402:    struct utsname sysInfo;
1.178     brouard  10403:    int cross = CROSS;
                   10404:    if (cross){
                   10405:           printf("Cross-");
1.191     brouard  10406:           if(logged) fprintf(ficlog, "Cross-");
1.178     brouard  10407:    }
1.174     brouard  10408: #endif
                   10409: 
1.191     brouard  10410:    printf("Compiled with:");if(logged)fprintf(ficlog,"Compiled with:");
1.169     brouard  10411: #if defined(__clang__)
1.191     brouard  10412:    printf(" Clang/LLVM");if(logged)fprintf(ficlog," Clang/LLVM");      /* Clang/LLVM. ---------------------------------------------- */
1.169     brouard  10413: #endif
                   10414: #if defined(__ICC) || defined(__INTEL_COMPILER)
1.191     brouard  10415:    printf(" Intel ICC/ICPC");if(logged)fprintf(ficlog," Intel ICC/ICPC");/* Intel ICC/ICPC. ------------------------------------------ */
1.169     brouard  10416: #endif
                   10417: #if defined(__GNUC__) || defined(__GNUG__)
1.191     brouard  10418:    printf(" GNU GCC/G++");if(logged)fprintf(ficlog," GNU GCC/G++");/* GNU GCC/G++. --------------------------------------------- */
1.169     brouard  10419: #endif
                   10420: #if defined(__HP_cc) || defined(__HP_aCC)
1.191     brouard  10421:    printf(" Hewlett-Packard C/aC++");if(logged)fprintf(fcilog," Hewlett-Packard C/aC++"); /* Hewlett-Packard C/aC++. ---------------------------------- */
1.169     brouard  10422: #endif
                   10423: #if defined(__IBMC__) || defined(__IBMCPP__)
1.191     brouard  10424:    printf(" IBM XL C/C++"); if(logged) fprintf(ficlog," IBM XL C/C++");/* IBM XL C/C++. -------------------------------------------- */
1.169     brouard  10425: #endif
                   10426: #if defined(_MSC_VER)
1.191     brouard  10427:    printf(" Microsoft Visual Studio");if(logged)fprintf(ficlog," Microsoft Visual Studio");/* Microsoft Visual Studio. --------------------------------- */
1.169     brouard  10428: #endif
                   10429: #if defined(__PGI)
1.191     brouard  10430:    printf(" Portland Group PGCC/PGCPP");if(logged) fprintf(ficlog," Portland Group PGCC/PGCPP");/* Portland Group PGCC/PGCPP. ------------------------------- */
1.169     brouard  10431: #endif
                   10432: #if defined(__SUNPRO_C) || defined(__SUNPRO_CC)
1.191     brouard  10433:    printf(" Oracle Solaris Studio");if(logged)fprintf(ficlog," Oracle Solaris Studio\n");/* Oracle Solaris Studio. ----------------------------------- */
1.167     brouard  10434: #endif
1.191     brouard  10435:    printf(" for "); if (logged) fprintf(ficlog, " for ");
1.169     brouard  10436:    
1.167     brouard  10437: // http://stackoverflow.com/questions/4605842/how-to-identify-platform-compiler-from-preprocessor-macros
                   10438: #ifdef _WIN32 // note the underscore: without it, it's not msdn official!
                   10439:     // Windows (x64 and x86)
1.191     brouard  10440:    printf("Windows (x64 and x86) ");if(logged) fprintf(ficlog,"Windows (x64 and x86) ");
1.167     brouard  10441: #elif __unix__ // all unices, not all compilers
                   10442:     // Unix
1.191     brouard  10443:    printf("Unix ");if(logged) fprintf(ficlog,"Unix ");
1.167     brouard  10444: #elif __linux__
                   10445:     // linux
1.191     brouard  10446:    printf("linux ");if(logged) fprintf(ficlog,"linux ");
1.167     brouard  10447: #elif __APPLE__
1.174     brouard  10448:     // Mac OS, not sure if this is covered by __posix__ and/or __unix__ though..
1.191     brouard  10449:    printf("Mac OS ");if(logged) fprintf(ficlog,"Mac OS ");
1.167     brouard  10450: #endif
                   10451: 
                   10452: /*  __MINGW32__          */
                   10453: /*  __CYGWIN__  */
                   10454: /* __MINGW64__  */
                   10455: // http://msdn.microsoft.com/en-us/library/b0084kay.aspx
                   10456: /* _MSC_VER  //the Visual C++ compiler is 17.00.51106.1, the _MSC_VER macro evaluates to 1700. Type cl /?  */
                   10457: /* _MSC_FULL_VER //the Visual C++ compiler is 15.00.20706.01, the _MSC_FULL_VER macro evaluates to 150020706 */
                   10458: /* _WIN64  // Defined for applications for Win64. */
                   10459: /* _M_X64 // Defined for compilations that target x64 processors. */
                   10460: /* _DEBUG // Defined when you compile with /LDd, /MDd, and /MTd. */
1.171     brouard  10461: 
1.167     brouard  10462: #if UINTPTR_MAX == 0xffffffff
1.191     brouard  10463:    printf(" 32-bit"); if(logged) fprintf(ficlog," 32-bit");/* 32-bit */
1.167     brouard  10464: #elif UINTPTR_MAX == 0xffffffffffffffff
1.191     brouard  10465:    printf(" 64-bit"); if(logged) fprintf(ficlog," 64-bit");/* 64-bit */
1.167     brouard  10466: #else
1.191     brouard  10467:    printf(" wtf-bit"); if(logged) fprintf(ficlog," wtf-bit");/* wtf */
1.167     brouard  10468: #endif
                   10469: 
1.169     brouard  10470: #if defined(__GNUC__)
                   10471: # if defined(__GNUC_PATCHLEVEL__)
                   10472: #  define __GNUC_VERSION__ (__GNUC__ * 10000 \
                   10473:                             + __GNUC_MINOR__ * 100 \
                   10474:                             + __GNUC_PATCHLEVEL__)
                   10475: # else
                   10476: #  define __GNUC_VERSION__ (__GNUC__ * 10000 \
                   10477:                             + __GNUC_MINOR__ * 100)
                   10478: # endif
1.174     brouard  10479:    printf(" using GNU C version %d.\n", __GNUC_VERSION__);
1.191     brouard  10480:    if(logged) fprintf(ficlog, " using GNU C version %d.\n", __GNUC_VERSION__);
1.176     brouard  10481: 
                   10482:    if (uname(&sysInfo) != -1) {
                   10483:      printf("Running on: %s %s %s %s %s\n",sysInfo.sysname, sysInfo.nodename, sysInfo.release, sysInfo.version, sysInfo.machine);
1.191     brouard  10484:         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  10485:    }
                   10486:    else
                   10487:       perror("uname() error");
1.179     brouard  10488:    //#ifndef __INTEL_COMPILER 
                   10489: #if !defined (__INTEL_COMPILER) && !defined(__APPLE__)
1.174     brouard  10490:    printf("GNU libc version: %s\n", gnu_get_libc_version()); 
1.191     brouard  10491:    if(logged) fprintf(ficlog,"GNU libc version: %s\n", gnu_get_libc_version());
1.177     brouard  10492: #endif
1.169     brouard  10493: #endif
1.172     brouard  10494: 
1.286     brouard  10495:    //   void main ()
1.172     brouard  10496:    //   {
1.169     brouard  10497: #if defined(_MSC_VER)
1.174     brouard  10498:    if (IsWow64()){
1.191     brouard  10499:           printf("\nThe program (probably compiled for 32bit) is running under WOW64 (64bit) emulation.\n");
                   10500:           if (logged) fprintf(ficlog, "\nThe program (probably compiled for 32bit) is running under WOW64 (64bit) emulation.\n");
1.174     brouard  10501:    }
                   10502:    else{
1.191     brouard  10503:           printf("\nThe program is not running under WOW64 (i.e probably on a 64bit Windows).\n");
                   10504:           if (logged) fprintf(ficlog, "\nThe programm is not running under WOW64 (i.e probably on a 64bit Windows).\n");
1.174     brouard  10505:    }
1.172     brouard  10506:    //     printf("\nPress Enter to continue...");
                   10507:    //     getchar();
                   10508:    //   }
                   10509: 
1.169     brouard  10510: #endif
                   10511:    
1.167     brouard  10512: 
1.219     brouard  10513: }
1.136     brouard  10514: 
1.219     brouard  10515: int prevalence_limit(double *p, double **prlim, double ageminpar, double agemaxpar, double ftolpl, int *ncvyearp){
1.288     brouard  10516:   /*--------------- Prevalence limit  (forward period or forward stable prevalence) --------------*/
1.235     brouard  10517:   int i, j, k, i1, k4=0, nres=0 ;
1.202     brouard  10518:   /* double ftolpl = 1.e-10; */
1.180     brouard  10519:   double age, agebase, agelim;
1.203     brouard  10520:   double tot;
1.180     brouard  10521: 
1.202     brouard  10522:   strcpy(filerespl,"PL_");
                   10523:   strcat(filerespl,fileresu);
                   10524:   if((ficrespl=fopen(filerespl,"w"))==NULL) {
1.288     brouard  10525:     printf("Problem with forward period (stable) prevalence resultfile: %s\n", filerespl);return 1;
                   10526:     fprintf(ficlog,"Problem with forward period (stable) prevalence resultfile: %s\n", filerespl);return 1;
1.202     brouard  10527:   }
1.288     brouard  10528:   printf("\nComputing forward period (stable) prevalence: result on file '%s' \n", filerespl);
                   10529:   fprintf(ficlog,"\nComputing forward period (stable) prevalence: result on file '%s' \n", filerespl);
1.202     brouard  10530:   pstamp(ficrespl);
1.288     brouard  10531:   fprintf(ficrespl,"# Forward period (stable) prevalence. Precision given by ftolpl=%g \n", ftolpl);
1.202     brouard  10532:   fprintf(ficrespl,"#Age ");
                   10533:   for(i=1; i<=nlstate;i++) fprintf(ficrespl,"%d-%d ",i,i);
                   10534:   fprintf(ficrespl,"\n");
1.180     brouard  10535:   
1.219     brouard  10536:   /* prlim=matrix(1,nlstate,1,nlstate);*/ /* back in main */
1.180     brouard  10537: 
1.219     brouard  10538:   agebase=ageminpar;
                   10539:   agelim=agemaxpar;
1.180     brouard  10540: 
1.227     brouard  10541:   /* i1=pow(2,ncoveff); */
1.234     brouard  10542:   i1=pow(2,cptcoveff); /* Number of combination of dummy covariates */
1.219     brouard  10543:   if (cptcovn < 1){i1=1;}
1.180     brouard  10544: 
1.238     brouard  10545:   for(k=1; k<=i1;k++){ /* For each combination k of dummy covariates in the model */
                   10546:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.253     brouard  10547:       if(i1 != 1 && TKresult[nres]!= k)
1.238     brouard  10548:        continue;
1.235     brouard  10549: 
1.238     brouard  10550:       /* for(cptcov=1,k=0;cptcov<=i1;cptcov++){ */
                   10551:       /* for(cptcov=1,k=0;cptcov<=1;cptcov++){ */
                   10552:       //for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){
                   10553:       /* k=k+1; */
                   10554:       /* to clean */
                   10555:       //printf("cptcov=%d cptcod=%d codtab=%d\n",cptcov, cptcod,codtabm(cptcod,cptcov));
                   10556:       fprintf(ficrespl,"#******");
                   10557:       printf("#******");
                   10558:       fprintf(ficlog,"#******");
                   10559:       for(j=1;j<=cptcoveff ;j++) {/* all covariates */
                   10560:        fprintf(ficrespl," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]); /* Here problem for varying dummy*/
                   10561:        printf(" V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   10562:        fprintf(ficlog," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   10563:       }
                   10564:       for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
                   10565:        printf(" V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
                   10566:        fprintf(ficrespl," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
                   10567:        fprintf(ficlog," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
                   10568:       }
                   10569:       fprintf(ficrespl,"******\n");
                   10570:       printf("******\n");
                   10571:       fprintf(ficlog,"******\n");
                   10572:       if(invalidvarcomb[k]){
                   10573:        printf("\nCombination (%d) ignored because no case \n",k); 
                   10574:        fprintf(ficrespl,"#Combination (%d) ignored because no case \n",k); 
                   10575:        fprintf(ficlog,"\nCombination (%d) ignored because no case \n",k); 
                   10576:        continue;
                   10577:       }
1.219     brouard  10578: 
1.238     brouard  10579:       fprintf(ficrespl,"#Age ");
                   10580:       for(j=1;j<=cptcoveff;j++) {
                   10581:        fprintf(ficrespl,"V%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   10582:       }
                   10583:       for(i=1; i<=nlstate;i++) fprintf(ficrespl,"  %d-%d   ",i,i);
                   10584:       fprintf(ficrespl,"Total Years_to_converge\n");
1.227     brouard  10585:     
1.238     brouard  10586:       for (age=agebase; age<=agelim; age++){
                   10587:        /* for (age=agebase; age<=agebase; age++){ */
                   10588:        prevalim(prlim, nlstate, p, age, oldm, savm, ftolpl, ncvyearp, k, nres);
                   10589:        fprintf(ficrespl,"%.0f ",age );
                   10590:        for(j=1;j<=cptcoveff;j++)
                   10591:          fprintf(ficrespl,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   10592:        tot=0.;
                   10593:        for(i=1; i<=nlstate;i++){
                   10594:          tot +=  prlim[i][i];
                   10595:          fprintf(ficrespl," %.5f", prlim[i][i]);
                   10596:        }
                   10597:        fprintf(ficrespl," %.3f %d\n", tot, *ncvyearp);
                   10598:       } /* Age */
                   10599:       /* was end of cptcod */
                   10600:     } /* cptcov */
                   10601:   } /* nres */
1.219     brouard  10602:   return 0;
1.180     brouard  10603: }
                   10604: 
1.218     brouard  10605: 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  10606:        /*--------------- Back Prevalence limit  (backward stable prevalence) --------------*/
1.218     brouard  10607:        
                   10608:        /* Computes the back prevalence limit  for any combination      of covariate values 
                   10609:    * at any age between ageminpar and agemaxpar
                   10610:         */
1.235     brouard  10611:   int i, j, k, i1, nres=0 ;
1.217     brouard  10612:   /* double ftolpl = 1.e-10; */
                   10613:   double age, agebase, agelim;
                   10614:   double tot;
1.218     brouard  10615:   /* double ***mobaverage; */
                   10616:   /* double     **dnewm, **doldm, **dsavm;  /\* for use *\/ */
1.217     brouard  10617: 
                   10618:   strcpy(fileresplb,"PLB_");
                   10619:   strcat(fileresplb,fileresu);
                   10620:   if((ficresplb=fopen(fileresplb,"w"))==NULL) {
1.288     brouard  10621:     printf("Problem with backward prevalence resultfile: %s\n", fileresplb);return 1;
                   10622:     fprintf(ficlog,"Problem with backward prevalence resultfile: %s\n", fileresplb);return 1;
1.217     brouard  10623:   }
1.288     brouard  10624:   printf("Computing backward prevalence: result on file '%s' \n", fileresplb);
                   10625:   fprintf(ficlog,"Computing backward prevalence: result on file '%s' \n", fileresplb);
1.217     brouard  10626:   pstamp(ficresplb);
1.288     brouard  10627:   fprintf(ficresplb,"# Backward prevalence. Precision given by ftolpl=%g \n", ftolpl);
1.217     brouard  10628:   fprintf(ficresplb,"#Age ");
                   10629:   for(i=1; i<=nlstate;i++) fprintf(ficresplb,"%d-%d ",i,i);
                   10630:   fprintf(ficresplb,"\n");
                   10631:   
1.218     brouard  10632:   
                   10633:   /* prlim=matrix(1,nlstate,1,nlstate);*/ /* back in main */
                   10634:   
                   10635:   agebase=ageminpar;
                   10636:   agelim=agemaxpar;
                   10637:   
                   10638:   
1.227     brouard  10639:   i1=pow(2,cptcoveff);
1.218     brouard  10640:   if (cptcovn < 1){i1=1;}
1.227     brouard  10641:   
1.238     brouard  10642:   for(nres=1; nres <= nresult; nres++){ /* For each resultline */
                   10643:     for(k=1; k<=i1;k++){ /* For any combination of dummy covariates, fixed and varying */
1.253     brouard  10644:      if(i1 != 1 && TKresult[nres]!= k)
1.238     brouard  10645:        continue;
                   10646:       //printf("cptcov=%d cptcod=%d codtab=%d\n",cptcov, cptcod,codtabm(cptcod,cptcov));
                   10647:       fprintf(ficresplb,"#******");
                   10648:       printf("#******");
                   10649:       fprintf(ficlog,"#******");
                   10650:       for(j=1;j<=cptcoveff ;j++) {/* all covariates */
                   10651:        fprintf(ficresplb," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   10652:        printf(" V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   10653:        fprintf(ficlog," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   10654:       }
                   10655:       for (j=1; j<= nsq; j++){ /* For each selected (single) quantitative value */
                   10656:        printf(" V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]);
                   10657:        fprintf(ficresplb," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]);
                   10658:        fprintf(ficlog," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]);
                   10659:       }
                   10660:       fprintf(ficresplb,"******\n");
                   10661:       printf("******\n");
                   10662:       fprintf(ficlog,"******\n");
                   10663:       if(invalidvarcomb[k]){
                   10664:        printf("\nCombination (%d) ignored because no cases \n",k); 
                   10665:        fprintf(ficresplb,"#Combination (%d) ignored because no cases \n",k); 
                   10666:        fprintf(ficlog,"\nCombination (%d) ignored because no cases \n",k); 
                   10667:        continue;
                   10668:       }
1.218     brouard  10669:     
1.238     brouard  10670:       fprintf(ficresplb,"#Age ");
                   10671:       for(j=1;j<=cptcoveff;j++) {
                   10672:        fprintf(ficresplb,"V%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   10673:       }
                   10674:       for(i=1; i<=nlstate;i++) fprintf(ficresplb,"  %d-%d   ",i,i);
                   10675:       fprintf(ficresplb,"Total Years_to_converge\n");
1.218     brouard  10676:     
                   10677:     
1.238     brouard  10678:       for (age=agebase; age<=agelim; age++){
                   10679:        /* for (age=agebase; age<=agebase; age++){ */
                   10680:        if(mobilavproj > 0){
                   10681:          /* bprevalim(bprlim, mobaverage, nlstate, p, age, ageminpar, agemaxpar, oldm, savm, doldm, dsavm, ftolpl, ncvyearp, k); */
                   10682:          /* bprevalim(bprlim, mobaverage, nlstate, p, age, oldm, savm, dnewm, doldm, dsavm, ftolpl, ncvyearp, k); */
1.242     brouard  10683:          bprevalim(bprlim, mobaverage, nlstate, p, age, ftolpl, ncvyearp, k, nres);
1.238     brouard  10684:        }else if (mobilavproj == 0){
                   10685:          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);
                   10686:          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);
                   10687:          exit(1);
                   10688:        }else{
                   10689:          /* bprevalim(bprlim, probs, nlstate, p, age, oldm, savm, dnewm, doldm, dsavm, ftolpl, ncvyearp, k); */
1.242     brouard  10690:          bprevalim(bprlim, probs, nlstate, p, age, ftolpl, ncvyearp, k,nres);
1.266     brouard  10691:          /* printf("TOTOT\n"); */
                   10692:           /* exit(1); */
1.238     brouard  10693:        }
                   10694:        fprintf(ficresplb,"%.0f ",age );
                   10695:        for(j=1;j<=cptcoveff;j++)
                   10696:          fprintf(ficresplb,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   10697:        tot=0.;
                   10698:        for(i=1; i<=nlstate;i++){
                   10699:          tot +=  bprlim[i][i];
                   10700:          fprintf(ficresplb," %.5f", bprlim[i][i]);
                   10701:        }
                   10702:        fprintf(ficresplb," %.3f %d\n", tot, *ncvyearp);
                   10703:       } /* Age */
                   10704:       /* was end of cptcod */
1.255     brouard  10705:       /*fprintf(ficresplb,"\n");*/ /* Seems to be necessary for gnuplot only if two result lines and no covariate. */
1.238     brouard  10706:     } /* end of any combination */
                   10707:   } /* end of nres */  
1.218     brouard  10708:   /* hBijx(p, bage, fage); */
                   10709:   /* fclose(ficrespijb); */
                   10710:   
                   10711:   return 0;
1.217     brouard  10712: }
1.218     brouard  10713:  
1.180     brouard  10714: int hPijx(double *p, int bage, int fage){
                   10715:     /*------------- h Pij x at various ages ------------*/
                   10716: 
                   10717:   int stepsize;
                   10718:   int agelim;
                   10719:   int hstepm;
                   10720:   int nhstepm;
1.235     brouard  10721:   int h, i, i1, j, k, k4, nres=0;
1.180     brouard  10722: 
                   10723:   double agedeb;
                   10724:   double ***p3mat;
                   10725: 
1.201     brouard  10726:     strcpy(filerespij,"PIJ_");  strcat(filerespij,fileresu);
1.180     brouard  10727:     if((ficrespij=fopen(filerespij,"w"))==NULL) {
                   10728:       printf("Problem with Pij resultfile: %s\n", filerespij); return 1;
                   10729:       fprintf(ficlog,"Problem with Pij resultfile: %s\n", filerespij); return 1;
                   10730:     }
                   10731:     printf("Computing pij: result on file '%s' \n", filerespij);
                   10732:     fprintf(ficlog,"Computing pij: result on file '%s' \n", filerespij);
                   10733:   
                   10734:     stepsize=(int) (stepm+YEARM-1)/YEARM;
                   10735:     /*if (stepm<=24) stepsize=2;*/
                   10736: 
                   10737:     agelim=AGESUP;
                   10738:     hstepm=stepsize*YEARM; /* Every year of age */
                   10739:     hstepm=hstepm/stepm; /* Typically 2 years, = 2/6 months = 4 */ 
1.218     brouard  10740:                
1.180     brouard  10741:     /* hstepm=1;   aff par mois*/
                   10742:     pstamp(ficrespij);
                   10743:     fprintf(ficrespij,"#****** h Pij x Probability to be in state j at age x+h being in i at x ");
1.227     brouard  10744:     i1= pow(2,cptcoveff);
1.218     brouard  10745:                /* for(cptcov=1,k=0;cptcov<=i1;cptcov++){ */
                   10746:                /*    /\*for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*\/ */
                   10747:                /*      k=k+1;  */
1.235     brouard  10748:     for(nres=1; nres <= nresult; nres++) /* For each resultline */
                   10749:     for(k=1; k<=i1;k++){
1.253     brouard  10750:       if(i1 != 1 && TKresult[nres]!= k)
1.235     brouard  10751:        continue;
1.183     brouard  10752:       fprintf(ficrespij,"\n#****** ");
1.227     brouard  10753:       for(j=1;j<=cptcoveff;j++) 
1.198     brouard  10754:        fprintf(ficrespij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
1.235     brouard  10755:       for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
                   10756:        printf(" V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
                   10757:        fprintf(ficrespij," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
                   10758:       }
1.183     brouard  10759:       fprintf(ficrespij,"******\n");
                   10760:       
                   10761:       for (agedeb=fage; agedeb>=bage; agedeb--){ /* If stepm=6 months */
                   10762:        nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */ 
                   10763:        nhstepm = nhstepm/hstepm; /* Typically 40/4=10 */
                   10764:        
                   10765:        /*        nhstepm=nhstepm*YEARM; aff par mois*/
1.180     brouard  10766:        
1.183     brouard  10767:        p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   10768:        oldm=oldms;savm=savms;
1.235     brouard  10769:        hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k, nres);  
1.183     brouard  10770:        fprintf(ficrespij,"# Cov Agex agex+h hpijx with i,j=");
                   10771:        for(i=1; i<=nlstate;i++)
                   10772:          for(j=1; j<=nlstate+ndeath;j++)
                   10773:            fprintf(ficrespij," %1d-%1d",i,j);
                   10774:        fprintf(ficrespij,"\n");
                   10775:        for (h=0; h<=nhstepm; h++){
                   10776:          /*agedebphstep = agedeb + h*hstepm/YEARM*stepm;*/
                   10777:          fprintf(ficrespij,"%d %3.f %3.f",k, agedeb, agedeb + h*hstepm/YEARM*stepm );
1.180     brouard  10778:          for(i=1; i<=nlstate;i++)
                   10779:            for(j=1; j<=nlstate+ndeath;j++)
1.183     brouard  10780:              fprintf(ficrespij," %.5f", p3mat[i][j][h]);
1.180     brouard  10781:          fprintf(ficrespij,"\n");
                   10782:        }
1.183     brouard  10783:        free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   10784:        fprintf(ficrespij,"\n");
                   10785:       }
1.180     brouard  10786:       /*}*/
                   10787:     }
1.218     brouard  10788:     return 0;
1.180     brouard  10789: }
1.218     brouard  10790:  
                   10791:  int hBijx(double *p, int bage, int fage, double ***prevacurrent){
1.217     brouard  10792:     /*------------- h Bij x at various ages ------------*/
                   10793: 
                   10794:   int stepsize;
1.218     brouard  10795:   /* int agelim; */
                   10796:        int ageminl;
1.217     brouard  10797:   int hstepm;
                   10798:   int nhstepm;
1.238     brouard  10799:   int h, i, i1, j, k, nres;
1.218     brouard  10800:        
1.217     brouard  10801:   double agedeb;
                   10802:   double ***p3mat;
1.218     brouard  10803:        
                   10804:   strcpy(filerespijb,"PIJB_");  strcat(filerespijb,fileresu);
                   10805:   if((ficrespijb=fopen(filerespijb,"w"))==NULL) {
                   10806:     printf("Problem with Pij back resultfile: %s\n", filerespijb); return 1;
                   10807:     fprintf(ficlog,"Problem with Pij back resultfile: %s\n", filerespijb); return 1;
                   10808:   }
                   10809:   printf("Computing pij back: result on file '%s' \n", filerespijb);
                   10810:   fprintf(ficlog,"Computing pij back: result on file '%s' \n", filerespijb);
                   10811:   
                   10812:   stepsize=(int) (stepm+YEARM-1)/YEARM;
                   10813:   /*if (stepm<=24) stepsize=2;*/
1.217     brouard  10814:   
1.218     brouard  10815:   /* agelim=AGESUP; */
1.289     brouard  10816:   ageminl=AGEINF; /* was 30 */
1.218     brouard  10817:   hstepm=stepsize*YEARM; /* Every year of age */
                   10818:   hstepm=hstepm/stepm; /* Typically 2 years, = 2/6 months = 4 */
                   10819:   
                   10820:   /* hstepm=1;   aff par mois*/
                   10821:   pstamp(ficrespijb);
1.255     brouard  10822:   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  10823:   i1= pow(2,cptcoveff);
1.218     brouard  10824:   /* for(cptcov=1,k=0;cptcov<=i1;cptcov++){ */
                   10825:   /*    /\*for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*\/ */
                   10826:   /*   k=k+1;  */
1.238     brouard  10827:   for(nres=1; nres <= nresult; nres++){ /* For each resultline */
                   10828:     for(k=1; k<=i1;k++){ /* For any combination of dummy covariates, fixed and varying */
1.253     brouard  10829:       if(i1 != 1 && TKresult[nres]!= k)
1.238     brouard  10830:        continue;
                   10831:       fprintf(ficrespijb,"\n#****** ");
                   10832:       for(j=1;j<=cptcoveff;j++)
                   10833:        fprintf(ficrespijb,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   10834:       for (j=1; j<= nsq; j++){ /* For each selected (single) quantitative value */
                   10835:        fprintf(ficrespijb," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]);
                   10836:       }
                   10837:       fprintf(ficrespijb,"******\n");
1.264     brouard  10838:       if(invalidvarcomb[k]){  /* Is it necessary here? */
1.238     brouard  10839:        fprintf(ficrespijb,"\n#Combination (%d) ignored because no cases \n",k); 
                   10840:        continue;
                   10841:       }
                   10842:       
                   10843:       /* for (agedeb=fage; agedeb>=bage; agedeb--){ /\* If stepm=6 months *\/ */
                   10844:       for (agedeb=bage; agedeb<=fage; agedeb++){ /* If stepm=6 months and estepm=24 (2 years) */
                   10845:        /* nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm); /\* Typically 20 years = 20*12/6=40 *\/ */
1.297     brouard  10846:        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 */
                   10847:        nhstepm = nhstepm/hstepm; /* Typically 40/4=10, because estepm=24 stepm=6 => hstepm=24/6=4 or 28*/
1.238     brouard  10848:        
                   10849:        /*        nhstepm=nhstepm*YEARM; aff par mois*/
                   10850:        
1.266     brouard  10851:        p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm); /* We can't have it at an upper level because of nhstepm */
                   10852:        /* and memory limitations if stepm is small */
                   10853: 
1.238     brouard  10854:        /* oldm=oldms;savm=savms; */
                   10855:        /* hbxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);   */
1.267     brouard  10856:        hbxij(p3mat,nhstepm,agedeb,hstepm,p,prevacurrent,nlstate,stepm, k, nres);
1.238     brouard  10857:        /* hbxij(p3mat,nhstepm,agedeb,hstepm,p,prevacurrent,nlstate,stepm,oldm,savm, dnewm, doldm, dsavm, k); */
1.255     brouard  10858:        fprintf(ficrespijb,"# Cov Agex agex-h hbijx with i,j=");
1.217     brouard  10859:        for(i=1; i<=nlstate;i++)
                   10860:          for(j=1; j<=nlstate+ndeath;j++)
1.238     brouard  10861:            fprintf(ficrespijb," %1d-%1d",i,j);
1.217     brouard  10862:        fprintf(ficrespijb,"\n");
1.238     brouard  10863:        for (h=0; h<=nhstepm; h++){
                   10864:          /*agedebphstep = agedeb + h*hstepm/YEARM*stepm;*/
                   10865:          fprintf(ficrespijb,"%d %3.f %3.f",k, agedeb, agedeb - h*hstepm/YEARM*stepm );
                   10866:          /* fprintf(ficrespijb,"%d %3.f %3.f",k, agedeb, agedeb + h*hstepm/YEARM*stepm ); */
                   10867:          for(i=1; i<=nlstate;i++)
                   10868:            for(j=1; j<=nlstate+ndeath;j++)
                   10869:              fprintf(ficrespijb," %.5f", p3mat[i][j][h]);
                   10870:          fprintf(ficrespijb,"\n");
                   10871:        }
                   10872:        free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   10873:        fprintf(ficrespijb,"\n");
                   10874:       } /* end age deb */
                   10875:     } /* end combination */
                   10876:   } /* end nres */
1.218     brouard  10877:   return 0;
                   10878:  } /*  hBijx */
1.217     brouard  10879: 
1.180     brouard  10880: 
1.136     brouard  10881: /***********************************************/
                   10882: /**************** Main Program *****************/
                   10883: /***********************************************/
                   10884: 
                   10885: int main(int argc, char *argv[])
                   10886: {
                   10887: #ifdef GSL
                   10888:   const gsl_multimin_fminimizer_type *T;
                   10889:   size_t iteri = 0, it;
                   10890:   int rval = GSL_CONTINUE;
                   10891:   int status = GSL_SUCCESS;
                   10892:   double ssval;
                   10893: #endif
                   10894:   int movingaverage(double ***probs, double bage,double fage, double ***mobaverage, int mobilav);
1.290     brouard  10895:   int i,j, k, iter=0,m,size=100, cptcod; /* Suppressing because nobs */
                   10896:   /* int i,j, k, n=MAXN,iter=0,m,size=100, cptcod; */
1.209     brouard  10897:   int ncvyear=0; /* Number of years needed for the period prevalence to converge */
1.164     brouard  10898:   int jj, ll, li, lj, lk;
1.136     brouard  10899:   int numlinepar=0; /* Current linenumber of parameter file */
1.197     brouard  10900:   int num_filled;
1.136     brouard  10901:   int itimes;
                   10902:   int NDIM=2;
                   10903:   int vpopbased=0;
1.235     brouard  10904:   int nres=0;
1.258     brouard  10905:   int endishere=0;
1.277     brouard  10906:   int noffset=0;
1.274     brouard  10907:   int ncurrv=0; /* Temporary variable */
                   10908:   
1.164     brouard  10909:   char ca[32], cb[32];
1.136     brouard  10910:   /*  FILE *fichtm; *//* Html File */
                   10911:   /* FILE *ficgp;*/ /*Gnuplot File */
                   10912:   struct stat info;
1.191     brouard  10913:   double agedeb=0.;
1.194     brouard  10914: 
                   10915:   double ageminpar=AGEOVERFLOW,agemin=AGEOVERFLOW, agemaxpar=-AGEOVERFLOW, agemax=-AGEOVERFLOW;
1.219     brouard  10916:   double ageminout=-AGEOVERFLOW,agemaxout=AGEOVERFLOW; /* Smaller Age range redefined after movingaverage */
1.136     brouard  10917: 
1.165     brouard  10918:   double fret;
1.191     brouard  10919:   double dum=0.; /* Dummy variable */
1.136     brouard  10920:   double ***p3mat;
1.218     brouard  10921:   /* double ***mobaverage; */
1.164     brouard  10922: 
                   10923:   char line[MAXLINE];
1.197     brouard  10924:   char path[MAXLINE],pathc[MAXLINE],pathcd[MAXLINE],pathtot[MAXLINE];
                   10925: 
1.234     brouard  10926:   char  modeltemp[MAXLINE];
1.230     brouard  10927:   char resultline[MAXLINE];
                   10928:   
1.136     brouard  10929:   char pathr[MAXLINE], pathimach[MAXLINE]; 
1.164     brouard  10930:   char *tok, *val; /* pathtot */
1.290     brouard  10931:   int firstobs=1, lastobs=10; /* nobs = lastobs-firstobs declared globally ;*/
1.195     brouard  10932:   int c,  h , cpt, c2;
1.191     brouard  10933:   int jl=0;
                   10934:   int i1, j1, jk, stepsize=0;
1.194     brouard  10935:   int count=0;
                   10936: 
1.164     brouard  10937:   int *tab; 
1.136     brouard  10938:   int mobilavproj=0 , prevfcast=0 ; /* moving average of prev, If prevfcast=1 prevalence projection */
1.296     brouard  10939:   /* double anprojd, mprojd, jprojd; /\* For eventual projections *\/ */
                   10940:   /* double anprojf, mprojf, jprojf; */
                   10941:   /* double jintmean,mintmean,aintmean;   */
                   10942:   int prvforecast = 0; /* Might be 1 (date of beginning of projection is a choice or 2 is the dateintmean */
                   10943:   int prvbackcast = 0; /* Might be 1 (date of beginning of projection is a choice or 2 is the dateintmean */
                   10944:   double yrfproj= 10.0; /* Number of years of forward projections */
                   10945:   double yrbproj= 10.0; /* Number of years of backward projections */
                   10946:   int prevbcast=0; /* defined as global for mlikeli and mle, replacing backcast */
1.136     brouard  10947:   int mobilav=0,popforecast=0;
1.191     brouard  10948:   int hstepm=0, nhstepm=0;
1.136     brouard  10949:   int agemortsup;
                   10950:   float  sumlpop=0.;
                   10951:   double jprev1=1, mprev1=1,anprev1=2000,jprev2=1, mprev2=1,anprev2=2000;
                   10952:   double jpyram=1, mpyram=1,anpyram=2000,jpyram1=1, mpyram1=1,anpyram1=2000;
                   10953: 
1.191     brouard  10954:   double bage=0, fage=110., age, agelim=0., agebase=0.;
1.136     brouard  10955:   double ftolpl=FTOL;
                   10956:   double **prlim;
1.217     brouard  10957:   double **bprlim;
1.136     brouard  10958:   double ***param; /* Matrix of parameters */
1.251     brouard  10959:   double ***paramstart; /* Matrix of starting parameter values */
                   10960:   double  *p, *pstart; /* p=param[1][1] pstart is for starting values guessed by freqsummary */
1.136     brouard  10961:   double **matcov; /* Matrix of covariance */
1.203     brouard  10962:   double **hess; /* Hessian matrix */
1.136     brouard  10963:   double ***delti3; /* Scale */
                   10964:   double *delti; /* Scale */
                   10965:   double ***eij, ***vareij;
                   10966:   double **varpl; /* Variances of prevalence limits by age */
1.269     brouard  10967: 
1.136     brouard  10968:   double *epj, vepp;
1.164     brouard  10969: 
1.273     brouard  10970:   double dateprev1, dateprev2;
1.296     brouard  10971:   double jproj1=1,mproj1=1,anproj1=2000,jproj2=1,mproj2=1,anproj2=2000, dateproj1=0, dateproj2=0, dateprojd=0, dateprojf=0;
                   10972:   double jback1=1,mback1=1,anback1=2000,jback2=1,mback2=1,anback2=2000, dateback1=0, dateback2=0, datebackd=0, datebackf=0;
                   10973: 
1.217     brouard  10974: 
1.136     brouard  10975:   double **ximort;
1.145     brouard  10976:   char *alph[]={"a","a","b","c","d","e"}, str[4]="1234";
1.136     brouard  10977:   int *dcwave;
                   10978: 
1.164     brouard  10979:   char z[1]="c";
1.136     brouard  10980: 
                   10981:   /*char  *strt;*/
                   10982:   char strtend[80];
1.126     brouard  10983: 
1.164     brouard  10984: 
1.126     brouard  10985: /*   setlocale (LC_ALL, ""); */
                   10986: /*   bindtextdomain (PACKAGE, LOCALEDIR); */
                   10987: /*   textdomain (PACKAGE); */
                   10988: /*   setlocale (LC_CTYPE, ""); */
                   10989: /*   setlocale (LC_MESSAGES, ""); */
                   10990: 
                   10991:   /*   gettimeofday(&start_time, (struct timezone*)0); */ /* at first time */
1.157     brouard  10992:   rstart_time = time(NULL);  
                   10993:   /*  (void) gettimeofday(&start_time,&tzp);*/
                   10994:   start_time = *localtime(&rstart_time);
1.126     brouard  10995:   curr_time=start_time;
1.157     brouard  10996:   /*tml = *localtime(&start_time.tm_sec);*/
                   10997:   /* strcpy(strstart,asctime(&tml)); */
                   10998:   strcpy(strstart,asctime(&start_time));
1.126     brouard  10999: 
                   11000: /*  printf("Localtime (at start)=%s",strstart); */
1.157     brouard  11001: /*  tp.tm_sec = tp.tm_sec +86400; */
                   11002: /*  tm = *localtime(&start_time.tm_sec); */
1.126     brouard  11003: /*   tmg.tm_year=tmg.tm_year +dsign*dyear; */
                   11004: /*   tmg.tm_mon=tmg.tm_mon +dsign*dmonth; */
                   11005: /*   tmg.tm_hour=tmg.tm_hour + 1; */
1.157     brouard  11006: /*   tp.tm_sec = mktime(&tmg); */
1.126     brouard  11007: /*   strt=asctime(&tmg); */
                   11008: /*   printf("Time(after) =%s",strstart);  */
                   11009: /*  (void) time (&time_value);
                   11010: *  printf("time=%d,t-=%d\n",time_value,time_value-86400);
                   11011: *  tm = *localtime(&time_value);
                   11012: *  strstart=asctime(&tm);
                   11013: *  printf("tim_value=%d,asctime=%s\n",time_value,strstart); 
                   11014: */
                   11015: 
                   11016:   nberr=0; /* Number of errors and warnings */
                   11017:   nbwarn=0;
1.184     brouard  11018: #ifdef WIN32
                   11019:   _getcwd(pathcd, size);
                   11020: #else
1.126     brouard  11021:   getcwd(pathcd, size);
1.184     brouard  11022: #endif
1.191     brouard  11023:   syscompilerinfo(0);
1.196     brouard  11024:   printf("\nIMaCh version %s, %s\n%s",version, copyright, fullversion);
1.126     brouard  11025:   if(argc <=1){
                   11026:     printf("\nEnter the parameter file name: ");
1.205     brouard  11027:     if(!fgets(pathr,FILENAMELENGTH,stdin)){
                   11028:       printf("ERROR Empty parameter file name\n");
                   11029:       goto end;
                   11030:     }
1.126     brouard  11031:     i=strlen(pathr);
                   11032:     if(pathr[i-1]=='\n')
                   11033:       pathr[i-1]='\0';
1.156     brouard  11034:     i=strlen(pathr);
1.205     brouard  11035:     if(i >= 1 && pathr[i-1]==' ') {/* This may happen when dragging on oS/X! */
1.156     brouard  11036:       pathr[i-1]='\0';
1.205     brouard  11037:     }
                   11038:     i=strlen(pathr);
                   11039:     if( i==0 ){
                   11040:       printf("ERROR Empty parameter file name\n");
                   11041:       goto end;
                   11042:     }
                   11043:     for (tok = pathr; tok != NULL; ){
1.126     brouard  11044:       printf("Pathr |%s|\n",pathr);
                   11045:       while ((val = strsep(&tok, "\"" )) != NULL && *val == '\0');
                   11046:       printf("val= |%s| pathr=%s\n",val,pathr);
                   11047:       strcpy (pathtot, val);
                   11048:       if(pathr[0] == '\0') break; /* Dirty */
                   11049:     }
                   11050:   }
1.281     brouard  11051:   else if (argc<=2){
                   11052:     strcpy(pathtot,argv[1]);
                   11053:   }
1.126     brouard  11054:   else{
                   11055:     strcpy(pathtot,argv[1]);
1.281     brouard  11056:     strcpy(z,argv[2]);
                   11057:     printf("\nargv[2]=%s z=%c\n",argv[2],z[0]);
1.126     brouard  11058:   }
                   11059:   /*if(getcwd(pathcd, MAXLINE)!= NULL)printf ("Error pathcd\n");*/
                   11060:   /*cygwin_split_path(pathtot,path,optionfile);
                   11061:     printf("pathtot=%s, path=%s, optionfile=%s\n",pathtot,path,optionfile);*/
                   11062:   /* cutv(path,optionfile,pathtot,'\\');*/
                   11063: 
                   11064:   /* Split argv[0], imach program to get pathimach */
                   11065:   printf("\nargv[0]=%s argv[1]=%s, \n",argv[0],argv[1]);
                   11066:   split(argv[0],pathimach,optionfile,optionfilext,optionfilefiname);
                   11067:   printf("\nargv[0]=%s pathimach=%s, \noptionfile=%s \noptionfilext=%s \noptionfilefiname=%s\n",argv[0],pathimach,optionfile,optionfilext,optionfilefiname);
                   11068:  /*   strcpy(pathimach,argv[0]); */
                   11069:   /* Split argv[1]=pathtot, parameter file name to get path, optionfile, extension and name */
                   11070:   split(pathtot,path,optionfile,optionfilext,optionfilefiname);
                   11071:   printf("\npathtot=%s,\npath=%s,\noptionfile=%s \noptionfilext=%s \noptionfilefiname=%s\n",pathtot,path,optionfile,optionfilext,optionfilefiname);
1.184     brouard  11072: #ifdef WIN32
                   11073:   _chdir(path); /* Can be a relative path */
                   11074:   if(_getcwd(pathcd,MAXLINE) > 0) /* So pathcd is the full path */
                   11075: #else
1.126     brouard  11076:   chdir(path); /* Can be a relative path */
1.184     brouard  11077:   if (getcwd(pathcd, MAXLINE) > 0) /* So pathcd is the full path */
                   11078: #endif
                   11079:   printf("Current directory %s!\n",pathcd);
1.126     brouard  11080:   strcpy(command,"mkdir ");
                   11081:   strcat(command,optionfilefiname);
                   11082:   if((outcmd=system(command)) != 0){
1.169     brouard  11083:     printf("Directory already exists (or can't create it) %s%s, err=%d\n",path,optionfilefiname,outcmd);
1.126     brouard  11084:     /* fprintf(ficlog,"Problem creating directory %s%s\n",path,optionfilefiname); */
                   11085:     /* fclose(ficlog); */
                   11086: /*     exit(1); */
                   11087:   }
                   11088: /*   if((imk=mkdir(optionfilefiname))<0){ */
                   11089: /*     perror("mkdir"); */
                   11090: /*   } */
                   11091: 
                   11092:   /*-------- arguments in the command line --------*/
                   11093: 
1.186     brouard  11094:   /* Main Log file */
1.126     brouard  11095:   strcat(filelog, optionfilefiname);
                   11096:   strcat(filelog,".log");    /* */
                   11097:   if((ficlog=fopen(filelog,"w"))==NULL)    {
                   11098:     printf("Problem with logfile %s\n",filelog);
                   11099:     goto end;
                   11100:   }
                   11101:   fprintf(ficlog,"Log filename:%s\n",filelog);
1.197     brouard  11102:   fprintf(ficlog,"Version %s %s",version,fullversion);
1.126     brouard  11103:   fprintf(ficlog,"\nEnter the parameter file name: \n");
                   11104:   fprintf(ficlog,"pathimach=%s\npathtot=%s\n\
                   11105:  path=%s \n\
                   11106:  optionfile=%s\n\
                   11107:  optionfilext=%s\n\
1.156     brouard  11108:  optionfilefiname='%s'\n",pathimach,pathtot,path,optionfile,optionfilext,optionfilefiname);
1.126     brouard  11109: 
1.197     brouard  11110:   syscompilerinfo(1);
1.167     brouard  11111: 
1.126     brouard  11112:   printf("Local time (at start):%s",strstart);
                   11113:   fprintf(ficlog,"Local time (at start): %s",strstart);
                   11114:   fflush(ficlog);
                   11115: /*   (void) gettimeofday(&curr_time,&tzp); */
1.157     brouard  11116: /*   printf("Elapsed time %d\n", asc_diff_time(curr_time.tm_sec-start_time.tm_sec,tmpout)); */
1.126     brouard  11117: 
                   11118:   /* */
                   11119:   strcpy(fileres,"r");
                   11120:   strcat(fileres, optionfilefiname);
1.201     brouard  11121:   strcat(fileresu, optionfilefiname); /* Without r in front */
1.126     brouard  11122:   strcat(fileres,".txt");    /* Other files have txt extension */
1.201     brouard  11123:   strcat(fileresu,".txt");    /* Other files have txt extension */
1.126     brouard  11124: 
1.186     brouard  11125:   /* Main ---------arguments file --------*/
1.126     brouard  11126: 
                   11127:   if((ficpar=fopen(optionfile,"r"))==NULL)    {
1.155     brouard  11128:     printf("Problem with optionfile '%s' with errno='%s'\n",optionfile,strerror(errno));
                   11129:     fprintf(ficlog,"Problem with optionfile '%s' with errno='%s'\n",optionfile,strerror(errno));
1.126     brouard  11130:     fflush(ficlog);
1.149     brouard  11131:     /* goto end; */
                   11132:     exit(70); 
1.126     brouard  11133:   }
                   11134: 
                   11135:   strcpy(filereso,"o");
1.201     brouard  11136:   strcat(filereso,fileresu);
1.126     brouard  11137:   if((ficparo=fopen(filereso,"w"))==NULL) { /* opened on subdirectory */
                   11138:     printf("Problem with Output resultfile: %s\n", filereso);
                   11139:     fprintf(ficlog,"Problem with Output resultfile: %s\n", filereso);
                   11140:     fflush(ficlog);
                   11141:     goto end;
                   11142:   }
1.278     brouard  11143:       /*-------- Rewriting parameter file ----------*/
                   11144:   strcpy(rfileres,"r");    /* "Rparameterfile */
                   11145:   strcat(rfileres,optionfilefiname);    /* Parameter file first name */
                   11146:   strcat(rfileres,".");    /* */
                   11147:   strcat(rfileres,optionfilext);    /* Other files have txt extension */
                   11148:   if((ficres =fopen(rfileres,"w"))==NULL) {
                   11149:     printf("Problem writing new parameter file: %s\n", rfileres);goto end;
                   11150:     fprintf(ficlog,"Problem writing new parameter file: %s\n", rfileres);goto end;
                   11151:     fflush(ficlog);
                   11152:     goto end;
                   11153:   }
                   11154:   fprintf(ficres,"#IMaCh %s\n",version);
1.126     brouard  11155: 
1.278     brouard  11156:                                      
1.126     brouard  11157:   /* Reads comments: lines beginning with '#' */
                   11158:   numlinepar=0;
1.277     brouard  11159:   /* Is it a BOM UTF-8 Windows file? */
                   11160:   /* First parameter line */
1.197     brouard  11161:   while(fgets(line, MAXLINE, ficpar)) {
1.277     brouard  11162:     noffset=0;
                   11163:     if( line[0] == (char)0xEF && line[1] == (char)0xBB) /* EF BB BF */
                   11164:     {
                   11165:       noffset=noffset+3;
                   11166:       printf("# File is an UTF8 Bom.\n"); // 0xBF
                   11167:     }
1.302     brouard  11168: /*    else if( line[0] == (char)0xFE && line[1] == (char)0xFF)*/
                   11169:     else if( line[0] == (char)0xFF && line[1] == (char)0xFE)
1.277     brouard  11170:     {
                   11171:       noffset=noffset+2;
                   11172:       printf("# File is an UTF16BE BOM file\n");
                   11173:     }
                   11174:     else if( line[0] == 0 && line[1] == 0)
                   11175:     {
                   11176:       if( line[2] == (char)0xFE && line[3] == (char)0xFF){
                   11177:        noffset=noffset+4;
                   11178:        printf("# File is an UTF16BE BOM file\n");
                   11179:       }
                   11180:     } else{
                   11181:       ;/*printf(" Not a BOM file\n");*/
                   11182:     }
                   11183:   
1.197     brouard  11184:     /* If line starts with a # it is a comment */
1.277     brouard  11185:     if (line[noffset] == '#') {
1.197     brouard  11186:       numlinepar++;
                   11187:       fputs(line,stdout);
                   11188:       fputs(line,ficparo);
1.278     brouard  11189:       fputs(line,ficres);
1.197     brouard  11190:       fputs(line,ficlog);
                   11191:       continue;
                   11192:     }else
                   11193:       break;
                   11194:   }
                   11195:   if((num_filled=sscanf(line,"title=%s datafile=%s lastobs=%d firstpass=%d lastpass=%d\n", \
                   11196:                        title, datafile, &lastobs, &firstpass,&lastpass)) !=EOF){
                   11197:     if (num_filled != 5) {
                   11198:       printf("Should be 5 parameters\n");
1.283     brouard  11199:       fprintf(ficlog,"Should be 5 parameters\n");
1.197     brouard  11200:     }
1.126     brouard  11201:     numlinepar++;
1.197     brouard  11202:     printf("title=%s datafile=%s lastobs=%d firstpass=%d lastpass=%d\n", title, datafile, lastobs, firstpass,lastpass);
1.283     brouard  11203:     fprintf(ficparo,"title=%s datafile=%s lastobs=%d firstpass=%d lastpass=%d\n", title, datafile, lastobs, firstpass,lastpass);
                   11204:     fprintf(ficres,"title=%s datafile=%s lastobs=%d firstpass=%d lastpass=%d\n", title, datafile, lastobs, firstpass,lastpass);
                   11205:     fprintf(ficlog,"title=%s datafile=%s lastobs=%d firstpass=%d lastpass=%d\n", title, datafile, lastobs, firstpass,lastpass);
1.197     brouard  11206:   }
                   11207:   /* Second parameter line */
                   11208:   while(fgets(line, MAXLINE, ficpar)) {
1.283     brouard  11209:     /* while(fscanf(ficpar,"%[^\n]", line)) { */
                   11210:     /* If line starts with a # it is a comment. Strangely fgets reads the EOL and fputs doesn't */
1.197     brouard  11211:     if (line[0] == '#') {
                   11212:       numlinepar++;
1.283     brouard  11213:       printf("%s",line);
                   11214:       fprintf(ficres,"%s",line);
                   11215:       fprintf(ficparo,"%s",line);
                   11216:       fprintf(ficlog,"%s",line);
1.197     brouard  11217:       continue;
                   11218:     }else
                   11219:       break;
                   11220:   }
1.223     brouard  11221:   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", \
                   11222:                        &ftol, &stepm, &ncovcol, &nqv, &ntv, &nqtv, &nlstate, &ndeath, &maxwav, &mle, &weightopt)) !=EOF){
                   11223:     if (num_filled != 11) {
                   11224:       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  11225:       printf("but line=%s\n",line);
1.283     brouard  11226:       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");
                   11227:       fprintf(ficlog,"but line=%s\n",line);
1.197     brouard  11228:     }
1.286     brouard  11229:     if( lastpass > maxwav){
                   11230:       printf("Error (lastpass = %d) > (maxwav = %d)\n",lastpass, maxwav);
                   11231:       fprintf(ficlog,"Error (lastpass = %d) > (maxwav = %d)\n",lastpass, maxwav);
                   11232:       fflush(ficlog);
                   11233:       goto end;
                   11234:     }
                   11235:       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  11236:     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  11237:     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  11238:     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  11239:   }
1.203     brouard  11240:   /* ftolpl=6*ftol*1.e5; /\* 6.e-3 make convergences in less than 80 loops for the prevalence limit *\/ */
1.209     brouard  11241:   /*ftolpl=6.e-4; *//* 6.e-3 make convergences in less than 80 loops for the prevalence limit */
1.197     brouard  11242:   /* Third parameter line */
                   11243:   while(fgets(line, MAXLINE, ficpar)) {
                   11244:     /* If line starts with a # it is a comment */
                   11245:     if (line[0] == '#') {
                   11246:       numlinepar++;
1.283     brouard  11247:       printf("%s",line);
                   11248:       fprintf(ficres,"%s",line);
                   11249:       fprintf(ficparo,"%s",line);
                   11250:       fprintf(ficlog,"%s",line);
1.197     brouard  11251:       continue;
                   11252:     }else
                   11253:       break;
                   11254:   }
1.201     brouard  11255:   if((num_filled=sscanf(line,"model=1+age%[^.\n]", model)) !=EOF){
1.279     brouard  11256:     if (num_filled != 1){
1.302     brouard  11257:       printf("ERROR %d: Model should be at minimum 'model=1+age+' instead of '%s'\n",num_filled, line);
                   11258:       fprintf(ficlog,"ERROR %d: Model should be at minimum 'model=1+age+' instead of '%s'\n",num_filled, line);
1.197     brouard  11259:       model[0]='\0';
                   11260:       goto end;
                   11261:     }
                   11262:     else{
                   11263:       if (model[0]=='+'){
                   11264:        for(i=1; i<=strlen(model);i++)
                   11265:          modeltemp[i-1]=model[i];
1.201     brouard  11266:        strcpy(model,modeltemp); 
1.197     brouard  11267:       }
                   11268:     }
1.199     brouard  11269:     /* printf(" model=1+age%s modeltemp= %s, model=%s\n",model, modeltemp, model);fflush(stdout); */
1.203     brouard  11270:     printf("model=1+age+%s\n",model);fflush(stdout);
1.283     brouard  11271:     fprintf(ficparo,"model=1+age+%s\n",model);fflush(stdout);
                   11272:     fprintf(ficres,"model=1+age+%s\n",model);fflush(stdout);
                   11273:     fprintf(ficlog,"model=1+age+%s\n",model);fflush(stdout);
1.197     brouard  11274:   }
                   11275:   /* 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); */
                   11276:   /* numlinepar=numlinepar+3; /\* In general *\/ */
                   11277:   /* 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  11278:   /* 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); */
                   11279:   /* 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  11280:   fflush(ficlog);
1.190     brouard  11281:   /* if(model[0]=='#'|| model[0]== '\0'){ */
                   11282:   if(model[0]=='#'){
1.279     brouard  11283:     printf("Error in 'model' line: model should start with 'model=1+age+' and end without space \n \
                   11284:  'model=1+age+' or 'model=1+age+V1.' or 'model=1+age+age*age+V1+V1*age' or \n \
                   11285:  'model=1+age+V1+V2' or 'model=1+age+V1+V2+V1*V2' etc. \n");           \
1.187     brouard  11286:     if(mle != -1){
1.279     brouard  11287:       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  11288:       exit(1);
                   11289:     }
                   11290:   }
1.126     brouard  11291:   while((c=getc(ficpar))=='#' && c!= EOF){
                   11292:     ungetc(c,ficpar);
                   11293:     fgets(line, MAXLINE, ficpar);
                   11294:     numlinepar++;
1.195     brouard  11295:     if(line[1]=='q'){ /* This #q will quit imach (the answer is q) */
                   11296:       z[0]=line[1];
                   11297:     }
                   11298:     /* printf("****line [1] = %c \n",line[1]); */
1.141     brouard  11299:     fputs(line, stdout);
                   11300:     //puts(line);
1.126     brouard  11301:     fputs(line,ficparo);
                   11302:     fputs(line,ficlog);
                   11303:   }
                   11304:   ungetc(c,ficpar);
                   11305: 
                   11306:    
1.290     brouard  11307:   covar=matrix(0,NCOVMAX,firstobs,lastobs);  /**< used in readdata */
                   11308:   if(nqv>=1)coqvar=matrix(1,nqv,firstobs,lastobs);  /**< Fixed quantitative covariate */
                   11309:   if(nqtv>=1)cotqvar=ma3x(1,maxwav,1,nqtv,firstobs,lastobs);  /**< Time varying quantitative covariate */
                   11310:   if(ntv+nqtv>=1)cotvar=ma3x(1,maxwav,1,ntv+nqtv,firstobs,lastobs);  /**< Time varying covariate (dummy and quantitative)*/
1.136     brouard  11311:   cptcovn=0; /*Number of covariates, i.e. number of '+' in model statement plus one, indepently of n in Vn*/
                   11312:   /* v1+v2+v3+v2*v4+v5*age makes cptcovn = 5
                   11313:      v1+v2*age+v2*v3 makes cptcovn = 3
                   11314:   */
                   11315:   if (strlen(model)>1) 
1.187     brouard  11316:     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  11317:   else
1.187     brouard  11318:     ncovmodel=2; /* Constant and age */
1.133     brouard  11319:   nforce= (nlstate+ndeath-1)*nlstate; /* Number of forces ij from state i to j */
                   11320:   npar= nforce*ncovmodel; /* Number of parameters like aij*/
1.131     brouard  11321:   if(npar >MAXPARM || nlstate >NLSTATEMAX || ndeath >NDEATHMAX || ncovmodel>NCOVMAX){
                   11322:     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);
                   11323:     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);
                   11324:     fflush(stdout);
                   11325:     fclose (ficlog);
                   11326:     goto end;
                   11327:   }
1.126     brouard  11328:   delti3= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
                   11329:   delti=delti3[1][1];
                   11330:   /*delti=vector(1,npar); *//* Scale of each paramater (output from hesscov)*/
                   11331:   if(mle==-1){ /* Print a wizard for help writing covariance matrix */
1.247     brouard  11332: /* We could also provide initial parameters values giving by simple logistic regression 
                   11333:  * only one way, that is without matrix product. We will have nlstate maximizations */
                   11334:       /* for(i=1;i<nlstate;i++){ */
                   11335:       /*       /\*reducing xi for 1 to npar to 1 to ncovmodel; *\/ */
                   11336:       /*    mlikeli(ficres,p, ncovmodel, ncovmodel, nlstate, ftol, funcnoprod); */
                   11337:       /* } */
1.126     brouard  11338:     prwizard(ncovmodel, nlstate, ndeath, model, ficparo);
1.191     brouard  11339:     printf(" You chose mle=-1, look at file %s for a template of covariance matrix \n",filereso);
                   11340:     fprintf(ficlog," You chose mle=-1, look at file %s for a template of covariance matrix \n",filereso);
1.126     brouard  11341:     free_ma3x(delti3,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel); 
                   11342:     fclose (ficparo);
                   11343:     fclose (ficlog);
                   11344:     goto end;
                   11345:     exit(0);
1.220     brouard  11346:   }  else if(mle==-5) { /* Main Wizard */
1.126     brouard  11347:     prwizard(ncovmodel, nlstate, ndeath, model, ficparo);
1.192     brouard  11348:     printf(" You chose mle=-3, look at file %s for a template of covariance matrix \n",filereso);
                   11349:     fprintf(ficlog," You chose mle=-3, look at file %s for a template of covariance matrix \n",filereso);
1.126     brouard  11350:     param= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
                   11351:     matcov=matrix(1,npar,1,npar);
1.203     brouard  11352:     hess=matrix(1,npar,1,npar);
1.220     brouard  11353:   }  else{ /* Begin of mle != -1 or -5 */
1.145     brouard  11354:     /* Read guessed parameters */
1.126     brouard  11355:     /* Reads comments: lines beginning with '#' */
                   11356:     while((c=getc(ficpar))=='#' && c!= EOF){
                   11357:       ungetc(c,ficpar);
                   11358:       fgets(line, MAXLINE, ficpar);
                   11359:       numlinepar++;
1.141     brouard  11360:       fputs(line,stdout);
1.126     brouard  11361:       fputs(line,ficparo);
                   11362:       fputs(line,ficlog);
                   11363:     }
                   11364:     ungetc(c,ficpar);
                   11365:     
                   11366:     param= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
1.251     brouard  11367:     paramstart= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
1.126     brouard  11368:     for(i=1; i <=nlstate; i++){
1.234     brouard  11369:       j=0;
1.126     brouard  11370:       for(jj=1; jj <=nlstate+ndeath; jj++){
1.234     brouard  11371:        if(jj==i) continue;
                   11372:        j++;
1.292     brouard  11373:        while((c=getc(ficpar))=='#' && c!= EOF){
                   11374:          ungetc(c,ficpar);
                   11375:          fgets(line, MAXLINE, ficpar);
                   11376:          numlinepar++;
                   11377:          fputs(line,stdout);
                   11378:          fputs(line,ficparo);
                   11379:          fputs(line,ficlog);
                   11380:        }
                   11381:        ungetc(c,ficpar);
1.234     brouard  11382:        fscanf(ficpar,"%1d%1d",&i1,&j1);
                   11383:        if ((i1 != i) || (j1 != jj)){
                   11384:          printf("Error in line parameters number %d, %1d%1d instead of %1d%1d \n \
1.126     brouard  11385: It might be a problem of design; if ncovcol and the model are correct\n \
                   11386: run imach with mle=-1 to get a correct template of the parameter file.\n",numlinepar, i,j, i1, j1);
1.234     brouard  11387:          exit(1);
                   11388:        }
                   11389:        fprintf(ficparo,"%1d%1d",i1,j1);
                   11390:        if(mle==1)
                   11391:          printf("%1d%1d",i,jj);
                   11392:        fprintf(ficlog,"%1d%1d",i,jj);
                   11393:        for(k=1; k<=ncovmodel;k++){
                   11394:          fscanf(ficpar," %lf",&param[i][j][k]);
                   11395:          if(mle==1){
                   11396:            printf(" %lf",param[i][j][k]);
                   11397:            fprintf(ficlog," %lf",param[i][j][k]);
                   11398:          }
                   11399:          else
                   11400:            fprintf(ficlog," %lf",param[i][j][k]);
                   11401:          fprintf(ficparo," %lf",param[i][j][k]);
                   11402:        }
                   11403:        fscanf(ficpar,"\n");
                   11404:        numlinepar++;
                   11405:        if(mle==1)
                   11406:          printf("\n");
                   11407:        fprintf(ficlog,"\n");
                   11408:        fprintf(ficparo,"\n");
1.126     brouard  11409:       }
                   11410:     }  
                   11411:     fflush(ficlog);
1.234     brouard  11412:     
1.251     brouard  11413:     /* Reads parameters values */
1.126     brouard  11414:     p=param[1][1];
1.251     brouard  11415:     pstart=paramstart[1][1];
1.126     brouard  11416:     
                   11417:     /* Reads comments: lines beginning with '#' */
                   11418:     while((c=getc(ficpar))=='#' && c!= EOF){
                   11419:       ungetc(c,ficpar);
                   11420:       fgets(line, MAXLINE, ficpar);
                   11421:       numlinepar++;
1.141     brouard  11422:       fputs(line,stdout);
1.126     brouard  11423:       fputs(line,ficparo);
                   11424:       fputs(line,ficlog);
                   11425:     }
                   11426:     ungetc(c,ficpar);
                   11427: 
                   11428:     for(i=1; i <=nlstate; i++){
                   11429:       for(j=1; j <=nlstate+ndeath-1; j++){
1.234     brouard  11430:        fscanf(ficpar,"%1d%1d",&i1,&j1);
                   11431:        if ( (i1-i) * (j1-j) != 0){
                   11432:          printf("Error in line parameters number %d, %1d%1d instead of %1d%1d \n",numlinepar, i,j, i1, j1);
                   11433:          exit(1);
                   11434:        }
                   11435:        printf("%1d%1d",i,j);
                   11436:        fprintf(ficparo,"%1d%1d",i1,j1);
                   11437:        fprintf(ficlog,"%1d%1d",i1,j1);
                   11438:        for(k=1; k<=ncovmodel;k++){
                   11439:          fscanf(ficpar,"%le",&delti3[i][j][k]);
                   11440:          printf(" %le",delti3[i][j][k]);
                   11441:          fprintf(ficparo," %le",delti3[i][j][k]);
                   11442:          fprintf(ficlog," %le",delti3[i][j][k]);
                   11443:        }
                   11444:        fscanf(ficpar,"\n");
                   11445:        numlinepar++;
                   11446:        printf("\n");
                   11447:        fprintf(ficparo,"\n");
                   11448:        fprintf(ficlog,"\n");
1.126     brouard  11449:       }
                   11450:     }
                   11451:     fflush(ficlog);
1.234     brouard  11452:     
1.145     brouard  11453:     /* Reads covariance matrix */
1.126     brouard  11454:     delti=delti3[1][1];
1.220     brouard  11455:                
                   11456:                
1.126     brouard  11457:     /* 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  11458:                
1.126     brouard  11459:     /* Reads comments: lines beginning with '#' */
                   11460:     while((c=getc(ficpar))=='#' && c!= EOF){
                   11461:       ungetc(c,ficpar);
                   11462:       fgets(line, MAXLINE, ficpar);
                   11463:       numlinepar++;
1.141     brouard  11464:       fputs(line,stdout);
1.126     brouard  11465:       fputs(line,ficparo);
                   11466:       fputs(line,ficlog);
                   11467:     }
                   11468:     ungetc(c,ficpar);
1.220     brouard  11469:                
1.126     brouard  11470:     matcov=matrix(1,npar,1,npar);
1.203     brouard  11471:     hess=matrix(1,npar,1,npar);
1.131     brouard  11472:     for(i=1; i <=npar; i++)
                   11473:       for(j=1; j <=npar; j++) matcov[i][j]=0.;
1.220     brouard  11474:                
1.194     brouard  11475:     /* Scans npar lines */
1.126     brouard  11476:     for(i=1; i <=npar; i++){
1.226     brouard  11477:       count=fscanf(ficpar,"%1d%1d%d",&i1,&j1,&jk);
1.194     brouard  11478:       if(count != 3){
1.226     brouard  11479:        printf("Error! Error in parameter file %s at line %d after line starting with %1d%1d%1d\n\
1.194     brouard  11480: This is probably because your covariance matrix doesn't \n  contain exactly %d lines corresponding to your model line '1+age+%s'.\n\
                   11481: Please run with mle=-1 to get a correct covariance matrix.\n",optionfile,numlinepar, i1,j1,jk, npar, model);
1.226     brouard  11482:        fprintf(ficlog,"Error! Error in parameter file %s at line %d after line starting with %1d%1d%1d\n\
1.194     brouard  11483: This is probably because your covariance matrix doesn't \n  contain exactly %d lines corresponding to your model line '1+age+%s'.\n\
                   11484: Please run with mle=-1 to get a correct covariance matrix.\n",optionfile,numlinepar, i1,j1,jk, npar, model);
1.226     brouard  11485:        exit(1);
1.220     brouard  11486:       }else{
1.226     brouard  11487:        if(mle==1)
                   11488:          printf("%1d%1d%d",i1,j1,jk);
                   11489:       }
                   11490:       fprintf(ficlog,"%1d%1d%d",i1,j1,jk);
                   11491:       fprintf(ficparo,"%1d%1d%d",i1,j1,jk);
1.126     brouard  11492:       for(j=1; j <=i; j++){
1.226     brouard  11493:        fscanf(ficpar," %le",&matcov[i][j]);
                   11494:        if(mle==1){
                   11495:          printf(" %.5le",matcov[i][j]);
                   11496:        }
                   11497:        fprintf(ficlog," %.5le",matcov[i][j]);
                   11498:        fprintf(ficparo," %.5le",matcov[i][j]);
1.126     brouard  11499:       }
                   11500:       fscanf(ficpar,"\n");
                   11501:       numlinepar++;
                   11502:       if(mle==1)
1.220     brouard  11503:                                printf("\n");
1.126     brouard  11504:       fprintf(ficlog,"\n");
                   11505:       fprintf(ficparo,"\n");
                   11506:     }
1.194     brouard  11507:     /* End of read covariance matrix npar lines */
1.126     brouard  11508:     for(i=1; i <=npar; i++)
                   11509:       for(j=i+1;j<=npar;j++)
1.226     brouard  11510:        matcov[i][j]=matcov[j][i];
1.126     brouard  11511:     
                   11512:     if(mle==1)
                   11513:       printf("\n");
                   11514:     fprintf(ficlog,"\n");
                   11515:     
                   11516:     fflush(ficlog);
                   11517:     
                   11518:   }    /* End of mle != -3 */
1.218     brouard  11519:   
1.186     brouard  11520:   /*  Main data
                   11521:    */
1.290     brouard  11522:   nobs=lastobs-firstobs+1; /* was = lastobs;*/
                   11523:   /* num=lvector(1,n); */
                   11524:   /* moisnais=vector(1,n); */
                   11525:   /* annais=vector(1,n); */
                   11526:   /* moisdc=vector(1,n); */
                   11527:   /* andc=vector(1,n); */
                   11528:   /* weight=vector(1,n); */
                   11529:   /* agedc=vector(1,n); */
                   11530:   /* cod=ivector(1,n); */
                   11531:   /* for(i=1;i<=n;i++){ */
                   11532:   num=lvector(firstobs,lastobs);
                   11533:   moisnais=vector(firstobs,lastobs);
                   11534:   annais=vector(firstobs,lastobs);
                   11535:   moisdc=vector(firstobs,lastobs);
                   11536:   andc=vector(firstobs,lastobs);
                   11537:   weight=vector(firstobs,lastobs);
                   11538:   agedc=vector(firstobs,lastobs);
                   11539:   cod=ivector(firstobs,lastobs);
                   11540:   for(i=firstobs;i<=lastobs;i++){
1.234     brouard  11541:     num[i]=0;
                   11542:     moisnais[i]=0;
                   11543:     annais[i]=0;
                   11544:     moisdc[i]=0;
                   11545:     andc[i]=0;
                   11546:     agedc[i]=0;
                   11547:     cod[i]=0;
                   11548:     weight[i]=1.0; /* Equal weights, 1 by default */
                   11549:   }
1.290     brouard  11550:   mint=matrix(1,maxwav,firstobs,lastobs);
                   11551:   anint=matrix(1,maxwav,firstobs,lastobs);
                   11552:   s=imatrix(1,maxwav+1,firstobs,lastobs); /* s[i][j] health state for wave i and individual j */ 
1.126     brouard  11553:   tab=ivector(1,NCOVMAX);
1.144     brouard  11554:   ncodemax=ivector(1,NCOVMAX); /* Number of code per covariate; if O and 1 only, 2**ncov; V1+V2+V3+V4=>16 */
1.192     brouard  11555:   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  11556: 
1.136     brouard  11557:   /* Reads data from file datafile */
                   11558:   if (readdata(datafile, firstobs, lastobs, &imx)==1)
                   11559:     goto end;
                   11560: 
                   11561:   /* Calculation of the number of parameters from char model */
1.234     brouard  11562:   /*    modelsav=V2+V1+V4+age*V3 strb=age*V3 stra=V2+V1+V4 
1.137     brouard  11563:        k=4 (age*V3) Tvar[k=4]= 3 (from V3) Tag[cptcovage=1]=4
                   11564:        k=3 V4 Tvar[k=3]= 4 (from V4)
                   11565:        k=2 V1 Tvar[k=2]= 1 (from V1)
                   11566:        k=1 Tvar[1]=2 (from V2)
1.234     brouard  11567:   */
                   11568:   
                   11569:   Tvar=ivector(1,NCOVMAX); /* Was 15 changed to NCOVMAX. */
                   11570:   TvarsDind=ivector(1,NCOVMAX); /*  */
                   11571:   TvarsD=ivector(1,NCOVMAX); /*  */
                   11572:   TvarsQind=ivector(1,NCOVMAX); /*  */
                   11573:   TvarsQ=ivector(1,NCOVMAX); /*  */
1.232     brouard  11574:   TvarF=ivector(1,NCOVMAX); /*  */
                   11575:   TvarFind=ivector(1,NCOVMAX); /*  */
                   11576:   TvarV=ivector(1,NCOVMAX); /*  */
                   11577:   TvarVind=ivector(1,NCOVMAX); /*  */
                   11578:   TvarA=ivector(1,NCOVMAX); /*  */
                   11579:   TvarAind=ivector(1,NCOVMAX); /*  */
1.231     brouard  11580:   TvarFD=ivector(1,NCOVMAX); /*  */
                   11581:   TvarFDind=ivector(1,NCOVMAX); /*  */
                   11582:   TvarFQ=ivector(1,NCOVMAX); /*  */
                   11583:   TvarFQind=ivector(1,NCOVMAX); /*  */
                   11584:   TvarVD=ivector(1,NCOVMAX); /*  */
                   11585:   TvarVDind=ivector(1,NCOVMAX); /*  */
                   11586:   TvarVQ=ivector(1,NCOVMAX); /*  */
                   11587:   TvarVQind=ivector(1,NCOVMAX); /*  */
                   11588: 
1.230     brouard  11589:   Tvalsel=vector(1,NCOVMAX); /*  */
1.233     brouard  11590:   Tvarsel=ivector(1,NCOVMAX); /*  */
1.226     brouard  11591:   Typevar=ivector(-1,NCOVMAX); /* -1 to 2 */
                   11592:   Fixed=ivector(-1,NCOVMAX); /* -1 to 3 */
                   11593:   Dummy=ivector(-1,NCOVMAX); /* -1 to 3 */
1.137     brouard  11594:   /*  V2+V1+V4+age*V3 is a model with 4 covariates (3 plus signs). 
                   11595:       For each model-covariate stores the data-covariate id. Tvar[1]=2, Tvar[2]=1, Tvar[3]=4, 
                   11596:       Tvar[4=age*V3] is 3 and 'age' is recorded in Tage.
                   11597:   */
                   11598:   /* For model-covariate k tells which data-covariate to use but
                   11599:     because this model-covariate is a construction we invent a new column
                   11600:     ncovcol + k1
                   11601:     If already ncovcol=4 and model=V2+V1+V1*V4+age*V3
                   11602:     Tvar[3=V1*V4]=4+1 etc */
1.227     brouard  11603:   Tprod=ivector(1,NCOVMAX); /* Gives the k position of the k1 product */
                   11604:   Tposprod=ivector(1,NCOVMAX); /* Gives the k1 product from the k position */
1.137     brouard  11605:   /* Tprod[k1=1]=3(=V1*V4) for V2+V1+V1*V4+age*V3
                   11606:      if  V2+V1+V1*V4+age*V3+V3*V2   TProd[k1=2]=5 (V3*V2)
1.227     brouard  11607:      Tposprod[k]=k1 , Tposprod[3]=1, Tposprod[5]=2 
1.137     brouard  11608:   */
1.145     brouard  11609:   Tvaraff=ivector(1,NCOVMAX); /* Unclear */
                   11610:   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  11611:                            * For V3*V2 (in V2+V1+V1*V4+age*V3+V3*V2), V3*V2 position is 2nd. 
                   11612:                            * Tvard[k1=2][1]=3 (V3) Tvard[k1=2][2]=2(V2) */
1.145     brouard  11613:   Tage=ivector(1,NCOVMAX); /* Gives the covariate id of covariates associated with age: V2 + V1 + age*V4 + V3*age
1.137     brouard  11614:                         4 covariates (3 plus signs)
                   11615:                         Tage[1=V3*age]= 4; Tage[2=age*V4] = 3
                   11616:                      */  
1.230     brouard  11617:   Tmodelind=ivector(1,NCOVMAX);/** gives the k model position of an
1.227     brouard  11618:                                * individual dummy, fixed or varying:
                   11619:                                * Tmodelind[Tvaraff[3]]=9,Tvaraff[1]@9={4,
                   11620:                                * 3, 1, 0, 0, 0, 0, 0, 0},
1.230     brouard  11621:                                * model=V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 , 
                   11622:                                * V1 df, V2 qf, V3 & V4 dv, V5 qv
                   11623:                                * Tmodelind[1]@9={9,0,3,2,}*/
                   11624:   TmodelInvind=ivector(1,NCOVMAX); /* TmodelInvind=Tvar[k]- ncovcol-nqv={5-2-1=2,*/
                   11625:   TmodelInvQind=ivector(1,NCOVMAX);/** gives the k model position of an
1.228     brouard  11626:                                * individual quantitative, fixed or varying:
                   11627:                                * Tmodelqind[1]=1,Tvaraff[1]@9={4,
                   11628:                                * 3, 1, 0, 0, 0, 0, 0, 0},
                   11629:                                * model=V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1*/
1.186     brouard  11630: /* Main decodemodel */
                   11631: 
1.187     brouard  11632: 
1.223     brouard  11633:   if(decodemodel(model, lastobs) == 1) /* In order to get Tvar[k] V4+V3+V5 p Tvar[1]@3  = {4, 3, 5}*/
1.136     brouard  11634:     goto end;
                   11635: 
1.137     brouard  11636:   if((double)(lastobs-imx)/(double)imx > 1.10){
                   11637:     nbwarn++;
                   11638:     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); 
                   11639:     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); 
                   11640:   }
1.136     brouard  11641:     /*  if(mle==1){*/
1.137     brouard  11642:   if (weightopt != 1) { /* Maximisation without weights. We can have weights different from 1 but want no weight*/
                   11643:     for(i=1;i<=imx;i++) weight[i]=1.0; /* changed to imx */
1.136     brouard  11644:   }
                   11645: 
                   11646:     /*-calculation of age at interview from date of interview and age at death -*/
                   11647:   agev=matrix(1,maxwav,1,imx);
                   11648: 
                   11649:   if(calandcheckages(imx, maxwav, &agemin, &agemax, &nberr, &nbwarn) == 1)
                   11650:     goto end;
                   11651: 
1.126     brouard  11652: 
1.136     brouard  11653:   agegomp=(int)agemin;
1.290     brouard  11654:   free_vector(moisnais,firstobs,lastobs);
                   11655:   free_vector(annais,firstobs,lastobs);
1.126     brouard  11656:   /* free_matrix(mint,1,maxwav,1,n);
                   11657:      free_matrix(anint,1,maxwav,1,n);*/
1.215     brouard  11658:   /* free_vector(moisdc,1,n); */
                   11659:   /* free_vector(andc,1,n); */
1.145     brouard  11660:   /* */
                   11661:   
1.126     brouard  11662:   wav=ivector(1,imx);
1.214     brouard  11663:   /* dh=imatrix(1,lastpass-firstpass+1,1,imx); */
                   11664:   /* bh=imatrix(1,lastpass-firstpass+1,1,imx); */
                   11665:   /* mw=imatrix(1,lastpass-firstpass+1,1,imx); */
                   11666:   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.*/
                   11667:   bh=imatrix(1,lastpass-firstpass+2,1,imx);
                   11668:   mw=imatrix(1,lastpass-firstpass+2,1,imx);
1.126     brouard  11669:    
                   11670:   /* Concatenates waves */
1.214     brouard  11671:   /* Concatenates waves: wav[i] is the number of effective (useful waves) of individual i.
                   11672:      Death is a valid wave (if date is known).
                   11673:      mw[mi][i] is the number of (mi=1 to wav[i]) effective wave out of mi of individual i
                   11674:      dh[m][i] or dh[mw[mi][i]][i] is the delay between two effective waves m=mw[mi][i]
                   11675:      and mw[mi+1][i]. dh depends on stepm.
                   11676:   */
                   11677: 
1.126     brouard  11678:   concatwav(wav, dh, bh, mw, s, agedc, agev,  firstpass, lastpass, imx, nlstate, stepm);
1.248     brouard  11679:   /* Concatenates waves */
1.145     brouard  11680:  
1.290     brouard  11681:   free_vector(moisdc,firstobs,lastobs);
                   11682:   free_vector(andc,firstobs,lastobs);
1.215     brouard  11683: 
1.126     brouard  11684:   /* Routine tricode is to calculate cptcoveff (real number of unique covariates) and to associate covariable number and modality */
                   11685:   nbcode=imatrix(0,NCOVMAX,0,NCOVMAX); 
                   11686:   ncodemax[1]=1;
1.145     brouard  11687:   Ndum =ivector(-1,NCOVMAX);  
1.225     brouard  11688:   cptcoveff=0;
1.220     brouard  11689:   if (ncovmodel-nagesqr > 2 ){ /* That is if covariate other than cst, age and age*age */
                   11690:     tricode(&cptcoveff,Tvar,nbcode,imx, Ndum); /**< Fills nbcode[Tvar[j]][l]; */
1.227     brouard  11691:   }
                   11692:   
                   11693:   ncovcombmax=pow(2,cptcoveff);
                   11694:   invalidvarcomb=ivector(1, ncovcombmax); 
                   11695:   for(i=1;i<ncovcombmax;i++)
                   11696:     invalidvarcomb[i]=0;
                   11697:   
1.211     brouard  11698:   /* Nbcode gives the value of the lth modality (currently 1 to 2) of jth covariate, in
1.186     brouard  11699:      V2+V1*age, there are 3 covariates Tvar[2]=1 (V1).*/
1.211     brouard  11700:   /* 1 to ncodemax[j] which is the maximum value of this jth covariate */
1.227     brouard  11701:   
1.200     brouard  11702:   /*  codtab=imatrix(1,100,1,10);*/ /* codtab[h,k]=( (h-1) - mod(k-1,2**(k-1) )/2**(k-1) */
1.198     brouard  11703:   /*printf(" codtab[1,1],codtab[100,10]=%d,%d\n", codtab[1][1],codtabm(100,10));*/
1.186     brouard  11704:   /* codtab gives the value 1 or 2 of the hth combination of k covariates (1 or 2).*/
1.211     brouard  11705:   /* nbcode[Tvaraff[j]][codtabm(h,j)]) : if there are only 2 modalities for a covariate j, 
                   11706:    * codtabm(h,j) gives its value classified at position h and nbcode gives how it is coded 
                   11707:    * (currently 0 or 1) in the data.
                   11708:    * In a loop on h=1 to 2**k, and a loop on j (=1 to k), we get the value of 
                   11709:    * corresponding modality (h,j).
                   11710:    */
                   11711: 
1.145     brouard  11712:   h=0;
                   11713:   /*if (cptcovn > 0) */
1.126     brouard  11714:   m=pow(2,cptcoveff);
                   11715:  
1.144     brouard  11716:          /**< codtab(h,k)  k   = codtab[h,k]=( (h-1) - mod(k-1,2**(k-1) )/2**(k-1) + 1
1.211     brouard  11717:           * For k=4 covariates, h goes from 1 to m=2**k
                   11718:           * codtabm(h,k)=  (1 & (h-1) >> (k-1)) + 1;
                   11719:            * #define codtabm(h,k)  (1 & (h-1) >> (k-1))+1
1.186     brouard  11720:           *     h\k   1     2     3     4
1.143     brouard  11721:           *______________________________  
                   11722:           *     1 i=1 1 i=1 1 i=1 1 i=1 1
                   11723:           *     2     2     1     1     1
                   11724:           *     3 i=2 1     2     1     1
                   11725:           *     4     2     2     1     1
                   11726:           *     5 i=3 1 i=2 1     2     1
                   11727:           *     6     2     1     2     1
                   11728:           *     7 i=4 1     2     2     1
                   11729:           *     8     2     2     2     1
1.197     brouard  11730:           *     9 i=5 1 i=3 1 i=2 1     2
                   11731:           *    10     2     1     1     2
                   11732:           *    11 i=6 1     2     1     2
                   11733:           *    12     2     2     1     2
                   11734:           *    13 i=7 1 i=4 1     2     2    
                   11735:           *    14     2     1     2     2
                   11736:           *    15 i=8 1     2     2     2
                   11737:           *    16     2     2     2     2
1.143     brouard  11738:           */
1.212     brouard  11739:   /* How to do the opposite? From combination h (=1 to 2**k) how to get the value on the covariates? */
1.211     brouard  11740:      /* from h=5 and m, we get then number of covariates k=log(m)/log(2)=4
                   11741:      * and the value of each covariate?
                   11742:      * V1=1, V2=1, V3=2, V4=1 ?
                   11743:      * h-1=4 and 4 is 0100 or reverse 0010, and +1 is 1121 ok.
                   11744:      * h=6, 6-1=5, 5 is 0101, 1010, 2121, V1=2nd, V2=1st, V3=2nd, V4=1st.
                   11745:      * In order to get the real value in the data, we use nbcode
                   11746:      * nbcode[Tvar[3][2nd]]=1 and nbcode[Tvar[4][1]]=0
                   11747:      * We are keeping this crazy system in order to be able (in the future?) 
                   11748:      * to have more than 2 values (0 or 1) for a covariate.
                   11749:      * #define codtabm(h,k)  (1 & (h-1) >> (k-1))+1
                   11750:      * h=6, k=2? h-1=5=0101, reverse 1010, +1=2121, k=2nd position: value is 1: codtabm(6,2)=1
                   11751:      *              bbbbbbbb
                   11752:      *              76543210     
                   11753:      *   h-1        00000101 (6-1=5)
1.219     brouard  11754:      *(h-1)>>(k-1)= 00000010 >> (2-1) = 1 right shift
1.211     brouard  11755:      *           &
                   11756:      *     1        00000001 (1)
1.219     brouard  11757:      *              00000000        = 1 & ((h-1) >> (k-1))
                   11758:      *          +1= 00000001 =1 
1.211     brouard  11759:      *
                   11760:      * h=14, k=3 => h'=h-1=13, k'=k-1=2
                   11761:      *          h'      1101 =2^3+2^2+0x2^1+2^0
                   11762:      *    >>k'            11
                   11763:      *          &   00000001
                   11764:      *            = 00000001
                   11765:      *      +1    = 00000010=2    =  codtabm(14,3)   
                   11766:      * Reverse h=6 and m=16?
                   11767:      * cptcoveff=log(16)/log(2)=4 covariate: 6-1=5=0101 reversed=1010 +1=2121 =>V1=2, V2=1, V3=2, V4=1.
                   11768:      * for (j=1 to cptcoveff) Vj=decodtabm(j,h,cptcoveff)
                   11769:      * decodtabm(h,j,cptcoveff)= (((h-1) >> (j-1)) & 1) +1 
                   11770:      * decodtabm(h,j,cptcoveff)= (h <= (1<<cptcoveff)?(((h-1) >> (j-1)) & 1) +1 : -1)
                   11771:      * V3=decodtabm(14,3,2**4)=2
                   11772:      *          h'=13   1101 =2^3+2^2+0x2^1+2^0
                   11773:      *(h-1) >> (j-1)    0011 =13 >> 2
                   11774:      *          &1 000000001
                   11775:      *           = 000000001
                   11776:      *         +1= 000000010 =2
                   11777:      *                  2211
                   11778:      *                  V1=1+1, V2=0+1, V3=1+1, V4=1+1
                   11779:      *                  V3=2
1.220     brouard  11780:                 * codtabm and decodtabm are identical
1.211     brouard  11781:      */
                   11782: 
1.145     brouard  11783: 
                   11784:  free_ivector(Ndum,-1,NCOVMAX);
                   11785: 
                   11786: 
1.126     brouard  11787:     
1.186     brouard  11788:   /* Initialisation of ----------- gnuplot -------------*/
1.126     brouard  11789:   strcpy(optionfilegnuplot,optionfilefiname);
                   11790:   if(mle==-3)
1.201     brouard  11791:     strcat(optionfilegnuplot,"-MORT_");
1.126     brouard  11792:   strcat(optionfilegnuplot,".gp");
                   11793: 
                   11794:   if((ficgp=fopen(optionfilegnuplot,"w"))==NULL) {
                   11795:     printf("Problem with file %s",optionfilegnuplot);
                   11796:   }
                   11797:   else{
1.204     brouard  11798:     fprintf(ficgp,"\n# IMaCh-%s\n", version); 
1.126     brouard  11799:     fprintf(ficgp,"# %s\n", optionfilegnuplot); 
1.141     brouard  11800:     //fprintf(ficgp,"set missing 'NaNq'\n");
                   11801:     fprintf(ficgp,"set datafile missing 'NaNq'\n");
1.126     brouard  11802:   }
                   11803:   /*  fclose(ficgp);*/
1.186     brouard  11804: 
                   11805: 
                   11806:   /* Initialisation of --------- index.htm --------*/
1.126     brouard  11807: 
                   11808:   strcpy(optionfilehtm,optionfilefiname); /* Main html file */
                   11809:   if(mle==-3)
1.201     brouard  11810:     strcat(optionfilehtm,"-MORT_");
1.126     brouard  11811:   strcat(optionfilehtm,".htm");
                   11812:   if((fichtm=fopen(optionfilehtm,"w"))==NULL)    {
1.131     brouard  11813:     printf("Problem with %s \n",optionfilehtm);
                   11814:     exit(0);
1.126     brouard  11815:   }
                   11816: 
                   11817:   strcpy(optionfilehtmcov,optionfilefiname); /* Only for matrix of covariance */
                   11818:   strcat(optionfilehtmcov,"-cov.htm");
                   11819:   if((fichtmcov=fopen(optionfilehtmcov,"w"))==NULL)    {
                   11820:     printf("Problem with %s \n",optionfilehtmcov), exit(0);
                   11821:   }
                   11822:   else{
                   11823:   fprintf(fichtmcov,"<html><head>\n<title>IMaCh Cov %s</title></head>\n <body><font size=\"2\">%s <br> %s</font> \
                   11824: <hr size=\"2\" color=\"#EC5E5E\"> \n\
1.204     brouard  11825: Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=1+age+%s<br>\n",\
1.126     brouard  11826:          optionfilehtmcov,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model);
                   11827:   }
                   11828: 
1.213     brouard  11829:   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  11830: <hr size=\"2\" color=\"#EC5E5E\"> \n\
                   11831: <font size=\"2\">IMaCh-%s <br> %s</font> \
1.126     brouard  11832: <hr size=\"2\" color=\"#EC5E5E\"> \n\
1.204     brouard  11833: Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=1+age+%s<br>\n\
1.126     brouard  11834: \n\
                   11835: <hr  size=\"2\" color=\"#EC5E5E\">\
                   11836:  <ul><li><h4>Parameter files</h4>\n\
                   11837:  - Parameter file: <a href=\"%s.%s\">%s.%s</a><br>\n\
                   11838:  - Copy of the parameter file: <a href=\"o%s\">o%s</a><br>\n\
                   11839:  - Log file of the run: <a href=\"%s\">%s</a><br>\n\
                   11840:  - Gnuplot file name: <a href=\"%s\">%s</a><br>\n\
                   11841:  - Date and time at start: %s</ul>\n",\
                   11842:          optionfilehtm,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model,\
                   11843:          optionfilefiname,optionfilext,optionfilefiname,optionfilext,\
                   11844:          fileres,fileres,\
                   11845:          filelog,filelog,optionfilegnuplot,optionfilegnuplot,strstart);
                   11846:   fflush(fichtm);
                   11847: 
                   11848:   strcpy(pathr,path);
                   11849:   strcat(pathr,optionfilefiname);
1.184     brouard  11850: #ifdef WIN32
                   11851:   _chdir(optionfilefiname); /* Move to directory named optionfile */
                   11852: #else
1.126     brouard  11853:   chdir(optionfilefiname); /* Move to directory named optionfile */
1.184     brouard  11854: #endif
                   11855:          
1.126     brouard  11856:   
1.220     brouard  11857:   /* Calculates basic frequencies. Computes observed prevalence at single age 
                   11858:                 and for any valid combination of covariates
1.126     brouard  11859:      and prints on file fileres'p'. */
1.251     brouard  11860:   freqsummary(fileres, p, pstart, agemin, agemax, s, agev, nlstate, imx, Tvaraff, invalidvarcomb, nbcode, ncodemax,mint,anint,strstart, \
1.227     brouard  11861:              firstpass, lastpass,  stepm,  weightopt, model);
1.126     brouard  11862: 
                   11863:   fprintf(fichtm,"\n");
1.286     brouard  11864:   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  11865:          ftol, stepm);
                   11866:   fprintf(fichtm,"\n<li>Number of fixed dummy covariates: ncovcol=%d ", ncovcol);
                   11867:   ncurrv=1;
                   11868:   for(i=ncurrv; i <=ncovcol; i++) fprintf(fichtm,"V%d ", i);
                   11869:   fprintf(fichtm,"\n<li> Number of fixed quantitative variables: nqv=%d ", nqv); 
                   11870:   ncurrv=i;
                   11871:   for(i=ncurrv; i <=ncurrv-1+nqv; i++) fprintf(fichtm,"V%d ", i);
1.290     brouard  11872:   fprintf(fichtm,"\n<li> Number of time varying (wave varying) dummy covariates: ntv=%d ", ntv);
1.274     brouard  11873:   ncurrv=i;
                   11874:   for(i=ncurrv; i <=ncurrv-1+ntv; i++) fprintf(fichtm,"V%d ", i);
1.290     brouard  11875:   fprintf(fichtm,"\n<li>Number of time varying  quantitative covariates: nqtv=%d ", nqtv);
1.274     brouard  11876:   ncurrv=i;
                   11877:   for(i=ncurrv; i <=ncurrv-1+nqtv; i++) fprintf(fichtm,"V%d ", i);
                   11878:   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", \
                   11879:           nlstate, ndeath, maxwav, mle, weightopt);
                   11880: 
                   11881:   fprintf(fichtm,"<h4> Diagram of states <a href=\"%s_.svg\">%s_.svg</a></h4> \n\
                   11882: <img src=\"%s_.svg\">", subdirf2(optionfilefiname,"D_"),subdirf2(optionfilefiname,"D_"),subdirf2(optionfilefiname,"D_"));
                   11883: 
                   11884:   
                   11885:   fprintf(fichtm,"\n<h4>Some descriptive statistics </h4>\n<br>Total number of observations=%d <br>\n\
1.126     brouard  11886: Youngest age at first (selected) pass %.2f, oldest age %.2f<br>\n\
                   11887: Interval (in months) between two waves: Min=%d Max=%d Mean=%.2lf<br>\n",\
1.274     brouard  11888:   imx,agemin,agemax,jmin,jmax,jmean);
1.126     brouard  11889:   pmmij= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
1.268     brouard  11890:   oldms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
                   11891:   newms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
                   11892:   savms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
                   11893:   oldm=oldms; newm=newms; savm=savms; /* Keeps fixed addresses to free */
1.218     brouard  11894: 
1.126     brouard  11895:   /* For Powell, parameters are in a vector p[] starting at p[1]
                   11896:      so we point p on param[1][1] so that p[1] maps on param[1][1][1] */
                   11897:   p=param[1][1]; /* *(*(*(param +1)+1)+0) */
                   11898: 
                   11899:   globpr=0; /* To get the number ipmx of contributions and the sum of weights*/
1.186     brouard  11900:   /* For mortality only */
1.126     brouard  11901:   if (mle==-3){
1.136     brouard  11902:     ximort=matrix(1,NDIM,1,NDIM); 
1.248     brouard  11903:     for(i=1;i<=NDIM;i++)
                   11904:       for(j=1;j<=NDIM;j++)
                   11905:        ximort[i][j]=0.;
1.186     brouard  11906:     /*     ximort=gsl_matrix_alloc(1,NDIM,1,NDIM); */
1.290     brouard  11907:     cens=ivector(firstobs,lastobs);
                   11908:     ageexmed=vector(firstobs,lastobs);
                   11909:     agecens=vector(firstobs,lastobs);
                   11910:     dcwave=ivector(firstobs,lastobs);
1.223     brouard  11911:                
1.126     brouard  11912:     for (i=1; i<=imx; i++){
                   11913:       dcwave[i]=-1;
                   11914:       for (m=firstpass; m<=lastpass; m++)
1.226     brouard  11915:        if (s[m][i]>nlstate) {
                   11916:          dcwave[i]=m;
                   11917:          /*    printf("i=%d j=%d s=%d dcwave=%d\n",i,j, s[j][i],dcwave[i]);*/
                   11918:          break;
                   11919:        }
1.126     brouard  11920:     }
1.226     brouard  11921:     
1.126     brouard  11922:     for (i=1; i<=imx; i++) {
                   11923:       if (wav[i]>0){
1.226     brouard  11924:        ageexmed[i]=agev[mw[1][i]][i];
                   11925:        j=wav[i];
                   11926:        agecens[i]=1.; 
                   11927:        
                   11928:        if (ageexmed[i]> 1 && wav[i] > 0){
                   11929:          agecens[i]=agev[mw[j][i]][i];
                   11930:          cens[i]= 1;
                   11931:        }else if (ageexmed[i]< 1) 
                   11932:          cens[i]= -1;
                   11933:        if (agedc[i]< AGESUP && agedc[i]>1 && dcwave[i]>firstpass && dcwave[i]<=lastpass)
                   11934:          cens[i]=0 ;
1.126     brouard  11935:       }
                   11936:       else cens[i]=-1;
                   11937:     }
                   11938:     
                   11939:     for (i=1;i<=NDIM;i++) {
                   11940:       for (j=1;j<=NDIM;j++)
1.226     brouard  11941:        ximort[i][j]=(i == j ? 1.0 : 0.0);
1.126     brouard  11942:     }
                   11943:     
1.302     brouard  11944:     p[1]=0.0268; p[NDIM]=0.083;
                   11945:     /* printf("%lf %lf", p[1], p[2]); */
1.126     brouard  11946:     
                   11947:     
1.136     brouard  11948: #ifdef GSL
                   11949:     printf("GSL optimization\n");  fprintf(ficlog,"Powell\n");
1.162     brouard  11950: #else
1.126     brouard  11951:     printf("Powell\n");  fprintf(ficlog,"Powell\n");
1.136     brouard  11952: #endif
1.201     brouard  11953:     strcpy(filerespow,"POW-MORT_"); 
                   11954:     strcat(filerespow,fileresu);
1.126     brouard  11955:     if((ficrespow=fopen(filerespow,"w"))==NULL) {
                   11956:       printf("Problem with resultfile: %s\n", filerespow);
                   11957:       fprintf(ficlog,"Problem with resultfile: %s\n", filerespow);
                   11958:     }
1.136     brouard  11959: #ifdef GSL
                   11960:     fprintf(ficrespow,"# GSL optimization\n# iter -2*LL");
1.162     brouard  11961: #else
1.126     brouard  11962:     fprintf(ficrespow,"# Powell\n# iter -2*LL");
1.136     brouard  11963: #endif
1.126     brouard  11964:     /*  for (i=1;i<=nlstate;i++)
                   11965:        for(j=1;j<=nlstate+ndeath;j++)
                   11966:        if(j!=i)fprintf(ficrespow," p%1d%1d",i,j);
                   11967:     */
                   11968:     fprintf(ficrespow,"\n");
1.136     brouard  11969: #ifdef GSL
                   11970:     /* gsl starts here */ 
                   11971:     T = gsl_multimin_fminimizer_nmsimplex;
                   11972:     gsl_multimin_fminimizer *sfm = NULL;
                   11973:     gsl_vector *ss, *x;
                   11974:     gsl_multimin_function minex_func;
                   11975: 
                   11976:     /* Initial vertex size vector */
                   11977:     ss = gsl_vector_alloc (NDIM);
                   11978:     
                   11979:     if (ss == NULL){
                   11980:       GSL_ERROR_VAL ("failed to allocate space for ss", GSL_ENOMEM, 0);
                   11981:     }
                   11982:     /* Set all step sizes to 1 */
                   11983:     gsl_vector_set_all (ss, 0.001);
                   11984: 
                   11985:     /* Starting point */
1.126     brouard  11986:     
1.136     brouard  11987:     x = gsl_vector_alloc (NDIM);
                   11988:     
                   11989:     if (x == NULL){
                   11990:       gsl_vector_free(ss);
                   11991:       GSL_ERROR_VAL ("failed to allocate space for x", GSL_ENOMEM, 0);
                   11992:     }
                   11993:   
                   11994:     /* Initialize method and iterate */
                   11995:     /*     p[1]=0.0268; p[NDIM]=0.083; */
1.186     brouard  11996:     /*     gsl_vector_set(x, 0, 0.0268); */
                   11997:     /*     gsl_vector_set(x, 1, 0.083); */
1.136     brouard  11998:     gsl_vector_set(x, 0, p[1]);
                   11999:     gsl_vector_set(x, 1, p[2]);
                   12000: 
                   12001:     minex_func.f = &gompertz_f;
                   12002:     minex_func.n = NDIM;
                   12003:     minex_func.params = (void *)&p; /* ??? */
                   12004:     
                   12005:     sfm = gsl_multimin_fminimizer_alloc (T, NDIM);
                   12006:     gsl_multimin_fminimizer_set (sfm, &minex_func, x, ss);
                   12007:     
                   12008:     printf("Iterations beginning .....\n\n");
                   12009:     printf("Iter. #    Intercept       Slope     -Log Likelihood     Simplex size\n");
                   12010: 
                   12011:     iteri=0;
                   12012:     while (rval == GSL_CONTINUE){
                   12013:       iteri++;
                   12014:       status = gsl_multimin_fminimizer_iterate(sfm);
                   12015:       
                   12016:       if (status) printf("error: %s\n", gsl_strerror (status));
                   12017:       fflush(0);
                   12018:       
                   12019:       if (status) 
                   12020:         break;
                   12021:       
                   12022:       rval = gsl_multimin_test_size (gsl_multimin_fminimizer_size (sfm), 1e-6);
                   12023:       ssval = gsl_multimin_fminimizer_size (sfm);
                   12024:       
                   12025:       if (rval == GSL_SUCCESS)
                   12026:         printf ("converged to a local maximum at\n");
                   12027:       
                   12028:       printf("%5d ", iteri);
                   12029:       for (it = 0; it < NDIM; it++){
                   12030:        printf ("%10.5f ", gsl_vector_get (sfm->x, it));
                   12031:       }
                   12032:       printf("f() = %-10.5f ssize = %.7f\n", sfm->fval, ssval);
                   12033:     }
                   12034:     
                   12035:     printf("\n\n Please note: Program should be run many times with varying starting points to detemine global maximum\n\n");
                   12036:     
                   12037:     gsl_vector_free(x); /* initial values */
                   12038:     gsl_vector_free(ss); /* inital step size */
                   12039:     for (it=0; it<NDIM; it++){
                   12040:       p[it+1]=gsl_vector_get(sfm->x,it);
                   12041:       fprintf(ficrespow," %.12lf", p[it]);
                   12042:     }
                   12043:     gsl_multimin_fminimizer_free (sfm); /* p *(sfm.x.data) et p *(sfm.x.data+1)  */
                   12044: #endif
                   12045: #ifdef POWELL
                   12046:      powell(p,ximort,NDIM,ftol,&iter,&fret,gompertz);
                   12047: #endif  
1.126     brouard  12048:     fclose(ficrespow);
                   12049:     
1.203     brouard  12050:     hesscov(matcov, hess, p, NDIM, delti, 1e-4, gompertz); 
1.126     brouard  12051: 
                   12052:     for(i=1; i <=NDIM; i++)
                   12053:       for(j=i+1;j<=NDIM;j++)
1.220     brouard  12054:                                matcov[i][j]=matcov[j][i];
1.126     brouard  12055:     
                   12056:     printf("\nCovariance matrix\n ");
1.203     brouard  12057:     fprintf(ficlog,"\nCovariance matrix\n ");
1.126     brouard  12058:     for(i=1; i <=NDIM; i++) {
                   12059:       for(j=1;j<=NDIM;j++){ 
1.220     brouard  12060:                                printf("%f ",matcov[i][j]);
                   12061:                                fprintf(ficlog,"%f ",matcov[i][j]);
1.126     brouard  12062:       }
1.203     brouard  12063:       printf("\n ");  fprintf(ficlog,"\n ");
1.126     brouard  12064:     }
                   12065:     
                   12066:     printf("iter=%d MLE=%f Eq=%lf*exp(%lf*(age-%d))\n",iter,-gompertz(p),p[1],p[2],agegomp);
1.193     brouard  12067:     for (i=1;i<=NDIM;i++) {
1.126     brouard  12068:       printf("%f [%f ; %f]\n",p[i],p[i]-2*sqrt(matcov[i][i]),p[i]+2*sqrt(matcov[i][i]));
1.193     brouard  12069:       fprintf(ficlog,"%f [%f ; %f]\n",p[i],p[i]-2*sqrt(matcov[i][i]),p[i]+2*sqrt(matcov[i][i]));
                   12070:     }
1.302     brouard  12071:     lsurv=vector(agegomp,AGESUP);
                   12072:     lpop=vector(agegomp,AGESUP);
                   12073:     tpop=vector(agegomp,AGESUP);
1.126     brouard  12074:     lsurv[agegomp]=100000;
                   12075:     
                   12076:     for (k=agegomp;k<=AGESUP;k++) {
                   12077:       agemortsup=k;
                   12078:       if (p[1]*exp(p[2]*(k-agegomp))>1) break;
                   12079:     }
                   12080:     
                   12081:     for (k=agegomp;k<agemortsup;k++)
                   12082:       lsurv[k+1]=lsurv[k]-lsurv[k]*(p[1]*exp(p[2]*(k-agegomp)));
                   12083:     
                   12084:     for (k=agegomp;k<agemortsup;k++){
                   12085:       lpop[k]=(lsurv[k]+lsurv[k+1])/2.;
                   12086:       sumlpop=sumlpop+lpop[k];
                   12087:     }
                   12088:     
                   12089:     tpop[agegomp]=sumlpop;
                   12090:     for (k=agegomp;k<(agemortsup-3);k++){
                   12091:       /*  tpop[k+1]=2;*/
                   12092:       tpop[k+1]=tpop[k]-lpop[k];
                   12093:     }
                   12094:     
                   12095:     
                   12096:     printf("\nAge   lx     qx    dx    Lx     Tx     e(x)\n");
                   12097:     for (k=agegomp;k<(agemortsup-2);k++) 
                   12098:       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]);
                   12099:     
                   12100:     
                   12101:     replace_back_to_slash(pathc,pathcd); /* Even gnuplot wants a / */
1.220     brouard  12102:                ageminpar=50;
                   12103:                agemaxpar=100;
1.194     brouard  12104:     if(ageminpar == AGEOVERFLOW ||agemaxpar == AGEOVERFLOW){
                   12105:        printf("Warning! Error in gnuplot file with ageminpar %f or agemaxpar %f overflow\n\
                   12106: This is probably because your parameter file doesn't \n  contain the exact number of lines (or columns) corresponding to your model line.\n\
                   12107: Please run with mle=-1 to get a correct covariance matrix.\n",ageminpar,agemaxpar);
                   12108:        fprintf(ficlog,"Warning! Error in gnuplot file with ageminpar %f or agemaxpar %f overflow\n\
                   12109: This is probably because your parameter file doesn't \n  contain the exact number of lines (or columns) corresponding to your model line.\n\
                   12110: Please run with mle=-1 to get a correct covariance matrix.\n",ageminpar,agemaxpar);
1.220     brouard  12111:     }else{
                   12112:                        printf("Warning! ageminpar %f and agemaxpar %f have been fixed because for simplification until it is fixed...\n\n",ageminpar,agemaxpar);
                   12113:                        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  12114:       printinggnuplotmort(fileresu, optionfilefiname,ageminpar,agemaxpar,fage, pathc,p);
1.220     brouard  12115:                }
1.201     brouard  12116:     printinghtmlmort(fileresu,title,datafile, firstpass, lastpass, \
1.126     brouard  12117:                     stepm, weightopt,\
                   12118:                     model,imx,p,matcov,agemortsup);
                   12119:     
1.302     brouard  12120:     free_vector(lsurv,agegomp,AGESUP);
                   12121:     free_vector(lpop,agegomp,AGESUP);
                   12122:     free_vector(tpop,agegomp,AGESUP);
1.220     brouard  12123:     free_matrix(ximort,1,NDIM,1,NDIM);
1.290     brouard  12124:     free_ivector(dcwave,firstobs,lastobs);
                   12125:     free_vector(agecens,firstobs,lastobs);
                   12126:     free_vector(ageexmed,firstobs,lastobs);
                   12127:     free_ivector(cens,firstobs,lastobs);
1.220     brouard  12128: #ifdef GSL
1.136     brouard  12129: #endif
1.186     brouard  12130:   } /* Endof if mle==-3 mortality only */
1.205     brouard  12131:   /* Standard  */
                   12132:   else{ /* For mle !=- 3, could be 0 or 1 or 4 etc. */
                   12133:     globpr=0;/* Computes sum of likelihood for globpr=1 and funcone */
                   12134:     /* Computes likelihood for initial parameters, uses funcone to compute gpimx and gsw */
1.132     brouard  12135:     likelione(ficres, p, npar, nlstate, &globpr, &ipmx, &sw, &fretone, funcone); /* Prints the contributions to the likelihood */
1.126     brouard  12136:     printf("First Likeli=%12.6f ipmx=%ld sw=%12.6f",fretone,ipmx,sw);
                   12137:     for (k=1; k<=npar;k++)
                   12138:       printf(" %d %8.5f",k,p[k]);
                   12139:     printf("\n");
1.205     brouard  12140:     if(mle>=1){ /* Could be 1 or 2, Real Maximization */
                   12141:       /* mlikeli uses func not funcone */
1.247     brouard  12142:       /* for(i=1;i<nlstate;i++){ */
                   12143:       /*       /\*reducing xi for 1 to npar to 1 to ncovmodel; *\/ */
                   12144:       /*    mlikeli(ficres,p, ncovmodel, ncovmodel, nlstate, ftol, funcnoprod); */
                   12145:       /* } */
1.205     brouard  12146:       mlikeli(ficres,p, npar, ncovmodel, nlstate, ftol, func);
                   12147:     }
                   12148:     if(mle==0) {/* No optimization, will print the likelihoods for the datafile */
                   12149:       globpr=0;/* Computes sum of likelihood for globpr=1 and funcone */
                   12150:       /* Computes likelihood for initial parameters, uses funcone to compute gpimx and gsw */
                   12151:       likelione(ficres, p, npar, nlstate, &globpr, &ipmx, &sw, &fretone, funcone); /* Prints the contributions to the likelihood */
                   12152:     }
                   12153:     globpr=1; /* again, to print the individual contributions using computed gpimx and gsw */
1.126     brouard  12154:     likelione(ficres, p, npar, nlstate, &globpr, &ipmx, &sw, &fretone, funcone); /* Prints the contributions to the likelihood */
                   12155:     printf("Second 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");
                   12159:     
                   12160:     /*--------- results files --------------*/
1.283     brouard  12161:     /* 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  12162:     
                   12163:     
                   12164:     fprintf(ficres,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
                   12165:     printf("# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
                   12166:     fprintf(ficlog,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
                   12167:     for(i=1,jk=1; i <=nlstate; i++){
                   12168:       for(k=1; k <=(nlstate+ndeath); k++){
1.225     brouard  12169:        if (k != i) {
                   12170:          printf("%d%d ",i,k);
                   12171:          fprintf(ficlog,"%d%d ",i,k);
                   12172:          fprintf(ficres,"%1d%1d ",i,k);
                   12173:          for(j=1; j <=ncovmodel; j++){
                   12174:            printf("%12.7f ",p[jk]);
                   12175:            fprintf(ficlog,"%12.7f ",p[jk]);
                   12176:            fprintf(ficres,"%12.7f ",p[jk]);
                   12177:            jk++; 
                   12178:          }
                   12179:          printf("\n");
                   12180:          fprintf(ficlog,"\n");
                   12181:          fprintf(ficres,"\n");
                   12182:        }
1.126     brouard  12183:       }
                   12184:     }
1.203     brouard  12185:     if(mle != 0){
                   12186:       /* Computing hessian and covariance matrix only at a peak of the Likelihood, that is after optimization */
1.126     brouard  12187:       ftolhess=ftol; /* Usually correct */
1.203     brouard  12188:       hesscov(matcov, hess, p, npar, delti, ftolhess, func);
                   12189:       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");
                   12190:       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");
                   12191:       for(i=1,jk=1; i <=nlstate; i++){
1.225     brouard  12192:        for(k=1; k <=(nlstate+ndeath); k++){
                   12193:          if (k != i) {
                   12194:            printf("%d%d ",i,k);
                   12195:            fprintf(ficlog,"%d%d ",i,k);
                   12196:            for(j=1; j <=ncovmodel; j++){
                   12197:              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]));
                   12198:              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]));
                   12199:              jk++; 
                   12200:            }
                   12201:            printf("\n");
                   12202:            fprintf(ficlog,"\n");
                   12203:          }
                   12204:        }
1.193     brouard  12205:       }
1.203     brouard  12206:     } /* end of hesscov and Wald tests */
1.225     brouard  12207:     
1.203     brouard  12208:     /*  */
1.126     brouard  12209:     fprintf(ficres,"# Scales (for hessian or gradient estimation)\n");
                   12210:     printf("# Scales (for hessian or gradient estimation)\n");
                   12211:     fprintf(ficlog,"# Scales (for hessian or gradient estimation)\n");
                   12212:     for(i=1,jk=1; i <=nlstate; i++){
                   12213:       for(j=1; j <=nlstate+ndeath; j++){
1.225     brouard  12214:        if (j!=i) {
                   12215:          fprintf(ficres,"%1d%1d",i,j);
                   12216:          printf("%1d%1d",i,j);
                   12217:          fprintf(ficlog,"%1d%1d",i,j);
                   12218:          for(k=1; k<=ncovmodel;k++){
                   12219:            printf(" %.5e",delti[jk]);
                   12220:            fprintf(ficlog," %.5e",delti[jk]);
                   12221:            fprintf(ficres," %.5e",delti[jk]);
                   12222:            jk++;
                   12223:          }
                   12224:          printf("\n");
                   12225:          fprintf(ficlog,"\n");
                   12226:          fprintf(ficres,"\n");
                   12227:        }
1.126     brouard  12228:       }
                   12229:     }
                   12230:     
                   12231:     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  12232:     if(mle >= 1) /* To big for the screen */
1.126     brouard  12233:       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");
                   12234:     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");
                   12235:     /* # 121 Var(a12)\n\ */
                   12236:     /* # 122 Cov(b12,a12) Var(b12)\n\ */
                   12237:     /* # 131 Cov(a13,a12) Cov(a13,b12, Var(a13)\n\ */
                   12238:     /* # 132 Cov(b13,a12) Cov(b13,b12, Cov(b13,a13) Var(b13)\n\ */
                   12239:     /* # 212 Cov(a21,a12) Cov(a21,b12, Cov(a21,a13) Cov(a21,b13) Var(a21)\n\ */
                   12240:     /* # 212 Cov(b21,a12) Cov(b21,b12, Cov(b21,a13) Cov(b21,b13) Cov(b21,a21) Var(b21)\n\ */
                   12241:     /* # 232 Cov(a23,a12) Cov(a23,b12, Cov(a23,a13) Cov(a23,b13) Cov(a23,a21) Cov(a23,b21) Var(a23)\n\ */
                   12242:     /* # 232 Cov(b23,a12) Cov(b23,b12) ... Var (b23)\n" */
                   12243:     
                   12244:     
                   12245:     /* Just to have a covariance matrix which will be more understandable
                   12246:        even is we still don't want to manage dictionary of variables
                   12247:     */
                   12248:     for(itimes=1;itimes<=2;itimes++){
                   12249:       jj=0;
                   12250:       for(i=1; i <=nlstate; i++){
1.225     brouard  12251:        for(j=1; j <=nlstate+ndeath; j++){
                   12252:          if(j==i) continue;
                   12253:          for(k=1; k<=ncovmodel;k++){
                   12254:            jj++;
                   12255:            ca[0]= k+'a'-1;ca[1]='\0';
                   12256:            if(itimes==1){
                   12257:              if(mle>=1)
                   12258:                printf("#%1d%1d%d",i,j,k);
                   12259:              fprintf(ficlog,"#%1d%1d%d",i,j,k);
                   12260:              fprintf(ficres,"#%1d%1d%d",i,j,k);
                   12261:            }else{
                   12262:              if(mle>=1)
                   12263:                printf("%1d%1d%d",i,j,k);
                   12264:              fprintf(ficlog,"%1d%1d%d",i,j,k);
                   12265:              fprintf(ficres,"%1d%1d%d",i,j,k);
                   12266:            }
                   12267:            ll=0;
                   12268:            for(li=1;li <=nlstate; li++){
                   12269:              for(lj=1;lj <=nlstate+ndeath; lj++){
                   12270:                if(lj==li) continue;
                   12271:                for(lk=1;lk<=ncovmodel;lk++){
                   12272:                  ll++;
                   12273:                  if(ll<=jj){
                   12274:                    cb[0]= lk +'a'-1;cb[1]='\0';
                   12275:                    if(ll<jj){
                   12276:                      if(itimes==1){
                   12277:                        if(mle>=1)
                   12278:                          printf(" Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
                   12279:                        fprintf(ficlog," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
                   12280:                        fprintf(ficres," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
                   12281:                      }else{
                   12282:                        if(mle>=1)
                   12283:                          printf(" %.5e",matcov[jj][ll]); 
                   12284:                        fprintf(ficlog," %.5e",matcov[jj][ll]); 
                   12285:                        fprintf(ficres," %.5e",matcov[jj][ll]); 
                   12286:                      }
                   12287:                    }else{
                   12288:                      if(itimes==1){
                   12289:                        if(mle>=1)
                   12290:                          printf(" Var(%s%1d%1d)",ca,i,j);
                   12291:                        fprintf(ficlog," Var(%s%1d%1d)",ca,i,j);
                   12292:                        fprintf(ficres," Var(%s%1d%1d)",ca,i,j);
                   12293:                      }else{
                   12294:                        if(mle>=1)
                   12295:                          printf(" %.7e",matcov[jj][ll]); 
                   12296:                        fprintf(ficlog," %.7e",matcov[jj][ll]); 
                   12297:                        fprintf(ficres," %.7e",matcov[jj][ll]); 
                   12298:                      }
                   12299:                    }
                   12300:                  }
                   12301:                } /* end lk */
                   12302:              } /* end lj */
                   12303:            } /* end li */
                   12304:            if(mle>=1)
                   12305:              printf("\n");
                   12306:            fprintf(ficlog,"\n");
                   12307:            fprintf(ficres,"\n");
                   12308:            numlinepar++;
                   12309:          } /* end k*/
                   12310:        } /*end j */
1.126     brouard  12311:       } /* end i */
                   12312:     } /* end itimes */
                   12313:     
                   12314:     fflush(ficlog);
                   12315:     fflush(ficres);
1.225     brouard  12316:     while(fgets(line, MAXLINE, ficpar)) {
                   12317:       /* If line starts with a # it is a comment */
                   12318:       if (line[0] == '#') {
                   12319:        numlinepar++;
                   12320:        fputs(line,stdout);
                   12321:        fputs(line,ficparo);
                   12322:        fputs(line,ficlog);
1.299     brouard  12323:        fputs(line,ficres);
1.225     brouard  12324:        continue;
                   12325:       }else
                   12326:        break;
                   12327:     }
                   12328:     
1.209     brouard  12329:     /* while((c=getc(ficpar))=='#' && c!= EOF){ */
                   12330:     /*   ungetc(c,ficpar); */
                   12331:     /*   fgets(line, MAXLINE, ficpar); */
                   12332:     /*   fputs(line,stdout); */
                   12333:     /*   fputs(line,ficparo); */
                   12334:     /* } */
                   12335:     /* ungetc(c,ficpar); */
1.126     brouard  12336:     
                   12337:     estepm=0;
1.209     brouard  12338:     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  12339:       
                   12340:       if (num_filled != 6) {
                   12341:        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);
                   12342:        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);
                   12343:        goto end;
                   12344:       }
                   12345:       printf("agemin=%lf agemax=%lf bage=%lf fage=%lf estepm=%d ftolpl=%lf\n",ageminpar,agemaxpar, bage, fage, estepm, ftolpl);
                   12346:     }
                   12347:     /* ftolpl=6*ftol*1.e5; /\* 6.e-3 make convergences in less than 80 loops for the prevalence limit *\/ */
                   12348:     /*ftolpl=6.e-4;*/ /* 6.e-3 make convergences in less than 80 loops for the prevalence limit */
                   12349:     
1.209     brouard  12350:     /* fscanf(ficpar,"agemin=%lf agemax=%lf bage=%lf fage=%lf estepm=%d ftolpl=%\n",&ageminpar,&agemaxpar, &bage, &fage, &estepm); */
1.126     brouard  12351:     if (estepm==0 || estepm < stepm) estepm=stepm;
                   12352:     if (fage <= 2) {
                   12353:       bage = ageminpar;
                   12354:       fage = agemaxpar;
                   12355:     }
                   12356:     
                   12357:     fprintf(ficres,"# agemin agemax for life expectancy, bage fage (if mle==0 ie no data nor Max likelihood).\n");
1.211     brouard  12358:     fprintf(ficres,"agemin=%.0f agemax=%.0f bage=%.0f fage=%.0f estepm=%d ftolpl=%e\n",ageminpar,agemaxpar,bage,fage, estepm, ftolpl);
                   12359:     fprintf(ficparo,"agemin=%.0f agemax=%.0f bage=%.0f fage=%.0f estepm=%d, ftolpl=%e\n",ageminpar,agemaxpar,bage,fage, estepm, ftolpl);
1.220     brouard  12360:                
1.186     brouard  12361:     /* Other stuffs, more or less useful */    
1.254     brouard  12362:     while(fgets(line, MAXLINE, ficpar)) {
                   12363:       /* If line starts with a # it is a comment */
                   12364:       if (line[0] == '#') {
                   12365:        numlinepar++;
                   12366:        fputs(line,stdout);
                   12367:        fputs(line,ficparo);
                   12368:        fputs(line,ficlog);
1.299     brouard  12369:        fputs(line,ficres);
1.254     brouard  12370:        continue;
                   12371:       }else
                   12372:        break;
                   12373:     }
                   12374: 
                   12375:     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){
                   12376:       
                   12377:       if (num_filled != 7) {
                   12378:        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);
                   12379:        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);
                   12380:        goto end;
                   12381:       }
                   12382:       printf("begin-prev-date=%.lf/%.lf/%.lf end-prev-date=%.lf/%.lf/%.lf mov_average=%d\n",jprev1, mprev1,anprev1,jprev2, mprev2,anprev2,mobilav);
                   12383:       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);
                   12384:       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);
                   12385:       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  12386:     }
1.254     brouard  12387: 
                   12388:     while(fgets(line, MAXLINE, ficpar)) {
                   12389:       /* If line starts with a # it is a comment */
                   12390:       if (line[0] == '#') {
                   12391:        numlinepar++;
                   12392:        fputs(line,stdout);
                   12393:        fputs(line,ficparo);
                   12394:        fputs(line,ficlog);
1.299     brouard  12395:        fputs(line,ficres);
1.254     brouard  12396:        continue;
                   12397:       }else
                   12398:        break;
1.126     brouard  12399:     }
                   12400:     
                   12401:     
                   12402:     dateprev1=anprev1+(mprev1-1)/12.+(jprev1-1)/365.;
                   12403:     dateprev2=anprev2+(mprev2-1)/12.+(jprev2-1)/365.;
                   12404:     
1.254     brouard  12405:     if((num_filled=sscanf(line,"pop_based=%d\n",&popbased)) !=EOF){
                   12406:       if (num_filled != 1) {
                   12407:        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);
                   12408:        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);
                   12409:        goto end;
                   12410:       }
                   12411:       printf("pop_based=%d\n",popbased);
                   12412:       fprintf(ficlog,"pop_based=%d\n",popbased);
                   12413:       fprintf(ficparo,"pop_based=%d\n",popbased);   
                   12414:       fprintf(ficres,"pop_based=%d\n",popbased);   
                   12415:     }
                   12416:      
1.258     brouard  12417:     /* Results */
1.307   ! brouard  12418:     endishere=0;
1.258     brouard  12419:     nresult=0;
                   12420:     do{
                   12421:       if(!fgets(line, MAXLINE, ficpar)){
                   12422:        endishere=1;
                   12423:       }else if (line[0] == '#') {
                   12424:        /* If line starts with a # it is a comment */
1.254     brouard  12425:        numlinepar++;
                   12426:        fputs(line,stdout);
                   12427:        fputs(line,ficparo);
                   12428:        fputs(line,ficlog);
1.299     brouard  12429:        fputs(line,ficres);
1.254     brouard  12430:        continue;
1.258     brouard  12431:       }else if(sscanf(line,"prevforecast=%[^\n]\n",modeltemp))
                   12432:        parameterline=11;
1.296     brouard  12433:       else if(sscanf(line,"prevbackcast=%[^\n]\n",modeltemp))
1.258     brouard  12434:        parameterline=12;
1.307   ! brouard  12435:       else if(sscanf(line,"result:%[^\n]\n",modeltemp)){
1.258     brouard  12436:        parameterline=13;
1.307   ! brouard  12437:       }
1.258     brouard  12438:       else{
                   12439:        parameterline=14;
1.254     brouard  12440:       }
1.258     brouard  12441:       switch (parameterline){ 
                   12442:       case 11:
1.296     brouard  12443:        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)){
                   12444:                  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  12445:          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);
                   12446:          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);
                   12447:          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);
                   12448:          /* day and month of proj2 are not used but only year anproj2.*/
1.273     brouard  12449:          dateproj1=anproj1+(mproj1-1)/12.+(jproj1-1)/365.;
                   12450:          dateproj2=anproj2+(mproj2-1)/12.+(jproj2-1)/365.;
1.296     brouard  12451:           prvforecast = 1;
                   12452:        } 
                   12453:        else if((num_filled=sscanf(line,"prevforecast=%d yearsfproj=%lf mobil_average=%d\n",&prevfcast,&yrfproj,&mobilavproj)) !=EOF){/* && (num_filled == 3))*/
1.302     brouard  12454:          printf("prevforecast=%d yearsfproj=%lf.2 mobil_average=%d\n",prevfcast,yrfproj,mobilavproj);
                   12455:          fprintf(ficlog,"prevforecast=%d yearsfproj=%lf.2 mobil_average=%d\n",prevfcast,yrfproj,mobilavproj);
                   12456:          fprintf(ficres,"prevforecast=%d yearsfproj=%lf.2 mobil_average=%d\n",prevfcast,yrfproj,mobilavproj);
1.296     brouard  12457:           prvforecast = 2;
                   12458:        }
                   12459:        else {
                   12460:          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);
                   12461:          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);
                   12462:          goto end;
1.258     brouard  12463:        }
1.254     brouard  12464:        break;
1.258     brouard  12465:       case 12:
1.296     brouard  12466:        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)){
                   12467:           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);
                   12468:          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);
                   12469:          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);
                   12470:          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);
                   12471:          /* day and month of back2 are not used but only year anback2.*/
1.273     brouard  12472:          dateback1=anback1+(mback1-1)/12.+(jback1-1)/365.;
                   12473:          dateback2=anback2+(mback2-1)/12.+(jback2-1)/365.;
1.296     brouard  12474:           prvbackcast = 1;
                   12475:        } 
                   12476:        else if((num_filled=sscanf(line,"prevbackcast=%d yearsbproj=%lf mobil_average=%d\n",&prevbcast,&yrbproj,&mobilavproj)) ==3){/* && (num_filled == 3))*/
1.302     brouard  12477:          printf("prevbackcast=%d yearsbproj=%lf.2 mobil_average=%d\n",prevbcast,yrbproj,mobilavproj);
                   12478:          fprintf(ficlog,"prevbackcast=%d yearsbproj=%lf.2 mobil_average=%d\n",prevbcast,yrbproj,mobilavproj);
                   12479:          fprintf(ficres,"prevbackcast=%d yearsbproj=%lf.2 mobil_average=%d\n",prevbcast,yrbproj,mobilavproj);
1.296     brouard  12480:           prvbackcast = 2;
                   12481:        }
                   12482:        else {
                   12483:          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);
                   12484:          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);
                   12485:          goto end;
1.258     brouard  12486:        }
1.230     brouard  12487:        break;
1.258     brouard  12488:       case 13:
1.307   ! brouard  12489:        num_filled=sscanf(line,"result:%[^\n]\n",resultline);
        !          12490:        nresult++; /* Sum of resultlines */
        !          12491:        printf("Result %d: result:%s\n",nresult, resultline);
        !          12492:        if(nresult > MAXRESULTLINES){
        !          12493:          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);
        !          12494:          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);
        !          12495:          goto end;
        !          12496:        }
        !          12497:        decoderesult(resultline, nresult); /* Fills TKresult[nresult] combination and Tresult[nresult][k4+1] combination values */
        !          12498:        fprintf(ficparo,"result: %s\n",resultline);
        !          12499:        fprintf(ficres,"result: %s\n",resultline);
        !          12500:        fprintf(ficlog,"result: %s\n",resultline);
        !          12501:        break;
        !          12502:       case 14:
        !          12503:        printf("Error: Unknown command '%s'\n",line);
        !          12504:        fprintf(ficlog,"Error: Unknown command '%s'\n",line);
        !          12505:        if(ncovmodel >=2 && nresult==0 ){
        !          12506:          printf("ERROR: no result lines! It should be at minimum 'result: V2=0 V1=1 or result:.' %s\n",line);
        !          12507:          fprintf(ficlog,"ERROR: no result lines! It should be at minimum 'result: V2=0 V1=1 or result:.' %s\n",line);
1.258     brouard  12508:        }
1.307   ! brouard  12509:        /* goto end; */
        !          12510:        break;
        !          12511:       default:
        !          12512:        nresult=1;
        !          12513:        decoderesult(".",nresult ); /* No covariate */
1.258     brouard  12514:       } /* End switch parameterline */
1.307   ! brouard  12515:       parameterline=0;
1.258     brouard  12516:     }while(endishere==0); /* End do */
1.126     brouard  12517:     
1.230     brouard  12518:     /* freqsummary(fileres, agemin, agemax, s, agev, nlstate, imx,Tvaraff,nbcode, ncodemax,mint,anint); */
1.145     brouard  12519:     /* ,dateprev1,dateprev2,jprev1, mprev1,anprev1,jprev2, mprev2,anprev2); */
1.126     brouard  12520:     
                   12521:     replace_back_to_slash(pathc,pathcd); /* Even gnuplot wants a / */
1.194     brouard  12522:     if(ageminpar == AGEOVERFLOW ||agemaxpar == -AGEOVERFLOW){
1.230     brouard  12523:       printf("Warning! Error in gnuplot file with ageminpar %f or agemaxpar %f overflow\n\
1.194     brouard  12524: This is probably because your parameter file doesn't \n  contain the exact number of lines (or columns) corresponding to your model line.\n\
                   12525: Please run with mle=-1 to get a correct covariance matrix.\n",ageminpar,agemaxpar);
1.230     brouard  12526:       fprintf(ficlog,"Warning! Error in gnuplot file with ageminpar %f or agemaxpar %f overflow\n\
1.194     brouard  12527: This is probably because your parameter file doesn't \n  contain the exact number of lines (or columns) corresponding to your model line.\n\
                   12528: Please run with mle=-1 to get a correct covariance matrix.\n",ageminpar,agemaxpar);
1.220     brouard  12529:     }else{
1.270     brouard  12530:       /* printinggnuplot(fileresu, optionfilefiname,ageminpar,agemaxpar,fage, prevfcast, backcast, pathc,p, (int)anproj1-(int)agemin, (int)anback1-(int)agemax+1); */
1.296     brouard  12531:       /* It seems that anprojd which is computed from the mean year at interview which is known yet because of freqsummary */
                   12532:       /* date2dmy(dateintmean,&jintmean,&mintmean,&aintmean); */ /* Done in freqsummary */
                   12533:       if(prvforecast==1){
                   12534:         dateprojd=(jproj1+12*mproj1+365*anproj1)/365;
                   12535:         jprojd=jproj1;
                   12536:         mprojd=mproj1;
                   12537:         anprojd=anproj1;
                   12538:         dateprojf=(jproj2+12*mproj2+365*anproj2)/365;
                   12539:         jprojf=jproj2;
                   12540:         mprojf=mproj2;
                   12541:         anprojf=anproj2;
                   12542:       } else if(prvforecast == 2){
                   12543:         dateprojd=dateintmean;
                   12544:         date2dmy(dateprojd,&jprojd, &mprojd, &anprojd);
                   12545:         dateprojf=dateintmean+yrfproj;
                   12546:         date2dmy(dateprojf,&jprojf, &mprojf, &anprojf);
                   12547:       }
                   12548:       if(prvbackcast==1){
                   12549:         datebackd=(jback1+12*mback1+365*anback1)/365;
                   12550:         jbackd=jback1;
                   12551:         mbackd=mback1;
                   12552:         anbackd=anback1;
                   12553:         datebackf=(jback2+12*mback2+365*anback2)/365;
                   12554:         jbackf=jback2;
                   12555:         mbackf=mback2;
                   12556:         anbackf=anback2;
                   12557:       } else if(prvbackcast == 2){
                   12558:         datebackd=dateintmean;
                   12559:         date2dmy(datebackd,&jbackd, &mbackd, &anbackd);
                   12560:         datebackf=dateintmean-yrbproj;
                   12561:         date2dmy(datebackf,&jbackf, &mbackf, &anbackf);
                   12562:       }
                   12563:       
                   12564:       printinggnuplot(fileresu, optionfilefiname,ageminpar,agemaxpar,bage, fage, prevfcast, prevbcast, pathc,p, (int)anprojd-bage, (int)anbackd-fage);
1.220     brouard  12565:     }
                   12566:     printinghtml(fileresu,title,datafile, firstpass, lastpass, stepm, weightopt, \
1.296     brouard  12567:                 model,imx,jmin,jmax,jmean,rfileres,popforecast,mobilav,prevfcast,mobilavproj,prevbcast, estepm, \
                   12568:                 jprev1,mprev1,anprev1,dateprev1, dateprojd, datebackd,jprev2,mprev2,anprev2,dateprev2,dateprojf, datebackf);
1.220     brouard  12569:                
1.225     brouard  12570:     /*------------ free_vector  -------------*/
                   12571:     /*  chdir(path); */
1.220     brouard  12572:                
1.215     brouard  12573:     /* free_ivector(wav,1,imx); */  /* Moved after last prevalence call */
                   12574:     /* free_imatrix(dh,1,lastpass-firstpass+2,1,imx); */
                   12575:     /* free_imatrix(bh,1,lastpass-firstpass+2,1,imx); */
                   12576:     /* free_imatrix(mw,1,lastpass-firstpass+2,1,imx);    */
1.290     brouard  12577:     free_lvector(num,firstobs,lastobs);
                   12578:     free_vector(agedc,firstobs,lastobs);
1.126     brouard  12579:     /*free_matrix(covar,0,NCOVMAX,1,n);*/
                   12580:     /*free_matrix(covar,1,NCOVMAX,1,n);*/
                   12581:     fclose(ficparo);
                   12582:     fclose(ficres);
1.220     brouard  12583:                
                   12584:                
1.186     brouard  12585:     /* Other results (useful)*/
1.220     brouard  12586:                
                   12587:                
1.126     brouard  12588:     /*--------------- Prevalence limit  (period or stable prevalence) --------------*/
1.180     brouard  12589:     /*#include "prevlim.h"*/  /* Use ficrespl, ficlog */
                   12590:     prlim=matrix(1,nlstate,1,nlstate);
1.209     brouard  12591:     prevalence_limit(p, prlim,  ageminpar, agemaxpar, ftolpl, &ncvyear);
1.126     brouard  12592:     fclose(ficrespl);
                   12593: 
                   12594:     /*------------- h Pij x at various ages ------------*/
1.180     brouard  12595:     /*#include "hpijx.h"*/
                   12596:     hPijx(p, bage, fage);
1.145     brouard  12597:     fclose(ficrespij);
1.227     brouard  12598:     
1.220     brouard  12599:     /* ncovcombmax=  pow(2,cptcoveff); */
1.219     brouard  12600:     /*-------------- Variance of one-step probabilities---*/
1.145     brouard  12601:     k=1;
1.126     brouard  12602:     varprob(optionfilefiname, matcov, p, delti, nlstate, bage, fage,k,Tvar,nbcode, ncodemax,strstart);
1.227     brouard  12603:     
1.269     brouard  12604:     /* Prevalence for each covariate combination in probs[age][status][cov] */
                   12605:     probs= ma3x(AGEINF,AGESUP,1,nlstate+ndeath, 1,ncovcombmax);
                   12606:     for(i=AGEINF;i<=AGESUP;i++)
1.219     brouard  12607:       for(j=1;j<=nlstate+ndeath;j++) /* ndeath is useless but a necessity to be compared with mobaverages */
1.225     brouard  12608:        for(k=1;k<=ncovcombmax;k++)
                   12609:          probs[i][j][k]=0.;
1.269     brouard  12610:     prevalence(probs, ageminpar, agemaxpar, s, agev, nlstate, imx, Tvar, nbcode, 
                   12611:               ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass);
1.219     brouard  12612:     if (mobilav!=0 ||mobilavproj !=0 ) {
1.269     brouard  12613:       mobaverages= ma3x(AGEINF, AGESUP,1,nlstate+ndeath, 1,ncovcombmax);
                   12614:       for(i=AGEINF;i<=AGESUP;i++)
1.268     brouard  12615:        for(j=1;j<=nlstate+ndeath;j++)
1.227     brouard  12616:          for(k=1;k<=ncovcombmax;k++)
                   12617:            mobaverages[i][j][k]=0.;
1.219     brouard  12618:       mobaverage=mobaverages;
                   12619:       if (mobilav!=0) {
1.235     brouard  12620:        printf("Movingaveraging observed prevalence\n");
1.258     brouard  12621:        fprintf(ficlog,"Movingaveraging observed prevalence\n");
1.227     brouard  12622:        if (movingaverage(probs, ageminpar, agemaxpar, mobaverage, mobilav)!=0){
                   12623:          fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);
                   12624:          printf(" Error in movingaverage mobilav=%d\n",mobilav);
                   12625:        }
1.269     brouard  12626:       } else if (mobilavproj !=0) {
1.235     brouard  12627:        printf("Movingaveraging projected observed prevalence\n");
1.258     brouard  12628:        fprintf(ficlog,"Movingaveraging projected observed prevalence\n");
1.227     brouard  12629:        if (movingaverage(probs, ageminpar, agemaxpar, mobaverage, mobilavproj)!=0){
                   12630:          fprintf(ficlog," Error in movingaverage mobilavproj=%d\n",mobilavproj);
                   12631:          printf(" Error in movingaverage mobilavproj=%d\n",mobilavproj);
                   12632:        }
1.269     brouard  12633:       }else{
                   12634:        printf("Internal error moving average\n");
                   12635:        fflush(stdout);
                   12636:        exit(1);
1.219     brouard  12637:       }
                   12638:     }/* end if moving average */
1.227     brouard  12639:     
1.126     brouard  12640:     /*---------- Forecasting ------------------*/
1.296     brouard  12641:     if(prevfcast==1){ 
                   12642:       /*   /\*    if(stepm ==1){*\/ */
                   12643:       /*   /\*  anproj1, mproj1, jproj1 either read explicitly or yrfproj *\/ */
                   12644:       /*This done previously after freqsummary.*/
                   12645:       /*   dateprojd=(jproj1+12*mproj1+365*anproj1)/365; */
                   12646:       /*   dateprojf=(jproj2+12*mproj2+365*anproj2)/365; */
                   12647:       
                   12648:       /* } else if (prvforecast==2){ */
                   12649:       /*   /\*    if(stepm ==1){*\/ */
                   12650:       /*   /\*  anproj1, mproj1, jproj1 either read explicitly or yrfproj *\/ */
                   12651:       /* } */
                   12652:       /*prevforecast(fileresu, dateintmean, anproj1, mproj1, jproj1, agemin, agemax, dateprev1, dateprev2, mobilavproj, mobaverage, bage, fage, firstpass, lastpass, anproj2, p, cptcoveff);*/
                   12653:       prevforecast(fileresu,dateintmean, dateprojd, dateprojf, agemin, agemax, dateprev1, dateprev2, mobilavproj, mobaverage, bage, fage, firstpass, lastpass, p, cptcoveff);
1.126     brouard  12654:     }
1.269     brouard  12655: 
1.296     brouard  12656:     /* Prevbcasting */
                   12657:     if(prevbcast==1){
1.219     brouard  12658:       ddnewms=matrix(1,nlstate+ndeath,1,nlstate+ndeath);       
                   12659:       ddoldms=matrix(1,nlstate+ndeath,1,nlstate+ndeath);       
                   12660:       ddsavms=matrix(1,nlstate+ndeath,1,nlstate+ndeath);
                   12661: 
                   12662:       /*--------------- Back Prevalence limit  (period or stable prevalence) --------------*/
                   12663: 
                   12664:       bprlim=matrix(1,nlstate,1,nlstate);
1.269     brouard  12665: 
1.219     brouard  12666:       back_prevalence_limit(p, bprlim,  ageminpar, agemaxpar, ftolpl, &ncvyear, dateprev1, dateprev2, firstpass, lastpass, mobilavproj);
                   12667:       fclose(ficresplb);
                   12668: 
1.222     brouard  12669:       hBijx(p, bage, fage, mobaverage);
                   12670:       fclose(ficrespijb);
1.219     brouard  12671: 
1.296     brouard  12672:       /* /\* prevbackforecast(fileresu, mobaverage, anback1, mback1, jback1, agemin, agemax, dateprev1, dateprev2, *\/ */
                   12673:       /* /\*                  mobilavproj, bage, fage, firstpass, lastpass, anback2, p, cptcoveff); *\/ */
                   12674:       /* prevbackforecast(fileresu, mobaverage, anback1, mback1, jback1, agemin, agemax, dateprev1, dateprev2, */
                   12675:       /*                      mobilavproj, bage, fage, firstpass, lastpass, anback2, p, cptcoveff); */
                   12676:       prevbackforecast(fileresu, mobaverage, dateintmean, dateprojd, dateprojf, agemin, agemax, dateprev1, dateprev2,
                   12677:                       mobilavproj, bage, fage, firstpass, lastpass, p, cptcoveff);
                   12678: 
                   12679:       
1.269     brouard  12680:       varbprlim(fileresu, nresult, mobaverage, mobilavproj, bage, fage, bprlim, &ncvyear, ftolpl, p, matcov, delti, stepm, cptcoveff);
1.268     brouard  12681: 
                   12682:       
1.269     brouard  12683:       free_matrix(bprlim,1,nlstate,1,nlstate); /*here or after loop ? */
1.219     brouard  12684:       free_matrix(ddnewms, 1, nlstate+ndeath, 1, nlstate+ndeath);
                   12685:       free_matrix(ddsavms, 1, nlstate+ndeath, 1, nlstate+ndeath);
                   12686:       free_matrix(ddoldms, 1, nlstate+ndeath, 1, nlstate+ndeath);
1.296     brouard  12687:     }    /* end  Prevbcasting */
1.268     brouard  12688:  
1.186     brouard  12689:  
                   12690:     /* ------ Other prevalence ratios------------ */
1.126     brouard  12691: 
1.215     brouard  12692:     free_ivector(wav,1,imx);
                   12693:     free_imatrix(dh,1,lastpass-firstpass+2,1,imx);
                   12694:     free_imatrix(bh,1,lastpass-firstpass+2,1,imx);
                   12695:     free_imatrix(mw,1,lastpass-firstpass+2,1,imx);   
1.218     brouard  12696:                
                   12697:                
1.127     brouard  12698:     /*---------- Health expectancies, no variances ------------*/
1.218     brouard  12699:                
1.201     brouard  12700:     strcpy(filerese,"E_");
                   12701:     strcat(filerese,fileresu);
1.126     brouard  12702:     if((ficreseij=fopen(filerese,"w"))==NULL) {
                   12703:       printf("Problem with Health Exp. resultfile: %s\n", filerese); exit(0);
                   12704:       fprintf(ficlog,"Problem with Health Exp. resultfile: %s\n", filerese); exit(0);
                   12705:     }
1.208     brouard  12706:     printf("Computing Health Expectancies: result on file '%s' ...", filerese);fflush(stdout);
                   12707:     fprintf(ficlog,"Computing Health Expectancies: result on file '%s' ...", filerese);fflush(ficlog);
1.238     brouard  12708: 
                   12709:     pstamp(ficreseij);
1.219     brouard  12710:                
1.235     brouard  12711:     i1=pow(2,cptcoveff); /* Number of combination of dummy covariates */
                   12712:     if (cptcovn < 1){i1=1;}
                   12713:     
                   12714:     for(nres=1; nres <= nresult; nres++) /* For each resultline */
                   12715:     for(k=1; k<=i1;k++){ /* For any combination of dummy covariates, fixed and varying */
1.253     brouard  12716:       if(i1 != 1 && TKresult[nres]!= k)
1.235     brouard  12717:        continue;
1.219     brouard  12718:       fprintf(ficreseij,"\n#****** ");
1.235     brouard  12719:       printf("\n#****** ");
1.225     brouard  12720:       for(j=1;j<=cptcoveff;j++) {
1.227     brouard  12721:        fprintf(ficreseij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
1.235     brouard  12722:        printf("V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   12723:       }
                   12724:       for (j=1; j<= nsq; j++){ /* For each selected (single) quantitative value */
                   12725:        printf(" V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]);
                   12726:        fprintf(ficreseij," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]);
1.219     brouard  12727:       }
                   12728:       fprintf(ficreseij,"******\n");
1.235     brouard  12729:       printf("******\n");
1.219     brouard  12730:       
                   12731:       eij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
                   12732:       oldm=oldms;savm=savms;
1.235     brouard  12733:       evsij(eij, p, nlstate, stepm, (int) bage, (int)fage, oldm, savm, k, estepm, strstart, nres);  
1.127     brouard  12734:       
1.219     brouard  12735:       free_ma3x(eij,1,nlstate,1,nlstate,(int) bage, (int)fage);
1.127     brouard  12736:     }
                   12737:     fclose(ficreseij);
1.208     brouard  12738:     printf("done evsij\n");fflush(stdout);
                   12739:     fprintf(ficlog,"done evsij\n");fflush(ficlog);
1.269     brouard  12740: 
1.218     brouard  12741:                
1.227     brouard  12742:     /*---------- State-specific expectancies and variances ------------*/
1.218     brouard  12743:                
1.201     brouard  12744:     strcpy(filerest,"T_");
                   12745:     strcat(filerest,fileresu);
1.127     brouard  12746:     if((ficrest=fopen(filerest,"w"))==NULL) {
                   12747:       printf("Problem with total LE resultfile: %s\n", filerest);goto end;
                   12748:       fprintf(ficlog,"Problem with total LE resultfile: %s\n", filerest);goto end;
                   12749:     }
1.208     brouard  12750:     printf("Computing Total Life expectancies with their standard errors: file '%s' ...\n", filerest); fflush(stdout);
                   12751:     fprintf(ficlog,"Computing Total Life expectancies with their standard errors: file '%s' ...\n", filerest); fflush(ficlog);
1.201     brouard  12752:     strcpy(fileresstde,"STDE_");
                   12753:     strcat(fileresstde,fileresu);
1.126     brouard  12754:     if((ficresstdeij=fopen(fileresstde,"w"))==NULL) {
1.227     brouard  12755:       printf("Problem with State specific Exp. and std errors resultfile: %s\n", fileresstde); exit(0);
                   12756:       fprintf(ficlog,"Problem with State specific Exp. and std errors resultfile: %s\n", fileresstde); exit(0);
1.126     brouard  12757:     }
1.227     brouard  12758:     printf("  Computing State-specific Expectancies and standard errors: result on file '%s' \n", fileresstde);
                   12759:     fprintf(ficlog,"  Computing State-specific Expectancies and standard errors: result on file '%s' \n", fileresstde);
1.126     brouard  12760: 
1.201     brouard  12761:     strcpy(filerescve,"CVE_");
                   12762:     strcat(filerescve,fileresu);
1.126     brouard  12763:     if((ficrescveij=fopen(filerescve,"w"))==NULL) {
1.227     brouard  12764:       printf("Problem with Covar. State-specific Exp. resultfile: %s\n", filerescve); exit(0);
                   12765:       fprintf(ficlog,"Problem with Covar. State-specific Exp. resultfile: %s\n", filerescve); exit(0);
1.126     brouard  12766:     }
1.227     brouard  12767:     printf("    Computing Covar. of State-specific Expectancies: result on file '%s' \n", filerescve);
                   12768:     fprintf(ficlog,"    Computing Covar. of State-specific Expectancies: result on file '%s' \n", filerescve);
1.126     brouard  12769: 
1.201     brouard  12770:     strcpy(fileresv,"V_");
                   12771:     strcat(fileresv,fileresu);
1.126     brouard  12772:     if((ficresvij=fopen(fileresv,"w"))==NULL) {
                   12773:       printf("Problem with variance resultfile: %s\n", fileresv);exit(0);
                   12774:       fprintf(ficlog,"Problem with variance resultfile: %s\n", fileresv);exit(0);
                   12775:     }
1.227     brouard  12776:     printf("      Computing Variance-covariance of State-specific Expectancies: file '%s' ... ", fileresv);fflush(stdout);
                   12777:     fprintf(ficlog,"      Computing Variance-covariance of State-specific Expectancies: file '%s' ... ", fileresv);fflush(ficlog);
1.126     brouard  12778: 
1.235     brouard  12779:     i1=pow(2,cptcoveff); /* Number of combination of dummy covariates */
                   12780:     if (cptcovn < 1){i1=1;}
                   12781:     
                   12782:     for(nres=1; nres <= nresult; nres++) /* For each resultline */
                   12783:     for(k=1; k<=i1;k++){ /* For any combination of dummy covariates, fixed and varying */
1.253     brouard  12784:       if(i1 != 1 && TKresult[nres]!= k)
1.235     brouard  12785:        continue;
1.242     brouard  12786:       printf("\n#****** Result for:");
                   12787:       fprintf(ficrest,"\n#****** Result for:");
                   12788:       fprintf(ficlog,"\n#****** Result for:");
1.227     brouard  12789:       for(j=1;j<=cptcoveff;j++){ 
                   12790:        printf("V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   12791:        fprintf(ficrest,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   12792:        fprintf(ficlog,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   12793:       }
1.235     brouard  12794:       for (j=1; j<= nsq; j++){ /* For each selected (single) quantitative value */
                   12795:        printf(" V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]);
                   12796:        fprintf(ficrest," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]);
                   12797:        fprintf(ficlog," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]);
                   12798:       }        
1.208     brouard  12799:       fprintf(ficrest,"******\n");
1.227     brouard  12800:       fprintf(ficlog,"******\n");
                   12801:       printf("******\n");
1.208     brouard  12802:       
                   12803:       fprintf(ficresstdeij,"\n#****** ");
                   12804:       fprintf(ficrescveij,"\n#****** ");
1.225     brouard  12805:       for(j=1;j<=cptcoveff;j++) {
1.227     brouard  12806:        fprintf(ficresstdeij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   12807:        fprintf(ficrescveij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
1.208     brouard  12808:       }
1.235     brouard  12809:       for (j=1; j<= nsq; j++){ /* For each selected (single) quantitative value */
                   12810:        fprintf(ficresstdeij," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]);
                   12811:        fprintf(ficrescveij," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]);
                   12812:       }        
1.208     brouard  12813:       fprintf(ficresstdeij,"******\n");
                   12814:       fprintf(ficrescveij,"******\n");
                   12815:       
                   12816:       fprintf(ficresvij,"\n#****** ");
1.238     brouard  12817:       /* pstamp(ficresvij); */
1.225     brouard  12818:       for(j=1;j<=cptcoveff;j++) 
1.227     brouard  12819:        fprintf(ficresvij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
1.235     brouard  12820:       for (j=1; j<= nsq; j++){ /* For each selected (single) quantitative value */
                   12821:        fprintf(ficresvij," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]);
                   12822:       }        
1.208     brouard  12823:       fprintf(ficresvij,"******\n");
                   12824:       
                   12825:       eij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
                   12826:       oldm=oldms;savm=savms;
1.235     brouard  12827:       printf(" cvevsij ");
                   12828:       fprintf(ficlog, " cvevsij ");
                   12829:       cvevsij(eij, p, nlstate, stepm, (int) bage, (int)fage, oldm, savm, k, estepm, delti, matcov, strstart, nres);
1.208     brouard  12830:       printf(" end cvevsij \n ");
                   12831:       fprintf(ficlog, " end cvevsij \n ");
                   12832:       
                   12833:       /*
                   12834:        */
                   12835:       /* goto endfree; */
                   12836:       
                   12837:       vareij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
                   12838:       pstamp(ficrest);
                   12839:       
1.269     brouard  12840:       epj=vector(1,nlstate+1);
1.208     brouard  12841:       for(vpopbased=0; vpopbased <= popbased; vpopbased++){ /* Done for vpopbased=0 and vpopbased=1 if popbased==1*/
1.227     brouard  12842:        oldm=oldms;savm=savms; /* ZZ Segmentation fault */
                   12843:        cptcod= 0; /* To be deleted */
                   12844:        printf("varevsij vpopbased=%d \n",vpopbased);
                   12845:        fprintf(ficlog, "varevsij vpopbased=%d \n",vpopbased);
1.235     brouard  12846:        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  12847:        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 ");
                   12848:        if(vpopbased==1)
                   12849:          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);
                   12850:        else
1.288     brouard  12851:          fprintf(ficrest,"the age specific forward period (stable) prevalences in each health state \n");
1.227     brouard  12852:        fprintf(ficrest,"# Age popbased mobilav e.. (std) ");
                   12853:        for (i=1;i<=nlstate;i++) fprintf(ficrest,"e.%d (std) ",i);
                   12854:        fprintf(ficrest,"\n");
                   12855:        /* printf("Which p?\n"); for(i=1;i<=npar;i++)printf("p[i=%d]=%lf,",i,p[i]);printf("\n"); */
1.288     brouard  12856:        printf("Computing age specific forward period (stable) prevalences in each health state \n");
                   12857:        fprintf(ficlog,"Computing age specific forward period (stable) prevalences in each health state \n");
1.227     brouard  12858:        for(age=bage; age <=fage ;age++){
1.235     brouard  12859:          prevalim(prlim, nlstate, p, age, oldm, savm, ftolpl, &ncvyear, k, nres); /*ZZ Is it the correct prevalim */
1.227     brouard  12860:          if (vpopbased==1) {
                   12861:            if(mobilav ==0){
                   12862:              for(i=1; i<=nlstate;i++)
                   12863:                prlim[i][i]=probs[(int)age][i][k];
                   12864:            }else{ /* mobilav */ 
                   12865:              for(i=1; i<=nlstate;i++)
                   12866:                prlim[i][i]=mobaverage[(int)age][i][k];
                   12867:            }
                   12868:          }
1.219     brouard  12869:          
1.227     brouard  12870:          fprintf(ficrest," %4.0f %d %d",age, vpopbased, mobilav);
                   12871:          /* fprintf(ficrest," %4.0f %d %d %d %d",age, vpopbased, mobilav,Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]); */ /* to be done */
                   12872:          /* printf(" age %4.0f ",age); */
                   12873:          for(j=1, epj[nlstate+1]=0.;j <=nlstate;j++){
                   12874:            for(i=1, epj[j]=0.;i <=nlstate;i++) {
                   12875:              epj[j] += prlim[i][i]*eij[i][j][(int)age];
                   12876:              /*ZZZ  printf("%lf %lf ", prlim[i][i] ,eij[i][j][(int)age]);*/
                   12877:              /* printf("%lf %lf ", prlim[i][i] ,eij[i][j][(int)age]); */
                   12878:            }
                   12879:            epj[nlstate+1] +=epj[j];
                   12880:          }
                   12881:          /* printf(" age %4.0f \n",age); */
1.219     brouard  12882:          
1.227     brouard  12883:          for(i=1, vepp=0.;i <=nlstate;i++)
                   12884:            for(j=1;j <=nlstate;j++)
                   12885:              vepp += vareij[i][j][(int)age];
                   12886:          fprintf(ficrest," %7.3f (%7.3f)", epj[nlstate+1],sqrt(vepp));
                   12887:          for(j=1;j <=nlstate;j++){
                   12888:            fprintf(ficrest," %7.3f (%7.3f)", epj[j],sqrt(vareij[j][j][(int)age]));
                   12889:          }
                   12890:          fprintf(ficrest,"\n");
                   12891:        }
1.208     brouard  12892:       } /* End vpopbased */
1.269     brouard  12893:       free_vector(epj,1,nlstate+1);
1.208     brouard  12894:       free_ma3x(eij,1,nlstate,1,nlstate,(int) bage, (int)fage);
                   12895:       free_ma3x(vareij,1,nlstate,1,nlstate,(int) bage, (int)fage);
1.235     brouard  12896:       printf("done selection\n");fflush(stdout);
                   12897:       fprintf(ficlog,"done selection\n");fflush(ficlog);
1.208     brouard  12898:       
1.235     brouard  12899:     } /* End k selection */
1.227     brouard  12900: 
                   12901:     printf("done State-specific expectancies\n");fflush(stdout);
                   12902:     fprintf(ficlog,"done State-specific expectancies\n");fflush(ficlog);
                   12903: 
1.288     brouard  12904:     /* variance-covariance of forward period prevalence*/
1.269     brouard  12905:     varprlim(fileresu, nresult, mobaverage, mobilavproj, bage, fage, prlim, &ncvyear, ftolpl, p, matcov, delti, stepm, cptcoveff);
1.268     brouard  12906: 
1.227     brouard  12907:     
1.290     brouard  12908:     free_vector(weight,firstobs,lastobs);
1.227     brouard  12909:     free_imatrix(Tvard,1,NCOVMAX,1,2);
1.290     brouard  12910:     free_imatrix(s,1,maxwav+1,firstobs,lastobs);
                   12911:     free_matrix(anint,1,maxwav,firstobs,lastobs); 
                   12912:     free_matrix(mint,1,maxwav,firstobs,lastobs);
                   12913:     free_ivector(cod,firstobs,lastobs);
1.227     brouard  12914:     free_ivector(tab,1,NCOVMAX);
                   12915:     fclose(ficresstdeij);
                   12916:     fclose(ficrescveij);
                   12917:     fclose(ficresvij);
                   12918:     fclose(ficrest);
                   12919:     fclose(ficpar);
                   12920:     
                   12921:     
1.126     brouard  12922:     /*---------- End : free ----------------*/
1.219     brouard  12923:     if (mobilav!=0 ||mobilavproj !=0)
1.269     brouard  12924:       free_ma3x(mobaverages,AGEINF, AGESUP,1,nlstate+ndeath, 1,ncovcombmax); /* We need to have a squared matrix with prevalence of the dead! */
                   12925:     free_ma3x(probs,AGEINF,AGESUP,1,nlstate+ndeath, 1,ncovcombmax);
1.220     brouard  12926:     free_matrix(prlim,1,nlstate,1,nlstate); /*here or after loop ? */
                   12927:     free_matrix(pmmij,1,nlstate+ndeath,1,nlstate+ndeath);
1.126     brouard  12928:   }  /* mle==-3 arrives here for freeing */
1.227     brouard  12929:   /* endfree:*/
                   12930:   free_matrix(oldms, 1,nlstate+ndeath,1,nlstate+ndeath);
                   12931:   free_matrix(newms, 1,nlstate+ndeath,1,nlstate+ndeath);
                   12932:   free_matrix(savms, 1,nlstate+ndeath,1,nlstate+ndeath);
1.290     brouard  12933:   if(ntv+nqtv>=1)free_ma3x(cotvar,1,maxwav,1,ntv+nqtv,firstobs,lastobs);
                   12934:   if(nqtv>=1)free_ma3x(cotqvar,1,maxwav,1,nqtv,firstobs,lastobs);
                   12935:   if(nqv>=1)free_matrix(coqvar,1,nqv,firstobs,lastobs);
                   12936:   free_matrix(covar,0,NCOVMAX,firstobs,lastobs);
1.227     brouard  12937:   free_matrix(matcov,1,npar,1,npar);
                   12938:   free_matrix(hess,1,npar,1,npar);
                   12939:   /*free_vector(delti,1,npar);*/
                   12940:   free_ma3x(delti3,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel); 
                   12941:   free_matrix(agev,1,maxwav,1,imx);
1.269     brouard  12942:   free_ma3x(paramstart,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel);
1.227     brouard  12943:   free_ma3x(param,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel);
                   12944:   
                   12945:   free_ivector(ncodemax,1,NCOVMAX);
                   12946:   free_ivector(ncodemaxwundef,1,NCOVMAX);
                   12947:   free_ivector(Dummy,-1,NCOVMAX);
                   12948:   free_ivector(Fixed,-1,NCOVMAX);
1.238     brouard  12949:   free_ivector(DummyV,1,NCOVMAX);
                   12950:   free_ivector(FixedV,1,NCOVMAX);
1.227     brouard  12951:   free_ivector(Typevar,-1,NCOVMAX);
                   12952:   free_ivector(Tvar,1,NCOVMAX);
1.234     brouard  12953:   free_ivector(TvarsQ,1,NCOVMAX);
                   12954:   free_ivector(TvarsQind,1,NCOVMAX);
                   12955:   free_ivector(TvarsD,1,NCOVMAX);
                   12956:   free_ivector(TvarsDind,1,NCOVMAX);
1.231     brouard  12957:   free_ivector(TvarFD,1,NCOVMAX);
                   12958:   free_ivector(TvarFDind,1,NCOVMAX);
1.232     brouard  12959:   free_ivector(TvarF,1,NCOVMAX);
                   12960:   free_ivector(TvarFind,1,NCOVMAX);
                   12961:   free_ivector(TvarV,1,NCOVMAX);
                   12962:   free_ivector(TvarVind,1,NCOVMAX);
                   12963:   free_ivector(TvarA,1,NCOVMAX);
                   12964:   free_ivector(TvarAind,1,NCOVMAX);
1.231     brouard  12965:   free_ivector(TvarFQ,1,NCOVMAX);
                   12966:   free_ivector(TvarFQind,1,NCOVMAX);
                   12967:   free_ivector(TvarVD,1,NCOVMAX);
                   12968:   free_ivector(TvarVDind,1,NCOVMAX);
                   12969:   free_ivector(TvarVQ,1,NCOVMAX);
                   12970:   free_ivector(TvarVQind,1,NCOVMAX);
1.230     brouard  12971:   free_ivector(Tvarsel,1,NCOVMAX);
                   12972:   free_vector(Tvalsel,1,NCOVMAX);
1.227     brouard  12973:   free_ivector(Tposprod,1,NCOVMAX);
                   12974:   free_ivector(Tprod,1,NCOVMAX);
                   12975:   free_ivector(Tvaraff,1,NCOVMAX);
                   12976:   free_ivector(invalidvarcomb,1,ncovcombmax);
                   12977:   free_ivector(Tage,1,NCOVMAX);
                   12978:   free_ivector(Tmodelind,1,NCOVMAX);
1.228     brouard  12979:   free_ivector(TmodelInvind,1,NCOVMAX);
                   12980:   free_ivector(TmodelInvQind,1,NCOVMAX);
1.227     brouard  12981:   
                   12982:   free_imatrix(nbcode,0,NCOVMAX,0,NCOVMAX);
                   12983:   /* free_imatrix(codtab,1,100,1,10); */
1.126     brouard  12984:   fflush(fichtm);
                   12985:   fflush(ficgp);
                   12986:   
1.227     brouard  12987:   
1.126     brouard  12988:   if((nberr >0) || (nbwarn>0)){
1.216     brouard  12989:     printf("End of Imach with %d errors and/or %d warnings. Please look at the log file for details.\n",nberr,nbwarn);
                   12990:     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  12991:   }else{
                   12992:     printf("End of Imach\n");
                   12993:     fprintf(ficlog,"End of Imach\n");
                   12994:   }
                   12995:   printf("See log file on %s\n",filelog);
                   12996:   /*  gettimeofday(&end_time, (struct timezone*)0);*/  /* after time */
1.157     brouard  12997:   /*(void) gettimeofday(&end_time,&tzp);*/
                   12998:   rend_time = time(NULL);  
                   12999:   end_time = *localtime(&rend_time);
                   13000:   /* tml = *localtime(&end_time.tm_sec); */
                   13001:   strcpy(strtend,asctime(&end_time));
1.126     brouard  13002:   printf("Local time at start %s\nLocal time at end   %s",strstart, strtend); 
                   13003:   fprintf(ficlog,"Local time at start %s\nLocal time at end   %s\n",strstart, strtend); 
1.157     brouard  13004:   printf("Total time used %s\n", asc_diff_time(rend_time -rstart_time,tmpout));
1.227     brouard  13005:   
1.157     brouard  13006:   printf("Total time was %.0lf Sec.\n", difftime(rend_time,rstart_time));
                   13007:   fprintf(ficlog,"Total time used %s\n", asc_diff_time(rend_time -rstart_time,tmpout));
                   13008:   fprintf(ficlog,"Total time was %.0lf Sec.\n", difftime(rend_time,rstart_time));
1.126     brouard  13009:   /*  printf("Total time was %d uSec.\n", total_usecs);*/
                   13010: /*   if(fileappend(fichtm,optionfilehtm)){ */
                   13011:   fprintf(fichtm,"<br>Local time at start %s<br>Local time at end   %s<br>\n</body></html>",strstart, strtend);
                   13012:   fclose(fichtm);
                   13013:   fprintf(fichtmcov,"<br>Local time at start %s<br>Local time at end   %s<br>\n</body></html>",strstart, strtend);
                   13014:   fclose(fichtmcov);
                   13015:   fclose(ficgp);
                   13016:   fclose(ficlog);
                   13017:   /*------ End -----------*/
1.227     brouard  13018:   
1.281     brouard  13019: 
                   13020: /* Executes gnuplot */
1.227     brouard  13021:   
                   13022:   printf("Before Current directory %s!\n",pathcd);
1.184     brouard  13023: #ifdef WIN32
1.227     brouard  13024:   if (_chdir(pathcd) != 0)
                   13025:     printf("Can't move to directory %s!\n",path);
                   13026:   if(_getcwd(pathcd,MAXLINE) > 0)
1.184     brouard  13027: #else
1.227     brouard  13028:     if(chdir(pathcd) != 0)
                   13029:       printf("Can't move to directory %s!\n", path);
                   13030:   if (getcwd(pathcd, MAXLINE) > 0)
1.184     brouard  13031: #endif 
1.126     brouard  13032:     printf("Current directory %s!\n",pathcd);
                   13033:   /*strcat(plotcmd,CHARSEPARATOR);*/
                   13034:   sprintf(plotcmd,"gnuplot");
1.157     brouard  13035: #ifdef _WIN32
1.126     brouard  13036:   sprintf(plotcmd,"\"%sgnuplot.exe\"",pathimach);
                   13037: #endif
                   13038:   if(!stat(plotcmd,&info)){
1.158     brouard  13039:     printf("Error or gnuplot program not found: '%s'\n",plotcmd);fflush(stdout);
1.126     brouard  13040:     if(!stat(getenv("GNUPLOTBIN"),&info)){
1.158     brouard  13041:       printf("Error or gnuplot program not found: '%s' Environment GNUPLOTBIN not set.\n",plotcmd);fflush(stdout);
1.126     brouard  13042:     }else
                   13043:       strcpy(pplotcmd,plotcmd);
1.157     brouard  13044: #ifdef __unix
1.126     brouard  13045:     strcpy(plotcmd,GNUPLOTPROGRAM);
                   13046:     if(!stat(plotcmd,&info)){
1.158     brouard  13047:       printf("Error gnuplot program not found: '%s'\n",plotcmd);fflush(stdout);
1.126     brouard  13048:     }else
                   13049:       strcpy(pplotcmd,plotcmd);
                   13050: #endif
                   13051:   }else
                   13052:     strcpy(pplotcmd,plotcmd);
                   13053:   
                   13054:   sprintf(plotcmd,"%s %s",pplotcmd, optionfilegnuplot);
1.158     brouard  13055:   printf("Starting graphs with: '%s'\n",plotcmd);fflush(stdout);
1.292     brouard  13056:   strcpy(pplotcmd,plotcmd);
1.227     brouard  13057:   
1.126     brouard  13058:   if((outcmd=system(plotcmd)) != 0){
1.292     brouard  13059:     printf("Error in gnuplot, command might not be in your path: '%s', err=%d\n", plotcmd, outcmd);
1.154     brouard  13060:     printf("\n Trying if gnuplot resides on the same directory that IMaCh\n");
1.152     brouard  13061:     sprintf(plotcmd,"%sgnuplot %s", pathimach, optionfilegnuplot);
1.292     brouard  13062:     if((outcmd=system(plotcmd)) != 0){
1.153     brouard  13063:       printf("\n Still a problem with gnuplot command %s, err=%d\n", plotcmd, outcmd);
1.292     brouard  13064:       strcpy(plotcmd,pplotcmd);
                   13065:     }
1.126     brouard  13066:   }
1.158     brouard  13067:   printf(" Successful, please wait...");
1.126     brouard  13068:   while (z[0] != 'q') {
                   13069:     /* chdir(path); */
1.154     brouard  13070:     printf("\nType e to edit results with your browser, g to graph again and q for exit: ");
1.126     brouard  13071:     scanf("%s",z);
                   13072: /*     if (z[0] == 'c') system("./imach"); */
                   13073:     if (z[0] == 'e') {
1.158     brouard  13074: #ifdef __APPLE__
1.152     brouard  13075:       sprintf(pplotcmd, "open %s", optionfilehtm);
1.157     brouard  13076: #elif __linux
                   13077:       sprintf(pplotcmd, "xdg-open %s", optionfilehtm);
1.153     brouard  13078: #else
1.152     brouard  13079:       sprintf(pplotcmd, "%s", optionfilehtm);
1.153     brouard  13080: #endif
                   13081:       printf("Starting browser with: %s",pplotcmd);fflush(stdout);
                   13082:       system(pplotcmd);
1.126     brouard  13083:     }
                   13084:     else if (z[0] == 'g') system(plotcmd);
                   13085:     else if (z[0] == 'q') exit(0);
                   13086:   }
1.227     brouard  13087: end:
1.126     brouard  13088:   while (z[0] != 'q') {
1.195     brouard  13089:     printf("\nType  q for exiting: "); fflush(stdout);
1.126     brouard  13090:     scanf("%s",z);
                   13091:   }
1.283     brouard  13092:   printf("End\n");
1.282     brouard  13093:   exit(0);
1.126     brouard  13094: }

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