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

1.299   ! brouard     1: /* $Id: imach.c,v 1.298 2019/05/22 18:19:56 brouard Exp $
1.126     brouard     2:   $State: Exp $
1.163     brouard     3:   $Log: imach.c,v $
1.299   ! brouard     4:   Revision 1.298  2019/05/22 18:19:56  brouard
        !             5:   *** empty log message ***
        !             6: 
1.298     brouard     7:   Revision 1.297  2019/05/22 17:56:10  brouard
                      8:   Summary: Fix bug by moving date2dmy and nhstepm which gaefin=-1
                      9: 
1.297     brouard    10:   Revision 1.296  2019/05/20 13:03:18  brouard
                     11:   Summary: Projection syntax simplified
                     12: 
                     13: 
                     14:   We can now start projections, forward or backward, from the mean date
                     15:   of inteviews up to or down to a number of years of projection:
                     16:   prevforecast=1 yearsfproj=15.3 mobil_average=0
                     17:   or
                     18:   prevforecast=1 starting-proj-date=1/1/2007 final-proj-date=12/31/2017 mobil_average=0
                     19:   or
                     20:   prevbackcast=1 yearsbproj=12.3 mobil_average=1
                     21:   or
                     22:   prevbackcast=1 starting-back-date=1/10/1999 final-back-date=1/1/1985 mobil_average=1
                     23: 
1.296     brouard    24:   Revision 1.295  2019/05/18 09:52:50  brouard
                     25:   Summary: doxygen tex bug
                     26: 
1.295     brouard    27:   Revision 1.294  2019/05/16 14:54:33  brouard
                     28:   Summary: There was some wrong lines added
                     29: 
1.294     brouard    30:   Revision 1.293  2019/05/09 15:17:34  brouard
                     31:   *** empty log message ***
                     32: 
1.293     brouard    33:   Revision 1.292  2019/05/09 14:17:20  brouard
                     34:   Summary: Some updates
                     35: 
1.292     brouard    36:   Revision 1.291  2019/05/09 13:44:18  brouard
                     37:   Summary: Before ncovmax
                     38: 
1.291     brouard    39:   Revision 1.290  2019/05/09 13:39:37  brouard
                     40:   Summary: 0.99r18 unlimited number of individuals
                     41: 
                     42:   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.
                     43: 
1.290     brouard    44:   Revision 1.289  2018/12/13 09:16:26  brouard
                     45:   Summary: Bug for young ages (<-30) will be in r17
                     46: 
1.289     brouard    47:   Revision 1.288  2018/05/02 20:58:27  brouard
                     48:   Summary: Some bugs fixed
                     49: 
1.288     brouard    50:   Revision 1.287  2018/05/01 17:57:25  brouard
                     51:   Summary: Bug fixed by providing frequencies only for non missing covariates
                     52: 
1.287     brouard    53:   Revision 1.286  2018/04/27 14:27:04  brouard
                     54:   Summary: some minor bugs
                     55: 
1.286     brouard    56:   Revision 1.285  2018/04/21 21:02:16  brouard
                     57:   Summary: Some bugs fixed, valgrind tested
                     58: 
1.285     brouard    59:   Revision 1.284  2018/04/20 05:22:13  brouard
                     60:   Summary: Computing mean and stdeviation of fixed quantitative variables
                     61: 
1.284     brouard    62:   Revision 1.283  2018/04/19 14:49:16  brouard
                     63:   Summary: Some minor bugs fixed
                     64: 
1.283     brouard    65:   Revision 1.282  2018/02/27 22:50:02  brouard
                     66:   *** empty log message ***
                     67: 
1.282     brouard    68:   Revision 1.281  2018/02/27 19:25:23  brouard
                     69:   Summary: Adding second argument for quitting
                     70: 
1.281     brouard    71:   Revision 1.280  2018/02/21 07:58:13  brouard
                     72:   Summary: 0.99r15
                     73: 
                     74:   New Makefile with recent VirtualBox 5.26. Bug in sqrt negatve in imach.c
                     75: 
1.280     brouard    76:   Revision 1.279  2017/07/20 13:35:01  brouard
                     77:   Summary: temporary working
                     78: 
1.279     brouard    79:   Revision 1.278  2017/07/19 14:09:02  brouard
                     80:   Summary: Bug for mobil_average=0 and prevforecast fixed(?)
                     81: 
1.278     brouard    82:   Revision 1.277  2017/07/17 08:53:49  brouard
                     83:   Summary: BOM files can be read now
                     84: 
1.277     brouard    85:   Revision 1.276  2017/06/30 15:48:31  brouard
                     86:   Summary: Graphs improvements
                     87: 
1.276     brouard    88:   Revision 1.275  2017/06/30 13:39:33  brouard
                     89:   Summary: Saito's color
                     90: 
1.275     brouard    91:   Revision 1.274  2017/06/29 09:47:08  brouard
                     92:   Summary: Version 0.99r14
                     93: 
1.274     brouard    94:   Revision 1.273  2017/06/27 11:06:02  brouard
                     95:   Summary: More documentation on projections
                     96: 
1.273     brouard    97:   Revision 1.272  2017/06/27 10:22:40  brouard
                     98:   Summary: Color of backprojection changed from 6 to 5(yellow)
                     99: 
1.272     brouard   100:   Revision 1.271  2017/06/27 10:17:50  brouard
                    101:   Summary: Some bug with rint
                    102: 
1.271     brouard   103:   Revision 1.270  2017/05/24 05:45:29  brouard
                    104:   *** empty log message ***
                    105: 
1.270     brouard   106:   Revision 1.269  2017/05/23 08:39:25  brouard
                    107:   Summary: Code into subroutine, cleanings
                    108: 
1.269     brouard   109:   Revision 1.268  2017/05/18 20:09:32  brouard
                    110:   Summary: backprojection and confidence intervals of backprevalence
                    111: 
1.268     brouard   112:   Revision 1.267  2017/05/13 10:25:05  brouard
                    113:   Summary: temporary save for backprojection
                    114: 
1.267     brouard   115:   Revision 1.266  2017/05/13 07:26:12  brouard
                    116:   Summary: Version 0.99r13 (improvements and bugs fixed)
                    117: 
1.266     brouard   118:   Revision 1.265  2017/04/26 16:22:11  brouard
                    119:   Summary: imach 0.99r13 Some bugs fixed
                    120: 
1.265     brouard   121:   Revision 1.264  2017/04/26 06:01:29  brouard
                    122:   Summary: Labels in graphs
                    123: 
1.264     brouard   124:   Revision 1.263  2017/04/24 15:23:15  brouard
                    125:   Summary: to save
                    126: 
1.263     brouard   127:   Revision 1.262  2017/04/18 16:48:12  brouard
                    128:   *** empty log message ***
                    129: 
1.262     brouard   130:   Revision 1.261  2017/04/05 10:14:09  brouard
                    131:   Summary: Bug in E_ as well as in T_ fixed nres-1 vs k1-1
                    132: 
1.261     brouard   133:   Revision 1.260  2017/04/04 17:46:59  brouard
                    134:   Summary: Gnuplot indexations fixed (humm)
                    135: 
1.260     brouard   136:   Revision 1.259  2017/04/04 13:01:16  brouard
                    137:   Summary: Some errors to warnings only if date of death is unknown but status is death we could set to pi3
                    138: 
1.259     brouard   139:   Revision 1.258  2017/04/03 10:17:47  brouard
                    140:   Summary: Version 0.99r12
                    141: 
                    142:   Some cleanings, conformed with updated documentation.
                    143: 
1.258     brouard   144:   Revision 1.257  2017/03/29 16:53:30  brouard
                    145:   Summary: Temp
                    146: 
1.257     brouard   147:   Revision 1.256  2017/03/27 05:50:23  brouard
                    148:   Summary: Temporary
                    149: 
1.256     brouard   150:   Revision 1.255  2017/03/08 16:02:28  brouard
                    151:   Summary: IMaCh version 0.99r10 bugs in gnuplot fixed
                    152: 
1.255     brouard   153:   Revision 1.254  2017/03/08 07:13:00  brouard
                    154:   Summary: Fixing data parameter line
                    155: 
1.254     brouard   156:   Revision 1.253  2016/12/15 11:59:41  brouard
                    157:   Summary: 0.99 in progress
                    158: 
1.253     brouard   159:   Revision 1.252  2016/09/15 21:15:37  brouard
                    160:   *** empty log message ***
                    161: 
1.252     brouard   162:   Revision 1.251  2016/09/15 15:01:13  brouard
                    163:   Summary: not working
                    164: 
1.251     brouard   165:   Revision 1.250  2016/09/08 16:07:27  brouard
                    166:   Summary: continue
                    167: 
1.250     brouard   168:   Revision 1.249  2016/09/07 17:14:18  brouard
                    169:   Summary: Starting values from frequencies
                    170: 
1.249     brouard   171:   Revision 1.248  2016/09/07 14:10:18  brouard
                    172:   *** empty log message ***
                    173: 
1.248     brouard   174:   Revision 1.247  2016/09/02 11:11:21  brouard
                    175:   *** empty log message ***
                    176: 
1.247     brouard   177:   Revision 1.246  2016/09/02 08:49:22  brouard
                    178:   *** empty log message ***
                    179: 
1.246     brouard   180:   Revision 1.245  2016/09/02 07:25:01  brouard
                    181:   *** empty log message ***
                    182: 
1.245     brouard   183:   Revision 1.244  2016/09/02 07:17:34  brouard
                    184:   *** empty log message ***
                    185: 
1.244     brouard   186:   Revision 1.243  2016/09/02 06:45:35  brouard
                    187:   *** empty log message ***
                    188: 
1.243     brouard   189:   Revision 1.242  2016/08/30 15:01:20  brouard
                    190:   Summary: Fixing a lots
                    191: 
1.242     brouard   192:   Revision 1.241  2016/08/29 17:17:25  brouard
                    193:   Summary: gnuplot problem in Back projection to fix
                    194: 
1.241     brouard   195:   Revision 1.240  2016/08/29 07:53:18  brouard
                    196:   Summary: Better
                    197: 
1.240     brouard   198:   Revision 1.239  2016/08/26 15:51:03  brouard
                    199:   Summary: Improvement in Powell output in order to copy and paste
                    200: 
                    201:   Author:
                    202: 
1.239     brouard   203:   Revision 1.238  2016/08/26 14:23:35  brouard
                    204:   Summary: Starting tests of 0.99
                    205: 
1.238     brouard   206:   Revision 1.237  2016/08/26 09:20:19  brouard
                    207:   Summary: to valgrind
                    208: 
1.237     brouard   209:   Revision 1.236  2016/08/25 10:50:18  brouard
                    210:   *** empty log message ***
                    211: 
1.236     brouard   212:   Revision 1.235  2016/08/25 06:59:23  brouard
                    213:   *** empty log message ***
                    214: 
1.235     brouard   215:   Revision 1.234  2016/08/23 16:51:20  brouard
                    216:   *** empty log message ***
                    217: 
1.234     brouard   218:   Revision 1.233  2016/08/23 07:40:50  brouard
                    219:   Summary: not working
                    220: 
1.233     brouard   221:   Revision 1.232  2016/08/22 14:20:21  brouard
                    222:   Summary: not working
                    223: 
1.232     brouard   224:   Revision 1.231  2016/08/22 07:17:15  brouard
                    225:   Summary: not working
                    226: 
1.231     brouard   227:   Revision 1.230  2016/08/22 06:55:53  brouard
                    228:   Summary: Not working
                    229: 
1.230     brouard   230:   Revision 1.229  2016/07/23 09:45:53  brouard
                    231:   Summary: Completing for func too
                    232: 
1.229     brouard   233:   Revision 1.228  2016/07/22 17:45:30  brouard
                    234:   Summary: Fixing some arrays, still debugging
                    235: 
1.227     brouard   236:   Revision 1.226  2016/07/12 18:42:34  brouard
                    237:   Summary: temp
                    238: 
1.226     brouard   239:   Revision 1.225  2016/07/12 08:40:03  brouard
                    240:   Summary: saving but not running
                    241: 
1.225     brouard   242:   Revision 1.224  2016/07/01 13:16:01  brouard
                    243:   Summary: Fixes
                    244: 
1.224     brouard   245:   Revision 1.223  2016/02/19 09:23:35  brouard
                    246:   Summary: temporary
                    247: 
1.223     brouard   248:   Revision 1.222  2016/02/17 08:14:50  brouard
                    249:   Summary: Probably last 0.98 stable version 0.98r6
                    250: 
1.222     brouard   251:   Revision 1.221  2016/02/15 23:35:36  brouard
                    252:   Summary: minor bug
                    253: 
1.220     brouard   254:   Revision 1.219  2016/02/15 00:48:12  brouard
                    255:   *** empty log message ***
                    256: 
1.219     brouard   257:   Revision 1.218  2016/02/12 11:29:23  brouard
                    258:   Summary: 0.99 Back projections
                    259: 
1.218     brouard   260:   Revision 1.217  2015/12/23 17:18:31  brouard
                    261:   Summary: Experimental backcast
                    262: 
1.217     brouard   263:   Revision 1.216  2015/12/18 17:32:11  brouard
                    264:   Summary: 0.98r4 Warning and status=-2
                    265: 
                    266:   Version 0.98r4 is now:
                    267:    - displaying an error when status is -1, date of interview unknown and date of death known;
                    268:    - permitting a status -2 when the vital status is unknown at a known date of right truncation.
                    269:   Older changes concerning s=-2, dating from 2005 have been supersed.
                    270: 
1.216     brouard   271:   Revision 1.215  2015/12/16 08:52:24  brouard
                    272:   Summary: 0.98r4 working
                    273: 
1.215     brouard   274:   Revision 1.214  2015/12/16 06:57:54  brouard
                    275:   Summary: temporary not working
                    276: 
1.214     brouard   277:   Revision 1.213  2015/12/11 18:22:17  brouard
                    278:   Summary: 0.98r4
                    279: 
1.213     brouard   280:   Revision 1.212  2015/11/21 12:47:24  brouard
                    281:   Summary: minor typo
                    282: 
1.212     brouard   283:   Revision 1.211  2015/11/21 12:41:11  brouard
                    284:   Summary: 0.98r3 with some graph of projected cross-sectional
                    285: 
                    286:   Author: Nicolas Brouard
                    287: 
1.211     brouard   288:   Revision 1.210  2015/11/18 17:41:20  brouard
1.252     brouard   289:   Summary: Start working on projected prevalences  Revision 1.209  2015/11/17 22:12:03  brouard
1.210     brouard   290:   Summary: Adding ftolpl parameter
                    291:   Author: N Brouard
                    292: 
                    293:   We had difficulties to get smoothed confidence intervals. It was due
                    294:   to the period prevalence which wasn't computed accurately. The inner
                    295:   parameter ftolpl is now an outer parameter of the .imach parameter
                    296:   file after estepm. If ftolpl is small 1.e-4 and estepm too,
                    297:   computation are long.
                    298: 
1.209     brouard   299:   Revision 1.208  2015/11/17 14:31:57  brouard
                    300:   Summary: temporary
                    301: 
1.208     brouard   302:   Revision 1.207  2015/10/27 17:36:57  brouard
                    303:   *** empty log message ***
                    304: 
1.207     brouard   305:   Revision 1.206  2015/10/24 07:14:11  brouard
                    306:   *** empty log message ***
                    307: 
1.206     brouard   308:   Revision 1.205  2015/10/23 15:50:53  brouard
                    309:   Summary: 0.98r3 some clarification for graphs on likelihood contributions
                    310: 
1.205     brouard   311:   Revision 1.204  2015/10/01 16:20:26  brouard
                    312:   Summary: Some new graphs of contribution to likelihood
                    313: 
1.204     brouard   314:   Revision 1.203  2015/09/30 17:45:14  brouard
                    315:   Summary: looking at better estimation of the hessian
                    316: 
                    317:   Also a better criteria for convergence to the period prevalence And
                    318:   therefore adding the number of years needed to converge. (The
                    319:   prevalence in any alive state shold sum to one
                    320: 
1.203     brouard   321:   Revision 1.202  2015/09/22 19:45:16  brouard
                    322:   Summary: Adding some overall graph on contribution to likelihood. Might change
                    323: 
1.202     brouard   324:   Revision 1.201  2015/09/15 17:34:58  brouard
                    325:   Summary: 0.98r0
                    326: 
                    327:   - Some new graphs like suvival functions
                    328:   - Some bugs fixed like model=1+age+V2.
                    329: 
1.201     brouard   330:   Revision 1.200  2015/09/09 16:53:55  brouard
                    331:   Summary: Big bug thanks to Flavia
                    332: 
                    333:   Even model=1+age+V2. did not work anymore
                    334: 
1.200     brouard   335:   Revision 1.199  2015/09/07 14:09:23  brouard
                    336:   Summary: 0.98q6 changing default small png format for graph to vectorized svg.
                    337: 
1.199     brouard   338:   Revision 1.198  2015/09/03 07:14:39  brouard
                    339:   Summary: 0.98q5 Flavia
                    340: 
1.198     brouard   341:   Revision 1.197  2015/09/01 18:24:39  brouard
                    342:   *** empty log message ***
                    343: 
1.197     brouard   344:   Revision 1.196  2015/08/18 23:17:52  brouard
                    345:   Summary: 0.98q5
                    346: 
1.196     brouard   347:   Revision 1.195  2015/08/18 16:28:39  brouard
                    348:   Summary: Adding a hack for testing purpose
                    349: 
                    350:   After reading the title, ftol and model lines, if the comment line has
                    351:   a q, starting with #q, the answer at the end of the run is quit. It
                    352:   permits to run test files in batch with ctest. The former workaround was
                    353:   $ echo q | imach foo.imach
                    354: 
1.195     brouard   355:   Revision 1.194  2015/08/18 13:32:00  brouard
                    356:   Summary:  Adding error when the covariance matrix doesn't contain the exact number of lines required by the model line.
                    357: 
1.194     brouard   358:   Revision 1.193  2015/08/04 07:17:42  brouard
                    359:   Summary: 0.98q4
                    360: 
1.193     brouard   361:   Revision 1.192  2015/07/16 16:49:02  brouard
                    362:   Summary: Fixing some outputs
                    363: 
1.192     brouard   364:   Revision 1.191  2015/07/14 10:00:33  brouard
                    365:   Summary: Some fixes
                    366: 
1.191     brouard   367:   Revision 1.190  2015/05/05 08:51:13  brouard
                    368:   Summary: Adding digits in output parameters (7 digits instead of 6)
                    369: 
                    370:   Fix 1+age+.
                    371: 
1.190     brouard   372:   Revision 1.189  2015/04/30 14:45:16  brouard
                    373:   Summary: 0.98q2
                    374: 
1.189     brouard   375:   Revision 1.188  2015/04/30 08:27:53  brouard
                    376:   *** empty log message ***
                    377: 
1.188     brouard   378:   Revision 1.187  2015/04/29 09:11:15  brouard
                    379:   *** empty log message ***
                    380: 
1.187     brouard   381:   Revision 1.186  2015/04/23 12:01:52  brouard
                    382:   Summary: V1*age is working now, version 0.98q1
                    383: 
                    384:   Some codes had been disabled in order to simplify and Vn*age was
                    385:   working in the optimization phase, ie, giving correct MLE parameters,
                    386:   but, as usual, outputs were not correct and program core dumped.
                    387: 
1.186     brouard   388:   Revision 1.185  2015/03/11 13:26:42  brouard
                    389:   Summary: Inclusion of compile and links command line for Intel Compiler
                    390: 
1.185     brouard   391:   Revision 1.184  2015/03/11 11:52:39  brouard
                    392:   Summary: Back from Windows 8. Intel Compiler
                    393: 
1.184     brouard   394:   Revision 1.183  2015/03/10 20:34:32  brouard
                    395:   Summary: 0.98q0, trying with directest, mnbrak fixed
                    396: 
                    397:   We use directest instead of original Powell test; probably no
                    398:   incidence on the results, but better justifications;
                    399:   We fixed Numerical Recipes mnbrak routine which was wrong and gave
                    400:   wrong results.
                    401: 
1.183     brouard   402:   Revision 1.182  2015/02/12 08:19:57  brouard
                    403:   Summary: Trying to keep directest which seems simpler and more general
                    404:   Author: Nicolas Brouard
                    405: 
1.182     brouard   406:   Revision 1.181  2015/02/11 23:22:24  brouard
                    407:   Summary: Comments on Powell added
                    408: 
                    409:   Author:
                    410: 
1.181     brouard   411:   Revision 1.180  2015/02/11 17:33:45  brouard
                    412:   Summary: Finishing move from main to function (hpijx and prevalence_limit)
                    413: 
1.180     brouard   414:   Revision 1.179  2015/01/04 09:57:06  brouard
                    415:   Summary: back to OS/X
                    416: 
1.179     brouard   417:   Revision 1.178  2015/01/04 09:35:48  brouard
                    418:   *** empty log message ***
                    419: 
1.178     brouard   420:   Revision 1.177  2015/01/03 18:40:56  brouard
                    421:   Summary: Still testing ilc32 on OSX
                    422: 
1.177     brouard   423:   Revision 1.176  2015/01/03 16:45:04  brouard
                    424:   *** empty log message ***
                    425: 
1.176     brouard   426:   Revision 1.175  2015/01/03 16:33:42  brouard
                    427:   *** empty log message ***
                    428: 
1.175     brouard   429:   Revision 1.174  2015/01/03 16:15:49  brouard
                    430:   Summary: Still in cross-compilation
                    431: 
1.174     brouard   432:   Revision 1.173  2015/01/03 12:06:26  brouard
                    433:   Summary: trying to detect cross-compilation
                    434: 
1.173     brouard   435:   Revision 1.172  2014/12/27 12:07:47  brouard
                    436:   Summary: Back from Visual Studio and Intel, options for compiling for Windows XP
                    437: 
1.172     brouard   438:   Revision 1.171  2014/12/23 13:26:59  brouard
                    439:   Summary: Back from Visual C
                    440: 
                    441:   Still problem with utsname.h on Windows
                    442: 
1.171     brouard   443:   Revision 1.170  2014/12/23 11:17:12  brouard
                    444:   Summary: Cleaning some \%% back to %%
                    445: 
                    446:   The escape was mandatory for a specific compiler (which one?), but too many warnings.
                    447: 
1.170     brouard   448:   Revision 1.169  2014/12/22 23:08:31  brouard
                    449:   Summary: 0.98p
                    450: 
                    451:   Outputs some informations on compiler used, OS etc. Testing on different platforms.
                    452: 
1.169     brouard   453:   Revision 1.168  2014/12/22 15:17:42  brouard
1.170     brouard   454:   Summary: update
1.169     brouard   455: 
1.168     brouard   456:   Revision 1.167  2014/12/22 13:50:56  brouard
                    457:   Summary: Testing uname and compiler version and if compiled 32 or 64
                    458: 
                    459:   Testing on Linux 64
                    460: 
1.167     brouard   461:   Revision 1.166  2014/12/22 11:40:47  brouard
                    462:   *** empty log message ***
                    463: 
1.166     brouard   464:   Revision 1.165  2014/12/16 11:20:36  brouard
                    465:   Summary: After compiling on Visual C
                    466: 
                    467:   * imach.c (Module): Merging 1.61 to 1.162
                    468: 
1.165     brouard   469:   Revision 1.164  2014/12/16 10:52:11  brouard
                    470:   Summary: Merging with Visual C after suppressing some warnings for unused variables. Also fixing Saito's bug 0.98Xn
                    471: 
                    472:   * imach.c (Module): Merging 1.61 to 1.162
                    473: 
1.164     brouard   474:   Revision 1.163  2014/12/16 10:30:11  brouard
                    475:   * imach.c (Module): Merging 1.61 to 1.162
                    476: 
1.163     brouard   477:   Revision 1.162  2014/09/25 11:43:39  brouard
                    478:   Summary: temporary backup 0.99!
                    479: 
1.162     brouard   480:   Revision 1.1  2014/09/16 11:06:58  brouard
                    481:   Summary: With some code (wrong) for nlopt
                    482: 
                    483:   Author:
                    484: 
                    485:   Revision 1.161  2014/09/15 20:41:41  brouard
                    486:   Summary: Problem with macro SQR on Intel compiler
                    487: 
1.161     brouard   488:   Revision 1.160  2014/09/02 09:24:05  brouard
                    489:   *** empty log message ***
                    490: 
1.160     brouard   491:   Revision 1.159  2014/09/01 10:34:10  brouard
                    492:   Summary: WIN32
                    493:   Author: Brouard
                    494: 
1.159     brouard   495:   Revision 1.158  2014/08/27 17:11:51  brouard
                    496:   *** empty log message ***
                    497: 
1.158     brouard   498:   Revision 1.157  2014/08/27 16:26:55  brouard
                    499:   Summary: Preparing windows Visual studio version
                    500:   Author: Brouard
                    501: 
                    502:   In order to compile on Visual studio, time.h is now correct and time_t
                    503:   and tm struct should be used. difftime should be used but sometimes I
                    504:   just make the differences in raw time format (time(&now).
                    505:   Trying to suppress #ifdef LINUX
                    506:   Add xdg-open for __linux in order to open default browser.
                    507: 
1.157     brouard   508:   Revision 1.156  2014/08/25 20:10:10  brouard
                    509:   *** empty log message ***
                    510: 
1.156     brouard   511:   Revision 1.155  2014/08/25 18:32:34  brouard
                    512:   Summary: New compile, minor changes
                    513:   Author: Brouard
                    514: 
1.155     brouard   515:   Revision 1.154  2014/06/20 17:32:08  brouard
                    516:   Summary: Outputs now all graphs of convergence to period prevalence
                    517: 
1.154     brouard   518:   Revision 1.153  2014/06/20 16:45:46  brouard
                    519:   Summary: If 3 live state, convergence to period prevalence on same graph
                    520:   Author: Brouard
                    521: 
1.153     brouard   522:   Revision 1.152  2014/06/18 17:54:09  brouard
                    523:   Summary: open browser, use gnuplot on same dir than imach if not found in the path
                    524: 
1.152     brouard   525:   Revision 1.151  2014/06/18 16:43:30  brouard
                    526:   *** empty log message ***
                    527: 
1.151     brouard   528:   Revision 1.150  2014/06/18 16:42:35  brouard
                    529:   Summary: If gnuplot is not in the path try on same directory than imach binary (OSX)
                    530:   Author: brouard
                    531: 
1.150     brouard   532:   Revision 1.149  2014/06/18 15:51:14  brouard
                    533:   Summary: Some fixes in parameter files errors
                    534:   Author: Nicolas Brouard
                    535: 
1.149     brouard   536:   Revision 1.148  2014/06/17 17:38:48  brouard
                    537:   Summary: Nothing new
                    538:   Author: Brouard
                    539: 
                    540:   Just a new packaging for OS/X version 0.98nS
                    541: 
1.148     brouard   542:   Revision 1.147  2014/06/16 10:33:11  brouard
                    543:   *** empty log message ***
                    544: 
1.147     brouard   545:   Revision 1.146  2014/06/16 10:20:28  brouard
                    546:   Summary: Merge
                    547:   Author: Brouard
                    548: 
                    549:   Merge, before building revised version.
                    550: 
1.146     brouard   551:   Revision 1.145  2014/06/10 21:23:15  brouard
                    552:   Summary: Debugging with valgrind
                    553:   Author: Nicolas Brouard
                    554: 
                    555:   Lot of changes in order to output the results with some covariates
                    556:   After the Edimburgh REVES conference 2014, it seems mandatory to
                    557:   improve the code.
                    558:   No more memory valgrind error but a lot has to be done in order to
                    559:   continue the work of splitting the code into subroutines.
                    560:   Also, decodemodel has been improved. Tricode is still not
                    561:   optimal. nbcode should be improved. Documentation has been added in
                    562:   the source code.
                    563: 
1.144     brouard   564:   Revision 1.143  2014/01/26 09:45:38  brouard
                    565:   Summary: Version 0.98nR (to be improved, but gives same optimization results as 0.98k. Nice, promising
                    566: 
                    567:   * imach.c (Module): Trying to merge old staffs together while being at Tokyo. Not tested...
                    568:   (Module): Version 0.98nR Running ok, but output format still only works for three covariates.
                    569: 
1.143     brouard   570:   Revision 1.142  2014/01/26 03:57:36  brouard
                    571:   Summary: gnuplot changed plot w l 1 has to be changed to plot w l lt 2
                    572: 
                    573:   * imach.c (Module): Trying to merge old staffs together while being at Tokyo. Not tested...
                    574: 
1.142     brouard   575:   Revision 1.141  2014/01/26 02:42:01  brouard
                    576:   * imach.c (Module): Trying to merge old staffs together while being at Tokyo. Not tested...
                    577: 
1.141     brouard   578:   Revision 1.140  2011/09/02 10:37:54  brouard
                    579:   Summary: times.h is ok with mingw32 now.
                    580: 
1.140     brouard   581:   Revision 1.139  2010/06/14 07:50:17  brouard
                    582:   After the theft of my laptop, I probably lost some lines of codes which were not uploaded to the CVS tree.
                    583:   I remember having already fixed agemin agemax which are pointers now but not cvs saved.
                    584: 
1.139     brouard   585:   Revision 1.138  2010/04/30 18:19:40  brouard
                    586:   *** empty log message ***
                    587: 
1.138     brouard   588:   Revision 1.137  2010/04/29 18:11:38  brouard
                    589:   (Module): Checking covariates for more complex models
                    590:   than V1+V2. A lot of change to be done. Unstable.
                    591: 
1.137     brouard   592:   Revision 1.136  2010/04/26 20:30:53  brouard
                    593:   (Module): merging some libgsl code. Fixing computation
                    594:   of likelione (using inter/intrapolation if mle = 0) in order to
                    595:   get same likelihood as if mle=1.
                    596:   Some cleaning of code and comments added.
                    597: 
1.136     brouard   598:   Revision 1.135  2009/10/29 15:33:14  brouard
                    599:   (Module): Now imach stops if date of birth, at least year of birth, is not given. Some cleaning of the code.
                    600: 
1.135     brouard   601:   Revision 1.134  2009/10/29 13:18:53  brouard
                    602:   (Module): Now imach stops if date of birth, at least year of birth, is not given. Some cleaning of the code.
                    603: 
1.134     brouard   604:   Revision 1.133  2009/07/06 10:21:25  brouard
                    605:   just nforces
                    606: 
1.133     brouard   607:   Revision 1.132  2009/07/06 08:22:05  brouard
                    608:   Many tings
                    609: 
1.132     brouard   610:   Revision 1.131  2009/06/20 16:22:47  brouard
                    611:   Some dimensions resccaled
                    612: 
1.131     brouard   613:   Revision 1.130  2009/05/26 06:44:34  brouard
                    614:   (Module): Max Covariate is now set to 20 instead of 8. A
                    615:   lot of cleaning with variables initialized to 0. Trying to make
                    616:   V2+V3*age+V1+V4 strb=V3*age+V1+V4 working better.
                    617: 
1.130     brouard   618:   Revision 1.129  2007/08/31 13:49:27  lievre
                    619:   Modification of the way of exiting when the covariate is not binary in order to see on the window the error message before exiting
                    620: 
1.129     lievre    621:   Revision 1.128  2006/06/30 13:02:05  brouard
                    622:   (Module): Clarifications on computing e.j
                    623: 
1.128     brouard   624:   Revision 1.127  2006/04/28 18:11:50  brouard
                    625:   (Module): Yes the sum of survivors was wrong since
                    626:   imach-114 because nhstepm was no more computed in the age
                    627:   loop. Now we define nhstepma in the age loop.
                    628:   (Module): In order to speed up (in case of numerous covariates) we
                    629:   compute health expectancies (without variances) in a first step
                    630:   and then all the health expectancies with variances or standard
                    631:   deviation (needs data from the Hessian matrices) which slows the
                    632:   computation.
                    633:   In the future we should be able to stop the program is only health
                    634:   expectancies and graph are needed without standard deviations.
                    635: 
1.127     brouard   636:   Revision 1.126  2006/04/28 17:23:28  brouard
                    637:   (Module): Yes the sum of survivors was wrong since
                    638:   imach-114 because nhstepm was no more computed in the age
                    639:   loop. Now we define nhstepma in the age loop.
                    640:   Version 0.98h
                    641: 
1.126     brouard   642:   Revision 1.125  2006/04/04 15:20:31  lievre
                    643:   Errors in calculation of health expectancies. Age was not initialized.
                    644:   Forecasting file added.
                    645: 
                    646:   Revision 1.124  2006/03/22 17:13:53  lievre
                    647:   Parameters are printed with %lf instead of %f (more numbers after the comma).
                    648:   The log-likelihood is printed in the log file
                    649: 
                    650:   Revision 1.123  2006/03/20 10:52:43  brouard
                    651:   * imach.c (Module): <title> changed, corresponds to .htm file
                    652:   name. <head> headers where missing.
                    653: 
                    654:   * imach.c (Module): Weights can have a decimal point as for
                    655:   English (a comma might work with a correct LC_NUMERIC environment,
                    656:   otherwise the weight is truncated).
                    657:   Modification of warning when the covariates values are not 0 or
                    658:   1.
                    659:   Version 0.98g
                    660: 
                    661:   Revision 1.122  2006/03/20 09:45:41  brouard
                    662:   (Module): Weights can have a decimal point as for
                    663:   English (a comma might work with a correct LC_NUMERIC environment,
                    664:   otherwise the weight is truncated).
                    665:   Modification of warning when the covariates values are not 0 or
                    666:   1.
                    667:   Version 0.98g
                    668: 
                    669:   Revision 1.121  2006/03/16 17:45:01  lievre
                    670:   * imach.c (Module): Comments concerning covariates added
                    671: 
                    672:   * imach.c (Module): refinements in the computation of lli if
                    673:   status=-2 in order to have more reliable computation if stepm is
                    674:   not 1 month. Version 0.98f
                    675: 
                    676:   Revision 1.120  2006/03/16 15:10:38  lievre
                    677:   (Module): refinements in the computation of lli if
                    678:   status=-2 in order to have more reliable computation if stepm is
                    679:   not 1 month. Version 0.98f
                    680: 
                    681:   Revision 1.119  2006/03/15 17:42:26  brouard
                    682:   (Module): Bug if status = -2, the loglikelihood was
                    683:   computed as likelihood omitting the logarithm. Version O.98e
                    684: 
                    685:   Revision 1.118  2006/03/14 18:20:07  brouard
                    686:   (Module): varevsij Comments added explaining the second
                    687:   table of variances if popbased=1 .
                    688:   (Module): Covariances of eij, ekl added, graphs fixed, new html link.
                    689:   (Module): Function pstamp added
                    690:   (Module): Version 0.98d
                    691: 
                    692:   Revision 1.117  2006/03/14 17:16:22  brouard
                    693:   (Module): varevsij Comments added explaining the second
                    694:   table of variances if popbased=1 .
                    695:   (Module): Covariances of eij, ekl added, graphs fixed, new html link.
                    696:   (Module): Function pstamp added
                    697:   (Module): Version 0.98d
                    698: 
                    699:   Revision 1.116  2006/03/06 10:29:27  brouard
                    700:   (Module): Variance-covariance wrong links and
                    701:   varian-covariance of ej. is needed (Saito).
                    702: 
                    703:   Revision 1.115  2006/02/27 12:17:45  brouard
                    704:   (Module): One freematrix added in mlikeli! 0.98c
                    705: 
                    706:   Revision 1.114  2006/02/26 12:57:58  brouard
                    707:   (Module): Some improvements in processing parameter
                    708:   filename with strsep.
                    709: 
                    710:   Revision 1.113  2006/02/24 14:20:24  brouard
                    711:   (Module): Memory leaks checks with valgrind and:
                    712:   datafile was not closed, some imatrix were not freed and on matrix
                    713:   allocation too.
                    714: 
                    715:   Revision 1.112  2006/01/30 09:55:26  brouard
                    716:   (Module): Back to gnuplot.exe instead of wgnuplot.exe
                    717: 
                    718:   Revision 1.111  2006/01/25 20:38:18  brouard
                    719:   (Module): Lots of cleaning and bugs added (Gompertz)
                    720:   (Module): Comments can be added in data file. Missing date values
                    721:   can be a simple dot '.'.
                    722: 
                    723:   Revision 1.110  2006/01/25 00:51:50  brouard
                    724:   (Module): Lots of cleaning and bugs added (Gompertz)
                    725: 
                    726:   Revision 1.109  2006/01/24 19:37:15  brouard
                    727:   (Module): Comments (lines starting with a #) are allowed in data.
                    728: 
                    729:   Revision 1.108  2006/01/19 18:05:42  lievre
                    730:   Gnuplot problem appeared...
                    731:   To be fixed
                    732: 
                    733:   Revision 1.107  2006/01/19 16:20:37  brouard
                    734:   Test existence of gnuplot in imach path
                    735: 
                    736:   Revision 1.106  2006/01/19 13:24:36  brouard
                    737:   Some cleaning and links added in html output
                    738: 
                    739:   Revision 1.105  2006/01/05 20:23:19  lievre
                    740:   *** empty log message ***
                    741: 
                    742:   Revision 1.104  2005/09/30 16:11:43  lievre
                    743:   (Module): sump fixed, loop imx fixed, and simplifications.
                    744:   (Module): If the status is missing at the last wave but we know
                    745:   that the person is alive, then we can code his/her status as -2
                    746:   (instead of missing=-1 in earlier versions) and his/her
                    747:   contributions to the likelihood is 1 - Prob of dying from last
                    748:   health status (= 1-p13= p11+p12 in the easiest case of somebody in
                    749:   the healthy state at last known wave). Version is 0.98
                    750: 
                    751:   Revision 1.103  2005/09/30 15:54:49  lievre
                    752:   (Module): sump fixed, loop imx fixed, and simplifications.
                    753: 
                    754:   Revision 1.102  2004/09/15 17:31:30  brouard
                    755:   Add the possibility to read data file including tab characters.
                    756: 
                    757:   Revision 1.101  2004/09/15 10:38:38  brouard
                    758:   Fix on curr_time
                    759: 
                    760:   Revision 1.100  2004/07/12 18:29:06  brouard
                    761:   Add version for Mac OS X. Just define UNIX in Makefile
                    762: 
                    763:   Revision 1.99  2004/06/05 08:57:40  brouard
                    764:   *** empty log message ***
                    765: 
                    766:   Revision 1.98  2004/05/16 15:05:56  brouard
                    767:   New version 0.97 . First attempt to estimate force of mortality
                    768:   directly from the data i.e. without the need of knowing the health
                    769:   state at each age, but using a Gompertz model: log u =a + b*age .
                    770:   This is the basic analysis of mortality and should be done before any
                    771:   other analysis, in order to test if the mortality estimated from the
                    772:   cross-longitudinal survey is different from the mortality estimated
                    773:   from other sources like vital statistic data.
                    774: 
                    775:   The same imach parameter file can be used but the option for mle should be -3.
                    776: 
1.133     brouard   777:   Agnès, who wrote this part of the code, tried to keep most of the
1.126     brouard   778:   former routines in order to include the new code within the former code.
                    779: 
                    780:   The output is very simple: only an estimate of the intercept and of
                    781:   the slope with 95% confident intervals.
                    782: 
                    783:   Current limitations:
                    784:   A) Even if you enter covariates, i.e. with the
                    785:   model= V1+V2 equation for example, the programm does only estimate a unique global model without covariates.
                    786:   B) There is no computation of Life Expectancy nor Life Table.
                    787: 
                    788:   Revision 1.97  2004/02/20 13:25:42  lievre
                    789:   Version 0.96d. Population forecasting command line is (temporarily)
                    790:   suppressed.
                    791: 
                    792:   Revision 1.96  2003/07/15 15:38:55  brouard
                    793:   * imach.c (Repository): Errors in subdirf, 2, 3 while printing tmpout is
                    794:   rewritten within the same printf. Workaround: many printfs.
                    795: 
                    796:   Revision 1.95  2003/07/08 07:54:34  brouard
                    797:   * imach.c (Repository):
                    798:   (Repository): Using imachwizard code to output a more meaningful covariance
                    799:   matrix (cov(a12,c31) instead of numbers.
                    800: 
                    801:   Revision 1.94  2003/06/27 13:00:02  brouard
                    802:   Just cleaning
                    803: 
                    804:   Revision 1.93  2003/06/25 16:33:55  brouard
                    805:   (Module): On windows (cygwin) function asctime_r doesn't
                    806:   exist so I changed back to asctime which exists.
                    807:   (Module): Version 0.96b
                    808: 
                    809:   Revision 1.92  2003/06/25 16:30:45  brouard
                    810:   (Module): On windows (cygwin) function asctime_r doesn't
                    811:   exist so I changed back to asctime which exists.
                    812: 
                    813:   Revision 1.91  2003/06/25 15:30:29  brouard
                    814:   * imach.c (Repository): Duplicated warning errors corrected.
                    815:   (Repository): Elapsed time after each iteration is now output. It
                    816:   helps to forecast when convergence will be reached. Elapsed time
                    817:   is stamped in powell.  We created a new html file for the graphs
                    818:   concerning matrix of covariance. It has extension -cov.htm.
                    819: 
                    820:   Revision 1.90  2003/06/24 12:34:15  brouard
                    821:   (Module): Some bugs corrected for windows. Also, when
                    822:   mle=-1 a template is output in file "or"mypar.txt with the design
                    823:   of the covariance matrix to be input.
                    824: 
                    825:   Revision 1.89  2003/06/24 12:30:52  brouard
                    826:   (Module): Some bugs corrected for windows. Also, when
                    827:   mle=-1 a template is output in file "or"mypar.txt with the design
                    828:   of the covariance matrix to be input.
                    829: 
                    830:   Revision 1.88  2003/06/23 17:54:56  brouard
                    831:   * 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.
                    832: 
                    833:   Revision 1.87  2003/06/18 12:26:01  brouard
                    834:   Version 0.96
                    835: 
                    836:   Revision 1.86  2003/06/17 20:04:08  brouard
                    837:   (Module): Change position of html and gnuplot routines and added
                    838:   routine fileappend.
                    839: 
                    840:   Revision 1.85  2003/06/17 13:12:43  brouard
                    841:   * imach.c (Repository): Check when date of death was earlier that
                    842:   current date of interview. It may happen when the death was just
                    843:   prior to the death. In this case, dh was negative and likelihood
                    844:   was wrong (infinity). We still send an "Error" but patch by
                    845:   assuming that the date of death was just one stepm after the
                    846:   interview.
                    847:   (Repository): Because some people have very long ID (first column)
                    848:   we changed int to long in num[] and we added a new lvector for
                    849:   memory allocation. But we also truncated to 8 characters (left
                    850:   truncation)
                    851:   (Repository): No more line truncation errors.
                    852: 
                    853:   Revision 1.84  2003/06/13 21:44:43  brouard
                    854:   * imach.c (Repository): Replace "freqsummary" at a correct
                    855:   place. It differs from routine "prevalence" which may be called
                    856:   many times. Probs is memory consuming and must be used with
                    857:   parcimony.
                    858:   Version 0.95a3 (should output exactly the same maximization than 0.8a2)
                    859: 
                    860:   Revision 1.83  2003/06/10 13:39:11  lievre
                    861:   *** empty log message ***
                    862: 
                    863:   Revision 1.82  2003/06/05 15:57:20  brouard
                    864:   Add log in  imach.c and  fullversion number is now printed.
                    865: 
                    866: */
                    867: /*
                    868:    Interpolated Markov Chain
                    869: 
                    870:   Short summary of the programme:
                    871:   
1.227     brouard   872:   This program computes Healthy Life Expectancies or State-specific
                    873:   (if states aren't health statuses) Expectancies from
                    874:   cross-longitudinal data. Cross-longitudinal data consist in: 
                    875: 
                    876:   -1- a first survey ("cross") where individuals from different ages
                    877:   are interviewed on their health status or degree of disability (in
                    878:   the case of a health survey which is our main interest)
                    879: 
                    880:   -2- at least a second wave of interviews ("longitudinal") which
                    881:   measure each change (if any) in individual health status.  Health
                    882:   expectancies are computed from the time spent in each health state
                    883:   according to a model. More health states you consider, more time is
                    884:   necessary to reach the Maximum Likelihood of the parameters involved
                    885:   in the model.  The simplest model is the multinomial logistic model
                    886:   where pij is the probability to be observed in state j at the second
                    887:   wave conditional to be observed in state i at the first
                    888:   wave. Therefore the model is: log(pij/pii)= aij + bij*age+ cij*sex +
                    889:   etc , where 'age' is age and 'sex' is a covariate. If you want to
                    890:   have a more complex model than "constant and age", you should modify
                    891:   the program where the markup *Covariates have to be included here
                    892:   again* invites you to do it.  More covariates you add, slower the
1.126     brouard   893:   convergence.
                    894: 
                    895:   The advantage of this computer programme, compared to a simple
                    896:   multinomial logistic model, is clear when the delay between waves is not
                    897:   identical for each individual. Also, if a individual missed an
                    898:   intermediate interview, the information is lost, but taken into
                    899:   account using an interpolation or extrapolation.  
                    900: 
                    901:   hPijx is the probability to be observed in state i at age x+h
                    902:   conditional to the observed state i at age x. The delay 'h' can be
                    903:   split into an exact number (nh*stepm) of unobserved intermediate
                    904:   states. This elementary transition (by month, quarter,
                    905:   semester or year) is modelled as a multinomial logistic.  The hPx
                    906:   matrix is simply the matrix product of nh*stepm elementary matrices
                    907:   and the contribution of each individual to the likelihood is simply
                    908:   hPijx.
                    909: 
                    910:   Also this programme outputs the covariance matrix of the parameters but also
1.218     brouard   911:   of the life expectancies. It also computes the period (stable) prevalence.
                    912: 
                    913: Back prevalence and projections:
1.227     brouard   914: 
                    915:  - back_prevalence_limit(double *p, double **bprlim, double ageminpar,
                    916:    double agemaxpar, double ftolpl, int *ncvyearp, double
                    917:    dateprev1,double dateprev2, int firstpass, int lastpass, int
                    918:    mobilavproj)
                    919: 
                    920:     Computes the back prevalence limit for any combination of
                    921:     covariate values k at any age between ageminpar and agemaxpar and
                    922:     returns it in **bprlim. In the loops,
                    923: 
                    924:    - **bprevalim(**bprlim, ***mobaverage, nlstate, *p, age, **oldm,
                    925:        **savm, **dnewm, **doldm, **dsavm, ftolpl, ncvyearp, k);
                    926: 
                    927:    - hBijx Back Probability to be in state i at age x-h being in j at x
1.218     brouard   928:    Computes for any combination of covariates k and any age between bage and fage 
                    929:    p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                    930:                        oldm=oldms;savm=savms;
1.227     brouard   931: 
1.267     brouard   932:    - hbxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k, nres);
1.218     brouard   933:      Computes the transition matrix starting at age 'age' over
                    934:      'nhstepm*hstepm*stepm' months (i.e. until
                    935:      age (in years)  age+nhstepm*hstepm*stepm/12) by multiplying
1.227     brouard   936:      nhstepm*hstepm matrices. 
                    937: 
                    938:      Returns p3mat[i][j][h] after calling
                    939:      p3mat[i][j][h]=matprod2(newm,
                    940:      bmij(pmmij,cov,ncovmodel,x,nlstate,prevacurrent, dnewm, doldm,
                    941:      dsavm,ij),\ 1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath,
                    942:      oldm);
1.226     brouard   943: 
                    944: Important routines
                    945: 
                    946: - func (or funcone), computes logit (pij) distinguishing
                    947:   o fixed variables (single or product dummies or quantitative);
                    948:   o varying variables by:
                    949:    (1) wave (single, product dummies, quantitative), 
                    950:    (2) by age (can be month) age (done), age*age (done), age*Vn where Vn can be:
                    951:        % fixed dummy (treated) or quantitative (not done because time-consuming);
                    952:        % varying dummy (not done) or quantitative (not done);
                    953: - Tricode which tests the modality of dummy variables (in order to warn with wrong or empty modalities)
                    954:   and returns the number of efficient covariates cptcoveff and modalities nbcode[Tvar[k]][1]= 0 and nbcode[Tvar[k]][2]= 1 usually.
                    955: - printinghtml which outputs results like life expectancy in and from a state for a combination of modalities of dummy variables
                    956:   o There are 2*cptcoveff combinations of (0,1) for cptcoveff variables. Outputting only combinations with people, éliminating 1 1 if
                    957:     race White (0 0), Black vs White (1 0), Hispanic (0 1) and 1 1 being meaningless.
1.218     brouard   958: 
1.226     brouard   959: 
                    960:   
1.133     brouard   961:   Authors: Nicolas Brouard (brouard@ined.fr) and Agnès Lièvre (lievre@ined.fr).
                    962:            Institut national d'études démographiques, Paris.
1.126     brouard   963:   This software have been partly granted by Euro-REVES, a concerted action
                    964:   from the European Union.
                    965:   It is copyrighted identically to a GNU software product, ie programme and
                    966:   software can be distributed freely for non commercial use. Latest version
                    967:   can be accessed at http://euroreves.ined.fr/imach .
                    968: 
                    969:   Help to debug: LD_PRELOAD=/usr/local/lib/libnjamd.so ./imach foo.imach
                    970:   or better on gdb : set env LD_PRELOAD=/usr/local/lib/libnjamd.so
                    971:   
                    972:   **********************************************************************/
                    973: /*
                    974:   main
                    975:   read parameterfile
                    976:   read datafile
                    977:   concatwav
                    978:   freqsummary
                    979:   if (mle >= 1)
                    980:     mlikeli
                    981:   print results files
                    982:   if mle==1 
                    983:      computes hessian
                    984:   read end of parameter file: agemin, agemax, bage, fage, estepm
                    985:       begin-prev-date,...
                    986:   open gnuplot file
                    987:   open html file
1.145     brouard   988:   period (stable) prevalence      | pl_nom    1-1 2-2 etc by covariate
                    989:    for age prevalim()             | #****** V1=0  V2=1  V3=1  V4=0 ******
                    990:                                   | 65 1 0 2 1 3 1 4 0  0.96326 0.03674
                    991:     freexexit2 possible for memory heap.
                    992: 
                    993:   h Pij x                         | pij_nom  ficrestpij
                    994:    # Cov Agex agex+h hpijx with i,j= 1-1 1-2     1-3     2-1     2-2     2-3
                    995:        1  85   85    1.00000             0.00000 0.00000 0.00000 1.00000 0.00000
                    996:        1  85   86    0.68299             0.22291 0.09410 0.71093 0.00000 0.28907
                    997: 
                    998:        1  65   99    0.00364             0.00322 0.99314 0.00350 0.00310 0.99340
                    999:        1  65  100    0.00214             0.00204 0.99581 0.00206 0.00196 0.99597
                   1000:   variance of p one-step probabilities varprob  | prob_nom   ficresprob #One-step probabilities and stand. devi in ()
                   1001:    Standard deviation of one-step probabilities | probcor_nom   ficresprobcor #One-step probabilities and correlation matrix
                   1002:    Matrix of variance covariance of one-step probabilities |  probcov_nom ficresprobcov #One-step probabilities and covariance matrix
                   1003: 
1.126     brouard  1004:   forecasting if prevfcast==1 prevforecast call prevalence()
                   1005:   health expectancies
                   1006:   Variance-covariance of DFLE
                   1007:   prevalence()
                   1008:    movingaverage()
                   1009:   varevsij() 
                   1010:   if popbased==1 varevsij(,popbased)
                   1011:   total life expectancies
                   1012:   Variance of period (stable) prevalence
                   1013:  end
                   1014: */
                   1015: 
1.187     brouard  1016: /* #define DEBUG */
                   1017: /* #define DEBUGBRENT */
1.203     brouard  1018: /* #define DEBUGLINMIN */
                   1019: /* #define DEBUGHESS */
                   1020: #define DEBUGHESSIJ
1.224     brouard  1021: /* #define LINMINORIGINAL  /\* Don't use loop on scale in linmin (accepting nan) *\/ */
1.165     brouard  1022: #define POWELL /* Instead of NLOPT */
1.224     brouard  1023: #define POWELLNOF3INFF1TEST /* Skip test */
1.186     brouard  1024: /* #define POWELLORIGINAL /\* Don't use Directest to decide new direction but original Powell test *\/ */
                   1025: /* #define MNBRAKORIGINAL /\* Don't use mnbrak fix *\/ */
1.126     brouard  1026: 
                   1027: #include <math.h>
                   1028: #include <stdio.h>
                   1029: #include <stdlib.h>
                   1030: #include <string.h>
1.226     brouard  1031: #include <ctype.h>
1.159     brouard  1032: 
                   1033: #ifdef _WIN32
                   1034: #include <io.h>
1.172     brouard  1035: #include <windows.h>
                   1036: #include <tchar.h>
1.159     brouard  1037: #else
1.126     brouard  1038: #include <unistd.h>
1.159     brouard  1039: #endif
1.126     brouard  1040: 
                   1041: #include <limits.h>
                   1042: #include <sys/types.h>
1.171     brouard  1043: 
                   1044: #if defined(__GNUC__)
                   1045: #include <sys/utsname.h> /* Doesn't work on Windows */
                   1046: #endif
                   1047: 
1.126     brouard  1048: #include <sys/stat.h>
                   1049: #include <errno.h>
1.159     brouard  1050: /* extern int errno; */
1.126     brouard  1051: 
1.157     brouard  1052: /* #ifdef LINUX */
                   1053: /* #include <time.h> */
                   1054: /* #include "timeval.h" */
                   1055: /* #else */
                   1056: /* #include <sys/time.h> */
                   1057: /* #endif */
                   1058: 
1.126     brouard  1059: #include <time.h>
                   1060: 
1.136     brouard  1061: #ifdef GSL
                   1062: #include <gsl/gsl_errno.h>
                   1063: #include <gsl/gsl_multimin.h>
                   1064: #endif
                   1065: 
1.167     brouard  1066: 
1.162     brouard  1067: #ifdef NLOPT
                   1068: #include <nlopt.h>
                   1069: typedef struct {
                   1070:   double (* function)(double [] );
                   1071: } myfunc_data ;
                   1072: #endif
                   1073: 
1.126     brouard  1074: /* #include <libintl.h> */
                   1075: /* #define _(String) gettext (String) */
                   1076: 
1.251     brouard  1077: #define MAXLINE 2048 /* Was 256 and 1024. Overflow with 312 with 2 states and 4 covariates. Should be ok */
1.126     brouard  1078: 
                   1079: #define GNUPLOTPROGRAM "gnuplot"
                   1080: /*#define GNUPLOTPROGRAM "..\\gp37mgw\\wgnuplot"*/
                   1081: #define FILENAMELENGTH 132
                   1082: 
                   1083: #define        GLOCK_ERROR_NOPATH              -1      /* empty path */
                   1084: #define        GLOCK_ERROR_GETCWD              -2      /* cannot get cwd */
                   1085: 
1.144     brouard  1086: #define MAXPARM 128 /**< Maximum number of parameters for the optimization */
                   1087: #define NPARMAX 64 /**< (nlstate+ndeath-1)*nlstate*ncovmodel */
1.126     brouard  1088: 
                   1089: #define NINTERVMAX 8
1.144     brouard  1090: #define NLSTATEMAX 8 /**< Maximum number of live states (for func) */
                   1091: #define NDEATHMAX 8 /**< Maximum number of dead states (for func) */
1.291     brouard  1092: #define NCOVMAX 20  /**< Maximum number of covariates, including generated covariates V1*V2 */
1.197     brouard  1093: #define codtabm(h,k)  (1 & (h-1) >> (k-1))+1
1.211     brouard  1094: /*#define decodtabm(h,k,cptcoveff)= (h <= (1<<cptcoveff)?(((h-1) >> (k-1)) & 1) +1 : -1)*/
                   1095: #define decodtabm(h,k,cptcoveff) (((h-1) >> (k-1)) & 1) +1 
1.290     brouard  1096: /*#define MAXN 20000 */ /* Should by replaced by nobs, real number of observations and unlimited */
1.144     brouard  1097: #define YEARM 12. /**< Number of months per year */
1.218     brouard  1098: /* #define AGESUP 130 */
1.288     brouard  1099: /* #define AGESUP 150 */
                   1100: #define AGESUP 200
1.268     brouard  1101: #define AGEINF 0
1.218     brouard  1102: #define AGEMARGE 25 /* Marge for agemin and agemax for(iage=agemin-AGEMARGE; iage <= agemax+3+AGEMARGE; iage++) */
1.126     brouard  1103: #define AGEBASE 40
1.194     brouard  1104: #define AGEOVERFLOW 1.e20
1.164     brouard  1105: #define AGEGOMP 10 /**< Minimal age for Gompertz adjustment */
1.157     brouard  1106: #ifdef _WIN32
                   1107: #define DIRSEPARATOR '\\'
                   1108: #define CHARSEPARATOR "\\"
                   1109: #define ODIRSEPARATOR '/'
                   1110: #else
1.126     brouard  1111: #define DIRSEPARATOR '/'
                   1112: #define CHARSEPARATOR "/"
                   1113: #define ODIRSEPARATOR '\\'
                   1114: #endif
                   1115: 
1.299   ! brouard  1116: /* $Id: imach.c,v 1.298 2019/05/22 18:19:56 brouard Exp $ */
1.126     brouard  1117: /* $State: Exp $ */
1.196     brouard  1118: #include "version.h"
                   1119: char version[]=__IMACH_VERSION__;
1.283     brouard  1120: char copyright[]="April 2018,INED-EUROREVES-Institut de longevite-Japan Society for the Promotion of Science (Grant-in-Aid for Scientific Research 25293121), Intel Software 2015-2018";
1.299   ! brouard  1121: char fullversion[]="$Revision: 1.298 $ $Date: 2019/05/22 18:19:56 $"; 
1.126     brouard  1122: char strstart[80];
                   1123: char optionfilext[10], optionfilefiname[FILENAMELENGTH];
1.130     brouard  1124: int erreur=0, nberr=0, nbwarn=0; /* Error number, number of errors number of warnings  */
1.187     brouard  1125: int nagesqr=0, nforce=0; /* nagesqr=1 if model is including age*age, number of forces */
1.145     brouard  1126: /* Number of covariates model=V2+V1+ V3*age+V2*V4 */
                   1127: int cptcovn=0; /**< cptcovn number of covariates added in the model (excepting constant and age and age*product) */
                   1128: int cptcovt=0; /**< cptcovt number of covariates added in the model (excepting constant and age) */
1.225     brouard  1129: int cptcovs=0; /**< cptcovs number of simple covariates in the model V2+V1 =2 */
                   1130: int cptcovsnq=0; /**< cptcovsnq number of simple covariates in the model but non quantitative V2+V1 =2 */
1.145     brouard  1131: int cptcovage=0; /**< Number of covariates with age: V3*age only =1 */
                   1132: int cptcovprodnoage=0; /**< Number of covariate products without age */   
                   1133: int cptcoveff=0; /* Total number of covariates to vary for printing results */
1.233     brouard  1134: int ncovf=0; /* Total number of effective fixed covariates (dummy or quantitative) in the model */
                   1135: int ncovv=0; /* Total number of effective (wave) varying covariates (dummy or quantitative) in the model */
1.232     brouard  1136: int ncova=0; /* Total number of effective (wave and stepm) varying with age covariates (dummy of quantitative) in the model */
1.234     brouard  1137: int nsd=0; /**< Total number of single dummy variables (output) */
                   1138: int nsq=0; /**< Total number of single quantitative variables (output) */
1.232     brouard  1139: int ncoveff=0; /* Total number of effective fixed dummy covariates in the model */
1.225     brouard  1140: int nqfveff=0; /**< nqfveff Number of Quantitative Fixed Variables Effective */
1.224     brouard  1141: int ntveff=0; /**< ntveff number of effective time varying variables */
                   1142: int nqtveff=0; /**< ntqveff number of effective time varying quantitative variables */
1.145     brouard  1143: int cptcov=0; /* Working variable */
1.290     brouard  1144: int nobs=10;  /* Number of observations in the data lastobs-firstobs */
1.218     brouard  1145: int ncovcombmax=NCOVMAX; /* Maximum calculated number of covariate combination = pow(2, cptcoveff) */
1.126     brouard  1146: int npar=NPARMAX;
                   1147: int nlstate=2; /* Number of live states */
                   1148: int ndeath=1; /* Number of dead states */
1.130     brouard  1149: int ncovmodel=0, ncovcol=0;     /* Total number of covariables including constant a12*1 +b12*x ncovmodel=2 */
1.223     brouard  1150: int  nqv=0, ntv=0, nqtv=0;    /* Total number of quantitative variables, time variable (dummy), quantitative and time variable */ 
1.126     brouard  1151: int popbased=0;
                   1152: 
                   1153: int *wav; /* Number of waves for this individuual 0 is possible */
1.130     brouard  1154: int maxwav=0; /* Maxim number of waves */
                   1155: int jmin=0, jmax=0; /* min, max spacing between 2 waves */
                   1156: int ijmin=0, ijmax=0; /* Individuals having jmin and jmax */ 
                   1157: int gipmx=0, gsw=0; /* Global variables on the number of contributions 
1.126     brouard  1158:                   to the likelihood and the sum of weights (done by funcone)*/
1.130     brouard  1159: int mle=1, weightopt=0;
1.126     brouard  1160: int **mw; /* mw[mi][i] is number of the mi wave for this individual */
                   1161: int **dh; /* dh[mi][i] is number of steps between mi,mi+1 for this individual */
                   1162: int **bh; /* bh[mi][i] is the bias (+ or -) for this individual if the delay between
                   1163:           * wave mi and wave mi+1 is not an exact multiple of stepm. */
1.162     brouard  1164: int countcallfunc=0;  /* Count the number of calls to func */
1.230     brouard  1165: int selected(int kvar); /* Is covariate kvar selected for printing results */
                   1166: 
1.130     brouard  1167: double jmean=1; /* Mean space between 2 waves */
1.145     brouard  1168: double **matprod2(); /* test */
1.126     brouard  1169: double **oldm, **newm, **savm; /* Working pointers to matrices */
                   1170: double **oldms, **newms, **savms; /* Fixed working pointers to matrices */
1.218     brouard  1171: double  **ddnewms, **ddoldms, **ddsavms; /* for freeing later */
                   1172: 
1.136     brouard  1173: /*FILE *fic ; */ /* Used in readdata only */
1.217     brouard  1174: FILE *ficpar, *ficparo,*ficres, *ficresp, *ficresphtm, *ficresphtmfr, *ficrespl, *ficresplb,*ficrespij, *ficrespijb, *ficrest,*ficresf, *ficresfb,*ficrespop;
1.126     brouard  1175: FILE *ficlog, *ficrespow;
1.130     brouard  1176: int globpr=0; /* Global variable for printing or not */
1.126     brouard  1177: double fretone; /* Only one call to likelihood */
1.130     brouard  1178: long ipmx=0; /* Number of contributions */
1.126     brouard  1179: double sw; /* Sum of weights */
                   1180: char filerespow[FILENAMELENGTH];
                   1181: char fileresilk[FILENAMELENGTH]; /* File of individual contributions to the likelihood */
                   1182: FILE *ficresilk;
                   1183: FILE *ficgp,*ficresprob,*ficpop, *ficresprobcov, *ficresprobcor;
                   1184: FILE *ficresprobmorprev;
                   1185: FILE *fichtm, *fichtmcov; /* Html File */
                   1186: FILE *ficreseij;
                   1187: char filerese[FILENAMELENGTH];
                   1188: FILE *ficresstdeij;
                   1189: char fileresstde[FILENAMELENGTH];
                   1190: FILE *ficrescveij;
                   1191: char filerescve[FILENAMELENGTH];
                   1192: FILE  *ficresvij;
                   1193: char fileresv[FILENAMELENGTH];
1.269     brouard  1194: 
1.126     brouard  1195: char title[MAXLINE];
1.234     brouard  1196: char model[MAXLINE]; /**< The model line */
1.217     brouard  1197: char optionfile[FILENAMELENGTH], datafile[FILENAMELENGTH],  filerespl[FILENAMELENGTH],  fileresplb[FILENAMELENGTH];
1.126     brouard  1198: char plotcmd[FILENAMELENGTH], pplotcmd[FILENAMELENGTH];
                   1199: char tmpout[FILENAMELENGTH],  tmpout2[FILENAMELENGTH]; 
                   1200: char command[FILENAMELENGTH];
                   1201: int  outcmd=0;
                   1202: 
1.217     brouard  1203: char fileres[FILENAMELENGTH], filerespij[FILENAMELENGTH], filerespijb[FILENAMELENGTH], filereso[FILENAMELENGTH], rfileres[FILENAMELENGTH];
1.202     brouard  1204: char fileresu[FILENAMELENGTH]; /* fileres without r in front */
1.126     brouard  1205: char filelog[FILENAMELENGTH]; /* Log file */
                   1206: char filerest[FILENAMELENGTH];
                   1207: char fileregp[FILENAMELENGTH];
                   1208: char popfile[FILENAMELENGTH];
                   1209: 
                   1210: char optionfilegnuplot[FILENAMELENGTH], optionfilehtm[FILENAMELENGTH], optionfilehtmcov[FILENAMELENGTH] ;
                   1211: 
1.157     brouard  1212: /* struct timeval start_time, end_time, curr_time, last_time, forecast_time; */
                   1213: /* struct timezone tzp; */
                   1214: /* extern int gettimeofday(); */
                   1215: struct tm tml, *gmtime(), *localtime();
                   1216: 
                   1217: extern time_t time();
                   1218: 
                   1219: struct tm start_time, end_time, curr_time, last_time, forecast_time;
                   1220: time_t  rstart_time, rend_time, rcurr_time, rlast_time, rforecast_time; /* raw time */
                   1221: struct tm tm;
                   1222: 
1.126     brouard  1223: char strcurr[80], strfor[80];
                   1224: 
                   1225: char *endptr;
                   1226: long lval;
                   1227: double dval;
                   1228: 
                   1229: #define NR_END 1
                   1230: #define FREE_ARG char*
                   1231: #define FTOL 1.0e-10
                   1232: 
                   1233: #define NRANSI 
1.240     brouard  1234: #define ITMAX 200
                   1235: #define ITPOWMAX 20 /* This is now multiplied by the number of parameters */ 
1.126     brouard  1236: 
                   1237: #define TOL 2.0e-4 
                   1238: 
                   1239: #define CGOLD 0.3819660 
                   1240: #define ZEPS 1.0e-10 
                   1241: #define SHFT(a,b,c,d) (a)=(b);(b)=(c);(c)=(d); 
                   1242: 
                   1243: #define GOLD 1.618034 
                   1244: #define GLIMIT 100.0 
                   1245: #define TINY 1.0e-20 
                   1246: 
                   1247: static double maxarg1,maxarg2;
                   1248: #define FMAX(a,b) (maxarg1=(a),maxarg2=(b),(maxarg1)>(maxarg2)? (maxarg1):(maxarg2))
                   1249: #define FMIN(a,b) (maxarg1=(a),maxarg2=(b),(maxarg1)<(maxarg2)? (maxarg1):(maxarg2))
                   1250:   
                   1251: #define SIGN(a,b) ((b)>0.0 ? fabs(a) : -fabs(a))
                   1252: #define rint(a) floor(a+0.5)
1.166     brouard  1253: /* http://www.thphys.uni-heidelberg.de/~robbers/cmbeasy/doc/html/myutils_8h-source.html */
1.183     brouard  1254: #define mytinydouble 1.0e-16
1.166     brouard  1255: /* #define DEQUAL(a,b) (fabs((a)-(b))<mytinydouble) */
                   1256: /* http://www.thphys.uni-heidelberg.de/~robbers/cmbeasy/doc/html/mynrutils_8h-source.html */
                   1257: /* static double dsqrarg; */
                   1258: /* #define DSQR(a) (DEQUAL((dsqrarg=(a)),0.0) ? 0.0 : dsqrarg*dsqrarg) */
1.126     brouard  1259: static double sqrarg;
                   1260: #define SQR(a) ((sqrarg=(a)) == 0.0 ? 0.0 :sqrarg*sqrarg)
                   1261: #define SWAP(a,b) {temp=(a);(a)=(b);(b)=temp;} 
                   1262: int agegomp= AGEGOMP;
                   1263: 
                   1264: int imx; 
                   1265: int stepm=1;
                   1266: /* Stepm, step in month: minimum step interpolation*/
                   1267: 
                   1268: int estepm;
                   1269: /* Estepm, step in month to interpolate survival function in order to approximate Life Expectancy*/
                   1270: 
                   1271: int m,nb;
                   1272: long *num;
1.197     brouard  1273: int firstpass=0, lastpass=4,*cod, *cens;
1.192     brouard  1274: int *ncodemax;  /* ncodemax[j]= Number of modalities of the j th
                   1275:                   covariate for which somebody answered excluding 
                   1276:                   undefined. Usually 2: 0 and 1. */
                   1277: int *ncodemaxwundef;  /* ncodemax[j]= Number of modalities of the j th
                   1278:                             covariate for which somebody answered including 
                   1279:                             undefined. Usually 3: -1, 0 and 1. */
1.126     brouard  1280: double **agev,*moisnais, *annais, *moisdc, *andc,**mint, **anint;
1.218     brouard  1281: double **pmmij, ***probs; /* Global pointer */
1.219     brouard  1282: double ***mobaverage, ***mobaverages; /* New global variable */
1.126     brouard  1283: double *ageexmed,*agecens;
                   1284: double dateintmean=0;
1.296     brouard  1285:   double anprojd, mprojd, jprojd; /* For eventual projections */
                   1286:   double anprojf, mprojf, jprojf;
1.126     brouard  1287: 
1.296     brouard  1288:   double anbackd, mbackd, jbackd; /* For eventual backprojections */
                   1289:   double anbackf, mbackf, jbackf;
                   1290:   double jintmean,mintmean,aintmean;  
1.126     brouard  1291: double *weight;
                   1292: int **s; /* Status */
1.141     brouard  1293: double *agedc;
1.145     brouard  1294: double  **covar; /**< covar[j,i], value of jth covariate for individual i,
1.141     brouard  1295:                  * covar=matrix(0,NCOVMAX,1,n); 
1.187     brouard  1296:                  * cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*age; */
1.268     brouard  1297: double **coqvar; /* Fixed quantitative covariate nqv */
                   1298: double ***cotvar; /* Time varying covariate ntv */
1.225     brouard  1299: double ***cotqvar; /* Time varying quantitative covariate itqv */
1.141     brouard  1300: double  idx; 
                   1301: int **nbcode, *Tvar; /**< model=V2 => Tvar[1]= 2 */
1.234     brouard  1302: /*           V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
                   1303: /*k          1  2   3   4     5    6    7     8    9 */
                   1304: /*Tvar[k]=   5  4   3   6     5    2    7     1    1 */
                   1305: /* Tndvar[k]    1   2   3               4          5 */
                   1306: /*TDvar         4   3   6               7          1 */ /* For outputs only; combination of dummies fixed or varying */
                   1307: /* Tns[k]    1  2   2              4               5 */ /* Number of single cova */
                   1308: /* TvarsD[k]    1   2                              3 */ /* Number of single dummy cova */
                   1309: /* TvarsDind    2   3                              9 */ /* position K of single dummy cova */
                   1310: /* TvarsQ[k] 1                     2                 */ /* Number of single quantitative cova */
                   1311: /* TvarsQind 1                     6                 */ /* position K of single quantitative cova */
                   1312: /* Tprod[i]=k           4               7            */
                   1313: /* Tage[i]=k                  5               8      */
                   1314: /* */
                   1315: /* Type                    */
                   1316: /* V         1  2  3  4  5 */
                   1317: /*           F  F  V  V  V */
                   1318: /*           D  Q  D  D  Q */
                   1319: /*                         */
                   1320: int *TvarsD;
                   1321: int *TvarsDind;
                   1322: int *TvarsQ;
                   1323: int *TvarsQind;
                   1324: 
1.235     brouard  1325: #define MAXRESULTLINES 10
                   1326: int nresult=0;
1.258     brouard  1327: int parameterline=0; /* # of the parameter (type) line */
1.235     brouard  1328: int TKresult[MAXRESULTLINES];
1.237     brouard  1329: int Tresult[MAXRESULTLINES][NCOVMAX];/* For dummy variable , value (output) */
                   1330: int Tinvresult[MAXRESULTLINES][NCOVMAX];/* For dummy variable , value (output) */
1.235     brouard  1331: int Tvresult[MAXRESULTLINES][NCOVMAX]; /* For dummy variable , variable # (output) */
                   1332: double Tqresult[MAXRESULTLINES][NCOVMAX]; /* For quantitative variable , value (output) */
1.237     brouard  1333: double Tqinvresult[MAXRESULTLINES][NCOVMAX]; /* For quantitative variable , value (output) */
1.235     brouard  1334: int Tvqresult[MAXRESULTLINES][NCOVMAX]; /* For quantitative variable , variable # (output) */
                   1335: 
1.234     brouard  1336: /* 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  1337: 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 */
                   1338: 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 */
                   1339: 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 */
                   1340: int *TvarVind; /**< TvarVind[1]=1, TvarVind[2]=2  in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
                   1341: 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 */
                   1342: 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  1343: int *TvarFD; /**< TvarFD[1]=V1 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
                   1344: int *TvarFDind; /* TvarFDind[1]=9 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
                   1345: int *TvarFQ; /* TvarFQ[1]=V2 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */ /* Only simple fixed quantitative variable */
                   1346: int *TvarFQind; /* TvarFQind[1]=6 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */ /* Only simple fixed quantitative variable */
                   1347: int *TvarVD; /* TvarVD[1]=V5 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */ /* Only simple fixed quantitative variable */
                   1348: int *TvarVDind; /* TvarVDind[1]=1 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */ /* Only simple fixed quantitative variable */
                   1349: 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 */
                   1350: 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 */
                   1351: 
1.230     brouard  1352: int *Tvarsel; /**< Selected covariates for output */
                   1353: double *Tvalsel; /**< Selected modality value of covariate for output */
1.226     brouard  1354: int *Typevar; /**< 0 for simple covariate (dummy, quantitative, fixed or varying), 1 for age product, 2 for  product */
1.227     brouard  1355: int *Fixed; /** Fixed[k] 0=fixed, 1 varying, 2 fixed with age product, 3 varying with age product */ 
                   1356: 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  1357: int *DummyV; /** Dummy[v] 0=dummy (0 1), 1 quantitative */
                   1358: int *FixedV; /** FixedV[v] 0 fixed, 1 varying */
1.197     brouard  1359: int *Tage;
1.227     brouard  1360: int anyvaryingduminmodel=0; /**< Any varying dummy in Model=1 yes, 0 no, to avoid a loop on waves in freq */ 
1.228     brouard  1361: 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  1362: 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*/ 
                   1363: 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  1364: int *Ndum; /** Freq of modality (tricode */
1.200     brouard  1365: /* int **codtab;*/ /**< codtab=imatrix(1,100,1,10); */
1.227     brouard  1366: int **Tvard;
                   1367: int *Tprod;/**< Gives the k position of the k1 product */
1.238     brouard  1368: /* Tprod[k1=1]=3(=V1*V4) for V2+V1+V1*V4+age*V3  */
1.227     brouard  1369: int *Tposprod; /**< Gives the k1 product from the k position */
1.238     brouard  1370:    /* if  V2+V1+V1*V4+age*V3+V3*V2   TProd[k1=2]=5 (V3*V2) */
                   1371:    /* Tposprod[k]=k1 , Tposprod[3]=1, Tposprod[5(V3*V2)]=2 (2nd product without age) */
1.227     brouard  1372: int cptcovprod, *Tvaraff, *invalidvarcomb;
1.126     brouard  1373: double *lsurv, *lpop, *tpop;
                   1374: 
1.231     brouard  1375: #define FD 1; /* Fixed dummy covariate */
                   1376: #define FQ 2; /* Fixed quantitative covariate */
                   1377: #define FP 3; /* Fixed product covariate */
                   1378: #define FPDD 7; /* Fixed product dummy*dummy covariate */
                   1379: #define FPDQ 8; /* Fixed product dummy*quantitative covariate */
                   1380: #define FPQQ 9; /* Fixed product quantitative*quantitative covariate */
                   1381: #define VD 10; /* Varying dummy covariate */
                   1382: #define VQ 11; /* Varying quantitative covariate */
                   1383: #define VP 12; /* Varying product covariate */
                   1384: #define VPDD 13; /* Varying product dummy*dummy covariate */
                   1385: #define VPDQ 14; /* Varying product dummy*quantitative covariate */
                   1386: #define VPQQ 15; /* Varying product quantitative*quantitative covariate */
                   1387: #define APFD 16; /* Age product * fixed dummy covariate */
                   1388: #define APFQ 17; /* Age product * fixed quantitative covariate */
                   1389: #define APVD 18; /* Age product * varying dummy covariate */
                   1390: #define APVQ 19; /* Age product * varying quantitative covariate */
                   1391: 
                   1392: #define FTYPE 1; /* Fixed covariate */
                   1393: #define VTYPE 2; /* Varying covariate (loop in wave) */
                   1394: #define ATYPE 2; /* Age product covariate (loop in dh within wave)*/
                   1395: 
                   1396: struct kmodel{
                   1397:        int maintype; /* main type */
                   1398:        int subtype; /* subtype */
                   1399: };
                   1400: struct kmodel modell[NCOVMAX];
                   1401: 
1.143     brouard  1402: double ftol=FTOL; /**< Tolerance for computing Max Likelihood */
                   1403: double ftolhess; /**< Tolerance for computing hessian */
1.126     brouard  1404: 
                   1405: /**************** split *************************/
                   1406: static int split( char *path, char *dirc, char *name, char *ext, char *finame )
                   1407: {
                   1408:   /* From a file name with (full) path (either Unix or Windows) we extract the directory (dirc)
                   1409:      the name of the file (name), its extension only (ext) and its first part of the name (finame)
                   1410:   */ 
                   1411:   char *ss;                            /* pointer */
1.186     brouard  1412:   int  l1=0, l2=0;                             /* length counters */
1.126     brouard  1413: 
                   1414:   l1 = strlen(path );                  /* length of path */
                   1415:   if ( l1 == 0 ) return( GLOCK_ERROR_NOPATH );
                   1416:   ss= strrchr( path, DIRSEPARATOR );           /* find last / */
                   1417:   if ( ss == NULL ) {                  /* no directory, so determine current directory */
                   1418:     strcpy( name, path );              /* we got the fullname name because no directory */
                   1419:     /*if(strrchr(path, ODIRSEPARATOR )==NULL)
                   1420:       printf("Warning you should use %s as a separator\n",DIRSEPARATOR);*/
                   1421:     /* get current working directory */
                   1422:     /*    extern  char* getcwd ( char *buf , int len);*/
1.184     brouard  1423: #ifdef WIN32
                   1424:     if (_getcwd( dirc, FILENAME_MAX ) == NULL ) {
                   1425: #else
                   1426:        if (getcwd(dirc, FILENAME_MAX) == NULL) {
                   1427: #endif
1.126     brouard  1428:       return( GLOCK_ERROR_GETCWD );
                   1429:     }
                   1430:     /* got dirc from getcwd*/
                   1431:     printf(" DIRC = %s \n",dirc);
1.205     brouard  1432:   } else {                             /* strip directory from path */
1.126     brouard  1433:     ss++;                              /* after this, the filename */
                   1434:     l2 = strlen( ss );                 /* length of filename */
                   1435:     if ( l2 == 0 ) return( GLOCK_ERROR_NOPATH );
                   1436:     strcpy( name, ss );                /* save file name */
                   1437:     strncpy( dirc, path, l1 - l2 );    /* now the directory */
1.186     brouard  1438:     dirc[l1-l2] = '\0';                        /* add zero */
1.126     brouard  1439:     printf(" DIRC2 = %s \n",dirc);
                   1440:   }
                   1441:   /* We add a separator at the end of dirc if not exists */
                   1442:   l1 = strlen( dirc );                 /* length of directory */
                   1443:   if( dirc[l1-1] != DIRSEPARATOR ){
                   1444:     dirc[l1] =  DIRSEPARATOR;
                   1445:     dirc[l1+1] = 0; 
                   1446:     printf(" DIRC3 = %s \n",dirc);
                   1447:   }
                   1448:   ss = strrchr( name, '.' );           /* find last / */
                   1449:   if (ss >0){
                   1450:     ss++;
                   1451:     strcpy(ext,ss);                    /* save extension */
                   1452:     l1= strlen( name);
                   1453:     l2= strlen(ss)+1;
                   1454:     strncpy( finame, name, l1-l2);
                   1455:     finame[l1-l2]= 0;
                   1456:   }
                   1457: 
                   1458:   return( 0 );                         /* we're done */
                   1459: }
                   1460: 
                   1461: 
                   1462: /******************************************/
                   1463: 
                   1464: void replace_back_to_slash(char *s, char*t)
                   1465: {
                   1466:   int i;
                   1467:   int lg=0;
                   1468:   i=0;
                   1469:   lg=strlen(t);
                   1470:   for(i=0; i<= lg; i++) {
                   1471:     (s[i] = t[i]);
                   1472:     if (t[i]== '\\') s[i]='/';
                   1473:   }
                   1474: }
                   1475: 
1.132     brouard  1476: char *trimbb(char *out, char *in)
1.137     brouard  1477: { /* Trim multiple blanks in line but keeps first blanks if line starts with blanks */
1.132     brouard  1478:   char *s;
                   1479:   s=out;
                   1480:   while (*in != '\0'){
1.137     brouard  1481:     while( *in == ' ' && *(in+1) == ' '){ /* && *(in+1) != '\0'){*/
1.132     brouard  1482:       in++;
                   1483:     }
                   1484:     *out++ = *in++;
                   1485:   }
                   1486:   *out='\0';
                   1487:   return s;
                   1488: }
                   1489: 
1.187     brouard  1490: /* char *substrchaine(char *out, char *in, char *chain) */
                   1491: /* { */
                   1492: /*   /\* Substract chain 'chain' from 'in', return and output 'out' *\/ */
                   1493: /*   char *s, *t; */
                   1494: /*   t=in;s=out; */
                   1495: /*   while ((*in != *chain) && (*in != '\0')){ */
                   1496: /*     *out++ = *in++; */
                   1497: /*   } */
                   1498: 
                   1499: /*   /\* *in matches *chain *\/ */
                   1500: /*   while ((*in++ == *chain++) && (*in != '\0')){ */
                   1501: /*     printf("*in = %c, *out= %c *chain= %c \n", *in, *out, *chain);  */
                   1502: /*   } */
                   1503: /*   in--; chain--; */
                   1504: /*   while ( (*in != '\0')){ */
                   1505: /*     printf("Bef *in = %c, *out= %c *chain= %c \n", *in, *out, *chain);  */
                   1506: /*     *out++ = *in++; */
                   1507: /*     printf("Aft *in = %c, *out= %c *chain= %c \n", *in, *out, *chain);  */
                   1508: /*   } */
                   1509: /*   *out='\0'; */
                   1510: /*   out=s; */
                   1511: /*   return out; */
                   1512: /* } */
                   1513: char *substrchaine(char *out, char *in, char *chain)
                   1514: {
                   1515:   /* Substract chain 'chain' from 'in', return and output 'out' */
                   1516:   /* in="V1+V1*age+age*age+V2", chain="age*age" */
                   1517: 
                   1518:   char *strloc;
                   1519: 
                   1520:   strcpy (out, in); 
                   1521:   strloc = strstr(out, chain); /* strloc points to out at age*age+V2 */
                   1522:   printf("Bef strloc=%s chain=%s out=%s \n", strloc, chain, out);
                   1523:   if(strloc != NULL){ 
                   1524:     /* will affect out */ /* strloc+strlenc(chain)=+V2 */ /* Will also work in Unicode */
                   1525:     memmove(strloc,strloc+strlen(chain), strlen(strloc+strlen(chain))+1);
                   1526:     /* strcpy (strloc, strloc +strlen(chain));*/
                   1527:   }
                   1528:   printf("Aft strloc=%s chain=%s in=%s out=%s \n", strloc, chain, in, out);
                   1529:   return out;
                   1530: }
                   1531: 
                   1532: 
1.145     brouard  1533: char *cutl(char *blocc, char *alocc, char *in, char occ)
                   1534: {
1.187     brouard  1535:   /* cuts string in into blocc and alocc where blocc ends before FIRST occurence of char 'occ' 
1.145     brouard  1536:      and alocc starts after first occurence of char 'occ' : ex cutv(blocc,alocc,"abcdef2ghi2j",'2')
1.187     brouard  1537:      gives blocc="abcdef" and alocc="ghi2j".
1.145     brouard  1538:      If occ is not found blocc is null and alocc is equal to in. Returns blocc
                   1539:   */
1.160     brouard  1540:   char *s, *t;
1.145     brouard  1541:   t=in;s=in;
                   1542:   while ((*in != occ) && (*in != '\0')){
                   1543:     *alocc++ = *in++;
                   1544:   }
                   1545:   if( *in == occ){
                   1546:     *(alocc)='\0';
                   1547:     s=++in;
                   1548:   }
                   1549:  
                   1550:   if (s == t) {/* occ not found */
                   1551:     *(alocc-(in-s))='\0';
                   1552:     in=s;
                   1553:   }
                   1554:   while ( *in != '\0'){
                   1555:     *blocc++ = *in++;
                   1556:   }
                   1557: 
                   1558:   *blocc='\0';
                   1559:   return t;
                   1560: }
1.137     brouard  1561: char *cutv(char *blocc, char *alocc, char *in, char occ)
                   1562: {
1.187     brouard  1563:   /* cuts string in into blocc and alocc where blocc ends before LAST occurence of char 'occ' 
1.137     brouard  1564:      and alocc starts after last occurence of char 'occ' : ex cutv(blocc,alocc,"abcdef2ghi2j",'2')
                   1565:      gives blocc="abcdef2ghi" and alocc="j".
                   1566:      If occ is not found blocc is null and alocc is equal to in. Returns alocc
                   1567:   */
                   1568:   char *s, *t;
                   1569:   t=in;s=in;
                   1570:   while (*in != '\0'){
                   1571:     while( *in == occ){
                   1572:       *blocc++ = *in++;
                   1573:       s=in;
                   1574:     }
                   1575:     *blocc++ = *in++;
                   1576:   }
                   1577:   if (s == t) /* occ not found */
                   1578:     *(blocc-(in-s))='\0';
                   1579:   else
                   1580:     *(blocc-(in-s)-1)='\0';
                   1581:   in=s;
                   1582:   while ( *in != '\0'){
                   1583:     *alocc++ = *in++;
                   1584:   }
                   1585: 
                   1586:   *alocc='\0';
                   1587:   return s;
                   1588: }
                   1589: 
1.126     brouard  1590: int nbocc(char *s, char occ)
                   1591: {
                   1592:   int i,j=0;
                   1593:   int lg=20;
                   1594:   i=0;
                   1595:   lg=strlen(s);
                   1596:   for(i=0; i<= lg; i++) {
1.234     brouard  1597:     if  (s[i] == occ ) j++;
1.126     brouard  1598:   }
                   1599:   return j;
                   1600: }
                   1601: 
1.137     brouard  1602: /* void cutv(char *u,char *v, char*t, char occ) */
                   1603: /* { */
                   1604: /*   /\* cuts string t into u and v where u ends before last occurence of char 'occ'  */
                   1605: /*      and v starts after last occurence of char 'occ' : ex cutv(u,v,"abcdef2ghi2j",'2') */
                   1606: /*      gives u="abcdef2ghi" and v="j" *\/ */
                   1607: /*   int i,lg,j,p=0; */
                   1608: /*   i=0; */
                   1609: /*   lg=strlen(t); */
                   1610: /*   for(j=0; j<=lg-1; j++) { */
                   1611: /*     if((t[j]!= occ) && (t[j+1]== occ)) p=j+1; */
                   1612: /*   } */
1.126     brouard  1613: 
1.137     brouard  1614: /*   for(j=0; j<p; j++) { */
                   1615: /*     (u[j] = t[j]); */
                   1616: /*   } */
                   1617: /*      u[p]='\0'; */
1.126     brouard  1618: 
1.137     brouard  1619: /*    for(j=0; j<= lg; j++) { */
                   1620: /*     if (j>=(p+1))(v[j-p-1] = t[j]); */
                   1621: /*   } */
                   1622: /* } */
1.126     brouard  1623: 
1.160     brouard  1624: #ifdef _WIN32
                   1625: char * strsep(char **pp, const char *delim)
                   1626: {
                   1627:   char *p, *q;
                   1628:          
                   1629:   if ((p = *pp) == NULL)
                   1630:     return 0;
                   1631:   if ((q = strpbrk (p, delim)) != NULL)
                   1632:   {
                   1633:     *pp = q + 1;
                   1634:     *q = '\0';
                   1635:   }
                   1636:   else
                   1637:     *pp = 0;
                   1638:   return p;
                   1639: }
                   1640: #endif
                   1641: 
1.126     brouard  1642: /********************** nrerror ********************/
                   1643: 
                   1644: void nrerror(char error_text[])
                   1645: {
                   1646:   fprintf(stderr,"ERREUR ...\n");
                   1647:   fprintf(stderr,"%s\n",error_text);
                   1648:   exit(EXIT_FAILURE);
                   1649: }
                   1650: /*********************** vector *******************/
                   1651: double *vector(int nl, int nh)
                   1652: {
                   1653:   double *v;
                   1654:   v=(double *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(double)));
                   1655:   if (!v) nrerror("allocation failure in vector");
                   1656:   return v-nl+NR_END;
                   1657: }
                   1658: 
                   1659: /************************ free vector ******************/
                   1660: void free_vector(double*v, int nl, int nh)
                   1661: {
                   1662:   free((FREE_ARG)(v+nl-NR_END));
                   1663: }
                   1664: 
                   1665: /************************ivector *******************************/
                   1666: int *ivector(long nl,long nh)
                   1667: {
                   1668:   int *v;
                   1669:   v=(int *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(int)));
                   1670:   if (!v) nrerror("allocation failure in ivector");
                   1671:   return v-nl+NR_END;
                   1672: }
                   1673: 
                   1674: /******************free ivector **************************/
                   1675: void free_ivector(int *v, long nl, long nh)
                   1676: {
                   1677:   free((FREE_ARG)(v+nl-NR_END));
                   1678: }
                   1679: 
                   1680: /************************lvector *******************************/
                   1681: long *lvector(long nl,long nh)
                   1682: {
                   1683:   long *v;
                   1684:   v=(long *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(long)));
                   1685:   if (!v) nrerror("allocation failure in ivector");
                   1686:   return v-nl+NR_END;
                   1687: }
                   1688: 
                   1689: /******************free lvector **************************/
                   1690: void free_lvector(long *v, long nl, long nh)
                   1691: {
                   1692:   free((FREE_ARG)(v+nl-NR_END));
                   1693: }
                   1694: 
                   1695: /******************* imatrix *******************************/
                   1696: int **imatrix(long nrl, long nrh, long ncl, long nch) 
                   1697:      /* allocate a int matrix with subscript range m[nrl..nrh][ncl..nch] */ 
                   1698: { 
                   1699:   long i, nrow=nrh-nrl+1,ncol=nch-ncl+1; 
                   1700:   int **m; 
                   1701:   
                   1702:   /* allocate pointers to rows */ 
                   1703:   m=(int **) malloc((size_t)((nrow+NR_END)*sizeof(int*))); 
                   1704:   if (!m) nrerror("allocation failure 1 in matrix()"); 
                   1705:   m += NR_END; 
                   1706:   m -= nrl; 
                   1707:   
                   1708:   
                   1709:   /* allocate rows and set pointers to them */ 
                   1710:   m[nrl]=(int *) malloc((size_t)((nrow*ncol+NR_END)*sizeof(int))); 
                   1711:   if (!m[nrl]) nrerror("allocation failure 2 in matrix()"); 
                   1712:   m[nrl] += NR_END; 
                   1713:   m[nrl] -= ncl; 
                   1714:   
                   1715:   for(i=nrl+1;i<=nrh;i++) m[i]=m[i-1]+ncol; 
                   1716:   
                   1717:   /* return pointer to array of pointers to rows */ 
                   1718:   return m; 
                   1719: } 
                   1720: 
                   1721: /****************** free_imatrix *************************/
                   1722: void free_imatrix(m,nrl,nrh,ncl,nch)
                   1723:       int **m;
                   1724:       long nch,ncl,nrh,nrl; 
                   1725:      /* free an int matrix allocated by imatrix() */ 
                   1726: { 
                   1727:   free((FREE_ARG) (m[nrl]+ncl-NR_END)); 
                   1728:   free((FREE_ARG) (m+nrl-NR_END)); 
                   1729: } 
                   1730: 
                   1731: /******************* matrix *******************************/
                   1732: double **matrix(long nrl, long nrh, long ncl, long nch)
                   1733: {
                   1734:   long i, nrow=nrh-nrl+1, ncol=nch-ncl+1;
                   1735:   double **m;
                   1736: 
                   1737:   m=(double **) malloc((size_t)((nrow+NR_END)*sizeof(double*)));
                   1738:   if (!m) nrerror("allocation failure 1 in matrix()");
                   1739:   m += NR_END;
                   1740:   m -= nrl;
                   1741: 
                   1742:   m[nrl]=(double *) malloc((size_t)((nrow*ncol+NR_END)*sizeof(double)));
                   1743:   if (!m[nrl]) nrerror("allocation failure 2 in matrix()");
                   1744:   m[nrl] += NR_END;
                   1745:   m[nrl] -= ncl;
                   1746: 
                   1747:   for (i=nrl+1; i<=nrh; i++) m[i]=m[i-1]+ncol;
                   1748:   return m;
1.145     brouard  1749:   /* print *(*(m+1)+70) or print m[1][70]; print m+1 or print &(m[1]) or &(m[1][0])
                   1750: m[i] = address of ith row of the table. &(m[i]) is its value which is another adress
                   1751: that of m[i][0]. In order to get the value p m[i][0] but it is unitialized.
1.126     brouard  1752:    */
                   1753: }
                   1754: 
                   1755: /*************************free matrix ************************/
                   1756: void free_matrix(double **m, long nrl, long nrh, long ncl, long nch)
                   1757: {
                   1758:   free((FREE_ARG)(m[nrl]+ncl-NR_END));
                   1759:   free((FREE_ARG)(m+nrl-NR_END));
                   1760: }
                   1761: 
                   1762: /******************* ma3x *******************************/
                   1763: double ***ma3x(long nrl, long nrh, long ncl, long nch, long nll, long nlh)
                   1764: {
                   1765:   long i, j, nrow=nrh-nrl+1, ncol=nch-ncl+1, nlay=nlh-nll+1;
                   1766:   double ***m;
                   1767: 
                   1768:   m=(double ***) malloc((size_t)((nrow+NR_END)*sizeof(double*)));
                   1769:   if (!m) nrerror("allocation failure 1 in matrix()");
                   1770:   m += NR_END;
                   1771:   m -= nrl;
                   1772: 
                   1773:   m[nrl]=(double **) malloc((size_t)((nrow*ncol+NR_END)*sizeof(double)));
                   1774:   if (!m[nrl]) nrerror("allocation failure 2 in matrix()");
                   1775:   m[nrl] += NR_END;
                   1776:   m[nrl] -= ncl;
                   1777: 
                   1778:   for (i=nrl+1; i<=nrh; i++) m[i]=m[i-1]+ncol;
                   1779: 
                   1780:   m[nrl][ncl]=(double *) malloc((size_t)((nrow*ncol*nlay+NR_END)*sizeof(double)));
                   1781:   if (!m[nrl][ncl]) nrerror("allocation failure 3 in matrix()");
                   1782:   m[nrl][ncl] += NR_END;
                   1783:   m[nrl][ncl] -= nll;
                   1784:   for (j=ncl+1; j<=nch; j++) 
                   1785:     m[nrl][j]=m[nrl][j-1]+nlay;
                   1786:   
                   1787:   for (i=nrl+1; i<=nrh; i++) {
                   1788:     m[i][ncl]=m[i-1l][ncl]+ncol*nlay;
                   1789:     for (j=ncl+1; j<=nch; j++) 
                   1790:       m[i][j]=m[i][j-1]+nlay;
                   1791:   }
                   1792:   return m; 
                   1793:   /*  gdb: p *(m+1) <=> p m[1] and p (m+1) <=> p (m+1) <=> p &(m[1])
                   1794:            &(m[i][j][k]) <=> *((*(m+i) + j)+k)
                   1795:   */
                   1796: }
                   1797: 
                   1798: /*************************free ma3x ************************/
                   1799: void free_ma3x(double ***m, long nrl, long nrh, long ncl, long nch,long nll, long nlh)
                   1800: {
                   1801:   free((FREE_ARG)(m[nrl][ncl]+ nll-NR_END));
                   1802:   free((FREE_ARG)(m[nrl]+ncl-NR_END));
                   1803:   free((FREE_ARG)(m+nrl-NR_END));
                   1804: }
                   1805: 
                   1806: /*************** function subdirf ***********/
                   1807: char *subdirf(char fileres[])
                   1808: {
                   1809:   /* Caution optionfilefiname is hidden */
                   1810:   strcpy(tmpout,optionfilefiname);
                   1811:   strcat(tmpout,"/"); /* Add to the right */
                   1812:   strcat(tmpout,fileres);
                   1813:   return tmpout;
                   1814: }
                   1815: 
                   1816: /*************** function subdirf2 ***********/
                   1817: char *subdirf2(char fileres[], char *preop)
                   1818: {
                   1819:   
                   1820:   /* Caution optionfilefiname is hidden */
                   1821:   strcpy(tmpout,optionfilefiname);
                   1822:   strcat(tmpout,"/");
                   1823:   strcat(tmpout,preop);
                   1824:   strcat(tmpout,fileres);
                   1825:   return tmpout;
                   1826: }
                   1827: 
                   1828: /*************** function subdirf3 ***********/
                   1829: char *subdirf3(char fileres[], char *preop, char *preop2)
                   1830: {
                   1831:   
                   1832:   /* Caution optionfilefiname is hidden */
                   1833:   strcpy(tmpout,optionfilefiname);
                   1834:   strcat(tmpout,"/");
                   1835:   strcat(tmpout,preop);
                   1836:   strcat(tmpout,preop2);
                   1837:   strcat(tmpout,fileres);
                   1838:   return tmpout;
                   1839: }
1.213     brouard  1840:  
                   1841: /*************** function subdirfext ***********/
                   1842: char *subdirfext(char fileres[], char *preop, char *postop)
                   1843: {
                   1844:   
                   1845:   strcpy(tmpout,preop);
                   1846:   strcat(tmpout,fileres);
                   1847:   strcat(tmpout,postop);
                   1848:   return tmpout;
                   1849: }
1.126     brouard  1850: 
1.213     brouard  1851: /*************** function subdirfext3 ***********/
                   1852: char *subdirfext3(char fileres[], char *preop, char *postop)
                   1853: {
                   1854:   
                   1855:   /* Caution optionfilefiname is hidden */
                   1856:   strcpy(tmpout,optionfilefiname);
                   1857:   strcat(tmpout,"/");
                   1858:   strcat(tmpout,preop);
                   1859:   strcat(tmpout,fileres);
                   1860:   strcat(tmpout,postop);
                   1861:   return tmpout;
                   1862: }
                   1863:  
1.162     brouard  1864: char *asc_diff_time(long time_sec, char ascdiff[])
                   1865: {
                   1866:   long sec_left, days, hours, minutes;
                   1867:   days = (time_sec) / (60*60*24);
                   1868:   sec_left = (time_sec) % (60*60*24);
                   1869:   hours = (sec_left) / (60*60) ;
                   1870:   sec_left = (sec_left) %(60*60);
                   1871:   minutes = (sec_left) /60;
                   1872:   sec_left = (sec_left) % (60);
                   1873:   sprintf(ascdiff,"%ld day(s) %ld hour(s) %ld minute(s) %ld second(s)",days, hours, minutes, sec_left);  
                   1874:   return ascdiff;
                   1875: }
                   1876: 
1.126     brouard  1877: /***************** f1dim *************************/
                   1878: extern int ncom; 
                   1879: extern double *pcom,*xicom;
                   1880: extern double (*nrfunc)(double []); 
                   1881:  
                   1882: double f1dim(double x) 
                   1883: { 
                   1884:   int j; 
                   1885:   double f;
                   1886:   double *xt; 
                   1887:  
                   1888:   xt=vector(1,ncom); 
                   1889:   for (j=1;j<=ncom;j++) xt[j]=pcom[j]+x*xicom[j]; 
                   1890:   f=(*nrfunc)(xt); 
                   1891:   free_vector(xt,1,ncom); 
                   1892:   return f; 
                   1893: } 
                   1894: 
                   1895: /*****************brent *************************/
                   1896: double brent(double ax, double bx, double cx, double (*f)(double), double tol,         double *xmin) 
1.187     brouard  1897: {
                   1898:   /* Given a function f, and given a bracketing triplet of abscissas ax, bx, cx (such that bx is
                   1899:    * between ax and cx, and f(bx) is less than both f(ax) and f(cx) ), this routine isolates
                   1900:    * the minimum to a fractional precision of about tol using Brent’s method. The abscissa of
                   1901:    * the minimum is returned as xmin, and the minimum function value is returned as brent , the
                   1902:    * returned function value. 
                   1903:   */
1.126     brouard  1904:   int iter; 
                   1905:   double a,b,d,etemp;
1.159     brouard  1906:   double fu=0,fv,fw,fx;
1.164     brouard  1907:   double ftemp=0.;
1.126     brouard  1908:   double p,q,r,tol1,tol2,u,v,w,x,xm; 
                   1909:   double e=0.0; 
                   1910:  
                   1911:   a=(ax < cx ? ax : cx); 
                   1912:   b=(ax > cx ? ax : cx); 
                   1913:   x=w=v=bx; 
                   1914:   fw=fv=fx=(*f)(x); 
                   1915:   for (iter=1;iter<=ITMAX;iter++) { 
                   1916:     xm=0.5*(a+b); 
                   1917:     tol2=2.0*(tol1=tol*fabs(x)+ZEPS); 
                   1918:     /*         if (2.0*fabs(fp-(*fret)) <= ftol*(fabs(fp)+fabs(*fret)))*/
                   1919:     printf(".");fflush(stdout);
                   1920:     fprintf(ficlog,".");fflush(ficlog);
1.162     brouard  1921: #ifdef DEBUGBRENT
1.126     brouard  1922:     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);
                   1923:     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);
                   1924:     /*         if ((fabs(x-xm) <= (tol2-0.5*(b-a)))||(2.0*fabs(fu-ftemp) <= ftol*1.e-2*(fabs(fu)+fabs(ftemp)))) { */
                   1925: #endif
                   1926:     if (fabs(x-xm) <= (tol2-0.5*(b-a))){ 
                   1927:       *xmin=x; 
                   1928:       return fx; 
                   1929:     } 
                   1930:     ftemp=fu;
                   1931:     if (fabs(e) > tol1) { 
                   1932:       r=(x-w)*(fx-fv); 
                   1933:       q=(x-v)*(fx-fw); 
                   1934:       p=(x-v)*q-(x-w)*r; 
                   1935:       q=2.0*(q-r); 
                   1936:       if (q > 0.0) p = -p; 
                   1937:       q=fabs(q); 
                   1938:       etemp=e; 
                   1939:       e=d; 
                   1940:       if (fabs(p) >= fabs(0.5*q*etemp) || p <= q*(a-x) || p >= q*(b-x)) 
1.224     brouard  1941:                                d=CGOLD*(e=(x >= xm ? a-x : b-x)); 
1.126     brouard  1942:       else { 
1.224     brouard  1943:                                d=p/q; 
                   1944:                                u=x+d; 
                   1945:                                if (u-a < tol2 || b-u < tol2) 
                   1946:                                        d=SIGN(tol1,xm-x); 
1.126     brouard  1947:       } 
                   1948:     } else { 
                   1949:       d=CGOLD*(e=(x >= xm ? a-x : b-x)); 
                   1950:     } 
                   1951:     u=(fabs(d) >= tol1 ? x+d : x+SIGN(tol1,d)); 
                   1952:     fu=(*f)(u); 
                   1953:     if (fu <= fx) { 
                   1954:       if (u >= x) a=x; else b=x; 
                   1955:       SHFT(v,w,x,u) 
1.183     brouard  1956:       SHFT(fv,fw,fx,fu) 
                   1957:     } else { 
                   1958:       if (u < x) a=u; else b=u; 
                   1959:       if (fu <= fw || w == x) { 
1.224     brouard  1960:                                v=w; 
                   1961:                                w=u; 
                   1962:                                fv=fw; 
                   1963:                                fw=fu; 
1.183     brouard  1964:       } else if (fu <= fv || v == x || v == w) { 
1.224     brouard  1965:                                v=u; 
                   1966:                                fv=fu; 
1.183     brouard  1967:       } 
                   1968:     } 
1.126     brouard  1969:   } 
                   1970:   nrerror("Too many iterations in brent"); 
                   1971:   *xmin=x; 
                   1972:   return fx; 
                   1973: } 
                   1974: 
                   1975: /****************** mnbrak ***********************/
                   1976: 
                   1977: void mnbrak(double *ax, double *bx, double *cx, double *fa, double *fb, double *fc, 
                   1978:            double (*func)(double)) 
1.183     brouard  1979: { /* Given a function func , and given distinct initial points ax and bx , this routine searches in
                   1980: the downhill direction (defined by the function as evaluated at the initial points) and returns
                   1981: new points ax , bx , cx that bracket a minimum of the function. Also returned are the function
                   1982: values at the three points, fa, fb , and fc such that fa > fb and fb < fc.
                   1983:    */
1.126     brouard  1984:   double ulim,u,r,q, dum;
                   1985:   double fu; 
1.187     brouard  1986: 
                   1987:   double scale=10.;
                   1988:   int iterscale=0;
                   1989: 
                   1990:   *fa=(*func)(*ax); /*  xta[j]=pcom[j]+(*ax)*xicom[j]; fa=f(xta[j])*/
                   1991:   *fb=(*func)(*bx); /*  xtb[j]=pcom[j]+(*bx)*xicom[j]; fb=f(xtb[j]) */
                   1992: 
                   1993: 
                   1994:   /* while(*fb != *fb){ /\* *ax should be ok, reducing distance to *ax *\/ */
                   1995:   /*   printf("Warning mnbrak *fb = %lf, *bx=%lf *ax=%lf *fa==%lf iter=%d\n",*fb, *bx, *ax, *fa, iterscale++); */
                   1996:   /*   *bx = *ax - (*ax - *bx)/scale; */
                   1997:   /*   *fb=(*func)(*bx);  /\*  xtb[j]=pcom[j]+(*bx)*xicom[j]; fb=f(xtb[j]) *\/ */
                   1998:   /* } */
                   1999: 
1.126     brouard  2000:   if (*fb > *fa) { 
                   2001:     SHFT(dum,*ax,*bx,dum) 
1.183     brouard  2002:     SHFT(dum,*fb,*fa,dum) 
                   2003:   } 
1.126     brouard  2004:   *cx=(*bx)+GOLD*(*bx-*ax); 
                   2005:   *fc=(*func)(*cx); 
1.183     brouard  2006: #ifdef DEBUG
1.224     brouard  2007:   printf("mnbrak0 a=%lf *fa=%lf, b=%lf *fb=%lf, c=%lf *fc=%lf\n",*ax,*fa,*bx,*fb,*cx, *fc);
                   2008:   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  2009: #endif
1.224     brouard  2010:   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  2011:     r=(*bx-*ax)*(*fb-*fc); 
1.224     brouard  2012:     q=(*bx-*cx)*(*fb-*fa); /* What if fa=inf */
1.126     brouard  2013:     u=(*bx)-((*bx-*cx)*q-(*bx-*ax)*r)/ 
1.183     brouard  2014:       (2.0*SIGN(FMAX(fabs(q-r),TINY),q-r)); /* Minimum abscissa of a parabolic estimated from (a,fa), (b,fb) and (c,fc). */
                   2015:     ulim=(*bx)+GLIMIT*(*cx-*bx); /* Maximum abscissa where function should be evaluated */
                   2016:     if ((*bx-u)*(u-*cx) > 0.0) { /* if u_p is between b and c */
1.126     brouard  2017:       fu=(*func)(u); 
1.163     brouard  2018: #ifdef DEBUG
                   2019:       /* f(x)=A(x-u)**2+f(u) */
                   2020:       double A, fparabu; 
                   2021:       A= (*fb - *fa)/(*bx-*ax)/(*bx+*ax-2*u);
                   2022:       fparabu= *fa - A*(*ax-u)*(*ax-u);
1.224     brouard  2023:       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);
                   2024:       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  2025:       /* And thus,it can be that fu > *fc even if fparabu < *fc */
                   2026:       /* mnbrak (*ax=7.666299858533, *fa=299039.693133272231), (*bx=8.595447774979, *fb=298976.598289369489),
                   2027:         (*cx=10.098840694817, *fc=298946.631474258087),  (*u=9.852501168332, fu=298948.773013752128, fparabu=298945.434711494134) */
                   2028:       /* In that case, there is no bracket in the output! Routine is wrong with many consequences.*/
1.163     brouard  2029: #endif 
1.184     brouard  2030: #ifdef MNBRAKORIGINAL
1.183     brouard  2031: #else
1.191     brouard  2032: /*       if (fu > *fc) { */
                   2033: /* #ifdef DEBUG */
                   2034: /*       printf("mnbrak4  fu > fc \n"); */
                   2035: /*       fprintf(ficlog, "mnbrak4 fu > fc\n"); */
                   2036: /* #endif */
                   2037: /*     /\* 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 *\\/  *\/ */
                   2038: /*     /\* SHFT(*fa,*fc,fu,*fc) /\\* (b, u, c) is a bracket while test fb > fc will be fu > fc  will exit *\\/ *\/ */
                   2039: /*     dum=u; /\* Shifting c and u *\/ */
                   2040: /*     u = *cx; */
                   2041: /*     *cx = dum; */
                   2042: /*     dum = fu; */
                   2043: /*     fu = *fc; */
                   2044: /*     *fc =dum; */
                   2045: /*       } else { /\* end *\/ */
                   2046: /* #ifdef DEBUG */
                   2047: /*       printf("mnbrak3  fu < fc \n"); */
                   2048: /*       fprintf(ficlog, "mnbrak3 fu < fc\n"); */
                   2049: /* #endif */
                   2050: /*     dum=u; /\* Shifting c and u *\/ */
                   2051: /*     u = *cx; */
                   2052: /*     *cx = dum; */
                   2053: /*     dum = fu; */
                   2054: /*     fu = *fc; */
                   2055: /*     *fc =dum; */
                   2056: /*       } */
1.224     brouard  2057: #ifdef DEBUGMNBRAK
                   2058:                 double A, fparabu; 
                   2059:      A= (*fb - *fa)/(*bx-*ax)/(*bx+*ax-2*u);
                   2060:      fparabu= *fa - A*(*ax-u)*(*ax-u);
                   2061:      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);
                   2062:      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  2063: #endif
1.191     brouard  2064:       dum=u; /* Shifting c and u */
                   2065:       u = *cx;
                   2066:       *cx = dum;
                   2067:       dum = fu;
                   2068:       fu = *fc;
                   2069:       *fc =dum;
1.183     brouard  2070: #endif
1.162     brouard  2071:     } else if ((*cx-u)*(u-ulim) > 0.0) { /* u is after c but before ulim */
1.183     brouard  2072: #ifdef DEBUG
1.224     brouard  2073:       printf("\nmnbrak2  u=%lf after c=%lf but before ulim\n",u,*cx);
                   2074:       fprintf(ficlog,"\nmnbrak2  u=%lf after c=%lf but before ulim\n",u,*cx);
1.183     brouard  2075: #endif
1.126     brouard  2076:       fu=(*func)(u); 
                   2077:       if (fu < *fc) { 
1.183     brouard  2078: #ifdef DEBUG
1.224     brouard  2079:                                printf("\nmnbrak2  u=%lf after c=%lf but before ulim=%lf AND fu=%lf < %lf=fc\n",u,*cx,ulim,fu, *fc);
                   2080:                          fprintf(ficlog,"\nmnbrak2  u=%lf after c=%lf but before ulim=%lf AND fu=%lf < %lf=fc\n",u,*cx,ulim,fu, *fc);
                   2081: #endif
                   2082:                          SHFT(*bx,*cx,u,*cx+GOLD*(*cx-*bx)) 
                   2083:                                SHFT(*fb,*fc,fu,(*func)(u)) 
                   2084: #ifdef DEBUG
                   2085:                                        printf("\nmnbrak2 shift GOLD c=%lf",*cx+GOLD*(*cx-*bx));
1.183     brouard  2086: #endif
                   2087:       } 
1.162     brouard  2088:     } else if ((u-ulim)*(ulim-*cx) >= 0.0) { /* u outside ulim (verifying that ulim is beyond c) */
1.183     brouard  2089: #ifdef DEBUG
1.224     brouard  2090:       printf("\nmnbrak2  u=%lf outside ulim=%lf (verifying that ulim is beyond c=%lf)\n",u,ulim,*cx);
                   2091:       fprintf(ficlog,"\nmnbrak2  u=%lf outside ulim=%lf (verifying that ulim is beyond c=%lf)\n",u,ulim,*cx);
1.183     brouard  2092: #endif
1.126     brouard  2093:       u=ulim; 
                   2094:       fu=(*func)(u); 
1.183     brouard  2095:     } else { /* u could be left to b (if r > q parabola has a maximum) */
                   2096: #ifdef DEBUG
1.224     brouard  2097:       printf("\nmnbrak2  u=%lf could be left to b=%lf (if r=%lf > q=%lf parabola has a maximum)\n",u,*bx,r,q);
                   2098:       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  2099: #endif
1.126     brouard  2100:       u=(*cx)+GOLD*(*cx-*bx); 
                   2101:       fu=(*func)(u); 
1.224     brouard  2102: #ifdef DEBUG
                   2103:       printf("\nmnbrak2 new u=%lf fu=%lf shifted gold left from c=%lf and b=%lf \n",u,fu,*cx,*bx);
                   2104:       fprintf(ficlog,"\nmnbrak2 new u=%lf fu=%lf shifted gold left from c=%lf and b=%lf \n",u,fu,*cx,*bx);
                   2105: #endif
1.183     brouard  2106:     } /* end tests */
1.126     brouard  2107:     SHFT(*ax,*bx,*cx,u) 
1.183     brouard  2108:     SHFT(*fa,*fb,*fc,fu) 
                   2109: #ifdef DEBUG
1.224     brouard  2110:       printf("\nmnbrak2 shift (*ax=%.12f, *fa=%.12lf), (*bx=%.12f, *fb=%.12lf), (*cx=%.12f, *fc=%.12lf)\n",*ax,*fa,*bx,*fb,*cx,*fc);
                   2111:       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  2112: #endif
                   2113:   } /* 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  2114: } 
                   2115: 
                   2116: /*************** linmin ************************/
1.162     brouard  2117: /* Given an n -dimensional point p[1..n] and an n -dimensional direction xi[1..n] , moves and
                   2118: resets p to where the function func(p) takes on a minimum along the direction xi from p ,
                   2119: and replaces xi by the actual vector displacement that p was moved. Also returns as fret
                   2120: the value of func at the returned location p . This is actually all accomplished by calling the
                   2121: routines mnbrak and brent .*/
1.126     brouard  2122: int ncom; 
                   2123: double *pcom,*xicom;
                   2124: double (*nrfunc)(double []); 
                   2125:  
1.224     brouard  2126: #ifdef LINMINORIGINAL
1.126     brouard  2127: void linmin(double p[], double xi[], int n, double *fret,double (*func)(double [])) 
1.224     brouard  2128: #else
                   2129: void linmin(double p[], double xi[], int n, double *fret,double (*func)(double []), int *flat) 
                   2130: #endif
1.126     brouard  2131: { 
                   2132:   double brent(double ax, double bx, double cx, 
                   2133:               double (*f)(double), double tol, double *xmin); 
                   2134:   double f1dim(double x); 
                   2135:   void mnbrak(double *ax, double *bx, double *cx, double *fa, double *fb, 
                   2136:              double *fc, double (*func)(double)); 
                   2137:   int j; 
                   2138:   double xx,xmin,bx,ax; 
                   2139:   double fx,fb,fa;
1.187     brouard  2140: 
1.203     brouard  2141: #ifdef LINMINORIGINAL
                   2142: #else
                   2143:   double scale=10., axs, xxs; /* Scale added for infinity */
                   2144: #endif
                   2145:   
1.126     brouard  2146:   ncom=n; 
                   2147:   pcom=vector(1,n); 
                   2148:   xicom=vector(1,n); 
                   2149:   nrfunc=func; 
                   2150:   for (j=1;j<=n;j++) { 
                   2151:     pcom[j]=p[j]; 
1.202     brouard  2152:     xicom[j]=xi[j]; /* Former scale xi[j] of currrent direction i */
1.126     brouard  2153:   } 
1.187     brouard  2154: 
1.203     brouard  2155: #ifdef LINMINORIGINAL
                   2156:   xx=1.;
                   2157: #else
                   2158:   axs=0.0;
                   2159:   xxs=1.;
                   2160:   do{
                   2161:     xx= xxs;
                   2162: #endif
1.187     brouard  2163:     ax=0.;
                   2164:     mnbrak(&ax,&xx,&bx,&fa,&fx,&fb,f1dim);  /* Outputs: xtx[j]=pcom[j]+(*xx)*xicom[j]; fx=f(xtx[j]) */
                   2165:     /* brackets with inputs ax=0 and xx=1, but points, pcom=p, and directions values, xicom=xi, are sent via f1dim(x) */
                   2166:     /* 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))   */
                   2167:     /* Outputs: fa=f(p(j)) and fx=f(p(j) + xxs * xi(j) ) and f(bx)= f(p(j)+ bx* xi(j)) */
                   2168:     /* Given input ax=axs and xx=xxs, xx might be too far from ax to get a finite f(xx) */
                   2169:     /* Searches on line, outputs (ax, xx, bx) such that fx < min(fa and fb) */
                   2170:     /* 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  2171: #ifdef LINMINORIGINAL
                   2172: #else
                   2173:     if (fx != fx){
1.224     brouard  2174:                        xxs=xxs/scale; /* Trying a smaller xx, closer to initial ax=0 */
                   2175:                        printf("|");
                   2176:                        fprintf(ficlog,"|");
1.203     brouard  2177: #ifdef DEBUGLINMIN
1.224     brouard  2178:                        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  2179: #endif
                   2180:     }
1.224     brouard  2181:   }while(fx != fx && xxs > 1.e-5);
1.203     brouard  2182: #endif
                   2183:   
1.191     brouard  2184: #ifdef DEBUGLINMIN
                   2185:   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  2186:   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  2187: #endif
1.224     brouard  2188: #ifdef LINMINORIGINAL
                   2189: #else
                   2190:        if(fb == fx){ /* Flat function in the direction */
                   2191:                xmin=xx;
                   2192:     *flat=1;
                   2193:        }else{
                   2194:     *flat=0;
                   2195: #endif
                   2196:                /*Flat mnbrak2 shift (*ax=0.000000000000, *fa=51626.272983130431), (*bx=-1.618034000000, *fb=51590.149499362531), (*cx=-4.236068025156, *fc=51590.149499362531) */
1.187     brouard  2197:   *fret=brent(ax,xx,bx,f1dim,TOL,&xmin); /* Giving a bracketting triplet (ax, xx, bx), find a minimum, xmin, according to f1dim, *fret(xmin),*/
                   2198:   /* fa = f(p[j] + ax * xi[j]), fx = f(p[j] + xx * xi[j]), fb = f(p[j] + bx * xi[j]) */
                   2199:   /* fmin = f(p[j] + xmin * xi[j]) */
                   2200:   /* P+lambda n in that direction (lambdamin), with TOL between abscisses */
                   2201:   /* f1dim(xmin): for (j=1;j<=ncom;j++) xt[j]=pcom[j]+xmin*xicom[j]; */
1.126     brouard  2202: #ifdef DEBUG
1.224     brouard  2203:   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);
                   2204:   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);
                   2205: #endif
                   2206: #ifdef LINMINORIGINAL
                   2207: #else
                   2208:                        }
1.126     brouard  2209: #endif
1.191     brouard  2210: #ifdef DEBUGLINMIN
                   2211:   printf("linmin end ");
1.202     brouard  2212:   fprintf(ficlog,"linmin end ");
1.191     brouard  2213: #endif
1.126     brouard  2214:   for (j=1;j<=n;j++) { 
1.203     brouard  2215: #ifdef LINMINORIGINAL
                   2216:     xi[j] *= xmin; 
                   2217: #else
                   2218: #ifdef DEBUGLINMIN
                   2219:     if(xxs <1.0)
                   2220:       printf(" before xi[%d]=%12.8f", j,xi[j]);
                   2221: #endif
                   2222:     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) */
                   2223: #ifdef DEBUGLINMIN
                   2224:     if(xxs <1.0)
                   2225:       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 );
                   2226: #endif
                   2227: #endif
1.187     brouard  2228:     p[j] += xi[j]; /* Parameters values are updated accordingly */
1.126     brouard  2229:   } 
1.191     brouard  2230: #ifdef DEBUGLINMIN
1.203     brouard  2231:   printf("\n");
1.191     brouard  2232:   printf("Comparing last *frec(xmin=%12.8f)=%12.8f from Brent and frec(0.)=%12.8f \n", xmin, *fret, (*func)(p));
1.202     brouard  2233:   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  2234:   for (j=1;j<=n;j++) { 
1.202     brouard  2235:     printf(" xi[%d]= %14.10f p[%d]= %12.7f",j,xi[j],j,p[j]);
                   2236:     fprintf(ficlog," xi[%d]= %14.10f p[%d]= %12.7f",j,xi[j],j,p[j]);
                   2237:     if(j % ncovmodel == 0){
1.191     brouard  2238:       printf("\n");
1.202     brouard  2239:       fprintf(ficlog,"\n");
                   2240:     }
1.191     brouard  2241:   }
1.203     brouard  2242: #else
1.191     brouard  2243: #endif
1.126     brouard  2244:   free_vector(xicom,1,n); 
                   2245:   free_vector(pcom,1,n); 
                   2246: } 
                   2247: 
                   2248: 
                   2249: /*************** powell ************************/
1.162     brouard  2250: /*
                   2251: Minimization of a function func of n variables. Input consists of an initial starting point
                   2252: p[1..n] ; an initial matrix xi[1..n][1..n] , whose columns contain the initial set of di-
                   2253: rections (usually the n unit vectors); and ftol , the fractional tolerance in the function value
                   2254: such that failure to decrease by more than this amount on one iteration signals doneness. On
                   2255: output, p is set to the best point found, xi is the then-current direction set, fret is the returned
                   2256: function value at p , and iter is the number of iterations taken. The routine linmin is used.
                   2257:  */
1.224     brouard  2258: #ifdef LINMINORIGINAL
                   2259: #else
                   2260:        int *flatdir; /* Function is vanishing in that direction */
1.225     brouard  2261:        int flat=0, flatd=0; /* Function is vanishing in that direction */
1.224     brouard  2262: #endif
1.126     brouard  2263: void powell(double p[], double **xi, int n, double ftol, int *iter, double *fret, 
                   2264:            double (*func)(double [])) 
                   2265: { 
1.224     brouard  2266: #ifdef LINMINORIGINAL
                   2267:  void linmin(double p[], double xi[], int n, double *fret, 
1.126     brouard  2268:              double (*func)(double [])); 
1.224     brouard  2269: #else 
1.241     brouard  2270:  void linmin(double p[], double xi[], int n, double *fret,
                   2271:             double (*func)(double []),int *flat); 
1.224     brouard  2272: #endif
1.239     brouard  2273:  int i,ibig,j,jk,k; 
1.126     brouard  2274:   double del,t,*pt,*ptt,*xit;
1.181     brouard  2275:   double directest;
1.126     brouard  2276:   double fp,fptt;
                   2277:   double *xits;
                   2278:   int niterf, itmp;
1.224     brouard  2279: #ifdef LINMINORIGINAL
                   2280: #else
                   2281: 
                   2282:   flatdir=ivector(1,n); 
                   2283:   for (j=1;j<=n;j++) flatdir[j]=0; 
                   2284: #endif
1.126     brouard  2285: 
                   2286:   pt=vector(1,n); 
                   2287:   ptt=vector(1,n); 
                   2288:   xit=vector(1,n); 
                   2289:   xits=vector(1,n); 
                   2290:   *fret=(*func)(p); 
                   2291:   for (j=1;j<=n;j++) pt[j]=p[j]; 
1.202     brouard  2292:   rcurr_time = time(NULL);  
1.126     brouard  2293:   for (*iter=1;;++(*iter)) { 
1.187     brouard  2294:     fp=(*fret); /* From former iteration or initial value */
1.126     brouard  2295:     ibig=0; 
                   2296:     del=0.0; 
1.157     brouard  2297:     rlast_time=rcurr_time;
                   2298:     /* (void) gettimeofday(&curr_time,&tzp); */
                   2299:     rcurr_time = time(NULL);  
                   2300:     curr_time = *localtime(&rcurr_time);
                   2301:     printf("\nPowell iter=%d -2*LL=%.12f %ld sec. %ld sec.",*iter,*fret, rcurr_time-rlast_time, rcurr_time-rstart_time);fflush(stdout);
                   2302:     fprintf(ficlog,"\nPowell iter=%d -2*LL=%.12f %ld sec. %ld sec.",*iter,*fret,rcurr_time-rlast_time, rcurr_time-rstart_time); fflush(ficlog);
                   2303: /*     fprintf(ficrespow,"%d %.12f %ld",*iter,*fret,curr_time.tm_sec-start_time.tm_sec); */
1.192     brouard  2304:     for (i=1;i<=n;i++) {
1.126     brouard  2305:       fprintf(ficrespow," %.12lf", p[i]);
                   2306:     }
1.239     brouard  2307:     fprintf(ficrespow,"\n");fflush(ficrespow);
                   2308:     printf("\n#model=  1      +     age ");
                   2309:     fprintf(ficlog,"\n#model=  1      +     age ");
                   2310:     if(nagesqr==1){
1.241     brouard  2311:        printf("  + age*age  ");
                   2312:        fprintf(ficlog,"  + age*age  ");
1.239     brouard  2313:     }
                   2314:     for(j=1;j <=ncovmodel-2;j++){
                   2315:       if(Typevar[j]==0) {
                   2316:        printf("  +      V%d  ",Tvar[j]);
                   2317:        fprintf(ficlog,"  +      V%d  ",Tvar[j]);
                   2318:       }else if(Typevar[j]==1) {
                   2319:        printf("  +    V%d*age ",Tvar[j]);
                   2320:        fprintf(ficlog,"  +    V%d*age ",Tvar[j]);
                   2321:       }else if(Typevar[j]==2) {
                   2322:        printf("  +    V%d*V%d ",Tvard[Tposprod[j]][1],Tvard[Tposprod[j]][2]);
                   2323:        fprintf(ficlog,"  +    V%d*V%d ",Tvard[Tposprod[j]][1],Tvard[Tposprod[j]][2]);
                   2324:       }
                   2325:     }
1.126     brouard  2326:     printf("\n");
1.239     brouard  2327: /*     printf("12   47.0114589    0.0154322   33.2424412    0.3279905    2.3731903  */
                   2328: /* 13  -21.5392400    0.1118147    1.2680506    1.2973408   -1.0663662  */
1.126     brouard  2329:     fprintf(ficlog,"\n");
1.239     brouard  2330:     for(i=1,jk=1; i <=nlstate; i++){
                   2331:       for(k=1; k <=(nlstate+ndeath); k++){
                   2332:        if (k != i) {
                   2333:          printf("%d%d ",i,k);
                   2334:          fprintf(ficlog,"%d%d ",i,k);
                   2335:          for(j=1; j <=ncovmodel; j++){
                   2336:            printf("%12.7f ",p[jk]);
                   2337:            fprintf(ficlog,"%12.7f ",p[jk]);
                   2338:            jk++; 
                   2339:          }
                   2340:          printf("\n");
                   2341:          fprintf(ficlog,"\n");
                   2342:        }
                   2343:       }
                   2344:     }
1.241     brouard  2345:     if(*iter <=3 && *iter >1){
1.157     brouard  2346:       tml = *localtime(&rcurr_time);
                   2347:       strcpy(strcurr,asctime(&tml));
                   2348:       rforecast_time=rcurr_time; 
1.126     brouard  2349:       itmp = strlen(strcurr);
                   2350:       if(strcurr[itmp-1]=='\n')  /* Windows outputs with a new line */
1.241     brouard  2351:        strcurr[itmp-1]='\0';
1.162     brouard  2352:       printf("\nConsidering the time needed for the last iteration #%d: %ld seconds,\n",*iter,rcurr_time-rlast_time);
1.157     brouard  2353:       fprintf(ficlog,"\nConsidering the time needed for this last iteration #%d: %ld seconds,\n",*iter,rcurr_time-rlast_time);
1.126     brouard  2354:       for(niterf=10;niterf<=30;niterf+=10){
1.241     brouard  2355:        rforecast_time=rcurr_time+(niterf-*iter)*(rcurr_time-rlast_time);
                   2356:        forecast_time = *localtime(&rforecast_time);
                   2357:        strcpy(strfor,asctime(&forecast_time));
                   2358:        itmp = strlen(strfor);
                   2359:        if(strfor[itmp-1]=='\n')
                   2360:          strfor[itmp-1]='\0';
                   2361:        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);
                   2362:        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  2363:       }
                   2364:     }
1.187     brouard  2365:     for (i=1;i<=n;i++) { /* For each direction i */
                   2366:       for (j=1;j<=n;j++) xit[j]=xi[j][i]; /* Directions stored from previous iteration with previous scales */
1.126     brouard  2367:       fptt=(*fret); 
                   2368: #ifdef DEBUG
1.203     brouard  2369:       printf("fret=%lf, %lf, %lf \n", *fret, *fret, *fret);
                   2370:       fprintf(ficlog, "fret=%lf, %lf, %lf \n", *fret, *fret, *fret);
1.126     brouard  2371: #endif
1.203     brouard  2372:       printf("%d",i);fflush(stdout); /* print direction (parameter) i */
1.126     brouard  2373:       fprintf(ficlog,"%d",i);fflush(ficlog);
1.224     brouard  2374: #ifdef LINMINORIGINAL
1.188     brouard  2375:       linmin(p,xit,n,fret,func); /* Point p[n]. xit[n] has been loaded for direction i as input.*/
1.224     brouard  2376: #else
                   2377:       linmin(p,xit,n,fret,func,&flat); /* Point p[n]. xit[n] has been loaded for direction i as input.*/
                   2378:                        flatdir[i]=flat; /* Function is vanishing in that direction i */
                   2379: #endif
                   2380:                        /* Outputs are fret(new point p) p is updated and xit rescaled */
1.188     brouard  2381:       if (fabs(fptt-(*fret)) > del) { /* We are keeping the max gain on each of the n directions */
1.224     brouard  2382:                                /* because that direction will be replaced unless the gain del is small */
                   2383:                                /* in comparison with the 'probable' gain, mu^2, with the last average direction. */
                   2384:                                /* Unless the n directions are conjugate some gain in the determinant may be obtained */
                   2385:                                /* with the new direction. */
                   2386:                                del=fabs(fptt-(*fret)); 
                   2387:                                ibig=i; 
1.126     brouard  2388:       } 
                   2389: #ifdef DEBUG
                   2390:       printf("%d %.12e",i,(*fret));
                   2391:       fprintf(ficlog,"%d %.12e",i,(*fret));
                   2392:       for (j=1;j<=n;j++) {
1.224     brouard  2393:                                xits[j]=FMAX(fabs(p[j]-pt[j]),1.e-5);
                   2394:                                printf(" x(%d)=%.12e",j,xit[j]);
                   2395:                                fprintf(ficlog," x(%d)=%.12e",j,xit[j]);
1.126     brouard  2396:       }
                   2397:       for(j=1;j<=n;j++) {
1.225     brouard  2398:                                printf(" p(%d)=%.12e",j,p[j]);
                   2399:                                fprintf(ficlog," p(%d)=%.12e",j,p[j]);
1.126     brouard  2400:       }
                   2401:       printf("\n");
                   2402:       fprintf(ficlog,"\n");
                   2403: #endif
1.187     brouard  2404:     } /* end loop on each direction i */
                   2405:     /* Convergence test will use last linmin estimation (fret) and compare former iteration (fp) */ 
1.188     brouard  2406:     /* But p and xit have been updated at the end of linmin, *fret corresponds to new p, xit  */
1.187     brouard  2407:     /* New value of last point Pn is not computed, P(n-1) */
1.224     brouard  2408:       for(j=1;j<=n;j++) {
1.225     brouard  2409:                                if(flatdir[j] >0){
                   2410:                                        printf(" p(%d)=%lf flat=%d ",j,p[j],flatdir[j]);
                   2411:                                        fprintf(ficlog," p(%d)=%lf flat=%d ",j,p[j],flatdir[j]);
                   2412:                                }
                   2413:                                /* printf("\n"); */
                   2414:                                /* fprintf(ficlog,"\n"); */
                   2415:                        }
1.243     brouard  2416:     /* if (2.0*fabs(fp-(*fret)) <= ftol*(fabs(fp)+fabs(*fret))) { /\* Did we reach enough precision? *\/ */
                   2417:     if (2.0*fabs(fp-(*fret)) <= ftol) { /* Did we reach enough precision? */
1.188     brouard  2418:       /* We could compare with a chi^2. chisquare(0.95,ddl=1)=3.84 */
                   2419:       /* By adding age*age in a model, the new -2LL should be lower and the difference follows a */
                   2420:       /* a chisquare statistics with 1 degree. To be significant at the 95% level, it should have */
                   2421:       /* decreased of more than 3.84  */
                   2422:       /* By adding age*age and V1*age the gain (-2LL) should be more than 5.99 (ddl=2) */
                   2423:       /* By using V1+V2+V3, the gain should be  7.82, compared with basic 1+age. */
                   2424:       /* By adding 10 parameters more the gain should be 18.31 */
1.224     brouard  2425:                        
1.188     brouard  2426:       /* Starting the program with initial values given by a former maximization will simply change */
                   2427:       /* the scales of the directions and the directions, because the are reset to canonical directions */
                   2428:       /* Thus the first calls to linmin will give new points and better maximizations until fp-(*fret) is */
                   2429:       /* under the tolerance value. If the tolerance is very small 1.e-9, it could last long.  */
1.126     brouard  2430: #ifdef DEBUG
                   2431:       int k[2],l;
                   2432:       k[0]=1;
                   2433:       k[1]=-1;
                   2434:       printf("Max: %.12e",(*func)(p));
                   2435:       fprintf(ficlog,"Max: %.12e",(*func)(p));
                   2436:       for (j=1;j<=n;j++) {
                   2437:        printf(" %.12e",p[j]);
                   2438:        fprintf(ficlog," %.12e",p[j]);
                   2439:       }
                   2440:       printf("\n");
                   2441:       fprintf(ficlog,"\n");
                   2442:       for(l=0;l<=1;l++) {
                   2443:        for (j=1;j<=n;j++) {
                   2444:          ptt[j]=p[j]+(p[j]-pt[j])*k[l];
                   2445:          printf("l=%d j=%d ptt=%.12e, xits=%.12e, p=%.12e, xit=%.12e", l,j,ptt[j],xits[j],p[j],xit[j]);
                   2446:          fprintf(ficlog,"l=%d j=%d ptt=%.12e, xits=%.12e, p=%.12e, xit=%.12e", l,j,ptt[j],xits[j],p[j],xit[j]);
                   2447:        }
                   2448:        printf("func(ptt)=%.12e, deriv=%.12e\n",(*func)(ptt),(ptt[j]-p[j])/((*func)(ptt)-(*func)(p)));
                   2449:        fprintf(ficlog,"func(ptt)=%.12e, deriv=%.12e\n",(*func)(ptt),(ptt[j]-p[j])/((*func)(ptt)-(*func)(p)));
                   2450:       }
                   2451: #endif
                   2452: 
1.224     brouard  2453: #ifdef LINMINORIGINAL
                   2454: #else
                   2455:       free_ivector(flatdir,1,n); 
                   2456: #endif
1.126     brouard  2457:       free_vector(xit,1,n); 
                   2458:       free_vector(xits,1,n); 
                   2459:       free_vector(ptt,1,n); 
                   2460:       free_vector(pt,1,n); 
                   2461:       return; 
1.192     brouard  2462:     } /* enough precision */ 
1.240     brouard  2463:     if (*iter == ITMAX*n) nrerror("powell exceeding maximum iterations."); 
1.181     brouard  2464:     for (j=1;j<=n;j++) { /* Computes the extrapolated point P_0 + 2 (P_n-P_0) */
1.126     brouard  2465:       ptt[j]=2.0*p[j]-pt[j]; 
                   2466:       xit[j]=p[j]-pt[j]; 
                   2467:       pt[j]=p[j]; 
                   2468:     } 
1.181     brouard  2469:     fptt=(*func)(ptt); /* f_3 */
1.224     brouard  2470: #ifdef NODIRECTIONCHANGEDUNTILNITER  /* No change in drections until some iterations are done */
                   2471:                if (*iter <=4) {
1.225     brouard  2472: #else
                   2473: #endif
1.224     brouard  2474: #ifdef POWELLNOF3INFF1TEST    /* skips test F3 <F1 */
1.192     brouard  2475: #else
1.161     brouard  2476:     if (fptt < fp) { /* If extrapolated point is better, decide if we keep that new direction or not */
1.192     brouard  2477: #endif
1.162     brouard  2478:       /* (x1 f1=fp), (x2 f2=*fret), (x3 f3=fptt), (xm fm) */
1.161     brouard  2479:       /* From x1 (P0) distance of x2 is at h and x3 is 2h */
1.162     brouard  2480:       /* Let f"(x2) be the 2nd derivative equal everywhere.  */
                   2481:       /* Then the parabolic through (x1,f1), (x2,f2) and (x3,f3) */
                   2482:       /* will reach at f3 = fm + h^2/2 f"m  ; f" = (f1 -2f2 +f3 ) / h**2 */
1.224     brouard  2483:       /* Conditional for using this new direction is that mu^2 = (f1-2f2+f3)^2 /2 < del or directest <0 */
                   2484:       /* also  lamda^2=(f1-f2)^2/mu² is a parasite solution of powell */
                   2485:       /* For powell, inclusion of this average direction is only if t(del)<0 or del inbetween mu^2 and lambda^2 */
1.161     brouard  2486:       /* t=2.0*(fp-2.0*(*fret)+fptt)*SQR(fp-(*fret)-del)-del*SQR(fp-fptt); */
1.224     brouard  2487:       /*  Even if f3 <f1, directest can be negative and t >0 */
                   2488:       /* mu² and del² are equal when f3=f1 */
                   2489:                        /* f3 < f1 : mu² < del <= lambda^2 both test are equivalent */
                   2490:                        /* f3 < f1 : mu² < lambda^2 < del then directtest is negative and powell t is positive */
                   2491:                        /* f3 > f1 : lambda² < mu^2 < del then t is negative and directest >0  */
                   2492:                        /* f3 > f1 : lambda² < del < mu^2 then t is positive and directest >0  */
1.183     brouard  2493: #ifdef NRCORIGINAL
                   2494:       t=2.0*(fp-2.0*(*fret)+fptt)*SQR(fp-(*fret)-del)- del*SQR(fp-fptt); /* Original Numerical Recipes in C*/
                   2495: #else
                   2496:       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  2497:       t= t- del*SQR(fp-fptt);
1.183     brouard  2498: #endif
1.202     brouard  2499:       directest = fp-2.0*(*fret)+fptt - 2.0 * del; /* If delta was big enough we change it for a new direction */
1.161     brouard  2500: #ifdef DEBUG
1.181     brouard  2501:       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);
                   2502:       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  2503:       printf("t3= %.12lf, t4= %.12lf, t3*= %.12lf, t4*= %.12lf\n",SQR(fp-(*fret)-del),SQR(fp-fptt),
                   2504:             (fp-(*fret)-del)*(fp-(*fret)-del),(fp-fptt)*(fp-fptt));
                   2505:       fprintf(ficlog,"t3= %.12lf, t4= %.12lf, t3*= %.12lf, t4*= %.12lf\n",SQR(fp-(*fret)-del),SQR(fp-fptt),
                   2506:             (fp-(*fret)-del)*(fp-(*fret)-del),(fp-fptt)*(fp-fptt));
                   2507:       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);
                   2508:       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);
                   2509: #endif
1.183     brouard  2510: #ifdef POWELLORIGINAL
                   2511:       if (t < 0.0) { /* Then we use it for new direction */
                   2512: #else
1.182     brouard  2513:       if (directest*t < 0.0) { /* Contradiction between both tests */
1.224     brouard  2514:                                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  2515:         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  2516:         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  2517:         fprintf(ficlog,"f1-2f2+f3= %.12lf, f1-f2-del= %.12lf, f1-f3= %.12lf\n",fp-2.0*(*fret)+fptt, fp -(*fret) -del, fp-fptt);
                   2518:       } 
1.181     brouard  2519:       if (directest < 0.0) { /* Then we use it for new direction */
                   2520: #endif
1.191     brouard  2521: #ifdef DEBUGLINMIN
1.234     brouard  2522:        printf("Before linmin in direction P%d-P0\n",n);
                   2523:        for (j=1;j<=n;j++) {
                   2524:          printf(" Before xit[%d]= %12.7f p[%d]= %12.7f",j,xit[j],j,p[j]);
                   2525:          fprintf(ficlog," Before xit[%d]= %12.7f p[%d]= %12.7f",j,xit[j],j,p[j]);
                   2526:          if(j % ncovmodel == 0){
                   2527:            printf("\n");
                   2528:            fprintf(ficlog,"\n");
                   2529:          }
                   2530:        }
1.224     brouard  2531: #endif
                   2532: #ifdef LINMINORIGINAL
1.234     brouard  2533:        linmin(p,xit,n,fret,func); /* computes minimum on the extrapolated direction: changes p and rescales xit.*/
1.224     brouard  2534: #else
1.234     brouard  2535:        linmin(p,xit,n,fret,func,&flat); /* computes minimum on the extrapolated direction: changes p and rescales xit.*/
                   2536:        flatdir[i]=flat; /* Function is vanishing in that direction i */
1.191     brouard  2537: #endif
1.234     brouard  2538:        
1.191     brouard  2539: #ifdef DEBUGLINMIN
1.234     brouard  2540:        for (j=1;j<=n;j++) { 
                   2541:          printf("After xit[%d]= %12.7f p[%d]= %12.7f",j,xit[j],j,p[j]);
                   2542:          fprintf(ficlog,"After xit[%d]= %12.7f p[%d]= %12.7f",j,xit[j],j,p[j]);
                   2543:          if(j % ncovmodel == 0){
                   2544:            printf("\n");
                   2545:            fprintf(ficlog,"\n");
                   2546:          }
                   2547:        }
1.224     brouard  2548: #endif
1.234     brouard  2549:        for (j=1;j<=n;j++) { 
                   2550:          xi[j][ibig]=xi[j][n]; /* Replace direction with biggest decrease by last direction n */
                   2551:          xi[j][n]=xit[j];      /* and this nth direction by the by the average p_0 p_n */
                   2552:        }
1.224     brouard  2553: #ifdef LINMINORIGINAL
                   2554: #else
1.234     brouard  2555:        for (j=1, flatd=0;j<=n;j++) {
                   2556:          if(flatdir[j]>0)
                   2557:            flatd++;
                   2558:        }
                   2559:        if(flatd >0){
1.255     brouard  2560:          printf("%d flat directions: ",flatd);
                   2561:          fprintf(ficlog,"%d flat directions :",flatd);
1.234     brouard  2562:          for (j=1;j<=n;j++) { 
                   2563:            if(flatdir[j]>0){
                   2564:              printf("%d ",j);
                   2565:              fprintf(ficlog,"%d ",j);
                   2566:            }
                   2567:          }
                   2568:          printf("\n");
                   2569:          fprintf(ficlog,"\n");
                   2570:        }
1.191     brouard  2571: #endif
1.234     brouard  2572:        printf("Gaining to use new average direction of P0 P%d instead of biggest increase direction %d :\n",n,ibig);
                   2573:        fprintf(ficlog,"Gaining to use new average direction of P0 P%d instead of biggest increase direction %d :\n",n,ibig);
                   2574:        
1.126     brouard  2575: #ifdef DEBUG
1.234     brouard  2576:        printf("Direction changed  last moved %d in place of ibig=%d, new last is the average:\n",n,ibig);
                   2577:        fprintf(ficlog,"Direction changed  last moved %d in place of ibig=%d, new last is the average:\n",n,ibig);
                   2578:        for(j=1;j<=n;j++){
                   2579:          printf(" %lf",xit[j]);
                   2580:          fprintf(ficlog," %lf",xit[j]);
                   2581:        }
                   2582:        printf("\n");
                   2583:        fprintf(ficlog,"\n");
1.126     brouard  2584: #endif
1.192     brouard  2585:       } /* end of t or directest negative */
1.224     brouard  2586: #ifdef POWELLNOF3INFF1TEST
1.192     brouard  2587: #else
1.234     brouard  2588:       } /* end if (fptt < fp)  */
1.192     brouard  2589: #endif
1.225     brouard  2590: #ifdef NODIRECTIONCHANGEDUNTILNITER  /* No change in drections until some iterations are done */
1.234     brouard  2591:     } /*NODIRECTIONCHANGEDUNTILNITER  No change in drections until some iterations are done */
1.225     brouard  2592: #else
1.224     brouard  2593: #endif
1.234     brouard  2594:                } /* loop iteration */ 
1.126     brouard  2595: } 
1.234     brouard  2596:   
1.126     brouard  2597: /**** Prevalence limit (stable or period prevalence)  ****************/
1.234     brouard  2598:   
1.235     brouard  2599:   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  2600:   {
1.279     brouard  2601:     /**< Computes the prevalence limit in each live state at age x and for covariate combination ij 
                   2602:      *   (and selected quantitative values in nres)
                   2603:      *  by left multiplying the unit
                   2604:      *  matrix by transitions matrix until convergence is reached with precision ftolpl 
                   2605:      * Wx= Wx-1 Px-1= Wx-2 Px-2 Px-1  = Wx-n Px-n ... Px-2 Px-1 I
                   2606:      * Wx is row vector: population in state 1, population in state 2, population dead
                   2607:      * or prevalence in state 1, prevalence in state 2, 0
                   2608:      * newm is the matrix after multiplications, its rows are identical at a factor.
                   2609:      * Inputs are the parameter, age, a tolerance for the prevalence limit ftolpl.
                   2610:      * Output is prlim.
                   2611:      * Initial matrix pimij 
                   2612:      */
1.206     brouard  2613:   /* {0.85204250825084937, 0.13044499163996345, 0.017512500109187184, */
                   2614:   /* 0.090851990222114765, 0.88271245433047185, 0.026435555447413338, */
                   2615:   /*  0,                   0                  , 1} */
                   2616:   /*
                   2617:    * and after some iteration: */
                   2618:   /* {0.45504275246439968, 0.42731458730878791, 0.11764266022681241, */
                   2619:   /*  0.45201005341706885, 0.42865420071559901, 0.11933574586733192, */
                   2620:   /*  0,                   0                  , 1} */
                   2621:   /* And prevalence by suppressing the deaths are close to identical rows in prlim: */
                   2622:   /* {0.51571254859325999, 0.4842874514067399, */
                   2623:   /*  0.51326036147820708, 0.48673963852179264} */
                   2624:   /* If we start from prlim again, prlim tends to a constant matrix */
1.234     brouard  2625:     
1.126     brouard  2626:   int i, ii,j,k;
1.209     brouard  2627:   double *min, *max, *meandiff, maxmax,sumnew=0.;
1.145     brouard  2628:   /* double **matprod2(); */ /* test */
1.218     brouard  2629:   double **out, cov[NCOVMAX+1], **pmij(); /* **pmmij is a global variable feeded with oldms etc */
1.126     brouard  2630:   double **newm;
1.209     brouard  2631:   double agefin, delaymax=200. ; /* 100 Max number of years to converge */
1.203     brouard  2632:   int ncvloop=0;
1.288     brouard  2633:   int first=0;
1.169     brouard  2634:   
1.209     brouard  2635:   min=vector(1,nlstate);
                   2636:   max=vector(1,nlstate);
                   2637:   meandiff=vector(1,nlstate);
                   2638: 
1.218     brouard  2639:        /* Starting with matrix unity */
1.126     brouard  2640:   for (ii=1;ii<=nlstate+ndeath;ii++)
                   2641:     for (j=1;j<=nlstate+ndeath;j++){
                   2642:       oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   2643:     }
1.169     brouard  2644:   
                   2645:   cov[1]=1.;
                   2646:   
                   2647:   /* Even if hstepm = 1, at least one multiplication by the unit matrix */
1.202     brouard  2648:   /* Start at agefin= age, computes the matrix of passage and loops decreasing agefin until convergence is reached */
1.126     brouard  2649:   for(agefin=age-stepm/YEARM; agefin>=age-delaymax; agefin=agefin-stepm/YEARM){
1.202     brouard  2650:     ncvloop++;
1.126     brouard  2651:     newm=savm;
                   2652:     /* Covariates have to be included here again */
1.138     brouard  2653:     cov[2]=agefin;
1.187     brouard  2654:     if(nagesqr==1)
                   2655:       cov[3]= agefin*agefin;;
1.234     brouard  2656:     for (k=1; k<=nsd;k++) { /* For single dummy covariates only */
                   2657:                        /* Here comes the value of the covariate 'ij' after renumbering k with single dummy covariates */
                   2658:       cov[2+nagesqr+TvarsDind[k]]=nbcode[TvarsD[k]][codtabm(ij,k)];
1.235     brouard  2659:       /* 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  2660:     }
                   2661:     for (k=1; k<=nsq;k++) { /* For single varying covariates only */
                   2662:                        /* Here comes the value of quantitative after renumbering k with single quantitative covariates */
1.235     brouard  2663:       cov[2+nagesqr+TvarsQind[k]]=Tqresult[nres][k]; 
                   2664:       /* 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  2665:     }
1.237     brouard  2666:     for (k=1; k<=cptcovage;k++){  /* For product with age */
1.234     brouard  2667:       if(Dummy[Tvar[Tage[k]]]){
                   2668:        cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,k)]*cov[2];
                   2669:       } else{
1.235     brouard  2670:        cov[2+nagesqr+Tage[k]]=Tqresult[nres][k]; 
1.234     brouard  2671:       }
1.235     brouard  2672:       /* 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  2673:     }
1.237     brouard  2674:     for (k=1; k<=cptcovprod;k++){ /* For product without age */
1.235     brouard  2675:       /* 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  2676:       if(Dummy[Tvard[k][1]==0]){
                   2677:        if(Dummy[Tvard[k][2]==0]){
                   2678:          cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)] * nbcode[Tvard[k][2]][codtabm(ij,k)];
                   2679:        }else{
                   2680:          cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)] * Tqresult[nres][k];
                   2681:        }
                   2682:       }else{
                   2683:        if(Dummy[Tvard[k][2]==0]){
                   2684:          cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][2]][codtabm(ij,k)] * Tqinvresult[nres][Tvard[k][1]];
                   2685:        }else{
                   2686:          cov[2+nagesqr+Tprod[k]]=Tqinvresult[nres][Tvard[k][1]]*  Tqinvresult[nres][Tvard[k][2]];
                   2687:        }
                   2688:       }
1.234     brouard  2689:     }
1.138     brouard  2690:     /*printf("ij=%d cptcovprod=%d tvar=%d ", ij, cptcovprod, Tvar[1]);*/
                   2691:     /*printf("ij=%d cov[3]=%lf cov[4]=%lf \n",ij, cov[3],cov[4]);*/
                   2692:     /*printf("ij=%d cov[3]=%lf \n",ij, cov[3]);*/
1.145     brouard  2693:     /* savm=pmij(pmmij,cov,ncovmodel,x,nlstate); */
                   2694:     /* out=matprod2(newm, pmij(pmmij,cov,ncovmodel,x,nlstate),1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm); /\* Bug Valgrind *\/ */
1.218     brouard  2695:                /* age and covariate values of ij are in 'cov' */
1.142     brouard  2696:     out=matprod2(newm, pmij(pmmij,cov,ncovmodel,x,nlstate),1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm); /* Bug Valgrind */
1.138     brouard  2697:     
1.126     brouard  2698:     savm=oldm;
                   2699:     oldm=newm;
1.209     brouard  2700: 
                   2701:     for(j=1; j<=nlstate; j++){
                   2702:       max[j]=0.;
                   2703:       min[j]=1.;
                   2704:     }
                   2705:     for(i=1;i<=nlstate;i++){
                   2706:       sumnew=0;
                   2707:       for(k=1; k<=ndeath; k++) sumnew+=newm[i][nlstate+k];
                   2708:       for(j=1; j<=nlstate; j++){ 
                   2709:        prlim[i][j]= newm[i][j]/(1-sumnew);
                   2710:        max[j]=FMAX(max[j],prlim[i][j]);
                   2711:        min[j]=FMIN(min[j],prlim[i][j]);
                   2712:       }
                   2713:     }
                   2714: 
1.126     brouard  2715:     maxmax=0.;
1.209     brouard  2716:     for(j=1; j<=nlstate; j++){
                   2717:       meandiff[j]=(max[j]-min[j])/(max[j]+min[j])*2.; /* mean difference for each column */
                   2718:       maxmax=FMAX(maxmax,meandiff[j]);
                   2719:       /* 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  2720:     } /* j loop */
1.203     brouard  2721:     *ncvyear= (int)age- (int)agefin;
1.208     brouard  2722:     /* 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  2723:     if(maxmax < ftolpl){
1.209     brouard  2724:       /* printf("maxmax=%lf ncvloop=%ld, age=%d, agefin=%d ncvyear=%d \n", maxmax, ncvloop, (int)age, (int)agefin, *ncvyear); */
                   2725:       free_vector(min,1,nlstate);
                   2726:       free_vector(max,1,nlstate);
                   2727:       free_vector(meandiff,1,nlstate);
1.126     brouard  2728:       return prlim;
                   2729:     }
1.288     brouard  2730:   } /* agefin loop */
1.208     brouard  2731:     /* After some age loop it doesn't converge */
1.288     brouard  2732:   if(!first){
                   2733:     first=1;
                   2734:     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);
                   2735:   }
                   2736:   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);
                   2737: 
1.209     brouard  2738:   /* 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); */
                   2739:   free_vector(min,1,nlstate);
                   2740:   free_vector(max,1,nlstate);
                   2741:   free_vector(meandiff,1,nlstate);
1.208     brouard  2742:   
1.169     brouard  2743:   return prlim; /* should not reach here */
1.126     brouard  2744: }
                   2745: 
1.217     brouard  2746: 
                   2747:  /**** Back Prevalence limit (stable or period prevalence)  ****************/
                   2748: 
1.218     brouard  2749:  /* 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) */
                   2750:  /* 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  2751:   double **bprevalim(double **bprlim, double ***prevacurrent, int nlstate, double x[], double age, double ftolpl, int *ncvyear, int ij, int nres)
1.217     brouard  2752: {
1.264     brouard  2753:   /* 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  2754:      matrix by transitions matrix until convergence is reached with precision ftolpl */
                   2755:   /* Wx= Wx-1 Px-1= Wx-2 Px-2 Px-1  = Wx-n Px-n ... Px-2 Px-1 I */
                   2756:   /* Wx is row vector: population in state 1, population in state 2, population dead */
                   2757:   /* or prevalence in state 1, prevalence in state 2, 0 */
                   2758:   /* newm is the matrix after multiplications, its rows are identical at a factor */
                   2759:   /* Initial matrix pimij */
                   2760:   /* {0.85204250825084937, 0.13044499163996345, 0.017512500109187184, */
                   2761:   /* 0.090851990222114765, 0.88271245433047185, 0.026435555447413338, */
                   2762:   /*  0,                   0                  , 1} */
                   2763:   /*
                   2764:    * and after some iteration: */
                   2765:   /* {0.45504275246439968, 0.42731458730878791, 0.11764266022681241, */
                   2766:   /*  0.45201005341706885, 0.42865420071559901, 0.11933574586733192, */
                   2767:   /*  0,                   0                  , 1} */
                   2768:   /* And prevalence by suppressing the deaths are close to identical rows in prlim: */
                   2769:   /* {0.51571254859325999, 0.4842874514067399, */
                   2770:   /*  0.51326036147820708, 0.48673963852179264} */
                   2771:   /* If we start from prlim again, prlim tends to a constant matrix */
                   2772: 
                   2773:   int i, ii,j,k;
1.247     brouard  2774:   int first=0;
1.217     brouard  2775:   double *min, *max, *meandiff, maxmax,sumnew=0.;
                   2776:   /* double **matprod2(); */ /* test */
                   2777:   double **out, cov[NCOVMAX+1], **bmij();
                   2778:   double **newm;
1.218     brouard  2779:   double        **dnewm, **doldm, **dsavm;  /* for use */
                   2780:   double        **oldm, **savm;  /* for use */
                   2781: 
1.217     brouard  2782:   double agefin, delaymax=200. ; /* 100 Max number of years to converge */
                   2783:   int ncvloop=0;
                   2784:   
                   2785:   min=vector(1,nlstate);
                   2786:   max=vector(1,nlstate);
                   2787:   meandiff=vector(1,nlstate);
                   2788: 
1.266     brouard  2789:   dnewm=ddnewms; doldm=ddoldms; dsavm=ddsavms;
                   2790:   oldm=oldms; savm=savms;
                   2791:   
                   2792:   /* Starting with matrix unity */
                   2793:   for (ii=1;ii<=nlstate+ndeath;ii++)
                   2794:     for (j=1;j<=nlstate+ndeath;j++){
1.217     brouard  2795:       oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   2796:     }
                   2797:   
                   2798:   cov[1]=1.;
                   2799:   
                   2800:   /* Even if hstepm = 1, at least one multiplication by the unit matrix */
                   2801:   /* Start at agefin= age, computes the matrix of passage and loops decreasing agefin until convergence is reached */
1.218     brouard  2802:   /* for(agefin=age+stepm/YEARM; agefin<=age+delaymax; agefin=agefin+stepm/YEARM){ /\* A changer en age *\/ */
1.288     brouard  2803:   /* for(agefin=age; agefin<AGESUP; agefin=agefin+stepm/YEARM){ /\* A changer en age *\/ */
                   2804:   for(agefin=age; agefin<FMIN(AGESUP,age+delaymax); agefin=agefin+stepm/YEARM){ /* A changer en age */
1.217     brouard  2805:     ncvloop++;
1.218     brouard  2806:     newm=savm; /* oldm should be kept from previous iteration or unity at start */
                   2807:                /* newm points to the allocated table savm passed by the function it can be written, savm could be reallocated */
1.217     brouard  2808:     /* Covariates have to be included here again */
                   2809:     cov[2]=agefin;
                   2810:     if(nagesqr==1)
                   2811:       cov[3]= agefin*agefin;;
1.242     brouard  2812:     for (k=1; k<=nsd;k++) { /* For single dummy covariates only */
                   2813:                        /* Here comes the value of the covariate 'ij' after renumbering k with single dummy covariates */
                   2814:       cov[2+nagesqr+TvarsDind[k]]=nbcode[TvarsD[k]][codtabm(ij,k)];
1.264     brouard  2815:       /* 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  2816:     }
                   2817:     /* for (k=1; k<=cptcovn;k++) { */
                   2818:     /*   /\* cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,Tvar[k])]; *\/ */
                   2819:     /*   cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,k)]; */
                   2820:     /*   /\* 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])]); *\/ */
                   2821:     /* } */
                   2822:     for (k=1; k<=nsq;k++) { /* For single varying covariates only */
                   2823:                        /* Here comes the value of quantitative after renumbering k with single quantitative covariates */
                   2824:       cov[2+nagesqr+TvarsQind[k]]=Tqresult[nres][k]; 
                   2825:       /* 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]); */
                   2826:     }
                   2827:     /* for (k=1; k<=cptcovage;k++) cov[2+nagesqr+Tage[k]]=nbcode[Tvar[k]][codtabm(ij,k)]*cov[2]; */
                   2828:     /* for (k=1; k<=cptcovprod;k++) /\* Useless *\/ */
                   2829:     /*   /\* cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,Tvard[k][1])] * nbcode[Tvard[k][2]][codtabm(ij,Tvard[k][2])]; *\/ */
                   2830:     /*   cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)] * nbcode[Tvard[k][2]][codtabm(ij,k)]; */
                   2831:     for (k=1; k<=cptcovage;k++){  /* For product with age */
                   2832:       if(Dummy[Tvar[Tage[k]]]){
                   2833:        cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,k)]*cov[2];
                   2834:       } else{
                   2835:        cov[2+nagesqr+Tage[k]]=Tqresult[nres][k]; 
                   2836:       }
                   2837:       /* 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]); */
                   2838:     }
                   2839:     for (k=1; k<=cptcovprod;k++){ /* For product without age */
                   2840:       /* 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]); */
                   2841:       if(Dummy[Tvard[k][1]==0]){
                   2842:        if(Dummy[Tvard[k][2]==0]){
                   2843:          cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)] * nbcode[Tvard[k][2]][codtabm(ij,k)];
                   2844:        }else{
                   2845:          cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)] * Tqresult[nres][k];
                   2846:        }
                   2847:       }else{
                   2848:        if(Dummy[Tvard[k][2]==0]){
                   2849:          cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][2]][codtabm(ij,k)] * Tqinvresult[nres][Tvard[k][1]];
                   2850:        }else{
                   2851:          cov[2+nagesqr+Tprod[k]]=Tqinvresult[nres][Tvard[k][1]]*  Tqinvresult[nres][Tvard[k][2]];
                   2852:        }
                   2853:       }
1.217     brouard  2854:     }
                   2855:     
                   2856:     /*printf("ij=%d cptcovprod=%d tvar=%d ", ij, cptcovprod, Tvar[1]);*/
                   2857:     /*printf("ij=%d cov[3]=%lf cov[4]=%lf \n",ij, cov[3],cov[4]);*/
                   2858:     /*printf("ij=%d cov[3]=%lf \n",ij, cov[3]);*/
                   2859:     /* savm=pmij(pmmij,cov,ncovmodel,x,nlstate); */
                   2860:     /* out=matprod2(newm, pmij(pmmij,cov,ncovmodel,x,nlstate),1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm); /\* Bug Valgrind *\/ */
1.218     brouard  2861:                /* ij should be linked to the correct index of cov */
                   2862:                /* age and covariate values ij are in 'cov', but we need to pass
                   2863:                 * ij for the observed prevalence at age and status and covariate
                   2864:                 * number:  prevacurrent[(int)agefin][ii][ij]
                   2865:                 */
                   2866:     /* 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 *\/ */
                   2867:     /* 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 *\/ */
                   2868:     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  2869:     /* if((int)age == 86 || (int)age == 87){ */
1.266     brouard  2870:     /*   printf(" Backward prevalim age=%d agefin=%d \n", (int) age, (int) agefin); */
                   2871:     /*   for(i=1; i<=nlstate+ndeath; i++) { */
                   2872:     /*         printf("%d newm= ",i); */
                   2873:     /*         for(j=1;j<=nlstate+ndeath;j++) { */
                   2874:     /*           printf("%f ",newm[i][j]); */
                   2875:     /*         } */
                   2876:     /*         printf("oldm * "); */
                   2877:     /*         for(j=1;j<=nlstate+ndeath;j++) { */
                   2878:     /*           printf("%f ",oldm[i][j]); */
                   2879:     /*         } */
1.268     brouard  2880:     /*         printf(" bmmij "); */
1.266     brouard  2881:     /*         for(j=1;j<=nlstate+ndeath;j++) { */
                   2882:     /*           printf("%f ",pmmij[i][j]); */
                   2883:     /*         } */
                   2884:     /*         printf("\n"); */
                   2885:     /*   } */
                   2886:     /* } */
1.217     brouard  2887:     savm=oldm;
                   2888:     oldm=newm;
1.266     brouard  2889: 
1.217     brouard  2890:     for(j=1; j<=nlstate; j++){
                   2891:       max[j]=0.;
                   2892:       min[j]=1.;
                   2893:     }
                   2894:     for(j=1; j<=nlstate; j++){ 
                   2895:       for(i=1;i<=nlstate;i++){
1.234     brouard  2896:        /* bprlim[i][j]= newm[i][j]/(1-sumnew); */
                   2897:        bprlim[i][j]= newm[i][j];
                   2898:        max[i]=FMAX(max[i],bprlim[i][j]); /* Max in line */
                   2899:        min[i]=FMIN(min[i],bprlim[i][j]);
1.217     brouard  2900:       }
                   2901:     }
1.218     brouard  2902:                
1.217     brouard  2903:     maxmax=0.;
                   2904:     for(i=1; i<=nlstate; i++){
                   2905:       meandiff[i]=(max[i]-min[i])/(max[i]+min[i])*2.; /* mean difference for each column */
                   2906:       maxmax=FMAX(maxmax,meandiff[i]);
                   2907:       /* 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  2908:     } /* i loop */
1.217     brouard  2909:     *ncvyear= -( (int)age- (int)agefin);
1.268     brouard  2910:     /* printf("Back maxmax=%lf ncvloop=%d, age=%d, agefin=%d ncvyear=%d \n", maxmax, ncvloop, (int)age, (int)agefin, *ncvyear); */
1.217     brouard  2911:     if(maxmax < ftolpl){
1.220     brouard  2912:       /* printf("OK Back maxmax=%lf ncvloop=%d, age=%d, agefin=%d ncvyear=%d \n", maxmax, ncvloop, (int)age, (int)agefin, *ncvyear); */
1.217     brouard  2913:       free_vector(min,1,nlstate);
                   2914:       free_vector(max,1,nlstate);
                   2915:       free_vector(meandiff,1,nlstate);
                   2916:       return bprlim;
                   2917:     }
1.288     brouard  2918:   } /* agefin loop */
1.217     brouard  2919:     /* After some age loop it doesn't converge */
1.288     brouard  2920:   if(!first){
1.247     brouard  2921:     first=1;
                   2922:     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\
                   2923: 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);
                   2924:   }
                   2925:   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  2926: 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);
                   2927:   /* 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); */
                   2928:   free_vector(min,1,nlstate);
                   2929:   free_vector(max,1,nlstate);
                   2930:   free_vector(meandiff,1,nlstate);
                   2931:   
                   2932:   return bprlim; /* should not reach here */
                   2933: }
                   2934: 
1.126     brouard  2935: /*************** transition probabilities ***************/ 
                   2936: 
                   2937: double **pmij(double **ps, double *cov, int ncovmodel, double *x, int nlstate )
                   2938: {
1.138     brouard  2939:   /* According to parameters values stored in x and the covariate's values stored in cov,
1.266     brouard  2940:      computes the probability to be observed in state j (after stepm years) being in state i by appying the
1.138     brouard  2941:      model to the ncovmodel covariates (including constant and age).
                   2942:      lnpijopii=ln(pij/pii)= aij+bij*age+cij*v1+dij*v2+... = sum_nc=1^ncovmodel xij(nc)*cov[nc]
                   2943:      and, according on how parameters are entered, the position of the coefficient xij(nc) of the
                   2944:      ncth covariate in the global vector x is given by the formula:
                   2945:      j<i nc+((i-1)*(nlstate+ndeath-1)+j-1)*ncovmodel
                   2946:      j>=i nc + ((i-1)*(nlstate+ndeath-1)+(j-2))*ncovmodel
                   2947:      Computes ln(pij/pii) (lnpijopii), deduces pij/pii by exponentiation,
                   2948:      sums on j different of i to get 1-pii/pii, deduces pii, and then all pij.
1.266     brouard  2949:      Outputs ps[i][j] or probability to be observed in j being in i according to
1.138     brouard  2950:      the values of the covariates cov[nc] and corresponding parameter values x[nc+shiftij]
1.266     brouard  2951:      Sum on j ps[i][j] should equal to 1.
1.138     brouard  2952:   */
                   2953:   double s1, lnpijopii;
1.126     brouard  2954:   /*double t34;*/
1.164     brouard  2955:   int i,j, nc, ii, jj;
1.126     brouard  2956: 
1.223     brouard  2957:   for(i=1; i<= nlstate; i++){
                   2958:     for(j=1; j<i;j++){
                   2959:       for (nc=1, lnpijopii=0.;nc <=ncovmodel; nc++){
                   2960:        /*lnpijopii += param[i][j][nc]*cov[nc];*/
                   2961:        lnpijopii += x[nc+((i-1)*(nlstate+ndeath-1)+j-1)*ncovmodel]*cov[nc];
                   2962:        /*       printf("Int j<i s1=%.17e, lnpijopii=%.17e\n",s1,lnpijopii); */
                   2963:       }
                   2964:       ps[i][j]=lnpijopii; /* In fact ln(pij/pii) */
                   2965:       /*       printf("s1=%.17e, lnpijopii=%.17e\n",s1,lnpijopii); */
                   2966:     }
                   2967:     for(j=i+1; j<=nlstate+ndeath;j++){
                   2968:       for (nc=1, lnpijopii=0.;nc <=ncovmodel; nc++){
                   2969:        /*lnpijopii += x[(i-1)*nlstate*ncovmodel+(j-2)*ncovmodel+nc+(i-1)*(ndeath-1)*ncovmodel]*cov[nc];*/
                   2970:        lnpijopii += x[nc + ((i-1)*(nlstate+ndeath-1)+(j-2))*ncovmodel]*cov[nc];
                   2971:        /*        printf("Int j>i s1=%.17e, lnpijopii=%.17e %lx %lx\n",s1,lnpijopii,s1,lnpijopii); */
                   2972:       }
                   2973:       ps[i][j]=lnpijopii; /* In fact ln(pij/pii) */
                   2974:     }
                   2975:   }
1.218     brouard  2976:   
1.223     brouard  2977:   for(i=1; i<= nlstate; i++){
                   2978:     s1=0;
                   2979:     for(j=1; j<i; j++){
                   2980:       s1+=exp(ps[i][j]); /* In fact sums pij/pii */
                   2981:       /*printf("debug1 %d %d ps=%lf exp(ps)=%lf s1+=%lf\n",i,j,ps[i][j],exp(ps[i][j]),s1); */
                   2982:     }
                   2983:     for(j=i+1; j<=nlstate+ndeath; j++){
                   2984:       s1+=exp(ps[i][j]); /* In fact sums pij/pii */
                   2985:       /*printf("debug2 %d %d ps=%lf exp(ps)=%lf s1+=%lf\n",i,j,ps[i][j],exp(ps[i][j]),s1); */
                   2986:     }
                   2987:     /* s1= sum_{j<>i} pij/pii=(1-pii)/pii and thus pii is known from s1 */
                   2988:     ps[i][i]=1./(s1+1.);
                   2989:     /* Computing other pijs */
                   2990:     for(j=1; j<i; j++)
                   2991:       ps[i][j]= exp(ps[i][j])*ps[i][i];
                   2992:     for(j=i+1; j<=nlstate+ndeath; j++)
                   2993:       ps[i][j]= exp(ps[i][j])*ps[i][i];
                   2994:     /* ps[i][nlstate+1]=1.-s1- ps[i][i];*/ /* Sum should be 1 */
                   2995:   } /* end i */
1.218     brouard  2996:   
1.223     brouard  2997:   for(ii=nlstate+1; ii<= nlstate+ndeath; ii++){
                   2998:     for(jj=1; jj<= nlstate+ndeath; jj++){
                   2999:       ps[ii][jj]=0;
                   3000:       ps[ii][ii]=1;
                   3001:     }
                   3002:   }
1.294     brouard  3003: 
                   3004: 
1.223     brouard  3005:   /* for(ii=1; ii<= nlstate+ndeath; ii++){ */
                   3006:   /*   for(jj=1; jj<= nlstate+ndeath; jj++){ */
                   3007:   /*   printf(" pmij  ps[%d][%d]=%lf ",ii,jj,ps[ii][jj]); */
                   3008:   /*   } */
                   3009:   /*   printf("\n "); */
                   3010:   /* } */
                   3011:   /* printf("\n ");printf("%lf ",cov[2]);*/
                   3012:   /*
                   3013:     for(i=1; i<= npar; i++) printf("%f ",x[i]);
1.218     brouard  3014:                goto end;*/
1.266     brouard  3015:   return ps; /* Pointer is unchanged since its call */
1.126     brouard  3016: }
                   3017: 
1.218     brouard  3018: /*************** backward transition probabilities ***************/ 
                   3019: 
                   3020:  /* 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 ) */
                   3021: /* double **bmij(double **ps, double *cov, int ncovmodel, double *x, int nlstate,  double ***prevacurrent, double ***dnewm, double **doldm, double **dsavm, int ij ) */
                   3022:  double **bmij(double **ps, double *cov, int ncovmodel, double *x, int nlstate,  double ***prevacurrent, int ij )
                   3023: {
1.266     brouard  3024:   /* Computes the backward probability at age agefin and covariate combination ij. In fact cov is already filled and x too.
                   3025:    * 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  3026:    */
1.218     brouard  3027:   int i, ii, j,k;
1.222     brouard  3028:   
                   3029:   double **out, **pmij();
                   3030:   double sumnew=0.;
1.218     brouard  3031:   double agefin;
1.292     brouard  3032:   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  3033:   double **dnewm, **dsavm, **doldm;
                   3034:   double **bbmij;
                   3035:   
1.218     brouard  3036:   doldm=ddoldms; /* global pointers */
1.222     brouard  3037:   dnewm=ddnewms;
                   3038:   dsavm=ddsavms;
                   3039:   
                   3040:   agefin=cov[2];
1.268     brouard  3041:   /* Bx = Diag(w_x) P_x Diag(Sum_i w^i_x p^ij_x */
1.222     brouard  3042:   /* bmij *//* age is cov[2], ij is included in cov, but we need for
1.266     brouard  3043:      the observed prevalence (with this covariate ij) at beginning of transition */
                   3044:   /* dsavm=pmij(pmmij,cov,ncovmodel,x,nlstate); */
1.268     brouard  3045: 
                   3046:   /* P_x */
1.266     brouard  3047:   pmmij=pmij(pmmij,cov,ncovmodel,x,nlstate); /*This is forward probability from agefin to agefin + stepm */
1.268     brouard  3048:   /* outputs pmmij which is a stochastic matrix in row */
                   3049: 
                   3050:   /* Diag(w_x) */
1.292     brouard  3051:   /* Rescaling the cross-sectional prevalence: Problem with prevacurrent which can be zero */
1.268     brouard  3052:   sumnew=0.;
1.269     brouard  3053:   /*for (ii=1;ii<=nlstate+ndeath;ii++){*/
1.268     brouard  3054:   for (ii=1;ii<=nlstate;ii++){ /* Only on live states */
1.297     brouard  3055:     /* printf(" agefin=%d, ii=%d, ij=%d, prev=%f\n",(int)agefin,ii, ij, prevacurrent[(int)agefin][ii][ij]); */
1.268     brouard  3056:     sumnew+=prevacurrent[(int)agefin][ii][ij];
                   3057:   }
                   3058:   if(sumnew >0.01){  /* At least some value in the prevalence */
                   3059:     for (ii=1;ii<=nlstate+ndeath;ii++){
                   3060:       for (j=1;j<=nlstate+ndeath;j++)
1.269     brouard  3061:        doldm[ii][j]=(ii==j ? prevacurrent[(int)agefin][ii][ij]/sumnew : 0.0);
1.268     brouard  3062:     }
                   3063:   }else{
                   3064:     for (ii=1;ii<=nlstate+ndeath;ii++){
                   3065:       for (j=1;j<=nlstate+ndeath;j++)
                   3066:       doldm[ii][j]=(ii==j ? 1./nlstate : 0.0);
                   3067:     }
                   3068:     /* if(sumnew <0.9){ */
                   3069:     /*   printf("Problem internal bmij B: sum on i wi <0.9: j=%d, sum_i wi=%lf,agefin=%d\n",j,sumnew, (int)agefin); */
                   3070:     /* } */
                   3071:   }
                   3072:   k3=0.0;  /* We put the last diagonal to 0 */
                   3073:   for (ii=nlstate+1;ii<=nlstate+ndeath;ii++){
                   3074:       doldm[ii][ii]= k3;
                   3075:   }
                   3076:   /* End doldm, At the end doldm is diag[(w_i)] */
                   3077:   
1.292     brouard  3078:   /* Left product of this diag matrix by pmmij=Px (dnewm=dsavm*doldm): diag[(w_i)*Px */
                   3079:   bbmij=matprod2(dnewm, doldm,1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, pmmij); /* was a Bug Valgrind */
1.268     brouard  3080: 
1.292     brouard  3081:   /* Diag(Sum_i w^i_x p^ij_x, should be the prevalence at age x+stepm */
1.268     brouard  3082:   /* 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  3083:   for (j=1;j<=nlstate+ndeath;j++){
1.268     brouard  3084:     sumnew=0.;
1.222     brouard  3085:     for (ii=1;ii<=nlstate;ii++){
1.266     brouard  3086:       /* sumnew+=dsavm[ii][j]*prevacurrent[(int)agefin][ii][ij]; */
1.268     brouard  3087:       sumnew+=pmmij[ii][j]*doldm[ii][ii]; /* Yes prevalence at beginning of transition */
1.222     brouard  3088:     } /* sumnew is (N11+N21)/N..= N.1/N.. = sum on i of w_i pij */
1.268     brouard  3089:     for (ii=1;ii<=nlstate+ndeath;ii++){
1.222     brouard  3090:        /* if(agefin >= agemaxpar && agefin <= agemaxpar+stepm/YEARM){ */
1.268     brouard  3091:        /*      dsavm[ii][j]=(ii==j ? 1./sumnew : 0.0); */
1.222     brouard  3092:        /* }else if(agefin >= agemaxpar+stepm/YEARM){ */
1.268     brouard  3093:        /*      dsavm[ii][j]=(ii==j ? 1./sumnew : 0.0); */
1.222     brouard  3094:        /* }else */
1.268     brouard  3095:       dsavm[ii][j]=(ii==j ? 1./sumnew : 0.0);
                   3096:     } /*End ii */
                   3097:   } /* 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 */
                   3098: 
1.292     brouard  3099:   ps=matprod2(ps, dnewm,1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, dsavm); /* was a Bug Valgrind */
1.268     brouard  3100:   /* ps is now diag[w_i] * Px * diag [1/(w_1p1i+w_2 p2i)] */
1.222     brouard  3101:   /* end bmij */
1.266     brouard  3102:   return ps; /*pointer is unchanged */
1.218     brouard  3103: }
1.217     brouard  3104: /*************** transition probabilities ***************/ 
                   3105: 
1.218     brouard  3106: double **bpmij(double **ps, double *cov, int ncovmodel, double *x, int nlstate )
1.217     brouard  3107: {
                   3108:   /* According to parameters values stored in x and the covariate's values stored in cov,
                   3109:      computes the probability to be observed in state j being in state i by appying the
                   3110:      model to the ncovmodel covariates (including constant and age).
                   3111:      lnpijopii=ln(pij/pii)= aij+bij*age+cij*v1+dij*v2+... = sum_nc=1^ncovmodel xij(nc)*cov[nc]
                   3112:      and, according on how parameters are entered, the position of the coefficient xij(nc) of the
                   3113:      ncth covariate in the global vector x is given by the formula:
                   3114:      j<i nc+((i-1)*(nlstate+ndeath-1)+j-1)*ncovmodel
                   3115:      j>=i nc + ((i-1)*(nlstate+ndeath-1)+(j-2))*ncovmodel
                   3116:      Computes ln(pij/pii) (lnpijopii), deduces pij/pii by exponentiation,
                   3117:      sums on j different of i to get 1-pii/pii, deduces pii, and then all pij.
                   3118:      Outputs ps[i][j] the probability to be observed in j being in j according to
                   3119:      the values of the covariates cov[nc] and corresponding parameter values x[nc+shiftij]
                   3120:   */
                   3121:   double s1, lnpijopii;
                   3122:   /*double t34;*/
                   3123:   int i,j, nc, ii, jj;
                   3124: 
1.234     brouard  3125:   for(i=1; i<= nlstate; i++){
                   3126:     for(j=1; j<i;j++){
                   3127:       for (nc=1, lnpijopii=0.;nc <=ncovmodel; nc++){
                   3128:        /*lnpijopii += param[i][j][nc]*cov[nc];*/
                   3129:        lnpijopii += x[nc+((i-1)*(nlstate+ndeath-1)+j-1)*ncovmodel]*cov[nc];
                   3130:        /*       printf("Int j<i s1=%.17e, lnpijopii=%.17e\n",s1,lnpijopii); */
                   3131:       }
                   3132:       ps[i][j]=lnpijopii; /* In fact ln(pij/pii) */
                   3133:       /*       printf("s1=%.17e, lnpijopii=%.17e\n",s1,lnpijopii); */
                   3134:     }
                   3135:     for(j=i+1; j<=nlstate+ndeath;j++){
                   3136:       for (nc=1, lnpijopii=0.;nc <=ncovmodel; nc++){
                   3137:        /*lnpijopii += x[(i-1)*nlstate*ncovmodel+(j-2)*ncovmodel+nc+(i-1)*(ndeath-1)*ncovmodel]*cov[nc];*/
                   3138:        lnpijopii += x[nc + ((i-1)*(nlstate+ndeath-1)+(j-2))*ncovmodel]*cov[nc];
                   3139:        /*        printf("Int j>i s1=%.17e, lnpijopii=%.17e %lx %lx\n",s1,lnpijopii,s1,lnpijopii); */
                   3140:       }
                   3141:       ps[i][j]=lnpijopii; /* In fact ln(pij/pii) */
                   3142:     }
                   3143:   }
                   3144:   
                   3145:   for(i=1; i<= nlstate; i++){
                   3146:     s1=0;
                   3147:     for(j=1; j<i; j++){
                   3148:       s1+=exp(ps[i][j]); /* In fact sums pij/pii */
                   3149:       /*printf("debug1 %d %d ps=%lf exp(ps)=%lf s1+=%lf\n",i,j,ps[i][j],exp(ps[i][j]),s1); */
                   3150:     }
                   3151:     for(j=i+1; j<=nlstate+ndeath; j++){
                   3152:       s1+=exp(ps[i][j]); /* In fact sums pij/pii */
                   3153:       /*printf("debug2 %d %d ps=%lf exp(ps)=%lf s1+=%lf\n",i,j,ps[i][j],exp(ps[i][j]),s1); */
                   3154:     }
                   3155:     /* s1= sum_{j<>i} pij/pii=(1-pii)/pii and thus pii is known from s1 */
                   3156:     ps[i][i]=1./(s1+1.);
                   3157:     /* Computing other pijs */
                   3158:     for(j=1; j<i; j++)
                   3159:       ps[i][j]= exp(ps[i][j])*ps[i][i];
                   3160:     for(j=i+1; j<=nlstate+ndeath; j++)
                   3161:       ps[i][j]= exp(ps[i][j])*ps[i][i];
                   3162:     /* ps[i][nlstate+1]=1.-s1- ps[i][i];*/ /* Sum should be 1 */
                   3163:   } /* end i */
                   3164:   
                   3165:   for(ii=nlstate+1; ii<= nlstate+ndeath; ii++){
                   3166:     for(jj=1; jj<= nlstate+ndeath; jj++){
                   3167:       ps[ii][jj]=0;
                   3168:       ps[ii][ii]=1;
                   3169:     }
                   3170:   }
1.296     brouard  3171:   /* Added for prevbcast */ /* Transposed matrix too */
1.234     brouard  3172:   for(jj=1; jj<= nlstate+ndeath; jj++){
                   3173:     s1=0.;
                   3174:     for(ii=1; ii<= nlstate+ndeath; ii++){
                   3175:       s1+=ps[ii][jj];
                   3176:     }
                   3177:     for(ii=1; ii<= nlstate; ii++){
                   3178:       ps[ii][jj]=ps[ii][jj]/s1;
                   3179:     }
                   3180:   }
                   3181:   /* Transposition */
                   3182:   for(jj=1; jj<= nlstate+ndeath; jj++){
                   3183:     for(ii=jj; ii<= nlstate+ndeath; ii++){
                   3184:       s1=ps[ii][jj];
                   3185:       ps[ii][jj]=ps[jj][ii];
                   3186:       ps[jj][ii]=s1;
                   3187:     }
                   3188:   }
                   3189:   /* for(ii=1; ii<= nlstate+ndeath; ii++){ */
                   3190:   /*   for(jj=1; jj<= nlstate+ndeath; jj++){ */
                   3191:   /*   printf(" pmij  ps[%d][%d]=%lf ",ii,jj,ps[ii][jj]); */
                   3192:   /*   } */
                   3193:   /*   printf("\n "); */
                   3194:   /* } */
                   3195:   /* printf("\n ");printf("%lf ",cov[2]);*/
                   3196:   /*
                   3197:     for(i=1; i<= npar; i++) printf("%f ",x[i]);
                   3198:     goto end;*/
                   3199:   return ps;
1.217     brouard  3200: }
                   3201: 
                   3202: 
1.126     brouard  3203: /**************** Product of 2 matrices ******************/
                   3204: 
1.145     brouard  3205: double **matprod2(double **out, double **in,int nrl, int nrh, int ncl, int nch, int ncolol, int ncoloh, double **b)
1.126     brouard  3206: {
                   3207:   /* Computes the matrix product of in(1,nrh-nrl+1)(1,nch-ncl+1) times
                   3208:      b(1,nch-ncl+1)(1,ncoloh-ncolol+1) into out(...) */
                   3209:   /* in, b, out are matrice of pointers which should have been initialized 
                   3210:      before: only the contents of out is modified. The function returns
                   3211:      a pointer to pointers identical to out */
1.145     brouard  3212:   int i, j, k;
1.126     brouard  3213:   for(i=nrl; i<= nrh; i++)
1.145     brouard  3214:     for(k=ncolol; k<=ncoloh; k++){
                   3215:       out[i][k]=0.;
                   3216:       for(j=ncl; j<=nch; j++)
                   3217:        out[i][k] +=in[i][j]*b[j][k];
                   3218:     }
1.126     brouard  3219:   return out;
                   3220: }
                   3221: 
                   3222: 
                   3223: /************* Higher Matrix Product ***************/
                   3224: 
1.235     brouard  3225: 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  3226: {
1.218     brouard  3227:   /* Computes the transition matrix starting at age 'age' and combination of covariate values corresponding to ij over 
1.126     brouard  3228:      'nhstepm*hstepm*stepm' months (i.e. until
                   3229:      age (in years)  age+nhstepm*hstepm*stepm/12) by multiplying 
                   3230:      nhstepm*hstepm matrices. 
                   3231:      Output is stored in matrix po[i][j][h] for h every 'hstepm' step 
                   3232:      (typically every 2 years instead of every month which is too big 
                   3233:      for the memory).
                   3234:      Model is determined by parameters x and covariates have to be 
                   3235:      included manually here. 
                   3236: 
                   3237:      */
                   3238: 
                   3239:   int i, j, d, h, k;
1.131     brouard  3240:   double **out, cov[NCOVMAX+1];
1.126     brouard  3241:   double **newm;
1.187     brouard  3242:   double agexact;
1.214     brouard  3243:   double agebegin, ageend;
1.126     brouard  3244: 
                   3245:   /* Hstepm could be zero and should return the unit matrix */
                   3246:   for (i=1;i<=nlstate+ndeath;i++)
                   3247:     for (j=1;j<=nlstate+ndeath;j++){
                   3248:       oldm[i][j]=(i==j ? 1.0 : 0.0);
                   3249:       po[i][j][0]=(i==j ? 1.0 : 0.0);
                   3250:     }
                   3251:   /* Even if hstepm = 1, at least one multiplication by the unit matrix */
                   3252:   for(h=1; h <=nhstepm; h++){
                   3253:     for(d=1; d <=hstepm; d++){
                   3254:       newm=savm;
                   3255:       /* Covariates have to be included here again */
                   3256:       cov[1]=1.;
1.214     brouard  3257:       agexact=age+((h-1)*hstepm + (d-1))*stepm/YEARM; /* age just before transition */
1.187     brouard  3258:       cov[2]=agexact;
                   3259:       if(nagesqr==1)
1.227     brouard  3260:        cov[3]= agexact*agexact;
1.235     brouard  3261:       for (k=1; k<=nsd;k++) { /* For single dummy covariates only */
                   3262:                        /* Here comes the value of the covariate 'ij' after renumbering k with single dummy covariates */
                   3263:        cov[2+nagesqr+TvarsDind[k]]=nbcode[TvarsD[k]][codtabm(ij,k)];
                   3264:        /* 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)); */
                   3265:       }
                   3266:       for (k=1; k<=nsq;k++) { /* For single varying covariates only */
                   3267:        /* Here comes the value of quantitative after renumbering k with single quantitative covariates */
                   3268:        cov[2+nagesqr+TvarsQind[k]]=Tqresult[nres][k]; 
                   3269:        /* 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]); */
                   3270:       }
                   3271:       for (k=1; k<=cptcovage;k++){
                   3272:        if(Dummy[Tvar[Tage[k]]]){
                   3273:          cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,k)]*cov[2];
                   3274:        } else{
                   3275:          cov[2+nagesqr+Tage[k]]=Tqresult[nres][k]; 
                   3276:        }
                   3277:        /* 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]); */
                   3278:       }
                   3279:       for (k=1; k<=cptcovprod;k++){ /*  */
                   3280:        /* 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]); */
                   3281:        cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)] * nbcode[Tvard[k][2]][codtabm(ij,k)];
                   3282:       }
                   3283:       /* for (k=1; k<=cptcovn;k++)  */
                   3284:       /*       cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,k)]; */
                   3285:       /* for (k=1; k<=cptcovage;k++) /\* Should start at cptcovn+1 *\/ */
                   3286:       /*       cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,k)]*cov[2]; */
                   3287:       /* for (k=1; k<=cptcovprod;k++) /\* Useless because included in cptcovn *\/ */
                   3288:       /*       cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)]*nbcode[Tvard[k][2]][codtabm(ij,k)]; */
1.227     brouard  3289:       
                   3290:       
1.126     brouard  3291:       /*printf("hxi cptcov=%d cptcode=%d\n",cptcov,cptcode);*/
                   3292:       /*printf("h=%d d=%d age=%f cov=%f\n",h,d,age,cov[2]);*/
1.218     brouard  3293:                        /* right multiplication of oldm by the current matrix */
1.126     brouard  3294:       out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, 
                   3295:                   pmij(pmmij,cov,ncovmodel,x,nlstate));
1.217     brouard  3296:       /* if((int)age == 70){ */
                   3297:       /*       printf(" Forward hpxij age=%d agexact=%f d=%d nhstepm=%d hstepm=%d\n", (int) age, agexact, d, nhstepm, hstepm); */
                   3298:       /*       for(i=1; i<=nlstate+ndeath; i++) { */
                   3299:       /*         printf("%d pmmij ",i); */
                   3300:       /*         for(j=1;j<=nlstate+ndeath;j++) { */
                   3301:       /*           printf("%f ",pmmij[i][j]); */
                   3302:       /*         } */
                   3303:       /*         printf(" oldm "); */
                   3304:       /*         for(j=1;j<=nlstate+ndeath;j++) { */
                   3305:       /*           printf("%f ",oldm[i][j]); */
                   3306:       /*         } */
                   3307:       /*         printf("\n"); */
                   3308:       /*       } */
                   3309:       /* } */
1.126     brouard  3310:       savm=oldm;
                   3311:       oldm=newm;
                   3312:     }
                   3313:     for(i=1; i<=nlstate+ndeath; i++)
                   3314:       for(j=1;j<=nlstate+ndeath;j++) {
1.267     brouard  3315:        po[i][j][h]=newm[i][j];
                   3316:        /*if(h==nhstepm) printf("po[%d][%d][%d]=%f ",i,j,h,po[i][j][h]);*/
1.126     brouard  3317:       }
1.128     brouard  3318:     /*printf("h=%d ",h);*/
1.126     brouard  3319:   } /* end h */
1.267     brouard  3320:   /*     printf("\n H=%d \n",h); */
1.126     brouard  3321:   return po;
                   3322: }
                   3323: 
1.217     brouard  3324: /************* Higher Back Matrix Product ***************/
1.218     brouard  3325: /* 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  3326: 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  3327: {
1.266     brouard  3328:   /* For a combination of dummy covariate ij, computes the transition matrix starting at age 'age' over
1.217     brouard  3329:      'nhstepm*hstepm*stepm' months (i.e. until
1.218     brouard  3330:      age (in years)  age+nhstepm*hstepm*stepm/12) by multiplying
                   3331:      nhstepm*hstepm matrices.
                   3332:      Output is stored in matrix po[i][j][h] for h every 'hstepm' step
                   3333:      (typically every 2 years instead of every month which is too big
1.217     brouard  3334:      for the memory).
1.218     brouard  3335:      Model is determined by parameters x and covariates have to be
1.266     brouard  3336:      included manually here. Then we use a call to bmij(x and cov)
                   3337:      The addresss of po (p3mat allocated to the dimension of nhstepm) should be stored for output
1.222     brouard  3338:   */
1.217     brouard  3339: 
                   3340:   int i, j, d, h, k;
1.266     brouard  3341:   double **out, cov[NCOVMAX+1], **bmij();
                   3342:   double **newm, ***newmm;
1.217     brouard  3343:   double agexact;
                   3344:   double agebegin, ageend;
1.222     brouard  3345:   double **oldm, **savm;
1.217     brouard  3346: 
1.266     brouard  3347:   newmm=po; /* To be saved */
                   3348:   oldm=oldms;savm=savms; /* Global pointers */
1.217     brouard  3349:   /* Hstepm could be zero and should return the unit matrix */
                   3350:   for (i=1;i<=nlstate+ndeath;i++)
                   3351:     for (j=1;j<=nlstate+ndeath;j++){
                   3352:       oldm[i][j]=(i==j ? 1.0 : 0.0);
                   3353:       po[i][j][0]=(i==j ? 1.0 : 0.0);
                   3354:     }
                   3355:   /* Even if hstepm = 1, at least one multiplication by the unit matrix */
                   3356:   for(h=1; h <=nhstepm; h++){
                   3357:     for(d=1; d <=hstepm; d++){
                   3358:       newm=savm;
                   3359:       /* Covariates have to be included here again */
                   3360:       cov[1]=1.;
1.271     brouard  3361:       agexact=age-( (h-1)*hstepm + (d)  )*stepm/YEARM; /* age just before transition, d or d-1? */
1.217     brouard  3362:       /* agexact=age+((h-1)*hstepm + (d-1))*stepm/YEARM; /\* age just before transition *\/ */
                   3363:       cov[2]=agexact;
                   3364:       if(nagesqr==1)
1.222     brouard  3365:        cov[3]= agexact*agexact;
1.266     brouard  3366:       for (k=1; k<=cptcovn;k++){
                   3367:       /*       cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,k)]; */
                   3368:       /* /\* cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,Tvar[k])]; *\/ */
                   3369:        cov[2+nagesqr+TvarsDind[k]]=nbcode[TvarsD[k]][codtabm(ij,k)];
                   3370:         /* 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)); */
                   3371:       }
1.267     brouard  3372:       for (k=1; k<=nsq;k++) { /* For single varying covariates only */
                   3373:        /* Here comes the value of quantitative after renumbering k with single quantitative covariates */
                   3374:        cov[2+nagesqr+TvarsQind[k]]=Tqresult[nres][k]; 
                   3375:        /* 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]); */
                   3376:       }
                   3377:       for (k=1; k<=cptcovage;k++){ /* Should start at cptcovn+1 */
                   3378:        if(Dummy[Tvar[Tage[k]]]){
                   3379:          cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,k)]*cov[2];
                   3380:        } else{
                   3381:          cov[2+nagesqr+Tage[k]]=Tqresult[nres][k]; 
                   3382:        }
                   3383:        /* 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]); */
                   3384:       }
                   3385:       for (k=1; k<=cptcovprod;k++){ /* Useless because included in cptcovn */
1.222     brouard  3386:        cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)]*nbcode[Tvard[k][2]][codtabm(ij,k)];
1.267     brouard  3387:       }                        
1.217     brouard  3388:       /*printf("hxi cptcov=%d cptcode=%d\n",cptcov,cptcode);*/
                   3389:       /*printf("h=%d d=%d age=%f cov=%f\n",h,d,age,cov[2]);*/
1.267     brouard  3390: 
1.218     brouard  3391:       /* Careful transposed matrix */
1.266     brouard  3392:       /* age is in cov[2], prevacurrent at beginning of transition. */
1.218     brouard  3393:       /* out=matprod2(newm, bmij(pmmij,cov,ncovmodel,x,nlstate,prevacurrent, dnewm, doldm, dsavm,ij),\ */
1.222     brouard  3394:       /*                                                1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm); */
1.218     brouard  3395:       out=matprod2(newm, bmij(pmmij,cov,ncovmodel,x,nlstate,prevacurrent,ij),\
1.222     brouard  3396:                   1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm);
1.217     brouard  3397:       /* if((int)age == 70){ */
                   3398:       /*       printf(" Backward hbxij age=%d agexact=%f d=%d nhstepm=%d hstepm=%d\n", (int) age, agexact, d, nhstepm, hstepm); */
                   3399:       /*       for(i=1; i<=nlstate+ndeath; i++) { */
                   3400:       /*         printf("%d pmmij ",i); */
                   3401:       /*         for(j=1;j<=nlstate+ndeath;j++) { */
                   3402:       /*           printf("%f ",pmmij[i][j]); */
                   3403:       /*         } */
                   3404:       /*         printf(" oldm "); */
                   3405:       /*         for(j=1;j<=nlstate+ndeath;j++) { */
                   3406:       /*           printf("%f ",oldm[i][j]); */
                   3407:       /*         } */
                   3408:       /*         printf("\n"); */
                   3409:       /*       } */
                   3410:       /* } */
                   3411:       savm=oldm;
                   3412:       oldm=newm;
                   3413:     }
                   3414:     for(i=1; i<=nlstate+ndeath; i++)
                   3415:       for(j=1;j<=nlstate+ndeath;j++) {
1.222     brouard  3416:        po[i][j][h]=newm[i][j];
1.268     brouard  3417:        /* if(h==nhstepm) */
                   3418:        /*   printf("po[%d][%d][%d]=%f ",i,j,h,po[i][j][h]); */
1.217     brouard  3419:       }
1.268     brouard  3420:     /* printf("h=%d %.1f ",h, agexact); */
1.217     brouard  3421:   } /* end h */
1.268     brouard  3422:   /* printf("\n H=%d nhs=%d \n",h, nhstepm); */
1.217     brouard  3423:   return po;
                   3424: }
                   3425: 
                   3426: 
1.162     brouard  3427: #ifdef NLOPT
                   3428:   double  myfunc(unsigned n, const double *p1, double *grad, void *pd){
                   3429:   double fret;
                   3430:   double *xt;
                   3431:   int j;
                   3432:   myfunc_data *d2 = (myfunc_data *) pd;
                   3433: /* xt = (p1-1); */
                   3434:   xt=vector(1,n); 
                   3435:   for (j=1;j<=n;j++)   xt[j]=p1[j-1]; /* xt[1]=p1[0] */
                   3436: 
                   3437:   fret=(d2->function)(xt); /*  p xt[1]@8 is fine */
                   3438:   /* fret=(*func)(xt); /\*  p xt[1]@8 is fine *\/ */
                   3439:   printf("Function = %.12lf ",fret);
                   3440:   for (j=1;j<=n;j++) printf(" %d %.8lf", j, xt[j]); 
                   3441:   printf("\n");
                   3442:  free_vector(xt,1,n);
                   3443:   return fret;
                   3444: }
                   3445: #endif
1.126     brouard  3446: 
                   3447: /*************** log-likelihood *************/
                   3448: double func( double *x)
                   3449: {
1.226     brouard  3450:   int i, ii, j, k, mi, d, kk;
                   3451:   int ioffset=0;
                   3452:   double l, ll[NLSTATEMAX+1], cov[NCOVMAX+1];
                   3453:   double **out;
                   3454:   double lli; /* Individual log likelihood */
                   3455:   int s1, s2;
1.228     brouard  3456:   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  3457:   double bbh, survp;
                   3458:   long ipmx;
                   3459:   double agexact;
                   3460:   /*extern weight */
                   3461:   /* We are differentiating ll according to initial status */
                   3462:   /*  for (i=1;i<=npar;i++) printf("%f ", x[i]);*/
                   3463:   /*for(i=1;i<imx;i++) 
                   3464:     printf(" %d\n",s[4][i]);
                   3465:   */
1.162     brouard  3466: 
1.226     brouard  3467:   ++countcallfunc;
1.162     brouard  3468: 
1.226     brouard  3469:   cov[1]=1.;
1.126     brouard  3470: 
1.226     brouard  3471:   for(k=1; k<=nlstate; k++) ll[k]=0.;
1.224     brouard  3472:   ioffset=0;
1.226     brouard  3473:   if(mle==1){
                   3474:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
                   3475:       /* Computes the values of the ncovmodel covariates of the model
                   3476:         depending if the covariates are fixed or varying (age dependent) and stores them in cov[]
                   3477:         Then computes with function pmij which return a matrix p[i][j] giving the elementary probability
                   3478:         to be observed in j being in i according to the model.
                   3479:       */
1.243     brouard  3480:       ioffset=2+nagesqr ;
1.233     brouard  3481:    /* Fixed */
1.234     brouard  3482:       for (k=1; k<=ncovf;k++){ /* Simple and product fixed covariates without age* products */
                   3483:        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)*/
                   3484:       }
1.226     brouard  3485:       /* In model V2+V1*V4+age*V3+V3*V2 Tvar[1] is V2, Tvar[2=V1*V4] 
                   3486:         is 6, Tvar[3=age*V3] should not be computed because of age Tvar[4=V3*V2] 
                   3487:         has been calculated etc */
                   3488:       /* For an individual i, wav[i] gives the number of effective waves */
                   3489:       /* We compute the contribution to Likelihood of each effective transition
                   3490:         mw[mi][i] is real wave of the mi th effectve wave */
                   3491:       /* Then statuses are computed at each begin and end of an effective wave s1=s[ mw[mi][i] ][i];
                   3492:         s2=s[mw[mi+1][i]][i];
                   3493:         And the iv th varying covariate is the cotvar[mw[mi+1][i]][iv][i]
                   3494:         But if the variable is not in the model TTvar[iv] is the real variable effective in the model:
                   3495:         meaning that decodemodel should be used cotvar[mw[mi+1][i]][TTvar[iv]][i]
                   3496:       */
                   3497:       for(mi=1; mi<= wav[i]-1; mi++){
1.234     brouard  3498:        for(k=1; k <= ncovv ; k++){ /* Varying  covariates (single and product but no age )*/
1.242     brouard  3499:          /* cov[ioffset+TvarVind[k]]=cotvar[mw[mi][i]][Tvar[TvarVind[k]]][i]; */
                   3500:          cov[ioffset+TvarVind[k]]=cotvar[mw[mi][i]][Tvar[TvarVind[k]]-ncovcol-nqv][i];
1.234     brouard  3501:        }
                   3502:        for (ii=1;ii<=nlstate+ndeath;ii++)
                   3503:          for (j=1;j<=nlstate+ndeath;j++){
                   3504:            oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   3505:            savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   3506:          }
                   3507:        for(d=0; d<dh[mi][i]; d++){
                   3508:          newm=savm;
                   3509:          agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
                   3510:          cov[2]=agexact;
                   3511:          if(nagesqr==1)
                   3512:            cov[3]= agexact*agexact;  /* Should be changed here */
                   3513:          for (kk=1; kk<=cptcovage;kk++) {
1.242     brouard  3514:          if(!FixedV[Tvar[Tage[kk]]])
1.234     brouard  3515:            cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact; /* Tage[kk] gives the data-covariate associated with age */
1.242     brouard  3516:          else
                   3517:            cov[Tage[kk]+2+nagesqr]=cotvar[mw[mi][i]][Tvar[Tage[kk]]-ncovcol-nqv][i]*agexact;
1.234     brouard  3518:          }
                   3519:          out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   3520:                       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   3521:          savm=oldm;
                   3522:          oldm=newm;
                   3523:        } /* end mult */
                   3524:        
                   3525:        /*lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]);*/ /* Original formula */
                   3526:        /* But now since version 0.9 we anticipate for bias at large stepm.
                   3527:         * If stepm is larger than one month (smallest stepm) and if the exact delay 
                   3528:         * (in months) between two waves is not a multiple of stepm, we rounded to 
                   3529:         * the nearest (and in case of equal distance, to the lowest) interval but now
                   3530:         * we keep into memory the bias bh[mi][i] and also the previous matrix product
                   3531:         * (i.e to dh[mi][i]-1) saved in 'savm'. Then we inter(extra)polate the
                   3532:         * probability in order to take into account the bias as a fraction of the way
1.231     brouard  3533:                                 * from savm to out if bh is negative or even beyond if bh is positive. bh varies
                   3534:                                 * -stepm/2 to stepm/2 .
                   3535:                                 * For stepm=1 the results are the same as for previous versions of Imach.
                   3536:                                 * For stepm > 1 the results are less biased than in previous versions. 
                   3537:                                 */
1.234     brouard  3538:        s1=s[mw[mi][i]][i];
                   3539:        s2=s[mw[mi+1][i]][i];
                   3540:        bbh=(double)bh[mi][i]/(double)stepm; 
                   3541:        /* bias bh is positive if real duration
                   3542:         * is higher than the multiple of stepm and negative otherwise.
                   3543:         */
                   3544:        /* lli= (savm[s1][s2]>1.e-8 ?(1.+bbh)*log(out[s1][s2])- bbh*log(savm[s1][s2]):log((1.+bbh)*out[s1][s2]));*/
                   3545:        if( s2 > nlstate){ 
                   3546:          /* i.e. if s2 is a death state and if the date of death is known 
                   3547:             then the contribution to the likelihood is the probability to 
                   3548:             die between last step unit time and current  step unit time, 
                   3549:             which is also equal to probability to die before dh 
                   3550:             minus probability to die before dh-stepm . 
                   3551:             In version up to 0.92 likelihood was computed
                   3552:             as if date of death was unknown. Death was treated as any other
                   3553:             health state: the date of the interview describes the actual state
                   3554:             and not the date of a change in health state. The former idea was
                   3555:             to consider that at each interview the state was recorded
                   3556:             (healthy, disable or death) and IMaCh was corrected; but when we
                   3557:             introduced the exact date of death then we should have modified
                   3558:             the contribution of an exact death to the likelihood. This new
                   3559:             contribution is smaller and very dependent of the step unit
                   3560:             stepm. It is no more the probability to die between last interview
                   3561:             and month of death but the probability to survive from last
                   3562:             interview up to one month before death multiplied by the
                   3563:             probability to die within a month. Thanks to Chris
                   3564:             Jackson for correcting this bug.  Former versions increased
                   3565:             mortality artificially. The bad side is that we add another loop
                   3566:             which slows down the processing. The difference can be up to 10%
                   3567:             lower mortality.
                   3568:          */
                   3569:          /* If, at the beginning of the maximization mostly, the
                   3570:             cumulative probability or probability to be dead is
                   3571:             constant (ie = 1) over time d, the difference is equal to
                   3572:             0.  out[s1][3] = savm[s1][3]: probability, being at state
                   3573:             s1 at precedent wave, to be dead a month before current
                   3574:             wave is equal to probability, being at state s1 at
                   3575:             precedent wave, to be dead at mont of the current
                   3576:             wave. Then the observed probability (that this person died)
                   3577:             is null according to current estimated parameter. In fact,
                   3578:             it should be very low but not zero otherwise the log go to
                   3579:             infinity.
                   3580:          */
1.183     brouard  3581: /* #ifdef INFINITYORIGINAL */
                   3582: /*         lli=log(out[s1][s2] - savm[s1][s2]); */
                   3583: /* #else */
                   3584: /*       if ((out[s1][s2] - savm[s1][s2]) < mytinydouble)  */
                   3585: /*         lli=log(mytinydouble); */
                   3586: /*       else */
                   3587: /*         lli=log(out[s1][s2] - savm[s1][s2]); */
                   3588: /* #endif */
1.226     brouard  3589:          lli=log(out[s1][s2] - savm[s1][s2]);
1.216     brouard  3590:          
1.226     brouard  3591:        } else if  ( s2==-1 ) { /* alive */
                   3592:          for (j=1,survp=0. ; j<=nlstate; j++) 
                   3593:            survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
                   3594:          /*survp += out[s1][j]; */
                   3595:          lli= log(survp);
                   3596:        }
                   3597:        else if  (s2==-4) { 
                   3598:          for (j=3,survp=0. ; j<=nlstate; j++)  
                   3599:            survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
                   3600:          lli= log(survp); 
                   3601:        } 
                   3602:        else if  (s2==-5) { 
                   3603:          for (j=1,survp=0. ; j<=2; j++)  
                   3604:            survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
                   3605:          lli= log(survp); 
                   3606:        } 
                   3607:        else{
                   3608:          lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */
                   3609:          /*  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 */
                   3610:        } 
                   3611:        /*lli=(1.+bbh)*log(out[s1][s2])- bbh*log(savm[s1][s2]);*/
                   3612:        /*if(lli ==000.0)*/
                   3613:        /*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); */
                   3614:        ipmx +=1;
                   3615:        sw += weight[i];
                   3616:        ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
                   3617:        /* if (lli < log(mytinydouble)){ */
                   3618:        /*   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); */
                   3619:        /*   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]); */
                   3620:        /* } */
                   3621:       } /* end of wave */
                   3622:     } /* end of individual */
                   3623:   }  else if(mle==2){
                   3624:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
                   3625:       for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i];
                   3626:       for(mi=1; mi<= wav[i]-1; mi++){
                   3627:        for (ii=1;ii<=nlstate+ndeath;ii++)
                   3628:          for (j=1;j<=nlstate+ndeath;j++){
                   3629:            oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   3630:            savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   3631:          }
                   3632:        for(d=0; d<=dh[mi][i]; d++){
                   3633:          newm=savm;
                   3634:          agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
                   3635:          cov[2]=agexact;
                   3636:          if(nagesqr==1)
                   3637:            cov[3]= agexact*agexact;
                   3638:          for (kk=1; kk<=cptcovage;kk++) {
                   3639:            cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact;
                   3640:          }
                   3641:          out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   3642:                       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   3643:          savm=oldm;
                   3644:          oldm=newm;
                   3645:        } /* end mult */
                   3646:       
                   3647:        s1=s[mw[mi][i]][i];
                   3648:        s2=s[mw[mi+1][i]][i];
                   3649:        bbh=(double)bh[mi][i]/(double)stepm; 
                   3650:        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 */
                   3651:        ipmx +=1;
                   3652:        sw += weight[i];
                   3653:        ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
                   3654:       } /* end of wave */
                   3655:     } /* end of individual */
                   3656:   }  else if(mle==3){  /* exponential inter-extrapolation */
                   3657:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
                   3658:       for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i];
                   3659:       for(mi=1; mi<= wav[i]-1; mi++){
                   3660:        for (ii=1;ii<=nlstate+ndeath;ii++)
                   3661:          for (j=1;j<=nlstate+ndeath;j++){
                   3662:            oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   3663:            savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   3664:          }
                   3665:        for(d=0; d<dh[mi][i]; d++){
                   3666:          newm=savm;
                   3667:          agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
                   3668:          cov[2]=agexact;
                   3669:          if(nagesqr==1)
                   3670:            cov[3]= agexact*agexact;
                   3671:          for (kk=1; kk<=cptcovage;kk++) {
                   3672:            cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact;
                   3673:          }
                   3674:          out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   3675:                       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   3676:          savm=oldm;
                   3677:          oldm=newm;
                   3678:        } /* end mult */
                   3679:       
                   3680:        s1=s[mw[mi][i]][i];
                   3681:        s2=s[mw[mi+1][i]][i];
                   3682:        bbh=(double)bh[mi][i]/(double)stepm; 
                   3683:        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 */
                   3684:        ipmx +=1;
                   3685:        sw += weight[i];
                   3686:        ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
                   3687:       } /* end of wave */
                   3688:     } /* end of individual */
                   3689:   }else if (mle==4){  /* ml=4 no inter-extrapolation */
                   3690:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
                   3691:       for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i];
                   3692:       for(mi=1; mi<= wav[i]-1; mi++){
                   3693:        for (ii=1;ii<=nlstate+ndeath;ii++)
                   3694:          for (j=1;j<=nlstate+ndeath;j++){
                   3695:            oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   3696:            savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   3697:          }
                   3698:        for(d=0; d<dh[mi][i]; d++){
                   3699:          newm=savm;
                   3700:          agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
                   3701:          cov[2]=agexact;
                   3702:          if(nagesqr==1)
                   3703:            cov[3]= agexact*agexact;
                   3704:          for (kk=1; kk<=cptcovage;kk++) {
                   3705:            cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact;
                   3706:          }
1.126     brouard  3707:        
1.226     brouard  3708:          out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   3709:                       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   3710:          savm=oldm;
                   3711:          oldm=newm;
                   3712:        } /* end mult */
                   3713:       
                   3714:        s1=s[mw[mi][i]][i];
                   3715:        s2=s[mw[mi+1][i]][i];
                   3716:        if( s2 > nlstate){ 
                   3717:          lli=log(out[s1][s2] - savm[s1][s2]);
                   3718:        } else if  ( s2==-1 ) { /* alive */
                   3719:          for (j=1,survp=0. ; j<=nlstate; j++) 
                   3720:            survp += out[s1][j];
                   3721:          lli= log(survp);
                   3722:        }else{
                   3723:          lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]); /* Original formula */
                   3724:        }
                   3725:        ipmx +=1;
                   3726:        sw += weight[i];
                   3727:        ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
1.126     brouard  3728: /*     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  3729:       } /* end of wave */
                   3730:     } /* end of individual */
                   3731:   }else{  /* ml=5 no inter-extrapolation no jackson =0.8a */
                   3732:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
                   3733:       for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i];
                   3734:       for(mi=1; mi<= wav[i]-1; mi++){
                   3735:        for (ii=1;ii<=nlstate+ndeath;ii++)
                   3736:          for (j=1;j<=nlstate+ndeath;j++){
                   3737:            oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   3738:            savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   3739:          }
                   3740:        for(d=0; d<dh[mi][i]; d++){
                   3741:          newm=savm;
                   3742:          agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
                   3743:          cov[2]=agexact;
                   3744:          if(nagesqr==1)
                   3745:            cov[3]= agexact*agexact;
                   3746:          for (kk=1; kk<=cptcovage;kk++) {
                   3747:            cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact;
                   3748:          }
1.126     brouard  3749:        
1.226     brouard  3750:          out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   3751:                       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   3752:          savm=oldm;
                   3753:          oldm=newm;
                   3754:        } /* end mult */
                   3755:       
                   3756:        s1=s[mw[mi][i]][i];
                   3757:        s2=s[mw[mi+1][i]][i];
                   3758:        lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]); /* Original formula */
                   3759:        ipmx +=1;
                   3760:        sw += weight[i];
                   3761:        ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
                   3762:        /*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]);*/
                   3763:       } /* end of wave */
                   3764:     } /* end of individual */
                   3765:   } /* End of if */
                   3766:   for(k=1,l=0.; k<=nlstate; k++) l += ll[k];
                   3767:   /* printf("l1=%f l2=%f ",ll[1],ll[2]); */
                   3768:   l= l*ipmx/sw; /* To get the same order of magnitude as if weight=1 for every body */
                   3769:   return -l;
1.126     brouard  3770: }
                   3771: 
                   3772: /*************** log-likelihood *************/
                   3773: double funcone( double *x)
                   3774: {
1.228     brouard  3775:   /* Same as func but slower because of a lot of printf and if */
1.126     brouard  3776:   int i, ii, j, k, mi, d, kk;
1.228     brouard  3777:   int ioffset=0;
1.131     brouard  3778:   double l, ll[NLSTATEMAX+1], cov[NCOVMAX+1];
1.126     brouard  3779:   double **out;
                   3780:   double lli; /* Individual log likelihood */
                   3781:   double llt;
                   3782:   int s1, s2;
1.228     brouard  3783:   int iv=0, iqv=0, itv=0, iqtv=0 ; /* Index of varying covariate, fixed quantitative cov, time varying covariate, quantitative time varying covariate */
                   3784: 
1.126     brouard  3785:   double bbh, survp;
1.187     brouard  3786:   double agexact;
1.214     brouard  3787:   double agebegin, ageend;
1.126     brouard  3788:   /*extern weight */
                   3789:   /* We are differentiating ll according to initial status */
                   3790:   /*  for (i=1;i<=npar;i++) printf("%f ", x[i]);*/
                   3791:   /*for(i=1;i<imx;i++) 
                   3792:     printf(" %d\n",s[4][i]);
                   3793:   */
                   3794:   cov[1]=1.;
                   3795: 
                   3796:   for(k=1; k<=nlstate; k++) ll[k]=0.;
1.224     brouard  3797:   ioffset=0;
                   3798:   for (i=1,ipmx=0, sw=0.; i<=imx; i++){
1.243     brouard  3799:     /* ioffset=2+nagesqr+cptcovage; */
                   3800:     ioffset=2+nagesqr;
1.232     brouard  3801:     /* Fixed */
1.224     brouard  3802:     /* for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i]; */
1.232     brouard  3803:     /* for (k=1; k<=ncoveff;k++){ /\* Simple and product fixed Dummy covariates without age* products *\/ */
                   3804:     for (k=1; k<=ncovf;k++){ /* Simple and product fixed covariates without age* products */
                   3805:       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)*/
                   3806: /*    cov[ioffset+TvarFind[1]]=covar[Tvar[TvarFind[1]]][i];  */
                   3807: /*    cov[2+6]=covar[Tvar[6]][i];  */
                   3808: /*    cov[2+6]=covar[2][i]; V2  */
                   3809: /*    cov[TvarFind[2]]=covar[Tvar[TvarFind[2]]][i];  */
                   3810: /*    cov[2+7]=covar[Tvar[7]][i];  */
                   3811: /*    cov[2+7]=covar[7][i]; V7=V1*V2  */
                   3812: /*    cov[TvarFind[3]]=covar[Tvar[TvarFind[3]]][i];  */
                   3813: /*    cov[2+9]=covar[Tvar[9]][i];  */
                   3814: /*    cov[2+9]=covar[1][i]; V1  */
1.225     brouard  3815:     }
1.232     brouard  3816:     /* for (k=1; k<=nqfveff;k++){ /\* Simple and product fixed Quantitative covariates without age* products *\/ */
                   3817:     /*   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?)*\/ */
                   3818:     /* } */
1.231     brouard  3819:     /* for(iqv=1; iqv <= nqfveff; iqv++){ /\* Quantitative fixed covariates *\/ */
                   3820:     /*   cov[++ioffset]=coqvar[Tvar[iqv]][i]; /\* Only V2 k=6 and V1*V2 7 *\/ */
                   3821:     /* } */
1.225     brouard  3822:     
1.233     brouard  3823: 
                   3824:     for(mi=1; mi<= wav[i]-1; mi++){  /* Varying with waves */
1.232     brouard  3825:     /* Wave varying (but not age varying) */
                   3826:       for(k=1; k <= ncovv ; k++){ /* Varying  covariates (single and product but no age )*/
1.242     brouard  3827:        /* cov[ioffset+TvarVind[k]]=cotvar[mw[mi][i]][Tvar[TvarVind[k]]][i]; */
                   3828:        cov[ioffset+TvarVind[k]]=cotvar[mw[mi][i]][Tvar[TvarVind[k]]-ncovcol-nqv][i];
                   3829:       }
1.232     brouard  3830:       /* for(itv=1; itv <= ntveff; itv++){ /\* Varying dummy covariates (single??)*\/ */
1.242     brouard  3831:       /* iv= Tvar[Tmodelind[ioffset-2-nagesqr-cptcovage+itv]]-ncovcol-nqv; /\* Counting the # varying covariate from 1 to ntveff *\/ */
                   3832:       /* cov[ioffset+iv]=cotvar[mw[mi][i]][iv][i]; */
                   3833:       /* k=ioffset-2-nagesqr-cptcovage+itv; /\* position in simple model *\/ */
                   3834:       /* cov[ioffset+itv]=cotvar[mw[mi][i]][TmodelInvind[itv]][i]; */
                   3835:       /* 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  3836:       /* for(iqtv=1; iqtv <= nqtveff; iqtv++){ /\* Varying quantitatives covariates *\/ */
1.242     brouard  3837:       /*       iv=TmodelInvQind[iqtv]; /\* Counting the # varying covariate from 1 to ntveff *\/ */
                   3838:       /*       /\* 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]); *\/ */
                   3839:       /*       cov[ioffset+ntveff+iqtv]=cotqvar[mw[mi][i]][TmodelInvQind[iqtv]][i]; */
1.232     brouard  3840:       /* } */
1.126     brouard  3841:       for (ii=1;ii<=nlstate+ndeath;ii++)
1.242     brouard  3842:        for (j=1;j<=nlstate+ndeath;j++){
                   3843:          oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   3844:          savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   3845:        }
1.214     brouard  3846:       
                   3847:       agebegin=agev[mw[mi][i]][i]; /* Age at beginning of effective wave */
                   3848:       ageend=agev[mw[mi][i]][i] + (dh[mi][i])*stepm/YEARM; /* Age at end of effective wave and at the end of transition */
                   3849:       for(d=0; d<dh[mi][i]; d++){  /* Delay between two effective waves */
1.247     brouard  3850:       /* for(d=0; d<=0; d++){  /\* Delay between two effective waves Only one matrix to speed up*\/ */
1.242     brouard  3851:        /*dh[m][i] or dh[mw[mi][i]][i] is the delay between two effective waves m=mw[mi][i]
                   3852:          and mw[mi+1][i]. dh depends on stepm.*/
                   3853:        newm=savm;
1.247     brouard  3854:        agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;  /* Here d is needed */
1.242     brouard  3855:        cov[2]=agexact;
                   3856:        if(nagesqr==1)
                   3857:          cov[3]= agexact*agexact;
                   3858:        for (kk=1; kk<=cptcovage;kk++) {
                   3859:          if(!FixedV[Tvar[Tage[kk]]])
                   3860:            cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact;
                   3861:          else
                   3862:            cov[Tage[kk]+2+nagesqr]=cotvar[mw[mi][i]][Tvar[Tage[kk]]-ncovcol-nqv][i]*agexact;
                   3863:        }
                   3864:        /* printf("i=%d,mi=%d,d=%d,mw[mi][i]=%d\n",i, mi,d,mw[mi][i]); */
                   3865:        /* savm=pmij(pmmij,cov,ncovmodel,x,nlstate); */
                   3866:        out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   3867:                     1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   3868:        /* out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath, */
                   3869:        /*           1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate)); */
                   3870:        savm=oldm;
                   3871:        oldm=newm;
1.126     brouard  3872:       } /* end mult */
                   3873:       
                   3874:       s1=s[mw[mi][i]][i];
                   3875:       s2=s[mw[mi+1][i]][i];
1.217     brouard  3876:       /* if(s2==-1){ */
1.268     brouard  3877:       /*       printf(" ERROR s1=%d, s2=%d i=%d \n", s1, s2, i); */
1.217     brouard  3878:       /*       /\* exit(1); *\/ */
                   3879:       /* } */
1.126     brouard  3880:       bbh=(double)bh[mi][i]/(double)stepm; 
                   3881:       /* bias is positive if real duration
                   3882:        * is higher than the multiple of stepm and negative otherwise.
                   3883:        */
                   3884:       if( s2 > nlstate && (mle <5) ){  /* Jackson */
1.242     brouard  3885:        lli=log(out[s1][s2] - savm[s1][s2]);
1.216     brouard  3886:       } else if  ( s2==-1 ) { /* alive */
1.242     brouard  3887:        for (j=1,survp=0. ; j<=nlstate; j++) 
                   3888:          survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
                   3889:        lli= log(survp);
1.126     brouard  3890:       }else if (mle==1){
1.242     brouard  3891:        lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */
1.126     brouard  3892:       } else if(mle==2){
1.242     brouard  3893:        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  3894:       } else if(mle==3){  /* exponential inter-extrapolation */
1.242     brouard  3895:        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  3896:       } else if (mle==4){  /* mle=4 no inter-extrapolation */
1.242     brouard  3897:        lli=log(out[s1][s2]); /* Original formula */
1.136     brouard  3898:       } else{  /* mle=0 back to 1 */
1.242     brouard  3899:        lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */
                   3900:        /*lli=log(out[s1][s2]); */ /* Original formula */
1.126     brouard  3901:       } /* End of if */
                   3902:       ipmx +=1;
                   3903:       sw += weight[i];
                   3904:       ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
1.132     brouard  3905:       /*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  3906:       if(globpr){
1.246     brouard  3907:        fprintf(ficresilk,"%09ld %6.1f %6.1f %6d %2d %2d %2d %2d %3d %15.6f %8.4f %8.3f\
1.126     brouard  3908:  %11.6f %11.6f %11.6f ", \
1.242     brouard  3909:                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  3910:                2*weight[i]*lli,(s2==-1? -1: out[s1][s2]),(s2==-1? -1: savm[s1][s2]));
1.242     brouard  3911:        for(k=1,llt=0.,l=0.; k<=nlstate; k++){
                   3912:          llt +=ll[k]*gipmx/gsw;
                   3913:          fprintf(ficresilk," %10.6f",-ll[k]*gipmx/gsw);
                   3914:        }
                   3915:        fprintf(ficresilk," %10.6f\n", -llt);
1.126     brouard  3916:       }
1.232     brouard  3917:        } /* end of wave */
                   3918: } /* end of individual */
                   3919: for(k=1,l=0.; k<=nlstate; k++) l += ll[k];
                   3920: /* printf("l1=%f l2=%f ",ll[1],ll[2]); */
                   3921: l= l*ipmx/sw; /* To get the same order of magnitude as if weight=1 for every body */
                   3922: if(globpr==0){ /* First time we count the contributions and weights */
                   3923:        gipmx=ipmx;
                   3924:        gsw=sw;
                   3925: }
                   3926: return -l;
1.126     brouard  3927: }
                   3928: 
                   3929: 
                   3930: /*************** function likelione ***********/
1.292     brouard  3931: void likelione(FILE *ficres,double p[], int npar, int nlstate, int *globpri, long *ipmx, double *sw, double *fretone, double (*func)(double []))
1.126     brouard  3932: {
                   3933:   /* This routine should help understanding what is done with 
                   3934:      the selection of individuals/waves and
                   3935:      to check the exact contribution to the likelihood.
                   3936:      Plotting could be done.
                   3937:    */
                   3938:   int k;
                   3939: 
                   3940:   if(*globpri !=0){ /* Just counts and sums, no printings */
1.201     brouard  3941:     strcpy(fileresilk,"ILK_"); 
1.202     brouard  3942:     strcat(fileresilk,fileresu);
1.126     brouard  3943:     if((ficresilk=fopen(fileresilk,"w"))==NULL) {
                   3944:       printf("Problem with resultfile: %s\n", fileresilk);
                   3945:       fprintf(ficlog,"Problem with resultfile: %s\n", fileresilk);
                   3946:     }
1.214     brouard  3947:     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");
                   3948:     fprintf(ficresilk, "#num_i ageb agend i s1 s2 mi mw dh likeli weight %%weight 2wlli out sav ");
1.126     brouard  3949:     /*         i,s1,s2,mi,mw[mi][i],dh[mi][i],exp(lli),weight[i],2*weight[i]*lli,out[s1][s2],savm[s1][s2]); */
                   3950:     for(k=1; k<=nlstate; k++) 
                   3951:       fprintf(ficresilk," -2*gipw/gsw*weight*ll[%d]++",k);
                   3952:     fprintf(ficresilk," -2*gipw/gsw*weight*ll(total)\n");
                   3953:   }
                   3954: 
1.292     brouard  3955:   *fretone=(*func)(p);
1.126     brouard  3956:   if(*globpri !=0){
                   3957:     fclose(ficresilk);
1.205     brouard  3958:     if (mle ==0)
                   3959:       fprintf(fichtm,"\n<br>File of contributions to the likelihood computed with initial parameters and mle = %d.",mle);
                   3960:     else if(mle >=1)
                   3961:       fprintf(fichtm,"\n<br>File of contributions to the likelihood computed with optimized parameters mle = %d.",mle);
                   3962:     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  3963:     fprintf(fichtm,"\n<br>Equation of the model: <b>model=1+age+%s</b><br>\n",model); 
1.208     brouard  3964:       
                   3965:     for (k=1; k<= nlstate ; k++) {
1.211     brouard  3966:       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  3967: <img src=\"%s-p%dj.png\">",k,k,subdirf2(optionfilefiname,"ILK_"),k,subdirf2(optionfilefiname,"ILK_"),k,subdirf2(optionfilefiname,"ILK_"),k);
                   3968:     }
1.207     brouard  3969:     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  3970: <img src=\"%s-ori.png\">",subdirf2(optionfilefiname,"ILK_"),subdirf2(optionfilefiname,"ILK_"),subdirf2(optionfilefiname,"ILK_"));
1.207     brouard  3971:     fprintf(fichtm,"<br>- and by state of destination <a href=\"%s-dest.png\">%s-dest.png</a><br> \
1.204     brouard  3972: <img src=\"%s-dest.png\">",subdirf2(optionfilefiname,"ILK_"),subdirf2(optionfilefiname,"ILK_"),subdirf2(optionfilefiname,"ILK_"));
1.207     brouard  3973:     fflush(fichtm);
1.205     brouard  3974:   }
1.126     brouard  3975:   return;
                   3976: }
                   3977: 
                   3978: 
                   3979: /*********** Maximum Likelihood Estimation ***************/
                   3980: 
                   3981: void mlikeli(FILE *ficres,double p[], int npar, int ncovmodel, int nlstate, double ftol, double (*func)(double []))
                   3982: {
1.165     brouard  3983:   int i,j, iter=0;
1.126     brouard  3984:   double **xi;
                   3985:   double fret;
                   3986:   double fretone; /* Only one call to likelihood */
                   3987:   /*  char filerespow[FILENAMELENGTH];*/
1.162     brouard  3988: 
                   3989: #ifdef NLOPT
                   3990:   int creturn;
                   3991:   nlopt_opt opt;
                   3992:   /* double lb[9] = { -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL }; /\* lower bounds *\/ */
                   3993:   double *lb;
                   3994:   double minf; /* the minimum objective value, upon return */
                   3995:   double * p1; /* Shifted parameters from 0 instead of 1 */
                   3996:   myfunc_data dinst, *d = &dinst;
                   3997: #endif
                   3998: 
                   3999: 
1.126     brouard  4000:   xi=matrix(1,npar,1,npar);
                   4001:   for (i=1;i<=npar;i++)
                   4002:     for (j=1;j<=npar;j++)
                   4003:       xi[i][j]=(i==j ? 1.0 : 0.0);
                   4004:   printf("Powell\n");  fprintf(ficlog,"Powell\n");
1.201     brouard  4005:   strcpy(filerespow,"POW_"); 
1.126     brouard  4006:   strcat(filerespow,fileres);
                   4007:   if((ficrespow=fopen(filerespow,"w"))==NULL) {
                   4008:     printf("Problem with resultfile: %s\n", filerespow);
                   4009:     fprintf(ficlog,"Problem with resultfile: %s\n", filerespow);
                   4010:   }
                   4011:   fprintf(ficrespow,"# Powell\n# iter -2*LL");
                   4012:   for (i=1;i<=nlstate;i++)
                   4013:     for(j=1;j<=nlstate+ndeath;j++)
                   4014:       if(j!=i)fprintf(ficrespow," p%1d%1d",i,j);
                   4015:   fprintf(ficrespow,"\n");
1.162     brouard  4016: #ifdef POWELL
1.126     brouard  4017:   powell(p,xi,npar,ftol,&iter,&fret,func);
1.162     brouard  4018: #endif
1.126     brouard  4019: 
1.162     brouard  4020: #ifdef NLOPT
                   4021: #ifdef NEWUOA
                   4022:   opt = nlopt_create(NLOPT_LN_NEWUOA,npar);
                   4023: #else
                   4024:   opt = nlopt_create(NLOPT_LN_BOBYQA,npar);
                   4025: #endif
                   4026:   lb=vector(0,npar-1);
                   4027:   for (i=0;i<npar;i++) lb[i]= -HUGE_VAL;
                   4028:   nlopt_set_lower_bounds(opt, lb);
                   4029:   nlopt_set_initial_step1(opt, 0.1);
                   4030:   
                   4031:   p1= (p+1); /*  p *(p+1)@8 and p *(p1)@8 are equal p1[0]=p[1] */
                   4032:   d->function = func;
                   4033:   printf(" Func %.12lf \n",myfunc(npar,p1,NULL,d));
                   4034:   nlopt_set_min_objective(opt, myfunc, d);
                   4035:   nlopt_set_xtol_rel(opt, ftol);
                   4036:   if ((creturn=nlopt_optimize(opt, p1, &minf)) < 0) {
                   4037:     printf("nlopt failed! %d\n",creturn); 
                   4038:   }
                   4039:   else {
                   4040:     printf("found minimum after %d evaluations (NLOPT=%d)\n", countcallfunc ,NLOPT);
                   4041:     printf("found minimum at f(%g,%g) = %0.10g\n", p[0], p[1], minf);
                   4042:     iter=1; /* not equal */
                   4043:   }
                   4044:   nlopt_destroy(opt);
                   4045: #endif
1.126     brouard  4046:   free_matrix(xi,1,npar,1,npar);
                   4047:   fclose(ficrespow);
1.203     brouard  4048:   printf("\n#Number of iterations & function calls = %d & %d, -2 Log likelihood = %.12f\n",iter, countcallfunc,func(p));
                   4049:   fprintf(ficlog,"\n#Number of iterations & function calls = %d & %d, -2 Log likelihood = %.12f\n",iter, countcallfunc,func(p));
1.180     brouard  4050:   fprintf(ficres,"#Number of iterations & function calls = %d & %d, -2 Log likelihood = %.12f\n",iter, countcallfunc,func(p));
1.126     brouard  4051: 
                   4052: }
                   4053: 
                   4054: /**** Computes Hessian and covariance matrix ***/
1.203     brouard  4055: void hesscov(double **matcov, double **hess, double p[], int npar, double delti[], double ftolhess, double (*func)(double []))
1.126     brouard  4056: {
                   4057:   double  **a,**y,*x,pd;
1.203     brouard  4058:   /* double **hess; */
1.164     brouard  4059:   int i, j;
1.126     brouard  4060:   int *indx;
                   4061: 
                   4062:   double hessii(double p[], double delta, int theta, double delti[],double (*func)(double []),int npar);
1.203     brouard  4063:   double hessij(double p[], double **hess, double delti[], int i, int j,double (*func)(double []),int npar);
1.126     brouard  4064:   void lubksb(double **a, int npar, int *indx, double b[]) ;
                   4065:   void ludcmp(double **a, int npar, int *indx, double *d) ;
                   4066:   double gompertz(double p[]);
1.203     brouard  4067:   /* hess=matrix(1,npar,1,npar); */
1.126     brouard  4068: 
                   4069:   printf("\nCalculation of the hessian matrix. Wait...\n");
                   4070:   fprintf(ficlog,"\nCalculation of the hessian matrix. Wait...\n");
                   4071:   for (i=1;i<=npar;i++){
1.203     brouard  4072:     printf("%d-",i);fflush(stdout);
                   4073:     fprintf(ficlog,"%d-",i);fflush(ficlog);
1.126     brouard  4074:    
                   4075:      hess[i][i]=hessii(p,ftolhess,i,delti,func,npar);
                   4076:     
                   4077:     /*  printf(" %f ",p[i]);
                   4078:        printf(" %lf %lf %lf",hess[i][i],ftolhess,delti[i]);*/
                   4079:   }
                   4080:   
                   4081:   for (i=1;i<=npar;i++) {
                   4082:     for (j=1;j<=npar;j++)  {
                   4083:       if (j>i) { 
1.203     brouard  4084:        printf(".%d-%d",i,j);fflush(stdout);
                   4085:        fprintf(ficlog,".%d-%d",i,j);fflush(ficlog);
                   4086:        hess[i][j]=hessij(p,hess, delti,i,j,func,npar);
1.126     brouard  4087:        
                   4088:        hess[j][i]=hess[i][j];    
                   4089:        /*printf(" %lf ",hess[i][j]);*/
                   4090:       }
                   4091:     }
                   4092:   }
                   4093:   printf("\n");
                   4094:   fprintf(ficlog,"\n");
                   4095: 
                   4096:   printf("\nInverting the hessian to get the covariance matrix. Wait...\n");
                   4097:   fprintf(ficlog,"\nInverting the hessian to get the covariance matrix. Wait...\n");
                   4098:   
                   4099:   a=matrix(1,npar,1,npar);
                   4100:   y=matrix(1,npar,1,npar);
                   4101:   x=vector(1,npar);
                   4102:   indx=ivector(1,npar);
                   4103:   for (i=1;i<=npar;i++)
                   4104:     for (j=1;j<=npar;j++) a[i][j]=hess[i][j];
                   4105:   ludcmp(a,npar,indx,&pd);
                   4106: 
                   4107:   for (j=1;j<=npar;j++) {
                   4108:     for (i=1;i<=npar;i++) x[i]=0;
                   4109:     x[j]=1;
                   4110:     lubksb(a,npar,indx,x);
                   4111:     for (i=1;i<=npar;i++){ 
                   4112:       matcov[i][j]=x[i];
                   4113:     }
                   4114:   }
                   4115: 
                   4116:   printf("\n#Hessian matrix#\n");
                   4117:   fprintf(ficlog,"\n#Hessian matrix#\n");
                   4118:   for (i=1;i<=npar;i++) { 
                   4119:     for (j=1;j<=npar;j++) { 
1.203     brouard  4120:       printf("%.6e ",hess[i][j]);
                   4121:       fprintf(ficlog,"%.6e ",hess[i][j]);
1.126     brouard  4122:     }
                   4123:     printf("\n");
                   4124:     fprintf(ficlog,"\n");
                   4125:   }
                   4126: 
1.203     brouard  4127:   /* printf("\n#Covariance matrix#\n"); */
                   4128:   /* fprintf(ficlog,"\n#Covariance matrix#\n"); */
                   4129:   /* for (i=1;i<=npar;i++) {  */
                   4130:   /*   for (j=1;j<=npar;j++) {  */
                   4131:   /*     printf("%.6e ",matcov[i][j]); */
                   4132:   /*     fprintf(ficlog,"%.6e ",matcov[i][j]); */
                   4133:   /*   } */
                   4134:   /*   printf("\n"); */
                   4135:   /*   fprintf(ficlog,"\n"); */
                   4136:   /* } */
                   4137: 
1.126     brouard  4138:   /* Recompute Inverse */
1.203     brouard  4139:   /* for (i=1;i<=npar;i++) */
                   4140:   /*   for (j=1;j<=npar;j++) a[i][j]=matcov[i][j]; */
                   4141:   /* ludcmp(a,npar,indx,&pd); */
                   4142: 
                   4143:   /*  printf("\n#Hessian matrix recomputed#\n"); */
                   4144: 
                   4145:   /* for (j=1;j<=npar;j++) { */
                   4146:   /*   for (i=1;i<=npar;i++) x[i]=0; */
                   4147:   /*   x[j]=1; */
                   4148:   /*   lubksb(a,npar,indx,x); */
                   4149:   /*   for (i=1;i<=npar;i++){  */
                   4150:   /*     y[i][j]=x[i]; */
                   4151:   /*     printf("%.3e ",y[i][j]); */
                   4152:   /*     fprintf(ficlog,"%.3e ",y[i][j]); */
                   4153:   /*   } */
                   4154:   /*   printf("\n"); */
                   4155:   /*   fprintf(ficlog,"\n"); */
                   4156:   /* } */
                   4157: 
                   4158:   /* Verifying the inverse matrix */
                   4159: #ifdef DEBUGHESS
                   4160:   y=matprod2(y,hess,1,npar,1,npar,1,npar,matcov);
1.126     brouard  4161: 
1.203     brouard  4162:    printf("\n#Verification: multiplying the matrix of covariance by the Hessian matrix, should be unity:#\n");
                   4163:    fprintf(ficlog,"\n#Verification: multiplying the matrix of covariance by the Hessian matrix. Should be unity:#\n");
1.126     brouard  4164: 
                   4165:   for (j=1;j<=npar;j++) {
                   4166:     for (i=1;i<=npar;i++){ 
1.203     brouard  4167:       printf("%.2f ",y[i][j]);
                   4168:       fprintf(ficlog,"%.2f ",y[i][j]);
1.126     brouard  4169:     }
                   4170:     printf("\n");
                   4171:     fprintf(ficlog,"\n");
                   4172:   }
1.203     brouard  4173: #endif
1.126     brouard  4174: 
                   4175:   free_matrix(a,1,npar,1,npar);
                   4176:   free_matrix(y,1,npar,1,npar);
                   4177:   free_vector(x,1,npar);
                   4178:   free_ivector(indx,1,npar);
1.203     brouard  4179:   /* free_matrix(hess,1,npar,1,npar); */
1.126     brouard  4180: 
                   4181: 
                   4182: }
                   4183: 
                   4184: /*************** hessian matrix ****************/
                   4185: double hessii(double x[], double delta, int theta, double delti[], double (*func)(double []), int npar)
1.203     brouard  4186: { /* Around values of x, computes the function func and returns the scales delti and hessian */
1.126     brouard  4187:   int i;
                   4188:   int l=1, lmax=20;
1.203     brouard  4189:   double k1,k2, res, fx;
1.132     brouard  4190:   double p2[MAXPARM+1]; /* identical to x */
1.126     brouard  4191:   double delt=0.0001, delts, nkhi=10.,nkhif=1., khi=1.e-4;
                   4192:   int k=0,kmax=10;
                   4193:   double l1;
                   4194: 
                   4195:   fx=func(x);
                   4196:   for (i=1;i<=npar;i++) p2[i]=x[i];
1.145     brouard  4197:   for(l=0 ; l <=lmax; l++){  /* Enlarging the zone around the Maximum */
1.126     brouard  4198:     l1=pow(10,l);
                   4199:     delts=delt;
                   4200:     for(k=1 ; k <kmax; k=k+1){
                   4201:       delt = delta*(l1*k);
                   4202:       p2[theta]=x[theta] +delt;
1.145     brouard  4203:       k1=func(p2)-fx;   /* Might be negative if too close to the theoretical maximum */
1.126     brouard  4204:       p2[theta]=x[theta]-delt;
                   4205:       k2=func(p2)-fx;
                   4206:       /*res= (k1-2.0*fx+k2)/delt/delt; */
1.203     brouard  4207:       res= (k1+k2)/delt/delt/2.; /* Divided by 2 because L and not 2*L */
1.126     brouard  4208:       
1.203     brouard  4209: #ifdef DEBUGHESSII
1.126     brouard  4210:       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);
                   4211:       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);
                   4212: #endif
                   4213:       /*if(fabs(k1-2.0*fx+k2) <1.e-13){ */
                   4214:       if((k1 <khi/nkhi/2.) || (k2 <khi/nkhi/2.)){
                   4215:        k=kmax;
                   4216:       }
                   4217:       else if((k1 >khi/nkhif) || (k2 >khi/nkhif)){ /* Keeps lastvalue before 3.84/2 KHI2 5% 1d.f. */
1.164     brouard  4218:        k=kmax; l=lmax*10;
1.126     brouard  4219:       }
                   4220:       else if((k1 >khi/nkhi) || (k2 >khi/nkhi)){ 
                   4221:        delts=delt;
                   4222:       }
1.203     brouard  4223:     } /* End loop k */
1.126     brouard  4224:   }
                   4225:   delti[theta]=delts;
                   4226:   return res; 
                   4227:   
                   4228: }
                   4229: 
1.203     brouard  4230: double hessij( double x[], double **hess, double delti[], int thetai,int thetaj,double (*func)(double []),int npar)
1.126     brouard  4231: {
                   4232:   int i;
1.164     brouard  4233:   int l=1, lmax=20;
1.126     brouard  4234:   double k1,k2,k3,k4,res,fx;
1.132     brouard  4235:   double p2[MAXPARM+1];
1.203     brouard  4236:   int k, kmax=1;
                   4237:   double v1, v2, cv12, lc1, lc2;
1.208     brouard  4238: 
                   4239:   int firstime=0;
1.203     brouard  4240:   
1.126     brouard  4241:   fx=func(x);
1.203     brouard  4242:   for (k=1; k<=kmax; k=k+10) {
1.126     brouard  4243:     for (i=1;i<=npar;i++) p2[i]=x[i];
1.203     brouard  4244:     p2[thetai]=x[thetai]+delti[thetai]*k;
                   4245:     p2[thetaj]=x[thetaj]+delti[thetaj]*k;
1.126     brouard  4246:     k1=func(p2)-fx;
                   4247:   
1.203     brouard  4248:     p2[thetai]=x[thetai]+delti[thetai]*k;
                   4249:     p2[thetaj]=x[thetaj]-delti[thetaj]*k;
1.126     brouard  4250:     k2=func(p2)-fx;
                   4251:   
1.203     brouard  4252:     p2[thetai]=x[thetai]-delti[thetai]*k;
                   4253:     p2[thetaj]=x[thetaj]+delti[thetaj]*k;
1.126     brouard  4254:     k3=func(p2)-fx;
                   4255:   
1.203     brouard  4256:     p2[thetai]=x[thetai]-delti[thetai]*k;
                   4257:     p2[thetaj]=x[thetaj]-delti[thetaj]*k;
1.126     brouard  4258:     k4=func(p2)-fx;
1.203     brouard  4259:     res=(k1-k2-k3+k4)/4.0/delti[thetai]/k/delti[thetaj]/k/2.; /* Because of L not 2*L */
                   4260:     if(k1*k2*k3*k4 <0.){
1.208     brouard  4261:       firstime=1;
1.203     brouard  4262:       kmax=kmax+10;
1.208     brouard  4263:     }
                   4264:     if(kmax >=10 || firstime ==1){
1.246     brouard  4265:       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);
                   4266:       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  4267:       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);
                   4268:       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);
                   4269:     }
                   4270: #ifdef DEBUGHESSIJ
                   4271:     v1=hess[thetai][thetai];
                   4272:     v2=hess[thetaj][thetaj];
                   4273:     cv12=res;
                   4274:     /* Computing eigen value of Hessian matrix */
                   4275:     lc1=((v1+v2)+sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
                   4276:     lc2=((v1+v2)-sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
                   4277:     if ((lc2 <0) || (lc1 <0) ){
                   4278:       printf("Warning: sub Hessian matrix '%d%d' does not have positive eigen values \n",thetai,thetaj);
                   4279:       fprintf(ficlog, "Warning: sub Hessian matrix '%d%d' does not have positive eigen values \n",thetai,thetaj);
                   4280:       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);
                   4281:       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);
                   4282:     }
1.126     brouard  4283: #endif
                   4284:   }
                   4285:   return res;
                   4286: }
                   4287: 
1.203     brouard  4288:     /* Not done yet: Was supposed to fix if not exactly at the maximum */
                   4289: /* double hessij( double x[], double delti[], int thetai,int thetaj,double (*func)(double []),int npar) */
                   4290: /* { */
                   4291: /*   int i; */
                   4292: /*   int l=1, lmax=20; */
                   4293: /*   double k1,k2,k3,k4,res,fx; */
                   4294: /*   double p2[MAXPARM+1]; */
                   4295: /*   double delt=0.0001, delts, nkhi=10.,nkhif=1., khi=1.e-4; */
                   4296: /*   int k=0,kmax=10; */
                   4297: /*   double l1; */
                   4298:   
                   4299: /*   fx=func(x); */
                   4300: /*   for(l=0 ; l <=lmax; l++){  /\* Enlarging the zone around the Maximum *\/ */
                   4301: /*     l1=pow(10,l); */
                   4302: /*     delts=delt; */
                   4303: /*     for(k=1 ; k <kmax; k=k+1){ */
                   4304: /*       delt = delti*(l1*k); */
                   4305: /*       for (i=1;i<=npar;i++) p2[i]=x[i]; */
                   4306: /*       p2[thetai]=x[thetai]+delti[thetai]/k; */
                   4307: /*       p2[thetaj]=x[thetaj]+delti[thetaj]/k; */
                   4308: /*       k1=func(p2)-fx; */
                   4309:       
                   4310: /*       p2[thetai]=x[thetai]+delti[thetai]/k; */
                   4311: /*       p2[thetaj]=x[thetaj]-delti[thetaj]/k; */
                   4312: /*       k2=func(p2)-fx; */
                   4313:       
                   4314: /*       p2[thetai]=x[thetai]-delti[thetai]/k; */
                   4315: /*       p2[thetaj]=x[thetaj]+delti[thetaj]/k; */
                   4316: /*       k3=func(p2)-fx; */
                   4317:       
                   4318: /*       p2[thetai]=x[thetai]-delti[thetai]/k; */
                   4319: /*       p2[thetaj]=x[thetaj]-delti[thetaj]/k; */
                   4320: /*       k4=func(p2)-fx; */
                   4321: /*       res=(k1-k2-k3+k4)/4.0/delti[thetai]*k/delti[thetaj]*k/2.; /\* Because of L not 2*L *\/ */
                   4322: /* #ifdef DEBUGHESSIJ */
                   4323: /*       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); */
                   4324: /*       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); */
                   4325: /* #endif */
                   4326: /*       if((k1 <khi/nkhi/2.) || (k2 <khi/nkhi/2.)|| (k4 <khi/nkhi/2.)|| (k4 <khi/nkhi/2.)){ */
                   4327: /*     k=kmax; */
                   4328: /*       } */
                   4329: /*       else if((k1 >khi/nkhif) || (k2 >khi/nkhif) || (k4 >khi/nkhif) || (k4 >khi/nkhif)){ /\* Keeps lastvalue before 3.84/2 KHI2 5% 1d.f. *\/ */
                   4330: /*     k=kmax; l=lmax*10; */
                   4331: /*       } */
                   4332: /*       else if((k1 >khi/nkhi) || (k2 >khi/nkhi)){  */
                   4333: /*     delts=delt; */
                   4334: /*       } */
                   4335: /*     } /\* End loop k *\/ */
                   4336: /*   } */
                   4337: /*   delti[theta]=delts; */
                   4338: /*   return res;  */
                   4339: /* } */
                   4340: 
                   4341: 
1.126     brouard  4342: /************** Inverse of matrix **************/
                   4343: void ludcmp(double **a, int n, int *indx, double *d) 
                   4344: { 
                   4345:   int i,imax,j,k; 
                   4346:   double big,dum,sum,temp; 
                   4347:   double *vv; 
                   4348:  
                   4349:   vv=vector(1,n); 
                   4350:   *d=1.0; 
                   4351:   for (i=1;i<=n;i++) { 
                   4352:     big=0.0; 
                   4353:     for (j=1;j<=n;j++) 
                   4354:       if ((temp=fabs(a[i][j])) > big) big=temp; 
1.256     brouard  4355:     if (big == 0.0){
                   4356:       printf(" Singular Hessian matrix at row %d:\n",i);
                   4357:       for (j=1;j<=n;j++) {
                   4358:        printf(" a[%d][%d]=%f,",i,j,a[i][j]);
                   4359:        fprintf(ficlog," a[%d][%d]=%f,",i,j,a[i][j]);
                   4360:       }
                   4361:       fflush(ficlog);
                   4362:       fclose(ficlog);
                   4363:       nrerror("Singular matrix in routine ludcmp"); 
                   4364:     }
1.126     brouard  4365:     vv[i]=1.0/big; 
                   4366:   } 
                   4367:   for (j=1;j<=n;j++) { 
                   4368:     for (i=1;i<j;i++) { 
                   4369:       sum=a[i][j]; 
                   4370:       for (k=1;k<i;k++) sum -= a[i][k]*a[k][j]; 
                   4371:       a[i][j]=sum; 
                   4372:     } 
                   4373:     big=0.0; 
                   4374:     for (i=j;i<=n;i++) { 
                   4375:       sum=a[i][j]; 
                   4376:       for (k=1;k<j;k++) 
                   4377:        sum -= a[i][k]*a[k][j]; 
                   4378:       a[i][j]=sum; 
                   4379:       if ( (dum=vv[i]*fabs(sum)) >= big) { 
                   4380:        big=dum; 
                   4381:        imax=i; 
                   4382:       } 
                   4383:     } 
                   4384:     if (j != imax) { 
                   4385:       for (k=1;k<=n;k++) { 
                   4386:        dum=a[imax][k]; 
                   4387:        a[imax][k]=a[j][k]; 
                   4388:        a[j][k]=dum; 
                   4389:       } 
                   4390:       *d = -(*d); 
                   4391:       vv[imax]=vv[j]; 
                   4392:     } 
                   4393:     indx[j]=imax; 
                   4394:     if (a[j][j] == 0.0) a[j][j]=TINY; 
                   4395:     if (j != n) { 
                   4396:       dum=1.0/(a[j][j]); 
                   4397:       for (i=j+1;i<=n;i++) a[i][j] *= dum; 
                   4398:     } 
                   4399:   } 
                   4400:   free_vector(vv,1,n);  /* Doesn't work */
                   4401: ;
                   4402: } 
                   4403: 
                   4404: void lubksb(double **a, int n, int *indx, double b[]) 
                   4405: { 
                   4406:   int i,ii=0,ip,j; 
                   4407:   double sum; 
                   4408:  
                   4409:   for (i=1;i<=n;i++) { 
                   4410:     ip=indx[i]; 
                   4411:     sum=b[ip]; 
                   4412:     b[ip]=b[i]; 
                   4413:     if (ii) 
                   4414:       for (j=ii;j<=i-1;j++) sum -= a[i][j]*b[j]; 
                   4415:     else if (sum) ii=i; 
                   4416:     b[i]=sum; 
                   4417:   } 
                   4418:   for (i=n;i>=1;i--) { 
                   4419:     sum=b[i]; 
                   4420:     for (j=i+1;j<=n;j++) sum -= a[i][j]*b[j]; 
                   4421:     b[i]=sum/a[i][i]; 
                   4422:   } 
                   4423: } 
                   4424: 
                   4425: void pstamp(FILE *fichier)
                   4426: {
1.196     brouard  4427:   fprintf(fichier,"# %s.%s\n#IMaCh version %s, %s\n#%s\n# %s", optionfilefiname,optionfilext,version,copyright, fullversion, strstart);
1.126     brouard  4428: }
                   4429: 
1.297     brouard  4430: void date2dmy(double date,double *day, double *month, double *year){
                   4431:   double yp=0., yp1=0., yp2=0.;
                   4432:   
                   4433:   yp1=modf(date,&yp);/* extracts integral of date in yp  and
                   4434:                        fractional in yp1 */
                   4435:   *year=yp;
                   4436:   yp2=modf((yp1*12),&yp);
                   4437:   *month=yp;
                   4438:   yp1=modf((yp2*30.5),&yp);
                   4439:   *day=yp;
                   4440:   if(*day==0) *day=1;
                   4441:   if(*month==0) *month=1;
                   4442: }
                   4443: 
1.253     brouard  4444: 
                   4445: 
1.126     brouard  4446: /************ Frequencies ********************/
1.251     brouard  4447: void  freqsummary(char fileres[], double p[], double pstart[], int iagemin, int iagemax, int **s, double **agev, int nlstate, int imx, \
1.226     brouard  4448:                  int *Tvaraff, int *invalidvarcomb, int **nbcode, int *ncodemax,double **mint,double **anint, char strstart[], \
                   4449:                  int firstpass,  int lastpass, int stepm, int weightopt, char model[])
1.250     brouard  4450: {  /* Some frequencies as well as proposing some starting values */
1.226     brouard  4451:   
1.265     brouard  4452:   int i, m, jk, j1, bool, z1,j, nj, nl, k, iv, jj=0, s1=1, s2=1;
1.226     brouard  4453:   int iind=0, iage=0;
                   4454:   int mi; /* Effective wave */
                   4455:   int first;
                   4456:   double ***freq; /* Frequencies */
1.268     brouard  4457:   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 */
                   4458:   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  4459:   double *meanq, *stdq, *idq;
1.226     brouard  4460:   double **meanqt;
                   4461:   double *pp, **prop, *posprop, *pospropt;
                   4462:   double pos=0., posproptt=0., pospropta=0., k2, dateintsum=0,k2cpt=0;
                   4463:   char fileresp[FILENAMELENGTH], fileresphtm[FILENAMELENGTH], fileresphtmfr[FILENAMELENGTH];
                   4464:   double agebegin, ageend;
                   4465:     
                   4466:   pp=vector(1,nlstate);
1.251     brouard  4467:   prop=matrix(1,nlstate,iagemin-AGEMARGE,iagemax+4+AGEMARGE); 
1.226     brouard  4468:   posprop=vector(1,nlstate); /* Counting the number of transition starting from a live state per age */ 
                   4469:   pospropt=vector(1,nlstate); /* Counting the number of transition starting from a live state */ 
                   4470:   /* prop=matrix(1,nlstate,iagemin,iagemax+3); */
                   4471:   meanq=vector(1,nqfveff); /* Number of Quantitative Fixed Variables Effective */
1.284     brouard  4472:   stdq=vector(1,nqfveff); /* Number of Quantitative Fixed Variables Effective */
1.283     brouard  4473:   idq=vector(1,nqfveff); /* Number of Quantitative Fixed Variables Effective */
1.226     brouard  4474:   meanqt=matrix(1,lastpass,1,nqtveff);
                   4475:   strcpy(fileresp,"P_");
                   4476:   strcat(fileresp,fileresu);
                   4477:   /*strcat(fileresphtm,fileresu);*/
                   4478:   if((ficresp=fopen(fileresp,"w"))==NULL) {
                   4479:     printf("Problem with prevalence resultfile: %s\n", fileresp);
                   4480:     fprintf(ficlog,"Problem with prevalence resultfile: %s\n", fileresp);
                   4481:     exit(0);
                   4482:   }
1.240     brouard  4483:   
1.226     brouard  4484:   strcpy(fileresphtm,subdirfext(optionfilefiname,"PHTM_",".htm"));
                   4485:   if((ficresphtm=fopen(fileresphtm,"w"))==NULL) {
                   4486:     printf("Problem with prevalence HTM resultfile '%s' with errno='%s'\n",fileresphtm,strerror(errno));
                   4487:     fprintf(ficlog,"Problem with prevalence HTM resultfile '%s' with errno='%s'\n",fileresphtm,strerror(errno));
                   4488:     fflush(ficlog);
                   4489:     exit(70); 
                   4490:   }
                   4491:   else{
                   4492:     fprintf(ficresphtm,"<html><head>\n<title>IMaCh PHTM_ %s</title></head>\n <body><font size=\"2\">%s <br> %s</font> \
1.240     brouard  4493: <hr size=\"2\" color=\"#EC5E5E\"> \n                                   \
1.214     brouard  4494: Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=1+age+%s<br>\n",\
1.226     brouard  4495:            fileresphtm,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model);
                   4496:   }
1.237     brouard  4497:   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  4498:   
1.226     brouard  4499:   strcpy(fileresphtmfr,subdirfext(optionfilefiname,"PHTMFR_",".htm"));
                   4500:   if((ficresphtmfr=fopen(fileresphtmfr,"w"))==NULL) {
                   4501:     printf("Problem with frequency table HTM resultfile '%s' with errno='%s'\n",fileresphtmfr,strerror(errno));
                   4502:     fprintf(ficlog,"Problem with frequency table HTM resultfile '%s' with errno='%s'\n",fileresphtmfr,strerror(errno));
                   4503:     fflush(ficlog);
                   4504:     exit(70); 
1.240     brouard  4505:   } else{
1.226     brouard  4506:     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  4507: <hr size=\"2\" color=\"#EC5E5E\"> \n                                   \
1.214     brouard  4508: Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=1+age+%s<br>\n",\
1.226     brouard  4509:            fileresphtmfr,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model);
                   4510:   }
1.240     brouard  4511:   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);
                   4512:   
1.253     brouard  4513:   y= vector(iagemin-AGEMARGE,iagemax+4+AGEMARGE);
                   4514:   x= vector(iagemin-AGEMARGE,iagemax+4+AGEMARGE);
1.251     brouard  4515:   freq= ma3x(-5,nlstate+ndeath,-5,nlstate+ndeath,iagemin-AGEMARGE,iagemax+4+AGEMARGE);
1.226     brouard  4516:   j1=0;
1.126     brouard  4517:   
1.227     brouard  4518:   /* j=ncoveff;  /\* Only fixed dummy covariates *\/ */
                   4519:   j=cptcoveff;  /* Only dummy covariates of the model */
1.226     brouard  4520:   if (cptcovn<1) {j=1;ncodemax[1]=1;}
1.240     brouard  4521:   
                   4522:   
1.226     brouard  4523:   /* Detects if a combination j1 is empty: for a multinomial variable like 3 education levels:
                   4524:      reference=low_education V1=0,V2=0
                   4525:      med_educ                V1=1 V2=0, 
                   4526:      high_educ               V1=0 V2=1
                   4527:      Then V1=1 and V2=1 is a noisy combination that we want to exclude for the list 2**cptcoveff 
                   4528:   */
1.249     brouard  4529:   dateintsum=0;
                   4530:   k2cpt=0;
                   4531: 
1.253     brouard  4532:   if(cptcoveff == 0 )
1.265     brouard  4533:     nl=1;  /* Constant and age model only */
1.253     brouard  4534:   else
                   4535:     nl=2;
1.265     brouard  4536: 
                   4537:   /* if a constant only model, one pass to compute frequency tables and to write it on ficresp */
                   4538:   /* Loop on nj=1 or 2 if dummy covariates j!=0
                   4539:    *   Loop on j1(1 to 2**cptcoveff) covariate combination
                   4540:    *     freq[s1][s2][iage] =0.
                   4541:    *     Loop on iind
                   4542:    *       ++freq[s1][s2][iage] weighted
                   4543:    *     end iind
                   4544:    *     if covariate and j!0
                   4545:    *       headers Variable on one line
                   4546:    *     endif cov j!=0
                   4547:    *     header of frequency table by age
                   4548:    *     Loop on age
                   4549:    *       pp[s1]+=freq[s1][s2][iage] weighted
                   4550:    *       pos+=freq[s1][s2][iage] weighted
                   4551:    *       Loop on s1 initial state
                   4552:    *         fprintf(ficresp
                   4553:    *       end s1
                   4554:    *     end age
                   4555:    *     if j!=0 computes starting values
                   4556:    *     end compute starting values
                   4557:    *   end j1
                   4558:    * end nl 
                   4559:    */
1.253     brouard  4560:   for (nj = 1; nj <= nl; nj++){   /* nj= 1 constant model, nl number of loops. */
                   4561:     if(nj==1)
                   4562:       j=0;  /* First pass for the constant */
1.265     brouard  4563:     else{
1.253     brouard  4564:       j=cptcoveff; /* Other passes for the covariate values */
1.265     brouard  4565:     }
1.251     brouard  4566:     first=1;
1.265     brouard  4567:     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  4568:       posproptt=0.;
                   4569:       /*printf("cptcoveff=%d Tvaraff=%d", cptcoveff,Tvaraff[1]);
                   4570:        scanf("%d", i);*/
                   4571:       for (i=-5; i<=nlstate+ndeath; i++)  
1.265     brouard  4572:        for (s2=-5; s2<=nlstate+ndeath; s2++)  
1.251     brouard  4573:          for(m=iagemin; m <= iagemax+3; m++)
1.265     brouard  4574:            freq[i][s2][m]=0;
1.251     brouard  4575:       
                   4576:       for (i=1; i<=nlstate; i++)  {
1.240     brouard  4577:        for(m=iagemin; m <= iagemax+3; m++)
1.251     brouard  4578:          prop[i][m]=0;
                   4579:        posprop[i]=0;
                   4580:        pospropt[i]=0;
                   4581:       }
1.283     brouard  4582:       for (z1=1; z1<= nqfveff; z1++) { /* zeroing for each combination j1 as well as for the total */
1.284     brouard  4583:         idq[z1]=0.;
                   4584:         meanq[z1]=0.;
                   4585:         stdq[z1]=0.;
1.283     brouard  4586:       }
                   4587:       /* for (z1=1; z1<= nqtveff; z1++) { */
1.251     brouard  4588:       /*   for(m=1;m<=lastpass;m++){ */
1.283     brouard  4589:       /*         meanqt[m][z1]=0.; */
                   4590:       /*       } */
                   4591:       /* }       */
1.251     brouard  4592:       /* dateintsum=0; */
                   4593:       /* k2cpt=0; */
                   4594:       
1.265     brouard  4595:       /* For that combination of covariates j1 (V4=1 V3=0 for example), we count and print the frequencies in one pass */
1.251     brouard  4596:       for (iind=1; iind<=imx; iind++) { /* For each individual iind */
                   4597:        bool=1;
                   4598:        if(j !=0){
                   4599:          if(anyvaryingduminmodel==0){ /* If All fixed covariates */
                   4600:            if (cptcoveff >0) { /* Filter is here: Must be looked at for model=V1+V2+V3+V4 */
                   4601:              for (z1=1; z1<=cptcoveff; z1++) { /* loops on covariates in the model */
                   4602:                /* if(Tvaraff[z1] ==-20){ */
                   4603:                /*       /\* sumnew+=cotvar[mw[mi][iind]][z1][iind]; *\/ */
                   4604:                /* }else  if(Tvaraff[z1] ==-10){ */
                   4605:                /*       /\* sumnew+=coqvar[z1][iind]; *\/ */
                   4606:                /* }else  */
                   4607:                if (covar[Tvaraff[z1]][iind]!= nbcode[Tvaraff[z1]][codtabm(j1,z1)]){ /* for combination j1 of covariates */
1.265     brouard  4608:                  /* Tests if the value of the covariate z1 for this individual iind responded to combination j1 (V4=1 V3=0) */
1.251     brouard  4609:                  bool=0; /* bool should be equal to 1 to be selected, one covariate value failed */
                   4610:                  /* 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", 
                   4611:                     bool,i,z1, z1, Tvaraff[z1],i,covar[Tvaraff[z1]][i],j1,z1,codtabm(j1,z1),
                   4612:                     j1,z1,nbcode[Tvaraff[z1]][codtabm(j1,z1)],j1);*/
                   4613:                  /* For j1=7 in V1+V2+V3+V4 = 0 1 1 0 and codtabm(7,3)=1 and nbcde[3][?]=1*/
                   4614:                } /* Onlyf fixed */
                   4615:              } /* end z1 */
                   4616:            } /* cptcovn > 0 */
                   4617:          } /* end any */
                   4618:        }/* end j==0 */
1.265     brouard  4619:        if (bool==1){ /* We selected an individual iind satisfying combination j1 (V4=1 V3=0) or all fixed covariates */
1.251     brouard  4620:          /* for(m=firstpass; m<=lastpass; m++){ */
1.284     brouard  4621:          for(mi=1; mi<wav[iind];mi++){ /* For each wave */
1.251     brouard  4622:            m=mw[mi][iind];
                   4623:            if(j!=0){
                   4624:              if(anyvaryingduminmodel==1){ /* Some are varying covariates */
                   4625:                for (z1=1; z1<=cptcoveff; z1++) {
                   4626:                  if( Fixed[Tmodelind[z1]]==1){
                   4627:                    iv= Tvar[Tmodelind[z1]]-ncovcol-nqv;
                   4628:                    if (cotvar[m][iv][iind]!= nbcode[Tvaraff[z1]][codtabm(j1,z1)]) /* iv=1 to ntv, right modality. If covariate's 
                   4629:                                                                                      value is -1, we don't select. It differs from the 
                   4630:                                                                                      constant and age model which counts them. */
                   4631:                      bool=0; /* not selected */
                   4632:                  }else if( Fixed[Tmodelind[z1]]== 0) { /* fixed */
                   4633:                    if (covar[Tvaraff[z1]][iind]!= nbcode[Tvaraff[z1]][codtabm(j1,z1)]) {
                   4634:                      bool=0;
                   4635:                    }
                   4636:                  }
                   4637:                }
                   4638:              }/* Some are varying covariates, we tried to speed up if all fixed covariates in the model, avoiding waves loop  */
                   4639:            } /* end j==0 */
                   4640:            /* bool =0 we keep that guy which corresponds to the combination of dummy values */
1.284     brouard  4641:            if(bool==1){ /*Selected */
1.251     brouard  4642:              /* dh[m][iind] or dh[mw[mi][iind]][iind] is the delay between two effective (mi) waves m=mw[mi][iind]
                   4643:                 and mw[mi+1][iind]. dh depends on stepm. */
                   4644:              agebegin=agev[m][iind]; /* Age at beginning of wave before transition*/
                   4645:              ageend=agev[m][iind]+(dh[m][iind])*stepm/YEARM; /* Age at end of wave and transition */
                   4646:              if(m >=firstpass && m <=lastpass){
                   4647:                k2=anint[m][iind]+(mint[m][iind]/12.);
                   4648:                /*if ((k2>=dateprev1) && (k2<=dateprev2)) {*/
                   4649:                if(agev[m][iind]==0) agev[m][iind]=iagemax+1;  /* All ages equal to 0 are in iagemax+1 */
                   4650:                if(agev[m][iind]==1) agev[m][iind]=iagemax+2;  /* All ages equal to 1 are in iagemax+2 */
                   4651:                if (s[m][iind]>0 && s[m][iind]<=nlstate)  /* If status at wave m is known and a live state */
                   4652:                  prop[s[m][iind]][(int)agev[m][iind]] += weight[iind];  /* At age of beginning of transition, where status is known */
                   4653:                if (m<lastpass) {
                   4654:                  /* if(s[m][iind]==4 && s[m+1][iind]==4) */
                   4655:                  /*   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]); */
                   4656:                  if(s[m][iind]==-1)
                   4657:                    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.));
                   4658:                  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  4659:                  for (z1=1; z1<= nqfveff; z1++) { /* Quantitative variables, calculating mean */
                   4660:                    idq[z1]=idq[z1]+weight[iind];
                   4661:                    meanq[z1]+=covar[ncovcol+z1][iind]*weight[iind];  /* Computes mean of quantitative with selected filter */
                   4662:                    stdq[z1]+=covar[ncovcol+z1][iind]*covar[ncovcol+z1][iind]*weight[iind]*weight[iind]; /* *weight[iind];*/  /* Computes mean of quantitative with selected filter */
                   4663:                  }
1.251     brouard  4664:                  /* if((int)agev[m][iind] == 55) */
                   4665:                  /*   printf("j=%d, j1=%d Age %d, iind=%d, num=%09ld m=%d\n",j,j1,(int)agev[m][iind],iind, num[iind],m); */
                   4666:                  /* freq[s[m][iind]][s[m+1][iind]][(int)((agebegin+ageend)/2.)] += weight[iind]; */
                   4667:                  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  4668:                }
1.251     brouard  4669:              } /* end if between passes */  
                   4670:              if ((agev[m][iind]>1) && (agev[m][iind]< (iagemax+3)) && (anint[m][iind]!=9999) && (mint[m][iind]!=99) && (j==0)) {
                   4671:                dateintsum=dateintsum+k2; /* on all covariates ?*/
                   4672:                k2cpt++;
                   4673:                /* printf("iind=%ld dateintmean = %lf dateintsum=%lf k2cpt=%lf k2=%lf\n",iind, dateintsum/k2cpt, dateintsum,k2cpt, k2); */
1.234     brouard  4674:              }
1.251     brouard  4675:            }else{
                   4676:              bool=1;
                   4677:            }/* end bool 2 */
                   4678:          } /* end m */
1.284     brouard  4679:          /* for (z1=1; z1<= nqfveff; z1++) { /\* Quantitative variables, calculating mean *\/ */
                   4680:          /*   idq[z1]=idq[z1]+weight[iind]; */
                   4681:          /*   meanq[z1]+=covar[ncovcol+z1][iind]*weight[iind];  /\* Computes mean of quantitative with selected filter *\/ */
                   4682:          /*   stdq[z1]+=covar[ncovcol+z1][iind]*covar[ncovcol+z1][iind]*weight[iind]*weight[iind]; /\* *weight[iind];*\/  /\* Computes mean of quantitative with selected filter *\/ */
                   4683:          /* } */
1.251     brouard  4684:        } /* end bool */
                   4685:       } /* end iind = 1 to imx */
                   4686:       /* prop[s][age] is feeded for any initial and valid live state as well as
                   4687:         freq[s1][s2][age] at single age of beginning the transition, for a combination j1 */
                   4688:       
                   4689:       
                   4690:       /*      fprintf(ficresp, "#Count between %.lf/%.lf/%.lf and %.lf/%.lf/%.lf\n",jprev1, mprev1,anprev1,jprev2, mprev2,anprev2);*/
1.265     brouard  4691:       if(cptcoveff==0 && nj==1) /* no covariate and first pass */
                   4692:         pstamp(ficresp);
1.251     brouard  4693:       if  (cptcoveff>0 && j!=0){
1.265     brouard  4694:         pstamp(ficresp);
1.251     brouard  4695:        printf( "\n#********** Variable "); 
                   4696:        fprintf(ficresp, "\n#********** Variable "); 
                   4697:        fprintf(ficresphtm, "\n<br/><br/><h3>********** Variable "); 
                   4698:        fprintf(ficresphtmfr, "\n<br/><br/><h3>********** Variable "); 
                   4699:        fprintf(ficlog, "\n#********** Variable "); 
                   4700:        for (z1=1; z1<=cptcoveff; z1++){
                   4701:          if(!FixedV[Tvaraff[z1]]){
                   4702:            printf( "V%d(fixed)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
                   4703:            fprintf(ficresp, "V%d(fixed)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
                   4704:            fprintf(ficresphtm, "V%d(fixed)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
                   4705:            fprintf(ficresphtmfr, "V%d(fixed)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
                   4706:            fprintf(ficlog, "V%d(fixed)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
1.250     brouard  4707:          }else{
1.251     brouard  4708:            printf( "V%d(varying)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
                   4709:            fprintf(ficresp, "V%d(varying)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
                   4710:            fprintf(ficresphtm, "V%d(varying)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
                   4711:            fprintf(ficresphtmfr, "V%d(varying)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
                   4712:            fprintf(ficlog, "V%d(varying)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
                   4713:          }
                   4714:        }
                   4715:        printf( "**********\n#");
                   4716:        fprintf(ficresp, "**********\n#");
                   4717:        fprintf(ficresphtm, "**********</h3>\n");
                   4718:        fprintf(ficresphtmfr, "**********</h3>\n");
                   4719:        fprintf(ficlog, "**********\n");
                   4720:       }
1.284     brouard  4721:       /*
                   4722:        Printing means of quantitative variables if any
                   4723:       */
                   4724:       for (z1=1; z1<= nqfveff; z1++) {
1.285     brouard  4725:        fprintf(ficlog,"Mean of fixed quantitative variable V%d on %.0f individuals sum=%f", ncovcol+z1, idq[z1], meanq[z1]);
1.284     brouard  4726:        fprintf(ficlog,", mean=%.3g\n",meanq[z1]/idq[z1]);
                   4727:        if(weightopt==1){
                   4728:          printf(" Weighted mean and standard deviation of");
                   4729:          fprintf(ficlog," Weighted mean and standard deviation of");
                   4730:          fprintf(ficresphtmfr," Weighted mean and standard deviation of");
                   4731:        }
1.285     brouard  4732:        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]));
                   4733:        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]));
                   4734:        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  4735:       }
                   4736:       /* for (z1=1; z1<= nqtveff; z1++) { */
                   4737:       /*       for(m=1;m<=lastpass;m++){ */
                   4738:       /*         fprintf(ficresphtmfr,"V quantitative id %d, pass id=%d, mean=%f<p>\n", z1, m, meanqt[m][z1]); */
                   4739:       /*   } */
                   4740:       /* } */
1.283     brouard  4741: 
1.251     brouard  4742:       fprintf(ficresphtm,"<table style=\"text-align:center; border: 1px solid\">");
1.265     brouard  4743:       if((cptcoveff==0 && nj==1)|| nj==2 ) /* no covariate and first pass */
                   4744:         fprintf(ficresp, " Age");
                   4745:       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  4746:       for(i=1; i<=nlstate;i++) {
1.265     brouard  4747:        if((cptcoveff==0 && nj==1)|| nj==2 ) fprintf(ficresp," Prev(%d)  N(%d)  N  ",i,i);
1.251     brouard  4748:        fprintf(ficresphtm, "<th>Age</th><th>Prev(%d)</th><th>N(%d)</th><th>N</th>",i,i);
                   4749:       }
1.265     brouard  4750:       if((cptcoveff==0 && nj==1)|| nj==2 ) fprintf(ficresp, "\n");
1.251     brouard  4751:       fprintf(ficresphtm, "\n");
                   4752:       
                   4753:       /* Header of frequency table by age */
                   4754:       fprintf(ficresphtmfr,"<table style=\"text-align:center; border: 1px solid\">");
                   4755:       fprintf(ficresphtmfr,"<th>Age</th> ");
1.265     brouard  4756:       for(s2=-1; s2 <=nlstate+ndeath; s2++){
1.251     brouard  4757:        for(m=-1; m <=nlstate+ndeath; m++){
1.265     brouard  4758:          if(s2!=0 && m!=0)
                   4759:            fprintf(ficresphtmfr,"<th>%d%d</th> ",s2,m);
1.240     brouard  4760:        }
1.226     brouard  4761:       }
1.251     brouard  4762:       fprintf(ficresphtmfr, "\n");
                   4763:     
                   4764:       /* For each age */
                   4765:       for(iage=iagemin; iage <= iagemax+3; iage++){
                   4766:        fprintf(ficresphtm,"<tr>");
                   4767:        if(iage==iagemax+1){
                   4768:          fprintf(ficlog,"1");
                   4769:          fprintf(ficresphtmfr,"<tr><th>0</th> ");
                   4770:        }else if(iage==iagemax+2){
                   4771:          fprintf(ficlog,"0");
                   4772:          fprintf(ficresphtmfr,"<tr><th>Unknown</th> ");
                   4773:        }else if(iage==iagemax+3){
                   4774:          fprintf(ficlog,"Total");
                   4775:          fprintf(ficresphtmfr,"<tr><th>Total</th> ");
                   4776:        }else{
1.240     brouard  4777:          if(first==1){
1.251     brouard  4778:            first=0;
                   4779:            printf("See log file for details...\n");
                   4780:          }
                   4781:          fprintf(ficresphtmfr,"<tr><th>%d</th> ",iage);
                   4782:          fprintf(ficlog,"Age %d", iage);
                   4783:        }
1.265     brouard  4784:        for(s1=1; s1 <=nlstate ; s1++){
                   4785:          for(m=-1, pp[s1]=0; m <=nlstate+ndeath ; m++)
                   4786:            pp[s1] += freq[s1][m][iage]; 
1.251     brouard  4787:        }
1.265     brouard  4788:        for(s1=1; s1 <=nlstate ; s1++){
1.251     brouard  4789:          for(m=-1, pos=0; m <=0 ; m++)
1.265     brouard  4790:            pos += freq[s1][m][iage];
                   4791:          if(pp[s1]>=1.e-10){
1.251     brouard  4792:            if(first==1){
1.265     brouard  4793:              printf(" %d.=%.0f loss[%d]=%.1f%%",s1,pp[s1],s1,100*pos/pp[s1]);
1.251     brouard  4794:            }
1.265     brouard  4795:            fprintf(ficlog," %d.=%.0f loss[%d]=%.1f%%",s1,pp[s1],s1,100*pos/pp[s1]);
1.251     brouard  4796:          }else{
                   4797:            if(first==1)
1.265     brouard  4798:              printf(" %d.=%.0f loss[%d]=NaNQ%%",s1,pp[s1],s1);
                   4799:            fprintf(ficlog," %d.=%.0f loss[%d]=NaNQ%%",s1,pp[s1],s1);
1.240     brouard  4800:          }
                   4801:        }
                   4802:       
1.265     brouard  4803:        for(s1=1; s1 <=nlstate ; s1++){ 
                   4804:          /* posprop[s1]=0; */
                   4805:          for(m=0, pp[s1]=0; m <=nlstate+ndeath; m++)/* Summing on all ages */
                   4806:            pp[s1] += freq[s1][m][iage];
                   4807:        }       /* pp[s1] is the total number of transitions starting from state s1 and any ending status until this age */
                   4808:       
                   4809:        for(s1=1,pos=0, pospropta=0.; s1 <=nlstate ; s1++){
                   4810:          pos += pp[s1]; /* pos is the total number of transitions until this age */
                   4811:          posprop[s1] += prop[s1][iage]; /* prop is the number of transitions from a live state
                   4812:                                            from s1 at age iage prop[s[m][iind]][(int)agev[m][iind]] += weight[iind] */
                   4813:          pospropta += prop[s1][iage]; /* prop is the number of transitions from a live state
                   4814:                                          from s1 at age iage prop[s[m][iind]][(int)agev[m][iind]] += weight[iind] */
                   4815:        }
                   4816:        
                   4817:        /* Writing ficresp */
                   4818:        if(cptcoveff==0 && nj==1){ /* no covariate and first pass */
                   4819:           if( iage <= iagemax){
                   4820:            fprintf(ficresp," %d",iage);
                   4821:           }
                   4822:         }else if( nj==2){
                   4823:           if( iage <= iagemax){
                   4824:            fprintf(ficresp," %d",iage);
                   4825:             for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresp, " %d %d",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
                   4826:           }
1.240     brouard  4827:        }
1.265     brouard  4828:        for(s1=1; s1 <=nlstate ; s1++){
1.240     brouard  4829:          if(pos>=1.e-5){
1.251     brouard  4830:            if(first==1)
1.265     brouard  4831:              printf(" %d.=%.0f prev[%d]=%.1f%%",s1,pp[s1],s1,100*pp[s1]/pos);
                   4832:            fprintf(ficlog," %d.=%.0f prev[%d]=%.1f%%",s1,pp[s1],s1,100*pp[s1]/pos);
1.251     brouard  4833:          }else{
                   4834:            if(first==1)
1.265     brouard  4835:              printf(" %d.=%.0f prev[%d]=NaNQ%%",s1,pp[s1],s1);
                   4836:            fprintf(ficlog," %d.=%.0f prev[%d]=NaNQ%%",s1,pp[s1],s1);
1.251     brouard  4837:          }
                   4838:          if( iage <= iagemax){
                   4839:            if(pos>=1.e-5){
1.265     brouard  4840:              if(cptcoveff==0 && nj==1){ /* no covariate and first pass */
                   4841:                fprintf(ficresp," %.5f %.0f %.0f",prop[s1][iage]/pospropta, prop[s1][iage],pospropta);
                   4842:               }else if( nj==2){
                   4843:                fprintf(ficresp," %.5f %.0f %.0f",prop[s1][iage]/pospropta, prop[s1][iage],pospropta);
                   4844:               }
                   4845:              fprintf(ficresphtm,"<th>%d</th><td>%.5f</td><td>%.0f</td><td>%.0f</td>",iage,prop[s1][iage]/pospropta, prop[s1][iage],pospropta);
                   4846:              /*probs[iage][s1][j1]= pp[s1]/pos;*/
                   4847:              /*printf("\niage=%d s1=%d j1=%d %.5f %.0f %.0f %f",iage,s1,j1,pp[s1]/pos, pp[s1],pos,probs[iage][s1][j1]);*/
                   4848:            } else{
                   4849:              if((cptcoveff==0 && nj==1)|| nj==2 ) fprintf(ficresp," NaNq %.0f %.0f",prop[s1][iage],pospropta);
                   4850:              fprintf(ficresphtm,"<th>%d</th><td>NaNq</td><td>%.0f</td><td>%.0f</td>",iage, prop[s1][iage],pospropta);
1.251     brouard  4851:            }
1.240     brouard  4852:          }
1.265     brouard  4853:          pospropt[s1] +=posprop[s1];
                   4854:        } /* end loop s1 */
1.251     brouard  4855:        /* pospropt=0.; */
1.265     brouard  4856:        for(s1=-1; s1 <=nlstate+ndeath; s1++){
1.251     brouard  4857:          for(m=-1; m <=nlstate+ndeath; m++){
1.265     brouard  4858:            if(freq[s1][m][iage] !=0 ) { /* minimizing output */
1.251     brouard  4859:              if(first==1){
1.265     brouard  4860:                printf(" %d%d=%.0f",s1,m,freq[s1][m][iage]);
1.251     brouard  4861:              }
1.265     brouard  4862:              /* printf(" %d%d=%.0f",s1,m,freq[s1][m][iage]); */
                   4863:              fprintf(ficlog," %d%d=%.0f",s1,m,freq[s1][m][iage]);
1.251     brouard  4864:            }
1.265     brouard  4865:            if(s1!=0 && m!=0)
                   4866:              fprintf(ficresphtmfr,"<td>%.0f</td> ",freq[s1][m][iage]);
1.240     brouard  4867:          }
1.265     brouard  4868:        } /* end loop s1 */
1.251     brouard  4869:        posproptt=0.; 
1.265     brouard  4870:        for(s1=1; s1 <=nlstate; s1++){
                   4871:          posproptt += pospropt[s1];
1.251     brouard  4872:        }
                   4873:        fprintf(ficresphtmfr,"</tr>\n ");
1.265     brouard  4874:        fprintf(ficresphtm,"</tr>\n");
                   4875:        if((cptcoveff==0 && nj==1)|| nj==2 ) {
                   4876:          if(iage <= iagemax)
                   4877:            fprintf(ficresp,"\n");
1.240     brouard  4878:        }
1.251     brouard  4879:        if(first==1)
                   4880:          printf("Others in log...\n");
                   4881:        fprintf(ficlog,"\n");
                   4882:       } /* end loop age iage */
1.265     brouard  4883:       
1.251     brouard  4884:       fprintf(ficresphtm,"<tr><th>Tot</th>");
1.265     brouard  4885:       for(s1=1; s1 <=nlstate ; s1++){
1.251     brouard  4886:        if(posproptt < 1.e-5){
1.265     brouard  4887:          fprintf(ficresphtm,"<td>Nanq</td><td>%.0f</td><td>%.0f</td>",pospropt[s1],posproptt); 
1.251     brouard  4888:        }else{
1.265     brouard  4889:          fprintf(ficresphtm,"<td>%.5f</td><td>%.0f</td><td>%.0f</td>",pospropt[s1]/posproptt,pospropt[s1],posproptt);  
1.240     brouard  4890:        }
1.226     brouard  4891:       }
1.251     brouard  4892:       fprintf(ficresphtm,"</tr>\n");
                   4893:       fprintf(ficresphtm,"</table>\n");
                   4894:       fprintf(ficresphtmfr,"</table>\n");
1.226     brouard  4895:       if(posproptt < 1.e-5){
1.251     brouard  4896:        fprintf(ficresphtm,"\n <p><b> This combination (%d) is not valid and no result will be produced</b></p>",j1);
                   4897:        fprintf(ficresphtmfr,"\n <p><b> This combination (%d) is not valid and no result will be produced</b></p>",j1);
1.260     brouard  4898:        fprintf(ficlog,"#  This combination (%d) is not valid and no result will be produced\n",j1);
                   4899:        printf("#  This combination (%d) is not valid and no result will be produced\n",j1);
1.251     brouard  4900:        invalidvarcomb[j1]=1;
1.226     brouard  4901:       }else{
1.251     brouard  4902:        fprintf(ficresphtm,"\n <p> This combination (%d) is valid and result will be produced.</p>",j1);
                   4903:        invalidvarcomb[j1]=0;
1.226     brouard  4904:       }
1.251     brouard  4905:       fprintf(ficresphtmfr,"</table>\n");
                   4906:       fprintf(ficlog,"\n");
                   4907:       if(j!=0){
                   4908:        printf("#Freqsummary: Starting values for combination j1=%d:\n", j1);
1.265     brouard  4909:        for(i=1,s1=1; i <=nlstate; i++){
1.251     brouard  4910:          for(k=1; k <=(nlstate+ndeath); k++){
                   4911:            if (k != i) {
1.265     brouard  4912:              for(jj=1; jj <=ncovmodel; jj++){ /* For counting s1 */
1.253     brouard  4913:                if(jj==1){  /* Constant case (in fact cste + age) */
1.251     brouard  4914:                  if(j1==1){ /* All dummy covariates to zero */
                   4915:                    freq[i][k][iagemax+4]=freq[i][k][iagemax+3]; /* Stores case 0 0 0 */
                   4916:                    freq[i][i][iagemax+4]=freq[i][i][iagemax+3]; /* Stores case 0 0 0 */
1.252     brouard  4917:                    printf("%d%d ",i,k);
                   4918:                    fprintf(ficlog,"%d%d ",i,k);
1.265     brouard  4919:                    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]));
                   4920:                    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]));
                   4921:                    pstart[s1]= log(freq[i][k][iagemax+3]/freq[i][i][iagemax+3]);
1.251     brouard  4922:                  }
1.253     brouard  4923:                }else if((j1==1) && (jj==2 || nagesqr==1)){ /* age or age*age parameter without covariate V4*age (to be done later) */
                   4924:                  for(iage=iagemin; iage <= iagemax+3; iage++){
                   4925:                    x[iage]= (double)iage;
                   4926:                    y[iage]= log(freq[i][k][iage]/freq[i][i][iage]);
1.265     brouard  4927:                    /* 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  4928:                  }
1.268     brouard  4929:                  /* Some are not finite, but linreg will ignore these ages */
                   4930:                  no=0;
1.253     brouard  4931:                  linreg(iagemin,iagemax,&no,x,y,&a,&b,&r, &sa, &sb ); /* y= a+b*x with standard errors */
1.265     brouard  4932:                  pstart[s1]=b;
                   4933:                  pstart[s1-1]=a;
1.252     brouard  4934:                }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 */ 
                   4935:                  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]);
                   4936:                  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  4937:                  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  4938:                  printf("%d%d ",i,k);
                   4939:                  fprintf(ficlog,"%d%d ",i,k);
1.265     brouard  4940:                  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  4941:                }else{ /* Other cases, like quantitative fixed or varying covariates */
                   4942:                  ;
                   4943:                }
                   4944:                /* printf("%12.7f )", param[i][jj][k]); */
                   4945:                /* fprintf(ficlog,"%12.7f )", param[i][jj][k]); */
1.265     brouard  4946:                s1++; 
1.251     brouard  4947:              } /* end jj */
                   4948:            } /* end k!= i */
                   4949:          } /* end k */
1.265     brouard  4950:        } /* end i, s1 */
1.251     brouard  4951:       } /* end j !=0 */
                   4952:     } /* end selected combination of covariate j1 */
                   4953:     if(j==0){ /* We can estimate starting values from the occurences in each case */
                   4954:       printf("#Freqsummary: Starting values for the constants:\n");
                   4955:       fprintf(ficlog,"\n");
1.265     brouard  4956:       for(i=1,s1=1; i <=nlstate; i++){
1.251     brouard  4957:        for(k=1; k <=(nlstate+ndeath); k++){
                   4958:          if (k != i) {
                   4959:            printf("%d%d ",i,k);
                   4960:            fprintf(ficlog,"%d%d ",i,k);
                   4961:            for(jj=1; jj <=ncovmodel; jj++){
1.265     brouard  4962:              pstart[s1]=p[s1]; /* Setting pstart to p values by default */
1.253     brouard  4963:              if(jj==1){ /* Age has to be done */
1.265     brouard  4964:                pstart[s1]= log(freq[i][k][iagemax+3]/freq[i][i][iagemax+3]);
                   4965:                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]));
                   4966:                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  4967:              }
                   4968:              /* printf("%12.7f )", param[i][jj][k]); */
                   4969:              /* fprintf(ficlog,"%12.7f )", param[i][jj][k]); */
1.265     brouard  4970:              s1++; 
1.250     brouard  4971:            }
1.251     brouard  4972:            printf("\n");
                   4973:            fprintf(ficlog,"\n");
1.250     brouard  4974:          }
                   4975:        }
1.284     brouard  4976:       } /* end of state i */
1.251     brouard  4977:       printf("#Freqsummary\n");
                   4978:       fprintf(ficlog,"\n");
1.265     brouard  4979:       for(s1=-1; s1 <=nlstate+ndeath; s1++){
                   4980:        for(s2=-1; s2 <=nlstate+ndeath; s2++){
                   4981:          /* param[i]|j][k]= freq[s1][s2][iagemax+3] */
                   4982:          printf(" %d%d=%.0f",s1,s2,freq[s1][s2][iagemax+3]);
                   4983:          fprintf(ficlog," %d%d=%.0f",s1,s2,freq[s1][s2][iagemax+3]);
                   4984:          /* if(freq[s1][s2][iage] !=0 ) { /\* minimizing output *\/ */
                   4985:          /*   printf(" %d%d=%.0f",s1,s2,freq[s1][s2][iagemax+3]); */
                   4986:          /*   fprintf(ficlog," %d%d=%.0f",s1,s2,freq[s1][s2][iagemax+3]); */
1.251     brouard  4987:          /* } */
                   4988:        }
1.265     brouard  4989:       } /* end loop s1 */
1.251     brouard  4990:       
                   4991:       printf("\n");
                   4992:       fprintf(ficlog,"\n");
                   4993:     } /* end j=0 */
1.249     brouard  4994:   } /* end j */
1.252     brouard  4995: 
1.253     brouard  4996:   if(mle == -2){  /* We want to use these values as starting values */
1.252     brouard  4997:     for(i=1, jk=1; i <=nlstate; i++){
                   4998:       for(j=1; j <=nlstate+ndeath; j++){
                   4999:        if(j!=i){
                   5000:          /*ca[0]= k+'a'-1;ca[1]='\0';*/
                   5001:          printf("%1d%1d",i,j);
                   5002:          fprintf(ficparo,"%1d%1d",i,j);
                   5003:          for(k=1; k<=ncovmodel;k++){
                   5004:            /*    printf(" %lf",param[i][j][k]); */
                   5005:            /*    fprintf(ficparo," %lf",param[i][j][k]); */
                   5006:            p[jk]=pstart[jk];
                   5007:            printf(" %f ",pstart[jk]);
                   5008:            fprintf(ficparo," %f ",pstart[jk]);
                   5009:            jk++;
                   5010:          }
                   5011:          printf("\n");
                   5012:          fprintf(ficparo,"\n");
                   5013:        }
                   5014:       }
                   5015:     }
                   5016:   } /* end mle=-2 */
1.226     brouard  5017:   dateintmean=dateintsum/k2cpt; 
1.296     brouard  5018:   date2dmy(dateintmean,&jintmean,&mintmean,&aintmean);
1.240     brouard  5019:   
1.226     brouard  5020:   fclose(ficresp);
                   5021:   fclose(ficresphtm);
                   5022:   fclose(ficresphtmfr);
1.283     brouard  5023:   free_vector(idq,1,nqfveff);
1.226     brouard  5024:   free_vector(meanq,1,nqfveff);
1.284     brouard  5025:   free_vector(stdq,1,nqfveff);
1.226     brouard  5026:   free_matrix(meanqt,1,lastpass,1,nqtveff);
1.253     brouard  5027:   free_vector(x, iagemin-AGEMARGE, iagemax+4+AGEMARGE);
                   5028:   free_vector(y, iagemin-AGEMARGE, iagemax+4+AGEMARGE);
1.251     brouard  5029:   free_ma3x(freq,-5,nlstate+ndeath,-5,nlstate+ndeath, iagemin-AGEMARGE, iagemax+4+AGEMARGE);
1.226     brouard  5030:   free_vector(pospropt,1,nlstate);
                   5031:   free_vector(posprop,1,nlstate);
1.251     brouard  5032:   free_matrix(prop,1,nlstate,iagemin-AGEMARGE, iagemax+4+AGEMARGE);
1.226     brouard  5033:   free_vector(pp,1,nlstate);
                   5034:   /* End of freqsummary */
                   5035: }
1.126     brouard  5036: 
1.268     brouard  5037: /* Simple linear regression */
                   5038: int linreg(int ifi, int ila, int *no, const double x[], const double y[], double* a, double* b, double* r, double* sa, double * sb) {
                   5039: 
                   5040:   /* y=a+bx regression */
                   5041:   double   sumx = 0.0;                        /* sum of x                      */
                   5042:   double   sumx2 = 0.0;                       /* sum of x**2                   */
                   5043:   double   sumxy = 0.0;                       /* sum of x * y                  */
                   5044:   double   sumy = 0.0;                        /* sum of y                      */
                   5045:   double   sumy2 = 0.0;                       /* sum of y**2                   */
                   5046:   double   sume2 = 0.0;                       /* sum of square or residuals */
                   5047:   double yhat;
                   5048:   
                   5049:   double denom=0;
                   5050:   int i;
                   5051:   int ne=*no;
                   5052:   
                   5053:   for ( i=ifi, ne=0;i<=ila;i++) {
                   5054:     if(!isfinite(x[i]) || !isfinite(y[i])){
                   5055:       /* printf(" x[%d]=%f, y[%d]=%f\n",i,x[i],i,y[i]); */
                   5056:       continue;
                   5057:     }
                   5058:     ne=ne+1;
                   5059:     sumx  += x[i];       
                   5060:     sumx2 += x[i]*x[i];  
                   5061:     sumxy += x[i] * y[i];
                   5062:     sumy  += y[i];      
                   5063:     sumy2 += y[i]*y[i]; 
                   5064:     denom = (ne * sumx2 - sumx*sumx);
                   5065:     /* 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); */
                   5066:   } 
                   5067:   
                   5068:   denom = (ne * sumx2 - sumx*sumx);
                   5069:   if (denom == 0) {
                   5070:     // vertical, slope m is infinity
                   5071:     *b = INFINITY;
                   5072:     *a = 0;
                   5073:     if (r) *r = 0;
                   5074:     return 1;
                   5075:   }
                   5076:   
                   5077:   *b = (ne * sumxy  -  sumx * sumy) / denom;
                   5078:   *a = (sumy * sumx2  -  sumx * sumxy) / denom;
                   5079:   if (r!=NULL) {
                   5080:     *r = (sumxy - sumx * sumy / ne) /          /* compute correlation coeff     */
                   5081:       sqrt((sumx2 - sumx*sumx/ne) *
                   5082:           (sumy2 - sumy*sumy/ne));
                   5083:   }
                   5084:   *no=ne;
                   5085:   for ( i=ifi, ne=0;i<=ila;i++) {
                   5086:     if(!isfinite(x[i]) || !isfinite(y[i])){
                   5087:       /* printf(" x[%d]=%f, y[%d]=%f\n",i,x[i],i,y[i]); */
                   5088:       continue;
                   5089:     }
                   5090:     ne=ne+1;
                   5091:     yhat = y[i] - *a -*b* x[i];
                   5092:     sume2  += yhat * yhat ;       
                   5093:     
                   5094:     denom = (ne * sumx2 - sumx*sumx);
                   5095:     /* 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); */
                   5096:   } 
                   5097:   *sb = sqrt(sume2/(double)(ne-2)/(sumx2 - sumx * sumx /(double)ne));
                   5098:   *sa= *sb * sqrt(sumx2/ne);
                   5099:   
                   5100:   return 0; 
                   5101: }
                   5102: 
1.126     brouard  5103: /************ Prevalence ********************/
1.227     brouard  5104: 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)
                   5105: {  
                   5106:   /* Compute observed prevalence between dateprev1 and dateprev2 by counting the number of people
                   5107:      in each health status at the date of interview (if between dateprev1 and dateprev2).
                   5108:      We still use firstpass and lastpass as another selection.
                   5109:   */
1.126     brouard  5110:  
1.227     brouard  5111:   int i, m, jk, j1, bool, z1,j, iv;
                   5112:   int mi; /* Effective wave */
                   5113:   int iage;
                   5114:   double agebegin, ageend;
                   5115: 
                   5116:   double **prop;
                   5117:   double posprop; 
                   5118:   double  y2; /* in fractional years */
                   5119:   int iagemin, iagemax;
                   5120:   int first; /** to stop verbosity which is redirected to log file */
                   5121: 
                   5122:   iagemin= (int) agemin;
                   5123:   iagemax= (int) agemax;
                   5124:   /*pp=vector(1,nlstate);*/
1.251     brouard  5125:   prop=matrix(1,nlstate,iagemin-AGEMARGE,iagemax+4+AGEMARGE); 
1.227     brouard  5126:   /*  freq=ma3x(-1,nlstate+ndeath,-1,nlstate+ndeath,iagemin,iagemax+3);*/
                   5127:   j1=0;
1.222     brouard  5128:   
1.227     brouard  5129:   /*j=cptcoveff;*/
                   5130:   if (cptcovn<1) {j=1;ncodemax[1]=1;}
1.222     brouard  5131:   
1.288     brouard  5132:   first=0;
1.227     brouard  5133:   for(j1=1; j1<= (int) pow(2,cptcoveff);j1++){ /* For each combination of covariate */
                   5134:     for (i=1; i<=nlstate; i++)  
1.251     brouard  5135:       for(iage=iagemin-AGEMARGE; iage <= iagemax+4+AGEMARGE; iage++)
1.227     brouard  5136:        prop[i][iage]=0.0;
                   5137:     printf("Prevalence combination of varying and fixed dummies %d\n",j1);
                   5138:     /* fprintf(ficlog," V%d=%d ",Tvaraff[j1],nbcode[Tvaraff[j1]][codtabm(k,j1)]); */
                   5139:     fprintf(ficlog,"Prevalence combination of varying and fixed dummies %d\n",j1);
                   5140:     
                   5141:     for (i=1; i<=imx; i++) { /* Each individual */
                   5142:       bool=1;
                   5143:       /* for(m=firstpass; m<=lastpass; m++){/\* Other selection (we can limit to certain interviews*\/ */
                   5144:       for(mi=1; mi<wav[i];mi++){ /* For this wave too look where individual can be counted V4=0 V3=0 */
                   5145:        m=mw[mi][i];
                   5146:        /* Tmodelind[z1]=k is the position of the varying covariate in the model, but which # within 1 to ntv? */
                   5147:        /* Tvar[Tmodelind[z1]] is the n of Vn; n-ncovcol-nqv is the first time varying covariate or iv */
                   5148:        for (z1=1; z1<=cptcoveff; z1++){
                   5149:          if( Fixed[Tmodelind[z1]]==1){
                   5150:            iv= Tvar[Tmodelind[z1]]-ncovcol-nqv;
                   5151:            if (cotvar[m][iv][i]!= nbcode[Tvaraff[z1]][codtabm(j1,z1)]) /* iv=1 to ntv, right modality */
                   5152:              bool=0;
                   5153:          }else if( Fixed[Tmodelind[z1]]== 0)  /* fixed */
                   5154:            if (covar[Tvaraff[z1]][i]!= nbcode[Tvaraff[z1]][codtabm(j1,z1)]) {
                   5155:              bool=0;
                   5156:            }
                   5157:        }
                   5158:        if(bool==1){ /* Otherwise we skip that wave/person */
                   5159:          agebegin=agev[m][i]; /* Age at beginning of wave before transition*/
                   5160:          /* ageend=agev[m][i]+(dh[m][i])*stepm/YEARM; /\* Age at end of wave and transition *\/ */
                   5161:          if(m >=firstpass && m <=lastpass){
                   5162:            y2=anint[m][i]+(mint[m][i]/12.); /* Fractional date in year */
                   5163:            if ((y2>=dateprev1) && (y2<=dateprev2)) { /* Here is the main selection (fractional years) */
                   5164:              if(agev[m][i]==0) agev[m][i]=iagemax+1;
                   5165:              if(agev[m][i]==1) agev[m][i]=iagemax+2;
1.251     brouard  5166:              if((int)agev[m][i] <iagemin-AGEMARGE || (int)agev[m][i] >iagemax+4+AGEMARGE){
1.227     brouard  5167:                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); 
                   5168:                exit(1);
                   5169:              }
                   5170:              if (s[m][i]>0 && s[m][i]<=nlstate) { 
                   5171:                /*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]]);*/
                   5172:                prop[s[m][i]][(int)agev[m][i]] += weight[i];/* At age of beginning of transition, where status is known */
                   5173:                prop[s[m][i]][iagemax+3] += weight[i]; 
                   5174:              } /* end valid statuses */ 
                   5175:            } /* end selection of dates */
                   5176:          } /* end selection of waves */
                   5177:        } /* end bool */
                   5178:       } /* end wave */
                   5179:     } /* end individual */
                   5180:     for(i=iagemin; i <= iagemax+3; i++){  
                   5181:       for(jk=1,posprop=0; jk <=nlstate ; jk++) { 
                   5182:        posprop += prop[jk][i]; 
                   5183:       } 
                   5184:       
                   5185:       for(jk=1; jk <=nlstate ; jk++){      
                   5186:        if( i <=  iagemax){ 
                   5187:          if(posprop>=1.e-5){ 
                   5188:            probs[i][jk][j1]= prop[jk][i]/posprop;
                   5189:          } else{
1.288     brouard  5190:            if(!first){
                   5191:              first=1;
1.266     brouard  5192:              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]);
                   5193:            }else{
1.288     brouard  5194:              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  5195:            }
                   5196:          }
                   5197:        } 
                   5198:       }/* end jk */ 
                   5199:     }/* end i */ 
1.222     brouard  5200:      /*} *//* end i1 */
1.227     brouard  5201:   } /* end j1 */
1.222     brouard  5202:   
1.227     brouard  5203:   /*  free_ma3x(freq,-1,nlstate+ndeath,-1,nlstate+ndeath, iagemin, iagemax+3);*/
                   5204:   /*free_vector(pp,1,nlstate);*/
1.251     brouard  5205:   free_matrix(prop,1,nlstate, iagemin-AGEMARGE,iagemax+4+AGEMARGE);
1.227     brouard  5206: }  /* End of prevalence */
1.126     brouard  5207: 
                   5208: /************* Waves Concatenation ***************/
                   5209: 
                   5210: 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)
                   5211: {
1.298     brouard  5212:   /* 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  5213:      Death is a valid wave (if date is known).
                   5214:      mw[mi][i] is the mi (mi=1 to wav[i])  effective wave of individual i
                   5215:      dh[m][i] or dh[mw[mi][i]][i] is the delay between two effective waves m=mw[mi][i]
1.298     brouard  5216:      and mw[mi+1][i]. dh depends on stepm. s[m][i] exists for any wave from firstpass to lastpass
1.227     brouard  5217:   */
1.126     brouard  5218: 
1.224     brouard  5219:   int i=0, mi=0, m=0, mli=0;
1.126     brouard  5220:   /* int j, k=0,jk, ju, jl,jmin=1e+5, jmax=-1;
                   5221:      double sum=0., jmean=0.;*/
1.224     brouard  5222:   int first=0, firstwo=0, firsthree=0, firstfour=0, firstfiv=0;
1.126     brouard  5223:   int j, k=0,jk, ju, jl;
                   5224:   double sum=0.;
                   5225:   first=0;
1.214     brouard  5226:   firstwo=0;
1.217     brouard  5227:   firsthree=0;
1.218     brouard  5228:   firstfour=0;
1.164     brouard  5229:   jmin=100000;
1.126     brouard  5230:   jmax=-1;
                   5231:   jmean=0.;
1.224     brouard  5232: 
                   5233: /* Treating live states */
1.214     brouard  5234:   for(i=1; i<=imx; i++){  /* For simple cases and if state is death */
1.224     brouard  5235:     mi=0;  /* First valid wave */
1.227     brouard  5236:     mli=0; /* Last valid wave */
1.126     brouard  5237:     m=firstpass;
1.214     brouard  5238:     while(s[m][i] <= nlstate){  /* a live state */
1.227     brouard  5239:       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 */
                   5240:        mli=m-1;/* mw[++mi][i]=m-1; */
                   5241:       }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 */
                   5242:        mw[++mi][i]=m;
                   5243:        mli=m;
1.224     brouard  5244:       } /* else might be a useless wave  -1 and mi is not incremented and mw[mi] not updated */
                   5245:       if(m < lastpass){ /* m < lastpass, standard case */
1.227     brouard  5246:        m++; /* mi gives the "effective" current wave, m the current wave, go to next wave by incrementing m */
1.216     brouard  5247:       }
1.227     brouard  5248:       else{ /* m >= lastpass, eventual special issue with warning */
1.224     brouard  5249: #ifdef UNKNOWNSTATUSNOTCONTRIBUTING
1.227     brouard  5250:        break;
1.224     brouard  5251: #else
1.227     brouard  5252:        if(s[m][i]==-1 && (int) andc[i] == 9999 && (int)anint[m][i] != 9999){
                   5253:          if(firsthree == 0){
1.262     brouard  5254:            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  5255:            firsthree=1;
                   5256:          }
1.262     brouard  5257:          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  5258:          mw[++mi][i]=m;
                   5259:          mli=m;
                   5260:        }
                   5261:        if(s[m][i]==-2){ /* Vital status is really unknown */
                   5262:          nbwarn++;
                   5263:          if((int)anint[m][i] == 9999){  /*  Has the vital status really been verified? */
                   5264:            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);
                   5265:            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);
                   5266:          }
                   5267:          break;
                   5268:        }
                   5269:        break;
1.224     brouard  5270: #endif
1.227     brouard  5271:       }/* End m >= lastpass */
1.126     brouard  5272:     }/* end while */
1.224     brouard  5273: 
1.227     brouard  5274:     /* 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  5275:     /* After last pass */
1.224     brouard  5276: /* Treating death states */
1.214     brouard  5277:     if (s[m][i] > nlstate){  /* In a death state */
1.227     brouard  5278:       /* if( mint[m][i]==mdc[m][i] && anint[m][i]==andc[m][i]){ /\* same date of death and date of interview *\/ */
                   5279:       /* } */
1.126     brouard  5280:       mi++;    /* Death is another wave */
                   5281:       /* if(mi==0)  never been interviewed correctly before death */
1.227     brouard  5282:       /* Only death is a correct wave */
1.126     brouard  5283:       mw[mi][i]=m;
1.257     brouard  5284:     } /* else not in a death state */
1.224     brouard  5285: #ifndef DISPATCHINGKNOWNDEATHAFTERLASTWAVE
1.257     brouard  5286:     else if ((int) andc[i] != 9999) {  /* Date of death is known */
1.218     brouard  5287:       if ((int)anint[m][i]!= 9999) { /* date of last interview is known */
1.227     brouard  5288:        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 */
                   5289:          nbwarn++;
                   5290:          if(firstfiv==0){
                   5291:            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 );
                   5292:            firstfiv=1;
                   5293:          }else{
                   5294:            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 );
                   5295:          }
                   5296:        }else{ /* Death occured afer last wave potential bias */
                   5297:          nberr++;
                   5298:          if(firstwo==0){
1.257     brouard  5299:            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  5300:            firstwo=1;
                   5301:          }
1.257     brouard  5302:          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  5303:        }
1.257     brouard  5304:       }else{ /* if date of interview is unknown */
1.227     brouard  5305:        /* death is known but not confirmed by death status at any wave */
                   5306:        if(firstfour==0){
                   5307:          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 );
                   5308:          firstfour=1;
                   5309:        }
                   5310:        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  5311:       }
1.224     brouard  5312:     } /* end if date of death is known */
                   5313: #endif
                   5314:     wav[i]=mi; /* mi should be the last effective wave (or mli) */
                   5315:     /* wav[i]=mw[mi][i]; */
1.126     brouard  5316:     if(mi==0){
                   5317:       nbwarn++;
                   5318:       if(first==0){
1.227     brouard  5319:        printf("Warning! No valid information for individual %ld line=%d (skipped) and may be others, see log file\n",num[i],i);
                   5320:        first=1;
1.126     brouard  5321:       }
                   5322:       if(first==1){
1.227     brouard  5323:        fprintf(ficlog,"Warning! No valid information for individual %ld line=%d (skipped)\n",num[i],i);
1.126     brouard  5324:       }
                   5325:     } /* end mi==0 */
                   5326:   } /* End individuals */
1.214     brouard  5327:   /* wav and mw are no more changed */
1.223     brouard  5328:        
1.214     brouard  5329:   
1.126     brouard  5330:   for(i=1; i<=imx; i++){
                   5331:     for(mi=1; mi<wav[i];mi++){
                   5332:       if (stepm <=0)
1.227     brouard  5333:        dh[mi][i]=1;
1.126     brouard  5334:       else{
1.260     brouard  5335:        if (s[mw[mi+1][i]][i] > nlstate) { /* A death, but what if date is unknown? */
1.227     brouard  5336:          if (agedc[i] < 2*AGESUP) {
                   5337:            j= rint(agedc[i]*12-agev[mw[mi][i]][i]*12); 
                   5338:            if(j==0) j=1;  /* Survives at least one month after exam */
                   5339:            else if(j<0){
                   5340:              nberr++;
                   5341:              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]);
                   5342:              j=1; /* Temporary Dangerous patch */
                   5343:              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);
                   5344:              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]);
                   5345:              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);
                   5346:            }
                   5347:            k=k+1;
                   5348:            if (j >= jmax){
                   5349:              jmax=j;
                   5350:              ijmax=i;
                   5351:            }
                   5352:            if (j <= jmin){
                   5353:              jmin=j;
                   5354:              ijmin=i;
                   5355:            }
                   5356:            sum=sum+j;
                   5357:            /*if (j<0) printf("j=%d num=%d \n",j,i);*/
                   5358:            /*    printf("%d %d %d %d\n", s[mw[mi][i]][i] ,s[mw[mi+1][i]][i],j,i);*/
                   5359:          }
                   5360:        }
                   5361:        else{
                   5362:          j= rint( (agev[mw[mi+1][i]][i]*12 - agev[mw[mi][i]][i]*12));
1.126     brouard  5363: /*       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  5364:                                        
1.227     brouard  5365:          k=k+1;
                   5366:          if (j >= jmax) {
                   5367:            jmax=j;
                   5368:            ijmax=i;
                   5369:          }
                   5370:          else if (j <= jmin){
                   5371:            jmin=j;
                   5372:            ijmin=i;
                   5373:          }
                   5374:          /*        if (j<10) printf("j=%d jmin=%d num=%d ",j,jmin,i); */
                   5375:          /*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]);*/
                   5376:          if(j<0){
                   5377:            nberr++;
                   5378:            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]);
                   5379:            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]);
                   5380:          }
                   5381:          sum=sum+j;
                   5382:        }
                   5383:        jk= j/stepm;
                   5384:        jl= j -jk*stepm;
                   5385:        ju= j -(jk+1)*stepm;
                   5386:        if(mle <=1){ /* only if we use a the linear-interpoloation pseudo-likelihood */
                   5387:          if(jl==0){
                   5388:            dh[mi][i]=jk;
                   5389:            bh[mi][i]=0;
                   5390:          }else{ /* We want a negative bias in order to only have interpolation ie
                   5391:                  * to avoid the price of an extra matrix product in likelihood */
                   5392:            dh[mi][i]=jk+1;
                   5393:            bh[mi][i]=ju;
                   5394:          }
                   5395:        }else{
                   5396:          if(jl <= -ju){
                   5397:            dh[mi][i]=jk;
                   5398:            bh[mi][i]=jl;       /* bias is positive if real duration
                   5399:                                 * is higher than the multiple of stepm and negative otherwise.
                   5400:                                 */
                   5401:          }
                   5402:          else{
                   5403:            dh[mi][i]=jk+1;
                   5404:            bh[mi][i]=ju;
                   5405:          }
                   5406:          if(dh[mi][i]==0){
                   5407:            dh[mi][i]=1; /* At least one step */
                   5408:            bh[mi][i]=ju; /* At least one step */
                   5409:            /*  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);*/
                   5410:          }
                   5411:        } /* end if mle */
1.126     brouard  5412:       }
                   5413:     } /* end wave */
                   5414:   }
                   5415:   jmean=sum/k;
                   5416:   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  5417:   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  5418: }
1.126     brouard  5419: 
                   5420: /*********** Tricode ****************************/
1.220     brouard  5421:  void tricode(int *cptcov, int *Tvar, int **nbcode, int imx, int *Ndum)
1.242     brouard  5422:  {
                   5423:    /**< Uses cptcovn+2*cptcovprod as the number of covariates */
                   5424:    /*    Tvar[i]=atoi(stre);  find 'n' in Vn and stores in Tvar. If model=V2+V1 Tvar[1]=2 and Tvar[2]=1 
                   5425:     * Boring subroutine which should only output nbcode[Tvar[j]][k]
                   5426:     * Tvar[5] in V2+V1+V3*age+V2*V4 is 4 (V4) even it is a time varying or quantitative variable
                   5427:     * nbcode[Tvar[5]][1]= nbcode[4][1]=0, nbcode[4][2]=1 (usually);
                   5428:     */
1.130     brouard  5429: 
1.242     brouard  5430:    int ij=1, k=0, j=0, i=0, maxncov=NCOVMAX;
                   5431:    int modmaxcovj=0; /* Modality max of covariates j */
                   5432:    int cptcode=0; /* Modality max of covariates j */
                   5433:    int modmincovj=0; /* Modality min of covariates j */
1.145     brouard  5434: 
                   5435: 
1.242     brouard  5436:    /* cptcoveff=0;  */
                   5437:    /* *cptcov=0; */
1.126     brouard  5438:  
1.242     brouard  5439:    for (k=1; k <= maxncov; k++) ncodemax[k]=0; /* Horrible constant again replaced by NCOVMAX */
1.285     brouard  5440:    for (k=1; k <= maxncov; k++)
                   5441:      for(j=1; j<=2; j++)
                   5442:        nbcode[k][j]=0; /* Valgrind */
1.126     brouard  5443: 
1.242     brouard  5444:    /* Loop on covariates without age and products and no quantitative variable */
                   5445:    for (k=1; k<=cptcovt; k++) { /* From model V1 + V2*age + V3 + V3*V4 keeps V1 + V3 = 2 only */
                   5446:      for (j=-1; (j < maxncov); j++) Ndum[j]=0;
                   5447:      if(Dummy[k]==0 && Typevar[k] !=1){ /* Dummy covariate and not age product */ 
                   5448:        switch(Fixed[k]) {
                   5449:        case 0: /* Testing on fixed dummy covariate, simple or product of fixed */
                   5450:         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*/
                   5451:           ij=(int)(covar[Tvar[k]][i]);
                   5452:           /* ij=0 or 1 or -1. Value of the covariate Tvar[j] for individual i
                   5453:            * If product of Vn*Vm, still boolean *:
                   5454:            * If it was coded 1, 2, 3, 4 should be splitted into 3 boolean variables
                   5455:            * 1 => 0 0 0, 2 => 0 0 1, 3 => 0 1 1, 4=1 0 0   */
                   5456:           /* Finds for covariate j, n=Tvar[j] of Vn . ij is the
                   5457:              modality of the nth covariate of individual i. */
                   5458:           if (ij > modmaxcovj)
                   5459:             modmaxcovj=ij; 
                   5460:           else if (ij < modmincovj) 
                   5461:             modmincovj=ij; 
1.287     brouard  5462:           if (ij <0 || ij >1 ){
                   5463:             printf("Information, IMaCh doesn't treat covariate with missing values (-1), individual %d will be skipped.\n",i);
                   5464:             fprintf(ficlog,"Information, currently IMaCh doesn't treat covariate with missing values (-1), individual %d will be skipped.\n",i);
                   5465:           }
                   5466:           if ((ij < -1) || (ij > NCOVMAX)){
1.242     brouard  5467:             printf( "Error: minimal is less than -1 or maximal is bigger than %d. Exiting. \n", NCOVMAX );
                   5468:             exit(1);
                   5469:           }else
                   5470:             Ndum[ij]++; /*counts and stores the occurence of this modality 0, 1, -1*/
                   5471:           /*  If coded 1, 2, 3 , counts the number of 1 Ndum[1], number of 2, Ndum[2], etc */
                   5472:           /*printf("i=%d ij=%d Ndum[ij]=%d imx=%d",i,ij,Ndum[ij],imx);*/
                   5473:           /* getting the maximum value of the modality of the covariate
                   5474:              (should be 0 or 1 now) Tvar[j]. If V=sex and male is coded 0 and
                   5475:              female ies 1, then modmaxcovj=1.
                   5476:           */
                   5477:         } /* end for loop on individuals i */
                   5478:         printf(" Minimal and maximal values of %d th (fixed) covariate V%d: min=%d max=%d \n", k, Tvar[k], modmincovj, modmaxcovj);
                   5479:         fprintf(ficlog," Minimal and maximal values of %d th (fixed) covariate V%d: min=%d max=%d \n", k, Tvar[k], modmincovj, modmaxcovj);
                   5480:         cptcode=modmaxcovj;
                   5481:         /* Ndum[0] = frequency of 0 for model-covariate j, Ndum[1] frequency of 1 etc. */
                   5482:         /*for (i=0; i<=cptcode; i++) {*/
                   5483:         for (j=modmincovj;  j<=modmaxcovj; j++) { /* j=-1 ? 0 and 1*//* For each value j of the modality of model-cov k */
                   5484:           printf("Frequencies of (fixed) covariate %d ie V%d with value %d: %d\n", k, Tvar[k], j, Ndum[j]);
                   5485:           fprintf(ficlog, "Frequencies of (fixed) covariate %d ie V%d with value %d: %d\n", k, Tvar[k], j, Ndum[j]);
                   5486:           if( Ndum[j] != 0 ){ /* Counts if nobody answered modality j ie empty modality, we skip it and reorder */
                   5487:             if( j != -1){
                   5488:               ncodemax[k]++;  /* ncodemax[k]= Number of modalities of the k th
                   5489:                                  covariate for which somebody answered excluding 
                   5490:                                  undefined. Usually 2: 0 and 1. */
                   5491:             }
                   5492:             ncodemaxwundef[k]++; /* ncodemax[j]= Number of modalities of the k th
                   5493:                                     covariate for which somebody answered including 
                   5494:                                     undefined. Usually 3: -1, 0 and 1. */
                   5495:           }    /* In fact  ncodemax[k]=2 (dichotom. variables only) but it could be more for
                   5496:                 * historical reasons: 3 if coded 1, 2, 3 and 4 and Ndum[2]=0 */
                   5497:         } /* Ndum[-1] number of undefined modalities */
1.231     brouard  5498:                        
1.242     brouard  5499:         /* j is a covariate, n=Tvar[j] of Vn; Fills nbcode */
                   5500:         /* For covariate j, modalities could be 1, 2, 3, 4, 5, 6, 7. */
                   5501:         /* If Ndum[1]=0, Ndum[2]=0, Ndum[3]= 635, Ndum[4]=0, Ndum[5]=0, Ndum[6]=27, Ndum[7]=125; */
                   5502:         /* modmincovj=3; modmaxcovj = 7; */
                   5503:         /* There are only 3 modalities non empty 3, 6, 7 (or 2 if 27 is too few) : ncodemax[j]=3; */
                   5504:         /* which will be coded 0, 1, 2 which in binary on 2=3-1 digits are 0=00 1=01, 2=10; */
                   5505:         /*              defining two dummy variables: variables V1_1 and V1_2.*/
                   5506:         /* nbcode[Tvar[j]][ij]=k; */
                   5507:         /* nbcode[Tvar[j]][1]=0; */
                   5508:         /* nbcode[Tvar[j]][2]=1; */
                   5509:         /* nbcode[Tvar[j]][3]=2; */
                   5510:         /* To be continued (not working yet). */
                   5511:         ij=0; /* ij is similar to i but can jump over null modalities */
1.287     brouard  5512: 
                   5513:         /* 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*/
                   5514:         /* Skipping the case of missing values by reducing nbcode to 0 and 1 and not -1, 0, 1 */
                   5515:         /* model=V1+V2+V3, if V2=-1, 0 or 1, then nbcode[2][1]=0 and nbcode[2][2]=1 instead of
                   5516:          * nbcode[2][1]=-1, nbcode[2][2]=0 and nbcode[2][3]=1 */
                   5517:         /*, could be restored in the future */
                   5518:         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  5519:           if (Ndum[i] == 0) { /* If nobody responded to this modality k */
                   5520:             break;
                   5521:           }
                   5522:           ij++;
1.287     brouard  5523:           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  5524:           cptcode = ij; /* New max modality for covar j */
                   5525:         } /* end of loop on modality i=-1 to 1 or more */
                   5526:         break;
                   5527:        case 1: /* Testing on varying covariate, could be simple and
                   5528:                * should look at waves or product of fixed *
                   5529:                * varying. No time to test -1, assuming 0 and 1 only */
                   5530:         ij=0;
                   5531:         for(i=0; i<=1;i++){
                   5532:           nbcode[Tvar[k]][++ij]=i;
                   5533:         }
                   5534:         break;
                   5535:        default:
                   5536:         break;
                   5537:        } /* end switch */
                   5538:      } /* end dummy test */
1.287     brouard  5539:    } /* 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  5540:   
                   5541:    for (k=-1; k< maxncov; k++) Ndum[k]=0; 
                   5542:    /* Look at fixed dummy (single or product) covariates to check empty modalities */
                   5543:    for (i=1; i<=ncovmodel-2-nagesqr; i++) { /* -2, cste and age and eventually age*age */ 
                   5544:      /* Listing of all covariables in statement model to see if some covariates appear twice. For example, V1 appears twice in V1+V1*V2.*/ 
                   5545:      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 */ 
                   5546:      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 */
                   5547:      /* V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1,  {2, 1, 1, 1, 2, 1, 1, 0, 0} */
                   5548:    } /* V4+V3+V5, Ndum[1]@5={0, 0, 1, 1, 1} */
                   5549:   
                   5550:    ij=0;
                   5551:    /* for (i=0; i<=  maxncov-1; i++) { /\* modmaxcovj is unknown here. Only Ndum[2(V2),3(age*V3), 5(V3*V2) 6(V1*V4) *\/ */
                   5552:    for (k=1; k<=  cptcovt; k++) { /* modmaxcovj is unknown here. Only Ndum[2(V2),3(age*V3), 5(V3*V2) 6(V1*V4) */
                   5553:      /*printf("Ndum[%d]=%d\n",i, Ndum[i]);*/
                   5554:      /* if((Ndum[i]!=0) && (i<=ncovcol)){  /\* Tvar[i] <= ncovmodel ? *\/ */
                   5555:      if(Ndum[Tvar[k]]!=0 && Dummy[k] == 0 && Typevar[k]==0){  /* Only Dummy and non empty in the model */
                   5556:        /* If product not in single variable we don't print results */
                   5557:        /*printf("diff Ndum[%d]=%d\n",i, Ndum[i]);*/
                   5558:        ++ij;/* V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1, */
                   5559:        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*/
                   5560:        Tmodelind[ij]=k; /* Tmodelind: index in model of dummies Tmodelind[1]=2 V4: pos=2; V3: pos=3, V1=9 {2, 3, 9, ?, ?,} */
                   5561:        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 */
                   5562:        if(Fixed[k]!=0)
                   5563:         anyvaryingduminmodel=1;
                   5564:        /* }else if((Ndum[i]!=0) && (i<=ncovcol+nqv)){ */
                   5565:        /*   Tvaraff[++ij]=-10; /\* Dont'n know how to treat quantitative variables yet *\/ */
                   5566:        /* }else if((Ndum[i]!=0) && (i<=ncovcol+nqv+ntv)){ */
                   5567:        /*   Tvaraff[++ij]=i; /\*For printing (unclear) *\/ */
                   5568:        /* }else if((Ndum[i]!=0) && (i<=ncovcol+nqv+ntv+nqtv)){ */
                   5569:        /*   Tvaraff[++ij]=-20; /\* Dont'n know how to treat quantitative variables yet *\/ */
                   5570:      } 
                   5571:    } /* Tvaraff[1]@5 {3, 4, -20, 0, 0} Very strange */
                   5572:    /* ij--; */
                   5573:    /* cptcoveff=ij; /\*Number of total covariates*\/ */
                   5574:    *cptcov=ij; /*Number of total real effective covariates: effective
                   5575:                * because they can be excluded from the model and real
                   5576:                * if in the model but excluded because missing values, but how to get k from ij?*/
                   5577:    for(j=ij+1; j<= cptcovt; j++){
                   5578:      Tvaraff[j]=0;
                   5579:      Tmodelind[j]=0;
                   5580:    }
                   5581:    for(j=ntveff+1; j<= cptcovt; j++){
                   5582:      TmodelInvind[j]=0;
                   5583:    }
                   5584:    /* To be sorted */
                   5585:    ;
                   5586:  }
1.126     brouard  5587: 
1.145     brouard  5588: 
1.126     brouard  5589: /*********** Health Expectancies ****************/
                   5590: 
1.235     brouard  5591:  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  5592: 
                   5593: {
                   5594:   /* Health expectancies, no variances */
1.164     brouard  5595:   int i, j, nhstepm, hstepm, h, nstepm;
1.126     brouard  5596:   int nhstepma, nstepma; /* Decreasing with age */
                   5597:   double age, agelim, hf;
                   5598:   double ***p3mat;
                   5599:   double eip;
                   5600: 
1.238     brouard  5601:   /* pstamp(ficreseij); */
1.126     brouard  5602:   fprintf(ficreseij,"# (a) Life expectancies by health status at initial age and (b) health expectancies by health status at initial age\n");
                   5603:   fprintf(ficreseij,"# Age");
                   5604:   for(i=1; i<=nlstate;i++){
                   5605:     for(j=1; j<=nlstate;j++){
                   5606:       fprintf(ficreseij," e%1d%1d ",i,j);
                   5607:     }
                   5608:     fprintf(ficreseij," e%1d. ",i);
                   5609:   }
                   5610:   fprintf(ficreseij,"\n");
                   5611: 
                   5612:   
                   5613:   if(estepm < stepm){
                   5614:     printf ("Problem %d lower than %d\n",estepm, stepm);
                   5615:   }
                   5616:   else  hstepm=estepm;   
                   5617:   /* We compute the life expectancy from trapezoids spaced every estepm months
                   5618:    * This is mainly to measure the difference between two models: for example
                   5619:    * if stepm=24 months pijx are given only every 2 years and by summing them
                   5620:    * we are calculating an estimate of the Life Expectancy assuming a linear 
                   5621:    * progression in between and thus overestimating or underestimating according
                   5622:    * to the curvature of the survival function. If, for the same date, we 
                   5623:    * estimate the model with stepm=1 month, we can keep estepm to 24 months
                   5624:    * to compare the new estimate of Life expectancy with the same linear 
                   5625:    * hypothesis. A more precise result, taking into account a more precise
                   5626:    * curvature will be obtained if estepm is as small as stepm. */
                   5627: 
                   5628:   /* For example we decided to compute the life expectancy with the smallest unit */
                   5629:   /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm. 
                   5630:      nhstepm is the number of hstepm from age to agelim 
                   5631:      nstepm is the number of stepm from age to agelin. 
1.270     brouard  5632:      Look at hpijx to understand the reason which relies in memory size consideration
1.126     brouard  5633:      and note for a fixed period like estepm months */
                   5634:   /* We decided (b) to get a life expectancy respecting the most precise curvature of the
                   5635:      survival function given by stepm (the optimization length). Unfortunately it
                   5636:      means that if the survival funtion is printed only each two years of age and if
                   5637:      you sum them up and add 1 year (area under the trapezoids) you won't get the same 
                   5638:      results. So we changed our mind and took the option of the best precision.
                   5639:   */
                   5640:   hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */ 
                   5641: 
                   5642:   agelim=AGESUP;
                   5643:   /* If stepm=6 months */
                   5644:     /* Computed by stepm unit matrices, product of hstepm matrices, stored
                   5645:        in an array of nhstepm length: nhstepm=10, hstepm=4, stepm=6 months */
                   5646:     
                   5647: /* nhstepm age range expressed in number of stepm */
                   5648:   nstepm=(int) rint((agelim-bage)*YEARM/stepm); /* Biggest nstepm */
                   5649:   /* Typically if 20 years nstepm = 20*12/6=40 stepm */ 
                   5650:   /* if (stepm >= YEARM) hstepm=1;*/
                   5651:   nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
                   5652:   p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   5653: 
                   5654:   for (age=bage; age<=fage; age ++){ 
                   5655:     nstepma=(int) rint((agelim-bage)*YEARM/stepm); /* Biggest nstepm */
                   5656:     /* Typically if 20 years nstepm = 20*12/6=40 stepm */ 
                   5657:     /* if (stepm >= YEARM) hstepm=1;*/
                   5658:     nhstepma = nstepma/hstepm;/* Expressed in hstepm, typically nhstepma=40/4=10 */
                   5659: 
                   5660:     /* If stepm=6 months */
                   5661:     /* Computed by stepm unit matrices, product of hstepma matrices, stored
                   5662:        in an array of nhstepma length: nhstepma=10, hstepm=4, stepm=6 months */
                   5663:     
1.235     brouard  5664:     hpxij(p3mat,nhstepma,age,hstepm,x,nlstate,stepm,oldm, savm, cij, nres);  
1.126     brouard  5665:     
                   5666:     hf=hstepm*stepm/YEARM;  /* Duration of hstepm expressed in year unit. */
                   5667:     
                   5668:     printf("%d|",(int)age);fflush(stdout);
                   5669:     fprintf(ficlog,"%d|",(int)age);fflush(ficlog);
                   5670:     
                   5671:     /* Computing expectancies */
                   5672:     for(i=1; i<=nlstate;i++)
                   5673:       for(j=1; j<=nlstate;j++)
                   5674:        for (h=0, eij[i][j][(int)age]=0; h<=nhstepm-1; h++){
                   5675:          eij[i][j][(int)age] += (p3mat[i][j][h]+p3mat[i][j][h+1])/2.0*hf;
                   5676:          
                   5677:          /* 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]);*/
                   5678: 
                   5679:        }
                   5680: 
                   5681:     fprintf(ficreseij,"%3.0f",age );
                   5682:     for(i=1; i<=nlstate;i++){
                   5683:       eip=0;
                   5684:       for(j=1; j<=nlstate;j++){
                   5685:        eip +=eij[i][j][(int)age];
                   5686:        fprintf(ficreseij,"%9.4f", eij[i][j][(int)age] );
                   5687:       }
                   5688:       fprintf(ficreseij,"%9.4f", eip );
                   5689:     }
                   5690:     fprintf(ficreseij,"\n");
                   5691:     
                   5692:   }
                   5693:   free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   5694:   printf("\n");
                   5695:   fprintf(ficlog,"\n");
                   5696:   
                   5697: }
                   5698: 
1.235     brouard  5699:  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  5700: 
                   5701: {
                   5702:   /* Covariances of health expectancies eij and of total life expectancies according
1.222     brouard  5703:      to initial status i, ei. .
1.126     brouard  5704:   */
                   5705:   int i, j, nhstepm, hstepm, h, nstepm, k, cptj, cptj2, i2, j2, ij, ji;
                   5706:   int nhstepma, nstepma; /* Decreasing with age */
                   5707:   double age, agelim, hf;
                   5708:   double ***p3matp, ***p3matm, ***varhe;
                   5709:   double **dnewm,**doldm;
                   5710:   double *xp, *xm;
                   5711:   double **gp, **gm;
                   5712:   double ***gradg, ***trgradg;
                   5713:   int theta;
                   5714: 
                   5715:   double eip, vip;
                   5716: 
                   5717:   varhe=ma3x(1,nlstate*nlstate,1,nlstate*nlstate,(int) bage, (int) fage);
                   5718:   xp=vector(1,npar);
                   5719:   xm=vector(1,npar);
                   5720:   dnewm=matrix(1,nlstate*nlstate,1,npar);
                   5721:   doldm=matrix(1,nlstate*nlstate,1,nlstate*nlstate);
                   5722:   
                   5723:   pstamp(ficresstdeij);
                   5724:   fprintf(ficresstdeij,"# Health expectancies with standard errors\n");
                   5725:   fprintf(ficresstdeij,"# Age");
                   5726:   for(i=1; i<=nlstate;i++){
                   5727:     for(j=1; j<=nlstate;j++)
                   5728:       fprintf(ficresstdeij," e%1d%1d (SE)",i,j);
                   5729:     fprintf(ficresstdeij," e%1d. ",i);
                   5730:   }
                   5731:   fprintf(ficresstdeij,"\n");
                   5732: 
                   5733:   pstamp(ficrescveij);
                   5734:   fprintf(ficrescveij,"# Subdiagonal matrix of covariances of health expectancies by age: cov(eij,ekl)\n");
                   5735:   fprintf(ficrescveij,"# Age");
                   5736:   for(i=1; i<=nlstate;i++)
                   5737:     for(j=1; j<=nlstate;j++){
                   5738:       cptj= (j-1)*nlstate+i;
                   5739:       for(i2=1; i2<=nlstate;i2++)
                   5740:        for(j2=1; j2<=nlstate;j2++){
                   5741:          cptj2= (j2-1)*nlstate+i2;
                   5742:          if(cptj2 <= cptj)
                   5743:            fprintf(ficrescveij,"  %1d%1d,%1d%1d",i,j,i2,j2);
                   5744:        }
                   5745:     }
                   5746:   fprintf(ficrescveij,"\n");
                   5747:   
                   5748:   if(estepm < stepm){
                   5749:     printf ("Problem %d lower than %d\n",estepm, stepm);
                   5750:   }
                   5751:   else  hstepm=estepm;   
                   5752:   /* We compute the life expectancy from trapezoids spaced every estepm months
                   5753:    * This is mainly to measure the difference between two models: for example
                   5754:    * if stepm=24 months pijx are given only every 2 years and by summing them
                   5755:    * we are calculating an estimate of the Life Expectancy assuming a linear 
                   5756:    * progression in between and thus overestimating or underestimating according
                   5757:    * to the curvature of the survival function. If, for the same date, we 
                   5758:    * estimate the model with stepm=1 month, we can keep estepm to 24 months
                   5759:    * to compare the new estimate of Life expectancy with the same linear 
                   5760:    * hypothesis. A more precise result, taking into account a more precise
                   5761:    * curvature will be obtained if estepm is as small as stepm. */
                   5762: 
                   5763:   /* For example we decided to compute the life expectancy with the smallest unit */
                   5764:   /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm. 
                   5765:      nhstepm is the number of hstepm from age to agelim 
                   5766:      nstepm is the number of stepm from age to agelin. 
                   5767:      Look at hpijx to understand the reason of that which relies in memory size
                   5768:      and note for a fixed period like estepm months */
                   5769:   /* We decided (b) to get a life expectancy respecting the most precise curvature of the
                   5770:      survival function given by stepm (the optimization length). Unfortunately it
                   5771:      means that if the survival funtion is printed only each two years of age and if
                   5772:      you sum them up and add 1 year (area under the trapezoids) you won't get the same 
                   5773:      results. So we changed our mind and took the option of the best precision.
                   5774:   */
                   5775:   hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */ 
                   5776: 
                   5777:   /* If stepm=6 months */
                   5778:   /* nhstepm age range expressed in number of stepm */
                   5779:   agelim=AGESUP;
                   5780:   nstepm=(int) rint((agelim-bage)*YEARM/stepm); 
                   5781:   /* Typically if 20 years nstepm = 20*12/6=40 stepm */ 
                   5782:   /* if (stepm >= YEARM) hstepm=1;*/
                   5783:   nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
                   5784:   
                   5785:   p3matp=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   5786:   p3matm=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   5787:   gradg=ma3x(0,nhstepm,1,npar,1,nlstate*nlstate);
                   5788:   trgradg =ma3x(0,nhstepm,1,nlstate*nlstate,1,npar);
                   5789:   gp=matrix(0,nhstepm,1,nlstate*nlstate);
                   5790:   gm=matrix(0,nhstepm,1,nlstate*nlstate);
                   5791: 
                   5792:   for (age=bage; age<=fage; age ++){ 
                   5793:     nstepma=(int) rint((agelim-bage)*YEARM/stepm); /* Biggest nstepm */
                   5794:     /* Typically if 20 years nstepm = 20*12/6=40 stepm */ 
                   5795:     /* if (stepm >= YEARM) hstepm=1;*/
                   5796:     nhstepma = nstepma/hstepm;/* Expressed in hstepm, typically nhstepma=40/4=10 */
1.218     brouard  5797:                
1.126     brouard  5798:     /* If stepm=6 months */
                   5799:     /* Computed by stepm unit matrices, product of hstepma matrices, stored
                   5800:        in an array of nhstepma length: nhstepma=10, hstepm=4, stepm=6 months */
                   5801:     
                   5802:     hf=hstepm*stepm/YEARM;  /* Duration of hstepm expressed in year unit. */
1.218     brouard  5803:                
1.126     brouard  5804:     /* Computing  Variances of health expectancies */
                   5805:     /* Gradient is computed with plus gp and minus gm. Code is duplicated in order to
                   5806:        decrease memory allocation */
                   5807:     for(theta=1; theta <=npar; theta++){
                   5808:       for(i=1; i<=npar; i++){ 
1.222     brouard  5809:        xp[i] = x[i] + (i==theta ?delti[theta]:0);
                   5810:        xm[i] = x[i] - (i==theta ?delti[theta]:0);
1.126     brouard  5811:       }
1.235     brouard  5812:       hpxij(p3matp,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, cij, nres);  
                   5813:       hpxij(p3matm,nhstepm,age,hstepm,xm,nlstate,stepm,oldm,savm, cij, nres);  
1.218     brouard  5814:                        
1.126     brouard  5815:       for(j=1; j<= nlstate; j++){
1.222     brouard  5816:        for(i=1; i<=nlstate; i++){
                   5817:          for(h=0; h<=nhstepm-1; h++){
                   5818:            gp[h][(j-1)*nlstate + i] = (p3matp[i][j][h]+p3matp[i][j][h+1])/2.;
                   5819:            gm[h][(j-1)*nlstate + i] = (p3matm[i][j][h]+p3matm[i][j][h+1])/2.;
                   5820:          }
                   5821:        }
1.126     brouard  5822:       }
1.218     brouard  5823:                        
1.126     brouard  5824:       for(ij=1; ij<= nlstate*nlstate; ij++)
1.222     brouard  5825:        for(h=0; h<=nhstepm-1; h++){
                   5826:          gradg[h][theta][ij]= (gp[h][ij]-gm[h][ij])/2./delti[theta];
                   5827:        }
1.126     brouard  5828:     }/* End theta */
                   5829:     
                   5830:     
                   5831:     for(h=0; h<=nhstepm-1; h++)
                   5832:       for(j=1; j<=nlstate*nlstate;j++)
1.222     brouard  5833:        for(theta=1; theta <=npar; theta++)
                   5834:          trgradg[h][j][theta]=gradg[h][theta][j];
1.126     brouard  5835:     
1.218     brouard  5836:                
1.222     brouard  5837:     for(ij=1;ij<=nlstate*nlstate;ij++)
1.126     brouard  5838:       for(ji=1;ji<=nlstate*nlstate;ji++)
1.222     brouard  5839:        varhe[ij][ji][(int)age] =0.;
1.218     brouard  5840:                
1.222     brouard  5841:     printf("%d|",(int)age);fflush(stdout);
                   5842:     fprintf(ficlog,"%d|",(int)age);fflush(ficlog);
                   5843:     for(h=0;h<=nhstepm-1;h++){
1.126     brouard  5844:       for(k=0;k<=nhstepm-1;k++){
1.222     brouard  5845:        matprod2(dnewm,trgradg[h],1,nlstate*nlstate,1,npar,1,npar,matcov);
                   5846:        matprod2(doldm,dnewm,1,nlstate*nlstate,1,npar,1,nlstate*nlstate,gradg[k]);
                   5847:        for(ij=1;ij<=nlstate*nlstate;ij++)
                   5848:          for(ji=1;ji<=nlstate*nlstate;ji++)
                   5849:            varhe[ij][ji][(int)age] += doldm[ij][ji]*hf*hf;
1.126     brouard  5850:       }
                   5851:     }
1.218     brouard  5852:                
1.126     brouard  5853:     /* Computing expectancies */
1.235     brouard  5854:     hpxij(p3matm,nhstepm,age,hstepm,x,nlstate,stepm,oldm, savm, cij,nres);  
1.126     brouard  5855:     for(i=1; i<=nlstate;i++)
                   5856:       for(j=1; j<=nlstate;j++)
1.222     brouard  5857:        for (h=0, eij[i][j][(int)age]=0; h<=nhstepm-1; h++){
                   5858:          eij[i][j][(int)age] += (p3matm[i][j][h]+p3matm[i][j][h+1])/2.0*hf;
1.218     brouard  5859:                                        
1.222     brouard  5860:          /* 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  5861:                                        
1.222     brouard  5862:        }
1.269     brouard  5863: 
                   5864:     /* Standard deviation of expectancies ij */                
1.126     brouard  5865:     fprintf(ficresstdeij,"%3.0f",age );
                   5866:     for(i=1; i<=nlstate;i++){
                   5867:       eip=0.;
                   5868:       vip=0.;
                   5869:       for(j=1; j<=nlstate;j++){
1.222     brouard  5870:        eip += eij[i][j][(int)age];
                   5871:        for(k=1; k<=nlstate;k++) /* Sum on j and k of cov(eij,eik) */
                   5872:          vip += varhe[(j-1)*nlstate+i][(k-1)*nlstate+i][(int)age];
                   5873:        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  5874:       }
                   5875:       fprintf(ficresstdeij," %9.4f (%.4f)", eip, sqrt(vip));
                   5876:     }
                   5877:     fprintf(ficresstdeij,"\n");
1.218     brouard  5878:                
1.269     brouard  5879:     /* Variance of expectancies ij */          
1.126     brouard  5880:     fprintf(ficrescveij,"%3.0f",age );
                   5881:     for(i=1; i<=nlstate;i++)
                   5882:       for(j=1; j<=nlstate;j++){
1.222     brouard  5883:        cptj= (j-1)*nlstate+i;
                   5884:        for(i2=1; i2<=nlstate;i2++)
                   5885:          for(j2=1; j2<=nlstate;j2++){
                   5886:            cptj2= (j2-1)*nlstate+i2;
                   5887:            if(cptj2 <= cptj)
                   5888:              fprintf(ficrescveij," %.4f", varhe[cptj][cptj2][(int)age]);
                   5889:          }
1.126     brouard  5890:       }
                   5891:     fprintf(ficrescveij,"\n");
1.218     brouard  5892:                
1.126     brouard  5893:   }
                   5894:   free_matrix(gm,0,nhstepm,1,nlstate*nlstate);
                   5895:   free_matrix(gp,0,nhstepm,1,nlstate*nlstate);
                   5896:   free_ma3x(gradg,0,nhstepm,1,npar,1,nlstate*nlstate);
                   5897:   free_ma3x(trgradg,0,nhstepm,1,nlstate*nlstate,1,npar);
                   5898:   free_ma3x(p3matm,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   5899:   free_ma3x(p3matp,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   5900:   printf("\n");
                   5901:   fprintf(ficlog,"\n");
1.218     brouard  5902:        
1.126     brouard  5903:   free_vector(xm,1,npar);
                   5904:   free_vector(xp,1,npar);
                   5905:   free_matrix(dnewm,1,nlstate*nlstate,1,npar);
                   5906:   free_matrix(doldm,1,nlstate*nlstate,1,nlstate*nlstate);
                   5907:   free_ma3x(varhe,1,nlstate*nlstate,1,nlstate*nlstate,(int) bage, (int)fage);
                   5908: }
1.218     brouard  5909:  
1.126     brouard  5910: /************ Variance ******************/
1.235     brouard  5911:  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  5912:  {
1.279     brouard  5913:    /** Variance of health expectancies 
                   5914:     *  double **prevalim(double **prlim, int nlstate, double *xp, double age, double **oldm, double ** savm,double ftolpl);
                   5915:     * double **newm;
                   5916:     * int movingaverage(double ***probs, double bage,double fage, double ***mobaverage, int mobilav) 
                   5917:     */
1.218     brouard  5918:   
                   5919:    /* int movingaverage(); */
                   5920:    double **dnewm,**doldm;
                   5921:    double **dnewmp,**doldmp;
                   5922:    int i, j, nhstepm, hstepm, h, nstepm ;
1.288     brouard  5923:    int first=0;
1.218     brouard  5924:    int k;
                   5925:    double *xp;
1.279     brouard  5926:    double **gp, **gm;  /**< for var eij */
                   5927:    double ***gradg, ***trgradg; /**< for var eij */
                   5928:    double **gradgp, **trgradgp; /**< for var p point j */
                   5929:    double *gpp, *gmp; /**< for var p point j */
                   5930:    double **varppt; /**< for var p point j nlstate to nlstate+ndeath */
1.218     brouard  5931:    double ***p3mat;
                   5932:    double age,agelim, hf;
                   5933:    /* double ***mobaverage; */
                   5934:    int theta;
                   5935:    char digit[4];
                   5936:    char digitp[25];
                   5937: 
                   5938:    char fileresprobmorprev[FILENAMELENGTH];
                   5939: 
                   5940:    if(popbased==1){
                   5941:      if(mobilav!=0)
                   5942:        strcpy(digitp,"-POPULBASED-MOBILAV_");
                   5943:      else strcpy(digitp,"-POPULBASED-NOMOBIL_");
                   5944:    }
                   5945:    else 
                   5946:      strcpy(digitp,"-STABLBASED_");
1.126     brouard  5947: 
1.218     brouard  5948:    /* if (mobilav!=0) { */
                   5949:    /*   mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX); */
                   5950:    /*   if (movingaverage(probs, bage, fage, mobaverage,mobilav)!=0){ */
                   5951:    /*     fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav); */
                   5952:    /*     printf(" Error in movingaverage mobilav=%d\n",mobilav); */
                   5953:    /*   } */
                   5954:    /* } */
                   5955: 
                   5956:    strcpy(fileresprobmorprev,"PRMORPREV-"); 
                   5957:    sprintf(digit,"%-d",ij);
                   5958:    /*printf("DIGIT=%s, ij=%d ijr=%-d|\n",digit, ij,ij);*/
                   5959:    strcat(fileresprobmorprev,digit); /* Tvar to be done */
                   5960:    strcat(fileresprobmorprev,digitp); /* Popbased or not, mobilav or not */
                   5961:    strcat(fileresprobmorprev,fileresu);
                   5962:    if((ficresprobmorprev=fopen(fileresprobmorprev,"w"))==NULL) {
                   5963:      printf("Problem with resultfile: %s\n", fileresprobmorprev);
                   5964:      fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobmorprev);
                   5965:    }
                   5966:    printf("Computing total mortality p.j=w1*p1j+w2*p2j+..: result on file '%s' \n",fileresprobmorprev);
                   5967:    fprintf(ficlog,"Computing total mortality p.j=w1*p1j+w2*p2j+..: result on file '%s' \n",fileresprobmorprev);
                   5968:    pstamp(ficresprobmorprev);
                   5969:    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  5970:    fprintf(ficresprobmorprev,"# Selected quantitative variables and dummies");
                   5971:    for (j=1; j<= nsq; j++){ /* For each selected (single) quantitative value */
                   5972:      fprintf(ficresprobmorprev," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]);
                   5973:    }
                   5974:    for(j=1;j<=cptcoveff;j++) 
                   5975:      fprintf(ficresprobmorprev,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(ij,j)]);
                   5976:    fprintf(ficresprobmorprev,"\n");
                   5977: 
1.218     brouard  5978:    fprintf(ficresprobmorprev,"# Age cov=%-d",ij);
                   5979:    for(j=nlstate+1; j<=(nlstate+ndeath);j++){
                   5980:      fprintf(ficresprobmorprev," p.%-d SE",j);
                   5981:      for(i=1; i<=nlstate;i++)
                   5982:        fprintf(ficresprobmorprev," w%1d p%-d%-d",i,i,j);
                   5983:    }  
                   5984:    fprintf(ficresprobmorprev,"\n");
                   5985:   
                   5986:    fprintf(ficgp,"\n# Routine varevsij");
                   5987:    fprintf(ficgp,"\nunset title \n");
                   5988:    /* fprintf(fichtm, "#Local time at start: %s", strstart);*/
                   5989:    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");
                   5990:    fprintf(fichtm,"\n<br>%s  <br>\n",digitp);
1.279     brouard  5991: 
1.218     brouard  5992:    varppt = matrix(nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
                   5993:    pstamp(ficresvij);
                   5994:    fprintf(ficresvij,"# Variance and covariance of health expectancies e.j \n#  (weighted average of eij where weights are ");
                   5995:    if(popbased==1)
                   5996:      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);
                   5997:    else
                   5998:      fprintf(ficresvij,"the age specific period (stable) prevalences in each health state \n");
                   5999:    fprintf(ficresvij,"# Age");
                   6000:    for(i=1; i<=nlstate;i++)
                   6001:      for(j=1; j<=nlstate;j++)
                   6002:        fprintf(ficresvij," Cov(e.%1d, e.%1d)",i,j);
                   6003:    fprintf(ficresvij,"\n");
                   6004: 
                   6005:    xp=vector(1,npar);
                   6006:    dnewm=matrix(1,nlstate,1,npar);
                   6007:    doldm=matrix(1,nlstate,1,nlstate);
                   6008:    dnewmp= matrix(nlstate+1,nlstate+ndeath,1,npar);
                   6009:    doldmp= matrix(nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
                   6010: 
                   6011:    gradgp=matrix(1,npar,nlstate+1,nlstate+ndeath);
                   6012:    gpp=vector(nlstate+1,nlstate+ndeath);
                   6013:    gmp=vector(nlstate+1,nlstate+ndeath);
                   6014:    trgradgp =matrix(nlstate+1,nlstate+ndeath,1,npar); /* mu or p point j*/
1.126     brouard  6015:   
1.218     brouard  6016:    if(estepm < stepm){
                   6017:      printf ("Problem %d lower than %d\n",estepm, stepm);
                   6018:    }
                   6019:    else  hstepm=estepm;   
                   6020:    /* For example we decided to compute the life expectancy with the smallest unit */
                   6021:    /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm. 
                   6022:       nhstepm is the number of hstepm from age to agelim 
                   6023:       nstepm is the number of stepm from age to agelim. 
                   6024:       Look at function hpijx to understand why because of memory size limitations, 
                   6025:       we decided (b) to get a life expectancy respecting the most precise curvature of the
                   6026:       survival function given by stepm (the optimization length). Unfortunately it
                   6027:       means that if the survival funtion is printed every two years of age and if
                   6028:       you sum them up and add 1 year (area under the trapezoids) you won't get the same 
                   6029:       results. So we changed our mind and took the option of the best precision.
                   6030:    */
                   6031:    hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */ 
                   6032:    agelim = AGESUP;
                   6033:    for (age=bage; age<=fage; age ++){ /* If stepm=6 months */
                   6034:      nstepm=(int) rint((agelim-age)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */ 
                   6035:      nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
                   6036:      p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   6037:      gradg=ma3x(0,nhstepm,1,npar,1,nlstate);
                   6038:      gp=matrix(0,nhstepm,1,nlstate);
                   6039:      gm=matrix(0,nhstepm,1,nlstate);
                   6040:                
                   6041:                
                   6042:      for(theta=1; theta <=npar; theta++){
                   6043:        for(i=1; i<=npar; i++){ /* Computes gradient x + delta*/
                   6044:         xp[i] = x[i] + (i==theta ?delti[theta]:0);
                   6045:        }
1.279     brouard  6046:        /**< Computes the prevalence limit with parameter theta shifted of delta up to ftolpl precision and 
                   6047:        * returns into prlim .
1.288     brouard  6048:        */
1.242     brouard  6049:        prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp,ij, nres);
1.279     brouard  6050: 
                   6051:        /* If popbased = 1 we use crossection prevalences. Previous step is useless but prlim is created */
1.218     brouard  6052:        if (popbased==1) {
                   6053:         if(mobilav ==0){
                   6054:           for(i=1; i<=nlstate;i++)
                   6055:             prlim[i][i]=probs[(int)age][i][ij];
                   6056:         }else{ /* mobilav */ 
                   6057:           for(i=1; i<=nlstate;i++)
                   6058:             prlim[i][i]=mobaverage[(int)age][i][ij];
                   6059:         }
                   6060:        }
1.295     brouard  6061:        /**< Computes the shifted transition matrix \f$ {}{h}_p^{ij}x\f$ at horizon h.
1.279     brouard  6062:        */                      
                   6063:        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  6064:        /**< 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  6065:        * at horizon h in state j including mortality.
                   6066:        */
1.218     brouard  6067:        for(j=1; j<= nlstate; j++){
                   6068:         for(h=0; h<=nhstepm; h++){
                   6069:           for(i=1, gp[h][j]=0.;i<=nlstate;i++)
                   6070:             gp[h][j] += prlim[i][i]*p3mat[i][j][h];
                   6071:         }
                   6072:        }
1.279     brouard  6073:        /* Next for computing shifted+ probability of death (h=1 means
1.218     brouard  6074:          computed over hstepm matrices product = hstepm*stepm months) 
1.279     brouard  6075:          as a weighted average of prlim(i) * p(i,j) p.3=w1*p13 + w2*p23 .
1.218     brouard  6076:        */
                   6077:        for(j=nlstate+1;j<=nlstate+ndeath;j++){
                   6078:         for(i=1,gpp[j]=0.; i<= nlstate; i++)
                   6079:           gpp[j] += prlim[i][i]*p3mat[i][j][1];
1.279     brouard  6080:        }
                   6081:        
                   6082:        /* Again with minus shift */
1.218     brouard  6083:                        
                   6084:        for(i=1; i<=npar; i++) /* Computes gradient x - delta */
                   6085:         xp[i] = x[i] - (i==theta ?delti[theta]:0);
1.288     brouard  6086: 
1.242     brouard  6087:        prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp, ij, nres);
1.218     brouard  6088:                        
                   6089:        if (popbased==1) {
                   6090:         if(mobilav ==0){
                   6091:           for(i=1; i<=nlstate;i++)
                   6092:             prlim[i][i]=probs[(int)age][i][ij];
                   6093:         }else{ /* mobilav */ 
                   6094:           for(i=1; i<=nlstate;i++)
                   6095:             prlim[i][i]=mobaverage[(int)age][i][ij];
                   6096:         }
                   6097:        }
                   6098:                        
1.235     brouard  6099:        hpxij(p3mat,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, ij,nres);  
1.218     brouard  6100:                        
                   6101:        for(j=1; j<= nlstate; j++){  /* Sum of wi * eij = e.j */
                   6102:         for(h=0; h<=nhstepm; h++){
                   6103:           for(i=1, gm[h][j]=0.;i<=nlstate;i++)
                   6104:             gm[h][j] += prlim[i][i]*p3mat[i][j][h];
                   6105:         }
                   6106:        }
                   6107:        /* This for computing probability of death (h=1 means
                   6108:          computed over hstepm matrices product = hstepm*stepm months) 
                   6109:          as a weighted average of prlim.
                   6110:        */
                   6111:        for(j=nlstate+1;j<=nlstate+ndeath;j++){
                   6112:         for(i=1,gmp[j]=0.; i<= nlstate; i++)
                   6113:           gmp[j] += prlim[i][i]*p3mat[i][j][1];
                   6114:        }    
1.279     brouard  6115:        /* end shifting computations */
                   6116: 
                   6117:        /**< Computing gradient matrix at horizon h 
                   6118:        */
1.218     brouard  6119:        for(j=1; j<= nlstate; j++) /* vareij */
                   6120:         for(h=0; h<=nhstepm; h++){
                   6121:           gradg[h][theta][j]= (gp[h][j]-gm[h][j])/2./delti[theta];
                   6122:         }
1.279     brouard  6123:        /**< Gradient of overall mortality p.3 (or p.j) 
                   6124:        */
                   6125:        for(j=nlstate+1; j<= nlstate+ndeath; j++){ /* var mu mortality from j */
1.218     brouard  6126:         gradgp[theta][j]= (gpp[j]-gmp[j])/2./delti[theta];
                   6127:        }
                   6128:                        
                   6129:      } /* End theta */
1.279     brouard  6130:      
                   6131:      /* We got the gradient matrix for each theta and state j */               
1.218     brouard  6132:      trgradg =ma3x(0,nhstepm,1,nlstate,1,npar); /* veij */
                   6133:                
                   6134:      for(h=0; h<=nhstepm; h++) /* veij */
                   6135:        for(j=1; j<=nlstate;j++)
                   6136:         for(theta=1; theta <=npar; theta++)
                   6137:           trgradg[h][j][theta]=gradg[h][theta][j];
                   6138:                
                   6139:      for(j=nlstate+1; j<=nlstate+ndeath;j++) /* mu */
                   6140:        for(theta=1; theta <=npar; theta++)
                   6141:         trgradgp[j][theta]=gradgp[theta][j];
1.279     brouard  6142:      /**< as well as its transposed matrix 
                   6143:       */               
1.218     brouard  6144:                
                   6145:      hf=hstepm*stepm/YEARM;  /* Duration of hstepm expressed in year unit. */
                   6146:      for(i=1;i<=nlstate;i++)
                   6147:        for(j=1;j<=nlstate;j++)
                   6148:         vareij[i][j][(int)age] =0.;
1.279     brouard  6149: 
                   6150:      /* Computing trgradg by matcov by gradg at age and summing over h
                   6151:       * and k (nhstepm) formula 15 of article
                   6152:       * Lievre-Brouard-Heathcote
                   6153:       */
                   6154:      
1.218     brouard  6155:      for(h=0;h<=nhstepm;h++){
                   6156:        for(k=0;k<=nhstepm;k++){
                   6157:         matprod2(dnewm,trgradg[h],1,nlstate,1,npar,1,npar,matcov);
                   6158:         matprod2(doldm,dnewm,1,nlstate,1,npar,1,nlstate,gradg[k]);
                   6159:         for(i=1;i<=nlstate;i++)
                   6160:           for(j=1;j<=nlstate;j++)
                   6161:             vareij[i][j][(int)age] += doldm[i][j]*hf*hf;
                   6162:        }
                   6163:      }
                   6164:                
1.279     brouard  6165:      /* pptj is p.3 or p.j = trgradgp by cov by gradgp, variance of
                   6166:       * p.j overall mortality formula 49 but computed directly because
                   6167:       * we compute the grad (wix pijx) instead of grad (pijx),even if
                   6168:       * wix is independent of theta.
                   6169:       */
1.218     brouard  6170:      matprod2(dnewmp,trgradgp,nlstate+1,nlstate+ndeath,1,npar,1,npar,matcov);
                   6171:      matprod2(doldmp,dnewmp,nlstate+1,nlstate+ndeath,1,npar,nlstate+1,nlstate+ndeath,gradgp);
                   6172:      for(j=nlstate+1;j<=nlstate+ndeath;j++)
                   6173:        for(i=nlstate+1;i<=nlstate+ndeath;i++)
                   6174:         varppt[j][i]=doldmp[j][i];
                   6175:      /* end ppptj */
                   6176:      /*  x centered again */
                   6177:                
1.242     brouard  6178:      prevalim(prlim,nlstate,x,age,oldm,savm,ftolpl,ncvyearp,ij, nres);
1.218     brouard  6179:                
                   6180:      if (popbased==1) {
                   6181:        if(mobilav ==0){
                   6182:         for(i=1; i<=nlstate;i++)
                   6183:           prlim[i][i]=probs[(int)age][i][ij];
                   6184:        }else{ /* mobilav */ 
                   6185:         for(i=1; i<=nlstate;i++)
                   6186:           prlim[i][i]=mobaverage[(int)age][i][ij];
                   6187:        }
                   6188:      }
                   6189:                
                   6190:      /* This for computing probability of death (h=1 means
                   6191:        computed over hstepm (estepm) matrices product = hstepm*stepm months) 
                   6192:        as a weighted average of prlim.
                   6193:      */
1.235     brouard  6194:      hpxij(p3mat,nhstepm,age,hstepm,x,nlstate,stepm,oldm,savm, ij, nres);  
1.218     brouard  6195:      for(j=nlstate+1;j<=nlstate+ndeath;j++){
                   6196:        for(i=1,gmp[j]=0.;i<= nlstate; i++) 
                   6197:         gmp[j] += prlim[i][i]*p3mat[i][j][1]; 
                   6198:      }    
                   6199:      /* end probability of death */
                   6200:                
                   6201:      fprintf(ficresprobmorprev,"%3d %d ",(int) age, ij);
                   6202:      for(j=nlstate+1; j<=(nlstate+ndeath);j++){
                   6203:        fprintf(ficresprobmorprev," %11.3e %11.3e",gmp[j], sqrt(varppt[j][j]));
                   6204:        for(i=1; i<=nlstate;i++){
                   6205:         fprintf(ficresprobmorprev," %11.3e %11.3e ",prlim[i][i],p3mat[i][j][1]);
                   6206:        }
                   6207:      } 
                   6208:      fprintf(ficresprobmorprev,"\n");
                   6209:                
                   6210:      fprintf(ficresvij,"%.0f ",age );
                   6211:      for(i=1; i<=nlstate;i++)
                   6212:        for(j=1; j<=nlstate;j++){
                   6213:         fprintf(ficresvij," %.4f", vareij[i][j][(int)age]);
                   6214:        }
                   6215:      fprintf(ficresvij,"\n");
                   6216:      free_matrix(gp,0,nhstepm,1,nlstate);
                   6217:      free_matrix(gm,0,nhstepm,1,nlstate);
                   6218:      free_ma3x(gradg,0,nhstepm,1,npar,1,nlstate);
                   6219:      free_ma3x(trgradg,0,nhstepm,1,nlstate,1,npar);
                   6220:      free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   6221:    } /* End age */
                   6222:    free_vector(gpp,nlstate+1,nlstate+ndeath);
                   6223:    free_vector(gmp,nlstate+1,nlstate+ndeath);
                   6224:    free_matrix(gradgp,1,npar,nlstate+1,nlstate+ndeath);
                   6225:    free_matrix(trgradgp,nlstate+1,nlstate+ndeath,1,npar); /* mu or p point j*/
                   6226:    /* fprintf(ficgp,"\nunset parametric;unset label; set ter png small size 320, 240"); */
                   6227:    fprintf(ficgp,"\nunset parametric;unset label; set ter svg size 640, 480");
                   6228:    /* for(j=nlstate+1; j<= nlstate+ndeath; j++){ *//* Only the first actually */
                   6229:    fprintf(ficgp,"\n set log y; unset log x;set xlabel \"Age\"; set ylabel \"Force of mortality (year-1)\";");
                   6230:    fprintf(ficgp,"\nset out \"%s%s.svg\";",subdirf3(optionfilefiname,"VARMUPTJGR-",digitp),digit);
                   6231:    /*   fprintf(ficgp,"\n plot \"%s\"  u 1:($3*%6.3f) not w l 1 ",fileresprobmorprev,YEARM/estepm); */
                   6232:    /*   fprintf(ficgp,"\n replot \"%s\"  u 1:(($3+1.96*$4)*%6.3f) t \"95\%% interval\" w l 2 ",fileresprobmorprev,YEARM/estepm); */
                   6233:    /*   fprintf(ficgp,"\n replot \"%s\"  u 1:(($3-1.96*$4)*%6.3f) not w l 2 ",fileresprobmorprev,YEARM/estepm); */
                   6234:    fprintf(ficgp,"\n plot \"%s\"  u 1:($3) not w l lt 1 ",subdirf(fileresprobmorprev));
                   6235:    fprintf(ficgp,"\n replot \"%s\"  u 1:(($3+1.96*$4)) t \"95%% interval\" w l lt 2 ",subdirf(fileresprobmorprev));
                   6236:    fprintf(ficgp,"\n replot \"%s\"  u 1:(($3-1.96*$4)) not w l lt 2 ",subdirf(fileresprobmorprev));
                   6237:    fprintf(fichtm,"\n<br> File (multiple files are possible if covariates are present): <A href=\"%s\">%s</a>\n",subdirf(fileresprobmorprev),subdirf(fileresprobmorprev));
                   6238:    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);
                   6239:    /*  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  6240:     */
1.218     brouard  6241:    /*   fprintf(ficgp,"\nset out \"varmuptjgr%s%s%s.svg\";replot;",digitp,optionfilefiname,digit); */
                   6242:    fprintf(ficgp,"\nset out;\nset out \"%s%s.svg\";replot;set out;\n",subdirf3(optionfilefiname,"VARMUPTJGR-",digitp),digit);
1.126     brouard  6243: 
1.218     brouard  6244:    free_vector(xp,1,npar);
                   6245:    free_matrix(doldm,1,nlstate,1,nlstate);
                   6246:    free_matrix(dnewm,1,nlstate,1,npar);
                   6247:    free_matrix(doldmp,nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
                   6248:    free_matrix(dnewmp,nlstate+1,nlstate+ndeath,1,npar);
                   6249:    free_matrix(varppt,nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
                   6250:    /* if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX); */
                   6251:    fclose(ficresprobmorprev);
                   6252:    fflush(ficgp);
                   6253:    fflush(fichtm); 
                   6254:  }  /* end varevsij */
1.126     brouard  6255: 
                   6256: /************ Variance of prevlim ******************/
1.269     brouard  6257:  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  6258: {
1.205     brouard  6259:   /* Variance of prevalence limit  for each state ij using current parameters x[] and estimates of neighbourhood give by delti*/
1.126     brouard  6260:   /*  double **prevalim(double **prlim, int nlstate, double *xp, double age, double **oldm, double **savm,double ftolpl);*/
1.164     brouard  6261: 
1.268     brouard  6262:   double **dnewmpar,**doldm;
1.126     brouard  6263:   int i, j, nhstepm, hstepm;
                   6264:   double *xp;
                   6265:   double *gp, *gm;
                   6266:   double **gradg, **trgradg;
1.208     brouard  6267:   double **mgm, **mgp;
1.126     brouard  6268:   double age,agelim;
                   6269:   int theta;
                   6270:   
                   6271:   pstamp(ficresvpl);
1.288     brouard  6272:   fprintf(ficresvpl,"# Standard deviation of period (forward stable) prevalences \n");
1.241     brouard  6273:   fprintf(ficresvpl,"# Age ");
                   6274:   if(nresult >=1)
                   6275:     fprintf(ficresvpl," Result# ");
1.126     brouard  6276:   for(i=1; i<=nlstate;i++)
                   6277:       fprintf(ficresvpl," %1d-%1d",i,i);
                   6278:   fprintf(ficresvpl,"\n");
                   6279: 
                   6280:   xp=vector(1,npar);
1.268     brouard  6281:   dnewmpar=matrix(1,nlstate,1,npar);
1.126     brouard  6282:   doldm=matrix(1,nlstate,1,nlstate);
                   6283:   
                   6284:   hstepm=1*YEARM; /* Every year of age */
                   6285:   hstepm=hstepm/stepm; /* Typically in stepm units, if j= 2 years, = 2/6 months = 4 */ 
                   6286:   agelim = AGESUP;
                   6287:   for (age=bage; age<=fage; age ++){ /* If stepm=6 months */
                   6288:     nhstepm=(int) rint((agelim-age)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */ 
                   6289:     if (stepm >= YEARM) hstepm=1;
                   6290:     nhstepm = nhstepm/hstepm; /* Typically 40/4=10 */
                   6291:     gradg=matrix(1,npar,1,nlstate);
1.208     brouard  6292:     mgp=matrix(1,npar,1,nlstate);
                   6293:     mgm=matrix(1,npar,1,nlstate);
1.126     brouard  6294:     gp=vector(1,nlstate);
                   6295:     gm=vector(1,nlstate);
                   6296: 
                   6297:     for(theta=1; theta <=npar; theta++){
                   6298:       for(i=1; i<=npar; i++){ /* Computes gradient */
                   6299:        xp[i] = x[i] + (i==theta ?delti[theta]:0);
                   6300:       }
1.288     brouard  6301:       /* if((int)age==79 ||(int)age== 80 ||(int)age== 81 ) */
                   6302:       /*       prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp,ij,nres); */
                   6303:       /* else */
                   6304:       prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp,ij,nres);
1.208     brouard  6305:       for(i=1;i<=nlstate;i++){
1.126     brouard  6306:        gp[i] = prlim[i][i];
1.208     brouard  6307:        mgp[theta][i] = prlim[i][i];
                   6308:       }
1.126     brouard  6309:       for(i=1; i<=npar; i++) /* Computes gradient */
                   6310:        xp[i] = x[i] - (i==theta ?delti[theta]:0);
1.288     brouard  6311:       /* if((int)age==79 ||(int)age== 80 ||(int)age== 81 ) */
                   6312:       /*       prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp,ij,nres); */
                   6313:       /* else */
                   6314:       prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp,ij,nres);
1.208     brouard  6315:       for(i=1;i<=nlstate;i++){
1.126     brouard  6316:        gm[i] = prlim[i][i];
1.208     brouard  6317:        mgm[theta][i] = prlim[i][i];
                   6318:       }
1.126     brouard  6319:       for(i=1;i<=nlstate;i++)
                   6320:        gradg[theta][i]= (gp[i]-gm[i])/2./delti[theta];
1.209     brouard  6321:       /* gradg[theta][2]= -gradg[theta][1]; */ /* For testing if nlstate=2 */
1.126     brouard  6322:     } /* End theta */
                   6323: 
                   6324:     trgradg =matrix(1,nlstate,1,npar);
                   6325: 
                   6326:     for(j=1; j<=nlstate;j++)
                   6327:       for(theta=1; theta <=npar; theta++)
                   6328:        trgradg[j][theta]=gradg[theta][j];
1.209     brouard  6329:     /* if((int)age==79 ||(int)age== 80 ||(int)age== 81 ){ */
                   6330:     /*   printf("\nmgm mgp %d ",(int)age); */
                   6331:     /*   for(j=1; j<=nlstate;j++){ */
                   6332:     /*         printf(" %d ",j); */
                   6333:     /*         for(theta=1; theta <=npar; theta++) */
                   6334:     /*           printf(" %d %lf %lf",theta,mgm[theta][j],mgp[theta][j]); */
                   6335:     /*         printf("\n "); */
                   6336:     /*   } */
                   6337:     /* } */
                   6338:     /* if((int)age==79 ||(int)age== 80 ||(int)age== 81 ){ */
                   6339:     /*   printf("\n gradg %d ",(int)age); */
                   6340:     /*   for(j=1; j<=nlstate;j++){ */
                   6341:     /*         printf("%d ",j); */
                   6342:     /*         for(theta=1; theta <=npar; theta++) */
                   6343:     /*           printf("%d %lf ",theta,gradg[theta][j]); */
                   6344:     /*         printf("\n "); */
                   6345:     /*   } */
                   6346:     /* } */
1.126     brouard  6347: 
                   6348:     for(i=1;i<=nlstate;i++)
                   6349:       varpl[i][(int)age] =0.;
1.209     brouard  6350:     if((int)age==79 ||(int)age== 80  ||(int)age== 81){
1.268     brouard  6351:     matprod2(dnewmpar,trgradg,1,nlstate,1,npar,1,npar,matcov);
                   6352:     matprod2(doldm,dnewmpar,1,nlstate,1,npar,1,nlstate,gradg);
1.205     brouard  6353:     }else{
1.268     brouard  6354:     matprod2(dnewmpar,trgradg,1,nlstate,1,npar,1,npar,matcov);
                   6355:     matprod2(doldm,dnewmpar,1,nlstate,1,npar,1,nlstate,gradg);
1.205     brouard  6356:     }
1.126     brouard  6357:     for(i=1;i<=nlstate;i++)
                   6358:       varpl[i][(int)age] = doldm[i][i]; /* Covariances are useless */
                   6359: 
                   6360:     fprintf(ficresvpl,"%.0f ",age );
1.241     brouard  6361:     if(nresult >=1)
                   6362:       fprintf(ficresvpl,"%d ",nres );
1.288     brouard  6363:     for(i=1; i<=nlstate;i++){
1.126     brouard  6364:       fprintf(ficresvpl," %.5f (%.5f)",prlim[i][i],sqrt(varpl[i][(int)age]));
1.288     brouard  6365:       /* for(j=1;j<=nlstate;j++) */
                   6366:       /*       fprintf(ficresvpl," %d %.5f ",j,prlim[j][i]); */
                   6367:     }
1.126     brouard  6368:     fprintf(ficresvpl,"\n");
                   6369:     free_vector(gp,1,nlstate);
                   6370:     free_vector(gm,1,nlstate);
1.208     brouard  6371:     free_matrix(mgm,1,npar,1,nlstate);
                   6372:     free_matrix(mgp,1,npar,1,nlstate);
1.126     brouard  6373:     free_matrix(gradg,1,npar,1,nlstate);
                   6374:     free_matrix(trgradg,1,nlstate,1,npar);
                   6375:   } /* End age */
                   6376: 
                   6377:   free_vector(xp,1,npar);
                   6378:   free_matrix(doldm,1,nlstate,1,npar);
1.268     brouard  6379:   free_matrix(dnewmpar,1,nlstate,1,nlstate);
                   6380: 
                   6381: }
                   6382: 
                   6383: 
                   6384: /************ Variance of backprevalence limit ******************/
1.269     brouard  6385:  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  6386: {
                   6387:   /* Variance of backward prevalence limit  for each state ij using current parameters x[] and estimates of neighbourhood give by delti*/
                   6388:   /*  double **prevalim(double **prlim, int nlstate, double *xp, double age, double **oldm, double **savm,double ftolpl);*/
                   6389: 
                   6390:   double **dnewmpar,**doldm;
                   6391:   int i, j, nhstepm, hstepm;
                   6392:   double *xp;
                   6393:   double *gp, *gm;
                   6394:   double **gradg, **trgradg;
                   6395:   double **mgm, **mgp;
                   6396:   double age,agelim;
                   6397:   int theta;
                   6398:   
                   6399:   pstamp(ficresvbl);
                   6400:   fprintf(ficresvbl,"# Standard deviation of back (stable) prevalences \n");
                   6401:   fprintf(ficresvbl,"# Age ");
                   6402:   if(nresult >=1)
                   6403:     fprintf(ficresvbl," Result# ");
                   6404:   for(i=1; i<=nlstate;i++)
                   6405:       fprintf(ficresvbl," %1d-%1d",i,i);
                   6406:   fprintf(ficresvbl,"\n");
                   6407: 
                   6408:   xp=vector(1,npar);
                   6409:   dnewmpar=matrix(1,nlstate,1,npar);
                   6410:   doldm=matrix(1,nlstate,1,nlstate);
                   6411:   
                   6412:   hstepm=1*YEARM; /* Every year of age */
                   6413:   hstepm=hstepm/stepm; /* Typically in stepm units, if j= 2 years, = 2/6 months = 4 */ 
                   6414:   agelim = AGEINF;
                   6415:   for (age=fage; age>=bage; age --){ /* If stepm=6 months */
                   6416:     nhstepm=(int) rint((age-agelim)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */ 
                   6417:     if (stepm >= YEARM) hstepm=1;
                   6418:     nhstepm = nhstepm/hstepm; /* Typically 40/4=10 */
                   6419:     gradg=matrix(1,npar,1,nlstate);
                   6420:     mgp=matrix(1,npar,1,nlstate);
                   6421:     mgm=matrix(1,npar,1,nlstate);
                   6422:     gp=vector(1,nlstate);
                   6423:     gm=vector(1,nlstate);
                   6424: 
                   6425:     for(theta=1; theta <=npar; theta++){
                   6426:       for(i=1; i<=npar; i++){ /* Computes gradient */
                   6427:        xp[i] = x[i] + (i==theta ?delti[theta]:0);
                   6428:       }
                   6429:       if(mobilavproj > 0 )
                   6430:        bprevalim(bprlim, mobaverage,nlstate,xp,age,ftolpl,ncvyearp,ij,nres);
                   6431:       else
                   6432:        bprevalim(bprlim, mobaverage,nlstate,xp,age,ftolpl,ncvyearp,ij,nres);
                   6433:       for(i=1;i<=nlstate;i++){
                   6434:        gp[i] = bprlim[i][i];
                   6435:        mgp[theta][i] = bprlim[i][i];
                   6436:       }
                   6437:      for(i=1; i<=npar; i++) /* Computes gradient */
                   6438:        xp[i] = x[i] - (i==theta ?delti[theta]:0);
                   6439:        if(mobilavproj > 0 )
                   6440:        bprevalim(bprlim, mobaverage,nlstate,xp,age,ftolpl,ncvyearp,ij,nres);
                   6441:        else
                   6442:        bprevalim(bprlim, mobaverage,nlstate,xp,age,ftolpl,ncvyearp,ij,nres);
                   6443:       for(i=1;i<=nlstate;i++){
                   6444:        gm[i] = bprlim[i][i];
                   6445:        mgm[theta][i] = bprlim[i][i];
                   6446:       }
                   6447:       for(i=1;i<=nlstate;i++)
                   6448:        gradg[theta][i]= (gp[i]-gm[i])/2./delti[theta];
                   6449:       /* gradg[theta][2]= -gradg[theta][1]; */ /* For testing if nlstate=2 */
                   6450:     } /* End theta */
                   6451: 
                   6452:     trgradg =matrix(1,nlstate,1,npar);
                   6453: 
                   6454:     for(j=1; j<=nlstate;j++)
                   6455:       for(theta=1; theta <=npar; theta++)
                   6456:        trgradg[j][theta]=gradg[theta][j];
                   6457:     /* if((int)age==79 ||(int)age== 80 ||(int)age== 81 ){ */
                   6458:     /*   printf("\nmgm mgp %d ",(int)age); */
                   6459:     /*   for(j=1; j<=nlstate;j++){ */
                   6460:     /*         printf(" %d ",j); */
                   6461:     /*         for(theta=1; theta <=npar; theta++) */
                   6462:     /*           printf(" %d %lf %lf",theta,mgm[theta][j],mgp[theta][j]); */
                   6463:     /*         printf("\n "); */
                   6464:     /*   } */
                   6465:     /* } */
                   6466:     /* if((int)age==79 ||(int)age== 80 ||(int)age== 81 ){ */
                   6467:     /*   printf("\n gradg %d ",(int)age); */
                   6468:     /*   for(j=1; j<=nlstate;j++){ */
                   6469:     /*         printf("%d ",j); */
                   6470:     /*         for(theta=1; theta <=npar; theta++) */
                   6471:     /*           printf("%d %lf ",theta,gradg[theta][j]); */
                   6472:     /*         printf("\n "); */
                   6473:     /*   } */
                   6474:     /* } */
                   6475: 
                   6476:     for(i=1;i<=nlstate;i++)
                   6477:       varbpl[i][(int)age] =0.;
                   6478:     if((int)age==79 ||(int)age== 80  ||(int)age== 81){
                   6479:     matprod2(dnewmpar,trgradg,1,nlstate,1,npar,1,npar,matcov);
                   6480:     matprod2(doldm,dnewmpar,1,nlstate,1,npar,1,nlstate,gradg);
                   6481:     }else{
                   6482:     matprod2(dnewmpar,trgradg,1,nlstate,1,npar,1,npar,matcov);
                   6483:     matprod2(doldm,dnewmpar,1,nlstate,1,npar,1,nlstate,gradg);
                   6484:     }
                   6485:     for(i=1;i<=nlstate;i++)
                   6486:       varbpl[i][(int)age] = doldm[i][i]; /* Covariances are useless */
                   6487: 
                   6488:     fprintf(ficresvbl,"%.0f ",age );
                   6489:     if(nresult >=1)
                   6490:       fprintf(ficresvbl,"%d ",nres );
                   6491:     for(i=1; i<=nlstate;i++)
                   6492:       fprintf(ficresvbl," %.5f (%.5f)",bprlim[i][i],sqrt(varbpl[i][(int)age]));
                   6493:     fprintf(ficresvbl,"\n");
                   6494:     free_vector(gp,1,nlstate);
                   6495:     free_vector(gm,1,nlstate);
                   6496:     free_matrix(mgm,1,npar,1,nlstate);
                   6497:     free_matrix(mgp,1,npar,1,nlstate);
                   6498:     free_matrix(gradg,1,npar,1,nlstate);
                   6499:     free_matrix(trgradg,1,nlstate,1,npar);
                   6500:   } /* End age */
                   6501: 
                   6502:   free_vector(xp,1,npar);
                   6503:   free_matrix(doldm,1,nlstate,1,npar);
                   6504:   free_matrix(dnewmpar,1,nlstate,1,nlstate);
1.126     brouard  6505: 
                   6506: }
                   6507: 
                   6508: /************ Variance of one-step probabilities  ******************/
                   6509: 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  6510:  {
                   6511:    int i, j=0,  k1, l1, tj;
                   6512:    int k2, l2, j1,  z1;
                   6513:    int k=0, l;
                   6514:    int first=1, first1, first2;
                   6515:    double cv12, mu1, mu2, lc1, lc2, v12, v21, v11, v22,v1,v2, c12, tnalp;
                   6516:    double **dnewm,**doldm;
                   6517:    double *xp;
                   6518:    double *gp, *gm;
                   6519:    double **gradg, **trgradg;
                   6520:    double **mu;
                   6521:    double age, cov[NCOVMAX+1];
                   6522:    double std=2.0; /* Number of standard deviation wide of confidence ellipsoids */
                   6523:    int theta;
                   6524:    char fileresprob[FILENAMELENGTH];
                   6525:    char fileresprobcov[FILENAMELENGTH];
                   6526:    char fileresprobcor[FILENAMELENGTH];
                   6527:    double ***varpij;
                   6528: 
                   6529:    strcpy(fileresprob,"PROB_"); 
                   6530:    strcat(fileresprob,fileres);
                   6531:    if((ficresprob=fopen(fileresprob,"w"))==NULL) {
                   6532:      printf("Problem with resultfile: %s\n", fileresprob);
                   6533:      fprintf(ficlog,"Problem with resultfile: %s\n", fileresprob);
                   6534:    }
                   6535:    strcpy(fileresprobcov,"PROBCOV_"); 
                   6536:    strcat(fileresprobcov,fileresu);
                   6537:    if((ficresprobcov=fopen(fileresprobcov,"w"))==NULL) {
                   6538:      printf("Problem with resultfile: %s\n", fileresprobcov);
                   6539:      fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobcov);
                   6540:    }
                   6541:    strcpy(fileresprobcor,"PROBCOR_"); 
                   6542:    strcat(fileresprobcor,fileresu);
                   6543:    if((ficresprobcor=fopen(fileresprobcor,"w"))==NULL) {
                   6544:      printf("Problem with resultfile: %s\n", fileresprobcor);
                   6545:      fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobcor);
                   6546:    }
                   6547:    printf("Computing standard deviation of one-step probabilities: result on file '%s' \n",fileresprob);
                   6548:    fprintf(ficlog,"Computing standard deviation of one-step probabilities: result on file '%s' \n",fileresprob);
                   6549:    printf("Computing matrix of variance covariance of one-step probabilities: result on file '%s' \n",fileresprobcov);
                   6550:    fprintf(ficlog,"Computing matrix of variance covariance of one-step probabilities: result on file '%s' \n",fileresprobcov);
                   6551:    printf("and correlation matrix of one-step probabilities: result on file '%s' \n",fileresprobcor);
                   6552:    fprintf(ficlog,"and correlation matrix of one-step probabilities: result on file '%s' \n",fileresprobcor);
                   6553:    pstamp(ficresprob);
                   6554:    fprintf(ficresprob,"#One-step probabilities and stand. devi in ()\n");
                   6555:    fprintf(ficresprob,"# Age");
                   6556:    pstamp(ficresprobcov);
                   6557:    fprintf(ficresprobcov,"#One-step probabilities and covariance matrix\n");
                   6558:    fprintf(ficresprobcov,"# Age");
                   6559:    pstamp(ficresprobcor);
                   6560:    fprintf(ficresprobcor,"#One-step probabilities and correlation matrix\n");
                   6561:    fprintf(ficresprobcor,"# Age");
1.126     brouard  6562: 
                   6563: 
1.222     brouard  6564:    for(i=1; i<=nlstate;i++)
                   6565:      for(j=1; j<=(nlstate+ndeath);j++){
                   6566:        fprintf(ficresprob," p%1d-%1d (SE)",i,j);
                   6567:        fprintf(ficresprobcov," p%1d-%1d ",i,j);
                   6568:        fprintf(ficresprobcor," p%1d-%1d ",i,j);
                   6569:      }  
                   6570:    /* fprintf(ficresprob,"\n");
                   6571:       fprintf(ficresprobcov,"\n");
                   6572:       fprintf(ficresprobcor,"\n");
                   6573:    */
                   6574:    xp=vector(1,npar);
                   6575:    dnewm=matrix(1,(nlstate)*(nlstate+ndeath),1,npar);
                   6576:    doldm=matrix(1,(nlstate)*(nlstate+ndeath),1,(nlstate)*(nlstate+ndeath));
                   6577:    mu=matrix(1,(nlstate)*(nlstate+ndeath), (int) bage, (int)fage);
                   6578:    varpij=ma3x(1,nlstate*(nlstate+ndeath),1,nlstate*(nlstate+ndeath),(int) bage, (int) fage);
                   6579:    first=1;
                   6580:    fprintf(ficgp,"\n# Routine varprob");
                   6581:    fprintf(fichtm,"\n<li><h4> Computing and drawing one step probabilities with their confidence intervals</h4></li>\n");
                   6582:    fprintf(fichtm,"\n");
                   6583: 
1.288     brouard  6584:    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  6585:    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);
                   6586:    fprintf(fichtmcov,"\nEllipsoids of confidence centered on point (p<inf>ij</inf>, p<inf>kl</inf>) are estimated \
1.126     brouard  6587: and drawn. It helps understanding how is the covariance between two incidences.\
                   6588:  They are expressed in year<sup>-1</sup> in order to be less dependent of stepm.<br>\n");
1.222     brouard  6589:    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  6590: It can be understood this way: if pij and pkl where uncorrelated the (2x2) matrix of covariance \
                   6591: would have been (1/(var pij), 0 , 0, 1/(var pkl)), and the confidence interval would be 2 \
                   6592: standard deviations wide on each axis. <br>\
                   6593:  Now, if both incidences are correlated (usual case) we diagonalised the inverse of the covariance matrix\
                   6594:  and made the appropriate rotation to look at the uncorrelated principal directions.<br>\
                   6595: To be simple, these graphs help to understand the significativity of each parameter in relation to a second other one.<br> \n");
                   6596: 
1.222     brouard  6597:    cov[1]=1;
                   6598:    /* tj=cptcoveff; */
1.225     brouard  6599:    tj = (int) pow(2,cptcoveff);
1.222     brouard  6600:    if (cptcovn<1) {tj=1;ncodemax[1]=1;}
                   6601:    j1=0;
1.224     brouard  6602:    for(j1=1; j1<=tj;j1++){  /* For each valid combination of covariates or only once*/
1.222     brouard  6603:      if  (cptcovn>0) {
                   6604:        fprintf(ficresprob, "\n#********** Variable "); 
1.225     brouard  6605:        for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresprob, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
1.222     brouard  6606:        fprintf(ficresprob, "**********\n#\n");
                   6607:        fprintf(ficresprobcov, "\n#********** Variable "); 
1.225     brouard  6608:        for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresprobcov, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
1.222     brouard  6609:        fprintf(ficresprobcov, "**********\n#\n");
1.220     brouard  6610:                        
1.222     brouard  6611:        fprintf(ficgp, "\n#********** Variable "); 
1.225     brouard  6612:        for (z1=1; z1<=cptcoveff; z1++) fprintf(ficgp, " V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
1.222     brouard  6613:        fprintf(ficgp, "**********\n#\n");
1.220     brouard  6614:                        
                   6615:                        
1.222     brouard  6616:        fprintf(fichtmcov, "\n<hr  size=\"2\" color=\"#EC5E5E\">********** Variable "); 
1.225     brouard  6617:        for (z1=1; z1<=cptcoveff; z1++) fprintf(fichtm, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
1.222     brouard  6618:        fprintf(fichtmcov, "**********\n<hr size=\"2\" color=\"#EC5E5E\">");
1.220     brouard  6619:                        
1.222     brouard  6620:        fprintf(ficresprobcor, "\n#********** Variable ");    
1.225     brouard  6621:        for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresprobcor, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
1.222     brouard  6622:        fprintf(ficresprobcor, "**********\n#");    
                   6623:        if(invalidvarcomb[j1]){
                   6624:         fprintf(ficgp,"\n#Combination (%d) ignored because no cases \n",j1); 
                   6625:         fprintf(fichtmcov,"\n<h3>Combination (%d) ignored because no cases </h3>\n",j1); 
                   6626:         continue;
                   6627:        }
                   6628:      }
                   6629:      gradg=matrix(1,npar,1,(nlstate)*(nlstate+ndeath));
                   6630:      trgradg=matrix(1,(nlstate)*(nlstate+ndeath),1,npar);
                   6631:      gp=vector(1,(nlstate)*(nlstate+ndeath));
                   6632:      gm=vector(1,(nlstate)*(nlstate+ndeath));
                   6633:      for (age=bage; age<=fage; age ++){ 
                   6634:        cov[2]=age;
                   6635:        if(nagesqr==1)
                   6636:         cov[3]= age*age;
                   6637:        for (k=1; k<=cptcovn;k++) {
                   6638:         cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(j1,k)];
                   6639:         /*cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(j1,Tvar[k])];*//* j1 1 2 3 4
                   6640:                                                                    * 1  1 1 1 1
                   6641:                                                                    * 2  2 1 1 1
                   6642:                                                                    * 3  1 2 1 1
                   6643:                                                                    */
                   6644:         /* nbcode[1][1]=0 nbcode[1][2]=1;*/
                   6645:        }
                   6646:        /* for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2]; */
                   6647:        for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,k)]*cov[2];
                   6648:        for (k=1; k<=cptcovprod;k++)
                   6649:         cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)]*nbcode[Tvard[k][2]][codtabm(ij,k)];
1.220     brouard  6650:                        
                   6651:                        
1.222     brouard  6652:        for(theta=1; theta <=npar; theta++){
                   6653:         for(i=1; i<=npar; i++)
                   6654:           xp[i] = x[i] + (i==theta ?delti[theta]:(double)0);
1.220     brouard  6655:                                
1.222     brouard  6656:         pmij(pmmij,cov,ncovmodel,xp,nlstate);
1.220     brouard  6657:                                
1.222     brouard  6658:         k=0;
                   6659:         for(i=1; i<= (nlstate); i++){
                   6660:           for(j=1; j<=(nlstate+ndeath);j++){
                   6661:             k=k+1;
                   6662:             gp[k]=pmmij[i][j];
                   6663:           }
                   6664:         }
1.220     brouard  6665:                                
1.222     brouard  6666:         for(i=1; i<=npar; i++)
                   6667:           xp[i] = x[i] - (i==theta ?delti[theta]:(double)0);
1.220     brouard  6668:                                
1.222     brouard  6669:         pmij(pmmij,cov,ncovmodel,xp,nlstate);
                   6670:         k=0;
                   6671:         for(i=1; i<=(nlstate); i++){
                   6672:           for(j=1; j<=(nlstate+ndeath);j++){
                   6673:             k=k+1;
                   6674:             gm[k]=pmmij[i][j];
                   6675:           }
                   6676:         }
1.220     brouard  6677:                                
1.222     brouard  6678:         for(i=1; i<= (nlstate)*(nlstate+ndeath); i++) 
                   6679:           gradg[theta][i]=(gp[i]-gm[i])/(double)2./delti[theta];  
                   6680:        }
1.126     brouard  6681: 
1.222     brouard  6682:        for(j=1; j<=(nlstate)*(nlstate+ndeath);j++)
                   6683:         for(theta=1; theta <=npar; theta++)
                   6684:           trgradg[j][theta]=gradg[theta][j];
1.220     brouard  6685:                        
1.222     brouard  6686:        matprod2(dnewm,trgradg,1,(nlstate)*(nlstate+ndeath),1,npar,1,npar,matcov); 
                   6687:        matprod2(doldm,dnewm,1,(nlstate)*(nlstate+ndeath),1,npar,1,(nlstate)*(nlstate+ndeath),gradg);
1.220     brouard  6688:                        
1.222     brouard  6689:        pmij(pmmij,cov,ncovmodel,x,nlstate);
1.220     brouard  6690:                        
1.222     brouard  6691:        k=0;
                   6692:        for(i=1; i<=(nlstate); i++){
                   6693:         for(j=1; j<=(nlstate+ndeath);j++){
                   6694:           k=k+1;
                   6695:           mu[k][(int) age]=pmmij[i][j];
                   6696:         }
                   6697:        }
                   6698:        for(i=1;i<=(nlstate)*(nlstate+ndeath);i++)
                   6699:         for(j=1;j<=(nlstate)*(nlstate+ndeath);j++)
                   6700:           varpij[i][j][(int)age] = doldm[i][j];
1.220     brouard  6701:                        
1.222     brouard  6702:        /*printf("\n%d ",(int)age);
                   6703:         for (i=1; i<=(nlstate)*(nlstate+ndeath);i++){
                   6704:         printf("%e [%e ;%e] ",gm[i],gm[i]-2*sqrt(doldm[i][i]),gm[i]+2*sqrt(doldm[i][i]));
                   6705:         fprintf(ficlog,"%e [%e ;%e] ",gm[i],gm[i]-2*sqrt(doldm[i][i]),gm[i]+2*sqrt(doldm[i][i]));
                   6706:         }*/
1.220     brouard  6707:                        
1.222     brouard  6708:        fprintf(ficresprob,"\n%d ",(int)age);
                   6709:        fprintf(ficresprobcov,"\n%d ",(int)age);
                   6710:        fprintf(ficresprobcor,"\n%d ",(int)age);
1.220     brouard  6711:                        
1.222     brouard  6712:        for (i=1; i<=(nlstate)*(nlstate+ndeath);i++)
                   6713:         fprintf(ficresprob,"%11.3e (%11.3e) ",mu[i][(int) age],sqrt(varpij[i][i][(int)age]));
                   6714:        for (i=1; i<=(nlstate)*(nlstate+ndeath);i++){
                   6715:         fprintf(ficresprobcov,"%11.3e ",mu[i][(int) age]);
                   6716:         fprintf(ficresprobcor,"%11.3e ",mu[i][(int) age]);
                   6717:        }
                   6718:        i=0;
                   6719:        for (k=1; k<=(nlstate);k++){
                   6720:         for (l=1; l<=(nlstate+ndeath);l++){ 
                   6721:           i++;
                   6722:           fprintf(ficresprobcov,"\n%d %d-%d",(int)age,k,l);
                   6723:           fprintf(ficresprobcor,"\n%d %d-%d",(int)age,k,l);
                   6724:           for (j=1; j<=i;j++){
                   6725:             /* printf(" k=%d l=%d i=%d j=%d\n",k,l,i,j);fflush(stdout); */
                   6726:             fprintf(ficresprobcov," %11.3e",varpij[i][j][(int)age]);
                   6727:             fprintf(ficresprobcor," %11.3e",varpij[i][j][(int) age]/sqrt(varpij[i][i][(int) age])/sqrt(varpij[j][j][(int)age]));
                   6728:           }
                   6729:         }
                   6730:        }/* end of loop for state */
                   6731:      } /* end of loop for age */
                   6732:      free_vector(gp,1,(nlstate+ndeath)*(nlstate+ndeath));
                   6733:      free_vector(gm,1,(nlstate+ndeath)*(nlstate+ndeath));
                   6734:      free_matrix(trgradg,1,(nlstate+ndeath)*(nlstate+ndeath),1,npar);
                   6735:      free_matrix(gradg,1,(nlstate+ndeath)*(nlstate+ndeath),1,npar);
                   6736:     
                   6737:      /* Confidence intervalle of pij  */
                   6738:      /*
                   6739:        fprintf(ficgp,"\nunset parametric;unset label");
                   6740:        fprintf(ficgp,"\nset log y;unset log x; set xlabel \"Age\";set ylabel \"probability (year-1)\"");
                   6741:        fprintf(ficgp,"\nset ter png small\nset size 0.65,0.65");
                   6742:        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);
                   6743:        fprintf(fichtm,"\n<br><img src=\"pijgr%s.png\"> ",optionfilefiname);
                   6744:        fprintf(ficgp,"\nset out \"pijgr%s.png\"",optionfilefiname);
                   6745:        fprintf(ficgp,"\nplot \"%s\" every :::%d::%d u 1:2 \"\%%lf",k1,k2,xfilevarprob);
                   6746:      */
                   6747:                
                   6748:      /* Drawing ellipsoids of confidence of two variables p(k1-l1,k2-l2)*/
                   6749:      first1=1;first2=2;
                   6750:      for (k2=1; k2<=(nlstate);k2++){
                   6751:        for (l2=1; l2<=(nlstate+ndeath);l2++){ 
                   6752:         if(l2==k2) continue;
                   6753:         j=(k2-1)*(nlstate+ndeath)+l2;
                   6754:         for (k1=1; k1<=(nlstate);k1++){
                   6755:           for (l1=1; l1<=(nlstate+ndeath);l1++){ 
                   6756:             if(l1==k1) continue;
                   6757:             i=(k1-1)*(nlstate+ndeath)+l1;
                   6758:             if(i<=j) continue;
                   6759:             for (age=bage; age<=fage; age ++){ 
                   6760:               if ((int)age %5==0){
                   6761:                 v1=varpij[i][i][(int)age]/stepm*YEARM/stepm*YEARM;
                   6762:                 v2=varpij[j][j][(int)age]/stepm*YEARM/stepm*YEARM;
                   6763:                 cv12=varpij[i][j][(int)age]/stepm*YEARM/stepm*YEARM;
                   6764:                 mu1=mu[i][(int) age]/stepm*YEARM ;
                   6765:                 mu2=mu[j][(int) age]/stepm*YEARM;
                   6766:                 c12=cv12/sqrt(v1*v2);
                   6767:                 /* Computing eigen value of matrix of covariance */
                   6768:                 lc1=((v1+v2)+sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
                   6769:                 lc2=((v1+v2)-sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
                   6770:                 if ((lc2 <0) || (lc1 <0) ){
                   6771:                   if(first2==1){
                   6772:                     first1=0;
                   6773:                     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);
                   6774:                   }
                   6775:                   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);
                   6776:                   /* lc1=fabs(lc1); */ /* If we want to have them positive */
                   6777:                   /* lc2=fabs(lc2); */
                   6778:                 }
1.220     brouard  6779:                                                                
1.222     brouard  6780:                 /* Eigen vectors */
1.280     brouard  6781:                 if(1+(v1-lc1)*(v1-lc1)/cv12/cv12 <1.e-5){
                   6782:                   printf(" Error sqrt of a negative number: %lf\n",1+(v1-lc1)*(v1-lc1)/cv12/cv12);
                   6783:                   fprintf(ficlog," Error sqrt of a negative number: %lf\n",1+(v1-lc1)*(v1-lc1)/cv12/cv12);
                   6784:                   v11=(1./sqrt(fabs(1+(v1-lc1)*(v1-lc1)/cv12/cv12)));
                   6785:                 }else
                   6786:                   v11=(1./sqrt(1+(v1-lc1)*(v1-lc1)/cv12/cv12));
1.222     brouard  6787:                 /*v21=sqrt(1.-v11*v11); *//* error */
                   6788:                 v21=(lc1-v1)/cv12*v11;
                   6789:                 v12=-v21;
                   6790:                 v22=v11;
                   6791:                 tnalp=v21/v11;
                   6792:                 if(first1==1){
                   6793:                   first1=0;
                   6794:                   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);
                   6795:                 }
                   6796:                 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);
                   6797:                 /*printf(fignu*/
                   6798:                 /* mu1+ v11*lc1*cost + v12*lc2*sin(t) */
                   6799:                 /* mu2+ v21*lc1*cost + v22*lc2*sin(t) */
                   6800:                 if(first==1){
                   6801:                   first=0;
                   6802:                   fprintf(ficgp,"\n# Ellipsoids of confidence\n#\n");
                   6803:                   fprintf(ficgp,"\nset parametric;unset label");
                   6804:                   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);
                   6805:                   fprintf(ficgp,"\nset ter svg size 640, 480");
1.266     brouard  6806:                   fprintf(fichtmcov,"\n<p><br>Ellipsoids of confidence cov(p%1d%1d,p%1d%1d) expressed in year<sup>-1</sup>\
1.220     brouard  6807:  :<a href=\"%s_%d%1d%1d-%1d%1d.svg\">                                                                                                                                          \
1.201     brouard  6808: %s_%d%1d%1d-%1d%1d.svg</A>, ",k1,l1,k2,l2,\
1.222     brouard  6809:                           subdirf2(optionfilefiname,"VARPIJGR_"), j1,k1,l1,k2,l2,      \
                   6810:                           subdirf2(optionfilefiname,"VARPIJGR_"), j1,k1,l1,k2,l2);
                   6811:                   fprintf(fichtmcov,"\n<br><img src=\"%s_%d%1d%1d-%1d%1d.svg\"> ",subdirf2(optionfilefiname,"VARPIJGR_"), j1,k1,l1,k2,l2);
                   6812:                   fprintf(fichtmcov,"\n<br> Correlation at age %d (%.3f),",(int) age, c12);
                   6813:                   fprintf(ficgp,"\nset out \"%s_%d%1d%1d-%1d%1d.svg\"",subdirf2(optionfilefiname,"VARPIJGR_"), j1,k1,l1,k2,l2);
                   6814:                   fprintf(ficgp,"\nset label \"%d\" at %11.3e,%11.3e center",(int) age, mu1,mu2);
                   6815:                   fprintf(ficgp,"\n# Age %d, p%1d%1d - p%1d%1d",(int) age, k1,l1,k2,l2);
                   6816:                   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  6817:                           mu1,std,v11,sqrt(fabs(lc1)),v12,sqrt(fabs(lc2)), \
                   6818:                           mu2,std,v21,sqrt(fabs(lc1)),v22,sqrt(fabs(lc2))); /* For gnuplot only */
1.222     brouard  6819:                 }else{
                   6820:                   first=0;
                   6821:                   fprintf(fichtmcov," %d (%.3f),",(int) age, c12);
                   6822:                   fprintf(ficgp,"\n# Age %d, p%1d%1d - p%1d%1d",(int) age, k1,l1,k2,l2);
                   6823:                   fprintf(ficgp,"\nset label \"%d\" at %11.3e,%11.3e center",(int) age, mu1,mu2);
                   6824:                   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  6825:                           mu1,std,v11,sqrt(lc1),v12,sqrt(fabs(lc2)),   \
                   6826:                           mu2,std,v21,sqrt(lc1),v22,sqrt(fabs(lc2)));
1.222     brouard  6827:                 }/* if first */
                   6828:               } /* age mod 5 */
                   6829:             } /* end loop age */
                   6830:             fprintf(ficgp,"\nset out;\nset out \"%s_%d%1d%1d-%1d%1d.svg\";replot;set out;",subdirf2(optionfilefiname,"VARPIJGR_"), j1,k1,l1,k2,l2);
                   6831:             first=1;
                   6832:           } /*l12 */
                   6833:         } /* k12 */
                   6834:        } /*l1 */
                   6835:      }/* k1 */
                   6836:    }  /* loop on combination of covariates j1 */
                   6837:    free_ma3x(varpij,1,nlstate,1,nlstate+ndeath,(int) bage, (int)fage);
                   6838:    free_matrix(mu,1,(nlstate+ndeath)*(nlstate+ndeath),(int) bage, (int)fage);
                   6839:    free_matrix(doldm,1,(nlstate)*(nlstate+ndeath),1,(nlstate)*(nlstate+ndeath));
                   6840:    free_matrix(dnewm,1,(nlstate)*(nlstate+ndeath),1,npar);
                   6841:    free_vector(xp,1,npar);
                   6842:    fclose(ficresprob);
                   6843:    fclose(ficresprobcov);
                   6844:    fclose(ficresprobcor);
                   6845:    fflush(ficgp);
                   6846:    fflush(fichtmcov);
                   6847:  }
1.126     brouard  6848: 
                   6849: 
                   6850: /******************* Printing html file ***********/
1.201     brouard  6851: void printinghtml(char fileresu[], char title[], char datafile[], int firstpass, \
1.126     brouard  6852:                  int lastpass, int stepm, int weightopt, char model[],\
                   6853:                  int imx,int jmin, int jmax, double jmeanint,char rfileres[],\
1.296     brouard  6854:                  int popforecast, int mobilav, int prevfcast, int mobilavproj, int prevbcast, int estepm , \
                   6855:                  double jprev1, double mprev1,double anprev1, double dateprev1, double dateprojd, double dateback1, \
                   6856:                  double jprev2, double mprev2,double anprev2, double dateprev2, double dateprojf, double dateback2){
1.237     brouard  6857:   int jj1, k1, i1, cpt, k4, nres;
1.126     brouard  6858: 
                   6859:    fprintf(fichtm,"<ul><li><a href='#firstorder'>Result files (first order: no variance)</a>\n \
                   6860:    <li><a href='#secondorder'>Result files (second order (variance)</a>\n \
                   6861: </ul>");
1.237     brouard  6862:    fprintf(fichtm,"<ul><li> model=1+age+%s\n \
                   6863: </ul>", model);
1.214     brouard  6864:    fprintf(fichtm,"<ul><li><h4><a name='firstorder'>Result files (first order: no variance)</a></h4>\n");
                   6865:    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",
                   6866:           jprev1, mprev1,anprev1,jprev2, mprev2,anprev2,subdirfext3(optionfilefiname,"PHTMFR_",".htm"),subdirfext3(optionfilefiname,"PHTMFR_",".htm"));
                   6867:    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  6868:           jprev1, mprev1,anprev1,jprev2, mprev2,anprev2,subdirfext3(optionfilefiname,"PHTM_",".htm"),subdirfext3(optionfilefiname,"PHTM_",".htm"));
                   6869:    fprintf(fichtm,",  <a href=\"%s\">%s</a> (text file) <br>\n",subdirf2(fileresu,"P_"),subdirf2(fileresu,"P_"));
1.126     brouard  6870:    fprintf(fichtm,"\
                   6871:  - Estimated transition probabilities over %d (stepm) months: <a href=\"%s\">%s</a><br>\n ",
1.201     brouard  6872:           stepm,subdirf2(fileresu,"PIJ_"),subdirf2(fileresu,"PIJ_"));
1.126     brouard  6873:    fprintf(fichtm,"\
1.217     brouard  6874:  - Estimated back transition probabilities over %d (stepm) months: <a href=\"%s\">%s</a><br>\n ",
                   6875:           stepm,subdirf2(fileresu,"PIJB_"),subdirf2(fileresu,"PIJB_"));
                   6876:    fprintf(fichtm,"\
1.288     brouard  6877:  - Period (forward) prevalence in each health state: <a href=\"%s\">%s</a> <br>\n",
1.201     brouard  6878:           subdirf2(fileresu,"PL_"),subdirf2(fileresu,"PL_"));
1.126     brouard  6879:    fprintf(fichtm,"\
1.288     brouard  6880:  - Backward prevalence in each health state: <a href=\"%s\">%s</a> <br>\n",
1.217     brouard  6881:           subdirf2(fileresu,"PLB_"),subdirf2(fileresu,"PLB_"));
                   6882:    fprintf(fichtm,"\
1.211     brouard  6883:  - (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  6884:    <a href=\"%s\">%s</a> <br>\n",
1.201     brouard  6885:           estepm,subdirf2(fileresu,"E_"),subdirf2(fileresu,"E_"));
1.211     brouard  6886:    if(prevfcast==1){
                   6887:      fprintf(fichtm,"\
                   6888:  - Prevalence projections by age and states:                           \
1.201     brouard  6889:    <a href=\"%s\">%s</a> <br>\n</li>", subdirf2(fileresu,"F_"),subdirf2(fileresu,"F_"));
1.211     brouard  6890:    }
1.126     brouard  6891: 
                   6892: 
1.225     brouard  6893:    m=pow(2,cptcoveff);
1.222     brouard  6894:    if (cptcovn < 1) {m=1;ncodemax[1]=1;}
1.126     brouard  6895: 
1.264     brouard  6896:    fprintf(fichtm," \n<ul><li><b>Graphs</b></li><p>");
                   6897: 
                   6898:    jj1=0;
                   6899: 
                   6900:    fprintf(fichtm," \n<ul>");
                   6901:    for(nres=1; nres <= nresult; nres++) /* For each resultline */
                   6902:    for(k1=1; k1<=m;k1++){ /* For each combination of covariate */
                   6903:      if(m != 1 && TKresult[nres]!= k1)
                   6904:        continue;
                   6905:      jj1++;
                   6906:      if (cptcovn > 0) {
                   6907:        fprintf(fichtm,"\n<li><a  size=\"1\" color=\"#EC5E5E\" href=\"#rescov");
                   6908:        for (cpt=1; cpt<=cptcoveff;cpt++){ 
                   6909:         fprintf(fichtm,"_V%d=%d_",Tvresult[nres][cpt],(int)Tresult[nres][cpt]);
                   6910:        }
                   6911:        for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
                   6912:         fprintf(fichtm,"_V%d=%f_",Tvqresult[nres][k4],Tqresult[nres][k4]);
                   6913:        }
                   6914:        fprintf(fichtm,"\">");
                   6915:        
                   6916:        /* if(nqfveff+nqtveff 0) */ /* Test to be done */
                   6917:        fprintf(fichtm,"************ Results for covariates");
                   6918:        for (cpt=1; cpt<=cptcoveff;cpt++){ 
                   6919:         fprintf(fichtm," V%d=%d ",Tvresult[nres][cpt],(int)Tresult[nres][cpt]);
                   6920:        }
                   6921:        for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
                   6922:         fprintf(fichtm," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
                   6923:        }
                   6924:        if(invalidvarcomb[k1]){
                   6925:         fprintf(fichtm," Warning Combination (%d) ignored because no cases ",k1); 
                   6926:         continue;
                   6927:        }
                   6928:        fprintf(fichtm,"</a></li>");
                   6929:      } /* cptcovn >0 */
                   6930:    }
                   6931:      fprintf(fichtm," \n</ul>");
                   6932: 
1.222     brouard  6933:    jj1=0;
1.237     brouard  6934: 
                   6935:    for(nres=1; nres <= nresult; nres++) /* For each resultline */
1.241     brouard  6936:    for(k1=1; k1<=m;k1++){ /* For each combination of covariate */
1.253     brouard  6937:      if(m != 1 && TKresult[nres]!= k1)
1.237     brouard  6938:        continue;
1.220     brouard  6939: 
1.222     brouard  6940:      /* for(i1=1; i1<=ncodemax[k1];i1++){ */
                   6941:      jj1++;
                   6942:      if (cptcovn > 0) {
1.264     brouard  6943:        fprintf(fichtm,"\n<p><a name=\"rescov");
                   6944:        for (cpt=1; cpt<=cptcoveff;cpt++){ 
                   6945:         fprintf(fichtm,"_V%d=%d_",Tvresult[nres][cpt],(int)Tresult[nres][cpt]);
                   6946:        }
                   6947:        for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
                   6948:         fprintf(fichtm,"_V%d=%f_",Tvqresult[nres][k4],Tqresult[nres][k4]);
                   6949:        }
                   6950:        fprintf(fichtm,"\"</a>");
                   6951:  
1.222     brouard  6952:        fprintf(fichtm,"<hr  size=\"2\" color=\"#EC5E5E\">************ Results for covariates");
1.225     brouard  6953:        for (cpt=1; cpt<=cptcoveff;cpt++){ 
1.237     brouard  6954:         fprintf(fichtm," V%d=%d ",Tvresult[nres][cpt],(int)Tresult[nres][cpt]);
                   6955:         printf(" V%d=%d ",Tvresult[nres][cpt],Tresult[nres][cpt]);fflush(stdout);
                   6956:         /* fprintf(fichtm," V%d=%d ",Tvaraff[cpt],nbcode[Tvaraff[cpt]][codtabm(jj1,cpt)]); */
                   6957:         /* printf(" V%d=%d ",Tvaraff[cpt],nbcode[Tvaraff[cpt]][codtabm(jj1,cpt)]);fflush(stdout); */
1.222     brouard  6958:        }
1.237     brouard  6959:        for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
                   6960:        fprintf(fichtm," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
                   6961:        printf(" V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);fflush(stdout);
                   6962:       }
                   6963:        
1.230     brouard  6964:        /* if(nqfveff+nqtveff 0) */ /* Test to be done */
1.222     brouard  6965:        fprintf(fichtm," ************\n<hr size=\"2\" color=\"#EC5E5E\">");
                   6966:        if(invalidvarcomb[k1]){
                   6967:         fprintf(fichtm,"\n<h3>Combination (%d) ignored because no cases </h3>\n",k1); 
                   6968:         printf("\nCombination (%d) ignored because no cases \n",k1); 
                   6969:         continue;
                   6970:        }
                   6971:      }
                   6972:      /* aij, bij */
1.259     brouard  6973:      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  6974: <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  6975:      /* Pij */
1.241     brouard  6976:      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> \
                   6977: <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  6978:      /* Quasi-incidences */
                   6979:      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  6980:  before but expressed in per year i.e. quasi incidences if stepm is small and probabilities too, \
1.211     brouard  6981:  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  6982: 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> \
                   6983: <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  6984:      /* Survival functions (period) in state j */
                   6985:      for(cpt=1; cpt<=nlstate;cpt++){
1.292     brouard  6986:        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  6987: <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  6988:      }
                   6989:      /* State specific survival functions (period) */
                   6990:      for(cpt=1; cpt<=nlstate;cpt++){
1.292     brouard  6991:        fprintf(fichtm,"<br>\n- Survival functions in state %d and in any other live state (total).\
                   6992:  And probability to be observed in various states (up to %d) being in state %d at different ages.      \
1.283     brouard  6993:  <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  6994:      }
1.288     brouard  6995:      /* Period (forward stable) prevalence in each health state */
1.222     brouard  6996:      for(cpt=1; cpt<=nlstate;cpt++){
1.264     brouard  6997:        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> \
                   6998: <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  6999:      }
1.296     brouard  7000:      if(prevbcast==1){
1.288     brouard  7001:        /* Backward prevalence in each health state */
1.222     brouard  7002:        for(cpt=1; cpt<=nlstate;cpt++){
1.264     brouard  7003:         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  7004: <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  7005:        }
1.217     brouard  7006:      }
1.222     brouard  7007:      if(prevfcast==1){
1.288     brouard  7008:        /* Projection of prevalence up to period (forward stable) prevalence in each health state */
1.222     brouard  7009:        for(cpt=1; cpt<=nlstate;cpt++){
1.288     brouard  7010:         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  7011: <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  7012:        }
                   7013:      }
1.296     brouard  7014:      if(prevbcast==1){
1.268     brouard  7015:       /* Back projection of prevalence up to stable (mixed) back-prevalence in each health state */
                   7016:        for(cpt=1; cpt<=nlstate;cpt++){
1.273     brouard  7017:         fprintf(fichtm,"<br>\n- Back projection of cross-sectional prevalence (estimated with cases observed from %.1f to %.1f and mobil_average=%d), \
                   7018:  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 \
                   7019:  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) \
                   7020: with weights corresponding to observed prevalence at different ages. <a href=\"%s_%d-%d-%d.svg\">%s_%d-%d-%d.svg</a><br> \
                   7021:  <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  7022:        }
                   7023:      }
1.220     brouard  7024:         
1.222     brouard  7025:      for(cpt=1; cpt<=nlstate;cpt++) {
1.241     brouard  7026:        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> \
                   7027: <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  7028:      }
                   7029:      /* } /\* end i1 *\/ */
                   7030:    }/* End k1 */
                   7031:    fprintf(fichtm,"</ul>");
1.126     brouard  7032: 
1.222     brouard  7033:    fprintf(fichtm,"\
1.126     brouard  7034: \n<br><li><h4> <a name='secondorder'>Result files (second order: variances)</a></h4>\n\
1.193     brouard  7035:  - Parameter file with estimated parameters and covariance matrix: <a href=\"%s\">%s</a> <br> \
1.203     brouard  7036:  - 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  7037: But because parameters are usually highly correlated (a higher incidence of disability \
                   7038: and a higher incidence of recovery can give very close observed transition) it might \
                   7039: be very useful to look not only at linear confidence intervals estimated from the \
                   7040: variances but at the covariance matrix. And instead of looking at the estimated coefficients \
                   7041: (parameters) of the logistic regression, it might be more meaningful to visualize the \
                   7042: covariance matrix of the one-step probabilities. \
                   7043: See page 'Matrix of variance-covariance of one-step probabilities' below. \n", rfileres,rfileres);
1.126     brouard  7044: 
1.222     brouard  7045:    fprintf(fichtm," - Standard deviation of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
                   7046:           subdirf2(fileresu,"PROB_"),subdirf2(fileresu,"PROB_"));
                   7047:    fprintf(fichtm,"\
1.126     brouard  7048:  - Variance-covariance of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
1.222     brouard  7049:           subdirf2(fileresu,"PROBCOV_"),subdirf2(fileresu,"PROBCOV_"));
1.126     brouard  7050: 
1.222     brouard  7051:    fprintf(fichtm,"\
1.126     brouard  7052:  - Correlation matrix of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
1.222     brouard  7053:           subdirf2(fileresu,"PROBCOR_"),subdirf2(fileresu,"PROBCOR_"));
                   7054:    fprintf(fichtm,"\
1.126     brouard  7055:  - 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): \
                   7056:    <a href=\"%s\">%s</a> <br>\n</li>",
1.201     brouard  7057:           estepm,subdirf2(fileresu,"CVE_"),subdirf2(fileresu,"CVE_"));
1.222     brouard  7058:    fprintf(fichtm,"\
1.126     brouard  7059:  - (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): \
                   7060:    <a href=\"%s\">%s</a> <br>\n</li>",
1.201     brouard  7061:           estepm,subdirf2(fileresu,"STDE_"),subdirf2(fileresu,"STDE_"));
1.222     brouard  7062:    fprintf(fichtm,"\
1.288     brouard  7063:  - 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  7064:           estepm, subdirf2(fileresu,"V_"),subdirf2(fileresu,"V_"));
                   7065:    fprintf(fichtm,"\
1.128     brouard  7066:  - 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  7067:           estepm, subdirf2(fileresu,"T_"),subdirf2(fileresu,"T_"));
                   7068:    fprintf(fichtm,"\
1.288     brouard  7069:  - Standard deviation of forward (period) prevalences: <a href=\"%s\">%s</a> <br>\n",\
1.222     brouard  7070:           subdirf2(fileresu,"VPL_"),subdirf2(fileresu,"VPL_"));
1.126     brouard  7071: 
                   7072: /*  if(popforecast==1) fprintf(fichtm,"\n */
                   7073: /*  - Prevalences forecasting: <a href=\"f%s\">f%s</a> <br>\n */
                   7074: /*  - Population forecasting (if popforecast=1): <a href=\"pop%s\">pop%s</a> <br>\n */
                   7075: /*     <br>",fileres,fileres,fileres,fileres); */
                   7076: /*  else  */
                   7077: /*    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  7078:    fflush(fichtm);
                   7079:    fprintf(fichtm," <ul><li><b>Graphs</b></li><p>");
1.126     brouard  7080: 
1.225     brouard  7081:    m=pow(2,cptcoveff);
1.222     brouard  7082:    if (cptcovn < 1) {m=1;ncodemax[1]=1;}
1.126     brouard  7083: 
1.222     brouard  7084:    jj1=0;
1.237     brouard  7085: 
1.241     brouard  7086:    for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.222     brouard  7087:    for(k1=1; k1<=m;k1++){
1.253     brouard  7088:      if(m != 1 && TKresult[nres]!= k1)
1.237     brouard  7089:        continue;
1.222     brouard  7090:      /* for(i1=1; i1<=ncodemax[k1];i1++){ */
                   7091:      jj1++;
1.126     brouard  7092:      if (cptcovn > 0) {
                   7093:        fprintf(fichtm,"<hr  size=\"2\" color=\"#EC5E5E\">************ Results for covariates");
1.225     brouard  7094:        for (cpt=1; cpt<=cptcoveff;cpt++)  /**< cptcoveff number of variables */
1.237     brouard  7095:         fprintf(fichtm," V%d=%d ",Tvresult[nres][cpt],Tresult[nres][cpt]);
                   7096:         /* fprintf(fichtm," V%d=%d ",Tvaraff[cpt],nbcode[Tvaraff[cpt]][codtabm(jj1,cpt)]); */
                   7097:        for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
                   7098:        fprintf(fichtm," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
                   7099:       }
                   7100: 
1.126     brouard  7101:        fprintf(fichtm," ************\n<hr size=\"2\" color=\"#EC5E5E\">");
1.220     brouard  7102: 
1.222     brouard  7103:        if(invalidvarcomb[k1]){
                   7104:         fprintf(fichtm,"\n<h4>Combination (%d) ignored because no cases </h4>\n",k1); 
                   7105:         continue;
                   7106:        }
1.126     brouard  7107:      }
                   7108:      for(cpt=1; cpt<=nlstate;cpt++) {
1.258     brouard  7109:        fprintf(fichtm,"\n<br>- Observed (cross-sectional with mov_average=%d) and period (incidence based) \
1.241     brouard  7110: 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  7111: <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  7112:      }
                   7113:      fprintf(fichtm,"\n<br>- Total life expectancy by age and \
1.128     brouard  7114: health expectancies in states (1) and (2). If popbased=1 the smooth (due to the model) \
                   7115: true period expectancies (those weighted with period prevalences are also\
                   7116:  drawn in addition to the population based expectancies computed using\
1.241     brouard  7117:  observed and cahotic prevalences:  <a href=\"%s_%d-%d.svg\">%s_%d-%d.svg</a>\n<br>\
                   7118: <img src=\"%s_%d-%d.svg\">",subdirf2(optionfilefiname,"E_"),k1,nres,subdirf2(optionfilefiname,"E_"),k1,nres,subdirf2(optionfilefiname,"E_"),k1,nres);
1.222     brouard  7119:      /* } /\* end i1 *\/ */
                   7120:    }/* End k1 */
1.241     brouard  7121:   }/* End nres */
1.222     brouard  7122:    fprintf(fichtm,"</ul>");
                   7123:    fflush(fichtm);
1.126     brouard  7124: }
                   7125: 
                   7126: /******************* Gnuplot file **************/
1.296     brouard  7127: 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  7128: 
                   7129:   char dirfileres[132],optfileres[132];
1.264     brouard  7130:   char gplotcondition[132], gplotlabel[132];
1.237     brouard  7131:   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  7132:   int lv=0, vlv=0, kl=0;
1.130     brouard  7133:   int ng=0;
1.201     brouard  7134:   int vpopbased;
1.223     brouard  7135:   int ioffset; /* variable offset for columns */
1.270     brouard  7136:   int iyearc=1; /* variable column for year of projection  */
                   7137:   int iagec=1; /* variable column for age of projection  */
1.235     brouard  7138:   int nres=0; /* Index of resultline */
1.266     brouard  7139:   int istart=1; /* For starting graphs in projections */
1.219     brouard  7140: 
1.126     brouard  7141: /*   if((ficgp=fopen(optionfilegnuplot,"a"))==NULL) { */
                   7142: /*     printf("Problem with file %s",optionfilegnuplot); */
                   7143: /*     fprintf(ficlog,"Problem with file %s",optionfilegnuplot); */
                   7144: /*   } */
                   7145: 
                   7146:   /*#ifdef windows */
                   7147:   fprintf(ficgp,"cd \"%s\" \n",pathc);
1.223     brouard  7148:   /*#endif */
1.225     brouard  7149:   m=pow(2,cptcoveff);
1.126     brouard  7150: 
1.274     brouard  7151:   /* diagram of the model */
                   7152:   fprintf(ficgp,"\n#Diagram of the model \n");
                   7153:   fprintf(ficgp,"\ndelta=0.03;delta2=0.07;unset arrow;\n");
                   7154:   fprintf(ficgp,"yoff=(%d > 2? 0:1);\n",nlstate);
                   7155:   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);
                   7156: 
                   7157:   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);
                   7158:   fprintf(ficgp,"\n#show arrow\nunset label\n");
                   7159:   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);
                   7160:   fprintf(ficgp,"\nset label %d+1 sprintf(\"State %%d\",%d+1) center at 0.,0.  font \"helvetica, 16\" tc rgbcolor \"red\"\n",nlstate,nlstate);
                   7161:   fprintf(ficgp,"\n#show label\nunset border;unset xtics; unset ytics;\n");
                   7162:   fprintf(ficgp,"\n\nset ter svg size 640, 480;set out \"%s_.svg\" \n",subdirf2(optionfilefiname,"D_"));
                   7163:   fprintf(ficgp,"unset log y; plot [-1.2:1.2][yoff-1.2:1.2] 1/0 not; set out;reset;\n");
                   7164: 
1.202     brouard  7165:   /* Contribution to likelihood */
                   7166:   /* Plot the probability implied in the likelihood */
1.223     brouard  7167:   fprintf(ficgp,"\n# Contributions to the Likelihood, mle >=1. For mle=4 no interpolation, pure matrix products.\n#\n");
                   7168:   fprintf(ficgp,"\n set log y; unset log x;set xlabel \"Age\"; set ylabel \"Likelihood (-2Log(L))\";");
                   7169:   /* fprintf(ficgp,"\nset ter svg size 640, 480"); */ /* Too big for svg */
                   7170:   fprintf(ficgp,"\nset ter pngcairo size 640, 480");
1.204     brouard  7171: /* nice for mle=4 plot by number of matrix products.
1.202     brouard  7172:    replot  "rrtest1/toto.txt" u 2:($4 == 1 && $5==2 ? $9 : 1/0):5 t "p12" with point lc 1 */
                   7173: /* replot exp(p1+p2*x)/(1+exp(p1+p2*x)+exp(p3+p4*x)+exp(p5+p6*x)) t "p12(x)"  */
1.223     brouard  7174:   /* fprintf(ficgp,"\nset out \"%s.svg\";",subdirf2(optionfilefiname,"ILK_")); */
                   7175:   fprintf(ficgp,"\nset out \"%s-dest.png\";",subdirf2(optionfilefiname,"ILK_"));
                   7176:   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));
                   7177:   fprintf(ficgp,"\nset out \"%s-ori.png\";",subdirf2(optionfilefiname,"ILK_"));
                   7178:   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));
                   7179:   for (i=1; i<= nlstate ; i ++) {
                   7180:     fprintf(ficgp,"\nset out \"%s-p%dj.png\";set ylabel \"Probability for each individual/wave\";",subdirf2(optionfilefiname,"ILK_"),i);
                   7181:     fprintf(ficgp,"unset log;\n# plot weighted, mean weight should have point size of 0.5\n plot  \"%s\"",subdirf(fileresilk));
                   7182:     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);
                   7183:     for (j=2; j<= nlstate+ndeath ; j ++) {
                   7184:       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);
                   7185:     }
                   7186:     fprintf(ficgp,";\nset out; unset ylabel;\n"); 
                   7187:   }
                   7188:   /* 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 */               
                   7189:   /* fprintf(ficgp,"\nset log y;plot  \"%s\" u 2:(-$11):3 t \"All sample, all transitions\" with dots lc variable",subdirf(fileresilk)); */
                   7190:   /* fprintf(ficgp,"\nreplot  \"%s\" u 2:($3 <= 3 ? -$11 : 1/0):3 t \"First 3 individuals\" with line lc variable", subdirf(fileresilk)); */
                   7191:   fprintf(ficgp,"\nset out;unset log\n");
                   7192:   /* fprintf(ficgp,"\nset out \"%s.svg\"; replot; set out; # bug gnuplot",subdirf2(optionfilefiname,"ILK_")); */
1.202     brouard  7193: 
1.126     brouard  7194:   strcpy(dirfileres,optionfilefiname);
                   7195:   strcpy(optfileres,"vpl");
1.223     brouard  7196:   /* 1eme*/
1.238     brouard  7197:   for (cpt=1; cpt<= nlstate ; cpt ++){ /* For each live state */
                   7198:     for (k1=1; k1<= m ; k1 ++){ /* For each valid combination of covariate */
1.236     brouard  7199:       for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.238     brouard  7200:        /* plot [100000000000000000000:-100000000000000000000] "mysbiaspar/vplrmysbiaspar.txt to check */
1.253     brouard  7201:        if(m != 1 && TKresult[nres]!= k1)
1.238     brouard  7202:          continue;
                   7203:        /* We are interested in selected combination by the resultline */
1.246     brouard  7204:        /* printf("\n# 1st: Period (stable) prevalence with CI: 'VPL_' files and live state =%d ", cpt); */
1.288     brouard  7205:        fprintf(ficgp,"\n# 1st: Forward (stable period) prevalence with CI: 'VPL_' files  and live state =%d ", cpt);
1.264     brouard  7206:        strcpy(gplotlabel,"(");
1.238     brouard  7207:        for (k=1; k<=cptcoveff; k++){    /* For each covariate k get corresponding value lv for combination k1 */
                   7208:          lv= decodtabm(k1,k,cptcoveff); /* Should be the value of the covariate corresponding to k1 combination */
                   7209:          /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   7210:          /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   7211:          /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
                   7212:          vlv= nbcode[Tvaraff[k]][lv]; /* vlv is the value of the covariate lv, 0 or 1 */
                   7213:          /* For each combination of covariate k1 (V1=1, V3=0), we printed the current covariate k and its value vlv */
1.246     brouard  7214:          /* printf(" V%d=%d ",Tvaraff[k],vlv); */
1.238     brouard  7215:          fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv);
1.264     brouard  7216:          sprintf(gplotlabel+strlen(gplotlabel)," V%d=%d ",Tvaraff[k],vlv);
1.238     brouard  7217:        }
                   7218:        for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
1.246     brouard  7219:          /* printf(" V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]); */
1.238     brouard  7220:          fprintf(ficgp," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
1.264     brouard  7221:          sprintf(gplotlabel+strlen(gplotlabel)," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
                   7222:        }
                   7223:        strcpy(gplotlabel+strlen(gplotlabel),")");
1.246     brouard  7224:        /* printf("\n#\n"); */
1.238     brouard  7225:        fprintf(ficgp,"\n#\n");
                   7226:        if(invalidvarcomb[k1]){
1.260     brouard  7227:           /*k1=k1-1;*/ /* To be checked */
1.238     brouard  7228:          fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   7229:          continue;
                   7230:        }
1.235     brouard  7231:       
1.241     brouard  7232:        fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" \n",subdirf2(optionfilefiname,"V_"),cpt,k1,nres);
                   7233:        fprintf(ficgp,"\n#set out \"V_%s_%d-%d-%d.svg\" \n",optionfilefiname,cpt,k1,nres);
1.276     brouard  7234:        /* fprintf(ficgp,"set label \"Alive state %d %s\" at graph 0.98,0.5 center rotate font \"Helvetica,12\"\n",cpt,gplotlabel); */
                   7235:        fprintf(ficgp,"set title \"Alive state %d %s\" font \"Helvetica,12\"\n",cpt,gplotlabel);
1.260     brouard  7236:        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);
                   7237:        /* 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); */
                   7238:       /* k1-1 error should be nres-1*/
1.238     brouard  7239:        for (i=1; i<= nlstate ; i ++) {
                   7240:          if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
                   7241:          else        fprintf(ficgp," %%*lf (%%*lf)");
                   7242:        }
1.288     brouard  7243:        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  7244:        for (i=1; i<= nlstate ; i ++) {
                   7245:          if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
                   7246:          else fprintf(ficgp," %%*lf (%%*lf)");
                   7247:        } 
1.260     brouard  7248:        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  7249:        for (i=1; i<= nlstate ; i ++) {
                   7250:          if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
                   7251:          else fprintf(ficgp," %%*lf (%%*lf)");
                   7252:        }  
1.265     brouard  7253:        /* 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)); */
                   7254:        
                   7255:        fprintf(ficgp,"\" t\"\" w l lt 1,\"%s\" u 1:((",subdirf2(fileresu,"P_"));
                   7256:         if(cptcoveff ==0){
1.271     brouard  7257:          fprintf(ficgp,"$%d)) t 'Observed prevalence in state %d' with line lt 3",      2+3*(cpt-1),  cpt );
1.265     brouard  7258:        }else{
                   7259:          kl=0;
                   7260:          for (k=1; k<=cptcoveff; k++){    /* For each combination of covariate  */
                   7261:            lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate value corresponding to k1 combination and kth covariate */
                   7262:            /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   7263:            /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   7264:            /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
                   7265:            vlv= nbcode[Tvaraff[k]][lv];
                   7266:            kl++;
                   7267:            /* 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 *\/ */
                   7268:            /*6+(cpt-1)*(nlstate+1)+1+(i-1)+(nlstate+1)*nlstate; 6+(1-1)*(2+1)+1+(1-1) +(2+1)*2=13 */ 
                   7269:            /*6+1+(i-1)+(nlstate+1)*nlstate; 6+1+(1-1) +(2+1)*2=13 */ 
                   7270:            /* ''  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*/
                   7271:            if(k==cptcoveff){
                   7272:              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], \
                   7273:                      2+cptcoveff*2+3*(cpt-1),  cpt );  /* 4 or 6 ?*/
                   7274:            }else{
                   7275:              fprintf(ficgp,"$%d==%d && $%d==%d && ",kl+1, Tvaraff[k],kl+1+1,nbcode[Tvaraff[k]][lv]);
                   7276:              kl++;
                   7277:            }
                   7278:          } /* end covariate */
                   7279:        } /* end if no covariate */
                   7280: 
1.296     brouard  7281:        if(prevbcast==1){ /* We need to get the corresponding values of the covariates involved in this combination k1 */
1.238     brouard  7282:          /* 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  7283:          fprintf(ficgp,",\"%s\" u 1:((",subdirf2(fileresu,"PLB_")); /* Age is in 1, nres in 2 to be fixed */
1.238     brouard  7284:          if(cptcoveff ==0){
1.245     brouard  7285:            fprintf(ficgp,"$%d)) t 'Backward prevalence in state %d' with line lt 3",    2+(cpt-1),  cpt );
1.238     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];
1.223     brouard  7294:              kl++;
1.238     brouard  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){
1.245     brouard  7300:                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  7301:                        2+cptcoveff*2+(cpt-1),  cpt );  /* 4 or 6 ?*/
1.238     brouard  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 */
1.296     brouard  7308:          if(prevbcast == 1){
1.268     brouard  7309:            fprintf(ficgp,", \"%s\" every :::%d::%d u 1:($2==%d ? $3:1/0) \"%%lf %%lf",subdirf2(fileresu,"VBL_"),nres-1,nres-1,nres);
                   7310:            /* k1-1 error should be nres-1*/
                   7311:            for (i=1; i<= nlstate ; i ++) {
                   7312:              if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
                   7313:              else        fprintf(ficgp," %%*lf (%%*lf)");
                   7314:            }
1.271     brouard  7315:            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  7316:            for (i=1; i<= nlstate ; i ++) {
                   7317:              if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
                   7318:              else fprintf(ficgp," %%*lf (%%*lf)");
                   7319:            } 
1.276     brouard  7320:            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  7321:            for (i=1; i<= nlstate ; i ++) {
                   7322:              if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
                   7323:              else fprintf(ficgp," %%*lf (%%*lf)");
                   7324:            } 
1.274     brouard  7325:            fprintf(ficgp,"\" t\"\" w l lt 4");
1.268     brouard  7326:          } /* end if backprojcast */
1.296     brouard  7327:        } /* end if prevbcast */
1.276     brouard  7328:        /* fprintf(ficgp,"\nset out ;unset label;\n"); */
                   7329:        fprintf(ficgp,"\nset out ;unset title;\n");
1.238     brouard  7330:       } /* nres */
1.201     brouard  7331:     } /* k1 */
                   7332:   } /* cpt */
1.235     brouard  7333: 
                   7334:   
1.126     brouard  7335:   /*2 eme*/
1.238     brouard  7336:   for (k1=1; k1<= m ; k1 ++){  
                   7337:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.253     brouard  7338:       if(m != 1 && TKresult[nres]!= k1)
1.238     brouard  7339:        continue;
                   7340:       fprintf(ficgp,"\n# 2nd: Total life expectancy with CI: 't' files ");
1.264     brouard  7341:       strcpy(gplotlabel,"(");
1.238     brouard  7342:       for (k=1; k<=cptcoveff; k++){    /* For each covariate and each value */
1.225     brouard  7343:        lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate number corresponding to k1 combination */
1.223     brouard  7344:        /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   7345:        /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   7346:        /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
                   7347:        vlv= nbcode[Tvaraff[k]][lv];
                   7348:        fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv);
1.264     brouard  7349:        sprintf(gplotlabel+strlen(gplotlabel)," V%d=%d ",Tvaraff[k],vlv);
1.211     brouard  7350:       }
1.237     brouard  7351:       /* for(k=1; k <= ncovds; k++){ */
1.236     brouard  7352:       for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
1.238     brouard  7353:        printf(" V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
1.236     brouard  7354:        fprintf(ficgp," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
1.264     brouard  7355:        sprintf(gplotlabel+strlen(gplotlabel)," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
1.238     brouard  7356:       }
1.264     brouard  7357:       strcpy(gplotlabel+strlen(gplotlabel),")");
1.211     brouard  7358:       fprintf(ficgp,"\n#\n");
1.223     brouard  7359:       if(invalidvarcomb[k1]){
                   7360:        fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   7361:        continue;
                   7362:       }
1.219     brouard  7363:                        
1.241     brouard  7364:       fprintf(ficgp,"\nset out \"%s_%d-%d.svg\" \n",subdirf2(optionfilefiname,"E_"),k1,nres);
1.238     brouard  7365:       for(vpopbased=0; vpopbased <= popbased; vpopbased++){ /* Done for vpopbased=0 and vpopbased=1 if popbased==1*/
1.264     brouard  7366:        fprintf(ficgp,"\nset label \"popbased %d %s\" at graph 0.98,0.5 center rotate font \"Helvetica,12\"\n",vpopbased,gplotlabel);
                   7367:        if(vpopbased==0){
1.238     brouard  7368:          fprintf(ficgp,"set ylabel \"Years\" \nset ter svg size 640, 480\nplot [%.f:%.f] ",ageminpar,fage);
1.264     brouard  7369:        }else
1.238     brouard  7370:          fprintf(ficgp,"\nreplot ");
                   7371:        for (i=1; i<= nlstate+1 ; i ++) {
                   7372:          k=2*i;
1.261     brouard  7373:          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  7374:          for (j=1; j<= nlstate+1 ; j ++) {
                   7375:            if (j==i) fprintf(ficgp," %%lf (%%lf)");
                   7376:            else fprintf(ficgp," %%*lf (%%*lf)");
                   7377:          }   
                   7378:          if (i== 1) fprintf(ficgp,"\" t\"TLE\" w l lt %d, \\\n",i);
                   7379:          else fprintf(ficgp,"\" t\"LE in state (%d)\" w l lt %d, \\\n",i-1,i+1);
1.261     brouard  7380:          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  7381:          for (j=1; j<= nlstate+1 ; j ++) {
                   7382:            if (j==i) fprintf(ficgp," %%lf (%%lf)");
                   7383:            else fprintf(ficgp," %%*lf (%%*lf)");
                   7384:          }   
                   7385:          fprintf(ficgp,"\" t\"\" w l lt 0,");
1.261     brouard  7386:          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  7387:          for (j=1; j<= nlstate+1 ; j ++) {
                   7388:            if (j==i) fprintf(ficgp," %%lf (%%lf)");
                   7389:            else fprintf(ficgp," %%*lf (%%*lf)");
                   7390:          }   
                   7391:          if (i== (nlstate+1)) fprintf(ficgp,"\" t\"\" w l lt 0");
                   7392:          else fprintf(ficgp,"\" t\"\" w l lt 0,\\\n");
                   7393:        } /* state */
                   7394:       } /* vpopbased */
1.264     brouard  7395:       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  7396:     } /* end nres */
                   7397:   } /* k1 end 2 eme*/
                   7398:        
                   7399:        
                   7400:   /*3eme*/
                   7401:   for (k1=1; k1<= m ; k1 ++){
                   7402:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.253     brouard  7403:       if(m != 1 && TKresult[nres]!= k1)
1.238     brouard  7404:        continue;
                   7405: 
                   7406:       for (cpt=1; cpt<= nlstate ; cpt ++) {
1.261     brouard  7407:        fprintf(ficgp,"\n\n# 3d: Life expectancy with EXP_ files:  combination=%d state=%d",k1, cpt);
1.264     brouard  7408:        strcpy(gplotlabel,"(");
1.238     brouard  7409:        for (k=1; k<=cptcoveff; k++){    /* For each covariate and each value */
                   7410:          lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate number corresponding to k1 combination */
                   7411:          /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   7412:          /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   7413:          /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
                   7414:          vlv= nbcode[Tvaraff[k]][lv];
                   7415:          fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv);
1.264     brouard  7416:          sprintf(gplotlabel+strlen(gplotlabel)," V%d=%d ",Tvaraff[k],vlv);
1.238     brouard  7417:        }
                   7418:        for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
                   7419:          fprintf(ficgp," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
1.264     brouard  7420:          sprintf(gplotlabel+strlen(gplotlabel)," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
1.238     brouard  7421:        }       
1.264     brouard  7422:        strcpy(gplotlabel+strlen(gplotlabel),")");
1.238     brouard  7423:        fprintf(ficgp,"\n#\n");
                   7424:        if(invalidvarcomb[k1]){
                   7425:          fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   7426:          continue;
                   7427:        }
                   7428:                        
                   7429:        /*       k=2+nlstate*(2*cpt-2); */
                   7430:        k=2+(nlstate+1)*(cpt-1);
1.241     brouard  7431:        fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" \n",subdirf2(optionfilefiname,"EXP_"),cpt,k1,nres);
1.264     brouard  7432:        fprintf(ficgp,"set label \"%s\" at graph 0.98,0.5 center rotate font \"Helvetica,12\"\n",gplotlabel);
1.238     brouard  7433:        fprintf(ficgp,"set ter svg size 640, 480\n\
1.261     brouard  7434: 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  7435:        /*fprintf(ficgp,",\"e%s\" every :::%d::%d u 1:($%d-2*$%d) \"\%%lf ",fileres,k1-1,k1-1,k,k+1);
                   7436:          for (i=1; i<= nlstate*2 ; i ++) fprintf(ficgp,"\%%lf (\%%lf) ");
                   7437:          fprintf(ficgp,"\" t \"e%d1\" w l",cpt);
                   7438:          fprintf(ficgp,",\"e%s\" every :::%d::%d u 1:($%d+2*$%d) \"\%%lf ",fileres,k1-1,k1-1,k,k+1);
                   7439:          for (i=1; i<= nlstate*2 ; i ++) fprintf(ficgp,"\%%lf (\%%lf) ");
                   7440:          fprintf(ficgp,"\" t \"e%d1\" w l",cpt);
1.219     brouard  7441:                                
1.238     brouard  7442:        */
                   7443:        for (i=1; i< nlstate ; i ++) {
1.261     brouard  7444:          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  7445:          /*    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  7446:                                
1.238     brouard  7447:        } 
1.261     brouard  7448:        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  7449:       }
1.264     brouard  7450:       fprintf(ficgp,"\nunset label;\n");
1.238     brouard  7451:     } /* end nres */
                   7452:   } /* end kl 3eme */
1.126     brouard  7453:   
1.223     brouard  7454:   /* 4eme */
1.201     brouard  7455:   /* Survival functions (period) from state i in state j by initial state i */
1.238     brouard  7456:   for (k1=1; k1<=m; k1++){    /* For each covariate and each value */
                   7457:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.253     brouard  7458:       if(m != 1 && TKresult[nres]!= k1)
1.223     brouard  7459:        continue;
1.238     brouard  7460:       for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each life state cpt*/
1.264     brouard  7461:        strcpy(gplotlabel,"(");
1.238     brouard  7462:        fprintf(ficgp,"\n#\n#\n# Survival functions in state j : 'LIJ_' files, cov=%d state=%d",k1, cpt);
                   7463:        for (k=1; k<=cptcoveff; k++){    /* For each covariate and each value */
                   7464:          lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate number corresponding to k1 combination */
                   7465:          /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   7466:          /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   7467:          /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
                   7468:          vlv= nbcode[Tvaraff[k]][lv];
                   7469:          fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv);
1.264     brouard  7470:          sprintf(gplotlabel+strlen(gplotlabel)," V%d=%d ",Tvaraff[k],vlv);
1.238     brouard  7471:        }
                   7472:        for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
                   7473:          fprintf(ficgp," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
1.264     brouard  7474:          sprintf(gplotlabel+strlen(gplotlabel)," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
1.238     brouard  7475:        }       
1.264     brouard  7476:        strcpy(gplotlabel+strlen(gplotlabel),")");
1.238     brouard  7477:        fprintf(ficgp,"\n#\n");
                   7478:        if(invalidvarcomb[k1]){
                   7479:          fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   7480:          continue;
1.223     brouard  7481:        }
1.238     brouard  7482:       
1.241     brouard  7483:        fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" \n",subdirf2(optionfilefiname,"LIJ_"),cpt,k1,nres);
1.264     brouard  7484:        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  7485:        fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Probability to be alive\" \n\
                   7486: set ter svg size 640, 480\nunset log y\nplot [%.f:%.f]  ", ageminpar, agemaxpar);
                   7487:        k=3;
                   7488:        for (i=1; i<= nlstate ; i ++){
                   7489:          if(i==1){
                   7490:            fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"PIJ_"));
                   7491:          }else{
                   7492:            fprintf(ficgp,", '' ");
                   7493:          }
                   7494:          l=(nlstate+ndeath)*(i-1)+1;
                   7495:          fprintf(ficgp," u ($1==%d ? ($3):1/0):($%d/($%d",k1,k+l+(cpt-1),k+l);
                   7496:          for (j=2; j<= nlstate+ndeath ; j ++)
                   7497:            fprintf(ficgp,"+$%d",k+l+j-1);
                   7498:          fprintf(ficgp,")) t \"l(%d,%d)\" w l",i,cpt);
                   7499:        } /* nlstate */
1.264     brouard  7500:        fprintf(ficgp,"\nset out; unset label;\n");
1.238     brouard  7501:       } /* end cpt state*/ 
                   7502:     } /* end nres */
                   7503:   } /* end covariate k1 */  
                   7504: 
1.220     brouard  7505: /* 5eme */
1.201     brouard  7506:   /* Survival functions (period) from state i in state j by final state j */
1.238     brouard  7507:   for (k1=1; k1<= m ; k1++){ /* For each covariate combination if any */
                   7508:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.253     brouard  7509:       if(m != 1 && TKresult[nres]!= k1)
1.227     brouard  7510:        continue;
1.238     brouard  7511:       for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each inital state  */
1.264     brouard  7512:        strcpy(gplotlabel,"(");
1.238     brouard  7513:        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);
                   7514:        for (k=1; k<=cptcoveff; k++){    /* For each covariate and each value */
                   7515:          lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate number corresponding to k1 combination */
                   7516:          /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   7517:          /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   7518:          /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
                   7519:          vlv= nbcode[Tvaraff[k]][lv];
                   7520:          fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv);
1.264     brouard  7521:          sprintf(gplotlabel+strlen(gplotlabel)," V%d=%d ",Tvaraff[k],vlv);
1.238     brouard  7522:        }
                   7523:        for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
                   7524:          fprintf(ficgp," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
1.264     brouard  7525:          sprintf(gplotlabel+strlen(gplotlabel)," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
1.238     brouard  7526:        }       
1.264     brouard  7527:        strcpy(gplotlabel+strlen(gplotlabel),")");
1.238     brouard  7528:        fprintf(ficgp,"\n#\n");
                   7529:        if(invalidvarcomb[k1]){
                   7530:          fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   7531:          continue;
                   7532:        }
1.227     brouard  7533:       
1.241     brouard  7534:        fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" \n",subdirf2(optionfilefiname,"LIJT_"),cpt,k1,nres);
1.264     brouard  7535:        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  7536:        fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Probability to be alive\" \n\
                   7537: set ter svg size 640, 480\nunset log y\nplot [%.f:%.f]  ", ageminpar, agemaxpar);
                   7538:        k=3;
                   7539:        for (j=1; j<= nlstate ; j ++){ /* Lived in state j */
                   7540:          if(j==1)
                   7541:            fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"PIJ_"));
                   7542:          else
                   7543:            fprintf(ficgp,", '' ");
                   7544:          l=(nlstate+ndeath)*(cpt-1) +j;
                   7545:          fprintf(ficgp," u (($1==%d && (floor($2)%%5 == 0)) ? ($3):1/0):($%d",k1,k+l);
                   7546:          /* for (i=2; i<= nlstate+ndeath ; i ++) */
                   7547:          /*   fprintf(ficgp,"+$%d",k+l+i-1); */
                   7548:          fprintf(ficgp,") t \"l(%d,%d)\" w l",cpt,j);
                   7549:        } /* nlstate */
                   7550:        fprintf(ficgp,", '' ");
                   7551:        fprintf(ficgp," u (($1==%d && (floor($2)%%5 == 0)) ? ($3):1/0):(",k1);
                   7552:        for (j=1; j<= nlstate ; j ++){ /* Lived in state j */
                   7553:          l=(nlstate+ndeath)*(cpt-1) +j;
                   7554:          if(j < nlstate)
                   7555:            fprintf(ficgp,"$%d +",k+l);
                   7556:          else
                   7557:            fprintf(ficgp,"$%d) t\"l(%d,.)\" w l",k+l,cpt);
                   7558:        }
1.264     brouard  7559:        fprintf(ficgp,"\nset out; unset label;\n");
1.238     brouard  7560:       } /* end cpt state*/ 
                   7561:     } /* end covariate */  
                   7562:   } /* end nres */
1.227     brouard  7563:   
1.220     brouard  7564: /* 6eme */
1.202     brouard  7565:   /* CV preval stable (period) for each covariate */
1.237     brouard  7566:   for (k1=1; k1<= m ; k1 ++) /* For each covariate combination if any */
                   7567:   for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.253     brouard  7568:     if(m != 1 && TKresult[nres]!= k1)
1.237     brouard  7569:       continue;
1.255     brouard  7570:     for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each life state of arrival */
1.264     brouard  7571:       strcpy(gplotlabel,"(");      
1.288     brouard  7572:       fprintf(ficgp,"\n#\n#\n#CV preval stable (forward): 'pij' files, covariatecombination#=%d state=%d",k1, cpt);
1.225     brouard  7573:       for (k=1; k<=cptcoveff; k++){    /* For each covariate and each value */
1.227     brouard  7574:        lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate number corresponding to k1 combination */
                   7575:        /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   7576:        /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   7577:        /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
                   7578:        vlv= nbcode[Tvaraff[k]][lv];
                   7579:        fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv);
1.264     brouard  7580:        sprintf(gplotlabel+strlen(gplotlabel)," V%d=%d ",Tvaraff[k],vlv);
1.211     brouard  7581:       }
1.237     brouard  7582:       for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
                   7583:        fprintf(ficgp," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
1.264     brouard  7584:        sprintf(gplotlabel+strlen(gplotlabel)," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
1.237     brouard  7585:       }        
1.264     brouard  7586:       strcpy(gplotlabel+strlen(gplotlabel),")");
1.211     brouard  7587:       fprintf(ficgp,"\n#\n");
1.223     brouard  7588:       if(invalidvarcomb[k1]){
1.227     brouard  7589:        fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   7590:        continue;
1.223     brouard  7591:       }
1.227     brouard  7592:       
1.241     brouard  7593:       fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" \n",subdirf2(optionfilefiname,"P_"),cpt,k1,nres);
1.264     brouard  7594:       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  7595:       fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Probability\" \n\
1.238     brouard  7596: set ter svg size 640, 480\nunset log y\nplot [%.f:%.f]  ", ageminpar, agemaxpar);
1.211     brouard  7597:       k=3; /* Offset */
1.255     brouard  7598:       for (i=1; i<= nlstate ; i ++){ /* State of origin */
1.227     brouard  7599:        if(i==1)
                   7600:          fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"PIJ_"));
                   7601:        else
                   7602:          fprintf(ficgp,", '' ");
1.255     brouard  7603:        l=(nlstate+ndeath)*(i-1)+1; /* 1, 1+ nlstate+ndeath, 1+2*(nlstate+ndeath) */
1.227     brouard  7604:        fprintf(ficgp," u ($1==%d ? ($3):1/0):($%d/($%d",k1,k+l+(cpt-1),k+l);
                   7605:        for (j=2; j<= nlstate ; j ++)
                   7606:          fprintf(ficgp,"+$%d",k+l+j-1);
                   7607:        fprintf(ficgp,")) t \"prev(%d,%d)\" w l",i,cpt);
1.153     brouard  7608:       } /* nlstate */
1.264     brouard  7609:       fprintf(ficgp,"\nset out; unset label;\n");
1.153     brouard  7610:     } /* end cpt state*/ 
                   7611:   } /* end covariate */  
1.227     brouard  7612:   
                   7613:   
1.220     brouard  7614: /* 7eme */
1.296     brouard  7615:   if(prevbcast == 1){
1.288     brouard  7616:     /* CV backward prevalence  for each covariate */
1.237     brouard  7617:     for (k1=1; k1<= m ; k1 ++) /* For each covariate combination if any */
                   7618:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.253     brouard  7619:       if(m != 1 && TKresult[nres]!= k1)
1.237     brouard  7620:        continue;
1.268     brouard  7621:       for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each life origin state */
1.264     brouard  7622:        strcpy(gplotlabel,"(");      
1.288     brouard  7623:        fprintf(ficgp,"\n#\n#\n#CV Backward stable prevalence: 'pijb' files, covariatecombination#=%d state=%d",k1, cpt);
1.227     brouard  7624:        for (k=1; k<=cptcoveff; k++){    /* For each covariate and each value */
                   7625:          lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate number corresponding to k1 combination */
                   7626:          /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   7627:          /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
1.223     brouard  7628:          /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
1.227     brouard  7629:          vlv= nbcode[Tvaraff[k]][lv];
                   7630:          fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv);
1.264     brouard  7631:          sprintf(gplotlabel+strlen(gplotlabel)," V%d=%d ",Tvaraff[k],vlv);
1.227     brouard  7632:        }
1.237     brouard  7633:        for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
                   7634:          fprintf(ficgp," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
1.264     brouard  7635:          sprintf(gplotlabel+strlen(gplotlabel)," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
1.237     brouard  7636:        }       
1.264     brouard  7637:        strcpy(gplotlabel+strlen(gplotlabel),")");
1.227     brouard  7638:        fprintf(ficgp,"\n#\n");
                   7639:        if(invalidvarcomb[k1]){
                   7640:          fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   7641:          continue;
                   7642:        }
                   7643:        
1.241     brouard  7644:        fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" \n",subdirf2(optionfilefiname,"PB_"),cpt,k1,nres);
1.268     brouard  7645:        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  7646:        fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Probability\" \n\
1.238     brouard  7647: set ter svg size 640, 480\nunset log y\nplot [%.f:%.f]  ", ageminpar, agemaxpar);
1.227     brouard  7648:        k=3; /* Offset */
1.268     brouard  7649:        for (i=1; i<= nlstate ; i ++){ /* State of arrival */
1.227     brouard  7650:          if(i==1)
                   7651:            fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"PIJB_"));
                   7652:          else
                   7653:            fprintf(ficgp,", '' ");
                   7654:          /* l=(nlstate+ndeath)*(i-1)+1; */
1.255     brouard  7655:          l=(nlstate+ndeath)*(cpt-1)+1; /* fixed for i; cpt=1 1, cpt=2 1+ nlstate+ndeath, 1+2*(nlstate+ndeath) */
1.227     brouard  7656:          /* fprintf(ficgp," u ($1==%d ? ($3):1/0):($%d/($%d",k1,k+l+(cpt-1),k+l); /\* a vérifier *\/ */
                   7657:          /* 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  7658:          fprintf(ficgp," u ($1==%d ? ($3):1/0):($%d",k1,k+l+i-1); /* To be verified */
1.227     brouard  7659:          /* for (j=2; j<= nlstate ; j ++) */
                   7660:          /*    fprintf(ficgp,"+$%d",k+l+j-1); */
                   7661:          /*    /\* fprintf(ficgp,"+$%d",k+l+j-1); *\/ */
1.268     brouard  7662:          fprintf(ficgp,") t \"bprev(%d,%d)\" w l",cpt,i);
1.227     brouard  7663:        } /* nlstate */
1.264     brouard  7664:        fprintf(ficgp,"\nset out; unset label;\n");
1.218     brouard  7665:       } /* end cpt state*/ 
                   7666:     } /* end covariate */  
1.296     brouard  7667:   } /* End if prevbcast */
1.218     brouard  7668:   
1.223     brouard  7669:   /* 8eme */
1.218     brouard  7670:   if(prevfcast==1){
1.288     brouard  7671:     /* Projection from cross-sectional to forward stable (period) prevalence for each covariate */
1.218     brouard  7672:     
1.237     brouard  7673:     for (k1=1; k1<= m ; k1 ++) /* For each covariate combination if any */
                   7674:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.253     brouard  7675:       if(m != 1 && TKresult[nres]!= k1)
1.237     brouard  7676:        continue;
1.211     brouard  7677:       for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each life state */
1.264     brouard  7678:        strcpy(gplotlabel,"(");      
1.288     brouard  7679:        fprintf(ficgp,"\n#\n#\n#Projection of prevalence to forward stable prevalence (period): 'PROJ_' files, covariatecombination#=%d state=%d",k1, cpt);
1.227     brouard  7680:        for (k=1; k<=cptcoveff; k++){    /* For each correspondig covariate value  */
                   7681:          lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate value corresponding to k1 combination and kth covariate */
                   7682:          /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   7683:          /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   7684:          /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
                   7685:          vlv= nbcode[Tvaraff[k]][lv];
                   7686:          fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv);
1.264     brouard  7687:          sprintf(gplotlabel+strlen(gplotlabel)," V%d=%d ",Tvaraff[k],vlv);
1.227     brouard  7688:        }
1.237     brouard  7689:        for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
                   7690:          fprintf(ficgp," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
1.264     brouard  7691:          sprintf(gplotlabel+strlen(gplotlabel)," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
1.237     brouard  7692:        }       
1.264     brouard  7693:        strcpy(gplotlabel+strlen(gplotlabel),")");
1.227     brouard  7694:        fprintf(ficgp,"\n#\n");
                   7695:        if(invalidvarcomb[k1]){
                   7696:          fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   7697:          continue;
                   7698:        }
                   7699:        
                   7700:        fprintf(ficgp,"# hpijx=probability over h years, hp.jx is weighted by observed prev\n ");
1.241     brouard  7701:        fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" \n",subdirf2(optionfilefiname,"PROJ_"),cpt,k1,nres);
1.264     brouard  7702:        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  7703:        fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Prevalence\" \n\
1.238     brouard  7704: set ter svg size 640, 480\nunset log y\nplot [%.f:%.f]  ", ageminpar, agemaxpar);
1.266     brouard  7705: 
                   7706:        /* for (i=1; i<= nlstate+1 ; i ++){  /\* nlstate +1 p11 p21 p.1 *\/ */
                   7707:        istart=nlstate+1; /* Could be one if by state, but nlstate+1 is w.i projection only */
                   7708:        /*istart=1;*/ /* Could be one if by state, but nlstate+1 is w.i projection only */
                   7709:        for (i=istart; i<= nlstate+1 ; i ++){  /* nlstate +1 p11 p21 p.1 */
1.227     brouard  7710:          /*#  V1  = 1  V2 =  0 yearproj age p11 p21 p.1 p12 p22 p.2 p13 p23 p.3*/
                   7711:          /*#   1    2   3    4    5      6  7   8   9   10   11 12  13   14  15 */   
                   7712:          /*# yearproj age p11 p21 p.1 p12 p22 p.2 p13 p23 p.3*/
                   7713:          /*#   1       2   3    4    5      6  7   8   9   10   11 12  13   14  15 */   
1.266     brouard  7714:          if(i==istart){
1.227     brouard  7715:            fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"F_"));
                   7716:          }else{
                   7717:            fprintf(ficgp,",\\\n '' ");
                   7718:          }
                   7719:          if(cptcoveff ==0){ /* No covariate */
                   7720:            ioffset=2; /* Age is in 2 */
                   7721:            /*# yearproj age p11 p21 p31 p.1 p12 p22 p32 p.2 p13 p23 p33 p.3 p14 p24 p34 p.4*/
                   7722:            /*#   1       2   3   4   5  6    7  8   9   10  11  12  13  14  15  16  17  18 */
                   7723:            /*# V1  = 1 yearproj age p11 p21 p31 p.1 p12 p22 p32 p.2 p13 p23 p33 p.3 p14 p24 p34 p.4*/
                   7724:            /*#  1    2        3   4   5  6    7  8   9   10  11  12  13  14  15  16  17  18 */
                   7725:            fprintf(ficgp," u %d:(", ioffset); 
1.266     brouard  7726:            if(i==nlstate+1){
1.270     brouard  7727:              fprintf(ficgp," $%d/(1.-$%d)):1 t 'pw.%d' with line lc variable ",        \
1.266     brouard  7728:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1),  ioffset+1+(i-1)+(nlstate+1)*nlstate,cpt );
                   7729:              fprintf(ficgp,",\\\n '' ");
                   7730:              fprintf(ficgp," u %d:(",ioffset); 
1.270     brouard  7731:              fprintf(ficgp," (($1-$2) == %d ) ? $%d/(1.-$%d) : 1/0):1 with labels center not ", \
1.266     brouard  7732:                     offyear,                           \
1.268     brouard  7733:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1),  ioffset+1+(i-1)+(nlstate+1)*nlstate );
1.266     brouard  7734:            }else
1.227     brouard  7735:              fprintf(ficgp," $%d/(1.-$%d)) t 'p%d%d' with line ",      \
                   7736:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1),  ioffset+1+(i-1)+(nlstate+1)*nlstate,i,cpt );
                   7737:          }else{ /* more than 2 covariates */
1.270     brouard  7738:            ioffset=2*cptcoveff+2; /* Age is in 4 or 6 or etc.*/
                   7739:            /*#  V1  = 1  V2 =  0 yearproj age p11 p21 p.1 p12 p22 p.2 p13 p23 p.3*/
                   7740:            /*#   1    2   3    4    5      6  7   8   9   10   11 12  13   14  15 */
                   7741:            iyearc=ioffset-1;
                   7742:            iagec=ioffset;
1.227     brouard  7743:            fprintf(ficgp," u %d:(",ioffset); 
                   7744:            kl=0;
                   7745:            strcpy(gplotcondition,"(");
                   7746:            for (k=1; k<=cptcoveff; k++){    /* For each covariate writing the chain of conditions */
                   7747:              lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate value corresponding to combination k1 and covariate k */
                   7748:              /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   7749:              /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   7750:              /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
                   7751:              vlv= nbcode[Tvaraff[k]][lv]; /* Value of the modality of Tvaraff[k] */
                   7752:              kl++;
                   7753:              sprintf(gplotcondition+strlen(gplotcondition),"$%d==%d && $%d==%d " ,kl,Tvaraff[k], kl+1, nbcode[Tvaraff[k]][lv]);
                   7754:              kl++;
                   7755:              if(k <cptcoveff && cptcoveff>1)
                   7756:                sprintf(gplotcondition+strlen(gplotcondition)," && ");
                   7757:            }
                   7758:            strcpy(gplotcondition+strlen(gplotcondition),")");
                   7759:            /* 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 *\/ */
                   7760:            /*6+(cpt-1)*(nlstate+1)+1+(i-1)+(nlstate+1)*nlstate; 6+(1-1)*(2+1)+1+(1-1) +(2+1)*2=13 */ 
                   7761:            /*6+1+(i-1)+(nlstate+1)*nlstate; 6+1+(1-1) +(2+1)*2=13 */ 
                   7762:            /* ''  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*/
                   7763:            if(i==nlstate+1){
1.270     brouard  7764:              fprintf(ficgp,"%s ? $%d/(1.-$%d) : 1/0):%d t 'p.%d' with line lc variable", gplotcondition, \
                   7765:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1),  ioffset+1+(i-1)+(nlstate+1)*nlstate,iyearc, cpt );
1.266     brouard  7766:              fprintf(ficgp,",\\\n '' ");
1.270     brouard  7767:              fprintf(ficgp," u %d:(",iagec); 
                   7768:              fprintf(ficgp,"%s && (($%d-$%d) == %d ) ? $%d/(1.-$%d) : 1/0):%d with labels center not ", gplotcondition, \
                   7769:                      iyearc, iagec, offyear,                           \
                   7770:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1),  ioffset+1+(i-1)+(nlstate+1)*nlstate, iyearc );
1.266     brouard  7771: /*  '' 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  7772:            }else{
                   7773:              fprintf(ficgp,"%s ? $%d/(1.-$%d) : 1/0) t 'p%d%d' with line ", gplotcondition, \
                   7774:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1), ioffset +1+(i-1)+(nlstate+1)*nlstate,i,cpt );
                   7775:            }
                   7776:          } /* end if covariate */
                   7777:        } /* nlstate */
1.264     brouard  7778:        fprintf(ficgp,"\nset out; unset label;\n");
1.223     brouard  7779:       } /* end cpt state*/
                   7780:     } /* end covariate */
                   7781:   } /* End if prevfcast */
1.227     brouard  7782:   
1.296     brouard  7783:   if(prevbcast==1){
1.268     brouard  7784:     /* Back projection from cross-sectional to stable (mixed) for each covariate */
                   7785:     
                   7786:     for (k1=1; k1<= m ; k1 ++) /* For each covariate combination if any */
                   7787:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
                   7788:       if(m != 1 && TKresult[nres]!= k1)
                   7789:        continue;
                   7790:       for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each life state */
                   7791:        strcpy(gplotlabel,"(");      
                   7792:        fprintf(ficgp,"\n#\n#\n#Back projection of prevalence to stable (mixed) back prevalence: 'BPROJ_' files, covariatecombination#=%d originstate=%d",k1, cpt);
                   7793:        for (k=1; k<=cptcoveff; k++){    /* For each correspondig covariate value  */
                   7794:          lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate value corresponding to k1 combination and kth covariate */
                   7795:          /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   7796:          /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   7797:          /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
                   7798:          vlv= nbcode[Tvaraff[k]][lv];
                   7799:          fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv);
                   7800:          sprintf(gplotlabel+strlen(gplotlabel)," V%d=%d ",Tvaraff[k],vlv);
                   7801:        }
                   7802:        for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
                   7803:          fprintf(ficgp," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
                   7804:          sprintf(gplotlabel+strlen(gplotlabel)," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
                   7805:        }       
                   7806:        strcpy(gplotlabel+strlen(gplotlabel),")");
                   7807:        fprintf(ficgp,"\n#\n");
                   7808:        if(invalidvarcomb[k1]){
                   7809:          fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   7810:          continue;
                   7811:        }
                   7812:        
                   7813:        fprintf(ficgp,"# hbijx=backprobability over h years, hb.jx is weighted by observed prev at destination state\n ");
                   7814:        fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" \n",subdirf2(optionfilefiname,"PROJB_"),cpt,k1,nres);
                   7815:        fprintf(ficgp,"set label \"Origin alive state %d %s\" at graph 0.98,0.5 center rotate font \"Helvetica,12\"\n",cpt,gplotlabel);
                   7816:        fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Prevalence\" \n\
                   7817: set ter svg size 640, 480\nunset log y\nplot [%.f:%.f]  ", ageminpar, agemaxpar);
                   7818: 
                   7819:        /* for (i=1; i<= nlstate+1 ; i ++){  /\* nlstate +1 p11 p21 p.1 *\/ */
                   7820:        istart=nlstate+1; /* Could be one if by state, but nlstate+1 is w.i projection only */
                   7821:        /*istart=1;*/ /* Could be one if by state, but nlstate+1 is w.i projection only */
                   7822:        for (i=istart; i<= nlstate+1 ; i ++){  /* nlstate +1 p11 p21 p.1 */
                   7823:          /*#  V1  = 1  V2 =  0 yearproj age p11 p21 p.1 p12 p22 p.2 p13 p23 p.3*/
                   7824:          /*#   1    2   3    4    5      6  7   8   9   10   11 12  13   14  15 */   
                   7825:          /*# yearproj age p11 p21 p.1 p12 p22 p.2 p13 p23 p.3*/
                   7826:          /*#   1       2   3    4    5      6  7   8   9   10   11 12  13   14  15 */   
                   7827:          if(i==istart){
                   7828:            fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"FB_"));
                   7829:          }else{
                   7830:            fprintf(ficgp,",\\\n '' ");
                   7831:          }
                   7832:          if(cptcoveff ==0){ /* No covariate */
                   7833:            ioffset=2; /* Age is in 2 */
                   7834:            /*# yearproj age p11 p21 p31 p.1 p12 p22 p32 p.2 p13 p23 p33 p.3 p14 p24 p34 p.4*/
                   7835:            /*#   1       2   3   4   5  6    7  8   9   10  11  12  13  14  15  16  17  18 */
                   7836:            /*# V1  = 1 yearproj age p11 p21 p31 p.1 p12 p22 p32 p.2 p13 p23 p33 p.3 p14 p24 p34 p.4*/
                   7837:            /*#  1    2        3   4   5  6    7  8   9   10  11  12  13  14  15  16  17  18 */
                   7838:            fprintf(ficgp," u %d:(", ioffset); 
                   7839:            if(i==nlstate+1){
1.270     brouard  7840:              fprintf(ficgp," $%d/(1.-$%d)):1 t 'bw%d' with line lc variable ", \
1.268     brouard  7841:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1),  ioffset+1+(i-1)+(nlstate+1)*nlstate,cpt );
                   7842:              fprintf(ficgp,",\\\n '' ");
                   7843:              fprintf(ficgp," u %d:(",ioffset); 
1.270     brouard  7844:              fprintf(ficgp," (($1-$2) == %d ) ? $%d : 1/0):1 with labels center not ", \
1.268     brouard  7845:                     offbyear,                          \
                   7846:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1) );
                   7847:            }else
                   7848:              fprintf(ficgp," $%d/(1.-$%d)) t 'b%d%d' with line ",      \
                   7849:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1),  ioffset+1+(i-1)+(nlstate+1)*nlstate,cpt,i );
                   7850:          }else{ /* more than 2 covariates */
1.270     brouard  7851:            ioffset=2*cptcoveff+2; /* Age is in 4 or 6 or etc.*/
                   7852:            /*#  V1  = 1  V2 =  0 yearproj age p11 p21 p.1 p12 p22 p.2 p13 p23 p.3*/
                   7853:            /*#   1    2   3    4    5      6  7   8   9   10   11 12  13   14  15 */
                   7854:            iyearc=ioffset-1;
                   7855:            iagec=ioffset;
1.268     brouard  7856:            fprintf(ficgp," u %d:(",ioffset); 
                   7857:            kl=0;
                   7858:            strcpy(gplotcondition,"(");
                   7859:            for (k=1; k<=cptcoveff; k++){    /* For each covariate writing the chain of conditions */
                   7860:              lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate value corresponding to combination k1 and covariate k */
                   7861:              /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   7862:              /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   7863:              /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
                   7864:              vlv= nbcode[Tvaraff[k]][lv]; /* Value of the modality of Tvaraff[k] */
                   7865:              kl++;
                   7866:              sprintf(gplotcondition+strlen(gplotcondition),"$%d==%d && $%d==%d " ,kl,Tvaraff[k], kl+1, nbcode[Tvaraff[k]][lv]);
                   7867:              kl++;
                   7868:              if(k <cptcoveff && cptcoveff>1)
                   7869:                sprintf(gplotcondition+strlen(gplotcondition)," && ");
                   7870:            }
                   7871:            strcpy(gplotcondition+strlen(gplotcondition),")");
                   7872:            /* 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 *\/ */
                   7873:            /*6+(cpt-1)*(nlstate+1)+1+(i-1)+(nlstate+1)*nlstate; 6+(1-1)*(2+1)+1+(1-1) +(2+1)*2=13 */ 
                   7874:            /*6+1+(i-1)+(nlstate+1)*nlstate; 6+1+(1-1) +(2+1)*2=13 */ 
                   7875:            /* ''  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*/
                   7876:            if(i==nlstate+1){
1.270     brouard  7877:              fprintf(ficgp,"%s ? $%d : 1/0):%d t 'bw%d' with line lc variable", gplotcondition, \
                   7878:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1),iyearc,cpt );
1.268     brouard  7879:              fprintf(ficgp,",\\\n '' ");
1.270     brouard  7880:              fprintf(ficgp," u %d:(",iagec); 
1.268     brouard  7881:              /* fprintf(ficgp,"%s && (($5-$6) == %d ) ? $%d/(1.-$%d) : 1/0):5 with labels center not ", gplotcondition, \ */
1.270     brouard  7882:              fprintf(ficgp,"%s && (($%d-$%d) == %d ) ? $%d : 1/0):%d with labels center not ", gplotcondition, \
                   7883:                      iyearc,iagec,offbyear,                            \
                   7884:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1), iyearc );
1.268     brouard  7885: /*  '' u 6:(($1==1 && $2==0  && $3==2 && $4==0) && (($5-$6) == 1947) ? $10/(1.-$22) : 1/0):5 with labels center boxed not*/
                   7886:            }else{
                   7887:              /* fprintf(ficgp,"%s ? $%d/(1.-$%d) : 1/0) t 'p%d%d' with line ", gplotcondition, \ */
                   7888:              fprintf(ficgp,"%s ? $%d : 1/0) t 'b%d%d' with line ", gplotcondition, \
                   7889:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1), cpt,i );
                   7890:            }
                   7891:          } /* end if covariate */
                   7892:        } /* nlstate */
                   7893:        fprintf(ficgp,"\nset out; unset label;\n");
                   7894:       } /* end cpt state*/
                   7895:     } /* end covariate */
1.296     brouard  7896:   } /* End if prevbcast */
1.268     brouard  7897:   
1.227     brouard  7898:   
1.238     brouard  7899:   /* 9eme writing MLE parameters */
                   7900:   fprintf(ficgp,"\n##############\n#9eme MLE estimated parameters\n#############\n");
1.126     brouard  7901:   for(i=1,jk=1; i <=nlstate; i++){
1.187     brouard  7902:     fprintf(ficgp,"# initial state %d\n",i);
1.126     brouard  7903:     for(k=1; k <=(nlstate+ndeath); k++){
                   7904:       if (k != i) {
1.227     brouard  7905:        fprintf(ficgp,"#   current state %d\n",k);
                   7906:        for(j=1; j <=ncovmodel; j++){
                   7907:          fprintf(ficgp,"p%d=%f; ",jk,p[jk]);
                   7908:          jk++; 
                   7909:        }
                   7910:        fprintf(ficgp,"\n");
1.126     brouard  7911:       }
                   7912:     }
1.223     brouard  7913:   }
1.187     brouard  7914:   fprintf(ficgp,"##############\n#\n");
1.227     brouard  7915:   
1.145     brouard  7916:   /*goto avoid;*/
1.238     brouard  7917:   /* 10eme Graphics of probabilities or incidences using written MLE parameters */
                   7918:   fprintf(ficgp,"\n##############\n#10eme Graphics of probabilities or incidences\n#############\n");
1.187     brouard  7919:   fprintf(ficgp,"# logi(p12/p11)=a12+b12*age+c12age*age+d12*V1+e12*V1*age\n");
                   7920:   fprintf(ficgp,"# logi(p12/p11)=p1 +p2*age +p3*age*age+ p4*V1+ p5*V1*age\n");
                   7921:   fprintf(ficgp,"# logi(p13/p11)=a13+b13*age+c13age*age+d13*V1+e13*V1*age\n");
                   7922:   fprintf(ficgp,"# logi(p13/p11)=p6 +p7*age +p8*age*age+ p9*V1+ p10*V1*age\n");
                   7923:   fprintf(ficgp,"# p12+p13+p14+p11=1=p11(1+exp(a12+b12*age+c12age*age+d12*V1+e12*V1*age)\n");
                   7924:   fprintf(ficgp,"#                      +exp(a13+b13*age+c13age*age+d13*V1+e13*V1*age)+...)\n");
                   7925:   fprintf(ficgp,"# p11=1/(1+exp(a12+b12*age+c12age*age+d12*V1+e12*V1*age)\n");
                   7926:   fprintf(ficgp,"#                      +exp(a13+b13*age+c13age*age+d13*V1+e13*V1*age)+...)\n");
                   7927:   fprintf(ficgp,"# p12=exp(a12+b12*age+c12age*age+d12*V1+e12*V1*age)/\n");
                   7928:   fprintf(ficgp,"#     (1+exp(a12+b12*age+c12age*age+d12*V1+e12*V1*age)\n");
                   7929:   fprintf(ficgp,"#       +exp(a13+b13*age+c13age*age+d13*V1+e13*V1*age))\n");
                   7930:   fprintf(ficgp,"#       +exp(a14+b14*age+c14age*age+d14*V1+e14*V1*age)+...)\n");
                   7931:   fprintf(ficgp,"#\n");
1.223     brouard  7932:   for(ng=1; ng<=3;ng++){ /* Number of graphics: first is logit, 2nd is probabilities, third is incidences per year*/
1.238     brouard  7933:     fprintf(ficgp,"#Number of graphics: first is logit, 2nd is probabilities, third is incidences per year\n");
1.237     brouard  7934:     fprintf(ficgp,"#model=%s \n",model);
1.238     brouard  7935:     fprintf(ficgp,"# Type of graphic ng=%d\n",ng);
1.264     brouard  7936:     fprintf(ficgp,"#   k1=1 to 2^%d=%d\n",cptcoveff,m);/* to be checked */
                   7937:     for(k1=1; k1 <=m; k1++)  /* For each combination of covariate */
1.237     brouard  7938:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.264     brouard  7939:       if(m != 1 && TKresult[nres]!= k1)
1.237     brouard  7940:        continue;
1.264     brouard  7941:       fprintf(ficgp,"\n\n# Combination of dummy  k1=%d which is ",k1);
                   7942:       strcpy(gplotlabel,"(");
1.276     brouard  7943:       /*sprintf(gplotlabel+strlen(gplotlabel)," Dummy combination %d ",k1);*/
1.264     brouard  7944:       for (k=1; k<=cptcoveff; k++){    /* For each correspondig covariate value  */
                   7945:        lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate value corresponding to k1 combination and kth covariate */
                   7946:        /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   7947:        /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   7948:        /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
                   7949:        vlv= nbcode[Tvaraff[k]][lv];
                   7950:        fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv);
                   7951:        sprintf(gplotlabel+strlen(gplotlabel)," V%d=%d ",Tvaraff[k],vlv);
                   7952:       }
1.237     brouard  7953:       for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
                   7954:        fprintf(ficgp," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
1.264     brouard  7955:        sprintf(gplotlabel+strlen(gplotlabel)," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
1.237     brouard  7956:       }        
1.264     brouard  7957:       strcpy(gplotlabel+strlen(gplotlabel),")");
1.237     brouard  7958:       fprintf(ficgp,"\n#\n");
1.264     brouard  7959:       fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" ",subdirf2(optionfilefiname,"PE_"),k1,ng,nres);
1.276     brouard  7960:       fprintf(ficgp,"\nset key outside ");
                   7961:       /* fprintf(ficgp,"\nset label \"%s\" at graph 1.2,0.5 center rotate font \"Helvetica,12\"\n",gplotlabel); */
                   7962:       fprintf(ficgp,"\nset title \"%s\" font \"Helvetica,12\"\n",gplotlabel);
1.223     brouard  7963:       fprintf(ficgp,"\nset ter svg size 640, 480 ");
                   7964:       if (ng==1){
                   7965:        fprintf(ficgp,"\nset ylabel \"Value of the logit of the model\"\n"); /* exp(a12+b12*x) could be nice */
                   7966:        fprintf(ficgp,"\nunset log y");
                   7967:       }else if (ng==2){
                   7968:        fprintf(ficgp,"\nset ylabel \"Probability\"\n");
                   7969:        fprintf(ficgp,"\nset log y");
                   7970:       }else if (ng==3){
                   7971:        fprintf(ficgp,"\nset ylabel \"Quasi-incidence per year\"\n");
                   7972:        fprintf(ficgp,"\nset log y");
                   7973:       }else
                   7974:        fprintf(ficgp,"\nunset title ");
                   7975:       fprintf(ficgp,"\nplot  [%.f:%.f] ",ageminpar,agemaxpar);
                   7976:       i=1;
                   7977:       for(k2=1; k2<=nlstate; k2++) {
                   7978:        k3=i;
                   7979:        for(k=1; k<=(nlstate+ndeath); k++) {
                   7980:          if (k != k2){
                   7981:            switch( ng) {
                   7982:            case 1:
                   7983:              if(nagesqr==0)
                   7984:                fprintf(ficgp," p%d+p%d*x",i,i+1);
                   7985:              else /* nagesqr =1 */
                   7986:                fprintf(ficgp," p%d+p%d*x+p%d*x*x",i,i+1,i+1+nagesqr);
                   7987:              break;
                   7988:            case 2: /* ng=2 */
                   7989:              if(nagesqr==0)
                   7990:                fprintf(ficgp," exp(p%d+p%d*x",i,i+1);
                   7991:              else /* nagesqr =1 */
                   7992:                fprintf(ficgp," exp(p%d+p%d*x+p%d*x*x",i,i+1,i+1+nagesqr);
                   7993:              break;
                   7994:            case 3:
                   7995:              if(nagesqr==0)
                   7996:                fprintf(ficgp," %f*exp(p%d+p%d*x",YEARM/stepm,i,i+1);
                   7997:              else /* nagesqr =1 */
                   7998:                fprintf(ficgp," %f*exp(p%d+p%d*x+p%d*x*x",YEARM/stepm,i,i+1,i+1+nagesqr);
                   7999:              break;
                   8000:            }
                   8001:            ij=1;/* To be checked else nbcode[0][0] wrong */
1.237     brouard  8002:            ijp=1; /* product no age */
                   8003:            /* for(j=3; j <=ncovmodel-nagesqr; j++) { */
                   8004:            for(j=1; j <=cptcovt; j++) { /* For each covariate of the simplified model */
1.223     brouard  8005:              /* printf("Tage[%d]=%d, j=%d\n", ij, Tage[ij], j); */
1.268     brouard  8006:              if(cptcovage >0){ /* V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1, 2 V5 and V1 */
                   8007:                if(j==Tage[ij]) { /* Product by age  To be looked at!!*/
                   8008:                  if(ij <=cptcovage) { /* V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1, 2 V5 and V1 */
                   8009:                    if(DummyV[j]==0){
                   8010:                      fprintf(ficgp,"+p%d*%d*x",i+j+2+nagesqr-1,Tinvresult[nres][Tvar[j]]);;
                   8011:                    }else{ /* quantitative */
                   8012:                      fprintf(ficgp,"+p%d*%f*x",i+j+2+nagesqr-1,Tqinvresult[nres][Tvar[j]]); /* Tqinvresult in decoderesult */
                   8013:                      /* fprintf(ficgp,"+p%d*%d*x",i+j+nagesqr-1,nbcode[Tvar[j-2]][codtabm(k1,Tvar[j-2])]); */
                   8014:                    }
                   8015:                    ij++;
1.237     brouard  8016:                  }
1.268     brouard  8017:                } 
                   8018:              }else if(cptcovprod >0){
                   8019:                if(j==Tprod[ijp]) { /* */ 
                   8020:                  /* printf("Tprod[%d]=%d, j=%d\n", ij, Tprod[ijp], j); */
                   8021:                  if(ijp <=cptcovprod) { /* Product */
                   8022:                    if(DummyV[Tvard[ijp][1]]==0){/* Vn is dummy */
                   8023:                      if(DummyV[Tvard[ijp][2]]==0){/* Vn and Vm are dummy */
                   8024:                        /* 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)]); */
                   8025:                        fprintf(ficgp,"+p%d*%d*%d",i+j+2+nagesqr-1,Tinvresult[nres][Tvard[ijp][1]],Tinvresult[nres][Tvard[ijp][2]]);
                   8026:                      }else{ /* Vn is dummy and Vm is quanti */
                   8027:                        /* fprintf(ficgp,"+p%d*%d*%f",i+j+2+nagesqr-1,nbcode[Tvard[ijp][1]][codtabm(k1,j)],Tqinvresult[nres][Tvard[ijp][2]]); */
                   8028:                        fprintf(ficgp,"+p%d*%d*%f",i+j+2+nagesqr-1,Tinvresult[nres][Tvard[ijp][1]],Tqinvresult[nres][Tvard[ijp][2]]);
                   8029:                      }
                   8030:                    }else{ /* Vn*Vm Vn is quanti */
                   8031:                      if(DummyV[Tvard[ijp][2]]==0){
                   8032:                        fprintf(ficgp,"+p%d*%d*%f",i+j+2+nagesqr-1,Tinvresult[nres][Tvard[ijp][2]],Tqinvresult[nres][Tvard[ijp][1]]);
                   8033:                      }else{ /* Both quanti */
                   8034:                        fprintf(ficgp,"+p%d*%f*%f",i+j+2+nagesqr-1,Tqinvresult[nres][Tvard[ijp][1]],Tqinvresult[nres][Tvard[ijp][2]]);
                   8035:                      }
1.237     brouard  8036:                    }
1.268     brouard  8037:                    ijp++;
1.237     brouard  8038:                  }
1.268     brouard  8039:                } /* end Tprod */
1.237     brouard  8040:              } else{  /* simple covariate */
1.264     brouard  8041:                /* fprintf(ficgp,"+p%d*%d",i+j+2+nagesqr-1,nbcode[Tvar[j]][codtabm(k1,j)]); /\* Valgrind bug nbcode *\/ */
1.237     brouard  8042:                if(Dummy[j]==0){
                   8043:                  fprintf(ficgp,"+p%d*%d",i+j+2+nagesqr-1,Tinvresult[nres][Tvar[j]]); /*  */
                   8044:                }else{ /* quantitative */
                   8045:                  fprintf(ficgp,"+p%d*%f",i+j+2+nagesqr-1,Tqinvresult[nres][Tvar[j]]); /* */
1.264     brouard  8046:                  /* fprintf(ficgp,"+p%d*%d*x",i+j+nagesqr-1,nbcode[Tvar[j-2]][codtabm(k1,Tvar[j-2])]); */
1.223     brouard  8047:                }
1.237     brouard  8048:              } /* end simple */
                   8049:            } /* end j */
1.223     brouard  8050:          }else{
                   8051:            i=i-ncovmodel;
                   8052:            if(ng !=1 ) /* For logit formula of log p11 is more difficult to get */
                   8053:              fprintf(ficgp," (1.");
                   8054:          }
1.227     brouard  8055:          
1.223     brouard  8056:          if(ng != 1){
                   8057:            fprintf(ficgp,")/(1");
1.227     brouard  8058:            
1.264     brouard  8059:            for(cpt=1; cpt <=nlstate; cpt++){ 
1.223     brouard  8060:              if(nagesqr==0)
1.264     brouard  8061:                fprintf(ficgp,"+exp(p%d+p%d*x",k3+(cpt-1)*ncovmodel,k3+(cpt-1)*ncovmodel+1);
1.223     brouard  8062:              else /* nagesqr =1 */
1.264     brouard  8063:                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  8064:               
1.223     brouard  8065:              ij=1;
                   8066:              for(j=3; j <=ncovmodel-nagesqr; j++){
1.268     brouard  8067:                 if(cptcovage >0){ 
                   8068:                   if((j-2)==Tage[ij]) { /* Bug valgrind */
                   8069:                     if(ij <=cptcovage) { /* Bug valgrind */
                   8070:                       fprintf(ficgp,"+p%d*%d*x",k3+(cpt-1)*ncovmodel+1+j-2+nagesqr,nbcode[Tvar[j-2]][codtabm(k1,j-2)]);
                   8071:                       /* fprintf(ficgp,"+p%d*%d*x",k3+(cpt-1)*ncovmodel+1+j-2+nagesqr,nbcode[Tvar[j-2]][codtabm(k1,Tvar[j-2])]); */
                   8072:                       ij++;
                   8073:                     }
                   8074:                   }
                   8075:                 }else
                   8076:                   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  8077:              }
                   8078:              fprintf(ficgp,")");
                   8079:            }
                   8080:            fprintf(ficgp,")");
                   8081:            if(ng ==2)
1.276     brouard  8082:              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  8083:            else /* ng= 3 */
1.276     brouard  8084:              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  8085:          }else{ /* end ng <> 1 */
                   8086:            if( k !=k2) /* logit p11 is hard to draw */
1.276     brouard  8087:              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  8088:          }
                   8089:          if ((k+k2)!= (nlstate*2+ndeath) && ng != 1)
                   8090:            fprintf(ficgp,",");
                   8091:          if (ng == 1 && k!=k2 && (k+k2)!= (nlstate*2+ndeath))
                   8092:            fprintf(ficgp,",");
                   8093:          i=i+ncovmodel;
                   8094:        } /* end k */
                   8095:       } /* end k2 */
1.276     brouard  8096:       /* fprintf(ficgp,"\n set out; unset label;set key default;\n"); */
                   8097:       fprintf(ficgp,"\n set out; unset title;set key default;\n");
1.264     brouard  8098:     } /* end k1 */
1.223     brouard  8099:   } /* end ng */
                   8100:   /* avoid: */
                   8101:   fflush(ficgp); 
1.126     brouard  8102: }  /* end gnuplot */
                   8103: 
                   8104: 
                   8105: /*************** Moving average **************/
1.219     brouard  8106: /* int movingaverage(double ***probs, double bage, double fage, double ***mobaverage, int mobilav, double bageout, double fageout){ */
1.222     brouard  8107:  int movingaverage(double ***probs, double bage, double fage, double ***mobaverage, int mobilav){
1.218     brouard  8108:    
1.222     brouard  8109:    int i, cpt, cptcod;
                   8110:    int modcovmax =1;
                   8111:    int mobilavrange, mob;
                   8112:    int iage=0;
1.288     brouard  8113:    int firstA1=0, firstA2=0;
1.222     brouard  8114: 
1.266     brouard  8115:    double sum=0., sumr=0.;
1.222     brouard  8116:    double age;
1.266     brouard  8117:    double *sumnewp, *sumnewm, *sumnewmr;
                   8118:    double *agemingood, *agemaxgood; 
                   8119:    double *agemingoodr, *agemaxgoodr; 
1.222     brouard  8120:   
                   8121:   
1.278     brouard  8122:    /* modcovmax=2*cptcoveff;  Max number of modalities. We suppose  */
                   8123:    /*             a covariate has 2 modalities, should be equal to ncovcombmax   */
1.222     brouard  8124: 
                   8125:    sumnewp = vector(1,ncovcombmax);
                   8126:    sumnewm = vector(1,ncovcombmax);
1.266     brouard  8127:    sumnewmr = vector(1,ncovcombmax);
1.222     brouard  8128:    agemingood = vector(1,ncovcombmax); 
1.266     brouard  8129:    agemingoodr = vector(1,ncovcombmax);        
1.222     brouard  8130:    agemaxgood = vector(1,ncovcombmax);
1.266     brouard  8131:    agemaxgoodr = vector(1,ncovcombmax);
1.222     brouard  8132: 
                   8133:    for (cptcod=1;cptcod<=ncovcombmax;cptcod++){
1.266     brouard  8134:      sumnewm[cptcod]=0.; sumnewmr[cptcod]=0.;
1.222     brouard  8135:      sumnewp[cptcod]=0.;
1.266     brouard  8136:      agemingood[cptcod]=0, agemingoodr[cptcod]=0;
                   8137:      agemaxgood[cptcod]=0, agemaxgoodr[cptcod]=0;
1.222     brouard  8138:    }
                   8139:    if (cptcovn<1) ncovcombmax=1; /* At least 1 pass */
                   8140:   
1.266     brouard  8141:    if(mobilav==-1 || mobilav==1||mobilav ==3 ||mobilav==5 ||mobilav== 7){
                   8142:      if(mobilav==1 || mobilav==-1) mobilavrange=5; /* default */
1.222     brouard  8143:      else mobilavrange=mobilav;
                   8144:      for (age=bage; age<=fage; age++)
                   8145:        for (i=1; i<=nlstate;i++)
                   8146:         for (cptcod=1;cptcod<=ncovcombmax;cptcod++)
                   8147:           mobaverage[(int)age][i][cptcod]=probs[(int)age][i][cptcod];
                   8148:      /* We keep the original values on the extreme ages bage, fage and for 
                   8149:        fage+1 and bage-1 we use a 3 terms moving average; for fage+2 bage+2
                   8150:        we use a 5 terms etc. until the borders are no more concerned. 
                   8151:      */ 
                   8152:      for (mob=3;mob <=mobilavrange;mob=mob+2){
                   8153:        for (age=bage+(mob-1)/2; age<=fage-(mob-1)/2; age++){
1.266     brouard  8154:         for (cptcod=1;cptcod<=ncovcombmax;cptcod++){
                   8155:           sumnewm[cptcod]=0.;
                   8156:           for (i=1; i<=nlstate;i++){
1.222     brouard  8157:             mobaverage[(int)age][i][cptcod] =probs[(int)age][i][cptcod];
                   8158:             for (cpt=1;cpt<=(mob-1)/2;cpt++){
                   8159:               mobaverage[(int)age][i][cptcod] +=probs[(int)age-cpt][i][cptcod];
                   8160:               mobaverage[(int)age][i][cptcod] +=probs[(int)age+cpt][i][cptcod];
                   8161:             }
                   8162:             mobaverage[(int)age][i][cptcod]=mobaverage[(int)age][i][cptcod]/mob;
1.266     brouard  8163:             sumnewm[cptcod]+=mobaverage[(int)age][i][cptcod];
                   8164:           } /* end i */
                   8165:           if(sumnewm[cptcod] >1.e-3) mobaverage[(int)age][i][cptcod]=mobaverage[(int)age][i][cptcod]/sumnewm[cptcod]; /* Rescaling to sum one */
                   8166:         } /* end cptcod */
1.222     brouard  8167:        }/* end age */
                   8168:      }/* end mob */
1.266     brouard  8169:    }else{
                   8170:      printf("Error internal in movingaverage, mobilav=%d.\n",mobilav);
1.222     brouard  8171:      return -1;
1.266     brouard  8172:    }
                   8173: 
                   8174:    for (cptcod=1;cptcod<=ncovcombmax;cptcod++){ /* for each combination */
1.222     brouard  8175:      /* for (age=bage+(mob-1)/2; age<=fage-(mob-1)/2; age++){ */
                   8176:      if(invalidvarcomb[cptcod]){
                   8177:        printf("\nCombination (%d) ignored because no cases \n",cptcod); 
                   8178:        continue;
                   8179:      }
1.219     brouard  8180: 
1.266     brouard  8181:      for (age=fage-(mob-1)/2; age>=bage+(mob-1)/2; age--){ /*looking for the youngest and oldest good age */
                   8182:        sumnewm[cptcod]=0.;
                   8183:        sumnewmr[cptcod]=0.;
                   8184:        for (i=1; i<=nlstate;i++){
                   8185:         sumnewm[cptcod]+=mobaverage[(int)age][i][cptcod];
                   8186:         sumnewmr[cptcod]+=probs[(int)age][i][cptcod];
                   8187:        }
                   8188:        if(fabs(sumnewmr[cptcod] - 1.) <= 1.e-3) { /* good without smoothing */
                   8189:         agemingoodr[cptcod]=age;
                   8190:        }
                   8191:        if(fabs(sumnewm[cptcod] - 1.) <= 1.e-3) { /* good */
                   8192:           agemingood[cptcod]=age;
                   8193:        }
                   8194:      } /* age */
                   8195:      for (age=bage+(mob-1)/2; age<=fage-(mob-1)/2; age++){ /*looking for the youngest and oldest good age */
1.222     brouard  8196:        sumnewm[cptcod]=0.;
1.266     brouard  8197:        sumnewmr[cptcod]=0.;
1.222     brouard  8198:        for (i=1; i<=nlstate;i++){
                   8199:         sumnewm[cptcod]+=mobaverage[(int)age][i][cptcod];
1.266     brouard  8200:         sumnewmr[cptcod]+=probs[(int)age][i][cptcod];
                   8201:        }
                   8202:        if(fabs(sumnewmr[cptcod] - 1.) <= 1.e-3) { /* good without smoothing */
                   8203:         agemaxgoodr[cptcod]=age;
1.222     brouard  8204:        }
                   8205:        if(fabs(sumnewm[cptcod] - 1.) <= 1.e-3) { /* good */
1.266     brouard  8206:         agemaxgood[cptcod]=age;
                   8207:        }
                   8208:      } /* age */
                   8209:      /* Thus we have agemingood and agemaxgood as well as goodr for raw (preobs) */
                   8210:      /* but they will change */
1.288     brouard  8211:      firstA1=0;firstA2=0;
1.266     brouard  8212:      for (age=fage-(mob-1)/2; age>=bage; age--){/* From oldest to youngest, filling up to the youngest */
                   8213:        sumnewm[cptcod]=0.;
                   8214:        sumnewmr[cptcod]=0.;
                   8215:        for (i=1; i<=nlstate;i++){
                   8216:         sumnewm[cptcod]+=mobaverage[(int)age][i][cptcod];
                   8217:         sumnewmr[cptcod]+=probs[(int)age][i][cptcod];
                   8218:        }
                   8219:        if(mobilav==-1){ /* Forcing raw ages if good else agemingood */
                   8220:         if(fabs(sumnewmr[cptcod] - 1.) <= 1.e-3) { /* good without smoothing */
                   8221:           agemaxgoodr[cptcod]=age;  /* age min */
                   8222:           for (i=1; i<=nlstate;i++)
                   8223:             mobaverage[(int)age][i][cptcod]=probs[(int)age][i][cptcod];
                   8224:         }else{ /* bad we change the value with the values of good ages */
                   8225:           for (i=1; i<=nlstate;i++){
                   8226:             mobaverage[(int)age][i][cptcod]=mobaverage[(int)agemaxgoodr[cptcod]][i][cptcod];
                   8227:           } /* i */
                   8228:         } /* end bad */
                   8229:        }else{
                   8230:         if(fabs(sumnewm[cptcod] - 1.) <= 1.e-3) { /* good */
                   8231:           agemaxgood[cptcod]=age;
                   8232:         }else{ /* bad we change the value with the values of good ages */
                   8233:           for (i=1; i<=nlstate;i++){
                   8234:             mobaverage[(int)age][i][cptcod]=mobaverage[(int)agemaxgood[cptcod]][i][cptcod];
                   8235:           } /* i */
                   8236:         } /* end bad */
                   8237:        }/* end else */
                   8238:        sum=0.;sumr=0.;
                   8239:        for (i=1; i<=nlstate;i++){
                   8240:         sum+=mobaverage[(int)age][i][cptcod];
                   8241:         sumr+=probs[(int)age][i][cptcod];
                   8242:        }
                   8243:        if(fabs(sum - 1.) > 1.e-3) { /* bad */
1.288     brouard  8244:         if(!firstA1){
                   8245:           firstA1=1;
                   8246:           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);
                   8247:         }
                   8248:         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  8249:        } /* end bad */
                   8250:        /* else{ /\* We found some ages summing to one, we will smooth the oldest *\/ */
                   8251:        if(fabs(sumr - 1.) > 1.e-3) { /* bad */
1.288     brouard  8252:         if(!firstA2){
                   8253:           firstA2=1;
                   8254:           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);
                   8255:         }
                   8256:         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  8257:        } /* end bad */
                   8258:      }/* age */
1.266     brouard  8259: 
                   8260:      for (age=bage+(mob-1)/2; age<=fage; age++){/* From youngest, finding the oldest wrong */
1.222     brouard  8261:        sumnewm[cptcod]=0.;
1.266     brouard  8262:        sumnewmr[cptcod]=0.;
1.222     brouard  8263:        for (i=1; i<=nlstate;i++){
                   8264:         sumnewm[cptcod]+=mobaverage[(int)age][i][cptcod];
1.266     brouard  8265:         sumnewmr[cptcod]+=probs[(int)age][i][cptcod];
                   8266:        } 
                   8267:        if(mobilav==-1){ /* Forcing raw ages if good else agemingood */
                   8268:         if(fabs(sumnewmr[cptcod] - 1.) <= 1.e-3) { /* good */
                   8269:           agemingoodr[cptcod]=age;
                   8270:           for (i=1; i<=nlstate;i++)
                   8271:             mobaverage[(int)age][i][cptcod]=probs[(int)age][i][cptcod];
                   8272:         }else{ /* bad we change the value with the values of good ages */
                   8273:           for (i=1; i<=nlstate;i++){
                   8274:             mobaverage[(int)age][i][cptcod]=mobaverage[(int)agemingoodr[cptcod]][i][cptcod];
                   8275:           } /* i */
                   8276:         } /* end bad */
                   8277:        }else{
                   8278:         if(fabs(sumnewm[cptcod] - 1.) <= 1.e-3) { /* good */
                   8279:           agemingood[cptcod]=age;
                   8280:         }else{ /* bad */
                   8281:           for (i=1; i<=nlstate;i++){
                   8282:             mobaverage[(int)age][i][cptcod]=mobaverage[(int)agemingood[cptcod]][i][cptcod];
                   8283:           } /* i */
                   8284:         } /* end bad */
                   8285:        }/* end else */
                   8286:        sum=0.;sumr=0.;
                   8287:        for (i=1; i<=nlstate;i++){
                   8288:         sum+=mobaverage[(int)age][i][cptcod];
                   8289:         sumr+=mobaverage[(int)age][i][cptcod];
1.222     brouard  8290:        }
1.266     brouard  8291:        if(fabs(sum - 1.) > 1.e-3) { /* bad */
1.268     brouard  8292:         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  8293:        } /* end bad */
                   8294:        /* else{ /\* We found some ages summing to one, we will smooth the oldest *\/ */
                   8295:        if(fabs(sumr - 1.) > 1.e-3) { /* bad */
1.268     brouard  8296:         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  8297:        } /* end bad */
                   8298:      }/* age */
1.266     brouard  8299: 
1.222     brouard  8300:                
                   8301:      for (age=bage; age<=fage; age++){
1.235     brouard  8302:        /* printf("%d %d ", cptcod, (int)age); */
1.222     brouard  8303:        sumnewp[cptcod]=0.;
                   8304:        sumnewm[cptcod]=0.;
                   8305:        for (i=1; i<=nlstate;i++){
                   8306:         sumnewp[cptcod]+=probs[(int)age][i][cptcod];
                   8307:         sumnewm[cptcod]+=mobaverage[(int)age][i][cptcod];
                   8308:         /* printf("%.4f %.4f ",probs[(int)age][i][cptcod], mobaverage[(int)age][i][cptcod]); */
                   8309:        }
                   8310:        /* printf("%.4f %.4f \n",sumnewp[cptcod], sumnewm[cptcod]); */
                   8311:      }
                   8312:      /* printf("\n"); */
                   8313:      /* } */
1.266     brouard  8314: 
1.222     brouard  8315:      /* brutal averaging */
1.266     brouard  8316:      /* for (i=1; i<=nlstate;i++){ */
                   8317:      /*   for (age=1; age<=bage; age++){ */
                   8318:      /*         mobaverage[(int)age][i][cptcod]=mobaverage[(int)agemingood[cptcod]][i][cptcod]; */
                   8319:      /*         /\* printf("age=%d i=%d cptcod=%d mobaverage=%.4f \n",(int)age,i, cptcod, mobaverage[(int)age][i][cptcod]); *\/ */
                   8320:      /*   }     */
                   8321:      /*   for (age=fage; age<=AGESUP; age++){ */
                   8322:      /*         mobaverage[(int)age][i][cptcod]=mobaverage[(int)agemaxgood[cptcod]][i][cptcod]; */
                   8323:      /*         /\* printf("age=%d i=%d cptcod=%d mobaverage=%.4f \n",(int)age,i, cptcod, mobaverage[(int)age][i][cptcod]); *\/ */
                   8324:      /*   } */
                   8325:      /* } /\* end i status *\/ */
                   8326:      /* for (i=nlstate+1; i<=nlstate+ndeath;i++){ */
                   8327:      /*   for (age=1; age<=AGESUP; age++){ */
                   8328:      /*         /\*printf("i=%d, age=%d, cptcod=%d\n",i, (int)age, cptcod);*\/ */
                   8329:      /*         mobaverage[(int)age][i][cptcod]=0.; */
                   8330:      /*   } */
                   8331:      /* } */
1.222     brouard  8332:    }/* end cptcod */
1.266     brouard  8333:    free_vector(agemaxgoodr,1, ncovcombmax);
                   8334:    free_vector(agemaxgood,1, ncovcombmax);
                   8335:    free_vector(agemingood,1, ncovcombmax);
                   8336:    free_vector(agemingoodr,1, ncovcombmax);
                   8337:    free_vector(sumnewmr,1, ncovcombmax);
1.222     brouard  8338:    free_vector(sumnewm,1, ncovcombmax);
                   8339:    free_vector(sumnewp,1, ncovcombmax);
                   8340:    return 0;
                   8341:  }/* End movingaverage */
1.218     brouard  8342:  
1.126     brouard  8343: 
1.296     brouard  8344:  
1.126     brouard  8345: /************** Forecasting ******************/
1.296     brouard  8346: /* 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)*/
                   8347: 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){
                   8348:   /* dateintemean, mean date of interviews
                   8349:      dateprojd, year, month, day of starting projection 
                   8350:      dateprojf date of end of projection;year of end of projection (same day and month as proj1).
1.126     brouard  8351:      agemin, agemax range of age
                   8352:      dateprev1 dateprev2 range of dates during which prevalence is computed
                   8353:   */
1.296     brouard  8354:   /* double anprojd, mprojd, jprojd; */
                   8355:   /* double anprojf, mprojf, jprojf; */
1.267     brouard  8356:   int yearp, stepsize, hstepm, nhstepm, j, k, cptcod, i, h, i1, k4, nres=0;
1.126     brouard  8357:   double agec; /* generic age */
1.296     brouard  8358:   double agelim, ppij, yp,yp1,yp2;
1.126     brouard  8359:   double *popeffectif,*popcount;
                   8360:   double ***p3mat;
1.218     brouard  8361:   /* double ***mobaverage; */
1.126     brouard  8362:   char fileresf[FILENAMELENGTH];
                   8363: 
                   8364:   agelim=AGESUP;
1.211     brouard  8365:   /* Compute observed prevalence between dateprev1 and dateprev2 by counting the number of people
                   8366:      in each health status at the date of interview (if between dateprev1 and dateprev2).
                   8367:      We still use firstpass and lastpass as another selection.
                   8368:   */
1.214     brouard  8369:   /* freqsummary(fileres, agemin, agemax, s, agev, nlstate, imx,Tvaraff,nbcode, ncodemax,mint,anint,strstart,\ */
                   8370:   /*         firstpass, lastpass,  stepm,  weightopt, model); */
1.126     brouard  8371:  
1.201     brouard  8372:   strcpy(fileresf,"F_"); 
                   8373:   strcat(fileresf,fileresu);
1.126     brouard  8374:   if((ficresf=fopen(fileresf,"w"))==NULL) {
                   8375:     printf("Problem with forecast resultfile: %s\n", fileresf);
                   8376:     fprintf(ficlog,"Problem with forecast resultfile: %s\n", fileresf);
                   8377:   }
1.235     brouard  8378:   printf("\nComputing forecasting: result on file '%s', please wait... \n", fileresf);
                   8379:   fprintf(ficlog,"\nComputing forecasting: result on file '%s', please wait... \n", fileresf);
1.126     brouard  8380: 
1.225     brouard  8381:   if (cptcoveff==0) ncodemax[cptcoveff]=1;
1.126     brouard  8382: 
                   8383: 
                   8384:   stepsize=(int) (stepm+YEARM-1)/YEARM;
                   8385:   if (stepm<=12) stepsize=1;
                   8386:   if(estepm < stepm){
                   8387:     printf ("Problem %d lower than %d\n",estepm, stepm);
                   8388:   }
1.270     brouard  8389:   else{
                   8390:     hstepm=estepm;   
                   8391:   }
                   8392:   if(estepm > stepm){ /* Yes every two year */
                   8393:     stepsize=2;
                   8394:   }
1.296     brouard  8395:   hstepm=hstepm/stepm;
1.126     brouard  8396: 
1.296     brouard  8397:   
                   8398:   /* yp1=modf(dateintmean,&yp);/\* extracts integral of datemean in yp  and */
                   8399:   /*                              fractional in yp1 *\/ */
                   8400:   /* aintmean=yp; */
                   8401:   /* yp2=modf((yp1*12),&yp); */
                   8402:   /* mintmean=yp; */
                   8403:   /* yp1=modf((yp2*30.5),&yp); */
                   8404:   /* jintmean=yp; */
                   8405:   /* if(jintmean==0) jintmean=1; */
                   8406:   /* if(mintmean==0) mintmean=1; */
1.126     brouard  8407: 
1.296     brouard  8408: 
                   8409:   /* date2dmy(dateintmean,&jintmean,&mintmean,&aintmean); */
                   8410:   /* date2dmy(dateprojd,&jprojd, &mprojd, &anprojd); */
                   8411:   /* date2dmy(dateprojf,&jprojf, &mprojf, &anprojf); */
1.227     brouard  8412:   i1=pow(2,cptcoveff);
1.126     brouard  8413:   if (cptcovn < 1){i1=1;}
                   8414:   
1.296     brouard  8415:   fprintf(ficresf,"# Mean day of interviews %.lf/%.lf/%.lf (%.2f) between %.2f and %.2f \n",jintmean,mintmean,aintmean,dateintmean,dateprev1,dateprev2); 
1.126     brouard  8416:   
                   8417:   fprintf(ficresf,"#****** Routine prevforecast **\n");
1.227     brouard  8418:   
1.126     brouard  8419: /*           if (h==(int)(YEARM*yearp)){ */
1.235     brouard  8420:   for(nres=1; nres <= nresult; nres++) /* For each resultline */
                   8421:   for(k=1; k<=i1;k++){
1.253     brouard  8422:     if(i1 != 1 && TKresult[nres]!= k)
1.235     brouard  8423:       continue;
1.227     brouard  8424:     if(invalidvarcomb[k]){
                   8425:       printf("\nCombination (%d) projection ignored because no cases \n",k); 
                   8426:       continue;
                   8427:     }
                   8428:     fprintf(ficresf,"\n#****** hpijx=probability over h years, hp.jx is weighted by observed prev \n#");
                   8429:     for(j=1;j<=cptcoveff;j++) {
                   8430:       fprintf(ficresf," V%d (=) %d",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   8431:     }
1.235     brouard  8432:     for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
1.238     brouard  8433:       fprintf(ficresf," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
1.235     brouard  8434:     }
1.227     brouard  8435:     fprintf(ficresf," yearproj age");
                   8436:     for(j=1; j<=nlstate+ndeath;j++){ 
                   8437:       for(i=1; i<=nlstate;i++)               
                   8438:        fprintf(ficresf," p%d%d",i,j);
                   8439:       fprintf(ficresf," wp.%d",j);
                   8440:     }
1.296     brouard  8441:     for (yearp=0; yearp<=(anprojf-anprojd);yearp +=stepsize) {
1.227     brouard  8442:       fprintf(ficresf,"\n");
1.296     brouard  8443:       fprintf(ficresf,"\n# Forecasting at date %.lf/%.lf/%.lf ",jprojd,mprojd,anprojd+yearp);   
1.270     brouard  8444:       /* for (agec=fage; agec>=(ageminpar-1); agec--){  */
                   8445:       for (agec=fage; agec>=(bage); agec--){ 
1.227     brouard  8446:        nhstepm=(int) rint((agelim-agec)*YEARM/stepm); 
                   8447:        nhstepm = nhstepm/hstepm; 
                   8448:        p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   8449:        oldm=oldms;savm=savms;
1.268     brouard  8450:        /* We compute pii at age agec over nhstepm);*/
1.235     brouard  8451:        hpxij(p3mat,nhstepm,agec,hstepm,p,nlstate,stepm,oldm,savm, k,nres);
1.268     brouard  8452:        /* Then we print p3mat for h corresponding to the right agec+h*stepms=yearp */
1.227     brouard  8453:        for (h=0; h<=nhstepm; h++){
                   8454:          if (h*hstepm/YEARM*stepm ==yearp) {
1.268     brouard  8455:            break;
                   8456:          }
                   8457:        }
                   8458:        fprintf(ficresf,"\n");
                   8459:        for(j=1;j<=cptcoveff;j++) 
                   8460:          fprintf(ficresf,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
1.296     brouard  8461:        fprintf(ficresf,"%.f %.f ",anprojd+yearp,agec+h*hstepm/YEARM*stepm);
1.268     brouard  8462:        
                   8463:        for(j=1; j<=nlstate+ndeath;j++) {
                   8464:          ppij=0.;
                   8465:          for(i=1; i<=nlstate;i++) {
1.278     brouard  8466:            if (mobilav>=1)
                   8467:             ppij=ppij+p3mat[i][j][h]*prev[(int)agec][i][k];
                   8468:            else { /* even if mobilav==-1 we use mobaverage, probs may not sums to 1 */
                   8469:                ppij=ppij+p3mat[i][j][h]*probs[(int)(agec)][i][k];
                   8470:            }
1.268     brouard  8471:            fprintf(ficresf," %.3f", p3mat[i][j][h]);
                   8472:          } /* end i */
                   8473:          fprintf(ficresf," %.3f", ppij);
                   8474:        }/* end j */
1.227     brouard  8475:        free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   8476:       } /* end agec */
1.266     brouard  8477:       /* diffyear=(int) anproj1+yearp-ageminpar-1; */
                   8478:       /*printf("Prevforecast %d+%d-%d=diffyear=%d\n",(int) anproj1, (int)yearp,(int)ageminpar,(int) anproj1-(int)ageminpar);*/
1.227     brouard  8479:     } /* end yearp */
                   8480:   } /* end  k */
1.219     brouard  8481:        
1.126     brouard  8482:   fclose(ficresf);
1.215     brouard  8483:   printf("End of Computing forecasting \n");
                   8484:   fprintf(ficlog,"End of Computing forecasting\n");
                   8485: 
1.126     brouard  8486: }
                   8487: 
1.269     brouard  8488: /************** Back Forecasting ******************/
1.296     brouard  8489:  /* 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){ */
                   8490:  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){
                   8491:   /* back1, year, month, day of starting backprojection
1.267     brouard  8492:      agemin, agemax range of age
                   8493:      dateprev1 dateprev2 range of dates during which prevalence is computed
1.269     brouard  8494:      anback2 year of end of backprojection (same day and month as back1).
                   8495:      prevacurrent and prev are prevalences.
1.267     brouard  8496:   */
                   8497:   int yearp, stepsize, hstepm, nhstepm, j, k, cptcod, i, h, i1, k4, nres=0;
                   8498:   double agec; /* generic age */
1.296     brouard  8499:   double agelim, ppij, ppi, yp,yp1,yp2,jintmean,mintmean,aintmean;
1.267     brouard  8500:   double *popeffectif,*popcount;
                   8501:   double ***p3mat;
                   8502:   /* double ***mobaverage; */
                   8503:   char fileresfb[FILENAMELENGTH];
                   8504:  
1.268     brouard  8505:   agelim=AGEINF;
1.267     brouard  8506:   /* Compute observed prevalence between dateprev1 and dateprev2 by counting the number of people
                   8507:      in each health status at the date of interview (if between dateprev1 and dateprev2).
                   8508:      We still use firstpass and lastpass as another selection.
                   8509:   */
                   8510:   /* freqsummary(fileres, agemin, agemax, s, agev, nlstate, imx,Tvaraff,nbcode, ncodemax,mint,anint,strstart,\ */
                   8511:   /*         firstpass, lastpass,  stepm,  weightopt, model); */
                   8512: 
                   8513:   /*Do we need to compute prevalence again?*/
                   8514: 
                   8515:   /* prevalence(probs, ageminpar, agemax, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass); */
                   8516:   
                   8517:   strcpy(fileresfb,"FB_");
                   8518:   strcat(fileresfb,fileresu);
                   8519:   if((ficresfb=fopen(fileresfb,"w"))==NULL) {
                   8520:     printf("Problem with back forecast resultfile: %s\n", fileresfb);
                   8521:     fprintf(ficlog,"Problem with back forecast resultfile: %s\n", fileresfb);
                   8522:   }
                   8523:   printf("\nComputing back forecasting: result on file '%s', please wait... \n", fileresfb);
                   8524:   fprintf(ficlog,"\nComputing back forecasting: result on file '%s', please wait... \n", fileresfb);
                   8525:   
                   8526:   if (cptcoveff==0) ncodemax[cptcoveff]=1;
                   8527:   
                   8528:    
                   8529:   stepsize=(int) (stepm+YEARM-1)/YEARM;
                   8530:   if (stepm<=12) stepsize=1;
                   8531:   if(estepm < stepm){
                   8532:     printf ("Problem %d lower than %d\n",estepm, stepm);
                   8533:   }
1.270     brouard  8534:   else{
                   8535:     hstepm=estepm;   
                   8536:   }
                   8537:   if(estepm >= stepm){ /* Yes every two year */
                   8538:     stepsize=2;
                   8539:   }
1.267     brouard  8540:   
                   8541:   hstepm=hstepm/stepm;
1.296     brouard  8542:   /* yp1=modf(dateintmean,&yp);/\* extracts integral of datemean in yp  and */
                   8543:   /*                              fractional in yp1 *\/ */
                   8544:   /* aintmean=yp; */
                   8545:   /* yp2=modf((yp1*12),&yp); */
                   8546:   /* mintmean=yp; */
                   8547:   /* yp1=modf((yp2*30.5),&yp); */
                   8548:   /* jintmean=yp; */
                   8549:   /* if(jintmean==0) jintmean=1; */
                   8550:   /* if(mintmean==0) jintmean=1; */
1.267     brouard  8551:   
                   8552:   i1=pow(2,cptcoveff);
                   8553:   if (cptcovn < 1){i1=1;}
                   8554:   
1.296     brouard  8555:   fprintf(ficresfb,"# Mean day of interviews %.lf/%.lf/%.lf (%.2f) between %.2f and %.2f \n",jintmean,mintmean,aintmean,dateintmean,dateprev1,dateprev2);
                   8556:   printf("# Mean day of interviews %.lf/%.lf/%.lf (%.2f) between %.2f and %.2f \n",jintmean,mintmean,aintmean,dateintmean,dateprev1,dateprev2);
1.267     brouard  8557:   
                   8558:   fprintf(ficresfb,"#****** Routine prevbackforecast **\n");
                   8559:   
                   8560:   for(nres=1; nres <= nresult; nres++) /* For each resultline */
                   8561:   for(k=1; k<=i1;k++){
                   8562:     if(i1 != 1 && TKresult[nres]!= k)
                   8563:       continue;
                   8564:     if(invalidvarcomb[k]){
                   8565:       printf("\nCombination (%d) projection ignored because no cases \n",k); 
                   8566:       continue;
                   8567:     }
1.268     brouard  8568:     fprintf(ficresfb,"\n#****** hbijx=probability over h years, hb.jx is weighted by observed prev \n#");
1.267     brouard  8569:     for(j=1;j<=cptcoveff;j++) {
                   8570:       fprintf(ficresfb," V%d (=) %d",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   8571:     }
                   8572:     for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
                   8573:       fprintf(ficresf," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
                   8574:     }
                   8575:     fprintf(ficresfb," yearbproj age");
                   8576:     for(j=1; j<=nlstate+ndeath;j++){
                   8577:       for(i=1; i<=nlstate;i++)
1.268     brouard  8578:        fprintf(ficresfb," b%d%d",i,j);
                   8579:       fprintf(ficresfb," b.%d",j);
1.267     brouard  8580:     }
1.296     brouard  8581:     for (yearp=0; yearp>=(anbackf-anbackd);yearp -=stepsize) {
1.267     brouard  8582:       /* for (yearp=0; yearp<=(anproj2-anproj1);yearp +=stepsize) {  */
                   8583:       fprintf(ficresfb,"\n");
1.296     brouard  8584:       fprintf(ficresfb,"\n# Back Forecasting at date %.lf/%.lf/%.lf ",jbackd,mbackd,anbackd+yearp);
1.273     brouard  8585:       /* printf("\n# Back Forecasting at date %.lf/%.lf/%.lf ",jback1,mback1,anback1+yearp); */
1.270     brouard  8586:       /* for (agec=bage; agec<=agemax-1; agec++){  /\* testing *\/ */
                   8587:       for (agec=bage; agec<=fage; agec++){  /* testing */
1.268     brouard  8588:        /* We compute bij at age agec over nhstepm, nhstepm decreases when agec increases because of agemax;*/
1.271     brouard  8589:        nhstepm=(int) (agec-agelim) *YEARM/stepm;/*     nhstepm=(int) rint((agec-agelim)*YEARM/stepm);*/
1.267     brouard  8590:        nhstepm = nhstepm/hstepm;
                   8591:        p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   8592:        oldm=oldms;savm=savms;
1.268     brouard  8593:        /* computes hbxij at age agec over 1 to nhstepm */
1.271     brouard  8594:        /* printf("####prevbackforecast debug  agec=%.2f nhstepm=%d\n",agec, nhstepm);fflush(stdout); */
1.267     brouard  8595:        hbxij(p3mat,nhstepm,agec,hstepm,p,prevacurrent,nlstate,stepm, k, nres);
1.268     brouard  8596:        /* hpxij(p3mat,nhstepm,agec,hstepm,p,             nlstate,stepm,oldm,savm, k,nres); */
                   8597:        /* Then we print p3mat for h corresponding to the right agec+h*stepms=yearp */
                   8598:        /* printf(" agec=%.2f\n",agec);fflush(stdout); */
1.267     brouard  8599:        for (h=0; h<=nhstepm; h++){
1.268     brouard  8600:          if (h*hstepm/YEARM*stepm ==-yearp) {
                   8601:            break;
                   8602:          }
                   8603:        }
                   8604:        fprintf(ficresfb,"\n");
                   8605:        for(j=1;j<=cptcoveff;j++)
                   8606:          fprintf(ficresfb,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
1.296     brouard  8607:        fprintf(ficresfb,"%.f %.f ",anbackd+yearp,agec-h*hstepm/YEARM*stepm);
1.268     brouard  8608:        for(i=1; i<=nlstate+ndeath;i++) {
                   8609:          ppij=0.;ppi=0.;
                   8610:          for(j=1; j<=nlstate;j++) {
                   8611:            /* if (mobilav==1) */
1.269     brouard  8612:            ppij=ppij+p3mat[i][j][h]*prevacurrent[(int)agec][j][k];
                   8613:            ppi=ppi+prevacurrent[(int)agec][j][k];
                   8614:            /* ppij=ppij+p3mat[i][j][h]*mobaverage[(int)agec][j][k]; */
                   8615:            /* ppi=ppi+mobaverage[(int)agec][j][k]; */
1.267     brouard  8616:              /* else { */
                   8617:              /*        ppij=ppij+p3mat[i][j][h]*probs[(int)(agec)][i][k]; */
                   8618:              /* } */
1.268     brouard  8619:            fprintf(ficresfb," %.3f", p3mat[i][j][h]);
                   8620:          } /* end j */
                   8621:          if(ppi <0.99){
                   8622:            printf("Error in prevbackforecast, prevalence doesn't sum to 1 for state %d: %3f\n",i, ppi);
                   8623:            fprintf(ficlog,"Error in prevbackforecast, prevalence doesn't sum to 1 for state %d: %3f\n",i, ppi);
                   8624:          }
                   8625:          fprintf(ficresfb," %.3f", ppij);
                   8626:        }/* end j */
1.267     brouard  8627:        free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   8628:       } /* end agec */
                   8629:     } /* end yearp */
                   8630:   } /* end k */
1.217     brouard  8631:   
1.267     brouard  8632:   /* if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX); */
1.217     brouard  8633:   
1.267     brouard  8634:   fclose(ficresfb);
                   8635:   printf("End of Computing Back forecasting \n");
                   8636:   fprintf(ficlog,"End of Computing Back forecasting\n");
1.218     brouard  8637:        
1.267     brouard  8638: }
1.217     brouard  8639: 
1.269     brouard  8640: /* Variance of prevalence limit: varprlim */
                   8641:  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  8642:     /*------- Variance of forward period (stable) prevalence------*/   
1.269     brouard  8643:  
                   8644:    char fileresvpl[FILENAMELENGTH];  
                   8645:    FILE *ficresvpl;
                   8646:    double **oldm, **savm;
                   8647:    double **varpl; /* Variances of prevalence limits by age */   
                   8648:    int i1, k, nres, j ;
                   8649:    
                   8650:     strcpy(fileresvpl,"VPL_");
                   8651:     strcat(fileresvpl,fileresu);
                   8652:     if((ficresvpl=fopen(fileresvpl,"w"))==NULL) {
1.288     brouard  8653:       printf("Problem with variance of forward period (stable) prevalence  resultfile: %s\n", fileresvpl);
1.269     brouard  8654:       exit(0);
                   8655:     }
1.288     brouard  8656:     printf("Computing Variance-covariance of forward period (stable) prevalence: file '%s' ...", fileresvpl);fflush(stdout);
                   8657:     fprintf(ficlog, "Computing Variance-covariance of forward period (stable) prevalence: file '%s' ...", fileresvpl);fflush(ficlog);
1.269     brouard  8658:     
                   8659:     /*for(cptcov=1,k=0;cptcov<=i1;cptcov++){
                   8660:       for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*/
                   8661:     
                   8662:     i1=pow(2,cptcoveff);
                   8663:     if (cptcovn < 1){i1=1;}
                   8664: 
                   8665:     for(nres=1; nres <= nresult; nres++) /* For each resultline */
                   8666:     for(k=1; k<=i1;k++){
                   8667:       if(i1 != 1 && TKresult[nres]!= k)
                   8668:        continue;
                   8669:       fprintf(ficresvpl,"\n#****** ");
                   8670:       printf("\n#****** ");
                   8671:       fprintf(ficlog,"\n#****** ");
                   8672:       for(j=1;j<=cptcoveff;j++) {
                   8673:        fprintf(ficresvpl,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   8674:        fprintf(ficlog,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   8675:        printf("V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   8676:       }
                   8677:       for (j=1; j<= nsq; j++){ /* For each selected (single) quantitative value */
                   8678:        printf(" V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]);
                   8679:        fprintf(ficresvpl," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]);
                   8680:        fprintf(ficlog," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]);
                   8681:       }        
                   8682:       fprintf(ficresvpl,"******\n");
                   8683:       printf("******\n");
                   8684:       fprintf(ficlog,"******\n");
                   8685:       
                   8686:       varpl=matrix(1,nlstate,(int) bage, (int) fage);
                   8687:       oldm=oldms;savm=savms;
                   8688:       varprevlim(fileresvpl, ficresvpl, varpl, matcov, p, delti, nlstate, stepm, (int) bage, (int) fage, oldm, savm, prlim, ftolpl, ncvyearp, k, strstart, nres);
                   8689:       free_matrix(varpl,1,nlstate,(int) bage, (int)fage);
                   8690:       /*}*/
                   8691:     }
                   8692:     
                   8693:     fclose(ficresvpl);
1.288     brouard  8694:     printf("done variance-covariance of forward period prevalence\n");fflush(stdout);
                   8695:     fprintf(ficlog,"done variance-covariance of forward period prevalence\n");fflush(ficlog);
1.269     brouard  8696: 
                   8697:  }
                   8698: /* Variance of back prevalence: varbprlim */
                   8699:  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){
                   8700:       /*------- Variance of back (stable) prevalence------*/
                   8701: 
                   8702:    char fileresvbl[FILENAMELENGTH];  
                   8703:    FILE  *ficresvbl;
                   8704: 
                   8705:    double **oldm, **savm;
                   8706:    double **varbpl; /* Variances of back prevalence limits by age */   
                   8707:    int i1, k, nres, j ;
                   8708: 
                   8709:    strcpy(fileresvbl,"VBL_");
                   8710:    strcat(fileresvbl,fileresu);
                   8711:    if((ficresvbl=fopen(fileresvbl,"w"))==NULL) {
                   8712:      printf("Problem with variance of back (stable) prevalence  resultfile: %s\n", fileresvbl);
                   8713:      exit(0);
                   8714:    }
                   8715:    printf("Computing Variance-covariance of back (stable) prevalence: file '%s' ...", fileresvbl);fflush(stdout);
                   8716:    fprintf(ficlog, "Computing Variance-covariance of back (stable) prevalence: file '%s' ...", fileresvbl);fflush(ficlog);
                   8717:    
                   8718:    
                   8719:    i1=pow(2,cptcoveff);
                   8720:    if (cptcovn < 1){i1=1;}
                   8721:    
                   8722:    for(nres=1; nres <= nresult; nres++) /* For each resultline */
                   8723:      for(k=1; k<=i1;k++){
                   8724:        if(i1 != 1 && TKresult[nres]!= k)
                   8725:         continue;
                   8726:        fprintf(ficresvbl,"\n#****** ");
                   8727:        printf("\n#****** ");
                   8728:        fprintf(ficlog,"\n#****** ");
                   8729:        for(j=1;j<=cptcoveff;j++) {
                   8730:         fprintf(ficresvbl,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   8731:         fprintf(ficlog,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   8732:         printf("V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   8733:        }
                   8734:        for (j=1; j<= nsq; j++){ /* For each selected (single) quantitative value */
                   8735:         printf(" V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]);
                   8736:         fprintf(ficresvbl," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]);
                   8737:         fprintf(ficlog," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]);
                   8738:        }
                   8739:        fprintf(ficresvbl,"******\n");
                   8740:        printf("******\n");
                   8741:        fprintf(ficlog,"******\n");
                   8742:        
                   8743:        varbpl=matrix(1,nlstate,(int) bage, (int) fage);
                   8744:        oldm=oldms;savm=savms;
                   8745:        
                   8746:        varbrevlim(fileresvbl, ficresvbl, varbpl, matcov, p, delti, nlstate, stepm, (int) bage, (int) fage, oldm, savm, bprlim, ftolpl, mobilavproj, ncvyearp, k, strstart, nres);
                   8747:        free_matrix(varbpl,1,nlstate,(int) bage, (int)fage);
                   8748:        /*}*/
                   8749:      }
                   8750:    
                   8751:    fclose(ficresvbl);
                   8752:    printf("done variance-covariance of back prevalence\n");fflush(stdout);
                   8753:    fprintf(ficlog,"done variance-covariance of back prevalence\n");fflush(ficlog);
                   8754: 
                   8755:  } /* End of varbprlim */
                   8756: 
1.126     brouard  8757: /************** Forecasting *****not tested NB*************/
1.227     brouard  8758: /* 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  8759:   
1.227     brouard  8760: /*   int cpt, stepsize, hstepm, nhstepm, j,k,c, cptcod, i,h; */
                   8761: /*   int *popage; */
                   8762: /*   double calagedatem, agelim, kk1, kk2; */
                   8763: /*   double *popeffectif,*popcount; */
                   8764: /*   double ***p3mat,***tabpop,***tabpopprev; */
                   8765: /*   /\* double ***mobaverage; *\/ */
                   8766: /*   char filerespop[FILENAMELENGTH]; */
1.126     brouard  8767: 
1.227     brouard  8768: /*   tabpop= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX); */
                   8769: /*   tabpopprev= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX); */
                   8770: /*   agelim=AGESUP; */
                   8771: /*   calagedatem=(anpyram+mpyram/12.+jpyram/365.-dateintmean)*YEARM; */
1.126     brouard  8772:   
1.227     brouard  8773: /*   prevalence(probs, ageminpar, agemax, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass); */
1.126     brouard  8774:   
                   8775:   
1.227     brouard  8776: /*   strcpy(filerespop,"POP_");  */
                   8777: /*   strcat(filerespop,fileresu); */
                   8778: /*   if((ficrespop=fopen(filerespop,"w"))==NULL) { */
                   8779: /*     printf("Problem with forecast resultfile: %s\n", filerespop); */
                   8780: /*     fprintf(ficlog,"Problem with forecast resultfile: %s\n", filerespop); */
                   8781: /*   } */
                   8782: /*   printf("Computing forecasting: result on file '%s' \n", filerespop); */
                   8783: /*   fprintf(ficlog,"Computing forecasting: result on file '%s' \n", filerespop); */
1.126     brouard  8784: 
1.227     brouard  8785: /*   if (cptcoveff==0) ncodemax[cptcoveff]=1; */
1.126     brouard  8786: 
1.227     brouard  8787: /*   /\* if (mobilav!=0) { *\/ */
                   8788: /*   /\*   mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX); *\/ */
                   8789: /*   /\*   if (movingaverage(probs, ageminpar, fage, mobaverage,mobilav)!=0){ *\/ */
                   8790: /*   /\*     fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav); *\/ */
                   8791: /*   /\*     printf(" Error in movingaverage mobilav=%d\n",mobilav); *\/ */
                   8792: /*   /\*   } *\/ */
                   8793: /*   /\* } *\/ */
1.126     brouard  8794: 
1.227     brouard  8795: /*   stepsize=(int) (stepm+YEARM-1)/YEARM; */
                   8796: /*   if (stepm<=12) stepsize=1; */
1.126     brouard  8797:   
1.227     brouard  8798: /*   agelim=AGESUP; */
1.126     brouard  8799:   
1.227     brouard  8800: /*   hstepm=1; */
                   8801: /*   hstepm=hstepm/stepm;  */
1.218     brouard  8802:        
1.227     brouard  8803: /*   if (popforecast==1) { */
                   8804: /*     if((ficpop=fopen(popfile,"r"))==NULL) { */
                   8805: /*       printf("Problem with population file : %s\n",popfile);exit(0); */
                   8806: /*       fprintf(ficlog,"Problem with population file : %s\n",popfile);exit(0); */
                   8807: /*     }  */
                   8808: /*     popage=ivector(0,AGESUP); */
                   8809: /*     popeffectif=vector(0,AGESUP); */
                   8810: /*     popcount=vector(0,AGESUP); */
1.126     brouard  8811:     
1.227     brouard  8812: /*     i=1;    */
                   8813: /*     while ((c=fscanf(ficpop,"%d %lf\n",&popage[i],&popcount[i])) != EOF) i=i+1; */
1.218     brouard  8814:     
1.227     brouard  8815: /*     imx=i; */
                   8816: /*     for (i=1; i<imx;i++) popeffectif[popage[i]]=popcount[i]; */
                   8817: /*   } */
1.218     brouard  8818:   
1.227     brouard  8819: /*   for(cptcov=1,k=0;cptcov<=i2;cptcov++){ */
                   8820: /*     for(cptcod=1;cptcod<=ncodemax[cptcoveff];cptcod++){ */
                   8821: /*       k=k+1; */
                   8822: /*       fprintf(ficrespop,"\n#******"); */
                   8823: /*       for(j=1;j<=cptcoveff;j++) { */
                   8824: /*     fprintf(ficrespop," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]); */
                   8825: /*       } */
                   8826: /*       fprintf(ficrespop,"******\n"); */
                   8827: /*       fprintf(ficrespop,"# Age"); */
                   8828: /*       for(j=1; j<=nlstate+ndeath;j++) fprintf(ficrespop," P.%d",j); */
                   8829: /*       if (popforecast==1)  fprintf(ficrespop," [Population]"); */
1.126     brouard  8830:       
1.227     brouard  8831: /*       for (cpt=0; cpt<=0;cpt++) {  */
                   8832: /*     fprintf(ficrespop,"\n\n# Forecasting at date %.lf/%.lf/%.lf ",jpyram,mpyram,anpyram+cpt);    */
1.126     brouard  8833:        
1.227     brouard  8834: /*     for (agedeb=(fage-((int)calagedatem %12/12.)); agedeb>=(ageminpar-((int)calagedatem %12)/12.); agedeb--){  */
                   8835: /*       nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm);  */
                   8836: /*       nhstepm = nhstepm/hstepm;  */
1.126     brouard  8837:          
1.227     brouard  8838: /*       p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm); */
                   8839: /*       oldm=oldms;savm=savms; */
                   8840: /*       hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);   */
1.218     brouard  8841:          
1.227     brouard  8842: /*       for (h=0; h<=nhstepm; h++){ */
                   8843: /*         if (h==(int) (calagedatem+YEARM*cpt)) { */
                   8844: /*           fprintf(ficrespop,"\n %3.f ",agedeb+h*hstepm/YEARM*stepm); */
                   8845: /*         }  */
                   8846: /*         for(j=1; j<=nlstate+ndeath;j++) { */
                   8847: /*           kk1=0.;kk2=0; */
                   8848: /*           for(i=1; i<=nlstate;i++) {               */
                   8849: /*             if (mobilav==1)  */
                   8850: /*               kk1=kk1+p3mat[i][j][h]*mobaverage[(int)agedeb+1][i][cptcod]; */
                   8851: /*             else { */
                   8852: /*               kk1=kk1+p3mat[i][j][h]*probs[(int)(agedeb+1)][i][cptcod]; */
                   8853: /*             } */
                   8854: /*           } */
                   8855: /*           if (h==(int)(calagedatem+12*cpt)){ */
                   8856: /*             tabpop[(int)(agedeb)][j][cptcod]=kk1; */
                   8857: /*             /\*fprintf(ficrespop," %.3f", kk1); */
                   8858: /*               if (popforecast==1) fprintf(ficrespop," [%.f]", kk1*popeffectif[(int)agedeb+1]);*\/ */
                   8859: /*           } */
                   8860: /*         } */
                   8861: /*         for(i=1; i<=nlstate;i++){ */
                   8862: /*           kk1=0.; */
                   8863: /*           for(j=1; j<=nlstate;j++){ */
                   8864: /*             kk1= kk1+tabpop[(int)(agedeb)][j][cptcod];  */
                   8865: /*           } */
                   8866: /*           tabpopprev[(int)(agedeb)][i][cptcod]=tabpop[(int)(agedeb)][i][cptcod]/kk1*popeffectif[(int)(agedeb+(calagedatem+12*cpt)*hstepm/YEARM*stepm-1)]; */
                   8867: /*         } */
1.218     brouard  8868:            
1.227     brouard  8869: /*         if (h==(int)(calagedatem+12*cpt)) */
                   8870: /*           for(j=1; j<=nlstate;j++)  */
                   8871: /*             fprintf(ficrespop," %15.2f",tabpopprev[(int)(agedeb+1)][j][cptcod]); */
                   8872: /*       } */
                   8873: /*       free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm); */
                   8874: /*     } */
                   8875: /*       } */
1.218     brouard  8876:       
1.227     brouard  8877: /*       /\******\/ */
1.218     brouard  8878:       
1.227     brouard  8879: /*       for (cpt=1; cpt<=(anpyram1-anpyram);cpt++) {  */
                   8880: /*     fprintf(ficrespop,"\n\n# Forecasting at date %.lf/%.lf/%.lf ",jpyram,mpyram,anpyram+cpt);    */
                   8881: /*     for (agedeb=(fage-((int)calagedatem %12/12.)); agedeb>=(ageminpar-((int)calagedatem %12)/12.); agedeb--){  */
                   8882: /*       nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm);  */
                   8883: /*       nhstepm = nhstepm/hstepm;  */
1.126     brouard  8884:          
1.227     brouard  8885: /*       p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm); */
                   8886: /*       oldm=oldms;savm=savms; */
                   8887: /*       hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);   */
                   8888: /*       for (h=0; h<=nhstepm; h++){ */
                   8889: /*         if (h==(int) (calagedatem+YEARM*cpt)) { */
                   8890: /*           fprintf(ficresf,"\n %3.f ",agedeb+h*hstepm/YEARM*stepm); */
                   8891: /*         }  */
                   8892: /*         for(j=1; j<=nlstate+ndeath;j++) { */
                   8893: /*           kk1=0.;kk2=0; */
                   8894: /*           for(i=1; i<=nlstate;i++) {               */
                   8895: /*             kk1=kk1+p3mat[i][j][h]*tabpopprev[(int)agedeb+1][i][cptcod];     */
                   8896: /*           } */
                   8897: /*           if (h==(int)(calagedatem+12*cpt)) fprintf(ficresf," %15.2f", kk1);         */
                   8898: /*         } */
                   8899: /*       } */
                   8900: /*       free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm); */
                   8901: /*     } */
                   8902: /*       } */
                   8903: /*     }  */
                   8904: /*   } */
1.218     brouard  8905:   
1.227     brouard  8906: /*   /\* if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX); *\/ */
1.218     brouard  8907:   
1.227     brouard  8908: /*   if (popforecast==1) { */
                   8909: /*     free_ivector(popage,0,AGESUP); */
                   8910: /*     free_vector(popeffectif,0,AGESUP); */
                   8911: /*     free_vector(popcount,0,AGESUP); */
                   8912: /*   } */
                   8913: /*   free_ma3x(tabpop,1, AGESUP,1,NCOVMAX, 1,NCOVMAX); */
                   8914: /*   free_ma3x(tabpopprev,1, AGESUP,1,NCOVMAX, 1,NCOVMAX); */
                   8915: /*   fclose(ficrespop); */
                   8916: /* } /\* End of popforecast *\/ */
1.218     brouard  8917:  
1.126     brouard  8918: int fileappend(FILE *fichier, char *optionfich)
                   8919: {
                   8920:   if((fichier=fopen(optionfich,"a"))==NULL) {
                   8921:     printf("Problem with file: %s\n", optionfich);
                   8922:     fprintf(ficlog,"Problem with file: %s\n", optionfich);
                   8923:     return (0);
                   8924:   }
                   8925:   fflush(fichier);
                   8926:   return (1);
                   8927: }
                   8928: 
                   8929: 
                   8930: /**************** function prwizard **********************/
                   8931: void prwizard(int ncovmodel, int nlstate, int ndeath,  char model[], FILE *ficparo)
                   8932: {
                   8933: 
                   8934:   /* Wizard to print covariance matrix template */
                   8935: 
1.164     brouard  8936:   char ca[32], cb[32];
                   8937:   int i,j, k, li, lj, lk, ll, jj, npar, itimes;
1.126     brouard  8938:   int numlinepar;
                   8939: 
                   8940:   printf("# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
                   8941:   fprintf(ficparo,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
                   8942:   for(i=1; i <=nlstate; i++){
                   8943:     jj=0;
                   8944:     for(j=1; j <=nlstate+ndeath; j++){
                   8945:       if(j==i) continue;
                   8946:       jj++;
                   8947:       /*ca[0]= k+'a'-1;ca[1]='\0';*/
                   8948:       printf("%1d%1d",i,j);
                   8949:       fprintf(ficparo,"%1d%1d",i,j);
                   8950:       for(k=1; k<=ncovmodel;k++){
                   8951:        /*        printf(" %lf",param[i][j][k]); */
                   8952:        /*        fprintf(ficparo," %lf",param[i][j][k]); */
                   8953:        printf(" 0.");
                   8954:        fprintf(ficparo," 0.");
                   8955:       }
                   8956:       printf("\n");
                   8957:       fprintf(ficparo,"\n");
                   8958:     }
                   8959:   }
                   8960:   printf("# Scales (for hessian or gradient estimation)\n");
                   8961:   fprintf(ficparo,"# Scales (for hessian or gradient estimation)\n");
                   8962:   npar= (nlstate+ndeath-1)*nlstate*ncovmodel; /* Number of parameters*/ 
                   8963:   for(i=1; i <=nlstate; i++){
                   8964:     jj=0;
                   8965:     for(j=1; j <=nlstate+ndeath; j++){
                   8966:       if(j==i) continue;
                   8967:       jj++;
                   8968:       fprintf(ficparo,"%1d%1d",i,j);
                   8969:       printf("%1d%1d",i,j);
                   8970:       fflush(stdout);
                   8971:       for(k=1; k<=ncovmodel;k++){
                   8972:        /*      printf(" %le",delti3[i][j][k]); */
                   8973:        /*      fprintf(ficparo," %le",delti3[i][j][k]); */
                   8974:        printf(" 0.");
                   8975:        fprintf(ficparo," 0.");
                   8976:       }
                   8977:       numlinepar++;
                   8978:       printf("\n");
                   8979:       fprintf(ficparo,"\n");
                   8980:     }
                   8981:   }
                   8982:   printf("# Covariance matrix\n");
                   8983: /* # 121 Var(a12)\n\ */
                   8984: /* # 122 Cov(b12,a12) Var(b12)\n\ */
                   8985: /* # 131 Cov(a13,a12) Cov(a13,b12, Var(a13)\n\ */
                   8986: /* # 132 Cov(b13,a12) Cov(b13,b12, Cov(b13,a13) Var(b13)\n\ */
                   8987: /* # 212 Cov(a21,a12) Cov(a21,b12, Cov(a21,a13) Cov(a21,b13) Var(a21)\n\ */
                   8988: /* # 212 Cov(b21,a12) Cov(b21,b12, Cov(b21,a13) Cov(b21,b13) Cov(b21,a21) Var(b21)\n\ */
                   8989: /* # 232 Cov(a23,a12) Cov(a23,b12, Cov(a23,a13) Cov(a23,b13) Cov(a23,a21) Cov(a23,b21) Var(a23)\n\ */
                   8990: /* # 232 Cov(b23,a12) Cov(b23,b12) ... Var (b23)\n" */
                   8991:   fflush(stdout);
                   8992:   fprintf(ficparo,"# Covariance matrix\n");
                   8993:   /* # 121 Var(a12)\n\ */
                   8994:   /* # 122 Cov(b12,a12) Var(b12)\n\ */
                   8995:   /* #   ...\n\ */
                   8996:   /* # 232 Cov(b23,a12)  Cov(b23,b12) ... Var (b23)\n" */
                   8997:   
                   8998:   for(itimes=1;itimes<=2;itimes++){
                   8999:     jj=0;
                   9000:     for(i=1; i <=nlstate; i++){
                   9001:       for(j=1; j <=nlstate+ndeath; j++){
                   9002:        if(j==i) continue;
                   9003:        for(k=1; k<=ncovmodel;k++){
                   9004:          jj++;
                   9005:          ca[0]= k+'a'-1;ca[1]='\0';
                   9006:          if(itimes==1){
                   9007:            printf("#%1d%1d%d",i,j,k);
                   9008:            fprintf(ficparo,"#%1d%1d%d",i,j,k);
                   9009:          }else{
                   9010:            printf("%1d%1d%d",i,j,k);
                   9011:            fprintf(ficparo,"%1d%1d%d",i,j,k);
                   9012:            /*  printf(" %.5le",matcov[i][j]); */
                   9013:          }
                   9014:          ll=0;
                   9015:          for(li=1;li <=nlstate; li++){
                   9016:            for(lj=1;lj <=nlstate+ndeath; lj++){
                   9017:              if(lj==li) continue;
                   9018:              for(lk=1;lk<=ncovmodel;lk++){
                   9019:                ll++;
                   9020:                if(ll<=jj){
                   9021:                  cb[0]= lk +'a'-1;cb[1]='\0';
                   9022:                  if(ll<jj){
                   9023:                    if(itimes==1){
                   9024:                      printf(" Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
                   9025:                      fprintf(ficparo," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
                   9026:                    }else{
                   9027:                      printf(" 0.");
                   9028:                      fprintf(ficparo," 0.");
                   9029:                    }
                   9030:                  }else{
                   9031:                    if(itimes==1){
                   9032:                      printf(" Var(%s%1d%1d)",ca,i,j);
                   9033:                      fprintf(ficparo," Var(%s%1d%1d)",ca,i,j);
                   9034:                    }else{
                   9035:                      printf(" 0.");
                   9036:                      fprintf(ficparo," 0.");
                   9037:                    }
                   9038:                  }
                   9039:                }
                   9040:              } /* end lk */
                   9041:            } /* end lj */
                   9042:          } /* end li */
                   9043:          printf("\n");
                   9044:          fprintf(ficparo,"\n");
                   9045:          numlinepar++;
                   9046:        } /* end k*/
                   9047:       } /*end j */
                   9048:     } /* end i */
                   9049:   } /* end itimes */
                   9050: 
                   9051: } /* end of prwizard */
                   9052: /******************* Gompertz Likelihood ******************************/
                   9053: double gompertz(double x[])
                   9054: { 
                   9055:   double A,B,L=0.0,sump=0.,num=0.;
                   9056:   int i,n=0; /* n is the size of the sample */
                   9057: 
1.220     brouard  9058:   for (i=1;i<=imx ; i++) {
1.126     brouard  9059:     sump=sump+weight[i];
                   9060:     /*    sump=sump+1;*/
                   9061:     num=num+1;
                   9062:   }
                   9063:  
                   9064:  
                   9065:   /* for (i=0; i<=imx; i++) 
                   9066:      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]);*/
                   9067: 
                   9068:   for (i=1;i<=imx ; i++)
                   9069:     {
                   9070:       if (cens[i] == 1 && wav[i]>1)
                   9071:        A=-x[1]/(x[2])*(exp(x[2]*(agecens[i]-agegomp))-exp(x[2]*(ageexmed[i]-agegomp)));
                   9072:       
                   9073:       if (cens[i] == 0 && wav[i]>1)
                   9074:        A=-x[1]/(x[2])*(exp(x[2]*(agedc[i]-agegomp))-exp(x[2]*(ageexmed[i]-agegomp)))
                   9075:             +log(x[1]/YEARM)+x[2]*(agedc[i]-agegomp)+log(YEARM);  
                   9076:       
                   9077:       /*if (wav[i] > 1 && agecens[i] > 15) {*/ /* ??? */
                   9078:       if (wav[i] > 1 ) { /* ??? */
                   9079:        L=L+A*weight[i];
                   9080:        /*      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]);*/
                   9081:       }
                   9082:     }
                   9083: 
                   9084:  /*printf("x1=%2.9f x2=%2.9f x3=%2.9f L=%f\n",x[1],x[2],x[3],L);*/
                   9085:  
                   9086:   return -2*L*num/sump;
                   9087: }
                   9088: 
1.136     brouard  9089: #ifdef GSL
                   9090: /******************* Gompertz_f Likelihood ******************************/
                   9091: double gompertz_f(const gsl_vector *v, void *params)
                   9092: { 
                   9093:   double A,B,LL=0.0,sump=0.,num=0.;
                   9094:   double *x= (double *) v->data;
                   9095:   int i,n=0; /* n is the size of the sample */
                   9096: 
                   9097:   for (i=0;i<=imx-1 ; i++) {
                   9098:     sump=sump+weight[i];
                   9099:     /*    sump=sump+1;*/
                   9100:     num=num+1;
                   9101:   }
                   9102:  
                   9103:  
                   9104:   /* for (i=0; i<=imx; i++) 
                   9105:      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]);*/
                   9106:   printf("x[0]=%lf x[1]=%lf\n",x[0],x[1]);
                   9107:   for (i=1;i<=imx ; i++)
                   9108:     {
                   9109:       if (cens[i] == 1 && wav[i]>1)
                   9110:        A=-x[0]/(x[1])*(exp(x[1]*(agecens[i]-agegomp))-exp(x[1]*(ageexmed[i]-agegomp)));
                   9111:       
                   9112:       if (cens[i] == 0 && wav[i]>1)
                   9113:        A=-x[0]/(x[1])*(exp(x[1]*(agedc[i]-agegomp))-exp(x[1]*(ageexmed[i]-agegomp)))
                   9114:             +log(x[0]/YEARM)+x[1]*(agedc[i]-agegomp)+log(YEARM);  
                   9115:       
                   9116:       /*if (wav[i] > 1 && agecens[i] > 15) {*/ /* ??? */
                   9117:       if (wav[i] > 1 ) { /* ??? */
                   9118:        LL=LL+A*weight[i];
                   9119:        /*      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]);*/
                   9120:       }
                   9121:     }
                   9122: 
                   9123:  /*printf("x1=%2.9f x2=%2.9f x3=%2.9f L=%f\n",x[1],x[2],x[3],L);*/
                   9124:   printf("x[0]=%lf x[1]=%lf -2*LL*num/sump=%lf\n",x[0],x[1],-2*LL*num/sump);
                   9125:  
                   9126:   return -2*LL*num/sump;
                   9127: }
                   9128: #endif
                   9129: 
1.126     brouard  9130: /******************* Printing html file ***********/
1.201     brouard  9131: void printinghtmlmort(char fileresu[], char title[], char datafile[], int firstpass, \
1.126     brouard  9132:                  int lastpass, int stepm, int weightopt, char model[],\
                   9133:                  int imx,  double p[],double **matcov,double agemortsup){
                   9134:   int i,k;
                   9135: 
                   9136:   fprintf(fichtm,"<ul><li><h4>Result files </h4>\n Force of mortality. Parameters of the Gompertz fit (with confidence interval in brackets):<br>");
                   9137:   fprintf(fichtm,"  mu(age) =%lf*exp(%lf*(age-%d)) per year<br><br>",p[1],p[2],agegomp);
                   9138:   for (i=1;i<=2;i++) 
                   9139:     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  9140:   fprintf(fichtm,"<br><br><img src=\"graphmort.svg\">");
1.126     brouard  9141:   fprintf(fichtm,"</ul>");
                   9142: 
                   9143: fprintf(fichtm,"<ul><li><h4>Life table</h4>\n <br>");
                   9144: 
                   9145:  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>");
                   9146: 
                   9147:  for (k=agegomp;k<(agemortsup-2);k++) 
                   9148:    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]);
                   9149: 
                   9150:  
                   9151:   fflush(fichtm);
                   9152: }
                   9153: 
                   9154: /******************* Gnuplot file **************/
1.201     brouard  9155: void printinggnuplotmort(char fileresu[], char optionfilefiname[], double ageminpar, double agemaxpar, double fage , char pathc[], double p[]){
1.126     brouard  9156: 
                   9157:   char dirfileres[132],optfileres[132];
1.164     brouard  9158: 
1.126     brouard  9159:   int ng;
                   9160: 
                   9161: 
                   9162:   /*#ifdef windows */
                   9163:   fprintf(ficgp,"cd \"%s\" \n",pathc);
                   9164:     /*#endif */
                   9165: 
                   9166: 
                   9167:   strcpy(dirfileres,optionfilefiname);
                   9168:   strcpy(optfileres,"vpl");
1.199     brouard  9169:   fprintf(ficgp,"set out \"graphmort.svg\"\n "); 
1.126     brouard  9170:   fprintf(ficgp,"set xlabel \"Age\"\n set ylabel \"Force of mortality (per year)\" \n "); 
1.199     brouard  9171:   fprintf(ficgp, "set ter svg size 640, 480\n set log y\n"); 
1.145     brouard  9172:   /* fprintf(ficgp, "set size 0.65,0.65\n"); */
1.126     brouard  9173:   fprintf(ficgp,"plot [%d:100] %lf*exp(%lf*(x-%d))",agegomp,p[1],p[2],agegomp);
                   9174: 
                   9175: } 
                   9176: 
1.136     brouard  9177: int readdata(char datafile[], int firstobs, int lastobs, int *imax)
                   9178: {
1.126     brouard  9179: 
1.136     brouard  9180:   /*-------- data file ----------*/
                   9181:   FILE *fic;
                   9182:   char dummy[]="                         ";
1.240     brouard  9183:   int i=0, j=0, n=0, iv=0, v;
1.223     brouard  9184:   int lstra;
1.136     brouard  9185:   int linei, month, year,iout;
                   9186:   char line[MAXLINE], linetmp[MAXLINE];
1.164     brouard  9187:   char stra[MAXLINE], strb[MAXLINE];
1.136     brouard  9188:   char *stratrunc;
1.223     brouard  9189: 
1.240     brouard  9190:   DummyV=ivector(1,NCOVMAX); /* 1 to 3 */
                   9191:   FixedV=ivector(1,NCOVMAX); /* 1 to 3 */
1.126     brouard  9192: 
1.240     brouard  9193:   for(v=1; v <=ncovcol;v++){
                   9194:     DummyV[v]=0;
                   9195:     FixedV[v]=0;
                   9196:   }
                   9197:   for(v=ncovcol+1; v <=ncovcol+nqv;v++){
                   9198:     DummyV[v]=1;
                   9199:     FixedV[v]=0;
                   9200:   }
                   9201:   for(v=ncovcol+nqv+1; v <=ncovcol+nqv+ntv;v++){
                   9202:     DummyV[v]=0;
                   9203:     FixedV[v]=1;
                   9204:   }
                   9205:   for(v=ncovcol+nqv+ntv+1; v <=ncovcol+nqv+ntv+nqtv;v++){
                   9206:     DummyV[v]=1;
                   9207:     FixedV[v]=1;
                   9208:   }
                   9209:   for(v=1; v <=ncovcol+nqv+ntv+nqtv;v++){
                   9210:     printf("Covariate type in the data: V%d, DummyV(V%d)=%d, FixedV(V%d)=%d\n",v,v,DummyV[v],v,FixedV[v]);
                   9211:     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]);
                   9212:   }
1.126     brouard  9213: 
1.136     brouard  9214:   if((fic=fopen(datafile,"r"))==NULL)    {
1.218     brouard  9215:     printf("Problem while opening datafile: %s with errno='%s'\n", datafile,strerror(errno));fflush(stdout);
                   9216:     fprintf(ficlog,"Problem while opening datafile: %s with errno='%s'\n", datafile,strerror(errno));fflush(ficlog);return 1;
1.136     brouard  9217:   }
1.126     brouard  9218: 
1.136     brouard  9219:   i=1;
                   9220:   linei=0;
                   9221:   while ((fgets(line, MAXLINE, fic) != NULL) &&((i >= firstobs) && (i <=lastobs))) {
                   9222:     linei=linei+1;
                   9223:     for(j=strlen(line); j>=0;j--){  /* Untabifies line */
                   9224:       if(line[j] == '\t')
                   9225:        line[j] = ' ';
                   9226:     }
                   9227:     for(j=strlen(line)-1; (line[j]==' ')||(line[j]==10)||(line[j]==13);j--){
                   9228:       ;
                   9229:     };
                   9230:     line[j+1]=0;  /* Trims blanks at end of line */
                   9231:     if(line[0]=='#'){
                   9232:       fprintf(ficlog,"Comment line\n%s\n",line);
                   9233:       printf("Comment line\n%s\n",line);
                   9234:       continue;
                   9235:     }
                   9236:     trimbb(linetmp,line); /* Trims multiple blanks in line */
1.164     brouard  9237:     strcpy(line, linetmp);
1.223     brouard  9238:     
                   9239:     /* Loops on waves */
                   9240:     for (j=maxwav;j>=1;j--){
                   9241:       for (iv=nqtv;iv>=1;iv--){  /* Loop  on time varying quantitative variables */
1.238     brouard  9242:        cutv(stra, strb, line, ' '); 
                   9243:        if(strb[0]=='.') { /* Missing value */
                   9244:          lval=-1;
                   9245:          cotqvar[j][iv][i]=-1; /* 0.0/0.0 */
                   9246:          cotvar[j][ntv+iv][i]=-1; /* For performance reasons */
                   9247:          if(isalpha(strb[1])) { /* .m or .d Really Missing value */
                   9248:            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);
                   9249:            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);
                   9250:            return 1;
                   9251:          }
                   9252:        }else{
                   9253:          errno=0;
                   9254:          /* what_kind_of_number(strb); */
                   9255:          dval=strtod(strb,&endptr); 
                   9256:          /* if( strb[0]=='\0' || (*endptr != '\0')){ */
                   9257:          /* if(strb != endptr && *endptr == '\0') */
                   9258:          /*    dval=dlval; */
                   9259:          /* if (errno == ERANGE && (lval == LONG_MAX || lval == LONG_MIN)) */
                   9260:          if( strb[0]=='\0' || (*endptr != '\0')){
                   9261:            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);
                   9262:            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);
                   9263:            return 1;
                   9264:          }
                   9265:          cotqvar[j][iv][i]=dval; 
                   9266:          cotvar[j][ntv+iv][i]=dval; 
                   9267:        }
                   9268:        strcpy(line,stra);
1.223     brouard  9269:       }/* end loop ntqv */
1.225     brouard  9270:       
1.223     brouard  9271:       for (iv=ntv;iv>=1;iv--){  /* Loop  on time varying dummies */
1.238     brouard  9272:        cutv(stra, strb, line, ' '); 
                   9273:        if(strb[0]=='.') { /* Missing value */
                   9274:          lval=-1;
                   9275:        }else{
                   9276:          errno=0;
                   9277:          lval=strtol(strb,&endptr,10); 
                   9278:          /*    if (errno == ERANGE && (lval == LONG_MAX || lval == LONG_MIN))*/
                   9279:          if( strb[0]=='\0' || (*endptr != '\0')){
                   9280:            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);
                   9281:            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);
                   9282:            return 1;
                   9283:          }
                   9284:        }
                   9285:        if(lval <-1 || lval >1){
                   9286:          printf("Error reading data around '%ld' at line number %d for individual %d, '%s'\n \
1.223     brouard  9287:  Should be a value of %d(nth) covariate (0 should be the value for the reference and 1\n \
                   9288:  for the alternative. IMaCh does not build design variables automatically, do it yourself.\n \
1.238     brouard  9289:  For example, for multinomial values like 1, 2 and 3,\n                        \
                   9290:  build V1=0 V2=0 for the reference value (1),\n                                \
                   9291:         V1=1 V2=0 for (2) \n                                           \
1.223     brouard  9292:  and V1=0 V2=1 for (3). V1=1 V2=1 should not exist and the corresponding\n \
1.238     brouard  9293:  output of IMaCh is often meaningless.\n                               \
1.223     brouard  9294:  Exiting.\n",lval,linei, i,line,j);
1.238     brouard  9295:          fprintf(ficlog,"Error reading data around '%ld' at line number %d for individual %d, '%s'\n \
1.223     brouard  9296:  Should be a value of %d(nth) covariate (0 should be the value for the reference and 1\n \
                   9297:  for the alternative. IMaCh does not build design variables automatically, do it yourself.\n \
1.238     brouard  9298:  For example, for multinomial values like 1, 2 and 3,\n                        \
                   9299:  build V1=0 V2=0 for the reference value (1),\n                                \
                   9300:         V1=1 V2=0 for (2) \n                                           \
1.223     brouard  9301:  and V1=0 V2=1 for (3). V1=1 V2=1 should not exist and the corresponding\n \
1.238     brouard  9302:  output of IMaCh is often meaningless.\n                               \
1.223     brouard  9303:  Exiting.\n",lval,linei, i,line,j);fflush(ficlog);
1.238     brouard  9304:          return 1;
                   9305:        }
                   9306:        cotvar[j][iv][i]=(double)(lval);
                   9307:        strcpy(line,stra);
1.223     brouard  9308:       }/* end loop ntv */
1.225     brouard  9309:       
1.223     brouard  9310:       /* Statuses  at wave */
1.137     brouard  9311:       cutv(stra, strb, line, ' '); 
1.223     brouard  9312:       if(strb[0]=='.') { /* Missing value */
1.238     brouard  9313:        lval=-1;
1.136     brouard  9314:       }else{
1.238     brouard  9315:        errno=0;
                   9316:        lval=strtol(strb,&endptr,10); 
                   9317:        /*      if (errno == ERANGE && (lval == LONG_MAX || lval == LONG_MIN))*/
                   9318:        if( strb[0]=='\0' || (*endptr != '\0')){
                   9319:          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);
                   9320:          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);
                   9321:          return 1;
                   9322:        }
1.136     brouard  9323:       }
1.225     brouard  9324:       
1.136     brouard  9325:       s[j][i]=lval;
1.225     brouard  9326:       
1.223     brouard  9327:       /* Date of Interview */
1.136     brouard  9328:       strcpy(line,stra);
                   9329:       cutv(stra, strb,line,' ');
1.169     brouard  9330:       if( (iout=sscanf(strb,"%d/%d",&month, &year)) != 0){
1.136     brouard  9331:       }
1.169     brouard  9332:       else  if( (iout=sscanf(strb,"%s.",dummy)) != 0){
1.225     brouard  9333:        month=99;
                   9334:        year=9999;
1.136     brouard  9335:       }else{
1.225     brouard  9336:        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);
                   9337:        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);
                   9338:        return 1;
1.136     brouard  9339:       }
                   9340:       anint[j][i]= (double) year; 
                   9341:       mint[j][i]= (double)month; 
                   9342:       strcpy(line,stra);
1.223     brouard  9343:     } /* End loop on waves */
1.225     brouard  9344:     
1.223     brouard  9345:     /* Date of death */
1.136     brouard  9346:     cutv(stra, strb,line,' '); 
1.169     brouard  9347:     if( (iout=sscanf(strb,"%d/%d",&month, &year)) != 0){
1.136     brouard  9348:     }
1.169     brouard  9349:     else  if( (iout=sscanf(strb,"%s.",dummy)) != 0){
1.136     brouard  9350:       month=99;
                   9351:       year=9999;
                   9352:     }else{
1.141     brouard  9353:       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  9354:       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);
                   9355:       return 1;
1.136     brouard  9356:     }
                   9357:     andc[i]=(double) year; 
                   9358:     moisdc[i]=(double) month; 
                   9359:     strcpy(line,stra);
                   9360:     
1.223     brouard  9361:     /* Date of birth */
1.136     brouard  9362:     cutv(stra, strb,line,' '); 
1.169     brouard  9363:     if( (iout=sscanf(strb,"%d/%d",&month, &year)) != 0){
1.136     brouard  9364:     }
1.169     brouard  9365:     else  if( (iout=sscanf(strb,"%s.", dummy)) != 0){
1.136     brouard  9366:       month=99;
                   9367:       year=9999;
                   9368:     }else{
1.141     brouard  9369:       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);
                   9370:       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  9371:       return 1;
1.136     brouard  9372:     }
                   9373:     if (year==9999) {
1.141     brouard  9374:       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);
                   9375:       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  9376:       return 1;
                   9377:       
1.136     brouard  9378:     }
                   9379:     annais[i]=(double)(year);
                   9380:     moisnais[i]=(double)(month); 
                   9381:     strcpy(line,stra);
1.225     brouard  9382:     
1.223     brouard  9383:     /* Sample weight */
1.136     brouard  9384:     cutv(stra, strb,line,' '); 
                   9385:     errno=0;
                   9386:     dval=strtod(strb,&endptr); 
                   9387:     if( strb[0]=='\0' || (*endptr != '\0')){
1.141     brouard  9388:       printf("Error reading data around '%f' at line number %d, \"%s\" for individual %d\nShould be a weight.  Exiting.\n",dval, i,line,linei);
                   9389:       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  9390:       fflush(ficlog);
                   9391:       return 1;
                   9392:     }
                   9393:     weight[i]=dval; 
                   9394:     strcpy(line,stra);
1.225     brouard  9395:     
1.223     brouard  9396:     for (iv=nqv;iv>=1;iv--){  /* Loop  on fixed quantitative variables */
                   9397:       cutv(stra, strb, line, ' '); 
                   9398:       if(strb[0]=='.') { /* Missing value */
1.225     brouard  9399:        lval=-1;
1.223     brouard  9400:       }else{
1.225     brouard  9401:        errno=0;
                   9402:        /* what_kind_of_number(strb); */
                   9403:        dval=strtod(strb,&endptr);
                   9404:        /* if(strb != endptr && *endptr == '\0') */
                   9405:        /*   dval=dlval; */
                   9406:        /* if (errno == ERANGE && (lval == LONG_MAX || lval == LONG_MIN)) */
                   9407:        if( strb[0]=='\0' || (*endptr != '\0')){
                   9408:          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);
                   9409:          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);
                   9410:          return 1;
                   9411:        }
                   9412:        coqvar[iv][i]=dval; 
1.226     brouard  9413:        covar[ncovcol+iv][i]=dval; /* including qvar in standard covar for performance reasons */ 
1.223     brouard  9414:       }
                   9415:       strcpy(line,stra);
                   9416:     }/* end loop nqv */
1.136     brouard  9417:     
1.223     brouard  9418:     /* Covariate values */
1.136     brouard  9419:     for (j=ncovcol;j>=1;j--){
                   9420:       cutv(stra, strb,line,' '); 
1.223     brouard  9421:       if(strb[0]=='.') { /* Missing covariate value */
1.225     brouard  9422:        lval=-1;
1.136     brouard  9423:       }else{
1.225     brouard  9424:        errno=0;
                   9425:        lval=strtol(strb,&endptr,10); 
                   9426:        if( strb[0]=='\0' || (*endptr != '\0')){
                   9427:          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);
                   9428:          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);
                   9429:          return 1;
                   9430:        }
1.136     brouard  9431:       }
                   9432:       if(lval <-1 || lval >1){
1.225     brouard  9433:        printf("Error reading data around '%ld' at line number %d for individual %d, '%s'\n \
1.136     brouard  9434:  Should be a value of %d(nth) covariate (0 should be the value for the reference and 1\n \
                   9435:  for the alternative. IMaCh does not build design variables automatically, do it yourself.\n \
1.225     brouard  9436:  For example, for multinomial values like 1, 2 and 3,\n                        \
                   9437:  build V1=0 V2=0 for the reference value (1),\n                                \
                   9438:         V1=1 V2=0 for (2) \n                                           \
1.136     brouard  9439:  and V1=0 V2=1 for (3). V1=1 V2=1 should not exist and the corresponding\n \
1.225     brouard  9440:  output of IMaCh is often meaningless.\n                               \
1.136     brouard  9441:  Exiting.\n",lval,linei, i,line,j);
1.225     brouard  9442:        fprintf(ficlog,"Error reading data around '%ld' at line number %d for individual %d, '%s'\n \
1.136     brouard  9443:  Should be a value of %d(nth) covariate (0 should be the value for the reference and 1\n \
                   9444:  for the alternative. IMaCh does not build design variables automatically, do it yourself.\n \
1.225     brouard  9445:  For example, for multinomial values like 1, 2 and 3,\n                        \
                   9446:  build V1=0 V2=0 for the reference value (1),\n                                \
                   9447:         V1=1 V2=0 for (2) \n                                           \
1.136     brouard  9448:  and V1=0 V2=1 for (3). V1=1 V2=1 should not exist and the corresponding\n \
1.225     brouard  9449:  output of IMaCh is often meaningless.\n                               \
1.136     brouard  9450:  Exiting.\n",lval,linei, i,line,j);fflush(ficlog);
1.225     brouard  9451:        return 1;
1.136     brouard  9452:       }
                   9453:       covar[j][i]=(double)(lval);
                   9454:       strcpy(line,stra);
                   9455:     }  
                   9456:     lstra=strlen(stra);
1.225     brouard  9457:     
1.136     brouard  9458:     if(lstra > 9){ /* More than 2**32 or max of what printf can write with %ld */
                   9459:       stratrunc = &(stra[lstra-9]);
                   9460:       num[i]=atol(stratrunc);
                   9461:     }
                   9462:     else
                   9463:       num[i]=atol(stra);
                   9464:     /*if((s[2][i]==2) && (s[3][i]==-1)&&(s[4][i]==9)){
                   9465:       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;}*/
                   9466:     
                   9467:     i=i+1;
                   9468:   } /* End loop reading  data */
1.225     brouard  9469:   
1.136     brouard  9470:   *imax=i-1; /* Number of individuals */
                   9471:   fclose(fic);
1.225     brouard  9472:   
1.136     brouard  9473:   return (0);
1.164     brouard  9474:   /* endread: */
1.225     brouard  9475:   printf("Exiting readdata: ");
                   9476:   fclose(fic);
                   9477:   return (1);
1.223     brouard  9478: }
1.126     brouard  9479: 
1.234     brouard  9480: void removefirstspace(char **stri){/*, char stro[]) {*/
1.230     brouard  9481:   char *p1 = *stri, *p2 = *stri;
1.235     brouard  9482:   while (*p2 == ' ')
1.234     brouard  9483:     p2++; 
                   9484:   /* while ((*p1++ = *p2++) !=0) */
                   9485:   /*   ; */
                   9486:   /* do */
                   9487:   /*   while (*p2 == ' ') */
                   9488:   /*     p2++; */
                   9489:   /* while (*p1++ == *p2++); */
                   9490:   *stri=p2; 
1.145     brouard  9491: }
                   9492: 
1.235     brouard  9493: int decoderesult ( char resultline[], int nres)
1.230     brouard  9494: /**< This routine decode one result line and returns the combination # of dummy covariates only **/
                   9495: {
1.235     brouard  9496:   int j=0, k=0, k1=0, k2=0, k3=0, k4=0, match=0, k2q=0, k3q=0, k4q=0;
1.230     brouard  9497:   char resultsav[MAXLINE];
1.234     brouard  9498:   int resultmodel[MAXLINE];
                   9499:   int modelresult[MAXLINE];
1.230     brouard  9500:   char stra[80], strb[80], strc[80], strd[80],stre[80];
                   9501: 
1.234     brouard  9502:   removefirstspace(&resultline);
1.233     brouard  9503:   printf("decoderesult:%s\n",resultline);
1.230     brouard  9504: 
                   9505:   if (strstr(resultline,"v") !=0){
                   9506:     printf("Error. 'v' must be in upper case 'V' result: %s ",resultline);
                   9507:     fprintf(ficlog,"Error. 'v' must be in upper case result: %s ",resultline);fflush(ficlog);
                   9508:     return 1;
                   9509:   }
                   9510:   trimbb(resultsav, resultline);
                   9511:   if (strlen(resultsav) >1){
                   9512:     j=nbocc(resultsav,'='); /**< j=Number of covariate values'=' */
                   9513:   }
1.253     brouard  9514:   if(j == 0){ /* Resultline but no = */
                   9515:     TKresult[nres]=0; /* Combination for the nresult and the model */
                   9516:     return (0);
                   9517:   }
                   9518:     
1.234     brouard  9519:   if( j != cptcovs ){ /* Be careful if a variable is in a product but not single */
                   9520:     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);
                   9521:     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);
                   9522:   }
                   9523:   for(k=1; k<=j;k++){ /* Loop on any covariate of the result line */
                   9524:     if(nbocc(resultsav,'=') >1){
                   9525:        cutl(stra,strb,resultsav,' '); /* keeps in strb after the first ' ' 
                   9526:                                      resultsav= V4=1 V5=25.1 V3=0 strb=V3=0 stra= V4=1 V5=25.1 */
                   9527:        cutl(strc,strd,strb,'=');  /* strb:V4=1 strc=1 strd=V4 */
                   9528:     }else
                   9529:       cutl(strc,strd,resultsav,'=');
1.230     brouard  9530:     Tvalsel[k]=atof(strc); /* 1 */
1.234     brouard  9531:     
1.230     brouard  9532:     cutl(strc,stre,strd,'V'); /* strd='V4' strc=4 stre='V' */;
                   9533:     Tvarsel[k]=atoi(strc);
                   9534:     /* Typevarsel[k]=1;  /\* 1 for age product *\/ */
                   9535:     /* cptcovsel++;     */
                   9536:     if (nbocc(stra,'=') >0)
                   9537:       strcpy(resultsav,stra); /* and analyzes it */
                   9538:   }
1.235     brouard  9539:   /* Checking for missing or useless values in comparison of current model needs */
1.236     brouard  9540:   for(k1=1; k1<= cptcovt ;k1++){ /* model line V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
                   9541:     if(Typevar[k1]==0){ /* Single covariate in model */
1.234     brouard  9542:       match=0;
1.236     brouard  9543:       for(k2=1; k2 <=j;k2++){/* result line V4=1 V5=24.1 V3=1  V2=8 V1=0 */
1.237     brouard  9544:        if(Tvar[k1]==Tvarsel[k2]) {/* Tvar[1]=5 == Tvarsel[2]=5   */
1.236     brouard  9545:          modelresult[k2]=k1;/* modelresult[2]=1 modelresult[1]=2  modelresult[3]=3  modelresult[6]=4 modelresult[9]=5 */
1.234     brouard  9546:          match=1;
                   9547:          break;
                   9548:        }
                   9549:       }
                   9550:       if(match == 0){
                   9551:        printf("Error in result line: %d value missing; result: %s, model=%s\n",k1, resultline, model);
                   9552:       }
                   9553:     }
                   9554:   }
1.235     brouard  9555:   /* Checking for missing or useless values in comparison of current model needs */
                   9556:   for(k2=1; k2 <=j;k2++){ /* result line V4=1 V5=24.1 V3=1  V2=8 V1=0 */
1.234     brouard  9557:     match=0;
1.235     brouard  9558:     for(k1=1; k1<= cptcovt ;k1++){ /* model line V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
                   9559:       if(Typevar[k1]==0){ /* Single */
1.237     brouard  9560:        if(Tvar[k1]==Tvarsel[k2]) { /* Tvar[2]=4 == Tvarsel[1]=4   */
1.235     brouard  9561:          resultmodel[k1]=k2;  /* resultmodel[2]=1 resultmodel[1]=2  resultmodel[3]=3  resultmodel[6]=4 resultmodel[9]=5 */
1.234     brouard  9562:          ++match;
                   9563:        }
                   9564:       }
                   9565:     }
                   9566:     if(match == 0){
                   9567:       printf("Error in result line: %d value missing; result: %s, model=%s\n",k1, resultline, model);
                   9568:     }else if(match > 1){
                   9569:       printf("Error in result line: %d doubled; result: %s, model=%s\n",k2, resultline, model);
                   9570:     }
                   9571:   }
1.235     brouard  9572:       
1.234     brouard  9573:   /* We need to deduce which combination number is chosen and save quantitative values */
1.235     brouard  9574:   /* model line V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
                   9575:   /* result line V4=1 V5=25.1 V3=0  V2=8 V1=1 */
                   9576:   /* should give a combination of dummy V4=1, V3=0, V1=1 => V4*2**(0) + V3*2**(1) + V1*2**(2) = 5 + (1offset) = 6*/
                   9577:   /* result line V4=1 V5=24.1 V3=1  V2=8 V1=0 */
                   9578:   /* should give a combination of dummy V4=1, V3=1, V1=0 => V4*2**(0) + V3*2**(1) + V1*2**(2) = 3 + (1offset) = 4*/
                   9579:   /*    1 0 0 0 */
                   9580:   /*    2 1 0 0 */
                   9581:   /*    3 0 1 0 */ 
                   9582:   /*    4 1 1 0 */ /* V4=1, V3=1, V1=0 */
                   9583:   /*    5 0 0 1 */
                   9584:   /*    6 1 0 1 */ /* V4=1, V3=0, V1=1 */
                   9585:   /*    7 0 1 1 */
                   9586:   /*    8 1 1 1 */
1.237     brouard  9587:   /* V(Tvresult)=Tresult V4=1 V3=0 V1=1 Tresult[nres=1][2]=0 */
                   9588:   /* V(Tvqresult)=Tqresult V5=25.1 V2=8 Tqresult[nres=1][1]=25.1 */
                   9589:   /* V5*age V5 known which value for nres?  */
                   9590:   /* Tqinvresult[2]=8 Tqinvresult[1]=25.1  */
1.235     brouard  9591:   for(k1=1, k=0, k4=0, k4q=0; k1 <=cptcovt;k1++){ /* model line */
                   9592:     if( Dummy[k1]==0 && Typevar[k1]==0 ){ /* Single dummy */
1.237     brouard  9593:       k3= resultmodel[k1]; /* resultmodel[2(V4)] = 1=k3 */
1.235     brouard  9594:       k2=(int)Tvarsel[k3]; /*  Tvarsel[resultmodel[2]]= Tvarsel[1] = 4=k2 */
                   9595:       k+=Tvalsel[k3]*pow(2,k4);  /*  Tvalsel[1]=1  */
1.237     brouard  9596:       Tresult[nres][k4+1]=Tvalsel[k3];/* Tresult[nres][1]=1(V4=1)  Tresult[nres][2]=0(V3=0) */
                   9597:       Tvresult[nres][k4+1]=(int)Tvarsel[k3];/* Tvresult[nres][1]=4 Tvresult[nres][3]=1 */
                   9598:       Tinvresult[nres][(int)Tvarsel[k3]]=Tvalsel[k3]; /* Tinvresult[nres][4]=1 */
1.235     brouard  9599:       printf("Decoderesult Dummy k=%d, V(k2=V%d)= Tvalsel[%d]=%d, 2**(%d)\n",k, k2, k3, (int)Tvalsel[k3], k4);
                   9600:       k4++;;
                   9601:     }  else if( Dummy[k1]==1 && Typevar[k1]==0 ){ /* Single quantitative */
                   9602:       k3q= resultmodel[k1]; /* resultmodel[2] = 1=k3 */
                   9603:       k2q=(int)Tvarsel[k3q]; /*  Tvarsel[resultmodel[2]]= Tvarsel[1] = 4=k2 */
1.237     brouard  9604:       Tqresult[nres][k4q+1]=Tvalsel[k3q]; /* Tqresult[nres][1]=25.1 */
                   9605:       Tvqresult[nres][k4q+1]=(int)Tvarsel[k3q]; /* Tvqresult[nres][1]=5 */
                   9606:       Tqinvresult[nres][(int)Tvarsel[k3q]]=Tvalsel[k3q]; /* Tqinvresult[nres][5]=25.1 */
1.235     brouard  9607:       printf("Decoderesult Quantitative nres=%d, V(k2q=V%d)= Tvalsel[%d]=%d, Tvarsel[%d]=%f\n",nres, k2q, k3q, Tvarsel[k3q], k3q, Tvalsel[k3q]);
                   9608:       k4q++;;
                   9609:     }
                   9610:   }
1.234     brouard  9611:   
1.235     brouard  9612:   TKresult[nres]=++k; /* Combination for the nresult and the model */
1.230     brouard  9613:   return (0);
                   9614: }
1.235     brouard  9615: 
1.230     brouard  9616: int decodemodel( char model[], int lastobs)
                   9617:  /**< This routine decodes the model and returns:
1.224     brouard  9618:        * Model  V1+V2+V3+V8+V7*V8+V5*V6+V8*age+V3*age+age*age
                   9619:        * - nagesqr = 1 if age*age in the model, otherwise 0.
                   9620:        * - cptcovt total number of covariates of the model nbocc(+)+1 = 8 excepting constant and age and age*age
                   9621:        * - cptcovn or number of covariates k of the models excluding age*products =6 and age*age
                   9622:        * - cptcovage number of covariates with age*products =2
                   9623:        * - cptcovs number of simple covariates
                   9624:        * - 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
                   9625:        *     which is a new column after the 9 (ncovcol) variables. 
                   9626:        * - if k is a product Vn*Vm covar[k][i] is filled with correct values for each individual
                   9627:        * - Tprod[l] gives the kth covariates of the product Vn*Vm l=1 to cptcovprod-cptcovage
                   9628:        *    Tprod[1]@2 {5, 6}: position of first product V7*V8 is 5, and second V5*V6 is 6.
                   9629:        * - Tvard[k]  p Tvard[1][1]@4 {7, 8, 5, 6} for V7*V8 and V5*V6 .
                   9630:        */
1.136     brouard  9631: {
1.238     brouard  9632:   int i, j, k, ks, v;
1.227     brouard  9633:   int  j1, k1, k2, k3, k4;
1.136     brouard  9634:   char modelsav[80];
1.145     brouard  9635:   char stra[80], strb[80], strc[80], strd[80],stre[80];
1.187     brouard  9636:   char *strpt;
1.136     brouard  9637: 
1.145     brouard  9638:   /*removespace(model);*/
1.136     brouard  9639:   if (strlen(model) >1){ /* If there is at least 1 covariate */
1.145     brouard  9640:     j=0, j1=0, k1=0, k2=-1, ks=0, cptcovn=0;
1.137     brouard  9641:     if (strstr(model,"AGE") !=0){
1.192     brouard  9642:       printf("Error. AGE must be in lower case 'age' model=1+age+%s. ",model);
                   9643:       fprintf(ficlog,"Error. AGE must be in lower case model=1+age+%s. ",model);fflush(ficlog);
1.136     brouard  9644:       return 1;
                   9645:     }
1.141     brouard  9646:     if (strstr(model,"v") !=0){
                   9647:       printf("Error. 'v' must be in upper case 'V' model=%s ",model);
                   9648:       fprintf(ficlog,"Error. 'v' must be in upper case model=%s ",model);fflush(ficlog);
                   9649:       return 1;
                   9650:     }
1.187     brouard  9651:     strcpy(modelsav,model); 
                   9652:     if ((strpt=strstr(model,"age*age")) !=0){
                   9653:       printf(" strpt=%s, model=%s\n",strpt, model);
                   9654:       if(strpt != model){
1.234     brouard  9655:        printf("Error in model: 'model=%s'; 'age*age' should in first place before other covariates\n \
1.192     brouard  9656:  'model=1+age+age*age+V1.' or 'model=1+age+age*age+V1+V1*age.', please swap as well as \n \
1.187     brouard  9657:  corresponding column of parameters.\n",model);
1.234     brouard  9658:        fprintf(ficlog,"Error in model: 'model=%s'; 'age*age' should in first place before other covariates\n \
1.192     brouard  9659:  'model=1+age+age*age+V1.' or 'model=1+age+age*age+V1+V1*age.', please swap as well as \n \
1.187     brouard  9660:  corresponding column of parameters.\n",model); fflush(ficlog);
1.234     brouard  9661:        return 1;
1.225     brouard  9662:       }
1.187     brouard  9663:       nagesqr=1;
                   9664:       if (strstr(model,"+age*age") !=0)
1.234     brouard  9665:        substrchaine(modelsav, model, "+age*age");
1.187     brouard  9666:       else if (strstr(model,"age*age+") !=0)
1.234     brouard  9667:        substrchaine(modelsav, model, "age*age+");
1.187     brouard  9668:       else 
1.234     brouard  9669:        substrchaine(modelsav, model, "age*age");
1.187     brouard  9670:     }else
                   9671:       nagesqr=0;
                   9672:     if (strlen(modelsav) >1){
                   9673:       j=nbocc(modelsav,'+'); /**< j=Number of '+' */
                   9674:       j1=nbocc(modelsav,'*'); /**< j1=Number of '*' */
1.224     brouard  9675:       cptcovs=j+1-j1; /**<  Number of simple covariates V1+V1*age+V3 +V3*V4+age*age=> V1 + V3 =5-3=2  */
1.187     brouard  9676:       cptcovt= j+1; /* Number of total covariates in the model, not including
1.225     brouard  9677:                     * cst, age and age*age 
                   9678:                     * V1+V1*age+ V3 + V3*V4+age*age=> 3+1=4*/
                   9679:       /* including age products which are counted in cptcovage.
                   9680:        * but the covariates which are products must be treated 
                   9681:        * separately: ncovn=4- 2=2 (V1+V3). */
1.187     brouard  9682:       cptcovprod=j1; /**< Number of products  V1*V2 +v3*age = 2 */
                   9683:       cptcovprodnoage=0; /**< Number of covariate products without age: V3*V4 =1  */
1.225     brouard  9684:       
                   9685:       
1.187     brouard  9686:       /*   Design
                   9687:        *  V1   V2   V3   V4  V5  V6  V7  V8  V9 Weight
                   9688:        *  <          ncovcol=8                >
                   9689:        * Model V2 + V1 + V3*age + V3 + V5*V6 + V7*V8 + V8*age + V8
                   9690:        *   k=  1    2      3       4     5       6      7        8
                   9691:        *  cptcovn number of covariates (not including constant and age ) = # of + plus 1 = 7+1=8
                   9692:        *  covar[k,i], value of kth covariate if not including age for individual i:
1.224     brouard  9693:        *       covar[1][i]= (V1), covar[4][i]=(V4), covar[8][i]=(V8)
                   9694:        *  Tvar[k] # of the kth covariate:  Tvar[1]=2  Tvar[2]=1 Tvar[4]=3 Tvar[8]=8
1.187     brouard  9695:        *       if multiplied by age: V3*age Tvar[3=V3*age]=3 (V3) Tvar[7]=8 and 
                   9696:        *  Tage[++cptcovage]=k
                   9697:        *       if products, new covar are created after ncovcol with k1
                   9698:        *  Tvar[k]=ncovcol+k1; # of the kth covariate product:  Tvar[5]=ncovcol+1=10  Tvar[6]=ncovcol+1=11
                   9699:        *  Tprod[k1]=k; Tprod[1]=5 Tprod[2]= 6; gives the position of the k1th product
                   9700:        *  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
                   9701:        *  Tvar[cptcovn+k2]=Tvard[k1][1];Tvar[cptcovn+k2+1]=Tvard[k1][2];
                   9702:        *  Tvar[8+1]=5;Tvar[8+2]=6;Tvar[8+3]=7;Tvar[8+4]=8 inverted
                   9703:        *  V1   V2   V3   V4  V5  V6  V7  V8  V9  V10  V11
                   9704:        *  <          ncovcol=8                >
                   9705:        *       Model V2 + V1 + V3*age + V3 + V5*V6 + V7*V8 + V8*age + V8    d1   d1   d2  d2
                   9706:        *          k=  1    2      3       4     5       6      7        8    9   10   11  12
                   9707:        *     Tvar[k]= 2    1      3       3    10      11      8        8    5    6    7   8
                   9708:        * p Tvar[1]@12={2,   1,     3,      3,   11,     10,     8,       8,   7,   8,   5,  6}
                   9709:        * p Tprod[1]@2={                         6, 5}
                   9710:        *p Tvard[1][1]@4= {7, 8, 5, 6}
                   9711:        * covar[k][i]= V2   V1      ?      V3    V5*V6?   V7*V8?  ?       V8   
                   9712:        *  cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];
                   9713:        *How to reorganize?
                   9714:        * Model V1 + V2 + V3 + V8 + V5*V6 + V7*V8 + V3*age + V8*age
                   9715:        * Tvars {2,   1,     3,      3,   11,     10,     8,       8,   7,   8,   5,  6}
                   9716:        *       {2,   1,     4,      8,    5,      6,     3,       7}
                   9717:        * Struct []
                   9718:        */
1.225     brouard  9719:       
1.187     brouard  9720:       /* This loop fills the array Tvar from the string 'model'.*/
                   9721:       /* j is the number of + signs in the model V1+V2+V3 j=2 i=3 to 1 */
                   9722:       /*   modelsav=V2+V1+V4+age*V3 strb=age*V3 stra=V2+V1+V4  */
                   9723:       /*       k=4 (age*V3) Tvar[k=4]= 3 (from V3) Tage[cptcovage=1]=4 */
                   9724:       /*       k=3 V4 Tvar[k=3]= 4 (from V4) */
                   9725:       /*       k=2 V1 Tvar[k=2]= 1 (from V1) */
                   9726:       /*       k=1 Tvar[1]=2 (from V2) */
                   9727:       /*       k=5 Tvar[5] */
                   9728:       /* for (k=1; k<=cptcovn;k++) { */
1.198     brouard  9729:       /*       cov[2+k]=nbcode[Tvar[k]][codtabm(ij,Tvar[k])]; */
1.187     brouard  9730:       /*       } */
1.198     brouard  9731:       /* for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,Tvar[Tage[k])]]*cov[2]; */
1.187     brouard  9732:       /*
                   9733:        * Treating invertedly V2+V1+V3*age+V2*V4 is as if written V2*V4 +V3*age + V1 + V2 */
1.227     brouard  9734:       for(k=cptcovt; k>=1;k--){ /**< Number of covariates not including constant and age, neither age*age*/
                   9735:         Tvar[k]=0; Tprod[k]=0; Tposprod[k]=0;
                   9736:       }
1.187     brouard  9737:       cptcovage=0;
                   9738:       for(k=1; k<=cptcovt;k++){ /* Loop on total covariates of the model */
1.234     brouard  9739:        cutl(stra,strb,modelsav,'+'); /* keeps in strb after the first '+' 
1.225     brouard  9740:                                         modelsav==V2+V1+V4+V3*age strb=V3*age stra=V2+V1+V4 */ 
1.234     brouard  9741:        if (nbocc(modelsav,'+')==0) strcpy(strb,modelsav); /* and analyzes it */
                   9742:        /*      printf("i=%d a=%s b=%s sav=%s\n",i, stra,strb,modelsav);*/
                   9743:        /*scanf("%d",i);*/
                   9744:        if (strchr(strb,'*')) {  /**< Model includes a product V2+V1+V4+V3*age strb=V3*age */
                   9745:          cutl(strc,strd,strb,'*'); /**< strd*strc  Vm*Vn: strb=V3*age(input) strc=age strd=V3 ; V3*V2 strc=V2, strd=V3 */
                   9746:          if (strcmp(strc,"age")==0) { /**< Model includes age: Vn*age */
                   9747:            /* covar is not filled and then is empty */
                   9748:            cptcovprod--;
                   9749:            cutl(stre,strb,strd,'V'); /* strd=V3(input): stre="3" */
                   9750:            Tvar[k]=atoi(stre);  /* V2+V1+V4+V3*age Tvar[4]=3 ; V1+V2*age Tvar[2]=2; V1+V1*age Tvar[2]=1 */
                   9751:            Typevar[k]=1;  /* 1 for age product */
                   9752:            cptcovage++; /* Sums the number of covariates which include age as a product */
                   9753:            Tage[cptcovage]=k;  /* Tvar[4]=3, Tage[1] = 4 or V1+V1*age Tvar[2]=1, Tage[1]=2 */
                   9754:            /*printf("stre=%s ", stre);*/
                   9755:          } else if (strcmp(strd,"age")==0) { /* or age*Vn */
                   9756:            cptcovprod--;
                   9757:            cutl(stre,strb,strc,'V');
                   9758:            Tvar[k]=atoi(stre);
                   9759:            Typevar[k]=1;  /* 1 for age product */
                   9760:            cptcovage++;
                   9761:            Tage[cptcovage]=k;
                   9762:          } else {  /* Age is not in the model product V2+V1+V1*V4+V3*age+V3*V2  strb=V3*V2*/
                   9763:            /* loops on k1=1 (V3*V2) and k1=2 V4*V3 */
                   9764:            cptcovn++;
                   9765:            cptcovprodnoage++;k1++;
                   9766:            cutl(stre,strb,strc,'V'); /* strc= Vn, stre is n; strb=V3*V2 stre=3 strc=*/
                   9767:            Tvar[k]=ncovcol+nqv+ntv+nqtv+k1; /* For model-covariate k tells which data-covariate to use but
                   9768:                                                because this model-covariate is a construction we invent a new column
                   9769:                                                which is after existing variables ncovcol+nqv+ntv+nqtv + k1
                   9770:                                                If already ncovcol=4 and model=V2+V1+V1*V4+age*V3+V3*V2
                   9771:                                                Tvar[3=V1*V4]=4+1 Tvar[5=V3*V2]=4 + 2= 6, etc */
                   9772:            Typevar[k]=2;  /* 2 for double fixed dummy covariates */
                   9773:            cutl(strc,strb,strd,'V'); /* strd was Vm, strc is m */
                   9774:            Tprod[k1]=k;  /* Tprod[1]=3(=V1*V4) for V2+V1+V1*V4+age*V3+V3*V2  */
                   9775:            Tposprod[k]=k1; /* Tpsprod[3]=1, Tposprod[2]=5 */
                   9776:            Tvard[k1][1] =atoi(strc); /* m 1 for V1*/
                   9777:            Tvard[k1][2] =atoi(stre); /* n 4 for V4*/
                   9778:            k2=k2+2;  /* k2 is initialize to -1, We want to store the n and m in Vn*Vm at the end of Tvar */
                   9779:            /* Tvar[cptcovt+k2]=Tvard[k1][1]; /\* Tvar[(cptcovt=4+k2=1)=5]= 1 (V1) *\/ */
                   9780:            /* Tvar[cptcovt+k2+1]=Tvard[k1][2];  /\* Tvar[(cptcovt=4+(k2=1)+1)=6]= 4 (V4) *\/ */
1.225     brouard  9781:             /*ncovcol=4 and model=V2+V1+V1*V4+age*V3+V3*V2, Tvar[3]=5, Tvar[4]=6, cptcovt=5 */
1.234     brouard  9782:            /*                     1  2   3      4     5 | Tvar[5+1)=1, Tvar[7]=2   */
                   9783:            for (i=1; i<=lastobs;i++){
                   9784:              /* Computes the new covariate which is a product of
                   9785:                 covar[n][i]* covar[m][i] and stores it at ncovol+k1 May not be defined */
                   9786:              covar[ncovcol+k1][i]=covar[atoi(stre)][i]*covar[atoi(strc)][i];
                   9787:            }
                   9788:          } /* End age is not in the model */
                   9789:        } /* End if model includes a product */
                   9790:        else { /* no more sum */
                   9791:          /*printf("d=%s c=%s b=%s\n", strd,strc,strb);*/
                   9792:          /*  scanf("%d",i);*/
                   9793:          cutl(strd,strc,strb,'V');
                   9794:          ks++; /**< Number of simple covariates dummy or quantitative, fixe or varying */
                   9795:          cptcovn++; /** V4+V3+V5: V4 and V3 timevarying dummy covariates, V5 timevarying quantitative */
                   9796:          Tvar[k]=atoi(strd);
                   9797:          Typevar[k]=0;  /* 0 for simple covariates */
                   9798:        }
                   9799:        strcpy(modelsav,stra);  /* modelsav=V2+V1+V4 stra=V2+V1+V4 */ 
1.223     brouard  9800:                                /*printf("a=%s b=%s sav=%s\n", stra,strb,modelsav);
1.225     brouard  9801:                                  scanf("%d",i);*/
1.187     brouard  9802:       } /* end of loop + on total covariates */
                   9803:     } /* end if strlen(modelsave == 0) age*age might exist */
                   9804:   } /* end if strlen(model == 0) */
1.136     brouard  9805:   
                   9806:   /*The number n of Vn is stored in Tvar. cptcovage =number of age covariate. Tage gives the position of age. cptcovprod= number of products.
                   9807:     If model=V1+V1*age then Tvar[1]=1 Tvar[2]=1 cptcovage=1 Tage[1]=2 cptcovprod=0*/
1.225     brouard  9808:   
1.136     brouard  9809:   /* printf("tvar1=%d tvar2=%d tvar3=%d cptcovage=%d Tage=%d",Tvar[1],Tvar[2],Tvar[3],cptcovage,Tage[1]);
1.225     brouard  9810:      printf("cptcovprod=%d ", cptcovprod);
                   9811:      fprintf(ficlog,"cptcovprod=%d ", cptcovprod);
                   9812:      scanf("%d ",i);*/
                   9813: 
                   9814: 
1.230     brouard  9815: /* Until here, decodemodel knows only the grammar (simple, product, age*) of the model but not what kind
                   9816:    of variable (dummy vs quantitative, fixed vs time varying) is behind. But we know the # of each. */
1.226     brouard  9817: /* ncovcol= 1, nqv=1 | ntv=2, nqtv= 1  = 5 possible variables data: 2 fixed 3, varying
                   9818:    model=        V5 + V4 +V3 + V4*V3 + V5*age + V2 + V1*V2 + V1*age + V5*age, V1 is not used saving its place
                   9819:    k =           1    2   3     4       5       6      7      8        9
                   9820:    Tvar[k]=      5    4   3 1+1+2+1+1=6 5       2      7      1        5
                   9821:    Typevar[k]=   0    0   0     2       1       0      2      1        1
1.227     brouard  9822:    Fixed[k]      1    1   1     1       3       0    0 or 2   2        3
                   9823:    Dummy[k]      1    0   0     0       3       1      1      2        3
                   9824:          Tmodelind[combination of covar]=k;
1.225     brouard  9825: */  
                   9826: /* Dispatching between quantitative and time varying covariates */
1.226     brouard  9827:   /* If Tvar[k] >ncovcol it is a product */
1.225     brouard  9828:   /* 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  9829:        /* Computing effective variables, ie used by the model, that is from the cptcovt variables */
1.227     brouard  9830:   printf("Model=%s\n\
                   9831: Typevar: 0 for simple covariate (dummy, quantitative, fixed or varying), 1 for age product, 2 for  product \n\
                   9832: Fixed[k] 0=fixed (product or simple), 1 varying, 2 fixed with age product, 3 varying with age product \n\
                   9833: 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);
                   9834:   fprintf(ficlog,"Model=%s\n\
                   9835: Typevar: 0 for simple covariate (dummy, quantitative, fixed or varying), 1 for age product, 2 for  product \n\
                   9836: Fixed[k] 0=fixed (product or simple), 1 varying, 2 fixed with age product, 3 varying with age product \n\
                   9837: 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  9838:   for(k=-1;k<=cptcovt; k++){ Fixed[k]=0; Dummy[k]=0;}
1.234     brouard  9839:   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 */
                   9840:     if (Tvar[k] <=ncovcol && Typevar[k]==0 ){ /* Simple fixed dummy (<=ncovcol) covariates */
1.227     brouard  9841:       Fixed[k]= 0;
                   9842:       Dummy[k]= 0;
1.225     brouard  9843:       ncoveff++;
1.232     brouard  9844:       ncovf++;
1.234     brouard  9845:       nsd++;
                   9846:       modell[k].maintype= FTYPE;
                   9847:       TvarsD[nsd]=Tvar[k];
                   9848:       TvarsDind[nsd]=k;
                   9849:       TvarF[ncovf]=Tvar[k];
                   9850:       TvarFind[ncovf]=k;
                   9851:       TvarFD[ncoveff]=Tvar[k]; /* TvarFD[1]=V1 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
                   9852:       TvarFDind[ncoveff]=k; /* TvarFDind[1]=9 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
                   9853:     }else if( Tvar[k] <=ncovcol &&  Typevar[k]==2){ /* Product of fixed dummy (<=ncovcol) covariates */
                   9854:       Fixed[k]= 0;
                   9855:       Dummy[k]= 0;
                   9856:       ncoveff++;
                   9857:       ncovf++;
                   9858:       modell[k].maintype= FTYPE;
                   9859:       TvarF[ncovf]=Tvar[k];
                   9860:       TvarFind[ncovf]=k;
1.230     brouard  9861:       TvarFD[ncoveff]=Tvar[k]; /* TvarFD[1]=V1 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
1.231     brouard  9862:       TvarFDind[ncoveff]=k; /* TvarFDind[1]=9 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
1.240     brouard  9863:     }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  9864:       Fixed[k]= 0;
                   9865:       Dummy[k]= 1;
1.230     brouard  9866:       nqfveff++;
1.234     brouard  9867:       modell[k].maintype= FTYPE;
                   9868:       modell[k].subtype= FQ;
                   9869:       nsq++;
                   9870:       TvarsQ[nsq]=Tvar[k];
                   9871:       TvarsQind[nsq]=k;
1.232     brouard  9872:       ncovf++;
1.234     brouard  9873:       TvarF[ncovf]=Tvar[k];
                   9874:       TvarFind[ncovf]=k;
1.231     brouard  9875:       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  9876:       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  9877:     }else if( Tvar[k] <=ncovcol+nqv+ntv && Typevar[k]==0){/* Only simple time varying dummy variables */
1.227     brouard  9878:       Fixed[k]= 1;
                   9879:       Dummy[k]= 0;
1.225     brouard  9880:       ntveff++; /* Only simple time varying dummy variable */
1.234     brouard  9881:       modell[k].maintype= VTYPE;
                   9882:       modell[k].subtype= VD;
                   9883:       nsd++;
                   9884:       TvarsD[nsd]=Tvar[k];
                   9885:       TvarsDind[nsd]=k;
                   9886:       ncovv++; /* Only simple time varying variables */
                   9887:       TvarV[ncovv]=Tvar[k];
1.242     brouard  9888:       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  9889:       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 */
                   9890:       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  9891:       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);
                   9892:       printf("Quasi TmodelInvind[%d]=%d\n",k,Tvar[k]- ncovcol-nqv);
1.231     brouard  9893:     }else if( Tvar[k] <=ncovcol+nqv+ntv+nqtv  && Typevar[k]==0){ /* Only simple time varying quantitative variable V5*/
1.234     brouard  9894:       Fixed[k]= 1;
                   9895:       Dummy[k]= 1;
                   9896:       nqtveff++;
                   9897:       modell[k].maintype= VTYPE;
                   9898:       modell[k].subtype= VQ;
                   9899:       ncovv++; /* Only simple time varying variables */
                   9900:       nsq++;
                   9901:       TvarsQ[nsq]=Tvar[k];
                   9902:       TvarsQind[nsq]=k;
                   9903:       TvarV[ncovv]=Tvar[k];
1.242     brouard  9904:       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  9905:       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 */
                   9906:       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  9907:       TmodelInvQind[nqtveff]=Tvar[k]- ncovcol-nqv-ntv;/* Only simple time varying quantitative variable */
                   9908:       /* Tmodeliqind[k]=nqtveff;/\* Only simple time varying quantitative variable *\/ */
                   9909:       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  9910:       printf("Quasi TmodelInvQind[%d]=%d\n",k,Tvar[k]- ncovcol-nqv-ntv);
1.227     brouard  9911:     }else if (Typevar[k] == 1) {  /* product with age */
1.234     brouard  9912:       ncova++;
                   9913:       TvarA[ncova]=Tvar[k];
                   9914:       TvarAind[ncova]=k;
1.231     brouard  9915:       if (Tvar[k] <=ncovcol ){ /* Product age with fixed dummy covariatee */
1.240     brouard  9916:        Fixed[k]= 2;
                   9917:        Dummy[k]= 2;
                   9918:        modell[k].maintype= ATYPE;
                   9919:        modell[k].subtype= APFD;
                   9920:        /* ncoveff++; */
1.227     brouard  9921:       }else if( Tvar[k] <=ncovcol+nqv) { /* Remind that product Vn*Vm are added in k*/
1.240     brouard  9922:        Fixed[k]= 2;
                   9923:        Dummy[k]= 3;
                   9924:        modell[k].maintype= ATYPE;
                   9925:        modell[k].subtype= APFQ;                /*      Product age * fixed quantitative */
                   9926:        /* nqfveff++;  /\* Only simple fixed quantitative variable *\/ */
1.227     brouard  9927:       }else if( Tvar[k] <=ncovcol+nqv+ntv ){
1.240     brouard  9928:        Fixed[k]= 3;
                   9929:        Dummy[k]= 2;
                   9930:        modell[k].maintype= ATYPE;
                   9931:        modell[k].subtype= APVD;                /*      Product age * varying dummy */
                   9932:        /* ntveff++; /\* Only simple time varying dummy variable *\/ */
1.227     brouard  9933:       }else if( Tvar[k] <=ncovcol+nqv+ntv+nqtv){
1.240     brouard  9934:        Fixed[k]= 3;
                   9935:        Dummy[k]= 3;
                   9936:        modell[k].maintype= ATYPE;
                   9937:        modell[k].subtype= APVQ;                /*      Product age * varying quantitative */
                   9938:        /* nqtveff++;/\* Only simple time varying quantitative variable *\/ */
1.227     brouard  9939:       }
                   9940:     }else if (Typevar[k] == 2) {  /* product without age */
                   9941:       k1=Tposprod[k];
                   9942:       if(Tvard[k1][1] <=ncovcol){
1.240     brouard  9943:        if(Tvard[k1][2] <=ncovcol){
                   9944:          Fixed[k]= 1;
                   9945:          Dummy[k]= 0;
                   9946:          modell[k].maintype= FTYPE;
                   9947:          modell[k].subtype= FPDD;              /*      Product fixed dummy * fixed dummy */
                   9948:          ncovf++; /* Fixed variables without age */
                   9949:          TvarF[ncovf]=Tvar[k];
                   9950:          TvarFind[ncovf]=k;
                   9951:        }else if(Tvard[k1][2] <=ncovcol+nqv){
                   9952:          Fixed[k]= 0;  /* or 2 ?*/
                   9953:          Dummy[k]= 1;
                   9954:          modell[k].maintype= FTYPE;
                   9955:          modell[k].subtype= FPDQ;              /*      Product fixed dummy * fixed quantitative */
                   9956:          ncovf++; /* Varying variables without age */
                   9957:          TvarF[ncovf]=Tvar[k];
                   9958:          TvarFind[ncovf]=k;
                   9959:        }else if(Tvard[k1][2] <=ncovcol+nqv+ntv){
                   9960:          Fixed[k]= 1;
                   9961:          Dummy[k]= 0;
                   9962:          modell[k].maintype= VTYPE;
                   9963:          modell[k].subtype= VPDD;              /*      Product fixed dummy * varying dummy */
                   9964:          ncovv++; /* Varying variables without age */
                   9965:          TvarV[ncovv]=Tvar[k];
                   9966:          TvarVind[ncovv]=k;
                   9967:        }else if(Tvard[k1][2] <=ncovcol+nqv+ntv+nqtv){
                   9968:          Fixed[k]= 1;
                   9969:          Dummy[k]= 1;
                   9970:          modell[k].maintype= VTYPE;
                   9971:          modell[k].subtype= VPDQ;              /*      Product fixed dummy * varying quantitative */
                   9972:          ncovv++; /* Varying variables without age */
                   9973:          TvarV[ncovv]=Tvar[k];
                   9974:          TvarVind[ncovv]=k;
                   9975:        }
1.227     brouard  9976:       }else if(Tvard[k1][1] <=ncovcol+nqv){
1.240     brouard  9977:        if(Tvard[k1][2] <=ncovcol){
                   9978:          Fixed[k]= 0;  /* or 2 ?*/
                   9979:          Dummy[k]= 1;
                   9980:          modell[k].maintype= FTYPE;
                   9981:          modell[k].subtype= FPDQ;              /*      Product fixed quantitative * fixed dummy */
                   9982:          ncovf++; /* Fixed variables without age */
                   9983:          TvarF[ncovf]=Tvar[k];
                   9984:          TvarFind[ncovf]=k;
                   9985:        }else if(Tvard[k1][2] <=ncovcol+nqv+ntv){
                   9986:          Fixed[k]= 1;
                   9987:          Dummy[k]= 1;
                   9988:          modell[k].maintype= VTYPE;
                   9989:          modell[k].subtype= VPDQ;              /*      Product fixed quantitative * varying dummy */
                   9990:          ncovv++; /* Varying variables without age */
                   9991:          TvarV[ncovv]=Tvar[k];
                   9992:          TvarVind[ncovv]=k;
                   9993:        }else if(Tvard[k1][2] <=ncovcol+nqv+ntv+nqtv){
                   9994:          Fixed[k]= 1;
                   9995:          Dummy[k]= 1;
                   9996:          modell[k].maintype= VTYPE;
                   9997:          modell[k].subtype= VPQQ;              /*      Product fixed quantitative * varying quantitative */
                   9998:          ncovv++; /* Varying variables without age */
                   9999:          TvarV[ncovv]=Tvar[k];
                   10000:          TvarVind[ncovv]=k;
                   10001:          ncovv++; /* Varying variables without age */
                   10002:          TvarV[ncovv]=Tvar[k];
                   10003:          TvarVind[ncovv]=k;
                   10004:        }
1.227     brouard  10005:       }else if(Tvard[k1][1] <=ncovcol+nqv+ntv){
1.240     brouard  10006:        if(Tvard[k1][2] <=ncovcol){
                   10007:          Fixed[k]= 1;
                   10008:          Dummy[k]= 1;
                   10009:          modell[k].maintype= VTYPE;
                   10010:          modell[k].subtype= VPDD;              /*      Product time varying dummy * fixed dummy */
                   10011:          ncovv++; /* Varying variables without age */
                   10012:          TvarV[ncovv]=Tvar[k];
                   10013:          TvarVind[ncovv]=k;
                   10014:        }else if(Tvard[k1][2] <=ncovcol+nqv){
                   10015:          Fixed[k]= 1;
                   10016:          Dummy[k]= 1;
                   10017:          modell[k].maintype= VTYPE;
                   10018:          modell[k].subtype= VPDQ;              /*      Product time varying dummy * fixed quantitative */
                   10019:          ncovv++; /* Varying variables without age */
                   10020:          TvarV[ncovv]=Tvar[k];
                   10021:          TvarVind[ncovv]=k;
                   10022:        }else if(Tvard[k1][2] <=ncovcol+nqv+ntv){
                   10023:          Fixed[k]= 1;
                   10024:          Dummy[k]= 0;
                   10025:          modell[k].maintype= VTYPE;
                   10026:          modell[k].subtype= VPDD;              /*      Product time varying dummy * time varying dummy */
                   10027:          ncovv++; /* Varying variables without age */
                   10028:          TvarV[ncovv]=Tvar[k];
                   10029:          TvarVind[ncovv]=k;
                   10030:        }else if(Tvard[k1][2] <=ncovcol+nqv+ntv+nqtv){
                   10031:          Fixed[k]= 1;
                   10032:          Dummy[k]= 1;
                   10033:          modell[k].maintype= VTYPE;
                   10034:          modell[k].subtype= VPDQ;              /*      Product time varying dummy * time varying quantitative */
                   10035:          ncovv++; /* Varying variables without age */
                   10036:          TvarV[ncovv]=Tvar[k];
                   10037:          TvarVind[ncovv]=k;
                   10038:        }
1.227     brouard  10039:       }else if(Tvard[k1][1] <=ncovcol+nqv+ntv+nqtv){
1.240     brouard  10040:        if(Tvard[k1][2] <=ncovcol){
                   10041:          Fixed[k]= 1;
                   10042:          Dummy[k]= 1;
                   10043:          modell[k].maintype= VTYPE;
                   10044:          modell[k].subtype= VPDQ;              /*      Product time varying quantitative * fixed dummy */
                   10045:          ncovv++; /* Varying variables without age */
                   10046:          TvarV[ncovv]=Tvar[k];
                   10047:          TvarVind[ncovv]=k;
                   10048:        }else if(Tvard[k1][2] <=ncovcol+nqv){
                   10049:          Fixed[k]= 1;
                   10050:          Dummy[k]= 1;
                   10051:          modell[k].maintype= VTYPE;
                   10052:          modell[k].subtype= VPQQ;              /*      Product time varying quantitative * fixed quantitative */
                   10053:          ncovv++; /* Varying variables without age */
                   10054:          TvarV[ncovv]=Tvar[k];
                   10055:          TvarVind[ncovv]=k;
                   10056:        }else if(Tvard[k1][2] <=ncovcol+nqv+ntv){
                   10057:          Fixed[k]= 1;
                   10058:          Dummy[k]= 1;
                   10059:          modell[k].maintype= VTYPE;
                   10060:          modell[k].subtype= VPDQ;              /*      Product time varying quantitative * time varying dummy */
                   10061:          ncovv++; /* Varying variables without age */
                   10062:          TvarV[ncovv]=Tvar[k];
                   10063:          TvarVind[ncovv]=k;
                   10064:        }else if(Tvard[k1][2] <=ncovcol+nqv+ntv+nqtv){
                   10065:          Fixed[k]= 1;
                   10066:          Dummy[k]= 1;
                   10067:          modell[k].maintype= VTYPE;
                   10068:          modell[k].subtype= VPQQ;              /*      Product time varying quantitative * time varying quantitative */
                   10069:          ncovv++; /* Varying variables without age */
                   10070:          TvarV[ncovv]=Tvar[k];
                   10071:          TvarVind[ncovv]=k;
                   10072:        }
1.227     brouard  10073:       }else{
1.240     brouard  10074:        printf("Error unknown type of covariate: Tvard[%d][1]=%d,Tvard[%d][2]=%d\n",k1,Tvard[k1][1],k1,Tvard[k1][2]);
                   10075:        fprintf(ficlog,"Error unknown type of covariate: Tvard[%d][1]=%d,Tvard[%d][2]=%d\n",k1,Tvard[k1][1],k1,Tvard[k1][2]);
                   10076:       } /*end k1*/
1.225     brouard  10077:     }else{
1.226     brouard  10078:       printf("Error, current version can't treat for performance reasons, Tvar[%d]=%d, Typevar[%d]=%d\n", k, Tvar[k], k, Typevar[k]);
                   10079:       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  10080:     }
1.227     brouard  10081:     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  10082:     printf("           modell[%d].maintype=%d, modell[%d].subtype=%d\n",k,modell[k].maintype,k,modell[k].subtype);
1.227     brouard  10083:     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]);
                   10084:   }
                   10085:   /* Searching for doublons in the model */
                   10086:   for(k1=1; k1<= cptcovt;k1++){
                   10087:     for(k2=1; k2 <k1;k2++){
1.285     brouard  10088:       /* if((Typevar[k1]==Typevar[k2]) && (Fixed[Tvar[k1]]==Fixed[Tvar[k2]]) && (Dummy[Tvar[k1]]==Dummy[Tvar[k2]] )){ */
                   10089:       if((Typevar[k1]==Typevar[k2]) && (Fixed[k1]==Fixed[k2]) && (Dummy[k1]==Dummy[k2] )){
1.234     brouard  10090:        if((Typevar[k1] == 0 || Typevar[k1] == 1)){ /* Simple or age product */
                   10091:          if(Tvar[k1]==Tvar[k2]){
1.285     brouard  10092:            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]);
                   10093:            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  10094:            return(1);
                   10095:          }
                   10096:        }else if (Typevar[k1] ==2){
                   10097:          k3=Tposprod[k1];
                   10098:          k4=Tposprod[k2];
                   10099:          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])) ){
                   10100:            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]]);
                   10101:            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);
                   10102:            return(1);
                   10103:          }
                   10104:        }
1.227     brouard  10105:       }
                   10106:     }
1.225     brouard  10107:   }
                   10108:   printf("ncoveff=%d, nqfveff=%d, ntveff=%d, nqtveff=%d, cptcovn=%d\n",ncoveff,nqfveff,ntveff,nqtveff,cptcovn);
                   10109:   fprintf(ficlog,"ncoveff=%d, nqfveff=%d, ntveff=%d, nqtveff=%d, cptcovn=%d\n",ncoveff,nqfveff,ntveff,nqtveff,cptcovn);
1.234     brouard  10110:   printf("ncovf=%d, ncovv=%d, ncova=%d, nsd=%d, nsq=%d\n",ncovf,ncovv,ncova,nsd,nsq);
                   10111:   fprintf(ficlog,"ncovf=%d, ncovv=%d, ncova=%d, nsd=%d, nsq=%d\n",ncovf,ncovv,ncova,nsd, nsq);
1.137     brouard  10112:   return (0); /* with covar[new additional covariate if product] and Tage if age */ 
1.164     brouard  10113:   /*endread:*/
1.225     brouard  10114:   printf("Exiting decodemodel: ");
                   10115:   return (1);
1.136     brouard  10116: }
                   10117: 
1.169     brouard  10118: int calandcheckages(int imx, int maxwav, double *agemin, double *agemax, int *nberr, int *nbwarn )
1.248     brouard  10119: {/* Check ages at death */
1.136     brouard  10120:   int i, m;
1.218     brouard  10121:   int firstone=0;
                   10122:   
1.136     brouard  10123:   for (i=1; i<=imx; i++) {
                   10124:     for(m=2; (m<= maxwav); m++) {
                   10125:       if (((int)mint[m][i]== 99) && (s[m][i] <= nlstate)){
                   10126:        anint[m][i]=9999;
1.216     brouard  10127:        if (s[m][i] != -2) /* Keeping initial status of unknown vital status */
                   10128:          s[m][i]=-1;
1.136     brouard  10129:       }
                   10130:       if((int)moisdc[i]==99 && (int)andc[i]==9999 && s[m][i]>nlstate){
1.260     brouard  10131:        *nberr = *nberr + 1;
1.218     brouard  10132:        if(firstone == 0){
                   10133:          firstone=1;
1.260     brouard  10134:        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  10135:        }
1.262     brouard  10136:        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  10137:        s[m][i]=-1;  /* Droping the death status */
1.136     brouard  10138:       }
                   10139:       if((int)moisdc[i]==99 && (int)andc[i]!=9999 && s[m][i]>nlstate){
1.169     brouard  10140:        (*nberr)++;
1.259     brouard  10141:        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  10142:        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  10143:        s[m][i]=-2; /* We prefer to skip it (and to skip it in version 0.8a1 too */
1.136     brouard  10144:       }
                   10145:     }
                   10146:   }
                   10147: 
                   10148:   for (i=1; i<=imx; i++)  {
                   10149:     agedc[i]=(moisdc[i]/12.+andc[i])-(moisnais[i]/12.+annais[i]);
                   10150:     for(m=firstpass; (m<= lastpass); m++){
1.214     brouard  10151:       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  10152:        if (s[m][i] >= nlstate+1) {
1.169     brouard  10153:          if(agedc[i]>0){
                   10154:            if((int)moisdc[i]!=99 && (int)andc[i]!=9999){
1.136     brouard  10155:              agev[m][i]=agedc[i];
1.214     brouard  10156:              /*if(moisdc[i]==99 && andc[i]==9999) s[m][i]=-1;*/
1.169     brouard  10157:            }else {
1.136     brouard  10158:              if ((int)andc[i]!=9999){
                   10159:                nbwarn++;
                   10160:                printf("Warning negative age at death: %ld line:%d\n",num[i],i);
                   10161:                fprintf(ficlog,"Warning negative age at death: %ld line:%d\n",num[i],i);
                   10162:                agev[m][i]=-1;
                   10163:              }
                   10164:            }
1.169     brouard  10165:          } /* agedc > 0 */
1.214     brouard  10166:        } /* end if */
1.136     brouard  10167:        else if(s[m][i] !=9){ /* Standard case, age in fractional
                   10168:                                 years but with the precision of a month */
                   10169:          agev[m][i]=(mint[m][i]/12.+1./24.+anint[m][i])-(moisnais[i]/12.+1./24.+annais[i]);
                   10170:          if((int)mint[m][i]==99 || (int)anint[m][i]==9999)
                   10171:            agev[m][i]=1;
                   10172:          else if(agev[m][i] < *agemin){ 
                   10173:            *agemin=agev[m][i];
                   10174:            printf(" Min anint[%d][%d]=%.2f annais[%d]=%.2f, agemin=%.2f\n",m,i,anint[m][i], i,annais[i], *agemin);
                   10175:          }
                   10176:          else if(agev[m][i] >*agemax){
                   10177:            *agemax=agev[m][i];
1.156     brouard  10178:            /* printf(" Max anint[%d][%d]=%.0f annais[%d]=%.0f, agemax=%.2f\n",m,i,anint[m][i], i,annais[i], *agemax);*/
1.136     brouard  10179:          }
                   10180:          /*agev[m][i]=anint[m][i]-annais[i];*/
                   10181:          /*     agev[m][i] = age[i]+2*m;*/
1.214     brouard  10182:        } /* en if 9*/
1.136     brouard  10183:        else { /* =9 */
1.214     brouard  10184:          /* printf("Debug num[%d]=%ld s[%d][%d]=%d\n",i,num[i], m,i, s[m][i]); */
1.136     brouard  10185:          agev[m][i]=1;
                   10186:          s[m][i]=-1;
                   10187:        }
                   10188:       }
1.214     brouard  10189:       else if(s[m][i]==0) /*= 0 Unknown */
1.136     brouard  10190:        agev[m][i]=1;
1.214     brouard  10191:       else{
                   10192:        printf("Warning, num[%d]=%ld, s[%d][%d]=%d\n", i, num[i], m, i,s[m][i]); 
                   10193:        fprintf(ficlog, "Warning, num[%d]=%ld, s[%d][%d]=%d\n", i, num[i], m, i,s[m][i]); 
                   10194:        agev[m][i]=0;
                   10195:       }
                   10196:     } /* End for lastpass */
                   10197:   }
1.136     brouard  10198:     
                   10199:   for (i=1; i<=imx; i++)  {
                   10200:     for(m=firstpass; (m<=lastpass); m++){
                   10201:       if (s[m][i] > (nlstate+ndeath)) {
1.169     brouard  10202:        (*nberr)++;
1.136     brouard  10203:        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);     
                   10204:        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);     
                   10205:        return 1;
                   10206:       }
                   10207:     }
                   10208:   }
                   10209: 
                   10210:   /*for (i=1; i<=imx; i++){
                   10211:   for (m=firstpass; (m<lastpass); m++){
                   10212:      printf("%ld %d %.lf %d %d\n", num[i],(covar[1][i]),agev[m][i],s[m][i],s[m+1][i]);
                   10213: }
                   10214: 
                   10215: }*/
                   10216: 
                   10217: 
1.139     brouard  10218:   printf("Total number of individuals= %d, Agemin = %.2f, Agemax= %.2f\n\n", imx, *agemin, *agemax);
                   10219:   fprintf(ficlog,"Total number of individuals= %d, Agemin = %.2f, Agemax= %.2f\n\n", imx, *agemin, *agemax); 
1.136     brouard  10220: 
                   10221:   return (0);
1.164     brouard  10222:  /* endread:*/
1.136     brouard  10223:     printf("Exiting calandcheckages: ");
                   10224:     return (1);
                   10225: }
                   10226: 
1.172     brouard  10227: #if defined(_MSC_VER)
                   10228: /*printf("Visual C++ compiler: %s \n;", _MSC_FULL_VER);*/
                   10229: /*fprintf(ficlog, "Visual C++ compiler: %s \n;", _MSC_FULL_VER);*/
                   10230: //#include "stdafx.h"
                   10231: //#include <stdio.h>
                   10232: //#include <tchar.h>
                   10233: //#include <windows.h>
                   10234: //#include <iostream>
                   10235: typedef BOOL(WINAPI *LPFN_ISWOW64PROCESS) (HANDLE, PBOOL);
                   10236: 
                   10237: LPFN_ISWOW64PROCESS fnIsWow64Process;
                   10238: 
                   10239: BOOL IsWow64()
                   10240: {
                   10241:        BOOL bIsWow64 = FALSE;
                   10242: 
                   10243:        //typedef BOOL (APIENTRY *LPFN_ISWOW64PROCESS)
                   10244:        //  (HANDLE, PBOOL);
                   10245: 
                   10246:        //LPFN_ISWOW64PROCESS fnIsWow64Process;
                   10247: 
                   10248:        HMODULE module = GetModuleHandle(_T("kernel32"));
                   10249:        const char funcName[] = "IsWow64Process";
                   10250:        fnIsWow64Process = (LPFN_ISWOW64PROCESS)
                   10251:                GetProcAddress(module, funcName);
                   10252: 
                   10253:        if (NULL != fnIsWow64Process)
                   10254:        {
                   10255:                if (!fnIsWow64Process(GetCurrentProcess(),
                   10256:                        &bIsWow64))
                   10257:                        //throw std::exception("Unknown error");
                   10258:                        printf("Unknown error\n");
                   10259:        }
                   10260:        return bIsWow64 != FALSE;
                   10261: }
                   10262: #endif
1.177     brouard  10263: 
1.191     brouard  10264: void syscompilerinfo(int logged)
1.292     brouard  10265: {
                   10266: #include <stdint.h>
                   10267: 
                   10268:   /* #include "syscompilerinfo.h"*/
1.185     brouard  10269:    /* command line Intel compiler 32bit windows, XP compatible:*/
                   10270:    /* /GS /W3 /Gy
                   10271:       /Zc:wchar_t /Zi /O2 /Fd"Release\vc120.pdb" /D "WIN32" /D "NDEBUG" /D
                   10272:       "_CONSOLE" /D "_LIB" /D "_USING_V110_SDK71_" /D "_UNICODE" /D
                   10273:       "UNICODE" /Qipo /Zc:forScope /Gd /Oi /MT /Fa"Release\" /EHsc /nologo
1.186     brouard  10274:       /Fo"Release\" /Qprof-dir "Release\" /Fp"Release\IMaCh.pch"
                   10275:    */ 
                   10276:    /* 64 bits */
1.185     brouard  10277:    /*
                   10278:      /GS /W3 /Gy
                   10279:      /Zc:wchar_t /Zi /O2 /Fd"x64\Release\vc120.pdb" /D "WIN32" /D "NDEBUG"
                   10280:      /D "_CONSOLE" /D "_LIB" /D "_UNICODE" /D "UNICODE" /Qipo /Zc:forScope
                   10281:      /Oi /MD /Fa"x64\Release\" /EHsc /nologo /Fo"x64\Release\" /Qprof-dir
                   10282:      "x64\Release\" /Fp"x64\Release\IMaCh.pch" */
                   10283:    /* Optimization are useless and O3 is slower than O2 */
                   10284:    /*
                   10285:      /GS /W3 /Gy /Zc:wchar_t /Zi /O3 /Fd"x64\Release\vc120.pdb" /D "WIN32" 
                   10286:      /D "NDEBUG" /D "_CONSOLE" /D "_LIB" /D "_UNICODE" /D "UNICODE" /Qipo 
                   10287:      /Zc:forScope /Oi /MD /Fa"x64\Release\" /EHsc /nologo /Qparallel 
                   10288:      /Fo"x64\Release\" /Qprof-dir "x64\Release\" /Fp"x64\Release\IMaCh.pch" 
                   10289:    */
1.186     brouard  10290:    /* Link is */ /* /OUT:"visual studio
1.185     brouard  10291:       2013\Projects\IMaCh\Release\IMaCh.exe" /MANIFEST /NXCOMPAT
                   10292:       /PDB:"visual studio
                   10293:       2013\Projects\IMaCh\Release\IMaCh.pdb" /DYNAMICBASE
                   10294:       "kernel32.lib" "user32.lib" "gdi32.lib" "winspool.lib"
                   10295:       "comdlg32.lib" "advapi32.lib" "shell32.lib" "ole32.lib"
                   10296:       "oleaut32.lib" "uuid.lib" "odbc32.lib" "odbccp32.lib"
                   10297:       /MACHINE:X86 /OPT:REF /SAFESEH /INCREMENTAL:NO
                   10298:       /SUBSYSTEM:CONSOLE",5.01" /MANIFESTUAC:"level='asInvoker'
                   10299:       uiAccess='false'"
                   10300:       /ManifestFile:"Release\IMaCh.exe.intermediate.manifest" /OPT:ICF
                   10301:       /NOLOGO /TLBID:1
                   10302:    */
1.292     brouard  10303: 
                   10304: 
1.177     brouard  10305: #if defined __INTEL_COMPILER
1.178     brouard  10306: #if defined(__GNUC__)
                   10307:        struct utsname sysInfo;  /* For Intel on Linux and OS/X */
                   10308: #endif
1.177     brouard  10309: #elif defined(__GNUC__) 
1.179     brouard  10310: #ifndef  __APPLE__
1.174     brouard  10311: #include <gnu/libc-version.h>  /* Only on gnu */
1.179     brouard  10312: #endif
1.177     brouard  10313:    struct utsname sysInfo;
1.178     brouard  10314:    int cross = CROSS;
                   10315:    if (cross){
                   10316:           printf("Cross-");
1.191     brouard  10317:           if(logged) fprintf(ficlog, "Cross-");
1.178     brouard  10318:    }
1.174     brouard  10319: #endif
                   10320: 
1.191     brouard  10321:    printf("Compiled with:");if(logged)fprintf(ficlog,"Compiled with:");
1.169     brouard  10322: #if defined(__clang__)
1.191     brouard  10323:    printf(" Clang/LLVM");if(logged)fprintf(ficlog," Clang/LLVM");      /* Clang/LLVM. ---------------------------------------------- */
1.169     brouard  10324: #endif
                   10325: #if defined(__ICC) || defined(__INTEL_COMPILER)
1.191     brouard  10326:    printf(" Intel ICC/ICPC");if(logged)fprintf(ficlog," Intel ICC/ICPC");/* Intel ICC/ICPC. ------------------------------------------ */
1.169     brouard  10327: #endif
                   10328: #if defined(__GNUC__) || defined(__GNUG__)
1.191     brouard  10329:    printf(" GNU GCC/G++");if(logged)fprintf(ficlog," GNU GCC/G++");/* GNU GCC/G++. --------------------------------------------- */
1.169     brouard  10330: #endif
                   10331: #if defined(__HP_cc) || defined(__HP_aCC)
1.191     brouard  10332:    printf(" Hewlett-Packard C/aC++");if(logged)fprintf(fcilog," Hewlett-Packard C/aC++"); /* Hewlett-Packard C/aC++. ---------------------------------- */
1.169     brouard  10333: #endif
                   10334: #if defined(__IBMC__) || defined(__IBMCPP__)
1.191     brouard  10335:    printf(" IBM XL C/C++"); if(logged) fprintf(ficlog," IBM XL C/C++");/* IBM XL C/C++. -------------------------------------------- */
1.169     brouard  10336: #endif
                   10337: #if defined(_MSC_VER)
1.191     brouard  10338:    printf(" Microsoft Visual Studio");if(logged)fprintf(ficlog," Microsoft Visual Studio");/* Microsoft Visual Studio. --------------------------------- */
1.169     brouard  10339: #endif
                   10340: #if defined(__PGI)
1.191     brouard  10341:    printf(" Portland Group PGCC/PGCPP");if(logged) fprintf(ficlog," Portland Group PGCC/PGCPP");/* Portland Group PGCC/PGCPP. ------------------------------- */
1.169     brouard  10342: #endif
                   10343: #if defined(__SUNPRO_C) || defined(__SUNPRO_CC)
1.191     brouard  10344:    printf(" Oracle Solaris Studio");if(logged)fprintf(ficlog," Oracle Solaris Studio\n");/* Oracle Solaris Studio. ----------------------------------- */
1.167     brouard  10345: #endif
1.191     brouard  10346:    printf(" for "); if (logged) fprintf(ficlog, " for ");
1.169     brouard  10347:    
1.167     brouard  10348: // http://stackoverflow.com/questions/4605842/how-to-identify-platform-compiler-from-preprocessor-macros
                   10349: #ifdef _WIN32 // note the underscore: without it, it's not msdn official!
                   10350:     // Windows (x64 and x86)
1.191     brouard  10351:    printf("Windows (x64 and x86) ");if(logged) fprintf(ficlog,"Windows (x64 and x86) ");
1.167     brouard  10352: #elif __unix__ // all unices, not all compilers
                   10353:     // Unix
1.191     brouard  10354:    printf("Unix ");if(logged) fprintf(ficlog,"Unix ");
1.167     brouard  10355: #elif __linux__
                   10356:     // linux
1.191     brouard  10357:    printf("linux ");if(logged) fprintf(ficlog,"linux ");
1.167     brouard  10358: #elif __APPLE__
1.174     brouard  10359:     // Mac OS, not sure if this is covered by __posix__ and/or __unix__ though..
1.191     brouard  10360:    printf("Mac OS ");if(logged) fprintf(ficlog,"Mac OS ");
1.167     brouard  10361: #endif
                   10362: 
                   10363: /*  __MINGW32__          */
                   10364: /*  __CYGWIN__  */
                   10365: /* __MINGW64__  */
                   10366: // http://msdn.microsoft.com/en-us/library/b0084kay.aspx
                   10367: /* _MSC_VER  //the Visual C++ compiler is 17.00.51106.1, the _MSC_VER macro evaluates to 1700. Type cl /?  */
                   10368: /* _MSC_FULL_VER //the Visual C++ compiler is 15.00.20706.01, the _MSC_FULL_VER macro evaluates to 150020706 */
                   10369: /* _WIN64  // Defined for applications for Win64. */
                   10370: /* _M_X64 // Defined for compilations that target x64 processors. */
                   10371: /* _DEBUG // Defined when you compile with /LDd, /MDd, and /MTd. */
1.171     brouard  10372: 
1.167     brouard  10373: #if UINTPTR_MAX == 0xffffffff
1.191     brouard  10374:    printf(" 32-bit"); if(logged) fprintf(ficlog," 32-bit");/* 32-bit */
1.167     brouard  10375: #elif UINTPTR_MAX == 0xffffffffffffffff
1.191     brouard  10376:    printf(" 64-bit"); if(logged) fprintf(ficlog," 64-bit");/* 64-bit */
1.167     brouard  10377: #else
1.191     brouard  10378:    printf(" wtf-bit"); if(logged) fprintf(ficlog," wtf-bit");/* wtf */
1.167     brouard  10379: #endif
                   10380: 
1.169     brouard  10381: #if defined(__GNUC__)
                   10382: # if defined(__GNUC_PATCHLEVEL__)
                   10383: #  define __GNUC_VERSION__ (__GNUC__ * 10000 \
                   10384:                             + __GNUC_MINOR__ * 100 \
                   10385:                             + __GNUC_PATCHLEVEL__)
                   10386: # else
                   10387: #  define __GNUC_VERSION__ (__GNUC__ * 10000 \
                   10388:                             + __GNUC_MINOR__ * 100)
                   10389: # endif
1.174     brouard  10390:    printf(" using GNU C version %d.\n", __GNUC_VERSION__);
1.191     brouard  10391:    if(logged) fprintf(ficlog, " using GNU C version %d.\n", __GNUC_VERSION__);
1.176     brouard  10392: 
                   10393:    if (uname(&sysInfo) != -1) {
                   10394:      printf("Running on: %s %s %s %s %s\n",sysInfo.sysname, sysInfo.nodename, sysInfo.release, sysInfo.version, sysInfo.machine);
1.191     brouard  10395:         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  10396:    }
                   10397:    else
                   10398:       perror("uname() error");
1.179     brouard  10399:    //#ifndef __INTEL_COMPILER 
                   10400: #if !defined (__INTEL_COMPILER) && !defined(__APPLE__)
1.174     brouard  10401:    printf("GNU libc version: %s\n", gnu_get_libc_version()); 
1.191     brouard  10402:    if(logged) fprintf(ficlog,"GNU libc version: %s\n", gnu_get_libc_version());
1.177     brouard  10403: #endif
1.169     brouard  10404: #endif
1.172     brouard  10405: 
1.286     brouard  10406:    //   void main ()
1.172     brouard  10407:    //   {
1.169     brouard  10408: #if defined(_MSC_VER)
1.174     brouard  10409:    if (IsWow64()){
1.191     brouard  10410:           printf("\nThe program (probably compiled for 32bit) is running under WOW64 (64bit) emulation.\n");
                   10411:           if (logged) fprintf(ficlog, "\nThe program (probably compiled for 32bit) is running under WOW64 (64bit) emulation.\n");
1.174     brouard  10412:    }
                   10413:    else{
1.191     brouard  10414:           printf("\nThe program is not running under WOW64 (i.e probably on a 64bit Windows).\n");
                   10415:           if (logged) fprintf(ficlog, "\nThe programm is not running under WOW64 (i.e probably on a 64bit Windows).\n");
1.174     brouard  10416:    }
1.172     brouard  10417:    //     printf("\nPress Enter to continue...");
                   10418:    //     getchar();
                   10419:    //   }
                   10420: 
1.169     brouard  10421: #endif
                   10422:    
1.167     brouard  10423: 
1.219     brouard  10424: }
1.136     brouard  10425: 
1.219     brouard  10426: int prevalence_limit(double *p, double **prlim, double ageminpar, double agemaxpar, double ftolpl, int *ncvyearp){
1.288     brouard  10427:   /*--------------- Prevalence limit  (forward period or forward stable prevalence) --------------*/
1.235     brouard  10428:   int i, j, k, i1, k4=0, nres=0 ;
1.202     brouard  10429:   /* double ftolpl = 1.e-10; */
1.180     brouard  10430:   double age, agebase, agelim;
1.203     brouard  10431:   double tot;
1.180     brouard  10432: 
1.202     brouard  10433:   strcpy(filerespl,"PL_");
                   10434:   strcat(filerespl,fileresu);
                   10435:   if((ficrespl=fopen(filerespl,"w"))==NULL) {
1.288     brouard  10436:     printf("Problem with forward period (stable) prevalence resultfile: %s\n", filerespl);return 1;
                   10437:     fprintf(ficlog,"Problem with forward period (stable) prevalence resultfile: %s\n", filerespl);return 1;
1.202     brouard  10438:   }
1.288     brouard  10439:   printf("\nComputing forward period (stable) prevalence: result on file '%s' \n", filerespl);
                   10440:   fprintf(ficlog,"\nComputing forward period (stable) prevalence: result on file '%s' \n", filerespl);
1.202     brouard  10441:   pstamp(ficrespl);
1.288     brouard  10442:   fprintf(ficrespl,"# Forward period (stable) prevalence. Precision given by ftolpl=%g \n", ftolpl);
1.202     brouard  10443:   fprintf(ficrespl,"#Age ");
                   10444:   for(i=1; i<=nlstate;i++) fprintf(ficrespl,"%d-%d ",i,i);
                   10445:   fprintf(ficrespl,"\n");
1.180     brouard  10446:   
1.219     brouard  10447:   /* prlim=matrix(1,nlstate,1,nlstate);*/ /* back in main */
1.180     brouard  10448: 
1.219     brouard  10449:   agebase=ageminpar;
                   10450:   agelim=agemaxpar;
1.180     brouard  10451: 
1.227     brouard  10452:   /* i1=pow(2,ncoveff); */
1.234     brouard  10453:   i1=pow(2,cptcoveff); /* Number of combination of dummy covariates */
1.219     brouard  10454:   if (cptcovn < 1){i1=1;}
1.180     brouard  10455: 
1.238     brouard  10456:   for(k=1; k<=i1;k++){ /* For each combination k of dummy covariates in the model */
                   10457:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.253     brouard  10458:       if(i1 != 1 && TKresult[nres]!= k)
1.238     brouard  10459:        continue;
1.235     brouard  10460: 
1.238     brouard  10461:       /* for(cptcov=1,k=0;cptcov<=i1;cptcov++){ */
                   10462:       /* for(cptcov=1,k=0;cptcov<=1;cptcov++){ */
                   10463:       //for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){
                   10464:       /* k=k+1; */
                   10465:       /* to clean */
                   10466:       //printf("cptcov=%d cptcod=%d codtab=%d\n",cptcov, cptcod,codtabm(cptcod,cptcov));
                   10467:       fprintf(ficrespl,"#******");
                   10468:       printf("#******");
                   10469:       fprintf(ficlog,"#******");
                   10470:       for(j=1;j<=cptcoveff ;j++) {/* all covariates */
                   10471:        fprintf(ficrespl," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]); /* Here problem for varying dummy*/
                   10472:        printf(" V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   10473:        fprintf(ficlog," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   10474:       }
                   10475:       for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
                   10476:        printf(" V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
                   10477:        fprintf(ficrespl," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
                   10478:        fprintf(ficlog," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
                   10479:       }
                   10480:       fprintf(ficrespl,"******\n");
                   10481:       printf("******\n");
                   10482:       fprintf(ficlog,"******\n");
                   10483:       if(invalidvarcomb[k]){
                   10484:        printf("\nCombination (%d) ignored because no case \n",k); 
                   10485:        fprintf(ficrespl,"#Combination (%d) ignored because no case \n",k); 
                   10486:        fprintf(ficlog,"\nCombination (%d) ignored because no case \n",k); 
                   10487:        continue;
                   10488:       }
1.219     brouard  10489: 
1.238     brouard  10490:       fprintf(ficrespl,"#Age ");
                   10491:       for(j=1;j<=cptcoveff;j++) {
                   10492:        fprintf(ficrespl,"V%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   10493:       }
                   10494:       for(i=1; i<=nlstate;i++) fprintf(ficrespl,"  %d-%d   ",i,i);
                   10495:       fprintf(ficrespl,"Total Years_to_converge\n");
1.227     brouard  10496:     
1.238     brouard  10497:       for (age=agebase; age<=agelim; age++){
                   10498:        /* for (age=agebase; age<=agebase; age++){ */
                   10499:        prevalim(prlim, nlstate, p, age, oldm, savm, ftolpl, ncvyearp, k, nres);
                   10500:        fprintf(ficrespl,"%.0f ",age );
                   10501:        for(j=1;j<=cptcoveff;j++)
                   10502:          fprintf(ficrespl,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   10503:        tot=0.;
                   10504:        for(i=1; i<=nlstate;i++){
                   10505:          tot +=  prlim[i][i];
                   10506:          fprintf(ficrespl," %.5f", prlim[i][i]);
                   10507:        }
                   10508:        fprintf(ficrespl," %.3f %d\n", tot, *ncvyearp);
                   10509:       } /* Age */
                   10510:       /* was end of cptcod */
                   10511:     } /* cptcov */
                   10512:   } /* nres */
1.219     brouard  10513:   return 0;
1.180     brouard  10514: }
                   10515: 
1.218     brouard  10516: 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  10517:        /*--------------- Back Prevalence limit  (backward stable prevalence) --------------*/
1.218     brouard  10518:        
                   10519:        /* Computes the back prevalence limit  for any combination      of covariate values 
                   10520:    * at any age between ageminpar and agemaxpar
                   10521:         */
1.235     brouard  10522:   int i, j, k, i1, nres=0 ;
1.217     brouard  10523:   /* double ftolpl = 1.e-10; */
                   10524:   double age, agebase, agelim;
                   10525:   double tot;
1.218     brouard  10526:   /* double ***mobaverage; */
                   10527:   /* double     **dnewm, **doldm, **dsavm;  /\* for use *\/ */
1.217     brouard  10528: 
                   10529:   strcpy(fileresplb,"PLB_");
                   10530:   strcat(fileresplb,fileresu);
                   10531:   if((ficresplb=fopen(fileresplb,"w"))==NULL) {
1.288     brouard  10532:     printf("Problem with backward prevalence resultfile: %s\n", fileresplb);return 1;
                   10533:     fprintf(ficlog,"Problem with backward prevalence resultfile: %s\n", fileresplb);return 1;
1.217     brouard  10534:   }
1.288     brouard  10535:   printf("Computing backward prevalence: result on file '%s' \n", fileresplb);
                   10536:   fprintf(ficlog,"Computing backward prevalence: result on file '%s' \n", fileresplb);
1.217     brouard  10537:   pstamp(ficresplb);
1.288     brouard  10538:   fprintf(ficresplb,"# Backward prevalence. Precision given by ftolpl=%g \n", ftolpl);
1.217     brouard  10539:   fprintf(ficresplb,"#Age ");
                   10540:   for(i=1; i<=nlstate;i++) fprintf(ficresplb,"%d-%d ",i,i);
                   10541:   fprintf(ficresplb,"\n");
                   10542:   
1.218     brouard  10543:   
                   10544:   /* prlim=matrix(1,nlstate,1,nlstate);*/ /* back in main */
                   10545:   
                   10546:   agebase=ageminpar;
                   10547:   agelim=agemaxpar;
                   10548:   
                   10549:   
1.227     brouard  10550:   i1=pow(2,cptcoveff);
1.218     brouard  10551:   if (cptcovn < 1){i1=1;}
1.227     brouard  10552:   
1.238     brouard  10553:   for(nres=1; nres <= nresult; nres++){ /* For each resultline */
                   10554:     for(k=1; k<=i1;k++){ /* For any combination of dummy covariates, fixed and varying */
1.253     brouard  10555:      if(i1 != 1 && TKresult[nres]!= k)
1.238     brouard  10556:        continue;
                   10557:       //printf("cptcov=%d cptcod=%d codtab=%d\n",cptcov, cptcod,codtabm(cptcod,cptcov));
                   10558:       fprintf(ficresplb,"#******");
                   10559:       printf("#******");
                   10560:       fprintf(ficlog,"#******");
                   10561:       for(j=1;j<=cptcoveff ;j++) {/* all covariates */
                   10562:        fprintf(ficresplb," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   10563:        printf(" V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   10564:        fprintf(ficlog," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   10565:       }
                   10566:       for (j=1; j<= nsq; j++){ /* For each selected (single) quantitative value */
                   10567:        printf(" V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]);
                   10568:        fprintf(ficresplb," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]);
                   10569:        fprintf(ficlog," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]);
                   10570:       }
                   10571:       fprintf(ficresplb,"******\n");
                   10572:       printf("******\n");
                   10573:       fprintf(ficlog,"******\n");
                   10574:       if(invalidvarcomb[k]){
                   10575:        printf("\nCombination (%d) ignored because no cases \n",k); 
                   10576:        fprintf(ficresplb,"#Combination (%d) ignored because no cases \n",k); 
                   10577:        fprintf(ficlog,"\nCombination (%d) ignored because no cases \n",k); 
                   10578:        continue;
                   10579:       }
1.218     brouard  10580:     
1.238     brouard  10581:       fprintf(ficresplb,"#Age ");
                   10582:       for(j=1;j<=cptcoveff;j++) {
                   10583:        fprintf(ficresplb,"V%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   10584:       }
                   10585:       for(i=1; i<=nlstate;i++) fprintf(ficresplb,"  %d-%d   ",i,i);
                   10586:       fprintf(ficresplb,"Total Years_to_converge\n");
1.218     brouard  10587:     
                   10588:     
1.238     brouard  10589:       for (age=agebase; age<=agelim; age++){
                   10590:        /* for (age=agebase; age<=agebase; age++){ */
                   10591:        if(mobilavproj > 0){
                   10592:          /* bprevalim(bprlim, mobaverage, nlstate, p, age, ageminpar, agemaxpar, oldm, savm, doldm, dsavm, ftolpl, ncvyearp, k); */
                   10593:          /* bprevalim(bprlim, mobaverage, nlstate, p, age, oldm, savm, dnewm, doldm, dsavm, ftolpl, ncvyearp, k); */
1.242     brouard  10594:          bprevalim(bprlim, mobaverage, nlstate, p, age, ftolpl, ncvyearp, k, nres);
1.238     brouard  10595:        }else if (mobilavproj == 0){
                   10596:          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);
                   10597:          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);
                   10598:          exit(1);
                   10599:        }else{
                   10600:          /* bprevalim(bprlim, probs, nlstate, p, age, oldm, savm, dnewm, doldm, dsavm, ftolpl, ncvyearp, k); */
1.242     brouard  10601:          bprevalim(bprlim, probs, nlstate, p, age, ftolpl, ncvyearp, k,nres);
1.266     brouard  10602:          /* printf("TOTOT\n"); */
                   10603:           /* exit(1); */
1.238     brouard  10604:        }
                   10605:        fprintf(ficresplb,"%.0f ",age );
                   10606:        for(j=1;j<=cptcoveff;j++)
                   10607:          fprintf(ficresplb,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   10608:        tot=0.;
                   10609:        for(i=1; i<=nlstate;i++){
                   10610:          tot +=  bprlim[i][i];
                   10611:          fprintf(ficresplb," %.5f", bprlim[i][i]);
                   10612:        }
                   10613:        fprintf(ficresplb," %.3f %d\n", tot, *ncvyearp);
                   10614:       } /* Age */
                   10615:       /* was end of cptcod */
1.255     brouard  10616:       /*fprintf(ficresplb,"\n");*/ /* Seems to be necessary for gnuplot only if two result lines and no covariate. */
1.238     brouard  10617:     } /* end of any combination */
                   10618:   } /* end of nres */  
1.218     brouard  10619:   /* hBijx(p, bage, fage); */
                   10620:   /* fclose(ficrespijb); */
                   10621:   
                   10622:   return 0;
1.217     brouard  10623: }
1.218     brouard  10624:  
1.180     brouard  10625: int hPijx(double *p, int bage, int fage){
                   10626:     /*------------- h Pij x at various ages ------------*/
                   10627: 
                   10628:   int stepsize;
                   10629:   int agelim;
                   10630:   int hstepm;
                   10631:   int nhstepm;
1.235     brouard  10632:   int h, i, i1, j, k, k4, nres=0;
1.180     brouard  10633: 
                   10634:   double agedeb;
                   10635:   double ***p3mat;
                   10636: 
1.201     brouard  10637:     strcpy(filerespij,"PIJ_");  strcat(filerespij,fileresu);
1.180     brouard  10638:     if((ficrespij=fopen(filerespij,"w"))==NULL) {
                   10639:       printf("Problem with Pij resultfile: %s\n", filerespij); return 1;
                   10640:       fprintf(ficlog,"Problem with Pij resultfile: %s\n", filerespij); return 1;
                   10641:     }
                   10642:     printf("Computing pij: result on file '%s' \n", filerespij);
                   10643:     fprintf(ficlog,"Computing pij: result on file '%s' \n", filerespij);
                   10644:   
                   10645:     stepsize=(int) (stepm+YEARM-1)/YEARM;
                   10646:     /*if (stepm<=24) stepsize=2;*/
                   10647: 
                   10648:     agelim=AGESUP;
                   10649:     hstepm=stepsize*YEARM; /* Every year of age */
                   10650:     hstepm=hstepm/stepm; /* Typically 2 years, = 2/6 months = 4 */ 
1.218     brouard  10651:                
1.180     brouard  10652:     /* hstepm=1;   aff par mois*/
                   10653:     pstamp(ficrespij);
                   10654:     fprintf(ficrespij,"#****** h Pij x Probability to be in state j at age x+h being in i at x ");
1.227     brouard  10655:     i1= pow(2,cptcoveff);
1.218     brouard  10656:                /* for(cptcov=1,k=0;cptcov<=i1;cptcov++){ */
                   10657:                /*    /\*for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*\/ */
                   10658:                /*      k=k+1;  */
1.235     brouard  10659:     for(nres=1; nres <= nresult; nres++) /* For each resultline */
                   10660:     for(k=1; k<=i1;k++){
1.253     brouard  10661:       if(i1 != 1 && TKresult[nres]!= k)
1.235     brouard  10662:        continue;
1.183     brouard  10663:       fprintf(ficrespij,"\n#****** ");
1.227     brouard  10664:       for(j=1;j<=cptcoveff;j++) 
1.198     brouard  10665:        fprintf(ficrespij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
1.235     brouard  10666:       for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
                   10667:        printf(" V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
                   10668:        fprintf(ficrespij," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
                   10669:       }
1.183     brouard  10670:       fprintf(ficrespij,"******\n");
                   10671:       
                   10672:       for (agedeb=fage; agedeb>=bage; agedeb--){ /* If stepm=6 months */
                   10673:        nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */ 
                   10674:        nhstepm = nhstepm/hstepm; /* Typically 40/4=10 */
                   10675:        
                   10676:        /*        nhstepm=nhstepm*YEARM; aff par mois*/
1.180     brouard  10677:        
1.183     brouard  10678:        p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   10679:        oldm=oldms;savm=savms;
1.235     brouard  10680:        hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k, nres);  
1.183     brouard  10681:        fprintf(ficrespij,"# Cov Agex agex+h hpijx with i,j=");
                   10682:        for(i=1; i<=nlstate;i++)
                   10683:          for(j=1; j<=nlstate+ndeath;j++)
                   10684:            fprintf(ficrespij," %1d-%1d",i,j);
                   10685:        fprintf(ficrespij,"\n");
                   10686:        for (h=0; h<=nhstepm; h++){
                   10687:          /*agedebphstep = agedeb + h*hstepm/YEARM*stepm;*/
                   10688:          fprintf(ficrespij,"%d %3.f %3.f",k, agedeb, agedeb + h*hstepm/YEARM*stepm );
1.180     brouard  10689:          for(i=1; i<=nlstate;i++)
                   10690:            for(j=1; j<=nlstate+ndeath;j++)
1.183     brouard  10691:              fprintf(ficrespij," %.5f", p3mat[i][j][h]);
1.180     brouard  10692:          fprintf(ficrespij,"\n");
                   10693:        }
1.183     brouard  10694:        free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   10695:        fprintf(ficrespij,"\n");
                   10696:       }
1.180     brouard  10697:       /*}*/
                   10698:     }
1.218     brouard  10699:     return 0;
1.180     brouard  10700: }
1.218     brouard  10701:  
                   10702:  int hBijx(double *p, int bage, int fage, double ***prevacurrent){
1.217     brouard  10703:     /*------------- h Bij x at various ages ------------*/
                   10704: 
                   10705:   int stepsize;
1.218     brouard  10706:   /* int agelim; */
                   10707:        int ageminl;
1.217     brouard  10708:   int hstepm;
                   10709:   int nhstepm;
1.238     brouard  10710:   int h, i, i1, j, k, nres;
1.218     brouard  10711:        
1.217     brouard  10712:   double agedeb;
                   10713:   double ***p3mat;
1.218     brouard  10714:        
                   10715:   strcpy(filerespijb,"PIJB_");  strcat(filerespijb,fileresu);
                   10716:   if((ficrespijb=fopen(filerespijb,"w"))==NULL) {
                   10717:     printf("Problem with Pij back resultfile: %s\n", filerespijb); return 1;
                   10718:     fprintf(ficlog,"Problem with Pij back resultfile: %s\n", filerespijb); return 1;
                   10719:   }
                   10720:   printf("Computing pij back: result on file '%s' \n", filerespijb);
                   10721:   fprintf(ficlog,"Computing pij back: result on file '%s' \n", filerespijb);
                   10722:   
                   10723:   stepsize=(int) (stepm+YEARM-1)/YEARM;
                   10724:   /*if (stepm<=24) stepsize=2;*/
1.217     brouard  10725:   
1.218     brouard  10726:   /* agelim=AGESUP; */
1.289     brouard  10727:   ageminl=AGEINF; /* was 30 */
1.218     brouard  10728:   hstepm=stepsize*YEARM; /* Every year of age */
                   10729:   hstepm=hstepm/stepm; /* Typically 2 years, = 2/6 months = 4 */
                   10730:   
                   10731:   /* hstepm=1;   aff par mois*/
                   10732:   pstamp(ficrespijb);
1.255     brouard  10733:   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  10734:   i1= pow(2,cptcoveff);
1.218     brouard  10735:   /* for(cptcov=1,k=0;cptcov<=i1;cptcov++){ */
                   10736:   /*    /\*for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*\/ */
                   10737:   /*   k=k+1;  */
1.238     brouard  10738:   for(nres=1; nres <= nresult; nres++){ /* For each resultline */
                   10739:     for(k=1; k<=i1;k++){ /* For any combination of dummy covariates, fixed and varying */
1.253     brouard  10740:       if(i1 != 1 && TKresult[nres]!= k)
1.238     brouard  10741:        continue;
                   10742:       fprintf(ficrespijb,"\n#****** ");
                   10743:       for(j=1;j<=cptcoveff;j++)
                   10744:        fprintf(ficrespijb,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   10745:       for (j=1; j<= nsq; j++){ /* For each selected (single) quantitative value */
                   10746:        fprintf(ficrespijb," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]);
                   10747:       }
                   10748:       fprintf(ficrespijb,"******\n");
1.264     brouard  10749:       if(invalidvarcomb[k]){  /* Is it necessary here? */
1.238     brouard  10750:        fprintf(ficrespijb,"\n#Combination (%d) ignored because no cases \n",k); 
                   10751:        continue;
                   10752:       }
                   10753:       
                   10754:       /* for (agedeb=fage; agedeb>=bage; agedeb--){ /\* If stepm=6 months *\/ */
                   10755:       for (agedeb=bage; agedeb<=fage; agedeb++){ /* If stepm=6 months and estepm=24 (2 years) */
                   10756:        /* nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm); /\* Typically 20 years = 20*12/6=40 *\/ */
1.297     brouard  10757:        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 */
                   10758:        nhstepm = nhstepm/hstepm; /* Typically 40/4=10, because estepm=24 stepm=6 => hstepm=24/6=4 or 28*/
1.238     brouard  10759:        
                   10760:        /*        nhstepm=nhstepm*YEARM; aff par mois*/
                   10761:        
1.266     brouard  10762:        p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm); /* We can't have it at an upper level because of nhstepm */
                   10763:        /* and memory limitations if stepm is small */
                   10764: 
1.238     brouard  10765:        /* oldm=oldms;savm=savms; */
                   10766:        /* hbxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);   */
1.267     brouard  10767:        hbxij(p3mat,nhstepm,agedeb,hstepm,p,prevacurrent,nlstate,stepm, k, nres);
1.238     brouard  10768:        /* hbxij(p3mat,nhstepm,agedeb,hstepm,p,prevacurrent,nlstate,stepm,oldm,savm, dnewm, doldm, dsavm, k); */
1.255     brouard  10769:        fprintf(ficrespijb,"# Cov Agex agex-h hbijx with i,j=");
1.217     brouard  10770:        for(i=1; i<=nlstate;i++)
                   10771:          for(j=1; j<=nlstate+ndeath;j++)
1.238     brouard  10772:            fprintf(ficrespijb," %1d-%1d",i,j);
1.217     brouard  10773:        fprintf(ficrespijb,"\n");
1.238     brouard  10774:        for (h=0; h<=nhstepm; h++){
                   10775:          /*agedebphstep = agedeb + h*hstepm/YEARM*stepm;*/
                   10776:          fprintf(ficrespijb,"%d %3.f %3.f",k, agedeb, agedeb - h*hstepm/YEARM*stepm );
                   10777:          /* fprintf(ficrespijb,"%d %3.f %3.f",k, agedeb, agedeb + h*hstepm/YEARM*stepm ); */
                   10778:          for(i=1; i<=nlstate;i++)
                   10779:            for(j=1; j<=nlstate+ndeath;j++)
                   10780:              fprintf(ficrespijb," %.5f", p3mat[i][j][h]);
                   10781:          fprintf(ficrespijb,"\n");
                   10782:        }
                   10783:        free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   10784:        fprintf(ficrespijb,"\n");
                   10785:       } /* end age deb */
                   10786:     } /* end combination */
                   10787:   } /* end nres */
1.218     brouard  10788:   return 0;
                   10789:  } /*  hBijx */
1.217     brouard  10790: 
1.180     brouard  10791: 
1.136     brouard  10792: /***********************************************/
                   10793: /**************** Main Program *****************/
                   10794: /***********************************************/
                   10795: 
                   10796: int main(int argc, char *argv[])
                   10797: {
                   10798: #ifdef GSL
                   10799:   const gsl_multimin_fminimizer_type *T;
                   10800:   size_t iteri = 0, it;
                   10801:   int rval = GSL_CONTINUE;
                   10802:   int status = GSL_SUCCESS;
                   10803:   double ssval;
                   10804: #endif
                   10805:   int movingaverage(double ***probs, double bage,double fage, double ***mobaverage, int mobilav);
1.290     brouard  10806:   int i,j, k, iter=0,m,size=100, cptcod; /* Suppressing because nobs */
                   10807:   /* int i,j, k, n=MAXN,iter=0,m,size=100, cptcod; */
1.209     brouard  10808:   int ncvyear=0; /* Number of years needed for the period prevalence to converge */
1.164     brouard  10809:   int jj, ll, li, lj, lk;
1.136     brouard  10810:   int numlinepar=0; /* Current linenumber of parameter file */
1.197     brouard  10811:   int num_filled;
1.136     brouard  10812:   int itimes;
                   10813:   int NDIM=2;
                   10814:   int vpopbased=0;
1.235     brouard  10815:   int nres=0;
1.258     brouard  10816:   int endishere=0;
1.277     brouard  10817:   int noffset=0;
1.274     brouard  10818:   int ncurrv=0; /* Temporary variable */
                   10819:   
1.164     brouard  10820:   char ca[32], cb[32];
1.136     brouard  10821:   /*  FILE *fichtm; *//* Html File */
                   10822:   /* FILE *ficgp;*/ /*Gnuplot File */
                   10823:   struct stat info;
1.191     brouard  10824:   double agedeb=0.;
1.194     brouard  10825: 
                   10826:   double ageminpar=AGEOVERFLOW,agemin=AGEOVERFLOW, agemaxpar=-AGEOVERFLOW, agemax=-AGEOVERFLOW;
1.219     brouard  10827:   double ageminout=-AGEOVERFLOW,agemaxout=AGEOVERFLOW; /* Smaller Age range redefined after movingaverage */
1.136     brouard  10828: 
1.165     brouard  10829:   double fret;
1.191     brouard  10830:   double dum=0.; /* Dummy variable */
1.136     brouard  10831:   double ***p3mat;
1.218     brouard  10832:   /* double ***mobaverage; */
1.164     brouard  10833: 
                   10834:   char line[MAXLINE];
1.197     brouard  10835:   char path[MAXLINE],pathc[MAXLINE],pathcd[MAXLINE],pathtot[MAXLINE];
                   10836: 
1.234     brouard  10837:   char  modeltemp[MAXLINE];
1.230     brouard  10838:   char resultline[MAXLINE];
                   10839:   
1.136     brouard  10840:   char pathr[MAXLINE], pathimach[MAXLINE]; 
1.164     brouard  10841:   char *tok, *val; /* pathtot */
1.290     brouard  10842:   int firstobs=1, lastobs=10; /* nobs = lastobs-firstobs declared globally ;*/
1.195     brouard  10843:   int c,  h , cpt, c2;
1.191     brouard  10844:   int jl=0;
                   10845:   int i1, j1, jk, stepsize=0;
1.194     brouard  10846:   int count=0;
                   10847: 
1.164     brouard  10848:   int *tab; 
1.136     brouard  10849:   int mobilavproj=0 , prevfcast=0 ; /* moving average of prev, If prevfcast=1 prevalence projection */
1.296     brouard  10850:   /* double anprojd, mprojd, jprojd; /\* For eventual projections *\/ */
                   10851:   /* double anprojf, mprojf, jprojf; */
                   10852:   /* double jintmean,mintmean,aintmean;   */
                   10853:   int prvforecast = 0; /* Might be 1 (date of beginning of projection is a choice or 2 is the dateintmean */
                   10854:   int prvbackcast = 0; /* Might be 1 (date of beginning of projection is a choice or 2 is the dateintmean */
                   10855:   double yrfproj= 10.0; /* Number of years of forward projections */
                   10856:   double yrbproj= 10.0; /* Number of years of backward projections */
                   10857:   int prevbcast=0; /* defined as global for mlikeli and mle, replacing backcast */
1.136     brouard  10858:   int mobilav=0,popforecast=0;
1.191     brouard  10859:   int hstepm=0, nhstepm=0;
1.136     brouard  10860:   int agemortsup;
                   10861:   float  sumlpop=0.;
                   10862:   double jprev1=1, mprev1=1,anprev1=2000,jprev2=1, mprev2=1,anprev2=2000;
                   10863:   double jpyram=1, mpyram=1,anpyram=2000,jpyram1=1, mpyram1=1,anpyram1=2000;
                   10864: 
1.191     brouard  10865:   double bage=0, fage=110., age, agelim=0., agebase=0.;
1.136     brouard  10866:   double ftolpl=FTOL;
                   10867:   double **prlim;
1.217     brouard  10868:   double **bprlim;
1.136     brouard  10869:   double ***param; /* Matrix of parameters */
1.251     brouard  10870:   double ***paramstart; /* Matrix of starting parameter values */
                   10871:   double  *p, *pstart; /* p=param[1][1] pstart is for starting values guessed by freqsummary */
1.136     brouard  10872:   double **matcov; /* Matrix of covariance */
1.203     brouard  10873:   double **hess; /* Hessian matrix */
1.136     brouard  10874:   double ***delti3; /* Scale */
                   10875:   double *delti; /* Scale */
                   10876:   double ***eij, ***vareij;
                   10877:   double **varpl; /* Variances of prevalence limits by age */
1.269     brouard  10878: 
1.136     brouard  10879:   double *epj, vepp;
1.164     brouard  10880: 
1.273     brouard  10881:   double dateprev1, dateprev2;
1.296     brouard  10882:   double jproj1=1,mproj1=1,anproj1=2000,jproj2=1,mproj2=1,anproj2=2000, dateproj1=0, dateproj2=0, dateprojd=0, dateprojf=0;
                   10883:   double jback1=1,mback1=1,anback1=2000,jback2=1,mback2=1,anback2=2000, dateback1=0, dateback2=0, datebackd=0, datebackf=0;
                   10884: 
1.217     brouard  10885: 
1.136     brouard  10886:   double **ximort;
1.145     brouard  10887:   char *alph[]={"a","a","b","c","d","e"}, str[4]="1234";
1.136     brouard  10888:   int *dcwave;
                   10889: 
1.164     brouard  10890:   char z[1]="c";
1.136     brouard  10891: 
                   10892:   /*char  *strt;*/
                   10893:   char strtend[80];
1.126     brouard  10894: 
1.164     brouard  10895: 
1.126     brouard  10896: /*   setlocale (LC_ALL, ""); */
                   10897: /*   bindtextdomain (PACKAGE, LOCALEDIR); */
                   10898: /*   textdomain (PACKAGE); */
                   10899: /*   setlocale (LC_CTYPE, ""); */
                   10900: /*   setlocale (LC_MESSAGES, ""); */
                   10901: 
                   10902:   /*   gettimeofday(&start_time, (struct timezone*)0); */ /* at first time */
1.157     brouard  10903:   rstart_time = time(NULL);  
                   10904:   /*  (void) gettimeofday(&start_time,&tzp);*/
                   10905:   start_time = *localtime(&rstart_time);
1.126     brouard  10906:   curr_time=start_time;
1.157     brouard  10907:   /*tml = *localtime(&start_time.tm_sec);*/
                   10908:   /* strcpy(strstart,asctime(&tml)); */
                   10909:   strcpy(strstart,asctime(&start_time));
1.126     brouard  10910: 
                   10911: /*  printf("Localtime (at start)=%s",strstart); */
1.157     brouard  10912: /*  tp.tm_sec = tp.tm_sec +86400; */
                   10913: /*  tm = *localtime(&start_time.tm_sec); */
1.126     brouard  10914: /*   tmg.tm_year=tmg.tm_year +dsign*dyear; */
                   10915: /*   tmg.tm_mon=tmg.tm_mon +dsign*dmonth; */
                   10916: /*   tmg.tm_hour=tmg.tm_hour + 1; */
1.157     brouard  10917: /*   tp.tm_sec = mktime(&tmg); */
1.126     brouard  10918: /*   strt=asctime(&tmg); */
                   10919: /*   printf("Time(after) =%s",strstart);  */
                   10920: /*  (void) time (&time_value);
                   10921: *  printf("time=%d,t-=%d\n",time_value,time_value-86400);
                   10922: *  tm = *localtime(&time_value);
                   10923: *  strstart=asctime(&tm);
                   10924: *  printf("tim_value=%d,asctime=%s\n",time_value,strstart); 
                   10925: */
                   10926: 
                   10927:   nberr=0; /* Number of errors and warnings */
                   10928:   nbwarn=0;
1.184     brouard  10929: #ifdef WIN32
                   10930:   _getcwd(pathcd, size);
                   10931: #else
1.126     brouard  10932:   getcwd(pathcd, size);
1.184     brouard  10933: #endif
1.191     brouard  10934:   syscompilerinfo(0);
1.196     brouard  10935:   printf("\nIMaCh version %s, %s\n%s",version, copyright, fullversion);
1.126     brouard  10936:   if(argc <=1){
                   10937:     printf("\nEnter the parameter file name: ");
1.205     brouard  10938:     if(!fgets(pathr,FILENAMELENGTH,stdin)){
                   10939:       printf("ERROR Empty parameter file name\n");
                   10940:       goto end;
                   10941:     }
1.126     brouard  10942:     i=strlen(pathr);
                   10943:     if(pathr[i-1]=='\n')
                   10944:       pathr[i-1]='\0';
1.156     brouard  10945:     i=strlen(pathr);
1.205     brouard  10946:     if(i >= 1 && pathr[i-1]==' ') {/* This may happen when dragging on oS/X! */
1.156     brouard  10947:       pathr[i-1]='\0';
1.205     brouard  10948:     }
                   10949:     i=strlen(pathr);
                   10950:     if( i==0 ){
                   10951:       printf("ERROR Empty parameter file name\n");
                   10952:       goto end;
                   10953:     }
                   10954:     for (tok = pathr; tok != NULL; ){
1.126     brouard  10955:       printf("Pathr |%s|\n",pathr);
                   10956:       while ((val = strsep(&tok, "\"" )) != NULL && *val == '\0');
                   10957:       printf("val= |%s| pathr=%s\n",val,pathr);
                   10958:       strcpy (pathtot, val);
                   10959:       if(pathr[0] == '\0') break; /* Dirty */
                   10960:     }
                   10961:   }
1.281     brouard  10962:   else if (argc<=2){
                   10963:     strcpy(pathtot,argv[1]);
                   10964:   }
1.126     brouard  10965:   else{
                   10966:     strcpy(pathtot,argv[1]);
1.281     brouard  10967:     strcpy(z,argv[2]);
                   10968:     printf("\nargv[2]=%s z=%c\n",argv[2],z[0]);
1.126     brouard  10969:   }
                   10970:   /*if(getcwd(pathcd, MAXLINE)!= NULL)printf ("Error pathcd\n");*/
                   10971:   /*cygwin_split_path(pathtot,path,optionfile);
                   10972:     printf("pathtot=%s, path=%s, optionfile=%s\n",pathtot,path,optionfile);*/
                   10973:   /* cutv(path,optionfile,pathtot,'\\');*/
                   10974: 
                   10975:   /* Split argv[0], imach program to get pathimach */
                   10976:   printf("\nargv[0]=%s argv[1]=%s, \n",argv[0],argv[1]);
                   10977:   split(argv[0],pathimach,optionfile,optionfilext,optionfilefiname);
                   10978:   printf("\nargv[0]=%s pathimach=%s, \noptionfile=%s \noptionfilext=%s \noptionfilefiname=%s\n",argv[0],pathimach,optionfile,optionfilext,optionfilefiname);
                   10979:  /*   strcpy(pathimach,argv[0]); */
                   10980:   /* Split argv[1]=pathtot, parameter file name to get path, optionfile, extension and name */
                   10981:   split(pathtot,path,optionfile,optionfilext,optionfilefiname);
                   10982:   printf("\npathtot=%s,\npath=%s,\noptionfile=%s \noptionfilext=%s \noptionfilefiname=%s\n",pathtot,path,optionfile,optionfilext,optionfilefiname);
1.184     brouard  10983: #ifdef WIN32
                   10984:   _chdir(path); /* Can be a relative path */
                   10985:   if(_getcwd(pathcd,MAXLINE) > 0) /* So pathcd is the full path */
                   10986: #else
1.126     brouard  10987:   chdir(path); /* Can be a relative path */
1.184     brouard  10988:   if (getcwd(pathcd, MAXLINE) > 0) /* So pathcd is the full path */
                   10989: #endif
                   10990:   printf("Current directory %s!\n",pathcd);
1.126     brouard  10991:   strcpy(command,"mkdir ");
                   10992:   strcat(command,optionfilefiname);
                   10993:   if((outcmd=system(command)) != 0){
1.169     brouard  10994:     printf("Directory already exists (or can't create it) %s%s, err=%d\n",path,optionfilefiname,outcmd);
1.126     brouard  10995:     /* fprintf(ficlog,"Problem creating directory %s%s\n",path,optionfilefiname); */
                   10996:     /* fclose(ficlog); */
                   10997: /*     exit(1); */
                   10998:   }
                   10999: /*   if((imk=mkdir(optionfilefiname))<0){ */
                   11000: /*     perror("mkdir"); */
                   11001: /*   } */
                   11002: 
                   11003:   /*-------- arguments in the command line --------*/
                   11004: 
1.186     brouard  11005:   /* Main Log file */
1.126     brouard  11006:   strcat(filelog, optionfilefiname);
                   11007:   strcat(filelog,".log");    /* */
                   11008:   if((ficlog=fopen(filelog,"w"))==NULL)    {
                   11009:     printf("Problem with logfile %s\n",filelog);
                   11010:     goto end;
                   11011:   }
                   11012:   fprintf(ficlog,"Log filename:%s\n",filelog);
1.197     brouard  11013:   fprintf(ficlog,"Version %s %s",version,fullversion);
1.126     brouard  11014:   fprintf(ficlog,"\nEnter the parameter file name: \n");
                   11015:   fprintf(ficlog,"pathimach=%s\npathtot=%s\n\
                   11016:  path=%s \n\
                   11017:  optionfile=%s\n\
                   11018:  optionfilext=%s\n\
1.156     brouard  11019:  optionfilefiname='%s'\n",pathimach,pathtot,path,optionfile,optionfilext,optionfilefiname);
1.126     brouard  11020: 
1.197     brouard  11021:   syscompilerinfo(1);
1.167     brouard  11022: 
1.126     brouard  11023:   printf("Local time (at start):%s",strstart);
                   11024:   fprintf(ficlog,"Local time (at start): %s",strstart);
                   11025:   fflush(ficlog);
                   11026: /*   (void) gettimeofday(&curr_time,&tzp); */
1.157     brouard  11027: /*   printf("Elapsed time %d\n", asc_diff_time(curr_time.tm_sec-start_time.tm_sec,tmpout)); */
1.126     brouard  11028: 
                   11029:   /* */
                   11030:   strcpy(fileres,"r");
                   11031:   strcat(fileres, optionfilefiname);
1.201     brouard  11032:   strcat(fileresu, optionfilefiname); /* Without r in front */
1.126     brouard  11033:   strcat(fileres,".txt");    /* Other files have txt extension */
1.201     brouard  11034:   strcat(fileresu,".txt");    /* Other files have txt extension */
1.126     brouard  11035: 
1.186     brouard  11036:   /* Main ---------arguments file --------*/
1.126     brouard  11037: 
                   11038:   if((ficpar=fopen(optionfile,"r"))==NULL)    {
1.155     brouard  11039:     printf("Problem with optionfile '%s' with errno='%s'\n",optionfile,strerror(errno));
                   11040:     fprintf(ficlog,"Problem with optionfile '%s' with errno='%s'\n",optionfile,strerror(errno));
1.126     brouard  11041:     fflush(ficlog);
1.149     brouard  11042:     /* goto end; */
                   11043:     exit(70); 
1.126     brouard  11044:   }
                   11045: 
                   11046:   strcpy(filereso,"o");
1.201     brouard  11047:   strcat(filereso,fileresu);
1.126     brouard  11048:   if((ficparo=fopen(filereso,"w"))==NULL) { /* opened on subdirectory */
                   11049:     printf("Problem with Output resultfile: %s\n", filereso);
                   11050:     fprintf(ficlog,"Problem with Output resultfile: %s\n", filereso);
                   11051:     fflush(ficlog);
                   11052:     goto end;
                   11053:   }
1.278     brouard  11054:       /*-------- Rewriting parameter file ----------*/
                   11055:   strcpy(rfileres,"r");    /* "Rparameterfile */
                   11056:   strcat(rfileres,optionfilefiname);    /* Parameter file first name */
                   11057:   strcat(rfileres,".");    /* */
                   11058:   strcat(rfileres,optionfilext);    /* Other files have txt extension */
                   11059:   if((ficres =fopen(rfileres,"w"))==NULL) {
                   11060:     printf("Problem writing new parameter file: %s\n", rfileres);goto end;
                   11061:     fprintf(ficlog,"Problem writing new parameter file: %s\n", rfileres);goto end;
                   11062:     fflush(ficlog);
                   11063:     goto end;
                   11064:   }
                   11065:   fprintf(ficres,"#IMaCh %s\n",version);
1.126     brouard  11066: 
1.278     brouard  11067:                                      
1.126     brouard  11068:   /* Reads comments: lines beginning with '#' */
                   11069:   numlinepar=0;
1.277     brouard  11070:   /* Is it a BOM UTF-8 Windows file? */
                   11071:   /* First parameter line */
1.197     brouard  11072:   while(fgets(line, MAXLINE, ficpar)) {
1.277     brouard  11073:     noffset=0;
                   11074:     if( line[0] == (char)0xEF && line[1] == (char)0xBB) /* EF BB BF */
                   11075:     {
                   11076:       noffset=noffset+3;
                   11077:       printf("# File is an UTF8 Bom.\n"); // 0xBF
                   11078:     }
                   11079:     else if( line[0] == (char)0xFE && line[1] == (char)0xFF)
                   11080:     {
                   11081:       noffset=noffset+2;
                   11082:       printf("# File is an UTF16BE BOM file\n");
                   11083:     }
                   11084:     else if( line[0] == 0 && line[1] == 0)
                   11085:     {
                   11086:       if( line[2] == (char)0xFE && line[3] == (char)0xFF){
                   11087:        noffset=noffset+4;
                   11088:        printf("# File is an UTF16BE BOM file\n");
                   11089:       }
                   11090:     } else{
                   11091:       ;/*printf(" Not a BOM file\n");*/
                   11092:     }
                   11093:   
1.197     brouard  11094:     /* If line starts with a # it is a comment */
1.277     brouard  11095:     if (line[noffset] == '#') {
1.197     brouard  11096:       numlinepar++;
                   11097:       fputs(line,stdout);
                   11098:       fputs(line,ficparo);
1.278     brouard  11099:       fputs(line,ficres);
1.197     brouard  11100:       fputs(line,ficlog);
                   11101:       continue;
                   11102:     }else
                   11103:       break;
                   11104:   }
                   11105:   if((num_filled=sscanf(line,"title=%s datafile=%s lastobs=%d firstpass=%d lastpass=%d\n", \
                   11106:                        title, datafile, &lastobs, &firstpass,&lastpass)) !=EOF){
                   11107:     if (num_filled != 5) {
                   11108:       printf("Should be 5 parameters\n");
1.283     brouard  11109:       fprintf(ficlog,"Should be 5 parameters\n");
1.197     brouard  11110:     }
1.126     brouard  11111:     numlinepar++;
1.197     brouard  11112:     printf("title=%s datafile=%s lastobs=%d firstpass=%d lastpass=%d\n", title, datafile, lastobs, firstpass,lastpass);
1.283     brouard  11113:     fprintf(ficparo,"title=%s datafile=%s lastobs=%d firstpass=%d lastpass=%d\n", title, datafile, lastobs, firstpass,lastpass);
                   11114:     fprintf(ficres,"title=%s datafile=%s lastobs=%d firstpass=%d lastpass=%d\n", title, datafile, lastobs, firstpass,lastpass);
                   11115:     fprintf(ficlog,"title=%s datafile=%s lastobs=%d firstpass=%d lastpass=%d\n", title, datafile, lastobs, firstpass,lastpass);
1.197     brouard  11116:   }
                   11117:   /* Second parameter line */
                   11118:   while(fgets(line, MAXLINE, ficpar)) {
1.283     brouard  11119:     /* while(fscanf(ficpar,"%[^\n]", line)) { */
                   11120:     /* If line starts with a # it is a comment. Strangely fgets reads the EOL and fputs doesn't */
1.197     brouard  11121:     if (line[0] == '#') {
                   11122:       numlinepar++;
1.283     brouard  11123:       printf("%s",line);
                   11124:       fprintf(ficres,"%s",line);
                   11125:       fprintf(ficparo,"%s",line);
                   11126:       fprintf(ficlog,"%s",line);
1.197     brouard  11127:       continue;
                   11128:     }else
                   11129:       break;
                   11130:   }
1.223     brouard  11131:   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", \
                   11132:                        &ftol, &stepm, &ncovcol, &nqv, &ntv, &nqtv, &nlstate, &ndeath, &maxwav, &mle, &weightopt)) !=EOF){
                   11133:     if (num_filled != 11) {
                   11134:       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  11135:       printf("but line=%s\n",line);
1.283     brouard  11136:       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");
                   11137:       fprintf(ficlog,"but line=%s\n",line);
1.197     brouard  11138:     }
1.286     brouard  11139:     if( lastpass > maxwav){
                   11140:       printf("Error (lastpass = %d) > (maxwav = %d)\n",lastpass, maxwav);
                   11141:       fprintf(ficlog,"Error (lastpass = %d) > (maxwav = %d)\n",lastpass, maxwav);
                   11142:       fflush(ficlog);
                   11143:       goto end;
                   11144:     }
                   11145:       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  11146:     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  11147:     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  11148:     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  11149:   }
1.203     brouard  11150:   /* ftolpl=6*ftol*1.e5; /\* 6.e-3 make convergences in less than 80 loops for the prevalence limit *\/ */
1.209     brouard  11151:   /*ftolpl=6.e-4; *//* 6.e-3 make convergences in less than 80 loops for the prevalence limit */
1.197     brouard  11152:   /* Third parameter line */
                   11153:   while(fgets(line, MAXLINE, ficpar)) {
                   11154:     /* If line starts with a # it is a comment */
                   11155:     if (line[0] == '#') {
                   11156:       numlinepar++;
1.283     brouard  11157:       printf("%s",line);
                   11158:       fprintf(ficres,"%s",line);
                   11159:       fprintf(ficparo,"%s",line);
                   11160:       fprintf(ficlog,"%s",line);
1.197     brouard  11161:       continue;
                   11162:     }else
                   11163:       break;
                   11164:   }
1.201     brouard  11165:   if((num_filled=sscanf(line,"model=1+age%[^.\n]", model)) !=EOF){
1.279     brouard  11166:     if (num_filled != 1){
                   11167:       printf("ERROR %d: Model should be at minimum 'model=1+age' %s\n",num_filled, line);
                   11168:       fprintf(ficlog,"ERROR %d: Model should be at minimum 'model=1+age' %s\n",num_filled, line);
1.197     brouard  11169:       model[0]='\0';
                   11170:       goto end;
                   11171:     }
                   11172:     else{
                   11173:       if (model[0]=='+'){
                   11174:        for(i=1; i<=strlen(model);i++)
                   11175:          modeltemp[i-1]=model[i];
1.201     brouard  11176:        strcpy(model,modeltemp); 
1.197     brouard  11177:       }
                   11178:     }
1.199     brouard  11179:     /* printf(" model=1+age%s modeltemp= %s, model=%s\n",model, modeltemp, model);fflush(stdout); */
1.203     brouard  11180:     printf("model=1+age+%s\n",model);fflush(stdout);
1.283     brouard  11181:     fprintf(ficparo,"model=1+age+%s\n",model);fflush(stdout);
                   11182:     fprintf(ficres,"model=1+age+%s\n",model);fflush(stdout);
                   11183:     fprintf(ficlog,"model=1+age+%s\n",model);fflush(stdout);
1.197     brouard  11184:   }
                   11185:   /* 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); */
                   11186:   /* numlinepar=numlinepar+3; /\* In general *\/ */
                   11187:   /* 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  11188:   /* 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); */
                   11189:   /* 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  11190:   fflush(ficlog);
1.190     brouard  11191:   /* if(model[0]=='#'|| model[0]== '\0'){ */
                   11192:   if(model[0]=='#'){
1.279     brouard  11193:     printf("Error in 'model' line: model should start with 'model=1+age+' and end without space \n \
                   11194:  'model=1+age+' or 'model=1+age+V1.' or 'model=1+age+age*age+V1+V1*age' or \n \
                   11195:  'model=1+age+V1+V2' or 'model=1+age+V1+V2+V1*V2' etc. \n");           \
1.187     brouard  11196:     if(mle != -1){
1.279     brouard  11197:       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  11198:       exit(1);
                   11199:     }
                   11200:   }
1.126     brouard  11201:   while((c=getc(ficpar))=='#' && c!= EOF){
                   11202:     ungetc(c,ficpar);
                   11203:     fgets(line, MAXLINE, ficpar);
                   11204:     numlinepar++;
1.195     brouard  11205:     if(line[1]=='q'){ /* This #q will quit imach (the answer is q) */
                   11206:       z[0]=line[1];
                   11207:     }
                   11208:     /* printf("****line [1] = %c \n",line[1]); */
1.141     brouard  11209:     fputs(line, stdout);
                   11210:     //puts(line);
1.126     brouard  11211:     fputs(line,ficparo);
                   11212:     fputs(line,ficlog);
                   11213:   }
                   11214:   ungetc(c,ficpar);
                   11215: 
                   11216:    
1.290     brouard  11217:   covar=matrix(0,NCOVMAX,firstobs,lastobs);  /**< used in readdata */
                   11218:   if(nqv>=1)coqvar=matrix(1,nqv,firstobs,lastobs);  /**< Fixed quantitative covariate */
                   11219:   if(nqtv>=1)cotqvar=ma3x(1,maxwav,1,nqtv,firstobs,lastobs);  /**< Time varying quantitative covariate */
                   11220:   if(ntv+nqtv>=1)cotvar=ma3x(1,maxwav,1,ntv+nqtv,firstobs,lastobs);  /**< Time varying covariate (dummy and quantitative)*/
1.136     brouard  11221:   cptcovn=0; /*Number of covariates, i.e. number of '+' in model statement plus one, indepently of n in Vn*/
                   11222:   /* v1+v2+v3+v2*v4+v5*age makes cptcovn = 5
                   11223:      v1+v2*age+v2*v3 makes cptcovn = 3
                   11224:   */
                   11225:   if (strlen(model)>1) 
1.187     brouard  11226:     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  11227:   else
1.187     brouard  11228:     ncovmodel=2; /* Constant and age */
1.133     brouard  11229:   nforce= (nlstate+ndeath-1)*nlstate; /* Number of forces ij from state i to j */
                   11230:   npar= nforce*ncovmodel; /* Number of parameters like aij*/
1.131     brouard  11231:   if(npar >MAXPARM || nlstate >NLSTATEMAX || ndeath >NDEATHMAX || ncovmodel>NCOVMAX){
                   11232:     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);
                   11233:     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);
                   11234:     fflush(stdout);
                   11235:     fclose (ficlog);
                   11236:     goto end;
                   11237:   }
1.126     brouard  11238:   delti3= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
                   11239:   delti=delti3[1][1];
                   11240:   /*delti=vector(1,npar); *//* Scale of each paramater (output from hesscov)*/
                   11241:   if(mle==-1){ /* Print a wizard for help writing covariance matrix */
1.247     brouard  11242: /* We could also provide initial parameters values giving by simple logistic regression 
                   11243:  * only one way, that is without matrix product. We will have nlstate maximizations */
                   11244:       /* for(i=1;i<nlstate;i++){ */
                   11245:       /*       /\*reducing xi for 1 to npar to 1 to ncovmodel; *\/ */
                   11246:       /*    mlikeli(ficres,p, ncovmodel, ncovmodel, nlstate, ftol, funcnoprod); */
                   11247:       /* } */
1.126     brouard  11248:     prwizard(ncovmodel, nlstate, ndeath, model, ficparo);
1.191     brouard  11249:     printf(" You chose mle=-1, look at file %s for a template of covariance matrix \n",filereso);
                   11250:     fprintf(ficlog," You chose mle=-1, look at file %s for a template of covariance matrix \n",filereso);
1.126     brouard  11251:     free_ma3x(delti3,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel); 
                   11252:     fclose (ficparo);
                   11253:     fclose (ficlog);
                   11254:     goto end;
                   11255:     exit(0);
1.220     brouard  11256:   }  else if(mle==-5) { /* Main Wizard */
1.126     brouard  11257:     prwizard(ncovmodel, nlstate, ndeath, model, ficparo);
1.192     brouard  11258:     printf(" You chose mle=-3, look at file %s for a template of covariance matrix \n",filereso);
                   11259:     fprintf(ficlog," You chose mle=-3, look at file %s for a template of covariance matrix \n",filereso);
1.126     brouard  11260:     param= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
                   11261:     matcov=matrix(1,npar,1,npar);
1.203     brouard  11262:     hess=matrix(1,npar,1,npar);
1.220     brouard  11263:   }  else{ /* Begin of mle != -1 or -5 */
1.145     brouard  11264:     /* Read guessed parameters */
1.126     brouard  11265:     /* Reads comments: lines beginning with '#' */
                   11266:     while((c=getc(ficpar))=='#' && c!= EOF){
                   11267:       ungetc(c,ficpar);
                   11268:       fgets(line, MAXLINE, ficpar);
                   11269:       numlinepar++;
1.141     brouard  11270:       fputs(line,stdout);
1.126     brouard  11271:       fputs(line,ficparo);
                   11272:       fputs(line,ficlog);
                   11273:     }
                   11274:     ungetc(c,ficpar);
                   11275:     
                   11276:     param= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
1.251     brouard  11277:     paramstart= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
1.126     brouard  11278:     for(i=1; i <=nlstate; i++){
1.234     brouard  11279:       j=0;
1.126     brouard  11280:       for(jj=1; jj <=nlstate+ndeath; jj++){
1.234     brouard  11281:        if(jj==i) continue;
                   11282:        j++;
1.292     brouard  11283:        while((c=getc(ficpar))=='#' && c!= EOF){
                   11284:          ungetc(c,ficpar);
                   11285:          fgets(line, MAXLINE, ficpar);
                   11286:          numlinepar++;
                   11287:          fputs(line,stdout);
                   11288:          fputs(line,ficparo);
                   11289:          fputs(line,ficlog);
                   11290:        }
                   11291:        ungetc(c,ficpar);
1.234     brouard  11292:        fscanf(ficpar,"%1d%1d",&i1,&j1);
                   11293:        if ((i1 != i) || (j1 != jj)){
                   11294:          printf("Error in line parameters number %d, %1d%1d instead of %1d%1d \n \
1.126     brouard  11295: It might be a problem of design; if ncovcol and the model are correct\n \
                   11296: run imach with mle=-1 to get a correct template of the parameter file.\n",numlinepar, i,j, i1, j1);
1.234     brouard  11297:          exit(1);
                   11298:        }
                   11299:        fprintf(ficparo,"%1d%1d",i1,j1);
                   11300:        if(mle==1)
                   11301:          printf("%1d%1d",i,jj);
                   11302:        fprintf(ficlog,"%1d%1d",i,jj);
                   11303:        for(k=1; k<=ncovmodel;k++){
                   11304:          fscanf(ficpar," %lf",&param[i][j][k]);
                   11305:          if(mle==1){
                   11306:            printf(" %lf",param[i][j][k]);
                   11307:            fprintf(ficlog," %lf",param[i][j][k]);
                   11308:          }
                   11309:          else
                   11310:            fprintf(ficlog," %lf",param[i][j][k]);
                   11311:          fprintf(ficparo," %lf",param[i][j][k]);
                   11312:        }
                   11313:        fscanf(ficpar,"\n");
                   11314:        numlinepar++;
                   11315:        if(mle==1)
                   11316:          printf("\n");
                   11317:        fprintf(ficlog,"\n");
                   11318:        fprintf(ficparo,"\n");
1.126     brouard  11319:       }
                   11320:     }  
                   11321:     fflush(ficlog);
1.234     brouard  11322:     
1.251     brouard  11323:     /* Reads parameters values */
1.126     brouard  11324:     p=param[1][1];
1.251     brouard  11325:     pstart=paramstart[1][1];
1.126     brouard  11326:     
                   11327:     /* Reads comments: lines beginning with '#' */
                   11328:     while((c=getc(ficpar))=='#' && c!= EOF){
                   11329:       ungetc(c,ficpar);
                   11330:       fgets(line, MAXLINE, ficpar);
                   11331:       numlinepar++;
1.141     brouard  11332:       fputs(line,stdout);
1.126     brouard  11333:       fputs(line,ficparo);
                   11334:       fputs(line,ficlog);
                   11335:     }
                   11336:     ungetc(c,ficpar);
                   11337: 
                   11338:     for(i=1; i <=nlstate; i++){
                   11339:       for(j=1; j <=nlstate+ndeath-1; j++){
1.234     brouard  11340:        fscanf(ficpar,"%1d%1d",&i1,&j1);
                   11341:        if ( (i1-i) * (j1-j) != 0){
                   11342:          printf("Error in line parameters number %d, %1d%1d instead of %1d%1d \n",numlinepar, i,j, i1, j1);
                   11343:          exit(1);
                   11344:        }
                   11345:        printf("%1d%1d",i,j);
                   11346:        fprintf(ficparo,"%1d%1d",i1,j1);
                   11347:        fprintf(ficlog,"%1d%1d",i1,j1);
                   11348:        for(k=1; k<=ncovmodel;k++){
                   11349:          fscanf(ficpar,"%le",&delti3[i][j][k]);
                   11350:          printf(" %le",delti3[i][j][k]);
                   11351:          fprintf(ficparo," %le",delti3[i][j][k]);
                   11352:          fprintf(ficlog," %le",delti3[i][j][k]);
                   11353:        }
                   11354:        fscanf(ficpar,"\n");
                   11355:        numlinepar++;
                   11356:        printf("\n");
                   11357:        fprintf(ficparo,"\n");
                   11358:        fprintf(ficlog,"\n");
1.126     brouard  11359:       }
                   11360:     }
                   11361:     fflush(ficlog);
1.234     brouard  11362:     
1.145     brouard  11363:     /* Reads covariance matrix */
1.126     brouard  11364:     delti=delti3[1][1];
1.220     brouard  11365:                
                   11366:                
1.126     brouard  11367:     /* 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  11368:                
1.126     brouard  11369:     /* Reads comments: lines beginning with '#' */
                   11370:     while((c=getc(ficpar))=='#' && c!= EOF){
                   11371:       ungetc(c,ficpar);
                   11372:       fgets(line, MAXLINE, ficpar);
                   11373:       numlinepar++;
1.141     brouard  11374:       fputs(line,stdout);
1.126     brouard  11375:       fputs(line,ficparo);
                   11376:       fputs(line,ficlog);
                   11377:     }
                   11378:     ungetc(c,ficpar);
1.220     brouard  11379:                
1.126     brouard  11380:     matcov=matrix(1,npar,1,npar);
1.203     brouard  11381:     hess=matrix(1,npar,1,npar);
1.131     brouard  11382:     for(i=1; i <=npar; i++)
                   11383:       for(j=1; j <=npar; j++) matcov[i][j]=0.;
1.220     brouard  11384:                
1.194     brouard  11385:     /* Scans npar lines */
1.126     brouard  11386:     for(i=1; i <=npar; i++){
1.226     brouard  11387:       count=fscanf(ficpar,"%1d%1d%d",&i1,&j1,&jk);
1.194     brouard  11388:       if(count != 3){
1.226     brouard  11389:        printf("Error! Error in parameter file %s at line %d after line starting with %1d%1d%1d\n\
1.194     brouard  11390: This is probably because your covariance matrix doesn't \n  contain exactly %d lines corresponding to your model line '1+age+%s'.\n\
                   11391: Please run with mle=-1 to get a correct covariance matrix.\n",optionfile,numlinepar, i1,j1,jk, npar, model);
1.226     brouard  11392:        fprintf(ficlog,"Error! Error in parameter file %s at line %d after line starting with %1d%1d%1d\n\
1.194     brouard  11393: This is probably because your covariance matrix doesn't \n  contain exactly %d lines corresponding to your model line '1+age+%s'.\n\
                   11394: Please run with mle=-1 to get a correct covariance matrix.\n",optionfile,numlinepar, i1,j1,jk, npar, model);
1.226     brouard  11395:        exit(1);
1.220     brouard  11396:       }else{
1.226     brouard  11397:        if(mle==1)
                   11398:          printf("%1d%1d%d",i1,j1,jk);
                   11399:       }
                   11400:       fprintf(ficlog,"%1d%1d%d",i1,j1,jk);
                   11401:       fprintf(ficparo,"%1d%1d%d",i1,j1,jk);
1.126     brouard  11402:       for(j=1; j <=i; j++){
1.226     brouard  11403:        fscanf(ficpar," %le",&matcov[i][j]);
                   11404:        if(mle==1){
                   11405:          printf(" %.5le",matcov[i][j]);
                   11406:        }
                   11407:        fprintf(ficlog," %.5le",matcov[i][j]);
                   11408:        fprintf(ficparo," %.5le",matcov[i][j]);
1.126     brouard  11409:       }
                   11410:       fscanf(ficpar,"\n");
                   11411:       numlinepar++;
                   11412:       if(mle==1)
1.220     brouard  11413:                                printf("\n");
1.126     brouard  11414:       fprintf(ficlog,"\n");
                   11415:       fprintf(ficparo,"\n");
                   11416:     }
1.194     brouard  11417:     /* End of read covariance matrix npar lines */
1.126     brouard  11418:     for(i=1; i <=npar; i++)
                   11419:       for(j=i+1;j<=npar;j++)
1.226     brouard  11420:        matcov[i][j]=matcov[j][i];
1.126     brouard  11421:     
                   11422:     if(mle==1)
                   11423:       printf("\n");
                   11424:     fprintf(ficlog,"\n");
                   11425:     
                   11426:     fflush(ficlog);
                   11427:     
                   11428:   }    /* End of mle != -3 */
1.218     brouard  11429:   
1.186     brouard  11430:   /*  Main data
                   11431:    */
1.290     brouard  11432:   nobs=lastobs-firstobs+1; /* was = lastobs;*/
                   11433:   /* num=lvector(1,n); */
                   11434:   /* moisnais=vector(1,n); */
                   11435:   /* annais=vector(1,n); */
                   11436:   /* moisdc=vector(1,n); */
                   11437:   /* andc=vector(1,n); */
                   11438:   /* weight=vector(1,n); */
                   11439:   /* agedc=vector(1,n); */
                   11440:   /* cod=ivector(1,n); */
                   11441:   /* for(i=1;i<=n;i++){ */
                   11442:   num=lvector(firstobs,lastobs);
                   11443:   moisnais=vector(firstobs,lastobs);
                   11444:   annais=vector(firstobs,lastobs);
                   11445:   moisdc=vector(firstobs,lastobs);
                   11446:   andc=vector(firstobs,lastobs);
                   11447:   weight=vector(firstobs,lastobs);
                   11448:   agedc=vector(firstobs,lastobs);
                   11449:   cod=ivector(firstobs,lastobs);
                   11450:   for(i=firstobs;i<=lastobs;i++){
1.234     brouard  11451:     num[i]=0;
                   11452:     moisnais[i]=0;
                   11453:     annais[i]=0;
                   11454:     moisdc[i]=0;
                   11455:     andc[i]=0;
                   11456:     agedc[i]=0;
                   11457:     cod[i]=0;
                   11458:     weight[i]=1.0; /* Equal weights, 1 by default */
                   11459:   }
1.290     brouard  11460:   mint=matrix(1,maxwav,firstobs,lastobs);
                   11461:   anint=matrix(1,maxwav,firstobs,lastobs);
                   11462:   s=imatrix(1,maxwav+1,firstobs,lastobs); /* s[i][j] health state for wave i and individual j */ 
1.126     brouard  11463:   tab=ivector(1,NCOVMAX);
1.144     brouard  11464:   ncodemax=ivector(1,NCOVMAX); /* Number of code per covariate; if O and 1 only, 2**ncov; V1+V2+V3+V4=>16 */
1.192     brouard  11465:   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  11466: 
1.136     brouard  11467:   /* Reads data from file datafile */
                   11468:   if (readdata(datafile, firstobs, lastobs, &imx)==1)
                   11469:     goto end;
                   11470: 
                   11471:   /* Calculation of the number of parameters from char model */
1.234     brouard  11472:   /*    modelsav=V2+V1+V4+age*V3 strb=age*V3 stra=V2+V1+V4 
1.137     brouard  11473:        k=4 (age*V3) Tvar[k=4]= 3 (from V3) Tag[cptcovage=1]=4
                   11474:        k=3 V4 Tvar[k=3]= 4 (from V4)
                   11475:        k=2 V1 Tvar[k=2]= 1 (from V1)
                   11476:        k=1 Tvar[1]=2 (from V2)
1.234     brouard  11477:   */
                   11478:   
                   11479:   Tvar=ivector(1,NCOVMAX); /* Was 15 changed to NCOVMAX. */
                   11480:   TvarsDind=ivector(1,NCOVMAX); /*  */
                   11481:   TvarsD=ivector(1,NCOVMAX); /*  */
                   11482:   TvarsQind=ivector(1,NCOVMAX); /*  */
                   11483:   TvarsQ=ivector(1,NCOVMAX); /*  */
1.232     brouard  11484:   TvarF=ivector(1,NCOVMAX); /*  */
                   11485:   TvarFind=ivector(1,NCOVMAX); /*  */
                   11486:   TvarV=ivector(1,NCOVMAX); /*  */
                   11487:   TvarVind=ivector(1,NCOVMAX); /*  */
                   11488:   TvarA=ivector(1,NCOVMAX); /*  */
                   11489:   TvarAind=ivector(1,NCOVMAX); /*  */
1.231     brouard  11490:   TvarFD=ivector(1,NCOVMAX); /*  */
                   11491:   TvarFDind=ivector(1,NCOVMAX); /*  */
                   11492:   TvarFQ=ivector(1,NCOVMAX); /*  */
                   11493:   TvarFQind=ivector(1,NCOVMAX); /*  */
                   11494:   TvarVD=ivector(1,NCOVMAX); /*  */
                   11495:   TvarVDind=ivector(1,NCOVMAX); /*  */
                   11496:   TvarVQ=ivector(1,NCOVMAX); /*  */
                   11497:   TvarVQind=ivector(1,NCOVMAX); /*  */
                   11498: 
1.230     brouard  11499:   Tvalsel=vector(1,NCOVMAX); /*  */
1.233     brouard  11500:   Tvarsel=ivector(1,NCOVMAX); /*  */
1.226     brouard  11501:   Typevar=ivector(-1,NCOVMAX); /* -1 to 2 */
                   11502:   Fixed=ivector(-1,NCOVMAX); /* -1 to 3 */
                   11503:   Dummy=ivector(-1,NCOVMAX); /* -1 to 3 */
1.137     brouard  11504:   /*  V2+V1+V4+age*V3 is a model with 4 covariates (3 plus signs). 
                   11505:       For each model-covariate stores the data-covariate id. Tvar[1]=2, Tvar[2]=1, Tvar[3]=4, 
                   11506:       Tvar[4=age*V3] is 3 and 'age' is recorded in Tage.
                   11507:   */
                   11508:   /* For model-covariate k tells which data-covariate to use but
                   11509:     because this model-covariate is a construction we invent a new column
                   11510:     ncovcol + k1
                   11511:     If already ncovcol=4 and model=V2+V1+V1*V4+age*V3
                   11512:     Tvar[3=V1*V4]=4+1 etc */
1.227     brouard  11513:   Tprod=ivector(1,NCOVMAX); /* Gives the k position of the k1 product */
                   11514:   Tposprod=ivector(1,NCOVMAX); /* Gives the k1 product from the k position */
1.137     brouard  11515:   /* Tprod[k1=1]=3(=V1*V4) for V2+V1+V1*V4+age*V3
                   11516:      if  V2+V1+V1*V4+age*V3+V3*V2   TProd[k1=2]=5 (V3*V2)
1.227     brouard  11517:      Tposprod[k]=k1 , Tposprod[3]=1, Tposprod[5]=2 
1.137     brouard  11518:   */
1.145     brouard  11519:   Tvaraff=ivector(1,NCOVMAX); /* Unclear */
                   11520:   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  11521:                            * For V3*V2 (in V2+V1+V1*V4+age*V3+V3*V2), V3*V2 position is 2nd. 
                   11522:                            * Tvard[k1=2][1]=3 (V3) Tvard[k1=2][2]=2(V2) */
1.145     brouard  11523:   Tage=ivector(1,NCOVMAX); /* Gives the covariate id of covariates associated with age: V2 + V1 + age*V4 + V3*age
1.137     brouard  11524:                         4 covariates (3 plus signs)
                   11525:                         Tage[1=V3*age]= 4; Tage[2=age*V4] = 3
                   11526:                      */  
1.230     brouard  11527:   Tmodelind=ivector(1,NCOVMAX);/** gives the k model position of an
1.227     brouard  11528:                                * individual dummy, fixed or varying:
                   11529:                                * Tmodelind[Tvaraff[3]]=9,Tvaraff[1]@9={4,
                   11530:                                * 3, 1, 0, 0, 0, 0, 0, 0},
1.230     brouard  11531:                                * model=V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 , 
                   11532:                                * V1 df, V2 qf, V3 & V4 dv, V5 qv
                   11533:                                * Tmodelind[1]@9={9,0,3,2,}*/
                   11534:   TmodelInvind=ivector(1,NCOVMAX); /* TmodelInvind=Tvar[k]- ncovcol-nqv={5-2-1=2,*/
                   11535:   TmodelInvQind=ivector(1,NCOVMAX);/** gives the k model position of an
1.228     brouard  11536:                                * individual quantitative, fixed or varying:
                   11537:                                * Tmodelqind[1]=1,Tvaraff[1]@9={4,
                   11538:                                * 3, 1, 0, 0, 0, 0, 0, 0},
                   11539:                                * model=V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1*/
1.186     brouard  11540: /* Main decodemodel */
                   11541: 
1.187     brouard  11542: 
1.223     brouard  11543:   if(decodemodel(model, lastobs) == 1) /* In order to get Tvar[k] V4+V3+V5 p Tvar[1]@3  = {4, 3, 5}*/
1.136     brouard  11544:     goto end;
                   11545: 
1.137     brouard  11546:   if((double)(lastobs-imx)/(double)imx > 1.10){
                   11547:     nbwarn++;
                   11548:     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); 
                   11549:     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); 
                   11550:   }
1.136     brouard  11551:     /*  if(mle==1){*/
1.137     brouard  11552:   if (weightopt != 1) { /* Maximisation without weights. We can have weights different from 1 but want no weight*/
                   11553:     for(i=1;i<=imx;i++) weight[i]=1.0; /* changed to imx */
1.136     brouard  11554:   }
                   11555: 
                   11556:     /*-calculation of age at interview from date of interview and age at death -*/
                   11557:   agev=matrix(1,maxwav,1,imx);
                   11558: 
                   11559:   if(calandcheckages(imx, maxwav, &agemin, &agemax, &nberr, &nbwarn) == 1)
                   11560:     goto end;
                   11561: 
1.126     brouard  11562: 
1.136     brouard  11563:   agegomp=(int)agemin;
1.290     brouard  11564:   free_vector(moisnais,firstobs,lastobs);
                   11565:   free_vector(annais,firstobs,lastobs);
1.126     brouard  11566:   /* free_matrix(mint,1,maxwav,1,n);
                   11567:      free_matrix(anint,1,maxwav,1,n);*/
1.215     brouard  11568:   /* free_vector(moisdc,1,n); */
                   11569:   /* free_vector(andc,1,n); */
1.145     brouard  11570:   /* */
                   11571:   
1.126     brouard  11572:   wav=ivector(1,imx);
1.214     brouard  11573:   /* dh=imatrix(1,lastpass-firstpass+1,1,imx); */
                   11574:   /* bh=imatrix(1,lastpass-firstpass+1,1,imx); */
                   11575:   /* mw=imatrix(1,lastpass-firstpass+1,1,imx); */
                   11576:   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.*/
                   11577:   bh=imatrix(1,lastpass-firstpass+2,1,imx);
                   11578:   mw=imatrix(1,lastpass-firstpass+2,1,imx);
1.126     brouard  11579:    
                   11580:   /* Concatenates waves */
1.214     brouard  11581:   /* Concatenates waves: wav[i] is the number of effective (useful waves) of individual i.
                   11582:      Death is a valid wave (if date is known).
                   11583:      mw[mi][i] is the number of (mi=1 to wav[i]) effective wave out of mi of individual i
                   11584:      dh[m][i] or dh[mw[mi][i]][i] is the delay between two effective waves m=mw[mi][i]
                   11585:      and mw[mi+1][i]. dh depends on stepm.
                   11586:   */
                   11587: 
1.126     brouard  11588:   concatwav(wav, dh, bh, mw, s, agedc, agev,  firstpass, lastpass, imx, nlstate, stepm);
1.248     brouard  11589:   /* Concatenates waves */
1.145     brouard  11590:  
1.290     brouard  11591:   free_vector(moisdc,firstobs,lastobs);
                   11592:   free_vector(andc,firstobs,lastobs);
1.215     brouard  11593: 
1.126     brouard  11594:   /* Routine tricode is to calculate cptcoveff (real number of unique covariates) and to associate covariable number and modality */
                   11595:   nbcode=imatrix(0,NCOVMAX,0,NCOVMAX); 
                   11596:   ncodemax[1]=1;
1.145     brouard  11597:   Ndum =ivector(-1,NCOVMAX);  
1.225     brouard  11598:   cptcoveff=0;
1.220     brouard  11599:   if (ncovmodel-nagesqr > 2 ){ /* That is if covariate other than cst, age and age*age */
                   11600:     tricode(&cptcoveff,Tvar,nbcode,imx, Ndum); /**< Fills nbcode[Tvar[j]][l]; */
1.227     brouard  11601:   }
                   11602:   
                   11603:   ncovcombmax=pow(2,cptcoveff);
                   11604:   invalidvarcomb=ivector(1, ncovcombmax); 
                   11605:   for(i=1;i<ncovcombmax;i++)
                   11606:     invalidvarcomb[i]=0;
                   11607:   
1.211     brouard  11608:   /* Nbcode gives the value of the lth modality (currently 1 to 2) of jth covariate, in
1.186     brouard  11609:      V2+V1*age, there are 3 covariates Tvar[2]=1 (V1).*/
1.211     brouard  11610:   /* 1 to ncodemax[j] which is the maximum value of this jth covariate */
1.227     brouard  11611:   
1.200     brouard  11612:   /*  codtab=imatrix(1,100,1,10);*/ /* codtab[h,k]=( (h-1) - mod(k-1,2**(k-1) )/2**(k-1) */
1.198     brouard  11613:   /*printf(" codtab[1,1],codtab[100,10]=%d,%d\n", codtab[1][1],codtabm(100,10));*/
1.186     brouard  11614:   /* codtab gives the value 1 or 2 of the hth combination of k covariates (1 or 2).*/
1.211     brouard  11615:   /* nbcode[Tvaraff[j]][codtabm(h,j)]) : if there are only 2 modalities for a covariate j, 
                   11616:    * codtabm(h,j) gives its value classified at position h and nbcode gives how it is coded 
                   11617:    * (currently 0 or 1) in the data.
                   11618:    * In a loop on h=1 to 2**k, and a loop on j (=1 to k), we get the value of 
                   11619:    * corresponding modality (h,j).
                   11620:    */
                   11621: 
1.145     brouard  11622:   h=0;
                   11623:   /*if (cptcovn > 0) */
1.126     brouard  11624:   m=pow(2,cptcoveff);
                   11625:  
1.144     brouard  11626:          /**< codtab(h,k)  k   = codtab[h,k]=( (h-1) - mod(k-1,2**(k-1) )/2**(k-1) + 1
1.211     brouard  11627:           * For k=4 covariates, h goes from 1 to m=2**k
                   11628:           * codtabm(h,k)=  (1 & (h-1) >> (k-1)) + 1;
                   11629:            * #define codtabm(h,k)  (1 & (h-1) >> (k-1))+1
1.186     brouard  11630:           *     h\k   1     2     3     4
1.143     brouard  11631:           *______________________________  
                   11632:           *     1 i=1 1 i=1 1 i=1 1 i=1 1
                   11633:           *     2     2     1     1     1
                   11634:           *     3 i=2 1     2     1     1
                   11635:           *     4     2     2     1     1
                   11636:           *     5 i=3 1 i=2 1     2     1
                   11637:           *     6     2     1     2     1
                   11638:           *     7 i=4 1     2     2     1
                   11639:           *     8     2     2     2     1
1.197     brouard  11640:           *     9 i=5 1 i=3 1 i=2 1     2
                   11641:           *    10     2     1     1     2
                   11642:           *    11 i=6 1     2     1     2
                   11643:           *    12     2     2     1     2
                   11644:           *    13 i=7 1 i=4 1     2     2    
                   11645:           *    14     2     1     2     2
                   11646:           *    15 i=8 1     2     2     2
                   11647:           *    16     2     2     2     2
1.143     brouard  11648:           */
1.212     brouard  11649:   /* How to do the opposite? From combination h (=1 to 2**k) how to get the value on the covariates? */
1.211     brouard  11650:      /* from h=5 and m, we get then number of covariates k=log(m)/log(2)=4
                   11651:      * and the value of each covariate?
                   11652:      * V1=1, V2=1, V3=2, V4=1 ?
                   11653:      * h-1=4 and 4 is 0100 or reverse 0010, and +1 is 1121 ok.
                   11654:      * h=6, 6-1=5, 5 is 0101, 1010, 2121, V1=2nd, V2=1st, V3=2nd, V4=1st.
                   11655:      * In order to get the real value in the data, we use nbcode
                   11656:      * nbcode[Tvar[3][2nd]]=1 and nbcode[Tvar[4][1]]=0
                   11657:      * We are keeping this crazy system in order to be able (in the future?) 
                   11658:      * to have more than 2 values (0 or 1) for a covariate.
                   11659:      * #define codtabm(h,k)  (1 & (h-1) >> (k-1))+1
                   11660:      * h=6, k=2? h-1=5=0101, reverse 1010, +1=2121, k=2nd position: value is 1: codtabm(6,2)=1
                   11661:      *              bbbbbbbb
                   11662:      *              76543210     
                   11663:      *   h-1        00000101 (6-1=5)
1.219     brouard  11664:      *(h-1)>>(k-1)= 00000010 >> (2-1) = 1 right shift
1.211     brouard  11665:      *           &
                   11666:      *     1        00000001 (1)
1.219     brouard  11667:      *              00000000        = 1 & ((h-1) >> (k-1))
                   11668:      *          +1= 00000001 =1 
1.211     brouard  11669:      *
                   11670:      * h=14, k=3 => h'=h-1=13, k'=k-1=2
                   11671:      *          h'      1101 =2^3+2^2+0x2^1+2^0
                   11672:      *    >>k'            11
                   11673:      *          &   00000001
                   11674:      *            = 00000001
                   11675:      *      +1    = 00000010=2    =  codtabm(14,3)   
                   11676:      * Reverse h=6 and m=16?
                   11677:      * cptcoveff=log(16)/log(2)=4 covariate: 6-1=5=0101 reversed=1010 +1=2121 =>V1=2, V2=1, V3=2, V4=1.
                   11678:      * for (j=1 to cptcoveff) Vj=decodtabm(j,h,cptcoveff)
                   11679:      * decodtabm(h,j,cptcoveff)= (((h-1) >> (j-1)) & 1) +1 
                   11680:      * decodtabm(h,j,cptcoveff)= (h <= (1<<cptcoveff)?(((h-1) >> (j-1)) & 1) +1 : -1)
                   11681:      * V3=decodtabm(14,3,2**4)=2
                   11682:      *          h'=13   1101 =2^3+2^2+0x2^1+2^0
                   11683:      *(h-1) >> (j-1)    0011 =13 >> 2
                   11684:      *          &1 000000001
                   11685:      *           = 000000001
                   11686:      *         +1= 000000010 =2
                   11687:      *                  2211
                   11688:      *                  V1=1+1, V2=0+1, V3=1+1, V4=1+1
                   11689:      *                  V3=2
1.220     brouard  11690:                 * codtabm and decodtabm are identical
1.211     brouard  11691:      */
                   11692: 
1.145     brouard  11693: 
                   11694:  free_ivector(Ndum,-1,NCOVMAX);
                   11695: 
                   11696: 
1.126     brouard  11697:     
1.186     brouard  11698:   /* Initialisation of ----------- gnuplot -------------*/
1.126     brouard  11699:   strcpy(optionfilegnuplot,optionfilefiname);
                   11700:   if(mle==-3)
1.201     brouard  11701:     strcat(optionfilegnuplot,"-MORT_");
1.126     brouard  11702:   strcat(optionfilegnuplot,".gp");
                   11703: 
                   11704:   if((ficgp=fopen(optionfilegnuplot,"w"))==NULL) {
                   11705:     printf("Problem with file %s",optionfilegnuplot);
                   11706:   }
                   11707:   else{
1.204     brouard  11708:     fprintf(ficgp,"\n# IMaCh-%s\n", version); 
1.126     brouard  11709:     fprintf(ficgp,"# %s\n", optionfilegnuplot); 
1.141     brouard  11710:     //fprintf(ficgp,"set missing 'NaNq'\n");
                   11711:     fprintf(ficgp,"set datafile missing 'NaNq'\n");
1.126     brouard  11712:   }
                   11713:   /*  fclose(ficgp);*/
1.186     brouard  11714: 
                   11715: 
                   11716:   /* Initialisation of --------- index.htm --------*/
1.126     brouard  11717: 
                   11718:   strcpy(optionfilehtm,optionfilefiname); /* Main html file */
                   11719:   if(mle==-3)
1.201     brouard  11720:     strcat(optionfilehtm,"-MORT_");
1.126     brouard  11721:   strcat(optionfilehtm,".htm");
                   11722:   if((fichtm=fopen(optionfilehtm,"w"))==NULL)    {
1.131     brouard  11723:     printf("Problem with %s \n",optionfilehtm);
                   11724:     exit(0);
1.126     brouard  11725:   }
                   11726: 
                   11727:   strcpy(optionfilehtmcov,optionfilefiname); /* Only for matrix of covariance */
                   11728:   strcat(optionfilehtmcov,"-cov.htm");
                   11729:   if((fichtmcov=fopen(optionfilehtmcov,"w"))==NULL)    {
                   11730:     printf("Problem with %s \n",optionfilehtmcov), exit(0);
                   11731:   }
                   11732:   else{
                   11733:   fprintf(fichtmcov,"<html><head>\n<title>IMaCh Cov %s</title></head>\n <body><font size=\"2\">%s <br> %s</font> \
                   11734: <hr size=\"2\" color=\"#EC5E5E\"> \n\
1.204     brouard  11735: Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=1+age+%s<br>\n",\
1.126     brouard  11736:          optionfilehtmcov,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model);
                   11737:   }
                   11738: 
1.213     brouard  11739:   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  11740: <hr size=\"2\" color=\"#EC5E5E\"> \n\
                   11741: <font size=\"2\">IMaCh-%s <br> %s</font> \
1.126     brouard  11742: <hr size=\"2\" color=\"#EC5E5E\"> \n\
1.204     brouard  11743: Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=1+age+%s<br>\n\
1.126     brouard  11744: \n\
                   11745: <hr  size=\"2\" color=\"#EC5E5E\">\
                   11746:  <ul><li><h4>Parameter files</h4>\n\
                   11747:  - Parameter file: <a href=\"%s.%s\">%s.%s</a><br>\n\
                   11748:  - Copy of the parameter file: <a href=\"o%s\">o%s</a><br>\n\
                   11749:  - Log file of the run: <a href=\"%s\">%s</a><br>\n\
                   11750:  - Gnuplot file name: <a href=\"%s\">%s</a><br>\n\
                   11751:  - Date and time at start: %s</ul>\n",\
                   11752:          optionfilehtm,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model,\
                   11753:          optionfilefiname,optionfilext,optionfilefiname,optionfilext,\
                   11754:          fileres,fileres,\
                   11755:          filelog,filelog,optionfilegnuplot,optionfilegnuplot,strstart);
                   11756:   fflush(fichtm);
                   11757: 
                   11758:   strcpy(pathr,path);
                   11759:   strcat(pathr,optionfilefiname);
1.184     brouard  11760: #ifdef WIN32
                   11761:   _chdir(optionfilefiname); /* Move to directory named optionfile */
                   11762: #else
1.126     brouard  11763:   chdir(optionfilefiname); /* Move to directory named optionfile */
1.184     brouard  11764: #endif
                   11765:          
1.126     brouard  11766:   
1.220     brouard  11767:   /* Calculates basic frequencies. Computes observed prevalence at single age 
                   11768:                 and for any valid combination of covariates
1.126     brouard  11769:      and prints on file fileres'p'. */
1.251     brouard  11770:   freqsummary(fileres, p, pstart, agemin, agemax, s, agev, nlstate, imx, Tvaraff, invalidvarcomb, nbcode, ncodemax,mint,anint,strstart, \
1.227     brouard  11771:              firstpass, lastpass,  stepm,  weightopt, model);
1.126     brouard  11772: 
                   11773:   fprintf(fichtm,"\n");
1.286     brouard  11774:   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  11775:          ftol, stepm);
                   11776:   fprintf(fichtm,"\n<li>Number of fixed dummy covariates: ncovcol=%d ", ncovcol);
                   11777:   ncurrv=1;
                   11778:   for(i=ncurrv; i <=ncovcol; i++) fprintf(fichtm,"V%d ", i);
                   11779:   fprintf(fichtm,"\n<li> Number of fixed quantitative variables: nqv=%d ", nqv); 
                   11780:   ncurrv=i;
                   11781:   for(i=ncurrv; i <=ncurrv-1+nqv; i++) fprintf(fichtm,"V%d ", i);
1.290     brouard  11782:   fprintf(fichtm,"\n<li> Number of time varying (wave varying) dummy covariates: ntv=%d ", ntv);
1.274     brouard  11783:   ncurrv=i;
                   11784:   for(i=ncurrv; i <=ncurrv-1+ntv; i++) fprintf(fichtm,"V%d ", i);
1.290     brouard  11785:   fprintf(fichtm,"\n<li>Number of time varying  quantitative covariates: nqtv=%d ", nqtv);
1.274     brouard  11786:   ncurrv=i;
                   11787:   for(i=ncurrv; i <=ncurrv-1+nqtv; i++) fprintf(fichtm,"V%d ", i);
                   11788:   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", \
                   11789:           nlstate, ndeath, maxwav, mle, weightopt);
                   11790: 
                   11791:   fprintf(fichtm,"<h4> Diagram of states <a href=\"%s_.svg\">%s_.svg</a></h4> \n\
                   11792: <img src=\"%s_.svg\">", subdirf2(optionfilefiname,"D_"),subdirf2(optionfilefiname,"D_"),subdirf2(optionfilefiname,"D_"));
                   11793: 
                   11794:   
                   11795:   fprintf(fichtm,"\n<h4>Some descriptive statistics </h4>\n<br>Total number of observations=%d <br>\n\
1.126     brouard  11796: Youngest age at first (selected) pass %.2f, oldest age %.2f<br>\n\
                   11797: Interval (in months) between two waves: Min=%d Max=%d Mean=%.2lf<br>\n",\
1.274     brouard  11798:   imx,agemin,agemax,jmin,jmax,jmean);
1.126     brouard  11799:   pmmij= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
1.268     brouard  11800:   oldms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
                   11801:   newms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
                   11802:   savms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
                   11803:   oldm=oldms; newm=newms; savm=savms; /* Keeps fixed addresses to free */
1.218     brouard  11804: 
1.126     brouard  11805:   /* For Powell, parameters are in a vector p[] starting at p[1]
                   11806:      so we point p on param[1][1] so that p[1] maps on param[1][1][1] */
                   11807:   p=param[1][1]; /* *(*(*(param +1)+1)+0) */
                   11808: 
                   11809:   globpr=0; /* To get the number ipmx of contributions and the sum of weights*/
1.186     brouard  11810:   /* For mortality only */
1.126     brouard  11811:   if (mle==-3){
1.136     brouard  11812:     ximort=matrix(1,NDIM,1,NDIM); 
1.248     brouard  11813:     for(i=1;i<=NDIM;i++)
                   11814:       for(j=1;j<=NDIM;j++)
                   11815:        ximort[i][j]=0.;
1.186     brouard  11816:     /*     ximort=gsl_matrix_alloc(1,NDIM,1,NDIM); */
1.290     brouard  11817:     cens=ivector(firstobs,lastobs);
                   11818:     ageexmed=vector(firstobs,lastobs);
                   11819:     agecens=vector(firstobs,lastobs);
                   11820:     dcwave=ivector(firstobs,lastobs);
1.223     brouard  11821:                
1.126     brouard  11822:     for (i=1; i<=imx; i++){
                   11823:       dcwave[i]=-1;
                   11824:       for (m=firstpass; m<=lastpass; m++)
1.226     brouard  11825:        if (s[m][i]>nlstate) {
                   11826:          dcwave[i]=m;
                   11827:          /*    printf("i=%d j=%d s=%d dcwave=%d\n",i,j, s[j][i],dcwave[i]);*/
                   11828:          break;
                   11829:        }
1.126     brouard  11830:     }
1.226     brouard  11831:     
1.126     brouard  11832:     for (i=1; i<=imx; i++) {
                   11833:       if (wav[i]>0){
1.226     brouard  11834:        ageexmed[i]=agev[mw[1][i]][i];
                   11835:        j=wav[i];
                   11836:        agecens[i]=1.; 
                   11837:        
                   11838:        if (ageexmed[i]> 1 && wav[i] > 0){
                   11839:          agecens[i]=agev[mw[j][i]][i];
                   11840:          cens[i]= 1;
                   11841:        }else if (ageexmed[i]< 1) 
                   11842:          cens[i]= -1;
                   11843:        if (agedc[i]< AGESUP && agedc[i]>1 && dcwave[i]>firstpass && dcwave[i]<=lastpass)
                   11844:          cens[i]=0 ;
1.126     brouard  11845:       }
                   11846:       else cens[i]=-1;
                   11847:     }
                   11848:     
                   11849:     for (i=1;i<=NDIM;i++) {
                   11850:       for (j=1;j<=NDIM;j++)
1.226     brouard  11851:        ximort[i][j]=(i == j ? 1.0 : 0.0);
1.126     brouard  11852:     }
                   11853:     
1.145     brouard  11854:     /*p[1]=0.0268; p[NDIM]=0.083;*/
1.126     brouard  11855:     /*printf("%lf %lf", p[1], p[2]);*/
                   11856:     
                   11857:     
1.136     brouard  11858: #ifdef GSL
                   11859:     printf("GSL optimization\n");  fprintf(ficlog,"Powell\n");
1.162     brouard  11860: #else
1.126     brouard  11861:     printf("Powell\n");  fprintf(ficlog,"Powell\n");
1.136     brouard  11862: #endif
1.201     brouard  11863:     strcpy(filerespow,"POW-MORT_"); 
                   11864:     strcat(filerespow,fileresu);
1.126     brouard  11865:     if((ficrespow=fopen(filerespow,"w"))==NULL) {
                   11866:       printf("Problem with resultfile: %s\n", filerespow);
                   11867:       fprintf(ficlog,"Problem with resultfile: %s\n", filerespow);
                   11868:     }
1.136     brouard  11869: #ifdef GSL
                   11870:     fprintf(ficrespow,"# GSL optimization\n# iter -2*LL");
1.162     brouard  11871: #else
1.126     brouard  11872:     fprintf(ficrespow,"# Powell\n# iter -2*LL");
1.136     brouard  11873: #endif
1.126     brouard  11874:     /*  for (i=1;i<=nlstate;i++)
                   11875:        for(j=1;j<=nlstate+ndeath;j++)
                   11876:        if(j!=i)fprintf(ficrespow," p%1d%1d",i,j);
                   11877:     */
                   11878:     fprintf(ficrespow,"\n");
1.136     brouard  11879: #ifdef GSL
                   11880:     /* gsl starts here */ 
                   11881:     T = gsl_multimin_fminimizer_nmsimplex;
                   11882:     gsl_multimin_fminimizer *sfm = NULL;
                   11883:     gsl_vector *ss, *x;
                   11884:     gsl_multimin_function minex_func;
                   11885: 
                   11886:     /* Initial vertex size vector */
                   11887:     ss = gsl_vector_alloc (NDIM);
                   11888:     
                   11889:     if (ss == NULL){
                   11890:       GSL_ERROR_VAL ("failed to allocate space for ss", GSL_ENOMEM, 0);
                   11891:     }
                   11892:     /* Set all step sizes to 1 */
                   11893:     gsl_vector_set_all (ss, 0.001);
                   11894: 
                   11895:     /* Starting point */
1.126     brouard  11896:     
1.136     brouard  11897:     x = gsl_vector_alloc (NDIM);
                   11898:     
                   11899:     if (x == NULL){
                   11900:       gsl_vector_free(ss);
                   11901:       GSL_ERROR_VAL ("failed to allocate space for x", GSL_ENOMEM, 0);
                   11902:     }
                   11903:   
                   11904:     /* Initialize method and iterate */
                   11905:     /*     p[1]=0.0268; p[NDIM]=0.083; */
1.186     brouard  11906:     /*     gsl_vector_set(x, 0, 0.0268); */
                   11907:     /*     gsl_vector_set(x, 1, 0.083); */
1.136     brouard  11908:     gsl_vector_set(x, 0, p[1]);
                   11909:     gsl_vector_set(x, 1, p[2]);
                   11910: 
                   11911:     minex_func.f = &gompertz_f;
                   11912:     minex_func.n = NDIM;
                   11913:     minex_func.params = (void *)&p; /* ??? */
                   11914:     
                   11915:     sfm = gsl_multimin_fminimizer_alloc (T, NDIM);
                   11916:     gsl_multimin_fminimizer_set (sfm, &minex_func, x, ss);
                   11917:     
                   11918:     printf("Iterations beginning .....\n\n");
                   11919:     printf("Iter. #    Intercept       Slope     -Log Likelihood     Simplex size\n");
                   11920: 
                   11921:     iteri=0;
                   11922:     while (rval == GSL_CONTINUE){
                   11923:       iteri++;
                   11924:       status = gsl_multimin_fminimizer_iterate(sfm);
                   11925:       
                   11926:       if (status) printf("error: %s\n", gsl_strerror (status));
                   11927:       fflush(0);
                   11928:       
                   11929:       if (status) 
                   11930:         break;
                   11931:       
                   11932:       rval = gsl_multimin_test_size (gsl_multimin_fminimizer_size (sfm), 1e-6);
                   11933:       ssval = gsl_multimin_fminimizer_size (sfm);
                   11934:       
                   11935:       if (rval == GSL_SUCCESS)
                   11936:         printf ("converged to a local maximum at\n");
                   11937:       
                   11938:       printf("%5d ", iteri);
                   11939:       for (it = 0; it < NDIM; it++){
                   11940:        printf ("%10.5f ", gsl_vector_get (sfm->x, it));
                   11941:       }
                   11942:       printf("f() = %-10.5f ssize = %.7f\n", sfm->fval, ssval);
                   11943:     }
                   11944:     
                   11945:     printf("\n\n Please note: Program should be run many times with varying starting points to detemine global maximum\n\n");
                   11946:     
                   11947:     gsl_vector_free(x); /* initial values */
                   11948:     gsl_vector_free(ss); /* inital step size */
                   11949:     for (it=0; it<NDIM; it++){
                   11950:       p[it+1]=gsl_vector_get(sfm->x,it);
                   11951:       fprintf(ficrespow," %.12lf", p[it]);
                   11952:     }
                   11953:     gsl_multimin_fminimizer_free (sfm); /* p *(sfm.x.data) et p *(sfm.x.data+1)  */
                   11954: #endif
                   11955: #ifdef POWELL
                   11956:      powell(p,ximort,NDIM,ftol,&iter,&fret,gompertz);
                   11957: #endif  
1.126     brouard  11958:     fclose(ficrespow);
                   11959:     
1.203     brouard  11960:     hesscov(matcov, hess, p, NDIM, delti, 1e-4, gompertz); 
1.126     brouard  11961: 
                   11962:     for(i=1; i <=NDIM; i++)
                   11963:       for(j=i+1;j<=NDIM;j++)
1.220     brouard  11964:                                matcov[i][j]=matcov[j][i];
1.126     brouard  11965:     
                   11966:     printf("\nCovariance matrix\n ");
1.203     brouard  11967:     fprintf(ficlog,"\nCovariance matrix\n ");
1.126     brouard  11968:     for(i=1; i <=NDIM; i++) {
                   11969:       for(j=1;j<=NDIM;j++){ 
1.220     brouard  11970:                                printf("%f ",matcov[i][j]);
                   11971:                                fprintf(ficlog,"%f ",matcov[i][j]);
1.126     brouard  11972:       }
1.203     brouard  11973:       printf("\n ");  fprintf(ficlog,"\n ");
1.126     brouard  11974:     }
                   11975:     
                   11976:     printf("iter=%d MLE=%f Eq=%lf*exp(%lf*(age-%d))\n",iter,-gompertz(p),p[1],p[2],agegomp);
1.193     brouard  11977:     for (i=1;i<=NDIM;i++) {
1.126     brouard  11978:       printf("%f [%f ; %f]\n",p[i],p[i]-2*sqrt(matcov[i][i]),p[i]+2*sqrt(matcov[i][i]));
1.193     brouard  11979:       fprintf(ficlog,"%f [%f ; %f]\n",p[i],p[i]-2*sqrt(matcov[i][i]),p[i]+2*sqrt(matcov[i][i]));
                   11980:     }
1.126     brouard  11981:     lsurv=vector(1,AGESUP);
                   11982:     lpop=vector(1,AGESUP);
                   11983:     tpop=vector(1,AGESUP);
                   11984:     lsurv[agegomp]=100000;
                   11985:     
                   11986:     for (k=agegomp;k<=AGESUP;k++) {
                   11987:       agemortsup=k;
                   11988:       if (p[1]*exp(p[2]*(k-agegomp))>1) break;
                   11989:     }
                   11990:     
                   11991:     for (k=agegomp;k<agemortsup;k++)
                   11992:       lsurv[k+1]=lsurv[k]-lsurv[k]*(p[1]*exp(p[2]*(k-agegomp)));
                   11993:     
                   11994:     for (k=agegomp;k<agemortsup;k++){
                   11995:       lpop[k]=(lsurv[k]+lsurv[k+1])/2.;
                   11996:       sumlpop=sumlpop+lpop[k];
                   11997:     }
                   11998:     
                   11999:     tpop[agegomp]=sumlpop;
                   12000:     for (k=agegomp;k<(agemortsup-3);k++){
                   12001:       /*  tpop[k+1]=2;*/
                   12002:       tpop[k+1]=tpop[k]-lpop[k];
                   12003:     }
                   12004:     
                   12005:     
                   12006:     printf("\nAge   lx     qx    dx    Lx     Tx     e(x)\n");
                   12007:     for (k=agegomp;k<(agemortsup-2);k++) 
                   12008:       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]);
                   12009:     
                   12010:     
                   12011:     replace_back_to_slash(pathc,pathcd); /* Even gnuplot wants a / */
1.220     brouard  12012:                ageminpar=50;
                   12013:                agemaxpar=100;
1.194     brouard  12014:     if(ageminpar == AGEOVERFLOW ||agemaxpar == AGEOVERFLOW){
                   12015:        printf("Warning! Error in gnuplot file with ageminpar %f or agemaxpar %f overflow\n\
                   12016: This is probably because your parameter file doesn't \n  contain the exact number of lines (or columns) corresponding to your model line.\n\
                   12017: Please run with mle=-1 to get a correct covariance matrix.\n",ageminpar,agemaxpar);
                   12018:        fprintf(ficlog,"Warning! Error in gnuplot file with ageminpar %f or agemaxpar %f overflow\n\
                   12019: This is probably because your parameter file doesn't \n  contain the exact number of lines (or columns) corresponding to your model line.\n\
                   12020: Please run with mle=-1 to get a correct covariance matrix.\n",ageminpar,agemaxpar);
1.220     brouard  12021:     }else{
                   12022:                        printf("Warning! ageminpar %f and agemaxpar %f have been fixed because for simplification until it is fixed...\n\n",ageminpar,agemaxpar);
                   12023:                        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  12024:       printinggnuplotmort(fileresu, optionfilefiname,ageminpar,agemaxpar,fage, pathc,p);
1.220     brouard  12025:                }
1.201     brouard  12026:     printinghtmlmort(fileresu,title,datafile, firstpass, lastpass, \
1.126     brouard  12027:                     stepm, weightopt,\
                   12028:                     model,imx,p,matcov,agemortsup);
                   12029:     
                   12030:     free_vector(lsurv,1,AGESUP);
                   12031:     free_vector(lpop,1,AGESUP);
                   12032:     free_vector(tpop,1,AGESUP);
1.220     brouard  12033:     free_matrix(ximort,1,NDIM,1,NDIM);
1.290     brouard  12034:     free_ivector(dcwave,firstobs,lastobs);
                   12035:     free_vector(agecens,firstobs,lastobs);
                   12036:     free_vector(ageexmed,firstobs,lastobs);
                   12037:     free_ivector(cens,firstobs,lastobs);
1.220     brouard  12038: #ifdef GSL
1.136     brouard  12039: #endif
1.186     brouard  12040:   } /* Endof if mle==-3 mortality only */
1.205     brouard  12041:   /* Standard  */
                   12042:   else{ /* For mle !=- 3, could be 0 or 1 or 4 etc. */
                   12043:     globpr=0;/* Computes sum of likelihood for globpr=1 and funcone */
                   12044:     /* Computes likelihood for initial parameters, uses funcone to compute gpimx and gsw */
1.132     brouard  12045:     likelione(ficres, p, npar, nlstate, &globpr, &ipmx, &sw, &fretone, funcone); /* Prints the contributions to the likelihood */
1.126     brouard  12046:     printf("First Likeli=%12.6f ipmx=%ld sw=%12.6f",fretone,ipmx,sw);
                   12047:     for (k=1; k<=npar;k++)
                   12048:       printf(" %d %8.5f",k,p[k]);
                   12049:     printf("\n");
1.205     brouard  12050:     if(mle>=1){ /* Could be 1 or 2, Real Maximization */
                   12051:       /* mlikeli uses func not funcone */
1.247     brouard  12052:       /* for(i=1;i<nlstate;i++){ */
                   12053:       /*       /\*reducing xi for 1 to npar to 1 to ncovmodel; *\/ */
                   12054:       /*    mlikeli(ficres,p, ncovmodel, ncovmodel, nlstate, ftol, funcnoprod); */
                   12055:       /* } */
1.205     brouard  12056:       mlikeli(ficres,p, npar, ncovmodel, nlstate, ftol, func);
                   12057:     }
                   12058:     if(mle==0) {/* No optimization, will print the likelihoods for the datafile */
                   12059:       globpr=0;/* Computes sum of likelihood for globpr=1 and funcone */
                   12060:       /* Computes likelihood for initial parameters, uses funcone to compute gpimx and gsw */
                   12061:       likelione(ficres, p, npar, nlstate, &globpr, &ipmx, &sw, &fretone, funcone); /* Prints the contributions to the likelihood */
                   12062:     }
                   12063:     globpr=1; /* again, to print the individual contributions using computed gpimx and gsw */
1.126     brouard  12064:     likelione(ficres, p, npar, nlstate, &globpr, &ipmx, &sw, &fretone, funcone); /* Prints the contributions to the likelihood */
                   12065:     printf("Second Likeli=%12.6f ipmx=%ld sw=%12.6f",fretone,ipmx,sw);
                   12066:     for (k=1; k<=npar;k++)
                   12067:       printf(" %d %8.5f",k,p[k]);
                   12068:     printf("\n");
                   12069:     
                   12070:     /*--------- results files --------------*/
1.283     brouard  12071:     /* 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  12072:     
                   12073:     
                   12074:     fprintf(ficres,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
                   12075:     printf("# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
                   12076:     fprintf(ficlog,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
                   12077:     for(i=1,jk=1; i <=nlstate; i++){
                   12078:       for(k=1; k <=(nlstate+ndeath); k++){
1.225     brouard  12079:        if (k != i) {
                   12080:          printf("%d%d ",i,k);
                   12081:          fprintf(ficlog,"%d%d ",i,k);
                   12082:          fprintf(ficres,"%1d%1d ",i,k);
                   12083:          for(j=1; j <=ncovmodel; j++){
                   12084:            printf("%12.7f ",p[jk]);
                   12085:            fprintf(ficlog,"%12.7f ",p[jk]);
                   12086:            fprintf(ficres,"%12.7f ",p[jk]);
                   12087:            jk++; 
                   12088:          }
                   12089:          printf("\n");
                   12090:          fprintf(ficlog,"\n");
                   12091:          fprintf(ficres,"\n");
                   12092:        }
1.126     brouard  12093:       }
                   12094:     }
1.203     brouard  12095:     if(mle != 0){
                   12096:       /* Computing hessian and covariance matrix only at a peak of the Likelihood, that is after optimization */
1.126     brouard  12097:       ftolhess=ftol; /* Usually correct */
1.203     brouard  12098:       hesscov(matcov, hess, p, npar, delti, ftolhess, func);
                   12099:       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");
                   12100:       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");
                   12101:       for(i=1,jk=1; i <=nlstate; i++){
1.225     brouard  12102:        for(k=1; k <=(nlstate+ndeath); k++){
                   12103:          if (k != i) {
                   12104:            printf("%d%d ",i,k);
                   12105:            fprintf(ficlog,"%d%d ",i,k);
                   12106:            for(j=1; j <=ncovmodel; j++){
                   12107:              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]));
                   12108:              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]));
                   12109:              jk++; 
                   12110:            }
                   12111:            printf("\n");
                   12112:            fprintf(ficlog,"\n");
                   12113:          }
                   12114:        }
1.193     brouard  12115:       }
1.203     brouard  12116:     } /* end of hesscov and Wald tests */
1.225     brouard  12117:     
1.203     brouard  12118:     /*  */
1.126     brouard  12119:     fprintf(ficres,"# Scales (for hessian or gradient estimation)\n");
                   12120:     printf("# Scales (for hessian or gradient estimation)\n");
                   12121:     fprintf(ficlog,"# Scales (for hessian or gradient estimation)\n");
                   12122:     for(i=1,jk=1; i <=nlstate; i++){
                   12123:       for(j=1; j <=nlstate+ndeath; j++){
1.225     brouard  12124:        if (j!=i) {
                   12125:          fprintf(ficres,"%1d%1d",i,j);
                   12126:          printf("%1d%1d",i,j);
                   12127:          fprintf(ficlog,"%1d%1d",i,j);
                   12128:          for(k=1; k<=ncovmodel;k++){
                   12129:            printf(" %.5e",delti[jk]);
                   12130:            fprintf(ficlog," %.5e",delti[jk]);
                   12131:            fprintf(ficres," %.5e",delti[jk]);
                   12132:            jk++;
                   12133:          }
                   12134:          printf("\n");
                   12135:          fprintf(ficlog,"\n");
                   12136:          fprintf(ficres,"\n");
                   12137:        }
1.126     brouard  12138:       }
                   12139:     }
                   12140:     
                   12141:     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  12142:     if(mle >= 1) /* To big for the screen */
1.126     brouard  12143:       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");
                   12144:     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");
                   12145:     /* # 121 Var(a12)\n\ */
                   12146:     /* # 122 Cov(b12,a12) Var(b12)\n\ */
                   12147:     /* # 131 Cov(a13,a12) Cov(a13,b12, Var(a13)\n\ */
                   12148:     /* # 132 Cov(b13,a12) Cov(b13,b12, Cov(b13,a13) Var(b13)\n\ */
                   12149:     /* # 212 Cov(a21,a12) Cov(a21,b12, Cov(a21,a13) Cov(a21,b13) Var(a21)\n\ */
                   12150:     /* # 212 Cov(b21,a12) Cov(b21,b12, Cov(b21,a13) Cov(b21,b13) Cov(b21,a21) Var(b21)\n\ */
                   12151:     /* # 232 Cov(a23,a12) Cov(a23,b12, Cov(a23,a13) Cov(a23,b13) Cov(a23,a21) Cov(a23,b21) Var(a23)\n\ */
                   12152:     /* # 232 Cov(b23,a12) Cov(b23,b12) ... Var (b23)\n" */
                   12153:     
                   12154:     
                   12155:     /* Just to have a covariance matrix which will be more understandable
                   12156:        even is we still don't want to manage dictionary of variables
                   12157:     */
                   12158:     for(itimes=1;itimes<=2;itimes++){
                   12159:       jj=0;
                   12160:       for(i=1; i <=nlstate; i++){
1.225     brouard  12161:        for(j=1; j <=nlstate+ndeath; j++){
                   12162:          if(j==i) continue;
                   12163:          for(k=1; k<=ncovmodel;k++){
                   12164:            jj++;
                   12165:            ca[0]= k+'a'-1;ca[1]='\0';
                   12166:            if(itimes==1){
                   12167:              if(mle>=1)
                   12168:                printf("#%1d%1d%d",i,j,k);
                   12169:              fprintf(ficlog,"#%1d%1d%d",i,j,k);
                   12170:              fprintf(ficres,"#%1d%1d%d",i,j,k);
                   12171:            }else{
                   12172:              if(mle>=1)
                   12173:                printf("%1d%1d%d",i,j,k);
                   12174:              fprintf(ficlog,"%1d%1d%d",i,j,k);
                   12175:              fprintf(ficres,"%1d%1d%d",i,j,k);
                   12176:            }
                   12177:            ll=0;
                   12178:            for(li=1;li <=nlstate; li++){
                   12179:              for(lj=1;lj <=nlstate+ndeath; lj++){
                   12180:                if(lj==li) continue;
                   12181:                for(lk=1;lk<=ncovmodel;lk++){
                   12182:                  ll++;
                   12183:                  if(ll<=jj){
                   12184:                    cb[0]= lk +'a'-1;cb[1]='\0';
                   12185:                    if(ll<jj){
                   12186:                      if(itimes==1){
                   12187:                        if(mle>=1)
                   12188:                          printf(" Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
                   12189:                        fprintf(ficlog," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
                   12190:                        fprintf(ficres," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
                   12191:                      }else{
                   12192:                        if(mle>=1)
                   12193:                          printf(" %.5e",matcov[jj][ll]); 
                   12194:                        fprintf(ficlog," %.5e",matcov[jj][ll]); 
                   12195:                        fprintf(ficres," %.5e",matcov[jj][ll]); 
                   12196:                      }
                   12197:                    }else{
                   12198:                      if(itimes==1){
                   12199:                        if(mle>=1)
                   12200:                          printf(" Var(%s%1d%1d)",ca,i,j);
                   12201:                        fprintf(ficlog," Var(%s%1d%1d)",ca,i,j);
                   12202:                        fprintf(ficres," Var(%s%1d%1d)",ca,i,j);
                   12203:                      }else{
                   12204:                        if(mle>=1)
                   12205:                          printf(" %.7e",matcov[jj][ll]); 
                   12206:                        fprintf(ficlog," %.7e",matcov[jj][ll]); 
                   12207:                        fprintf(ficres," %.7e",matcov[jj][ll]); 
                   12208:                      }
                   12209:                    }
                   12210:                  }
                   12211:                } /* end lk */
                   12212:              } /* end lj */
                   12213:            } /* end li */
                   12214:            if(mle>=1)
                   12215:              printf("\n");
                   12216:            fprintf(ficlog,"\n");
                   12217:            fprintf(ficres,"\n");
                   12218:            numlinepar++;
                   12219:          } /* end k*/
                   12220:        } /*end j */
1.126     brouard  12221:       } /* end i */
                   12222:     } /* end itimes */
                   12223:     
                   12224:     fflush(ficlog);
                   12225:     fflush(ficres);
1.225     brouard  12226:     while(fgets(line, MAXLINE, ficpar)) {
                   12227:       /* If line starts with a # it is a comment */
                   12228:       if (line[0] == '#') {
                   12229:        numlinepar++;
                   12230:        fputs(line,stdout);
                   12231:        fputs(line,ficparo);
                   12232:        fputs(line,ficlog);
1.299   ! brouard  12233:        fputs(line,ficres);
1.225     brouard  12234:        continue;
                   12235:       }else
                   12236:        break;
                   12237:     }
                   12238:     
1.209     brouard  12239:     /* while((c=getc(ficpar))=='#' && c!= EOF){ */
                   12240:     /*   ungetc(c,ficpar); */
                   12241:     /*   fgets(line, MAXLINE, ficpar); */
                   12242:     /*   fputs(line,stdout); */
                   12243:     /*   fputs(line,ficparo); */
                   12244:     /* } */
                   12245:     /* ungetc(c,ficpar); */
1.126     brouard  12246:     
                   12247:     estepm=0;
1.209     brouard  12248:     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  12249:       
                   12250:       if (num_filled != 6) {
                   12251:        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);
                   12252:        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);
                   12253:        goto end;
                   12254:       }
                   12255:       printf("agemin=%lf agemax=%lf bage=%lf fage=%lf estepm=%d ftolpl=%lf\n",ageminpar,agemaxpar, bage, fage, estepm, ftolpl);
                   12256:     }
                   12257:     /* ftolpl=6*ftol*1.e5; /\* 6.e-3 make convergences in less than 80 loops for the prevalence limit *\/ */
                   12258:     /*ftolpl=6.e-4;*/ /* 6.e-3 make convergences in less than 80 loops for the prevalence limit */
                   12259:     
1.209     brouard  12260:     /* fscanf(ficpar,"agemin=%lf agemax=%lf bage=%lf fage=%lf estepm=%d ftolpl=%\n",&ageminpar,&agemaxpar, &bage, &fage, &estepm); */
1.126     brouard  12261:     if (estepm==0 || estepm < stepm) estepm=stepm;
                   12262:     if (fage <= 2) {
                   12263:       bage = ageminpar;
                   12264:       fage = agemaxpar;
                   12265:     }
                   12266:     
                   12267:     fprintf(ficres,"# agemin agemax for life expectancy, bage fage (if mle==0 ie no data nor Max likelihood).\n");
1.211     brouard  12268:     fprintf(ficres,"agemin=%.0f agemax=%.0f bage=%.0f fage=%.0f estepm=%d ftolpl=%e\n",ageminpar,agemaxpar,bage,fage, estepm, ftolpl);
                   12269:     fprintf(ficparo,"agemin=%.0f agemax=%.0f bage=%.0f fage=%.0f estepm=%d, ftolpl=%e\n",ageminpar,agemaxpar,bage,fage, estepm, ftolpl);
1.220     brouard  12270:                
1.186     brouard  12271:     /* Other stuffs, more or less useful */    
1.254     brouard  12272:     while(fgets(line, MAXLINE, ficpar)) {
                   12273:       /* If line starts with a # it is a comment */
                   12274:       if (line[0] == '#') {
                   12275:        numlinepar++;
                   12276:        fputs(line,stdout);
                   12277:        fputs(line,ficparo);
                   12278:        fputs(line,ficlog);
1.299   ! brouard  12279:        fputs(line,ficres);
1.254     brouard  12280:        continue;
                   12281:       }else
                   12282:        break;
                   12283:     }
                   12284: 
                   12285:     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){
                   12286:       
                   12287:       if (num_filled != 7) {
                   12288:        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);
                   12289:        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);
                   12290:        goto end;
                   12291:       }
                   12292:       printf("begin-prev-date=%.lf/%.lf/%.lf end-prev-date=%.lf/%.lf/%.lf mov_average=%d\n",jprev1, mprev1,anprev1,jprev2, mprev2,anprev2,mobilav);
                   12293:       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);
                   12294:       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);
                   12295:       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  12296:     }
1.254     brouard  12297: 
                   12298:     while(fgets(line, MAXLINE, ficpar)) {
                   12299:       /* If line starts with a # it is a comment */
                   12300:       if (line[0] == '#') {
                   12301:        numlinepar++;
                   12302:        fputs(line,stdout);
                   12303:        fputs(line,ficparo);
                   12304:        fputs(line,ficlog);
1.299   ! brouard  12305:        fputs(line,ficres);
1.254     brouard  12306:        continue;
                   12307:       }else
                   12308:        break;
1.126     brouard  12309:     }
                   12310:     
                   12311:     
                   12312:     dateprev1=anprev1+(mprev1-1)/12.+(jprev1-1)/365.;
                   12313:     dateprev2=anprev2+(mprev2-1)/12.+(jprev2-1)/365.;
                   12314:     
1.254     brouard  12315:     if((num_filled=sscanf(line,"pop_based=%d\n",&popbased)) !=EOF){
                   12316:       if (num_filled != 1) {
                   12317:        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);
                   12318:        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);
                   12319:        goto end;
                   12320:       }
                   12321:       printf("pop_based=%d\n",popbased);
                   12322:       fprintf(ficlog,"pop_based=%d\n",popbased);
                   12323:       fprintf(ficparo,"pop_based=%d\n",popbased);   
                   12324:       fprintf(ficres,"pop_based=%d\n",popbased);   
                   12325:     }
                   12326:      
1.258     brouard  12327:     /* Results */
                   12328:     nresult=0;
                   12329:     do{
                   12330:       if(!fgets(line, MAXLINE, ficpar)){
                   12331:        endishere=1;
                   12332:        parameterline=14;
                   12333:       }else if (line[0] == '#') {
                   12334:        /* If line starts with a # it is a comment */
1.254     brouard  12335:        numlinepar++;
                   12336:        fputs(line,stdout);
                   12337:        fputs(line,ficparo);
                   12338:        fputs(line,ficlog);
1.299   ! brouard  12339:        fputs(line,ficres);
1.254     brouard  12340:        continue;
1.258     brouard  12341:       }else if(sscanf(line,"prevforecast=%[^\n]\n",modeltemp))
                   12342:        parameterline=11;
1.296     brouard  12343:       else if(sscanf(line,"prevbackcast=%[^\n]\n",modeltemp))
1.258     brouard  12344:        parameterline=12;
                   12345:       else if(sscanf(line,"result:%[^\n]\n",modeltemp))
                   12346:        parameterline=13;
                   12347:       else{
                   12348:        parameterline=14;
1.254     brouard  12349:       }
1.258     brouard  12350:       switch (parameterline){ 
                   12351:       case 11:
1.296     brouard  12352:        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)){
                   12353:                  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  12354:          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);
                   12355:          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);
                   12356:          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);
                   12357:          /* day and month of proj2 are not used but only year anproj2.*/
1.273     brouard  12358:          dateproj1=anproj1+(mproj1-1)/12.+(jproj1-1)/365.;
                   12359:          dateproj2=anproj2+(mproj2-1)/12.+(jproj2-1)/365.;
1.296     brouard  12360:           prvforecast = 1;
                   12361:        } 
                   12362:        else if((num_filled=sscanf(line,"prevforecast=%d yearsfproj=%lf mobil_average=%d\n",&prevfcast,&yrfproj,&mobilavproj)) !=EOF){/* && (num_filled == 3))*/
1.299   ! brouard  12363:          printf("prevforecast=%d yearsfproj=%lf mobil_average=%d\n",prevfcast,yrfproj,mobilavproj);
        !          12364:          fprintf(ficlog,"prevforecast=%d yearsfproj=%lf mobil_average=%d\n",prevfcast,yrfproj,mobilavproj);
        !          12365:          fprintf(ficres,"prevforecast=%d yearsfproj=%lf mobil_average=%d\n",prevfcast,yrfproj,mobilavproj);
1.296     brouard  12366:           prvforecast = 2;
                   12367:        }
                   12368:        else {
                   12369:          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);
                   12370:          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);
                   12371:          goto end;
1.258     brouard  12372:        }
1.254     brouard  12373:        break;
1.258     brouard  12374:       case 12:
1.296     brouard  12375:        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)){
                   12376:           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);
                   12377:          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);
                   12378:          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);
                   12379:          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);
                   12380:          /* day and month of back2 are not used but only year anback2.*/
1.273     brouard  12381:          dateback1=anback1+(mback1-1)/12.+(jback1-1)/365.;
                   12382:          dateback2=anback2+(mback2-1)/12.+(jback2-1)/365.;
1.296     brouard  12383:           prvbackcast = 1;
                   12384:        } 
                   12385:        else if((num_filled=sscanf(line,"prevbackcast=%d yearsbproj=%lf mobil_average=%d\n",&prevbcast,&yrbproj,&mobilavproj)) ==3){/* && (num_filled == 3))*/
1.299   ! brouard  12386:          printf("prevbackcast=%d yearsbproj=%lf mobil_average=%d\n",prevbcast,yrbproj,mobilavproj);
        !          12387:          fprintf(ficlog,"prevbackcast=%d yearsfproj=%lf mobil_average=%d\n",prevbcast,yrbproj,mobilavproj);
        !          12388:          fprintf(ficres,"prevbackcast=%d yearsfproj=%lf mobil_average=%d\n",prevbcast,yrbproj,mobilavproj);
1.296     brouard  12389:           prvbackcast = 2;
                   12390:        }
                   12391:        else {
                   12392:          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);
                   12393:          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);
                   12394:          goto end;
1.258     brouard  12395:        }
1.230     brouard  12396:        break;
1.258     brouard  12397:       case 13:
                   12398:        if((num_filled=sscanf(line,"result:%[^\n]\n",resultline)) !=EOF){
                   12399:          if (num_filled == 0){
                   12400:            resultline[0]='\0';
                   12401:            printf("Warning %d: no result line! It should be at minimum 'result: V2=0 V1=1 or result:.\n%s\n", num_filled, line);
                   12402:            fprintf(ficlog,"Warning %d: no result line! It should be at minimum 'result: V2=0 V1=1 or result:.\n%s\n", num_filled, line);
                   12403:            break;
                   12404:          } else if (num_filled != 1){
                   12405:            printf("ERROR %d: result line! It should be at minimum 'result: V2=0 V1=1 or result:.' %s\n",num_filled, line);
                   12406:            fprintf(ficlog,"ERROR %d: result line! It should be at minimum 'result: V2=0 V1=1 or result:.' %s\n",num_filled, line);
                   12407:          }
                   12408:          nresult++; /* Sum of resultlines */
                   12409:          printf("Result %d: result=%s\n",nresult, resultline);
                   12410:          if(nresult > MAXRESULTLINES){
                   12411:            printf("ERROR: Current version of IMaCh limits the number of resultlines to %d, you used %d\n",MAXRESULTLINES,nresult);
                   12412:            fprintf(ficlog,"ERROR: Current version of IMaCh limits the number of resultlines to %d, you used %d\n",MAXRESULTLINES,nresult);
                   12413:            goto end;
                   12414:          }
                   12415:          decoderesult(resultline, nresult); /* Fills TKresult[nresult] combination and Tresult[nresult][k4+1] combination values */
                   12416:          fprintf(ficparo,"result: %s\n",resultline);
                   12417:          fprintf(ficres,"result: %s\n",resultline);
                   12418:          fprintf(ficlog,"result: %s\n",resultline);
1.230     brouard  12419:          break;
1.258     brouard  12420:        case 14: 
1.259     brouard  12421:          if(ncovmodel >2 && nresult==0 ){
                   12422:            printf("ERROR: no result lines! It should be at minimum 'result: V2=0 V1=1 or result:.' %s\n",line);
1.258     brouard  12423:            goto end;
                   12424:          }
1.259     brouard  12425:          break;
1.258     brouard  12426:        default:
                   12427:          nresult=1;
                   12428:          decoderesult(".",nresult ); /* No covariate */
                   12429:        }
                   12430:       } /* End switch parameterline */
                   12431:     }while(endishere==0); /* End do */
1.126     brouard  12432:     
1.230     brouard  12433:     /* freqsummary(fileres, agemin, agemax, s, agev, nlstate, imx,Tvaraff,nbcode, ncodemax,mint,anint); */
1.145     brouard  12434:     /* ,dateprev1,dateprev2,jprev1, mprev1,anprev1,jprev2, mprev2,anprev2); */
1.126     brouard  12435:     
                   12436:     replace_back_to_slash(pathc,pathcd); /* Even gnuplot wants a / */
1.194     brouard  12437:     if(ageminpar == AGEOVERFLOW ||agemaxpar == -AGEOVERFLOW){
1.230     brouard  12438:       printf("Warning! Error in gnuplot file with ageminpar %f or agemaxpar %f overflow\n\
1.194     brouard  12439: This is probably because your parameter file doesn't \n  contain the exact number of lines (or columns) corresponding to your model line.\n\
                   12440: Please run with mle=-1 to get a correct covariance matrix.\n",ageminpar,agemaxpar);
1.230     brouard  12441:       fprintf(ficlog,"Warning! Error in gnuplot file with ageminpar %f or agemaxpar %f overflow\n\
1.194     brouard  12442: This is probably because your parameter file doesn't \n  contain the exact number of lines (or columns) corresponding to your model line.\n\
                   12443: Please run with mle=-1 to get a correct covariance matrix.\n",ageminpar,agemaxpar);
1.220     brouard  12444:     }else{
1.270     brouard  12445:       /* printinggnuplot(fileresu, optionfilefiname,ageminpar,agemaxpar,fage, prevfcast, backcast, pathc,p, (int)anproj1-(int)agemin, (int)anback1-(int)agemax+1); */
1.296     brouard  12446:       /* It seems that anprojd which is computed from the mean year at interview which is known yet because of freqsummary */
                   12447:       /* date2dmy(dateintmean,&jintmean,&mintmean,&aintmean); */ /* Done in freqsummary */
                   12448:       if(prvforecast==1){
                   12449:         dateprojd=(jproj1+12*mproj1+365*anproj1)/365;
                   12450:         jprojd=jproj1;
                   12451:         mprojd=mproj1;
                   12452:         anprojd=anproj1;
                   12453:         dateprojf=(jproj2+12*mproj2+365*anproj2)/365;
                   12454:         jprojf=jproj2;
                   12455:         mprojf=mproj2;
                   12456:         anprojf=anproj2;
                   12457:       } else if(prvforecast == 2){
                   12458:         dateprojd=dateintmean;
                   12459:         date2dmy(dateprojd,&jprojd, &mprojd, &anprojd);
                   12460:         dateprojf=dateintmean+yrfproj;
                   12461:         date2dmy(dateprojf,&jprojf, &mprojf, &anprojf);
                   12462:       }
                   12463:       if(prvbackcast==1){
                   12464:         datebackd=(jback1+12*mback1+365*anback1)/365;
                   12465:         jbackd=jback1;
                   12466:         mbackd=mback1;
                   12467:         anbackd=anback1;
                   12468:         datebackf=(jback2+12*mback2+365*anback2)/365;
                   12469:         jbackf=jback2;
                   12470:         mbackf=mback2;
                   12471:         anbackf=anback2;
                   12472:       } else if(prvbackcast == 2){
                   12473:         datebackd=dateintmean;
                   12474:         date2dmy(datebackd,&jbackd, &mbackd, &anbackd);
                   12475:         datebackf=dateintmean-yrbproj;
                   12476:         date2dmy(datebackf,&jbackf, &mbackf, &anbackf);
                   12477:       }
                   12478:       
                   12479:       printinggnuplot(fileresu, optionfilefiname,ageminpar,agemaxpar,bage, fage, prevfcast, prevbcast, pathc,p, (int)anprojd-bage, (int)anbackd-fage);
1.220     brouard  12480:     }
                   12481:     printinghtml(fileresu,title,datafile, firstpass, lastpass, stepm, weightopt, \
1.296     brouard  12482:                 model,imx,jmin,jmax,jmean,rfileres,popforecast,mobilav,prevfcast,mobilavproj,prevbcast, estepm, \
                   12483:                 jprev1,mprev1,anprev1,dateprev1, dateprojd, datebackd,jprev2,mprev2,anprev2,dateprev2,dateprojf, datebackf);
1.220     brouard  12484:                
1.225     brouard  12485:     /*------------ free_vector  -------------*/
                   12486:     /*  chdir(path); */
1.220     brouard  12487:                
1.215     brouard  12488:     /* free_ivector(wav,1,imx); */  /* Moved after last prevalence call */
                   12489:     /* free_imatrix(dh,1,lastpass-firstpass+2,1,imx); */
                   12490:     /* free_imatrix(bh,1,lastpass-firstpass+2,1,imx); */
                   12491:     /* free_imatrix(mw,1,lastpass-firstpass+2,1,imx);    */
1.290     brouard  12492:     free_lvector(num,firstobs,lastobs);
                   12493:     free_vector(agedc,firstobs,lastobs);
1.126     brouard  12494:     /*free_matrix(covar,0,NCOVMAX,1,n);*/
                   12495:     /*free_matrix(covar,1,NCOVMAX,1,n);*/
                   12496:     fclose(ficparo);
                   12497:     fclose(ficres);
1.220     brouard  12498:                
                   12499:                
1.186     brouard  12500:     /* Other results (useful)*/
1.220     brouard  12501:                
                   12502:                
1.126     brouard  12503:     /*--------------- Prevalence limit  (period or stable prevalence) --------------*/
1.180     brouard  12504:     /*#include "prevlim.h"*/  /* Use ficrespl, ficlog */
                   12505:     prlim=matrix(1,nlstate,1,nlstate);
1.209     brouard  12506:     prevalence_limit(p, prlim,  ageminpar, agemaxpar, ftolpl, &ncvyear);
1.126     brouard  12507:     fclose(ficrespl);
                   12508: 
                   12509:     /*------------- h Pij x at various ages ------------*/
1.180     brouard  12510:     /*#include "hpijx.h"*/
                   12511:     hPijx(p, bage, fage);
1.145     brouard  12512:     fclose(ficrespij);
1.227     brouard  12513:     
1.220     brouard  12514:     /* ncovcombmax=  pow(2,cptcoveff); */
1.219     brouard  12515:     /*-------------- Variance of one-step probabilities---*/
1.145     brouard  12516:     k=1;
1.126     brouard  12517:     varprob(optionfilefiname, matcov, p, delti, nlstate, bage, fage,k,Tvar,nbcode, ncodemax,strstart);
1.227     brouard  12518:     
1.269     brouard  12519:     /* Prevalence for each covariate combination in probs[age][status][cov] */
                   12520:     probs= ma3x(AGEINF,AGESUP,1,nlstate+ndeath, 1,ncovcombmax);
                   12521:     for(i=AGEINF;i<=AGESUP;i++)
1.219     brouard  12522:       for(j=1;j<=nlstate+ndeath;j++) /* ndeath is useless but a necessity to be compared with mobaverages */
1.225     brouard  12523:        for(k=1;k<=ncovcombmax;k++)
                   12524:          probs[i][j][k]=0.;
1.269     brouard  12525:     prevalence(probs, ageminpar, agemaxpar, s, agev, nlstate, imx, Tvar, nbcode, 
                   12526:               ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass);
1.219     brouard  12527:     if (mobilav!=0 ||mobilavproj !=0 ) {
1.269     brouard  12528:       mobaverages= ma3x(AGEINF, AGESUP,1,nlstate+ndeath, 1,ncovcombmax);
                   12529:       for(i=AGEINF;i<=AGESUP;i++)
1.268     brouard  12530:        for(j=1;j<=nlstate+ndeath;j++)
1.227     brouard  12531:          for(k=1;k<=ncovcombmax;k++)
                   12532:            mobaverages[i][j][k]=0.;
1.219     brouard  12533:       mobaverage=mobaverages;
                   12534:       if (mobilav!=0) {
1.235     brouard  12535:        printf("Movingaveraging observed prevalence\n");
1.258     brouard  12536:        fprintf(ficlog,"Movingaveraging observed prevalence\n");
1.227     brouard  12537:        if (movingaverage(probs, ageminpar, agemaxpar, mobaverage, mobilav)!=0){
                   12538:          fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);
                   12539:          printf(" Error in movingaverage mobilav=%d\n",mobilav);
                   12540:        }
1.269     brouard  12541:       } else if (mobilavproj !=0) {
1.235     brouard  12542:        printf("Movingaveraging projected observed prevalence\n");
1.258     brouard  12543:        fprintf(ficlog,"Movingaveraging projected observed prevalence\n");
1.227     brouard  12544:        if (movingaverage(probs, ageminpar, agemaxpar, mobaverage, mobilavproj)!=0){
                   12545:          fprintf(ficlog," Error in movingaverage mobilavproj=%d\n",mobilavproj);
                   12546:          printf(" Error in movingaverage mobilavproj=%d\n",mobilavproj);
                   12547:        }
1.269     brouard  12548:       }else{
                   12549:        printf("Internal error moving average\n");
                   12550:        fflush(stdout);
                   12551:        exit(1);
1.219     brouard  12552:       }
                   12553:     }/* end if moving average */
1.227     brouard  12554:     
1.126     brouard  12555:     /*---------- Forecasting ------------------*/
1.296     brouard  12556:     if(prevfcast==1){ 
                   12557:       /*   /\*    if(stepm ==1){*\/ */
                   12558:       /*   /\*  anproj1, mproj1, jproj1 either read explicitly or yrfproj *\/ */
                   12559:       /*This done previously after freqsummary.*/
                   12560:       /*   dateprojd=(jproj1+12*mproj1+365*anproj1)/365; */
                   12561:       /*   dateprojf=(jproj2+12*mproj2+365*anproj2)/365; */
                   12562:       
                   12563:       /* } else if (prvforecast==2){ */
                   12564:       /*   /\*    if(stepm ==1){*\/ */
                   12565:       /*   /\*  anproj1, mproj1, jproj1 either read explicitly or yrfproj *\/ */
                   12566:       /* } */
                   12567:       /*prevforecast(fileresu, dateintmean, anproj1, mproj1, jproj1, agemin, agemax, dateprev1, dateprev2, mobilavproj, mobaverage, bage, fage, firstpass, lastpass, anproj2, p, cptcoveff);*/
                   12568:       prevforecast(fileresu,dateintmean, dateprojd, dateprojf, agemin, agemax, dateprev1, dateprev2, mobilavproj, mobaverage, bage, fage, firstpass, lastpass, p, cptcoveff);
1.126     brouard  12569:     }
1.269     brouard  12570: 
1.296     brouard  12571:     /* Prevbcasting */
                   12572:     if(prevbcast==1){
1.219     brouard  12573:       ddnewms=matrix(1,nlstate+ndeath,1,nlstate+ndeath);       
                   12574:       ddoldms=matrix(1,nlstate+ndeath,1,nlstate+ndeath);       
                   12575:       ddsavms=matrix(1,nlstate+ndeath,1,nlstate+ndeath);
                   12576: 
                   12577:       /*--------------- Back Prevalence limit  (period or stable prevalence) --------------*/
                   12578: 
                   12579:       bprlim=matrix(1,nlstate,1,nlstate);
1.269     brouard  12580: 
1.219     brouard  12581:       back_prevalence_limit(p, bprlim,  ageminpar, agemaxpar, ftolpl, &ncvyear, dateprev1, dateprev2, firstpass, lastpass, mobilavproj);
                   12582:       fclose(ficresplb);
                   12583: 
1.222     brouard  12584:       hBijx(p, bage, fage, mobaverage);
                   12585:       fclose(ficrespijb);
1.219     brouard  12586: 
1.296     brouard  12587:       /* /\* prevbackforecast(fileresu, mobaverage, anback1, mback1, jback1, agemin, agemax, dateprev1, dateprev2, *\/ */
                   12588:       /* /\*                  mobilavproj, bage, fage, firstpass, lastpass, anback2, p, cptcoveff); *\/ */
                   12589:       /* prevbackforecast(fileresu, mobaverage, anback1, mback1, jback1, agemin, agemax, dateprev1, dateprev2, */
                   12590:       /*                      mobilavproj, bage, fage, firstpass, lastpass, anback2, p, cptcoveff); */
                   12591:       prevbackforecast(fileresu, mobaverage, dateintmean, dateprojd, dateprojf, agemin, agemax, dateprev1, dateprev2,
                   12592:                       mobilavproj, bage, fage, firstpass, lastpass, p, cptcoveff);
                   12593: 
                   12594:       
1.269     brouard  12595:       varbprlim(fileresu, nresult, mobaverage, mobilavproj, bage, fage, bprlim, &ncvyear, ftolpl, p, matcov, delti, stepm, cptcoveff);
1.268     brouard  12596: 
                   12597:       
1.269     brouard  12598:       free_matrix(bprlim,1,nlstate,1,nlstate); /*here or after loop ? */
1.219     brouard  12599:       free_matrix(ddnewms, 1, nlstate+ndeath, 1, nlstate+ndeath);
                   12600:       free_matrix(ddsavms, 1, nlstate+ndeath, 1, nlstate+ndeath);
                   12601:       free_matrix(ddoldms, 1, nlstate+ndeath, 1, nlstate+ndeath);
1.296     brouard  12602:     }    /* end  Prevbcasting */
1.268     brouard  12603:  
1.186     brouard  12604:  
                   12605:     /* ------ Other prevalence ratios------------ */
1.126     brouard  12606: 
1.215     brouard  12607:     free_ivector(wav,1,imx);
                   12608:     free_imatrix(dh,1,lastpass-firstpass+2,1,imx);
                   12609:     free_imatrix(bh,1,lastpass-firstpass+2,1,imx);
                   12610:     free_imatrix(mw,1,lastpass-firstpass+2,1,imx);   
1.218     brouard  12611:                
                   12612:                
1.127     brouard  12613:     /*---------- Health expectancies, no variances ------------*/
1.218     brouard  12614:                
1.201     brouard  12615:     strcpy(filerese,"E_");
                   12616:     strcat(filerese,fileresu);
1.126     brouard  12617:     if((ficreseij=fopen(filerese,"w"))==NULL) {
                   12618:       printf("Problem with Health Exp. resultfile: %s\n", filerese); exit(0);
                   12619:       fprintf(ficlog,"Problem with Health Exp. resultfile: %s\n", filerese); exit(0);
                   12620:     }
1.208     brouard  12621:     printf("Computing Health Expectancies: result on file '%s' ...", filerese);fflush(stdout);
                   12622:     fprintf(ficlog,"Computing Health Expectancies: result on file '%s' ...", filerese);fflush(ficlog);
1.238     brouard  12623: 
                   12624:     pstamp(ficreseij);
1.219     brouard  12625:                
1.235     brouard  12626:     i1=pow(2,cptcoveff); /* Number of combination of dummy covariates */
                   12627:     if (cptcovn < 1){i1=1;}
                   12628:     
                   12629:     for(nres=1; nres <= nresult; nres++) /* For each resultline */
                   12630:     for(k=1; k<=i1;k++){ /* For any combination of dummy covariates, fixed and varying */
1.253     brouard  12631:       if(i1 != 1 && TKresult[nres]!= k)
1.235     brouard  12632:        continue;
1.219     brouard  12633:       fprintf(ficreseij,"\n#****** ");
1.235     brouard  12634:       printf("\n#****** ");
1.225     brouard  12635:       for(j=1;j<=cptcoveff;j++) {
1.227     brouard  12636:        fprintf(ficreseij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
1.235     brouard  12637:        printf("V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   12638:       }
                   12639:       for (j=1; j<= nsq; j++){ /* For each selected (single) quantitative value */
                   12640:        printf(" V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]);
                   12641:        fprintf(ficreseij," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]);
1.219     brouard  12642:       }
                   12643:       fprintf(ficreseij,"******\n");
1.235     brouard  12644:       printf("******\n");
1.219     brouard  12645:       
                   12646:       eij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
                   12647:       oldm=oldms;savm=savms;
1.235     brouard  12648:       evsij(eij, p, nlstate, stepm, (int) bage, (int)fage, oldm, savm, k, estepm, strstart, nres);  
1.127     brouard  12649:       
1.219     brouard  12650:       free_ma3x(eij,1,nlstate,1,nlstate,(int) bage, (int)fage);
1.127     brouard  12651:     }
                   12652:     fclose(ficreseij);
1.208     brouard  12653:     printf("done evsij\n");fflush(stdout);
                   12654:     fprintf(ficlog,"done evsij\n");fflush(ficlog);
1.269     brouard  12655: 
1.218     brouard  12656:                
1.227     brouard  12657:     /*---------- State-specific expectancies and variances ------------*/
1.218     brouard  12658:                
1.201     brouard  12659:     strcpy(filerest,"T_");
                   12660:     strcat(filerest,fileresu);
1.127     brouard  12661:     if((ficrest=fopen(filerest,"w"))==NULL) {
                   12662:       printf("Problem with total LE resultfile: %s\n", filerest);goto end;
                   12663:       fprintf(ficlog,"Problem with total LE resultfile: %s\n", filerest);goto end;
                   12664:     }
1.208     brouard  12665:     printf("Computing Total Life expectancies with their standard errors: file '%s' ...\n", filerest); fflush(stdout);
                   12666:     fprintf(ficlog,"Computing Total Life expectancies with their standard errors: file '%s' ...\n", filerest); fflush(ficlog);
1.201     brouard  12667:     strcpy(fileresstde,"STDE_");
                   12668:     strcat(fileresstde,fileresu);
1.126     brouard  12669:     if((ficresstdeij=fopen(fileresstde,"w"))==NULL) {
1.227     brouard  12670:       printf("Problem with State specific Exp. and std errors resultfile: %s\n", fileresstde); exit(0);
                   12671:       fprintf(ficlog,"Problem with State specific Exp. and std errors resultfile: %s\n", fileresstde); exit(0);
1.126     brouard  12672:     }
1.227     brouard  12673:     printf("  Computing State-specific Expectancies and standard errors: result on file '%s' \n", fileresstde);
                   12674:     fprintf(ficlog,"  Computing State-specific Expectancies and standard errors: result on file '%s' \n", fileresstde);
1.126     brouard  12675: 
1.201     brouard  12676:     strcpy(filerescve,"CVE_");
                   12677:     strcat(filerescve,fileresu);
1.126     brouard  12678:     if((ficrescveij=fopen(filerescve,"w"))==NULL) {
1.227     brouard  12679:       printf("Problem with Covar. State-specific Exp. resultfile: %s\n", filerescve); exit(0);
                   12680:       fprintf(ficlog,"Problem with Covar. State-specific Exp. resultfile: %s\n", filerescve); exit(0);
1.126     brouard  12681:     }
1.227     brouard  12682:     printf("    Computing Covar. of State-specific Expectancies: result on file '%s' \n", filerescve);
                   12683:     fprintf(ficlog,"    Computing Covar. of State-specific Expectancies: result on file '%s' \n", filerescve);
1.126     brouard  12684: 
1.201     brouard  12685:     strcpy(fileresv,"V_");
                   12686:     strcat(fileresv,fileresu);
1.126     brouard  12687:     if((ficresvij=fopen(fileresv,"w"))==NULL) {
                   12688:       printf("Problem with variance resultfile: %s\n", fileresv);exit(0);
                   12689:       fprintf(ficlog,"Problem with variance resultfile: %s\n", fileresv);exit(0);
                   12690:     }
1.227     brouard  12691:     printf("      Computing Variance-covariance of State-specific Expectancies: file '%s' ... ", fileresv);fflush(stdout);
                   12692:     fprintf(ficlog,"      Computing Variance-covariance of State-specific Expectancies: file '%s' ... ", fileresv);fflush(ficlog);
1.126     brouard  12693: 
1.235     brouard  12694:     i1=pow(2,cptcoveff); /* Number of combination of dummy covariates */
                   12695:     if (cptcovn < 1){i1=1;}
                   12696:     
                   12697:     for(nres=1; nres <= nresult; nres++) /* For each resultline */
                   12698:     for(k=1; k<=i1;k++){ /* For any combination of dummy covariates, fixed and varying */
1.253     brouard  12699:       if(i1 != 1 && TKresult[nres]!= k)
1.235     brouard  12700:        continue;
1.242     brouard  12701:       printf("\n#****** Result for:");
                   12702:       fprintf(ficrest,"\n#****** Result for:");
                   12703:       fprintf(ficlog,"\n#****** Result for:");
1.227     brouard  12704:       for(j=1;j<=cptcoveff;j++){ 
                   12705:        printf("V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   12706:        fprintf(ficrest,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   12707:        fprintf(ficlog,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   12708:       }
1.235     brouard  12709:       for (j=1; j<= nsq; j++){ /* For each selected (single) quantitative value */
                   12710:        printf(" V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]);
                   12711:        fprintf(ficrest," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]);
                   12712:        fprintf(ficlog," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]);
                   12713:       }        
1.208     brouard  12714:       fprintf(ficrest,"******\n");
1.227     brouard  12715:       fprintf(ficlog,"******\n");
                   12716:       printf("******\n");
1.208     brouard  12717:       
                   12718:       fprintf(ficresstdeij,"\n#****** ");
                   12719:       fprintf(ficrescveij,"\n#****** ");
1.225     brouard  12720:       for(j=1;j<=cptcoveff;j++) {
1.227     brouard  12721:        fprintf(ficresstdeij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   12722:        fprintf(ficrescveij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
1.208     brouard  12723:       }
1.235     brouard  12724:       for (j=1; j<= nsq; j++){ /* For each selected (single) quantitative value */
                   12725:        fprintf(ficresstdeij," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]);
                   12726:        fprintf(ficrescveij," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]);
                   12727:       }        
1.208     brouard  12728:       fprintf(ficresstdeij,"******\n");
                   12729:       fprintf(ficrescveij,"******\n");
                   12730:       
                   12731:       fprintf(ficresvij,"\n#****** ");
1.238     brouard  12732:       /* pstamp(ficresvij); */
1.225     brouard  12733:       for(j=1;j<=cptcoveff;j++) 
1.227     brouard  12734:        fprintf(ficresvij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
1.235     brouard  12735:       for (j=1; j<= nsq; j++){ /* For each selected (single) quantitative value */
                   12736:        fprintf(ficresvij," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]);
                   12737:       }        
1.208     brouard  12738:       fprintf(ficresvij,"******\n");
                   12739:       
                   12740:       eij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
                   12741:       oldm=oldms;savm=savms;
1.235     brouard  12742:       printf(" cvevsij ");
                   12743:       fprintf(ficlog, " cvevsij ");
                   12744:       cvevsij(eij, p, nlstate, stepm, (int) bage, (int)fage, oldm, savm, k, estepm, delti, matcov, strstart, nres);
1.208     brouard  12745:       printf(" end cvevsij \n ");
                   12746:       fprintf(ficlog, " end cvevsij \n ");
                   12747:       
                   12748:       /*
                   12749:        */
                   12750:       /* goto endfree; */
                   12751:       
                   12752:       vareij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
                   12753:       pstamp(ficrest);
                   12754:       
1.269     brouard  12755:       epj=vector(1,nlstate+1);
1.208     brouard  12756:       for(vpopbased=0; vpopbased <= popbased; vpopbased++){ /* Done for vpopbased=0 and vpopbased=1 if popbased==1*/
1.227     brouard  12757:        oldm=oldms;savm=savms; /* ZZ Segmentation fault */
                   12758:        cptcod= 0; /* To be deleted */
                   12759:        printf("varevsij vpopbased=%d \n",vpopbased);
                   12760:        fprintf(ficlog, "varevsij vpopbased=%d \n",vpopbased);
1.235     brouard  12761:        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  12762:        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 ");
                   12763:        if(vpopbased==1)
                   12764:          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);
                   12765:        else
1.288     brouard  12766:          fprintf(ficrest,"the age specific forward period (stable) prevalences in each health state \n");
1.227     brouard  12767:        fprintf(ficrest,"# Age popbased mobilav e.. (std) ");
                   12768:        for (i=1;i<=nlstate;i++) fprintf(ficrest,"e.%d (std) ",i);
                   12769:        fprintf(ficrest,"\n");
                   12770:        /* printf("Which p?\n"); for(i=1;i<=npar;i++)printf("p[i=%d]=%lf,",i,p[i]);printf("\n"); */
1.288     brouard  12771:        printf("Computing age specific forward period (stable) prevalences in each health state \n");
                   12772:        fprintf(ficlog,"Computing age specific forward period (stable) prevalences in each health state \n");
1.227     brouard  12773:        for(age=bage; age <=fage ;age++){
1.235     brouard  12774:          prevalim(prlim, nlstate, p, age, oldm, savm, ftolpl, &ncvyear, k, nres); /*ZZ Is it the correct prevalim */
1.227     brouard  12775:          if (vpopbased==1) {
                   12776:            if(mobilav ==0){
                   12777:              for(i=1; i<=nlstate;i++)
                   12778:                prlim[i][i]=probs[(int)age][i][k];
                   12779:            }else{ /* mobilav */ 
                   12780:              for(i=1; i<=nlstate;i++)
                   12781:                prlim[i][i]=mobaverage[(int)age][i][k];
                   12782:            }
                   12783:          }
1.219     brouard  12784:          
1.227     brouard  12785:          fprintf(ficrest," %4.0f %d %d",age, vpopbased, mobilav);
                   12786:          /* fprintf(ficrest," %4.0f %d %d %d %d",age, vpopbased, mobilav,Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]); */ /* to be done */
                   12787:          /* printf(" age %4.0f ",age); */
                   12788:          for(j=1, epj[nlstate+1]=0.;j <=nlstate;j++){
                   12789:            for(i=1, epj[j]=0.;i <=nlstate;i++) {
                   12790:              epj[j] += prlim[i][i]*eij[i][j][(int)age];
                   12791:              /*ZZZ  printf("%lf %lf ", prlim[i][i] ,eij[i][j][(int)age]);*/
                   12792:              /* printf("%lf %lf ", prlim[i][i] ,eij[i][j][(int)age]); */
                   12793:            }
                   12794:            epj[nlstate+1] +=epj[j];
                   12795:          }
                   12796:          /* printf(" age %4.0f \n",age); */
1.219     brouard  12797:          
1.227     brouard  12798:          for(i=1, vepp=0.;i <=nlstate;i++)
                   12799:            for(j=1;j <=nlstate;j++)
                   12800:              vepp += vareij[i][j][(int)age];
                   12801:          fprintf(ficrest," %7.3f (%7.3f)", epj[nlstate+1],sqrt(vepp));
                   12802:          for(j=1;j <=nlstate;j++){
                   12803:            fprintf(ficrest," %7.3f (%7.3f)", epj[j],sqrt(vareij[j][j][(int)age]));
                   12804:          }
                   12805:          fprintf(ficrest,"\n");
                   12806:        }
1.208     brouard  12807:       } /* End vpopbased */
1.269     brouard  12808:       free_vector(epj,1,nlstate+1);
1.208     brouard  12809:       free_ma3x(eij,1,nlstate,1,nlstate,(int) bage, (int)fage);
                   12810:       free_ma3x(vareij,1,nlstate,1,nlstate,(int) bage, (int)fage);
1.235     brouard  12811:       printf("done selection\n");fflush(stdout);
                   12812:       fprintf(ficlog,"done selection\n");fflush(ficlog);
1.208     brouard  12813:       
1.235     brouard  12814:     } /* End k selection */
1.227     brouard  12815: 
                   12816:     printf("done State-specific expectancies\n");fflush(stdout);
                   12817:     fprintf(ficlog,"done State-specific expectancies\n");fflush(ficlog);
                   12818: 
1.288     brouard  12819:     /* variance-covariance of forward period prevalence*/
1.269     brouard  12820:     varprlim(fileresu, nresult, mobaverage, mobilavproj, bage, fage, prlim, &ncvyear, ftolpl, p, matcov, delti, stepm, cptcoveff);
1.268     brouard  12821: 
1.227     brouard  12822:     
1.290     brouard  12823:     free_vector(weight,firstobs,lastobs);
1.227     brouard  12824:     free_imatrix(Tvard,1,NCOVMAX,1,2);
1.290     brouard  12825:     free_imatrix(s,1,maxwav+1,firstobs,lastobs);
                   12826:     free_matrix(anint,1,maxwav,firstobs,lastobs); 
                   12827:     free_matrix(mint,1,maxwav,firstobs,lastobs);
                   12828:     free_ivector(cod,firstobs,lastobs);
1.227     brouard  12829:     free_ivector(tab,1,NCOVMAX);
                   12830:     fclose(ficresstdeij);
                   12831:     fclose(ficrescveij);
                   12832:     fclose(ficresvij);
                   12833:     fclose(ficrest);
                   12834:     fclose(ficpar);
                   12835:     
                   12836:     
1.126     brouard  12837:     /*---------- End : free ----------------*/
1.219     brouard  12838:     if (mobilav!=0 ||mobilavproj !=0)
1.269     brouard  12839:       free_ma3x(mobaverages,AGEINF, AGESUP,1,nlstate+ndeath, 1,ncovcombmax); /* We need to have a squared matrix with prevalence of the dead! */
                   12840:     free_ma3x(probs,AGEINF,AGESUP,1,nlstate+ndeath, 1,ncovcombmax);
1.220     brouard  12841:     free_matrix(prlim,1,nlstate,1,nlstate); /*here or after loop ? */
                   12842:     free_matrix(pmmij,1,nlstate+ndeath,1,nlstate+ndeath);
1.126     brouard  12843:   }  /* mle==-3 arrives here for freeing */
1.227     brouard  12844:   /* endfree:*/
                   12845:   free_matrix(oldms, 1,nlstate+ndeath,1,nlstate+ndeath);
                   12846:   free_matrix(newms, 1,nlstate+ndeath,1,nlstate+ndeath);
                   12847:   free_matrix(savms, 1,nlstate+ndeath,1,nlstate+ndeath);
1.290     brouard  12848:   if(ntv+nqtv>=1)free_ma3x(cotvar,1,maxwav,1,ntv+nqtv,firstobs,lastobs);
                   12849:   if(nqtv>=1)free_ma3x(cotqvar,1,maxwav,1,nqtv,firstobs,lastobs);
                   12850:   if(nqv>=1)free_matrix(coqvar,1,nqv,firstobs,lastobs);
                   12851:   free_matrix(covar,0,NCOVMAX,firstobs,lastobs);
1.227     brouard  12852:   free_matrix(matcov,1,npar,1,npar);
                   12853:   free_matrix(hess,1,npar,1,npar);
                   12854:   /*free_vector(delti,1,npar);*/
                   12855:   free_ma3x(delti3,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel); 
                   12856:   free_matrix(agev,1,maxwav,1,imx);
1.269     brouard  12857:   free_ma3x(paramstart,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel);
1.227     brouard  12858:   free_ma3x(param,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel);
                   12859:   
                   12860:   free_ivector(ncodemax,1,NCOVMAX);
                   12861:   free_ivector(ncodemaxwundef,1,NCOVMAX);
                   12862:   free_ivector(Dummy,-1,NCOVMAX);
                   12863:   free_ivector(Fixed,-1,NCOVMAX);
1.238     brouard  12864:   free_ivector(DummyV,1,NCOVMAX);
                   12865:   free_ivector(FixedV,1,NCOVMAX);
1.227     brouard  12866:   free_ivector(Typevar,-1,NCOVMAX);
                   12867:   free_ivector(Tvar,1,NCOVMAX);
1.234     brouard  12868:   free_ivector(TvarsQ,1,NCOVMAX);
                   12869:   free_ivector(TvarsQind,1,NCOVMAX);
                   12870:   free_ivector(TvarsD,1,NCOVMAX);
                   12871:   free_ivector(TvarsDind,1,NCOVMAX);
1.231     brouard  12872:   free_ivector(TvarFD,1,NCOVMAX);
                   12873:   free_ivector(TvarFDind,1,NCOVMAX);
1.232     brouard  12874:   free_ivector(TvarF,1,NCOVMAX);
                   12875:   free_ivector(TvarFind,1,NCOVMAX);
                   12876:   free_ivector(TvarV,1,NCOVMAX);
                   12877:   free_ivector(TvarVind,1,NCOVMAX);
                   12878:   free_ivector(TvarA,1,NCOVMAX);
                   12879:   free_ivector(TvarAind,1,NCOVMAX);
1.231     brouard  12880:   free_ivector(TvarFQ,1,NCOVMAX);
                   12881:   free_ivector(TvarFQind,1,NCOVMAX);
                   12882:   free_ivector(TvarVD,1,NCOVMAX);
                   12883:   free_ivector(TvarVDind,1,NCOVMAX);
                   12884:   free_ivector(TvarVQ,1,NCOVMAX);
                   12885:   free_ivector(TvarVQind,1,NCOVMAX);
1.230     brouard  12886:   free_ivector(Tvarsel,1,NCOVMAX);
                   12887:   free_vector(Tvalsel,1,NCOVMAX);
1.227     brouard  12888:   free_ivector(Tposprod,1,NCOVMAX);
                   12889:   free_ivector(Tprod,1,NCOVMAX);
                   12890:   free_ivector(Tvaraff,1,NCOVMAX);
                   12891:   free_ivector(invalidvarcomb,1,ncovcombmax);
                   12892:   free_ivector(Tage,1,NCOVMAX);
                   12893:   free_ivector(Tmodelind,1,NCOVMAX);
1.228     brouard  12894:   free_ivector(TmodelInvind,1,NCOVMAX);
                   12895:   free_ivector(TmodelInvQind,1,NCOVMAX);
1.227     brouard  12896:   
                   12897:   free_imatrix(nbcode,0,NCOVMAX,0,NCOVMAX);
                   12898:   /* free_imatrix(codtab,1,100,1,10); */
1.126     brouard  12899:   fflush(fichtm);
                   12900:   fflush(ficgp);
                   12901:   
1.227     brouard  12902:   
1.126     brouard  12903:   if((nberr >0) || (nbwarn>0)){
1.216     brouard  12904:     printf("End of Imach with %d errors and/or %d warnings. Please look at the log file for details.\n",nberr,nbwarn);
                   12905:     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  12906:   }else{
                   12907:     printf("End of Imach\n");
                   12908:     fprintf(ficlog,"End of Imach\n");
                   12909:   }
                   12910:   printf("See log file on %s\n",filelog);
                   12911:   /*  gettimeofday(&end_time, (struct timezone*)0);*/  /* after time */
1.157     brouard  12912:   /*(void) gettimeofday(&end_time,&tzp);*/
                   12913:   rend_time = time(NULL);  
                   12914:   end_time = *localtime(&rend_time);
                   12915:   /* tml = *localtime(&end_time.tm_sec); */
                   12916:   strcpy(strtend,asctime(&end_time));
1.126     brouard  12917:   printf("Local time at start %s\nLocal time at end   %s",strstart, strtend); 
                   12918:   fprintf(ficlog,"Local time at start %s\nLocal time at end   %s\n",strstart, strtend); 
1.157     brouard  12919:   printf("Total time used %s\n", asc_diff_time(rend_time -rstart_time,tmpout));
1.227     brouard  12920:   
1.157     brouard  12921:   printf("Total time was %.0lf Sec.\n", difftime(rend_time,rstart_time));
                   12922:   fprintf(ficlog,"Total time used %s\n", asc_diff_time(rend_time -rstart_time,tmpout));
                   12923:   fprintf(ficlog,"Total time was %.0lf Sec.\n", difftime(rend_time,rstart_time));
1.126     brouard  12924:   /*  printf("Total time was %d uSec.\n", total_usecs);*/
                   12925: /*   if(fileappend(fichtm,optionfilehtm)){ */
                   12926:   fprintf(fichtm,"<br>Local time at start %s<br>Local time at end   %s<br>\n</body></html>",strstart, strtend);
                   12927:   fclose(fichtm);
                   12928:   fprintf(fichtmcov,"<br>Local time at start %s<br>Local time at end   %s<br>\n</body></html>",strstart, strtend);
                   12929:   fclose(fichtmcov);
                   12930:   fclose(ficgp);
                   12931:   fclose(ficlog);
                   12932:   /*------ End -----------*/
1.227     brouard  12933:   
1.281     brouard  12934: 
                   12935: /* Executes gnuplot */
1.227     brouard  12936:   
                   12937:   printf("Before Current directory %s!\n",pathcd);
1.184     brouard  12938: #ifdef WIN32
1.227     brouard  12939:   if (_chdir(pathcd) != 0)
                   12940:     printf("Can't move to directory %s!\n",path);
                   12941:   if(_getcwd(pathcd,MAXLINE) > 0)
1.184     brouard  12942: #else
1.227     brouard  12943:     if(chdir(pathcd) != 0)
                   12944:       printf("Can't move to directory %s!\n", path);
                   12945:   if (getcwd(pathcd, MAXLINE) > 0)
1.184     brouard  12946: #endif 
1.126     brouard  12947:     printf("Current directory %s!\n",pathcd);
                   12948:   /*strcat(plotcmd,CHARSEPARATOR);*/
                   12949:   sprintf(plotcmd,"gnuplot");
1.157     brouard  12950: #ifdef _WIN32
1.126     brouard  12951:   sprintf(plotcmd,"\"%sgnuplot.exe\"",pathimach);
                   12952: #endif
                   12953:   if(!stat(plotcmd,&info)){
1.158     brouard  12954:     printf("Error or gnuplot program not found: '%s'\n",plotcmd);fflush(stdout);
1.126     brouard  12955:     if(!stat(getenv("GNUPLOTBIN"),&info)){
1.158     brouard  12956:       printf("Error or gnuplot program not found: '%s' Environment GNUPLOTBIN not set.\n",plotcmd);fflush(stdout);
1.126     brouard  12957:     }else
                   12958:       strcpy(pplotcmd,plotcmd);
1.157     brouard  12959: #ifdef __unix
1.126     brouard  12960:     strcpy(plotcmd,GNUPLOTPROGRAM);
                   12961:     if(!stat(plotcmd,&info)){
1.158     brouard  12962:       printf("Error gnuplot program not found: '%s'\n",plotcmd);fflush(stdout);
1.126     brouard  12963:     }else
                   12964:       strcpy(pplotcmd,plotcmd);
                   12965: #endif
                   12966:   }else
                   12967:     strcpy(pplotcmd,plotcmd);
                   12968:   
                   12969:   sprintf(plotcmd,"%s %s",pplotcmd, optionfilegnuplot);
1.158     brouard  12970:   printf("Starting graphs with: '%s'\n",plotcmd);fflush(stdout);
1.292     brouard  12971:   strcpy(pplotcmd,plotcmd);
1.227     brouard  12972:   
1.126     brouard  12973:   if((outcmd=system(plotcmd)) != 0){
1.292     brouard  12974:     printf("Error in gnuplot, command might not be in your path: '%s', err=%d\n", plotcmd, outcmd);
1.154     brouard  12975:     printf("\n Trying if gnuplot resides on the same directory that IMaCh\n");
1.152     brouard  12976:     sprintf(plotcmd,"%sgnuplot %s", pathimach, optionfilegnuplot);
1.292     brouard  12977:     if((outcmd=system(plotcmd)) != 0){
1.153     brouard  12978:       printf("\n Still a problem with gnuplot command %s, err=%d\n", plotcmd, outcmd);
1.292     brouard  12979:       strcpy(plotcmd,pplotcmd);
                   12980:     }
1.126     brouard  12981:   }
1.158     brouard  12982:   printf(" Successful, please wait...");
1.126     brouard  12983:   while (z[0] != 'q') {
                   12984:     /* chdir(path); */
1.154     brouard  12985:     printf("\nType e to edit results with your browser, g to graph again and q for exit: ");
1.126     brouard  12986:     scanf("%s",z);
                   12987: /*     if (z[0] == 'c') system("./imach"); */
                   12988:     if (z[0] == 'e') {
1.158     brouard  12989: #ifdef __APPLE__
1.152     brouard  12990:       sprintf(pplotcmd, "open %s", optionfilehtm);
1.157     brouard  12991: #elif __linux
                   12992:       sprintf(pplotcmd, "xdg-open %s", optionfilehtm);
1.153     brouard  12993: #else
1.152     brouard  12994:       sprintf(pplotcmd, "%s", optionfilehtm);
1.153     brouard  12995: #endif
                   12996:       printf("Starting browser with: %s",pplotcmd);fflush(stdout);
                   12997:       system(pplotcmd);
1.126     brouard  12998:     }
                   12999:     else if (z[0] == 'g') system(plotcmd);
                   13000:     else if (z[0] == 'q') exit(0);
                   13001:   }
1.227     brouard  13002: end:
1.126     brouard  13003:   while (z[0] != 'q') {
1.195     brouard  13004:     printf("\nType  q for exiting: "); fflush(stdout);
1.126     brouard  13005:     scanf("%s",z);
                   13006:   }
1.283     brouard  13007:   printf("End\n");
1.282     brouard  13008:   exit(0);
1.126     brouard  13009: }

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