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

1.294   ! brouard     1: /* $Id: imach.c,v 1.293 2019/05/09 15:17:34 brouard Exp $
1.126     brouard     2:   $State: Exp $
1.163     brouard     3:   $Log: imach.c,v $
1.294   ! brouard     4:   Revision 1.293  2019/05/09 15:17:34  brouard
        !             5:   *** empty log message ***
        !             6: 
1.293     brouard     7:   Revision 1.292  2019/05/09 14:17:20  brouard
                      8:   Summary: Some updates
                      9: 
1.292     brouard    10:   Revision 1.291  2019/05/09 13:44:18  brouard
                     11:   Summary: Before ncovmax
                     12: 
1.291     brouard    13:   Revision 1.290  2019/05/09 13:39:37  brouard
                     14:   Summary: 0.99r18 unlimited number of individuals
                     15: 
                     16:   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.
                     17: 
1.290     brouard    18:   Revision 1.289  2018/12/13 09:16:26  brouard
                     19:   Summary: Bug for young ages (<-30) will be in r17
                     20: 
1.289     brouard    21:   Revision 1.288  2018/05/02 20:58:27  brouard
                     22:   Summary: Some bugs fixed
                     23: 
1.288     brouard    24:   Revision 1.287  2018/05/01 17:57:25  brouard
                     25:   Summary: Bug fixed by providing frequencies only for non missing covariates
                     26: 
1.287     brouard    27:   Revision 1.286  2018/04/27 14:27:04  brouard
                     28:   Summary: some minor bugs
                     29: 
1.286     brouard    30:   Revision 1.285  2018/04/21 21:02:16  brouard
                     31:   Summary: Some bugs fixed, valgrind tested
                     32: 
1.285     brouard    33:   Revision 1.284  2018/04/20 05:22:13  brouard
                     34:   Summary: Computing mean and stdeviation of fixed quantitative variables
                     35: 
1.284     brouard    36:   Revision 1.283  2018/04/19 14:49:16  brouard
                     37:   Summary: Some minor bugs fixed
                     38: 
1.283     brouard    39:   Revision 1.282  2018/02/27 22:50:02  brouard
                     40:   *** empty log message ***
                     41: 
1.282     brouard    42:   Revision 1.281  2018/02/27 19:25:23  brouard
                     43:   Summary: Adding second argument for quitting
                     44: 
1.281     brouard    45:   Revision 1.280  2018/02/21 07:58:13  brouard
                     46:   Summary: 0.99r15
                     47: 
                     48:   New Makefile with recent VirtualBox 5.26. Bug in sqrt negatve in imach.c
                     49: 
1.280     brouard    50:   Revision 1.279  2017/07/20 13:35:01  brouard
                     51:   Summary: temporary working
                     52: 
1.279     brouard    53:   Revision 1.278  2017/07/19 14:09:02  brouard
                     54:   Summary: Bug for mobil_average=0 and prevforecast fixed(?)
                     55: 
1.278     brouard    56:   Revision 1.277  2017/07/17 08:53:49  brouard
                     57:   Summary: BOM files can be read now
                     58: 
1.277     brouard    59:   Revision 1.276  2017/06/30 15:48:31  brouard
                     60:   Summary: Graphs improvements
                     61: 
1.276     brouard    62:   Revision 1.275  2017/06/30 13:39:33  brouard
                     63:   Summary: Saito's color
                     64: 
1.275     brouard    65:   Revision 1.274  2017/06/29 09:47:08  brouard
                     66:   Summary: Version 0.99r14
                     67: 
1.274     brouard    68:   Revision 1.273  2017/06/27 11:06:02  brouard
                     69:   Summary: More documentation on projections
                     70: 
1.273     brouard    71:   Revision 1.272  2017/06/27 10:22:40  brouard
                     72:   Summary: Color of backprojection changed from 6 to 5(yellow)
                     73: 
1.272     brouard    74:   Revision 1.271  2017/06/27 10:17:50  brouard
                     75:   Summary: Some bug with rint
                     76: 
1.271     brouard    77:   Revision 1.270  2017/05/24 05:45:29  brouard
                     78:   *** empty log message ***
                     79: 
1.270     brouard    80:   Revision 1.269  2017/05/23 08:39:25  brouard
                     81:   Summary: Code into subroutine, cleanings
                     82: 
1.269     brouard    83:   Revision 1.268  2017/05/18 20:09:32  brouard
                     84:   Summary: backprojection and confidence intervals of backprevalence
                     85: 
1.268     brouard    86:   Revision 1.267  2017/05/13 10:25:05  brouard
                     87:   Summary: temporary save for backprojection
                     88: 
1.267     brouard    89:   Revision 1.266  2017/05/13 07:26:12  brouard
                     90:   Summary: Version 0.99r13 (improvements and bugs fixed)
                     91: 
1.266     brouard    92:   Revision 1.265  2017/04/26 16:22:11  brouard
                     93:   Summary: imach 0.99r13 Some bugs fixed
                     94: 
1.265     brouard    95:   Revision 1.264  2017/04/26 06:01:29  brouard
                     96:   Summary: Labels in graphs
                     97: 
1.264     brouard    98:   Revision 1.263  2017/04/24 15:23:15  brouard
                     99:   Summary: to save
                    100: 
1.263     brouard   101:   Revision 1.262  2017/04/18 16:48:12  brouard
                    102:   *** empty log message ***
                    103: 
1.262     brouard   104:   Revision 1.261  2017/04/05 10:14:09  brouard
                    105:   Summary: Bug in E_ as well as in T_ fixed nres-1 vs k1-1
                    106: 
1.261     brouard   107:   Revision 1.260  2017/04/04 17:46:59  brouard
                    108:   Summary: Gnuplot indexations fixed (humm)
                    109: 
1.260     brouard   110:   Revision 1.259  2017/04/04 13:01:16  brouard
                    111:   Summary: Some errors to warnings only if date of death is unknown but status is death we could set to pi3
                    112: 
1.259     brouard   113:   Revision 1.258  2017/04/03 10:17:47  brouard
                    114:   Summary: Version 0.99r12
                    115: 
                    116:   Some cleanings, conformed with updated documentation.
                    117: 
1.258     brouard   118:   Revision 1.257  2017/03/29 16:53:30  brouard
                    119:   Summary: Temp
                    120: 
1.257     brouard   121:   Revision 1.256  2017/03/27 05:50:23  brouard
                    122:   Summary: Temporary
                    123: 
1.256     brouard   124:   Revision 1.255  2017/03/08 16:02:28  brouard
                    125:   Summary: IMaCh version 0.99r10 bugs in gnuplot fixed
                    126: 
1.255     brouard   127:   Revision 1.254  2017/03/08 07:13:00  brouard
                    128:   Summary: Fixing data parameter line
                    129: 
1.254     brouard   130:   Revision 1.253  2016/12/15 11:59:41  brouard
                    131:   Summary: 0.99 in progress
                    132: 
1.253     brouard   133:   Revision 1.252  2016/09/15 21:15:37  brouard
                    134:   *** empty log message ***
                    135: 
1.252     brouard   136:   Revision 1.251  2016/09/15 15:01:13  brouard
                    137:   Summary: not working
                    138: 
1.251     brouard   139:   Revision 1.250  2016/09/08 16:07:27  brouard
                    140:   Summary: continue
                    141: 
1.250     brouard   142:   Revision 1.249  2016/09/07 17:14:18  brouard
                    143:   Summary: Starting values from frequencies
                    144: 
1.249     brouard   145:   Revision 1.248  2016/09/07 14:10:18  brouard
                    146:   *** empty log message ***
                    147: 
1.248     brouard   148:   Revision 1.247  2016/09/02 11:11:21  brouard
                    149:   *** empty log message ***
                    150: 
1.247     brouard   151:   Revision 1.246  2016/09/02 08:49:22  brouard
                    152:   *** empty log message ***
                    153: 
1.246     brouard   154:   Revision 1.245  2016/09/02 07:25:01  brouard
                    155:   *** empty log message ***
                    156: 
1.245     brouard   157:   Revision 1.244  2016/09/02 07:17:34  brouard
                    158:   *** empty log message ***
                    159: 
1.244     brouard   160:   Revision 1.243  2016/09/02 06:45:35  brouard
                    161:   *** empty log message ***
                    162: 
1.243     brouard   163:   Revision 1.242  2016/08/30 15:01:20  brouard
                    164:   Summary: Fixing a lots
                    165: 
1.242     brouard   166:   Revision 1.241  2016/08/29 17:17:25  brouard
                    167:   Summary: gnuplot problem in Back projection to fix
                    168: 
1.241     brouard   169:   Revision 1.240  2016/08/29 07:53:18  brouard
                    170:   Summary: Better
                    171: 
1.240     brouard   172:   Revision 1.239  2016/08/26 15:51:03  brouard
                    173:   Summary: Improvement in Powell output in order to copy and paste
                    174: 
                    175:   Author:
                    176: 
1.239     brouard   177:   Revision 1.238  2016/08/26 14:23:35  brouard
                    178:   Summary: Starting tests of 0.99
                    179: 
1.238     brouard   180:   Revision 1.237  2016/08/26 09:20:19  brouard
                    181:   Summary: to valgrind
                    182: 
1.237     brouard   183:   Revision 1.236  2016/08/25 10:50:18  brouard
                    184:   *** empty log message ***
                    185: 
1.236     brouard   186:   Revision 1.235  2016/08/25 06:59:23  brouard
                    187:   *** empty log message ***
                    188: 
1.235     brouard   189:   Revision 1.234  2016/08/23 16:51:20  brouard
                    190:   *** empty log message ***
                    191: 
1.234     brouard   192:   Revision 1.233  2016/08/23 07:40:50  brouard
                    193:   Summary: not working
                    194: 
1.233     brouard   195:   Revision 1.232  2016/08/22 14:20:21  brouard
                    196:   Summary: not working
                    197: 
1.232     brouard   198:   Revision 1.231  2016/08/22 07:17:15  brouard
                    199:   Summary: not working
                    200: 
1.231     brouard   201:   Revision 1.230  2016/08/22 06:55:53  brouard
                    202:   Summary: Not working
                    203: 
1.230     brouard   204:   Revision 1.229  2016/07/23 09:45:53  brouard
                    205:   Summary: Completing for func too
                    206: 
1.229     brouard   207:   Revision 1.228  2016/07/22 17:45:30  brouard
                    208:   Summary: Fixing some arrays, still debugging
                    209: 
1.227     brouard   210:   Revision 1.226  2016/07/12 18:42:34  brouard
                    211:   Summary: temp
                    212: 
1.226     brouard   213:   Revision 1.225  2016/07/12 08:40:03  brouard
                    214:   Summary: saving but not running
                    215: 
1.225     brouard   216:   Revision 1.224  2016/07/01 13:16:01  brouard
                    217:   Summary: Fixes
                    218: 
1.224     brouard   219:   Revision 1.223  2016/02/19 09:23:35  brouard
                    220:   Summary: temporary
                    221: 
1.223     brouard   222:   Revision 1.222  2016/02/17 08:14:50  brouard
                    223:   Summary: Probably last 0.98 stable version 0.98r6
                    224: 
1.222     brouard   225:   Revision 1.221  2016/02/15 23:35:36  brouard
                    226:   Summary: minor bug
                    227: 
1.220     brouard   228:   Revision 1.219  2016/02/15 00:48:12  brouard
                    229:   *** empty log message ***
                    230: 
1.219     brouard   231:   Revision 1.218  2016/02/12 11:29:23  brouard
                    232:   Summary: 0.99 Back projections
                    233: 
1.218     brouard   234:   Revision 1.217  2015/12/23 17:18:31  brouard
                    235:   Summary: Experimental backcast
                    236: 
1.217     brouard   237:   Revision 1.216  2015/12/18 17:32:11  brouard
                    238:   Summary: 0.98r4 Warning and status=-2
                    239: 
                    240:   Version 0.98r4 is now:
                    241:    - displaying an error when status is -1, date of interview unknown and date of death known;
                    242:    - permitting a status -2 when the vital status is unknown at a known date of right truncation.
                    243:   Older changes concerning s=-2, dating from 2005 have been supersed.
                    244: 
1.216     brouard   245:   Revision 1.215  2015/12/16 08:52:24  brouard
                    246:   Summary: 0.98r4 working
                    247: 
1.215     brouard   248:   Revision 1.214  2015/12/16 06:57:54  brouard
                    249:   Summary: temporary not working
                    250: 
1.214     brouard   251:   Revision 1.213  2015/12/11 18:22:17  brouard
                    252:   Summary: 0.98r4
                    253: 
1.213     brouard   254:   Revision 1.212  2015/11/21 12:47:24  brouard
                    255:   Summary: minor typo
                    256: 
1.212     brouard   257:   Revision 1.211  2015/11/21 12:41:11  brouard
                    258:   Summary: 0.98r3 with some graph of projected cross-sectional
                    259: 
                    260:   Author: Nicolas Brouard
                    261: 
1.211     brouard   262:   Revision 1.210  2015/11/18 17:41:20  brouard
1.252     brouard   263:   Summary: Start working on projected prevalences  Revision 1.209  2015/11/17 22:12:03  brouard
1.210     brouard   264:   Summary: Adding ftolpl parameter
                    265:   Author: N Brouard
                    266: 
                    267:   We had difficulties to get smoothed confidence intervals. It was due
                    268:   to the period prevalence which wasn't computed accurately. The inner
                    269:   parameter ftolpl is now an outer parameter of the .imach parameter
                    270:   file after estepm. If ftolpl is small 1.e-4 and estepm too,
                    271:   computation are long.
                    272: 
1.209     brouard   273:   Revision 1.208  2015/11/17 14:31:57  brouard
                    274:   Summary: temporary
                    275: 
1.208     brouard   276:   Revision 1.207  2015/10/27 17:36:57  brouard
                    277:   *** empty log message ***
                    278: 
1.207     brouard   279:   Revision 1.206  2015/10/24 07:14:11  brouard
                    280:   *** empty log message ***
                    281: 
1.206     brouard   282:   Revision 1.205  2015/10/23 15:50:53  brouard
                    283:   Summary: 0.98r3 some clarification for graphs on likelihood contributions
                    284: 
1.205     brouard   285:   Revision 1.204  2015/10/01 16:20:26  brouard
                    286:   Summary: Some new graphs of contribution to likelihood
                    287: 
1.204     brouard   288:   Revision 1.203  2015/09/30 17:45:14  brouard
                    289:   Summary: looking at better estimation of the hessian
                    290: 
                    291:   Also a better criteria for convergence to the period prevalence And
                    292:   therefore adding the number of years needed to converge. (The
                    293:   prevalence in any alive state shold sum to one
                    294: 
1.203     brouard   295:   Revision 1.202  2015/09/22 19:45:16  brouard
                    296:   Summary: Adding some overall graph on contribution to likelihood. Might change
                    297: 
1.202     brouard   298:   Revision 1.201  2015/09/15 17:34:58  brouard
                    299:   Summary: 0.98r0
                    300: 
                    301:   - Some new graphs like suvival functions
                    302:   - Some bugs fixed like model=1+age+V2.
                    303: 
1.201     brouard   304:   Revision 1.200  2015/09/09 16:53:55  brouard
                    305:   Summary: Big bug thanks to Flavia
                    306: 
                    307:   Even model=1+age+V2. did not work anymore
                    308: 
1.200     brouard   309:   Revision 1.199  2015/09/07 14:09:23  brouard
                    310:   Summary: 0.98q6 changing default small png format for graph to vectorized svg.
                    311: 
1.199     brouard   312:   Revision 1.198  2015/09/03 07:14:39  brouard
                    313:   Summary: 0.98q5 Flavia
                    314: 
1.198     brouard   315:   Revision 1.197  2015/09/01 18:24:39  brouard
                    316:   *** empty log message ***
                    317: 
1.197     brouard   318:   Revision 1.196  2015/08/18 23:17:52  brouard
                    319:   Summary: 0.98q5
                    320: 
1.196     brouard   321:   Revision 1.195  2015/08/18 16:28:39  brouard
                    322:   Summary: Adding a hack for testing purpose
                    323: 
                    324:   After reading the title, ftol and model lines, if the comment line has
                    325:   a q, starting with #q, the answer at the end of the run is quit. It
                    326:   permits to run test files in batch with ctest. The former workaround was
                    327:   $ echo q | imach foo.imach
                    328: 
1.195     brouard   329:   Revision 1.194  2015/08/18 13:32:00  brouard
                    330:   Summary:  Adding error when the covariance matrix doesn't contain the exact number of lines required by the model line.
                    331: 
1.194     brouard   332:   Revision 1.193  2015/08/04 07:17:42  brouard
                    333:   Summary: 0.98q4
                    334: 
1.193     brouard   335:   Revision 1.192  2015/07/16 16:49:02  brouard
                    336:   Summary: Fixing some outputs
                    337: 
1.192     brouard   338:   Revision 1.191  2015/07/14 10:00:33  brouard
                    339:   Summary: Some fixes
                    340: 
1.191     brouard   341:   Revision 1.190  2015/05/05 08:51:13  brouard
                    342:   Summary: Adding digits in output parameters (7 digits instead of 6)
                    343: 
                    344:   Fix 1+age+.
                    345: 
1.190     brouard   346:   Revision 1.189  2015/04/30 14:45:16  brouard
                    347:   Summary: 0.98q2
                    348: 
1.189     brouard   349:   Revision 1.188  2015/04/30 08:27:53  brouard
                    350:   *** empty log message ***
                    351: 
1.188     brouard   352:   Revision 1.187  2015/04/29 09:11:15  brouard
                    353:   *** empty log message ***
                    354: 
1.187     brouard   355:   Revision 1.186  2015/04/23 12:01:52  brouard
                    356:   Summary: V1*age is working now, version 0.98q1
                    357: 
                    358:   Some codes had been disabled in order to simplify and Vn*age was
                    359:   working in the optimization phase, ie, giving correct MLE parameters,
                    360:   but, as usual, outputs were not correct and program core dumped.
                    361: 
1.186     brouard   362:   Revision 1.185  2015/03/11 13:26:42  brouard
                    363:   Summary: Inclusion of compile and links command line for Intel Compiler
                    364: 
1.185     brouard   365:   Revision 1.184  2015/03/11 11:52:39  brouard
                    366:   Summary: Back from Windows 8. Intel Compiler
                    367: 
1.184     brouard   368:   Revision 1.183  2015/03/10 20:34:32  brouard
                    369:   Summary: 0.98q0, trying with directest, mnbrak fixed
                    370: 
                    371:   We use directest instead of original Powell test; probably no
                    372:   incidence on the results, but better justifications;
                    373:   We fixed Numerical Recipes mnbrak routine which was wrong and gave
                    374:   wrong results.
                    375: 
1.183     brouard   376:   Revision 1.182  2015/02/12 08:19:57  brouard
                    377:   Summary: Trying to keep directest which seems simpler and more general
                    378:   Author: Nicolas Brouard
                    379: 
1.182     brouard   380:   Revision 1.181  2015/02/11 23:22:24  brouard
                    381:   Summary: Comments on Powell added
                    382: 
                    383:   Author:
                    384: 
1.181     brouard   385:   Revision 1.180  2015/02/11 17:33:45  brouard
                    386:   Summary: Finishing move from main to function (hpijx and prevalence_limit)
                    387: 
1.180     brouard   388:   Revision 1.179  2015/01/04 09:57:06  brouard
                    389:   Summary: back to OS/X
                    390: 
1.179     brouard   391:   Revision 1.178  2015/01/04 09:35:48  brouard
                    392:   *** empty log message ***
                    393: 
1.178     brouard   394:   Revision 1.177  2015/01/03 18:40:56  brouard
                    395:   Summary: Still testing ilc32 on OSX
                    396: 
1.177     brouard   397:   Revision 1.176  2015/01/03 16:45:04  brouard
                    398:   *** empty log message ***
                    399: 
1.176     brouard   400:   Revision 1.175  2015/01/03 16:33:42  brouard
                    401:   *** empty log message ***
                    402: 
1.175     brouard   403:   Revision 1.174  2015/01/03 16:15:49  brouard
                    404:   Summary: Still in cross-compilation
                    405: 
1.174     brouard   406:   Revision 1.173  2015/01/03 12:06:26  brouard
                    407:   Summary: trying to detect cross-compilation
                    408: 
1.173     brouard   409:   Revision 1.172  2014/12/27 12:07:47  brouard
                    410:   Summary: Back from Visual Studio and Intel, options for compiling for Windows XP
                    411: 
1.172     brouard   412:   Revision 1.171  2014/12/23 13:26:59  brouard
                    413:   Summary: Back from Visual C
                    414: 
                    415:   Still problem with utsname.h on Windows
                    416: 
1.171     brouard   417:   Revision 1.170  2014/12/23 11:17:12  brouard
                    418:   Summary: Cleaning some \%% back to %%
                    419: 
                    420:   The escape was mandatory for a specific compiler (which one?), but too many warnings.
                    421: 
1.170     brouard   422:   Revision 1.169  2014/12/22 23:08:31  brouard
                    423:   Summary: 0.98p
                    424: 
                    425:   Outputs some informations on compiler used, OS etc. Testing on different platforms.
                    426: 
1.169     brouard   427:   Revision 1.168  2014/12/22 15:17:42  brouard
1.170     brouard   428:   Summary: update
1.169     brouard   429: 
1.168     brouard   430:   Revision 1.167  2014/12/22 13:50:56  brouard
                    431:   Summary: Testing uname and compiler version and if compiled 32 or 64
                    432: 
                    433:   Testing on Linux 64
                    434: 
1.167     brouard   435:   Revision 1.166  2014/12/22 11:40:47  brouard
                    436:   *** empty log message ***
                    437: 
1.166     brouard   438:   Revision 1.165  2014/12/16 11:20:36  brouard
                    439:   Summary: After compiling on Visual C
                    440: 
                    441:   * imach.c (Module): Merging 1.61 to 1.162
                    442: 
1.165     brouard   443:   Revision 1.164  2014/12/16 10:52:11  brouard
                    444:   Summary: Merging with Visual C after suppressing some warnings for unused variables. Also fixing Saito's bug 0.98Xn
                    445: 
                    446:   * imach.c (Module): Merging 1.61 to 1.162
                    447: 
1.164     brouard   448:   Revision 1.163  2014/12/16 10:30:11  brouard
                    449:   * imach.c (Module): Merging 1.61 to 1.162
                    450: 
1.163     brouard   451:   Revision 1.162  2014/09/25 11:43:39  brouard
                    452:   Summary: temporary backup 0.99!
                    453: 
1.162     brouard   454:   Revision 1.1  2014/09/16 11:06:58  brouard
                    455:   Summary: With some code (wrong) for nlopt
                    456: 
                    457:   Author:
                    458: 
                    459:   Revision 1.161  2014/09/15 20:41:41  brouard
                    460:   Summary: Problem with macro SQR on Intel compiler
                    461: 
1.161     brouard   462:   Revision 1.160  2014/09/02 09:24:05  brouard
                    463:   *** empty log message ***
                    464: 
1.160     brouard   465:   Revision 1.159  2014/09/01 10:34:10  brouard
                    466:   Summary: WIN32
                    467:   Author: Brouard
                    468: 
1.159     brouard   469:   Revision 1.158  2014/08/27 17:11:51  brouard
                    470:   *** empty log message ***
                    471: 
1.158     brouard   472:   Revision 1.157  2014/08/27 16:26:55  brouard
                    473:   Summary: Preparing windows Visual studio version
                    474:   Author: Brouard
                    475: 
                    476:   In order to compile on Visual studio, time.h is now correct and time_t
                    477:   and tm struct should be used. difftime should be used but sometimes I
                    478:   just make the differences in raw time format (time(&now).
                    479:   Trying to suppress #ifdef LINUX
                    480:   Add xdg-open for __linux in order to open default browser.
                    481: 
1.157     brouard   482:   Revision 1.156  2014/08/25 20:10:10  brouard
                    483:   *** empty log message ***
                    484: 
1.156     brouard   485:   Revision 1.155  2014/08/25 18:32:34  brouard
                    486:   Summary: New compile, minor changes
                    487:   Author: Brouard
                    488: 
1.155     brouard   489:   Revision 1.154  2014/06/20 17:32:08  brouard
                    490:   Summary: Outputs now all graphs of convergence to period prevalence
                    491: 
1.154     brouard   492:   Revision 1.153  2014/06/20 16:45:46  brouard
                    493:   Summary: If 3 live state, convergence to period prevalence on same graph
                    494:   Author: Brouard
                    495: 
1.153     brouard   496:   Revision 1.152  2014/06/18 17:54:09  brouard
                    497:   Summary: open browser, use gnuplot on same dir than imach if not found in the path
                    498: 
1.152     brouard   499:   Revision 1.151  2014/06/18 16:43:30  brouard
                    500:   *** empty log message ***
                    501: 
1.151     brouard   502:   Revision 1.150  2014/06/18 16:42:35  brouard
                    503:   Summary: If gnuplot is not in the path try on same directory than imach binary (OSX)
                    504:   Author: brouard
                    505: 
1.150     brouard   506:   Revision 1.149  2014/06/18 15:51:14  brouard
                    507:   Summary: Some fixes in parameter files errors
                    508:   Author: Nicolas Brouard
                    509: 
1.149     brouard   510:   Revision 1.148  2014/06/17 17:38:48  brouard
                    511:   Summary: Nothing new
                    512:   Author: Brouard
                    513: 
                    514:   Just a new packaging for OS/X version 0.98nS
                    515: 
1.148     brouard   516:   Revision 1.147  2014/06/16 10:33:11  brouard
                    517:   *** empty log message ***
                    518: 
1.147     brouard   519:   Revision 1.146  2014/06/16 10:20:28  brouard
                    520:   Summary: Merge
                    521:   Author: Brouard
                    522: 
                    523:   Merge, before building revised version.
                    524: 
1.146     brouard   525:   Revision 1.145  2014/06/10 21:23:15  brouard
                    526:   Summary: Debugging with valgrind
                    527:   Author: Nicolas Brouard
                    528: 
                    529:   Lot of changes in order to output the results with some covariates
                    530:   After the Edimburgh REVES conference 2014, it seems mandatory to
                    531:   improve the code.
                    532:   No more memory valgrind error but a lot has to be done in order to
                    533:   continue the work of splitting the code into subroutines.
                    534:   Also, decodemodel has been improved. Tricode is still not
                    535:   optimal. nbcode should be improved. Documentation has been added in
                    536:   the source code.
                    537: 
1.144     brouard   538:   Revision 1.143  2014/01/26 09:45:38  brouard
                    539:   Summary: Version 0.98nR (to be improved, but gives same optimization results as 0.98k. Nice, promising
                    540: 
                    541:   * imach.c (Module): Trying to merge old staffs together while being at Tokyo. Not tested...
                    542:   (Module): Version 0.98nR Running ok, but output format still only works for three covariates.
                    543: 
1.143     brouard   544:   Revision 1.142  2014/01/26 03:57:36  brouard
                    545:   Summary: gnuplot changed plot w l 1 has to be changed to plot w l lt 2
                    546: 
                    547:   * imach.c (Module): Trying to merge old staffs together while being at Tokyo. Not tested...
                    548: 
1.142     brouard   549:   Revision 1.141  2014/01/26 02:42:01  brouard
                    550:   * imach.c (Module): Trying to merge old staffs together while being at Tokyo. Not tested...
                    551: 
1.141     brouard   552:   Revision 1.140  2011/09/02 10:37:54  brouard
                    553:   Summary: times.h is ok with mingw32 now.
                    554: 
1.140     brouard   555:   Revision 1.139  2010/06/14 07:50:17  brouard
                    556:   After the theft of my laptop, I probably lost some lines of codes which were not uploaded to the CVS tree.
                    557:   I remember having already fixed agemin agemax which are pointers now but not cvs saved.
                    558: 
1.139     brouard   559:   Revision 1.138  2010/04/30 18:19:40  brouard
                    560:   *** empty log message ***
                    561: 
1.138     brouard   562:   Revision 1.137  2010/04/29 18:11:38  brouard
                    563:   (Module): Checking covariates for more complex models
                    564:   than V1+V2. A lot of change to be done. Unstable.
                    565: 
1.137     brouard   566:   Revision 1.136  2010/04/26 20:30:53  brouard
                    567:   (Module): merging some libgsl code. Fixing computation
                    568:   of likelione (using inter/intrapolation if mle = 0) in order to
                    569:   get same likelihood as if mle=1.
                    570:   Some cleaning of code and comments added.
                    571: 
1.136     brouard   572:   Revision 1.135  2009/10/29 15:33:14  brouard
                    573:   (Module): Now imach stops if date of birth, at least year of birth, is not given. Some cleaning of the code.
                    574: 
1.135     brouard   575:   Revision 1.134  2009/10/29 13:18:53  brouard
                    576:   (Module): Now imach stops if date of birth, at least year of birth, is not given. Some cleaning of the code.
                    577: 
1.134     brouard   578:   Revision 1.133  2009/07/06 10:21:25  brouard
                    579:   just nforces
                    580: 
1.133     brouard   581:   Revision 1.132  2009/07/06 08:22:05  brouard
                    582:   Many tings
                    583: 
1.132     brouard   584:   Revision 1.131  2009/06/20 16:22:47  brouard
                    585:   Some dimensions resccaled
                    586: 
1.131     brouard   587:   Revision 1.130  2009/05/26 06:44:34  brouard
                    588:   (Module): Max Covariate is now set to 20 instead of 8. A
                    589:   lot of cleaning with variables initialized to 0. Trying to make
                    590:   V2+V3*age+V1+V4 strb=V3*age+V1+V4 working better.
                    591: 
1.130     brouard   592:   Revision 1.129  2007/08/31 13:49:27  lievre
                    593:   Modification of the way of exiting when the covariate is not binary in order to see on the window the error message before exiting
                    594: 
1.129     lievre    595:   Revision 1.128  2006/06/30 13:02:05  brouard
                    596:   (Module): Clarifications on computing e.j
                    597: 
1.128     brouard   598:   Revision 1.127  2006/04/28 18:11:50  brouard
                    599:   (Module): Yes the sum of survivors was wrong since
                    600:   imach-114 because nhstepm was no more computed in the age
                    601:   loop. Now we define nhstepma in the age loop.
                    602:   (Module): In order to speed up (in case of numerous covariates) we
                    603:   compute health expectancies (without variances) in a first step
                    604:   and then all the health expectancies with variances or standard
                    605:   deviation (needs data from the Hessian matrices) which slows the
                    606:   computation.
                    607:   In the future we should be able to stop the program is only health
                    608:   expectancies and graph are needed without standard deviations.
                    609: 
1.127     brouard   610:   Revision 1.126  2006/04/28 17:23:28  brouard
                    611:   (Module): Yes the sum of survivors was wrong since
                    612:   imach-114 because nhstepm was no more computed in the age
                    613:   loop. Now we define nhstepma in the age loop.
                    614:   Version 0.98h
                    615: 
1.126     brouard   616:   Revision 1.125  2006/04/04 15:20:31  lievre
                    617:   Errors in calculation of health expectancies. Age was not initialized.
                    618:   Forecasting file added.
                    619: 
                    620:   Revision 1.124  2006/03/22 17:13:53  lievre
                    621:   Parameters are printed with %lf instead of %f (more numbers after the comma).
                    622:   The log-likelihood is printed in the log file
                    623: 
                    624:   Revision 1.123  2006/03/20 10:52:43  brouard
                    625:   * imach.c (Module): <title> changed, corresponds to .htm file
                    626:   name. <head> headers where missing.
                    627: 
                    628:   * imach.c (Module): Weights can have a decimal point as for
                    629:   English (a comma might work with a correct LC_NUMERIC environment,
                    630:   otherwise the weight is truncated).
                    631:   Modification of warning when the covariates values are not 0 or
                    632:   1.
                    633:   Version 0.98g
                    634: 
                    635:   Revision 1.122  2006/03/20 09:45:41  brouard
                    636:   (Module): Weights can have a decimal point as for
                    637:   English (a comma might work with a correct LC_NUMERIC environment,
                    638:   otherwise the weight is truncated).
                    639:   Modification of warning when the covariates values are not 0 or
                    640:   1.
                    641:   Version 0.98g
                    642: 
                    643:   Revision 1.121  2006/03/16 17:45:01  lievre
                    644:   * imach.c (Module): Comments concerning covariates added
                    645: 
                    646:   * imach.c (Module): refinements in the computation of lli if
                    647:   status=-2 in order to have more reliable computation if stepm is
                    648:   not 1 month. Version 0.98f
                    649: 
                    650:   Revision 1.120  2006/03/16 15:10:38  lievre
                    651:   (Module): refinements in the computation of lli if
                    652:   status=-2 in order to have more reliable computation if stepm is
                    653:   not 1 month. Version 0.98f
                    654: 
                    655:   Revision 1.119  2006/03/15 17:42:26  brouard
                    656:   (Module): Bug if status = -2, the loglikelihood was
                    657:   computed as likelihood omitting the logarithm. Version O.98e
                    658: 
                    659:   Revision 1.118  2006/03/14 18:20:07  brouard
                    660:   (Module): varevsij Comments added explaining the second
                    661:   table of variances if popbased=1 .
                    662:   (Module): Covariances of eij, ekl added, graphs fixed, new html link.
                    663:   (Module): Function pstamp added
                    664:   (Module): Version 0.98d
                    665: 
                    666:   Revision 1.117  2006/03/14 17:16:22  brouard
                    667:   (Module): varevsij Comments added explaining the second
                    668:   table of variances if popbased=1 .
                    669:   (Module): Covariances of eij, ekl added, graphs fixed, new html link.
                    670:   (Module): Function pstamp added
                    671:   (Module): Version 0.98d
                    672: 
                    673:   Revision 1.116  2006/03/06 10:29:27  brouard
                    674:   (Module): Variance-covariance wrong links and
                    675:   varian-covariance of ej. is needed (Saito).
                    676: 
                    677:   Revision 1.115  2006/02/27 12:17:45  brouard
                    678:   (Module): One freematrix added in mlikeli! 0.98c
                    679: 
                    680:   Revision 1.114  2006/02/26 12:57:58  brouard
                    681:   (Module): Some improvements in processing parameter
                    682:   filename with strsep.
                    683: 
                    684:   Revision 1.113  2006/02/24 14:20:24  brouard
                    685:   (Module): Memory leaks checks with valgrind and:
                    686:   datafile was not closed, some imatrix were not freed and on matrix
                    687:   allocation too.
                    688: 
                    689:   Revision 1.112  2006/01/30 09:55:26  brouard
                    690:   (Module): Back to gnuplot.exe instead of wgnuplot.exe
                    691: 
                    692:   Revision 1.111  2006/01/25 20:38:18  brouard
                    693:   (Module): Lots of cleaning and bugs added (Gompertz)
                    694:   (Module): Comments can be added in data file. Missing date values
                    695:   can be a simple dot '.'.
                    696: 
                    697:   Revision 1.110  2006/01/25 00:51:50  brouard
                    698:   (Module): Lots of cleaning and bugs added (Gompertz)
                    699: 
                    700:   Revision 1.109  2006/01/24 19:37:15  brouard
                    701:   (Module): Comments (lines starting with a #) are allowed in data.
                    702: 
                    703:   Revision 1.108  2006/01/19 18:05:42  lievre
                    704:   Gnuplot problem appeared...
                    705:   To be fixed
                    706: 
                    707:   Revision 1.107  2006/01/19 16:20:37  brouard
                    708:   Test existence of gnuplot in imach path
                    709: 
                    710:   Revision 1.106  2006/01/19 13:24:36  brouard
                    711:   Some cleaning and links added in html output
                    712: 
                    713:   Revision 1.105  2006/01/05 20:23:19  lievre
                    714:   *** empty log message ***
                    715: 
                    716:   Revision 1.104  2005/09/30 16:11:43  lievre
                    717:   (Module): sump fixed, loop imx fixed, and simplifications.
                    718:   (Module): If the status is missing at the last wave but we know
                    719:   that the person is alive, then we can code his/her status as -2
                    720:   (instead of missing=-1 in earlier versions) and his/her
                    721:   contributions to the likelihood is 1 - Prob of dying from last
                    722:   health status (= 1-p13= p11+p12 in the easiest case of somebody in
                    723:   the healthy state at last known wave). Version is 0.98
                    724: 
                    725:   Revision 1.103  2005/09/30 15:54:49  lievre
                    726:   (Module): sump fixed, loop imx fixed, and simplifications.
                    727: 
                    728:   Revision 1.102  2004/09/15 17:31:30  brouard
                    729:   Add the possibility to read data file including tab characters.
                    730: 
                    731:   Revision 1.101  2004/09/15 10:38:38  brouard
                    732:   Fix on curr_time
                    733: 
                    734:   Revision 1.100  2004/07/12 18:29:06  brouard
                    735:   Add version for Mac OS X. Just define UNIX in Makefile
                    736: 
                    737:   Revision 1.99  2004/06/05 08:57:40  brouard
                    738:   *** empty log message ***
                    739: 
                    740:   Revision 1.98  2004/05/16 15:05:56  brouard
                    741:   New version 0.97 . First attempt to estimate force of mortality
                    742:   directly from the data i.e. without the need of knowing the health
                    743:   state at each age, but using a Gompertz model: log u =a + b*age .
                    744:   This is the basic analysis of mortality and should be done before any
                    745:   other analysis, in order to test if the mortality estimated from the
                    746:   cross-longitudinal survey is different from the mortality estimated
                    747:   from other sources like vital statistic data.
                    748: 
                    749:   The same imach parameter file can be used but the option for mle should be -3.
                    750: 
1.133     brouard   751:   Agnès, who wrote this part of the code, tried to keep most of the
1.126     brouard   752:   former routines in order to include the new code within the former code.
                    753: 
                    754:   The output is very simple: only an estimate of the intercept and of
                    755:   the slope with 95% confident intervals.
                    756: 
                    757:   Current limitations:
                    758:   A) Even if you enter covariates, i.e. with the
                    759:   model= V1+V2 equation for example, the programm does only estimate a unique global model without covariates.
                    760:   B) There is no computation of Life Expectancy nor Life Table.
                    761: 
                    762:   Revision 1.97  2004/02/20 13:25:42  lievre
                    763:   Version 0.96d. Population forecasting command line is (temporarily)
                    764:   suppressed.
                    765: 
                    766:   Revision 1.96  2003/07/15 15:38:55  brouard
                    767:   * imach.c (Repository): Errors in subdirf, 2, 3 while printing tmpout is
                    768:   rewritten within the same printf. Workaround: many printfs.
                    769: 
                    770:   Revision 1.95  2003/07/08 07:54:34  brouard
                    771:   * imach.c (Repository):
                    772:   (Repository): Using imachwizard code to output a more meaningful covariance
                    773:   matrix (cov(a12,c31) instead of numbers.
                    774: 
                    775:   Revision 1.94  2003/06/27 13:00:02  brouard
                    776:   Just cleaning
                    777: 
                    778:   Revision 1.93  2003/06/25 16:33:55  brouard
                    779:   (Module): On windows (cygwin) function asctime_r doesn't
                    780:   exist so I changed back to asctime which exists.
                    781:   (Module): Version 0.96b
                    782: 
                    783:   Revision 1.92  2003/06/25 16:30:45  brouard
                    784:   (Module): On windows (cygwin) function asctime_r doesn't
                    785:   exist so I changed back to asctime which exists.
                    786: 
                    787:   Revision 1.91  2003/06/25 15:30:29  brouard
                    788:   * imach.c (Repository): Duplicated warning errors corrected.
                    789:   (Repository): Elapsed time after each iteration is now output. It
                    790:   helps to forecast when convergence will be reached. Elapsed time
                    791:   is stamped in powell.  We created a new html file for the graphs
                    792:   concerning matrix of covariance. It has extension -cov.htm.
                    793: 
                    794:   Revision 1.90  2003/06/24 12:34:15  brouard
                    795:   (Module): Some bugs corrected for windows. Also, when
                    796:   mle=-1 a template is output in file "or"mypar.txt with the design
                    797:   of the covariance matrix to be input.
                    798: 
                    799:   Revision 1.89  2003/06/24 12:30:52  brouard
                    800:   (Module): Some bugs corrected for windows. Also, when
                    801:   mle=-1 a template is output in file "or"mypar.txt with the design
                    802:   of the covariance matrix to be input.
                    803: 
                    804:   Revision 1.88  2003/06/23 17:54:56  brouard
                    805:   * 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.
                    806: 
                    807:   Revision 1.87  2003/06/18 12:26:01  brouard
                    808:   Version 0.96
                    809: 
                    810:   Revision 1.86  2003/06/17 20:04:08  brouard
                    811:   (Module): Change position of html and gnuplot routines and added
                    812:   routine fileappend.
                    813: 
                    814:   Revision 1.85  2003/06/17 13:12:43  brouard
                    815:   * imach.c (Repository): Check when date of death was earlier that
                    816:   current date of interview. It may happen when the death was just
                    817:   prior to the death. In this case, dh was negative and likelihood
                    818:   was wrong (infinity). We still send an "Error" but patch by
                    819:   assuming that the date of death was just one stepm after the
                    820:   interview.
                    821:   (Repository): Because some people have very long ID (first column)
                    822:   we changed int to long in num[] and we added a new lvector for
                    823:   memory allocation. But we also truncated to 8 characters (left
                    824:   truncation)
                    825:   (Repository): No more line truncation errors.
                    826: 
                    827:   Revision 1.84  2003/06/13 21:44:43  brouard
                    828:   * imach.c (Repository): Replace "freqsummary" at a correct
                    829:   place. It differs from routine "prevalence" which may be called
                    830:   many times. Probs is memory consuming and must be used with
                    831:   parcimony.
                    832:   Version 0.95a3 (should output exactly the same maximization than 0.8a2)
                    833: 
                    834:   Revision 1.83  2003/06/10 13:39:11  lievre
                    835:   *** empty log message ***
                    836: 
                    837:   Revision 1.82  2003/06/05 15:57:20  brouard
                    838:   Add log in  imach.c and  fullversion number is now printed.
                    839: 
                    840: */
                    841: /*
                    842:    Interpolated Markov Chain
                    843: 
                    844:   Short summary of the programme:
                    845:   
1.227     brouard   846:   This program computes Healthy Life Expectancies or State-specific
                    847:   (if states aren't health statuses) Expectancies from
                    848:   cross-longitudinal data. Cross-longitudinal data consist in: 
                    849: 
                    850:   -1- a first survey ("cross") where individuals from different ages
                    851:   are interviewed on their health status or degree of disability (in
                    852:   the case of a health survey which is our main interest)
                    853: 
                    854:   -2- at least a second wave of interviews ("longitudinal") which
                    855:   measure each change (if any) in individual health status.  Health
                    856:   expectancies are computed from the time spent in each health state
                    857:   according to a model. More health states you consider, more time is
                    858:   necessary to reach the Maximum Likelihood of the parameters involved
                    859:   in the model.  The simplest model is the multinomial logistic model
                    860:   where pij is the probability to be observed in state j at the second
                    861:   wave conditional to be observed in state i at the first
                    862:   wave. Therefore the model is: log(pij/pii)= aij + bij*age+ cij*sex +
                    863:   etc , where 'age' is age and 'sex' is a covariate. If you want to
                    864:   have a more complex model than "constant and age", you should modify
                    865:   the program where the markup *Covariates have to be included here
                    866:   again* invites you to do it.  More covariates you add, slower the
1.126     brouard   867:   convergence.
                    868: 
                    869:   The advantage of this computer programme, compared to a simple
                    870:   multinomial logistic model, is clear when the delay between waves is not
                    871:   identical for each individual. Also, if a individual missed an
                    872:   intermediate interview, the information is lost, but taken into
                    873:   account using an interpolation or extrapolation.  
                    874: 
                    875:   hPijx is the probability to be observed in state i at age x+h
                    876:   conditional to the observed state i at age x. The delay 'h' can be
                    877:   split into an exact number (nh*stepm) of unobserved intermediate
                    878:   states. This elementary transition (by month, quarter,
                    879:   semester or year) is modelled as a multinomial logistic.  The hPx
                    880:   matrix is simply the matrix product of nh*stepm elementary matrices
                    881:   and the contribution of each individual to the likelihood is simply
                    882:   hPijx.
                    883: 
                    884:   Also this programme outputs the covariance matrix of the parameters but also
1.218     brouard   885:   of the life expectancies. It also computes the period (stable) prevalence.
                    886: 
                    887: Back prevalence and projections:
1.227     brouard   888: 
                    889:  - back_prevalence_limit(double *p, double **bprlim, double ageminpar,
                    890:    double agemaxpar, double ftolpl, int *ncvyearp, double
                    891:    dateprev1,double dateprev2, int firstpass, int lastpass, int
                    892:    mobilavproj)
                    893: 
                    894:     Computes the back prevalence limit for any combination of
                    895:     covariate values k at any age between ageminpar and agemaxpar and
                    896:     returns it in **bprlim. In the loops,
                    897: 
                    898:    - **bprevalim(**bprlim, ***mobaverage, nlstate, *p, age, **oldm,
                    899:        **savm, **dnewm, **doldm, **dsavm, ftolpl, ncvyearp, k);
                    900: 
                    901:    - hBijx Back Probability to be in state i at age x-h being in j at x
1.218     brouard   902:    Computes for any combination of covariates k and any age between bage and fage 
                    903:    p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                    904:                        oldm=oldms;savm=savms;
1.227     brouard   905: 
1.267     brouard   906:    - hbxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k, nres);
1.218     brouard   907:      Computes the transition matrix starting at age 'age' over
                    908:      'nhstepm*hstepm*stepm' months (i.e. until
                    909:      age (in years)  age+nhstepm*hstepm*stepm/12) by multiplying
1.227     brouard   910:      nhstepm*hstepm matrices. 
                    911: 
                    912:      Returns p3mat[i][j][h] after calling
                    913:      p3mat[i][j][h]=matprod2(newm,
                    914:      bmij(pmmij,cov,ncovmodel,x,nlstate,prevacurrent, dnewm, doldm,
                    915:      dsavm,ij),\ 1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath,
                    916:      oldm);
1.226     brouard   917: 
                    918: Important routines
                    919: 
                    920: - func (or funcone), computes logit (pij) distinguishing
                    921:   o fixed variables (single or product dummies or quantitative);
                    922:   o varying variables by:
                    923:    (1) wave (single, product dummies, quantitative), 
                    924:    (2) by age (can be month) age (done), age*age (done), age*Vn where Vn can be:
                    925:        % fixed dummy (treated) or quantitative (not done because time-consuming);
                    926:        % varying dummy (not done) or quantitative (not done);
                    927: - Tricode which tests the modality of dummy variables (in order to warn with wrong or empty modalities)
                    928:   and returns the number of efficient covariates cptcoveff and modalities nbcode[Tvar[k]][1]= 0 and nbcode[Tvar[k]][2]= 1 usually.
                    929: - printinghtml which outputs results like life expectancy in and from a state for a combination of modalities of dummy variables
                    930:   o There are 2*cptcoveff combinations of (0,1) for cptcoveff variables. Outputting only combinations with people, éliminating 1 1 if
                    931:     race White (0 0), Black vs White (1 0), Hispanic (0 1) and 1 1 being meaningless.
1.218     brouard   932: 
1.226     brouard   933: 
                    934:   
1.133     brouard   935:   Authors: Nicolas Brouard (brouard@ined.fr) and Agnès Lièvre (lievre@ined.fr).
                    936:            Institut national d'études démographiques, Paris.
1.126     brouard   937:   This software have been partly granted by Euro-REVES, a concerted action
                    938:   from the European Union.
                    939:   It is copyrighted identically to a GNU software product, ie programme and
                    940:   software can be distributed freely for non commercial use. Latest version
                    941:   can be accessed at http://euroreves.ined.fr/imach .
                    942: 
                    943:   Help to debug: LD_PRELOAD=/usr/local/lib/libnjamd.so ./imach foo.imach
                    944:   or better on gdb : set env LD_PRELOAD=/usr/local/lib/libnjamd.so
                    945:   
                    946:   **********************************************************************/
                    947: /*
                    948:   main
                    949:   read parameterfile
                    950:   read datafile
                    951:   concatwav
                    952:   freqsummary
                    953:   if (mle >= 1)
                    954:     mlikeli
                    955:   print results files
                    956:   if mle==1 
                    957:      computes hessian
                    958:   read end of parameter file: agemin, agemax, bage, fage, estepm
                    959:       begin-prev-date,...
                    960:   open gnuplot file
                    961:   open html file
1.145     brouard   962:   period (stable) prevalence      | pl_nom    1-1 2-2 etc by covariate
                    963:    for age prevalim()             | #****** V1=0  V2=1  V3=1  V4=0 ******
                    964:                                   | 65 1 0 2 1 3 1 4 0  0.96326 0.03674
                    965:     freexexit2 possible for memory heap.
                    966: 
                    967:   h Pij x                         | pij_nom  ficrestpij
                    968:    # Cov Agex agex+h hpijx with i,j= 1-1 1-2     1-3     2-1     2-2     2-3
                    969:        1  85   85    1.00000             0.00000 0.00000 0.00000 1.00000 0.00000
                    970:        1  85   86    0.68299             0.22291 0.09410 0.71093 0.00000 0.28907
                    971: 
                    972:        1  65   99    0.00364             0.00322 0.99314 0.00350 0.00310 0.99340
                    973:        1  65  100    0.00214             0.00204 0.99581 0.00206 0.00196 0.99597
                    974:   variance of p one-step probabilities varprob  | prob_nom   ficresprob #One-step probabilities and stand. devi in ()
                    975:    Standard deviation of one-step probabilities | probcor_nom   ficresprobcor #One-step probabilities and correlation matrix
                    976:    Matrix of variance covariance of one-step probabilities |  probcov_nom ficresprobcov #One-step probabilities and covariance matrix
                    977: 
1.126     brouard   978:   forecasting if prevfcast==1 prevforecast call prevalence()
                    979:   health expectancies
                    980:   Variance-covariance of DFLE
                    981:   prevalence()
                    982:    movingaverage()
                    983:   varevsij() 
                    984:   if popbased==1 varevsij(,popbased)
                    985:   total life expectancies
                    986:   Variance of period (stable) prevalence
                    987:  end
                    988: */
                    989: 
1.187     brouard   990: /* #define DEBUG */
                    991: /* #define DEBUGBRENT */
1.203     brouard   992: /* #define DEBUGLINMIN */
                    993: /* #define DEBUGHESS */
                    994: #define DEBUGHESSIJ
1.224     brouard   995: /* #define LINMINORIGINAL  /\* Don't use loop on scale in linmin (accepting nan) *\/ */
1.165     brouard   996: #define POWELL /* Instead of NLOPT */
1.224     brouard   997: #define POWELLNOF3INFF1TEST /* Skip test */
1.186     brouard   998: /* #define POWELLORIGINAL /\* Don't use Directest to decide new direction but original Powell test *\/ */
                    999: /* #define MNBRAKORIGINAL /\* Don't use mnbrak fix *\/ */
1.126     brouard  1000: 
                   1001: #include <math.h>
                   1002: #include <stdio.h>
                   1003: #include <stdlib.h>
                   1004: #include <string.h>
1.226     brouard  1005: #include <ctype.h>
1.159     brouard  1006: 
                   1007: #ifdef _WIN32
                   1008: #include <io.h>
1.172     brouard  1009: #include <windows.h>
                   1010: #include <tchar.h>
1.159     brouard  1011: #else
1.126     brouard  1012: #include <unistd.h>
1.159     brouard  1013: #endif
1.126     brouard  1014: 
                   1015: #include <limits.h>
                   1016: #include <sys/types.h>
1.171     brouard  1017: 
                   1018: #if defined(__GNUC__)
                   1019: #include <sys/utsname.h> /* Doesn't work on Windows */
                   1020: #endif
                   1021: 
1.126     brouard  1022: #include <sys/stat.h>
                   1023: #include <errno.h>
1.159     brouard  1024: /* extern int errno; */
1.126     brouard  1025: 
1.157     brouard  1026: /* #ifdef LINUX */
                   1027: /* #include <time.h> */
                   1028: /* #include "timeval.h" */
                   1029: /* #else */
                   1030: /* #include <sys/time.h> */
                   1031: /* #endif */
                   1032: 
1.126     brouard  1033: #include <time.h>
                   1034: 
1.136     brouard  1035: #ifdef GSL
                   1036: #include <gsl/gsl_errno.h>
                   1037: #include <gsl/gsl_multimin.h>
                   1038: #endif
                   1039: 
1.167     brouard  1040: 
1.162     brouard  1041: #ifdef NLOPT
                   1042: #include <nlopt.h>
                   1043: typedef struct {
                   1044:   double (* function)(double [] );
                   1045: } myfunc_data ;
                   1046: #endif
                   1047: 
1.126     brouard  1048: /* #include <libintl.h> */
                   1049: /* #define _(String) gettext (String) */
                   1050: 
1.251     brouard  1051: #define MAXLINE 2048 /* Was 256 and 1024. Overflow with 312 with 2 states and 4 covariates. Should be ok */
1.126     brouard  1052: 
                   1053: #define GNUPLOTPROGRAM "gnuplot"
                   1054: /*#define GNUPLOTPROGRAM "..\\gp37mgw\\wgnuplot"*/
                   1055: #define FILENAMELENGTH 132
                   1056: 
                   1057: #define        GLOCK_ERROR_NOPATH              -1      /* empty path */
                   1058: #define        GLOCK_ERROR_GETCWD              -2      /* cannot get cwd */
                   1059: 
1.144     brouard  1060: #define MAXPARM 128 /**< Maximum number of parameters for the optimization */
                   1061: #define NPARMAX 64 /**< (nlstate+ndeath-1)*nlstate*ncovmodel */
1.126     brouard  1062: 
                   1063: #define NINTERVMAX 8
1.144     brouard  1064: #define NLSTATEMAX 8 /**< Maximum number of live states (for func) */
                   1065: #define NDEATHMAX 8 /**< Maximum number of dead states (for func) */
1.291     brouard  1066: #define NCOVMAX 20  /**< Maximum number of covariates, including generated covariates V1*V2 */
1.197     brouard  1067: #define codtabm(h,k)  (1 & (h-1) >> (k-1))+1
1.211     brouard  1068: /*#define decodtabm(h,k,cptcoveff)= (h <= (1<<cptcoveff)?(((h-1) >> (k-1)) & 1) +1 : -1)*/
                   1069: #define decodtabm(h,k,cptcoveff) (((h-1) >> (k-1)) & 1) +1 
1.290     brouard  1070: /*#define MAXN 20000 */ /* Should by replaced by nobs, real number of observations and unlimited */
1.144     brouard  1071: #define YEARM 12. /**< Number of months per year */
1.218     brouard  1072: /* #define AGESUP 130 */
1.288     brouard  1073: /* #define AGESUP 150 */
                   1074: #define AGESUP 200
1.268     brouard  1075: #define AGEINF 0
1.218     brouard  1076: #define AGEMARGE 25 /* Marge for agemin and agemax for(iage=agemin-AGEMARGE; iage <= agemax+3+AGEMARGE; iage++) */
1.126     brouard  1077: #define AGEBASE 40
1.194     brouard  1078: #define AGEOVERFLOW 1.e20
1.164     brouard  1079: #define AGEGOMP 10 /**< Minimal age for Gompertz adjustment */
1.157     brouard  1080: #ifdef _WIN32
                   1081: #define DIRSEPARATOR '\\'
                   1082: #define CHARSEPARATOR "\\"
                   1083: #define ODIRSEPARATOR '/'
                   1084: #else
1.126     brouard  1085: #define DIRSEPARATOR '/'
                   1086: #define CHARSEPARATOR "/"
                   1087: #define ODIRSEPARATOR '\\'
                   1088: #endif
                   1089: 
1.294   ! brouard  1090: /* $Id: imach.c,v 1.293 2019/05/09 15:17:34 brouard Exp $ */
1.126     brouard  1091: /* $State: Exp $ */
1.196     brouard  1092: #include "version.h"
                   1093: char version[]=__IMACH_VERSION__;
1.283     brouard  1094: 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.294   ! brouard  1095: char fullversion[]="$Revision: 1.293 $ $Date: 2019/05/09 15:17:34 $"; 
1.126     brouard  1096: char strstart[80];
                   1097: char optionfilext[10], optionfilefiname[FILENAMELENGTH];
1.130     brouard  1098: int erreur=0, nberr=0, nbwarn=0; /* Error number, number of errors number of warnings  */
1.187     brouard  1099: int nagesqr=0, nforce=0; /* nagesqr=1 if model is including age*age, number of forces */
1.145     brouard  1100: /* Number of covariates model=V2+V1+ V3*age+V2*V4 */
                   1101: int cptcovn=0; /**< cptcovn number of covariates added in the model (excepting constant and age and age*product) */
                   1102: int cptcovt=0; /**< cptcovt number of covariates added in the model (excepting constant and age) */
1.225     brouard  1103: int cptcovs=0; /**< cptcovs number of simple covariates in the model V2+V1 =2 */
                   1104: int cptcovsnq=0; /**< cptcovsnq number of simple covariates in the model but non quantitative V2+V1 =2 */
1.145     brouard  1105: int cptcovage=0; /**< Number of covariates with age: V3*age only =1 */
                   1106: int cptcovprodnoage=0; /**< Number of covariate products without age */   
                   1107: int cptcoveff=0; /* Total number of covariates to vary for printing results */
1.233     brouard  1108: int ncovf=0; /* Total number of effective fixed covariates (dummy or quantitative) in the model */
                   1109: int ncovv=0; /* Total number of effective (wave) varying covariates (dummy or quantitative) in the model */
1.232     brouard  1110: int ncova=0; /* Total number of effective (wave and stepm) varying with age covariates (dummy of quantitative) in the model */
1.234     brouard  1111: int nsd=0; /**< Total number of single dummy variables (output) */
                   1112: int nsq=0; /**< Total number of single quantitative variables (output) */
1.232     brouard  1113: int ncoveff=0; /* Total number of effective fixed dummy covariates in the model */
1.225     brouard  1114: int nqfveff=0; /**< nqfveff Number of Quantitative Fixed Variables Effective */
1.224     brouard  1115: int ntveff=0; /**< ntveff number of effective time varying variables */
                   1116: int nqtveff=0; /**< ntqveff number of effective time varying quantitative variables */
1.145     brouard  1117: int cptcov=0; /* Working variable */
1.290     brouard  1118: int nobs=10;  /* Number of observations in the data lastobs-firstobs */
1.218     brouard  1119: int ncovcombmax=NCOVMAX; /* Maximum calculated number of covariate combination = pow(2, cptcoveff) */
1.126     brouard  1120: int npar=NPARMAX;
                   1121: int nlstate=2; /* Number of live states */
                   1122: int ndeath=1; /* Number of dead states */
1.130     brouard  1123: int ncovmodel=0, ncovcol=0;     /* Total number of covariables including constant a12*1 +b12*x ncovmodel=2 */
1.223     brouard  1124: int  nqv=0, ntv=0, nqtv=0;    /* Total number of quantitative variables, time variable (dummy), quantitative and time variable */ 
1.126     brouard  1125: int popbased=0;
                   1126: 
                   1127: int *wav; /* Number of waves for this individuual 0 is possible */
1.130     brouard  1128: int maxwav=0; /* Maxim number of waves */
                   1129: int jmin=0, jmax=0; /* min, max spacing between 2 waves */
                   1130: int ijmin=0, ijmax=0; /* Individuals having jmin and jmax */ 
                   1131: int gipmx=0, gsw=0; /* Global variables on the number of contributions 
1.126     brouard  1132:                   to the likelihood and the sum of weights (done by funcone)*/
1.130     brouard  1133: int mle=1, weightopt=0;
1.126     brouard  1134: int **mw; /* mw[mi][i] is number of the mi wave for this individual */
                   1135: int **dh; /* dh[mi][i] is number of steps between mi,mi+1 for this individual */
                   1136: int **bh; /* bh[mi][i] is the bias (+ or -) for this individual if the delay between
                   1137:           * wave mi and wave mi+1 is not an exact multiple of stepm. */
1.162     brouard  1138: int countcallfunc=0;  /* Count the number of calls to func */
1.230     brouard  1139: int selected(int kvar); /* Is covariate kvar selected for printing results */
                   1140: 
1.130     brouard  1141: double jmean=1; /* Mean space between 2 waves */
1.145     brouard  1142: double **matprod2(); /* test */
1.126     brouard  1143: double **oldm, **newm, **savm; /* Working pointers to matrices */
                   1144: double **oldms, **newms, **savms; /* Fixed working pointers to matrices */
1.218     brouard  1145: double  **ddnewms, **ddoldms, **ddsavms; /* for freeing later */
                   1146: 
1.136     brouard  1147: /*FILE *fic ; */ /* Used in readdata only */
1.217     brouard  1148: FILE *ficpar, *ficparo,*ficres, *ficresp, *ficresphtm, *ficresphtmfr, *ficrespl, *ficresplb,*ficrespij, *ficrespijb, *ficrest,*ficresf, *ficresfb,*ficrespop;
1.126     brouard  1149: FILE *ficlog, *ficrespow;
1.130     brouard  1150: int globpr=0; /* Global variable for printing or not */
1.126     brouard  1151: double fretone; /* Only one call to likelihood */
1.130     brouard  1152: long ipmx=0; /* Number of contributions */
1.126     brouard  1153: double sw; /* Sum of weights */
                   1154: char filerespow[FILENAMELENGTH];
                   1155: char fileresilk[FILENAMELENGTH]; /* File of individual contributions to the likelihood */
                   1156: FILE *ficresilk;
                   1157: FILE *ficgp,*ficresprob,*ficpop, *ficresprobcov, *ficresprobcor;
                   1158: FILE *ficresprobmorprev;
                   1159: FILE *fichtm, *fichtmcov; /* Html File */
                   1160: FILE *ficreseij;
                   1161: char filerese[FILENAMELENGTH];
                   1162: FILE *ficresstdeij;
                   1163: char fileresstde[FILENAMELENGTH];
                   1164: FILE *ficrescveij;
                   1165: char filerescve[FILENAMELENGTH];
                   1166: FILE  *ficresvij;
                   1167: char fileresv[FILENAMELENGTH];
1.269     brouard  1168: 
1.126     brouard  1169: char title[MAXLINE];
1.234     brouard  1170: char model[MAXLINE]; /**< The model line */
1.217     brouard  1171: char optionfile[FILENAMELENGTH], datafile[FILENAMELENGTH],  filerespl[FILENAMELENGTH],  fileresplb[FILENAMELENGTH];
1.126     brouard  1172: char plotcmd[FILENAMELENGTH], pplotcmd[FILENAMELENGTH];
                   1173: char tmpout[FILENAMELENGTH],  tmpout2[FILENAMELENGTH]; 
                   1174: char command[FILENAMELENGTH];
                   1175: int  outcmd=0;
                   1176: 
1.217     brouard  1177: char fileres[FILENAMELENGTH], filerespij[FILENAMELENGTH], filerespijb[FILENAMELENGTH], filereso[FILENAMELENGTH], rfileres[FILENAMELENGTH];
1.202     brouard  1178: char fileresu[FILENAMELENGTH]; /* fileres without r in front */
1.126     brouard  1179: char filelog[FILENAMELENGTH]; /* Log file */
                   1180: char filerest[FILENAMELENGTH];
                   1181: char fileregp[FILENAMELENGTH];
                   1182: char popfile[FILENAMELENGTH];
                   1183: 
                   1184: char optionfilegnuplot[FILENAMELENGTH], optionfilehtm[FILENAMELENGTH], optionfilehtmcov[FILENAMELENGTH] ;
                   1185: 
1.157     brouard  1186: /* struct timeval start_time, end_time, curr_time, last_time, forecast_time; */
                   1187: /* struct timezone tzp; */
                   1188: /* extern int gettimeofday(); */
                   1189: struct tm tml, *gmtime(), *localtime();
                   1190: 
                   1191: extern time_t time();
                   1192: 
                   1193: struct tm start_time, end_time, curr_time, last_time, forecast_time;
                   1194: time_t  rstart_time, rend_time, rcurr_time, rlast_time, rforecast_time; /* raw time */
                   1195: struct tm tm;
                   1196: 
1.126     brouard  1197: char strcurr[80], strfor[80];
                   1198: 
                   1199: char *endptr;
                   1200: long lval;
                   1201: double dval;
                   1202: 
                   1203: #define NR_END 1
                   1204: #define FREE_ARG char*
                   1205: #define FTOL 1.0e-10
                   1206: 
                   1207: #define NRANSI 
1.240     brouard  1208: #define ITMAX 200
                   1209: #define ITPOWMAX 20 /* This is now multiplied by the number of parameters */ 
1.126     brouard  1210: 
                   1211: #define TOL 2.0e-4 
                   1212: 
                   1213: #define CGOLD 0.3819660 
                   1214: #define ZEPS 1.0e-10 
                   1215: #define SHFT(a,b,c,d) (a)=(b);(b)=(c);(c)=(d); 
                   1216: 
                   1217: #define GOLD 1.618034 
                   1218: #define GLIMIT 100.0 
                   1219: #define TINY 1.0e-20 
                   1220: 
                   1221: static double maxarg1,maxarg2;
                   1222: #define FMAX(a,b) (maxarg1=(a),maxarg2=(b),(maxarg1)>(maxarg2)? (maxarg1):(maxarg2))
                   1223: #define FMIN(a,b) (maxarg1=(a),maxarg2=(b),(maxarg1)<(maxarg2)? (maxarg1):(maxarg2))
                   1224:   
                   1225: #define SIGN(a,b) ((b)>0.0 ? fabs(a) : -fabs(a))
                   1226: #define rint(a) floor(a+0.5)
1.166     brouard  1227: /* http://www.thphys.uni-heidelberg.de/~robbers/cmbeasy/doc/html/myutils_8h-source.html */
1.183     brouard  1228: #define mytinydouble 1.0e-16
1.166     brouard  1229: /* #define DEQUAL(a,b) (fabs((a)-(b))<mytinydouble) */
                   1230: /* http://www.thphys.uni-heidelberg.de/~robbers/cmbeasy/doc/html/mynrutils_8h-source.html */
                   1231: /* static double dsqrarg; */
                   1232: /* #define DSQR(a) (DEQUAL((dsqrarg=(a)),0.0) ? 0.0 : dsqrarg*dsqrarg) */
1.126     brouard  1233: static double sqrarg;
                   1234: #define SQR(a) ((sqrarg=(a)) == 0.0 ? 0.0 :sqrarg*sqrarg)
                   1235: #define SWAP(a,b) {temp=(a);(a)=(b);(b)=temp;} 
                   1236: int agegomp= AGEGOMP;
                   1237: 
                   1238: int imx; 
                   1239: int stepm=1;
                   1240: /* Stepm, step in month: minimum step interpolation*/
                   1241: 
                   1242: int estepm;
                   1243: /* Estepm, step in month to interpolate survival function in order to approximate Life Expectancy*/
                   1244: 
                   1245: int m,nb;
                   1246: long *num;
1.197     brouard  1247: int firstpass=0, lastpass=4,*cod, *cens;
1.192     brouard  1248: int *ncodemax;  /* ncodemax[j]= Number of modalities of the j th
                   1249:                   covariate for which somebody answered excluding 
                   1250:                   undefined. Usually 2: 0 and 1. */
                   1251: int *ncodemaxwundef;  /* ncodemax[j]= Number of modalities of the j th
                   1252:                             covariate for which somebody answered including 
                   1253:                             undefined. Usually 3: -1, 0 and 1. */
1.126     brouard  1254: double **agev,*moisnais, *annais, *moisdc, *andc,**mint, **anint;
1.218     brouard  1255: double **pmmij, ***probs; /* Global pointer */
1.219     brouard  1256: double ***mobaverage, ***mobaverages; /* New global variable */
1.126     brouard  1257: double *ageexmed,*agecens;
                   1258: double dateintmean=0;
                   1259: 
                   1260: double *weight;
                   1261: int **s; /* Status */
1.141     brouard  1262: double *agedc;
1.145     brouard  1263: double  **covar; /**< covar[j,i], value of jth covariate for individual i,
1.141     brouard  1264:                  * covar=matrix(0,NCOVMAX,1,n); 
1.187     brouard  1265:                  * cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*age; */
1.268     brouard  1266: double **coqvar; /* Fixed quantitative covariate nqv */
                   1267: double ***cotvar; /* Time varying covariate ntv */
1.225     brouard  1268: double ***cotqvar; /* Time varying quantitative covariate itqv */
1.141     brouard  1269: double  idx; 
                   1270: int **nbcode, *Tvar; /**< model=V2 => Tvar[1]= 2 */
1.234     brouard  1271: /*           V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
                   1272: /*k          1  2   3   4     5    6    7     8    9 */
                   1273: /*Tvar[k]=   5  4   3   6     5    2    7     1    1 */
                   1274: /* Tndvar[k]    1   2   3               4          5 */
                   1275: /*TDvar         4   3   6               7          1 */ /* For outputs only; combination of dummies fixed or varying */
                   1276: /* Tns[k]    1  2   2              4               5 */ /* Number of single cova */
                   1277: /* TvarsD[k]    1   2                              3 */ /* Number of single dummy cova */
                   1278: /* TvarsDind    2   3                              9 */ /* position K of single dummy cova */
                   1279: /* TvarsQ[k] 1                     2                 */ /* Number of single quantitative cova */
                   1280: /* TvarsQind 1                     6                 */ /* position K of single quantitative cova */
                   1281: /* Tprod[i]=k           4               7            */
                   1282: /* Tage[i]=k                  5               8      */
                   1283: /* */
                   1284: /* Type                    */
                   1285: /* V         1  2  3  4  5 */
                   1286: /*           F  F  V  V  V */
                   1287: /*           D  Q  D  D  Q */
                   1288: /*                         */
                   1289: int *TvarsD;
                   1290: int *TvarsDind;
                   1291: int *TvarsQ;
                   1292: int *TvarsQind;
                   1293: 
1.235     brouard  1294: #define MAXRESULTLINES 10
                   1295: int nresult=0;
1.258     brouard  1296: int parameterline=0; /* # of the parameter (type) line */
1.235     brouard  1297: int TKresult[MAXRESULTLINES];
1.237     brouard  1298: int Tresult[MAXRESULTLINES][NCOVMAX];/* For dummy variable , value (output) */
                   1299: int Tinvresult[MAXRESULTLINES][NCOVMAX];/* For dummy variable , value (output) */
1.235     brouard  1300: int Tvresult[MAXRESULTLINES][NCOVMAX]; /* For dummy variable , variable # (output) */
                   1301: double Tqresult[MAXRESULTLINES][NCOVMAX]; /* For quantitative variable , value (output) */
1.237     brouard  1302: double Tqinvresult[MAXRESULTLINES][NCOVMAX]; /* For quantitative variable , value (output) */
1.235     brouard  1303: int Tvqresult[MAXRESULTLINES][NCOVMAX]; /* For quantitative variable , variable # (output) */
                   1304: 
1.234     brouard  1305: /* 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  1306: 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 */
                   1307: 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 */
                   1308: 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 */
                   1309: int *TvarVind; /**< TvarVind[1]=1, TvarVind[2]=2  in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
                   1310: 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 */
                   1311: 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  1312: int *TvarFD; /**< TvarFD[1]=V1 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
                   1313: int *TvarFDind; /* TvarFDind[1]=9 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
                   1314: int *TvarFQ; /* TvarFQ[1]=V2 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */ /* Only simple fixed quantitative variable */
                   1315: int *TvarFQind; /* TvarFQind[1]=6 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */ /* Only simple fixed quantitative variable */
                   1316: int *TvarVD; /* TvarVD[1]=V5 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */ /* Only simple fixed quantitative variable */
                   1317: int *TvarVDind; /* TvarVDind[1]=1 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */ /* Only simple fixed quantitative variable */
                   1318: 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 */
                   1319: 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 */
                   1320: 
1.230     brouard  1321: int *Tvarsel; /**< Selected covariates for output */
                   1322: double *Tvalsel; /**< Selected modality value of covariate for output */
1.226     brouard  1323: int *Typevar; /**< 0 for simple covariate (dummy, quantitative, fixed or varying), 1 for age product, 2 for  product */
1.227     brouard  1324: int *Fixed; /** Fixed[k] 0=fixed, 1 varying, 2 fixed with age product, 3 varying with age product */ 
                   1325: 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  1326: int *DummyV; /** Dummy[v] 0=dummy (0 1), 1 quantitative */
                   1327: int *FixedV; /** FixedV[v] 0 fixed, 1 varying */
1.197     brouard  1328: int *Tage;
1.227     brouard  1329: int anyvaryingduminmodel=0; /**< Any varying dummy in Model=1 yes, 0 no, to avoid a loop on waves in freq */ 
1.228     brouard  1330: 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  1331: 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*/ 
                   1332: 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  1333: int *Ndum; /** Freq of modality (tricode */
1.200     brouard  1334: /* int **codtab;*/ /**< codtab=imatrix(1,100,1,10); */
1.227     brouard  1335: int **Tvard;
                   1336: int *Tprod;/**< Gives the k position of the k1 product */
1.238     brouard  1337: /* Tprod[k1=1]=3(=V1*V4) for V2+V1+V1*V4+age*V3  */
1.227     brouard  1338: int *Tposprod; /**< Gives the k1 product from the k position */
1.238     brouard  1339:    /* if  V2+V1+V1*V4+age*V3+V3*V2   TProd[k1=2]=5 (V3*V2) */
                   1340:    /* Tposprod[k]=k1 , Tposprod[3]=1, Tposprod[5(V3*V2)]=2 (2nd product without age) */
1.227     brouard  1341: int cptcovprod, *Tvaraff, *invalidvarcomb;
1.126     brouard  1342: double *lsurv, *lpop, *tpop;
                   1343: 
1.231     brouard  1344: #define FD 1; /* Fixed dummy covariate */
                   1345: #define FQ 2; /* Fixed quantitative covariate */
                   1346: #define FP 3; /* Fixed product covariate */
                   1347: #define FPDD 7; /* Fixed product dummy*dummy covariate */
                   1348: #define FPDQ 8; /* Fixed product dummy*quantitative covariate */
                   1349: #define FPQQ 9; /* Fixed product quantitative*quantitative covariate */
                   1350: #define VD 10; /* Varying dummy covariate */
                   1351: #define VQ 11; /* Varying quantitative covariate */
                   1352: #define VP 12; /* Varying product covariate */
                   1353: #define VPDD 13; /* Varying product dummy*dummy covariate */
                   1354: #define VPDQ 14; /* Varying product dummy*quantitative covariate */
                   1355: #define VPQQ 15; /* Varying product quantitative*quantitative covariate */
                   1356: #define APFD 16; /* Age product * fixed dummy covariate */
                   1357: #define APFQ 17; /* Age product * fixed quantitative covariate */
                   1358: #define APVD 18; /* Age product * varying dummy covariate */
                   1359: #define APVQ 19; /* Age product * varying quantitative covariate */
                   1360: 
                   1361: #define FTYPE 1; /* Fixed covariate */
                   1362: #define VTYPE 2; /* Varying covariate (loop in wave) */
                   1363: #define ATYPE 2; /* Age product covariate (loop in dh within wave)*/
                   1364: 
                   1365: struct kmodel{
                   1366:        int maintype; /* main type */
                   1367:        int subtype; /* subtype */
                   1368: };
                   1369: struct kmodel modell[NCOVMAX];
                   1370: 
1.143     brouard  1371: double ftol=FTOL; /**< Tolerance for computing Max Likelihood */
                   1372: double ftolhess; /**< Tolerance for computing hessian */
1.126     brouard  1373: 
                   1374: /**************** split *************************/
                   1375: static int split( char *path, char *dirc, char *name, char *ext, char *finame )
                   1376: {
                   1377:   /* From a file name with (full) path (either Unix or Windows) we extract the directory (dirc)
                   1378:      the name of the file (name), its extension only (ext) and its first part of the name (finame)
                   1379:   */ 
                   1380:   char *ss;                            /* pointer */
1.186     brouard  1381:   int  l1=0, l2=0;                             /* length counters */
1.126     brouard  1382: 
                   1383:   l1 = strlen(path );                  /* length of path */
                   1384:   if ( l1 == 0 ) return( GLOCK_ERROR_NOPATH );
                   1385:   ss= strrchr( path, DIRSEPARATOR );           /* find last / */
                   1386:   if ( ss == NULL ) {                  /* no directory, so determine current directory */
                   1387:     strcpy( name, path );              /* we got the fullname name because no directory */
                   1388:     /*if(strrchr(path, ODIRSEPARATOR )==NULL)
                   1389:       printf("Warning you should use %s as a separator\n",DIRSEPARATOR);*/
                   1390:     /* get current working directory */
                   1391:     /*    extern  char* getcwd ( char *buf , int len);*/
1.184     brouard  1392: #ifdef WIN32
                   1393:     if (_getcwd( dirc, FILENAME_MAX ) == NULL ) {
                   1394: #else
                   1395:        if (getcwd(dirc, FILENAME_MAX) == NULL) {
                   1396: #endif
1.126     brouard  1397:       return( GLOCK_ERROR_GETCWD );
                   1398:     }
                   1399:     /* got dirc from getcwd*/
                   1400:     printf(" DIRC = %s \n",dirc);
1.205     brouard  1401:   } else {                             /* strip directory from path */
1.126     brouard  1402:     ss++;                              /* after this, the filename */
                   1403:     l2 = strlen( ss );                 /* length of filename */
                   1404:     if ( l2 == 0 ) return( GLOCK_ERROR_NOPATH );
                   1405:     strcpy( name, ss );                /* save file name */
                   1406:     strncpy( dirc, path, l1 - l2 );    /* now the directory */
1.186     brouard  1407:     dirc[l1-l2] = '\0';                        /* add zero */
1.126     brouard  1408:     printf(" DIRC2 = %s \n",dirc);
                   1409:   }
                   1410:   /* We add a separator at the end of dirc if not exists */
                   1411:   l1 = strlen( dirc );                 /* length of directory */
                   1412:   if( dirc[l1-1] != DIRSEPARATOR ){
                   1413:     dirc[l1] =  DIRSEPARATOR;
                   1414:     dirc[l1+1] = 0; 
                   1415:     printf(" DIRC3 = %s \n",dirc);
                   1416:   }
                   1417:   ss = strrchr( name, '.' );           /* find last / */
                   1418:   if (ss >0){
                   1419:     ss++;
                   1420:     strcpy(ext,ss);                    /* save extension */
                   1421:     l1= strlen( name);
                   1422:     l2= strlen(ss)+1;
                   1423:     strncpy( finame, name, l1-l2);
                   1424:     finame[l1-l2]= 0;
                   1425:   }
                   1426: 
                   1427:   return( 0 );                         /* we're done */
                   1428: }
                   1429: 
                   1430: 
                   1431: /******************************************/
                   1432: 
                   1433: void replace_back_to_slash(char *s, char*t)
                   1434: {
                   1435:   int i;
                   1436:   int lg=0;
                   1437:   i=0;
                   1438:   lg=strlen(t);
                   1439:   for(i=0; i<= lg; i++) {
                   1440:     (s[i] = t[i]);
                   1441:     if (t[i]== '\\') s[i]='/';
                   1442:   }
                   1443: }
                   1444: 
1.132     brouard  1445: char *trimbb(char *out, char *in)
1.137     brouard  1446: { /* Trim multiple blanks in line but keeps first blanks if line starts with blanks */
1.132     brouard  1447:   char *s;
                   1448:   s=out;
                   1449:   while (*in != '\0'){
1.137     brouard  1450:     while( *in == ' ' && *(in+1) == ' '){ /* && *(in+1) != '\0'){*/
1.132     brouard  1451:       in++;
                   1452:     }
                   1453:     *out++ = *in++;
                   1454:   }
                   1455:   *out='\0';
                   1456:   return s;
                   1457: }
                   1458: 
1.187     brouard  1459: /* char *substrchaine(char *out, char *in, char *chain) */
                   1460: /* { */
                   1461: /*   /\* Substract chain 'chain' from 'in', return and output 'out' *\/ */
                   1462: /*   char *s, *t; */
                   1463: /*   t=in;s=out; */
                   1464: /*   while ((*in != *chain) && (*in != '\0')){ */
                   1465: /*     *out++ = *in++; */
                   1466: /*   } */
                   1467: 
                   1468: /*   /\* *in matches *chain *\/ */
                   1469: /*   while ((*in++ == *chain++) && (*in != '\0')){ */
                   1470: /*     printf("*in = %c, *out= %c *chain= %c \n", *in, *out, *chain);  */
                   1471: /*   } */
                   1472: /*   in--; chain--; */
                   1473: /*   while ( (*in != '\0')){ */
                   1474: /*     printf("Bef *in = %c, *out= %c *chain= %c \n", *in, *out, *chain);  */
                   1475: /*     *out++ = *in++; */
                   1476: /*     printf("Aft *in = %c, *out= %c *chain= %c \n", *in, *out, *chain);  */
                   1477: /*   } */
                   1478: /*   *out='\0'; */
                   1479: /*   out=s; */
                   1480: /*   return out; */
                   1481: /* } */
                   1482: char *substrchaine(char *out, char *in, char *chain)
                   1483: {
                   1484:   /* Substract chain 'chain' from 'in', return and output 'out' */
                   1485:   /* in="V1+V1*age+age*age+V2", chain="age*age" */
                   1486: 
                   1487:   char *strloc;
                   1488: 
                   1489:   strcpy (out, in); 
                   1490:   strloc = strstr(out, chain); /* strloc points to out at age*age+V2 */
                   1491:   printf("Bef strloc=%s chain=%s out=%s \n", strloc, chain, out);
                   1492:   if(strloc != NULL){ 
                   1493:     /* will affect out */ /* strloc+strlenc(chain)=+V2 */ /* Will also work in Unicode */
                   1494:     memmove(strloc,strloc+strlen(chain), strlen(strloc+strlen(chain))+1);
                   1495:     /* strcpy (strloc, strloc +strlen(chain));*/
                   1496:   }
                   1497:   printf("Aft strloc=%s chain=%s in=%s out=%s \n", strloc, chain, in, out);
                   1498:   return out;
                   1499: }
                   1500: 
                   1501: 
1.145     brouard  1502: char *cutl(char *blocc, char *alocc, char *in, char occ)
                   1503: {
1.187     brouard  1504:   /* cuts string in into blocc and alocc where blocc ends before FIRST occurence of char 'occ' 
1.145     brouard  1505:      and alocc starts after first occurence of char 'occ' : ex cutv(blocc,alocc,"abcdef2ghi2j",'2')
1.187     brouard  1506:      gives blocc="abcdef" and alocc="ghi2j".
1.145     brouard  1507:      If occ is not found blocc is null and alocc is equal to in. Returns blocc
                   1508:   */
1.160     brouard  1509:   char *s, *t;
1.145     brouard  1510:   t=in;s=in;
                   1511:   while ((*in != occ) && (*in != '\0')){
                   1512:     *alocc++ = *in++;
                   1513:   }
                   1514:   if( *in == occ){
                   1515:     *(alocc)='\0';
                   1516:     s=++in;
                   1517:   }
                   1518:  
                   1519:   if (s == t) {/* occ not found */
                   1520:     *(alocc-(in-s))='\0';
                   1521:     in=s;
                   1522:   }
                   1523:   while ( *in != '\0'){
                   1524:     *blocc++ = *in++;
                   1525:   }
                   1526: 
                   1527:   *blocc='\0';
                   1528:   return t;
                   1529: }
1.137     brouard  1530: char *cutv(char *blocc, char *alocc, char *in, char occ)
                   1531: {
1.187     brouard  1532:   /* cuts string in into blocc and alocc where blocc ends before LAST occurence of char 'occ' 
1.137     brouard  1533:      and alocc starts after last occurence of char 'occ' : ex cutv(blocc,alocc,"abcdef2ghi2j",'2')
                   1534:      gives blocc="abcdef2ghi" and alocc="j".
                   1535:      If occ is not found blocc is null and alocc is equal to in. Returns alocc
                   1536:   */
                   1537:   char *s, *t;
                   1538:   t=in;s=in;
                   1539:   while (*in != '\0'){
                   1540:     while( *in == occ){
                   1541:       *blocc++ = *in++;
                   1542:       s=in;
                   1543:     }
                   1544:     *blocc++ = *in++;
                   1545:   }
                   1546:   if (s == t) /* occ not found */
                   1547:     *(blocc-(in-s))='\0';
                   1548:   else
                   1549:     *(blocc-(in-s)-1)='\0';
                   1550:   in=s;
                   1551:   while ( *in != '\0'){
                   1552:     *alocc++ = *in++;
                   1553:   }
                   1554: 
                   1555:   *alocc='\0';
                   1556:   return s;
                   1557: }
                   1558: 
1.126     brouard  1559: int nbocc(char *s, char occ)
                   1560: {
                   1561:   int i,j=0;
                   1562:   int lg=20;
                   1563:   i=0;
                   1564:   lg=strlen(s);
                   1565:   for(i=0; i<= lg; i++) {
1.234     brouard  1566:     if  (s[i] == occ ) j++;
1.126     brouard  1567:   }
                   1568:   return j;
                   1569: }
                   1570: 
1.137     brouard  1571: /* void cutv(char *u,char *v, char*t, char occ) */
                   1572: /* { */
                   1573: /*   /\* cuts string t into u and v where u ends before last occurence of char 'occ'  */
                   1574: /*      and v starts after last occurence of char 'occ' : ex cutv(u,v,"abcdef2ghi2j",'2') */
                   1575: /*      gives u="abcdef2ghi" and v="j" *\/ */
                   1576: /*   int i,lg,j,p=0; */
                   1577: /*   i=0; */
                   1578: /*   lg=strlen(t); */
                   1579: /*   for(j=0; j<=lg-1; j++) { */
                   1580: /*     if((t[j]!= occ) && (t[j+1]== occ)) p=j+1; */
                   1581: /*   } */
1.126     brouard  1582: 
1.137     brouard  1583: /*   for(j=0; j<p; j++) { */
                   1584: /*     (u[j] = t[j]); */
                   1585: /*   } */
                   1586: /*      u[p]='\0'; */
1.126     brouard  1587: 
1.137     brouard  1588: /*    for(j=0; j<= lg; j++) { */
                   1589: /*     if (j>=(p+1))(v[j-p-1] = t[j]); */
                   1590: /*   } */
                   1591: /* } */
1.126     brouard  1592: 
1.160     brouard  1593: #ifdef _WIN32
                   1594: char * strsep(char **pp, const char *delim)
                   1595: {
                   1596:   char *p, *q;
                   1597:          
                   1598:   if ((p = *pp) == NULL)
                   1599:     return 0;
                   1600:   if ((q = strpbrk (p, delim)) != NULL)
                   1601:   {
                   1602:     *pp = q + 1;
                   1603:     *q = '\0';
                   1604:   }
                   1605:   else
                   1606:     *pp = 0;
                   1607:   return p;
                   1608: }
                   1609: #endif
                   1610: 
1.126     brouard  1611: /********************** nrerror ********************/
                   1612: 
                   1613: void nrerror(char error_text[])
                   1614: {
                   1615:   fprintf(stderr,"ERREUR ...\n");
                   1616:   fprintf(stderr,"%s\n",error_text);
                   1617:   exit(EXIT_FAILURE);
                   1618: }
                   1619: /*********************** vector *******************/
                   1620: double *vector(int nl, int nh)
                   1621: {
                   1622:   double *v;
                   1623:   v=(double *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(double)));
                   1624:   if (!v) nrerror("allocation failure in vector");
                   1625:   return v-nl+NR_END;
                   1626: }
                   1627: 
                   1628: /************************ free vector ******************/
                   1629: void free_vector(double*v, int nl, int nh)
                   1630: {
                   1631:   free((FREE_ARG)(v+nl-NR_END));
                   1632: }
                   1633: 
                   1634: /************************ivector *******************************/
                   1635: int *ivector(long nl,long nh)
                   1636: {
                   1637:   int *v;
                   1638:   v=(int *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(int)));
                   1639:   if (!v) nrerror("allocation failure in ivector");
                   1640:   return v-nl+NR_END;
                   1641: }
                   1642: 
                   1643: /******************free ivector **************************/
                   1644: void free_ivector(int *v, long nl, long nh)
                   1645: {
                   1646:   free((FREE_ARG)(v+nl-NR_END));
                   1647: }
                   1648: 
                   1649: /************************lvector *******************************/
                   1650: long *lvector(long nl,long nh)
                   1651: {
                   1652:   long *v;
                   1653:   v=(long *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(long)));
                   1654:   if (!v) nrerror("allocation failure in ivector");
                   1655:   return v-nl+NR_END;
                   1656: }
                   1657: 
                   1658: /******************free lvector **************************/
                   1659: void free_lvector(long *v, long nl, long nh)
                   1660: {
                   1661:   free((FREE_ARG)(v+nl-NR_END));
                   1662: }
                   1663: 
                   1664: /******************* imatrix *******************************/
                   1665: int **imatrix(long nrl, long nrh, long ncl, long nch) 
                   1666:      /* allocate a int matrix with subscript range m[nrl..nrh][ncl..nch] */ 
                   1667: { 
                   1668:   long i, nrow=nrh-nrl+1,ncol=nch-ncl+1; 
                   1669:   int **m; 
                   1670:   
                   1671:   /* allocate pointers to rows */ 
                   1672:   m=(int **) malloc((size_t)((nrow+NR_END)*sizeof(int*))); 
                   1673:   if (!m) nrerror("allocation failure 1 in matrix()"); 
                   1674:   m += NR_END; 
                   1675:   m -= nrl; 
                   1676:   
                   1677:   
                   1678:   /* allocate rows and set pointers to them */ 
                   1679:   m[nrl]=(int *) malloc((size_t)((nrow*ncol+NR_END)*sizeof(int))); 
                   1680:   if (!m[nrl]) nrerror("allocation failure 2 in matrix()"); 
                   1681:   m[nrl] += NR_END; 
                   1682:   m[nrl] -= ncl; 
                   1683:   
                   1684:   for(i=nrl+1;i<=nrh;i++) m[i]=m[i-1]+ncol; 
                   1685:   
                   1686:   /* return pointer to array of pointers to rows */ 
                   1687:   return m; 
                   1688: } 
                   1689: 
                   1690: /****************** free_imatrix *************************/
                   1691: void free_imatrix(m,nrl,nrh,ncl,nch)
                   1692:       int **m;
                   1693:       long nch,ncl,nrh,nrl; 
                   1694:      /* free an int matrix allocated by imatrix() */ 
                   1695: { 
                   1696:   free((FREE_ARG) (m[nrl]+ncl-NR_END)); 
                   1697:   free((FREE_ARG) (m+nrl-NR_END)); 
                   1698: } 
                   1699: 
                   1700: /******************* matrix *******************************/
                   1701: double **matrix(long nrl, long nrh, long ncl, long nch)
                   1702: {
                   1703:   long i, nrow=nrh-nrl+1, ncol=nch-ncl+1;
                   1704:   double **m;
                   1705: 
                   1706:   m=(double **) malloc((size_t)((nrow+NR_END)*sizeof(double*)));
                   1707:   if (!m) nrerror("allocation failure 1 in matrix()");
                   1708:   m += NR_END;
                   1709:   m -= nrl;
                   1710: 
                   1711:   m[nrl]=(double *) malloc((size_t)((nrow*ncol+NR_END)*sizeof(double)));
                   1712:   if (!m[nrl]) nrerror("allocation failure 2 in matrix()");
                   1713:   m[nrl] += NR_END;
                   1714:   m[nrl] -= ncl;
                   1715: 
                   1716:   for (i=nrl+1; i<=nrh; i++) m[i]=m[i-1]+ncol;
                   1717:   return m;
1.145     brouard  1718:   /* print *(*(m+1)+70) or print m[1][70]; print m+1 or print &(m[1]) or &(m[1][0])
                   1719: m[i] = address of ith row of the table. &(m[i]) is its value which is another adress
                   1720: that of m[i][0]. In order to get the value p m[i][0] but it is unitialized.
1.126     brouard  1721:    */
                   1722: }
                   1723: 
                   1724: /*************************free matrix ************************/
                   1725: void free_matrix(double **m, long nrl, long nrh, long ncl, long nch)
                   1726: {
                   1727:   free((FREE_ARG)(m[nrl]+ncl-NR_END));
                   1728:   free((FREE_ARG)(m+nrl-NR_END));
                   1729: }
                   1730: 
                   1731: /******************* ma3x *******************************/
                   1732: double ***ma3x(long nrl, long nrh, long ncl, long nch, long nll, long nlh)
                   1733: {
                   1734:   long i, j, nrow=nrh-nrl+1, ncol=nch-ncl+1, nlay=nlh-nll+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: 
                   1749:   m[nrl][ncl]=(double *) malloc((size_t)((nrow*ncol*nlay+NR_END)*sizeof(double)));
                   1750:   if (!m[nrl][ncl]) nrerror("allocation failure 3 in matrix()");
                   1751:   m[nrl][ncl] += NR_END;
                   1752:   m[nrl][ncl] -= nll;
                   1753:   for (j=ncl+1; j<=nch; j++) 
                   1754:     m[nrl][j]=m[nrl][j-1]+nlay;
                   1755:   
                   1756:   for (i=nrl+1; i<=nrh; i++) {
                   1757:     m[i][ncl]=m[i-1l][ncl]+ncol*nlay;
                   1758:     for (j=ncl+1; j<=nch; j++) 
                   1759:       m[i][j]=m[i][j-1]+nlay;
                   1760:   }
                   1761:   return m; 
                   1762:   /*  gdb: p *(m+1) <=> p m[1] and p (m+1) <=> p (m+1) <=> p &(m[1])
                   1763:            &(m[i][j][k]) <=> *((*(m+i) + j)+k)
                   1764:   */
                   1765: }
                   1766: 
                   1767: /*************************free ma3x ************************/
                   1768: void free_ma3x(double ***m, long nrl, long nrh, long ncl, long nch,long nll, long nlh)
                   1769: {
                   1770:   free((FREE_ARG)(m[nrl][ncl]+ nll-NR_END));
                   1771:   free((FREE_ARG)(m[nrl]+ncl-NR_END));
                   1772:   free((FREE_ARG)(m+nrl-NR_END));
                   1773: }
                   1774: 
                   1775: /*************** function subdirf ***********/
                   1776: char *subdirf(char fileres[])
                   1777: {
                   1778:   /* Caution optionfilefiname is hidden */
                   1779:   strcpy(tmpout,optionfilefiname);
                   1780:   strcat(tmpout,"/"); /* Add to the right */
                   1781:   strcat(tmpout,fileres);
                   1782:   return tmpout;
                   1783: }
                   1784: 
                   1785: /*************** function subdirf2 ***********/
                   1786: char *subdirf2(char fileres[], char *preop)
                   1787: {
                   1788:   
                   1789:   /* Caution optionfilefiname is hidden */
                   1790:   strcpy(tmpout,optionfilefiname);
                   1791:   strcat(tmpout,"/");
                   1792:   strcat(tmpout,preop);
                   1793:   strcat(tmpout,fileres);
                   1794:   return tmpout;
                   1795: }
                   1796: 
                   1797: /*************** function subdirf3 ***********/
                   1798: char *subdirf3(char fileres[], char *preop, char *preop2)
                   1799: {
                   1800:   
                   1801:   /* Caution optionfilefiname is hidden */
                   1802:   strcpy(tmpout,optionfilefiname);
                   1803:   strcat(tmpout,"/");
                   1804:   strcat(tmpout,preop);
                   1805:   strcat(tmpout,preop2);
                   1806:   strcat(tmpout,fileres);
                   1807:   return tmpout;
                   1808: }
1.213     brouard  1809:  
                   1810: /*************** function subdirfext ***********/
                   1811: char *subdirfext(char fileres[], char *preop, char *postop)
                   1812: {
                   1813:   
                   1814:   strcpy(tmpout,preop);
                   1815:   strcat(tmpout,fileres);
                   1816:   strcat(tmpout,postop);
                   1817:   return tmpout;
                   1818: }
1.126     brouard  1819: 
1.213     brouard  1820: /*************** function subdirfext3 ***********/
                   1821: char *subdirfext3(char fileres[], char *preop, char *postop)
                   1822: {
                   1823:   
                   1824:   /* Caution optionfilefiname is hidden */
                   1825:   strcpy(tmpout,optionfilefiname);
                   1826:   strcat(tmpout,"/");
                   1827:   strcat(tmpout,preop);
                   1828:   strcat(tmpout,fileres);
                   1829:   strcat(tmpout,postop);
                   1830:   return tmpout;
                   1831: }
                   1832:  
1.162     brouard  1833: char *asc_diff_time(long time_sec, char ascdiff[])
                   1834: {
                   1835:   long sec_left, days, hours, minutes;
                   1836:   days = (time_sec) / (60*60*24);
                   1837:   sec_left = (time_sec) % (60*60*24);
                   1838:   hours = (sec_left) / (60*60) ;
                   1839:   sec_left = (sec_left) %(60*60);
                   1840:   minutes = (sec_left) /60;
                   1841:   sec_left = (sec_left) % (60);
                   1842:   sprintf(ascdiff,"%ld day(s) %ld hour(s) %ld minute(s) %ld second(s)",days, hours, minutes, sec_left);  
                   1843:   return ascdiff;
                   1844: }
                   1845: 
1.126     brouard  1846: /***************** f1dim *************************/
                   1847: extern int ncom; 
                   1848: extern double *pcom,*xicom;
                   1849: extern double (*nrfunc)(double []); 
                   1850:  
                   1851: double f1dim(double x) 
                   1852: { 
                   1853:   int j; 
                   1854:   double f;
                   1855:   double *xt; 
                   1856:  
                   1857:   xt=vector(1,ncom); 
                   1858:   for (j=1;j<=ncom;j++) xt[j]=pcom[j]+x*xicom[j]; 
                   1859:   f=(*nrfunc)(xt); 
                   1860:   free_vector(xt,1,ncom); 
                   1861:   return f; 
                   1862: } 
                   1863: 
                   1864: /*****************brent *************************/
                   1865: double brent(double ax, double bx, double cx, double (*f)(double), double tol,         double *xmin) 
1.187     brouard  1866: {
                   1867:   /* Given a function f, and given a bracketing triplet of abscissas ax, bx, cx (such that bx is
                   1868:    * between ax and cx, and f(bx) is less than both f(ax) and f(cx) ), this routine isolates
                   1869:    * the minimum to a fractional precision of about tol using Brent’s method. The abscissa of
                   1870:    * the minimum is returned as xmin, and the minimum function value is returned as brent , the
                   1871:    * returned function value. 
                   1872:   */
1.126     brouard  1873:   int iter; 
                   1874:   double a,b,d,etemp;
1.159     brouard  1875:   double fu=0,fv,fw,fx;
1.164     brouard  1876:   double ftemp=0.;
1.126     brouard  1877:   double p,q,r,tol1,tol2,u,v,w,x,xm; 
                   1878:   double e=0.0; 
                   1879:  
                   1880:   a=(ax < cx ? ax : cx); 
                   1881:   b=(ax > cx ? ax : cx); 
                   1882:   x=w=v=bx; 
                   1883:   fw=fv=fx=(*f)(x); 
                   1884:   for (iter=1;iter<=ITMAX;iter++) { 
                   1885:     xm=0.5*(a+b); 
                   1886:     tol2=2.0*(tol1=tol*fabs(x)+ZEPS); 
                   1887:     /*         if (2.0*fabs(fp-(*fret)) <= ftol*(fabs(fp)+fabs(*fret)))*/
                   1888:     printf(".");fflush(stdout);
                   1889:     fprintf(ficlog,".");fflush(ficlog);
1.162     brouard  1890: #ifdef DEBUGBRENT
1.126     brouard  1891:     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);
                   1892:     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);
                   1893:     /*         if ((fabs(x-xm) <= (tol2-0.5*(b-a)))||(2.0*fabs(fu-ftemp) <= ftol*1.e-2*(fabs(fu)+fabs(ftemp)))) { */
                   1894: #endif
                   1895:     if (fabs(x-xm) <= (tol2-0.5*(b-a))){ 
                   1896:       *xmin=x; 
                   1897:       return fx; 
                   1898:     } 
                   1899:     ftemp=fu;
                   1900:     if (fabs(e) > tol1) { 
                   1901:       r=(x-w)*(fx-fv); 
                   1902:       q=(x-v)*(fx-fw); 
                   1903:       p=(x-v)*q-(x-w)*r; 
                   1904:       q=2.0*(q-r); 
                   1905:       if (q > 0.0) p = -p; 
                   1906:       q=fabs(q); 
                   1907:       etemp=e; 
                   1908:       e=d; 
                   1909:       if (fabs(p) >= fabs(0.5*q*etemp) || p <= q*(a-x) || p >= q*(b-x)) 
1.224     brouard  1910:                                d=CGOLD*(e=(x >= xm ? a-x : b-x)); 
1.126     brouard  1911:       else { 
1.224     brouard  1912:                                d=p/q; 
                   1913:                                u=x+d; 
                   1914:                                if (u-a < tol2 || b-u < tol2) 
                   1915:                                        d=SIGN(tol1,xm-x); 
1.126     brouard  1916:       } 
                   1917:     } else { 
                   1918:       d=CGOLD*(e=(x >= xm ? a-x : b-x)); 
                   1919:     } 
                   1920:     u=(fabs(d) >= tol1 ? x+d : x+SIGN(tol1,d)); 
                   1921:     fu=(*f)(u); 
                   1922:     if (fu <= fx) { 
                   1923:       if (u >= x) a=x; else b=x; 
                   1924:       SHFT(v,w,x,u) 
1.183     brouard  1925:       SHFT(fv,fw,fx,fu) 
                   1926:     } else { 
                   1927:       if (u < x) a=u; else b=u; 
                   1928:       if (fu <= fw || w == x) { 
1.224     brouard  1929:                                v=w; 
                   1930:                                w=u; 
                   1931:                                fv=fw; 
                   1932:                                fw=fu; 
1.183     brouard  1933:       } else if (fu <= fv || v == x || v == w) { 
1.224     brouard  1934:                                v=u; 
                   1935:                                fv=fu; 
1.183     brouard  1936:       } 
                   1937:     } 
1.126     brouard  1938:   } 
                   1939:   nrerror("Too many iterations in brent"); 
                   1940:   *xmin=x; 
                   1941:   return fx; 
                   1942: } 
                   1943: 
                   1944: /****************** mnbrak ***********************/
                   1945: 
                   1946: void mnbrak(double *ax, double *bx, double *cx, double *fa, double *fb, double *fc, 
                   1947:            double (*func)(double)) 
1.183     brouard  1948: { /* Given a function func , and given distinct initial points ax and bx , this routine searches in
                   1949: the downhill direction (defined by the function as evaluated at the initial points) and returns
                   1950: new points ax , bx , cx that bracket a minimum of the function. Also returned are the function
                   1951: values at the three points, fa, fb , and fc such that fa > fb and fb < fc.
                   1952:    */
1.126     brouard  1953:   double ulim,u,r,q, dum;
                   1954:   double fu; 
1.187     brouard  1955: 
                   1956:   double scale=10.;
                   1957:   int iterscale=0;
                   1958: 
                   1959:   *fa=(*func)(*ax); /*  xta[j]=pcom[j]+(*ax)*xicom[j]; fa=f(xta[j])*/
                   1960:   *fb=(*func)(*bx); /*  xtb[j]=pcom[j]+(*bx)*xicom[j]; fb=f(xtb[j]) */
                   1961: 
                   1962: 
                   1963:   /* while(*fb != *fb){ /\* *ax should be ok, reducing distance to *ax *\/ */
                   1964:   /*   printf("Warning mnbrak *fb = %lf, *bx=%lf *ax=%lf *fa==%lf iter=%d\n",*fb, *bx, *ax, *fa, iterscale++); */
                   1965:   /*   *bx = *ax - (*ax - *bx)/scale; */
                   1966:   /*   *fb=(*func)(*bx);  /\*  xtb[j]=pcom[j]+(*bx)*xicom[j]; fb=f(xtb[j]) *\/ */
                   1967:   /* } */
                   1968: 
1.126     brouard  1969:   if (*fb > *fa) { 
                   1970:     SHFT(dum,*ax,*bx,dum) 
1.183     brouard  1971:     SHFT(dum,*fb,*fa,dum) 
                   1972:   } 
1.126     brouard  1973:   *cx=(*bx)+GOLD*(*bx-*ax); 
                   1974:   *fc=(*func)(*cx); 
1.183     brouard  1975: #ifdef DEBUG
1.224     brouard  1976:   printf("mnbrak0 a=%lf *fa=%lf, b=%lf *fb=%lf, c=%lf *fc=%lf\n",*ax,*fa,*bx,*fb,*cx, *fc);
                   1977:   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  1978: #endif
1.224     brouard  1979:   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  1980:     r=(*bx-*ax)*(*fb-*fc); 
1.224     brouard  1981:     q=(*bx-*cx)*(*fb-*fa); /* What if fa=inf */
1.126     brouard  1982:     u=(*bx)-((*bx-*cx)*q-(*bx-*ax)*r)/ 
1.183     brouard  1983:       (2.0*SIGN(FMAX(fabs(q-r),TINY),q-r)); /* Minimum abscissa of a parabolic estimated from (a,fa), (b,fb) and (c,fc). */
                   1984:     ulim=(*bx)+GLIMIT*(*cx-*bx); /* Maximum abscissa where function should be evaluated */
                   1985:     if ((*bx-u)*(u-*cx) > 0.0) { /* if u_p is between b and c */
1.126     brouard  1986:       fu=(*func)(u); 
1.163     brouard  1987: #ifdef DEBUG
                   1988:       /* f(x)=A(x-u)**2+f(u) */
                   1989:       double A, fparabu; 
                   1990:       A= (*fb - *fa)/(*bx-*ax)/(*bx+*ax-2*u);
                   1991:       fparabu= *fa - A*(*ax-u)*(*ax-u);
1.224     brouard  1992:       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);
                   1993:       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  1994:       /* And thus,it can be that fu > *fc even if fparabu < *fc */
                   1995:       /* mnbrak (*ax=7.666299858533, *fa=299039.693133272231), (*bx=8.595447774979, *fb=298976.598289369489),
                   1996:         (*cx=10.098840694817, *fc=298946.631474258087),  (*u=9.852501168332, fu=298948.773013752128, fparabu=298945.434711494134) */
                   1997:       /* In that case, there is no bracket in the output! Routine is wrong with many consequences.*/
1.163     brouard  1998: #endif 
1.184     brouard  1999: #ifdef MNBRAKORIGINAL
1.183     brouard  2000: #else
1.191     brouard  2001: /*       if (fu > *fc) { */
                   2002: /* #ifdef DEBUG */
                   2003: /*       printf("mnbrak4  fu > fc \n"); */
                   2004: /*       fprintf(ficlog, "mnbrak4 fu > fc\n"); */
                   2005: /* #endif */
                   2006: /*     /\* 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 *\\/  *\/ */
                   2007: /*     /\* SHFT(*fa,*fc,fu,*fc) /\\* (b, u, c) is a bracket while test fb > fc will be fu > fc  will exit *\\/ *\/ */
                   2008: /*     dum=u; /\* Shifting c and u *\/ */
                   2009: /*     u = *cx; */
                   2010: /*     *cx = dum; */
                   2011: /*     dum = fu; */
                   2012: /*     fu = *fc; */
                   2013: /*     *fc =dum; */
                   2014: /*       } else { /\* end *\/ */
                   2015: /* #ifdef DEBUG */
                   2016: /*       printf("mnbrak3  fu < fc \n"); */
                   2017: /*       fprintf(ficlog, "mnbrak3 fu < fc\n"); */
                   2018: /* #endif */
                   2019: /*     dum=u; /\* Shifting c and u *\/ */
                   2020: /*     u = *cx; */
                   2021: /*     *cx = dum; */
                   2022: /*     dum = fu; */
                   2023: /*     fu = *fc; */
                   2024: /*     *fc =dum; */
                   2025: /*       } */
1.224     brouard  2026: #ifdef DEBUGMNBRAK
                   2027:                 double A, fparabu; 
                   2028:      A= (*fb - *fa)/(*bx-*ax)/(*bx+*ax-2*u);
                   2029:      fparabu= *fa - A*(*ax-u)*(*ax-u);
                   2030:      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);
                   2031:      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  2032: #endif
1.191     brouard  2033:       dum=u; /* Shifting c and u */
                   2034:       u = *cx;
                   2035:       *cx = dum;
                   2036:       dum = fu;
                   2037:       fu = *fc;
                   2038:       *fc =dum;
1.183     brouard  2039: #endif
1.162     brouard  2040:     } else if ((*cx-u)*(u-ulim) > 0.0) { /* u is after c but before ulim */
1.183     brouard  2041: #ifdef DEBUG
1.224     brouard  2042:       printf("\nmnbrak2  u=%lf after c=%lf but before ulim\n",u,*cx);
                   2043:       fprintf(ficlog,"\nmnbrak2  u=%lf after c=%lf but before ulim\n",u,*cx);
1.183     brouard  2044: #endif
1.126     brouard  2045:       fu=(*func)(u); 
                   2046:       if (fu < *fc) { 
1.183     brouard  2047: #ifdef DEBUG
1.224     brouard  2048:                                printf("\nmnbrak2  u=%lf after c=%lf but before ulim=%lf AND fu=%lf < %lf=fc\n",u,*cx,ulim,fu, *fc);
                   2049:                          fprintf(ficlog,"\nmnbrak2  u=%lf after c=%lf but before ulim=%lf AND fu=%lf < %lf=fc\n",u,*cx,ulim,fu, *fc);
                   2050: #endif
                   2051:                          SHFT(*bx,*cx,u,*cx+GOLD*(*cx-*bx)) 
                   2052:                                SHFT(*fb,*fc,fu,(*func)(u)) 
                   2053: #ifdef DEBUG
                   2054:                                        printf("\nmnbrak2 shift GOLD c=%lf",*cx+GOLD*(*cx-*bx));
1.183     brouard  2055: #endif
                   2056:       } 
1.162     brouard  2057:     } else if ((u-ulim)*(ulim-*cx) >= 0.0) { /* u outside ulim (verifying that ulim is beyond c) */
1.183     brouard  2058: #ifdef DEBUG
1.224     brouard  2059:       printf("\nmnbrak2  u=%lf outside ulim=%lf (verifying that ulim is beyond c=%lf)\n",u,ulim,*cx);
                   2060:       fprintf(ficlog,"\nmnbrak2  u=%lf outside ulim=%lf (verifying that ulim is beyond c=%lf)\n",u,ulim,*cx);
1.183     brouard  2061: #endif
1.126     brouard  2062:       u=ulim; 
                   2063:       fu=(*func)(u); 
1.183     brouard  2064:     } else { /* u could be left to b (if r > q parabola has a maximum) */
                   2065: #ifdef DEBUG
1.224     brouard  2066:       printf("\nmnbrak2  u=%lf could be left to b=%lf (if r=%lf > q=%lf parabola has a maximum)\n",u,*bx,r,q);
                   2067:       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  2068: #endif
1.126     brouard  2069:       u=(*cx)+GOLD*(*cx-*bx); 
                   2070:       fu=(*func)(u); 
1.224     brouard  2071: #ifdef DEBUG
                   2072:       printf("\nmnbrak2 new u=%lf fu=%lf shifted gold left from c=%lf and b=%lf \n",u,fu,*cx,*bx);
                   2073:       fprintf(ficlog,"\nmnbrak2 new u=%lf fu=%lf shifted gold left from c=%lf and b=%lf \n",u,fu,*cx,*bx);
                   2074: #endif
1.183     brouard  2075:     } /* end tests */
1.126     brouard  2076:     SHFT(*ax,*bx,*cx,u) 
1.183     brouard  2077:     SHFT(*fa,*fb,*fc,fu) 
                   2078: #ifdef DEBUG
1.224     brouard  2079:       printf("\nmnbrak2 shift (*ax=%.12f, *fa=%.12lf), (*bx=%.12f, *fb=%.12lf), (*cx=%.12f, *fc=%.12lf)\n",*ax,*fa,*bx,*fb,*cx,*fc);
                   2080:       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  2081: #endif
                   2082:   } /* 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  2083: } 
                   2084: 
                   2085: /*************** linmin ************************/
1.162     brouard  2086: /* Given an n -dimensional point p[1..n] and an n -dimensional direction xi[1..n] , moves and
                   2087: resets p to where the function func(p) takes on a minimum along the direction xi from p ,
                   2088: and replaces xi by the actual vector displacement that p was moved. Also returns as fret
                   2089: the value of func at the returned location p . This is actually all accomplished by calling the
                   2090: routines mnbrak and brent .*/
1.126     brouard  2091: int ncom; 
                   2092: double *pcom,*xicom;
                   2093: double (*nrfunc)(double []); 
                   2094:  
1.224     brouard  2095: #ifdef LINMINORIGINAL
1.126     brouard  2096: void linmin(double p[], double xi[], int n, double *fret,double (*func)(double [])) 
1.224     brouard  2097: #else
                   2098: void linmin(double p[], double xi[], int n, double *fret,double (*func)(double []), int *flat) 
                   2099: #endif
1.126     brouard  2100: { 
                   2101:   double brent(double ax, double bx, double cx, 
                   2102:               double (*f)(double), double tol, double *xmin); 
                   2103:   double f1dim(double x); 
                   2104:   void mnbrak(double *ax, double *bx, double *cx, double *fa, double *fb, 
                   2105:              double *fc, double (*func)(double)); 
                   2106:   int j; 
                   2107:   double xx,xmin,bx,ax; 
                   2108:   double fx,fb,fa;
1.187     brouard  2109: 
1.203     brouard  2110: #ifdef LINMINORIGINAL
                   2111: #else
                   2112:   double scale=10., axs, xxs; /* Scale added for infinity */
                   2113: #endif
                   2114:   
1.126     brouard  2115:   ncom=n; 
                   2116:   pcom=vector(1,n); 
                   2117:   xicom=vector(1,n); 
                   2118:   nrfunc=func; 
                   2119:   for (j=1;j<=n;j++) { 
                   2120:     pcom[j]=p[j]; 
1.202     brouard  2121:     xicom[j]=xi[j]; /* Former scale xi[j] of currrent direction i */
1.126     brouard  2122:   } 
1.187     brouard  2123: 
1.203     brouard  2124: #ifdef LINMINORIGINAL
                   2125:   xx=1.;
                   2126: #else
                   2127:   axs=0.0;
                   2128:   xxs=1.;
                   2129:   do{
                   2130:     xx= xxs;
                   2131: #endif
1.187     brouard  2132:     ax=0.;
                   2133:     mnbrak(&ax,&xx,&bx,&fa,&fx,&fb,f1dim);  /* Outputs: xtx[j]=pcom[j]+(*xx)*xicom[j]; fx=f(xtx[j]) */
                   2134:     /* brackets with inputs ax=0 and xx=1, but points, pcom=p, and directions values, xicom=xi, are sent via f1dim(x) */
                   2135:     /* 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))   */
                   2136:     /* Outputs: fa=f(p(j)) and fx=f(p(j) + xxs * xi(j) ) and f(bx)= f(p(j)+ bx* xi(j)) */
                   2137:     /* Given input ax=axs and xx=xxs, xx might be too far from ax to get a finite f(xx) */
                   2138:     /* Searches on line, outputs (ax, xx, bx) such that fx < min(fa and fb) */
                   2139:     /* 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  2140: #ifdef LINMINORIGINAL
                   2141: #else
                   2142:     if (fx != fx){
1.224     brouard  2143:                        xxs=xxs/scale; /* Trying a smaller xx, closer to initial ax=0 */
                   2144:                        printf("|");
                   2145:                        fprintf(ficlog,"|");
1.203     brouard  2146: #ifdef DEBUGLINMIN
1.224     brouard  2147:                        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  2148: #endif
                   2149:     }
1.224     brouard  2150:   }while(fx != fx && xxs > 1.e-5);
1.203     brouard  2151: #endif
                   2152:   
1.191     brouard  2153: #ifdef DEBUGLINMIN
                   2154:   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  2155:   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  2156: #endif
1.224     brouard  2157: #ifdef LINMINORIGINAL
                   2158: #else
                   2159:        if(fb == fx){ /* Flat function in the direction */
                   2160:                xmin=xx;
                   2161:     *flat=1;
                   2162:        }else{
                   2163:     *flat=0;
                   2164: #endif
                   2165:                /*Flat mnbrak2 shift (*ax=0.000000000000, *fa=51626.272983130431), (*bx=-1.618034000000, *fb=51590.149499362531), (*cx=-4.236068025156, *fc=51590.149499362531) */
1.187     brouard  2166:   *fret=brent(ax,xx,bx,f1dim,TOL,&xmin); /* Giving a bracketting triplet (ax, xx, bx), find a minimum, xmin, according to f1dim, *fret(xmin),*/
                   2167:   /* fa = f(p[j] + ax * xi[j]), fx = f(p[j] + xx * xi[j]), fb = f(p[j] + bx * xi[j]) */
                   2168:   /* fmin = f(p[j] + xmin * xi[j]) */
                   2169:   /* P+lambda n in that direction (lambdamin), with TOL between abscisses */
                   2170:   /* f1dim(xmin): for (j=1;j<=ncom;j++) xt[j]=pcom[j]+xmin*xicom[j]; */
1.126     brouard  2171: #ifdef DEBUG
1.224     brouard  2172:   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);
                   2173:   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);
                   2174: #endif
                   2175: #ifdef LINMINORIGINAL
                   2176: #else
                   2177:                        }
1.126     brouard  2178: #endif
1.191     brouard  2179: #ifdef DEBUGLINMIN
                   2180:   printf("linmin end ");
1.202     brouard  2181:   fprintf(ficlog,"linmin end ");
1.191     brouard  2182: #endif
1.126     brouard  2183:   for (j=1;j<=n;j++) { 
1.203     brouard  2184: #ifdef LINMINORIGINAL
                   2185:     xi[j] *= xmin; 
                   2186: #else
                   2187: #ifdef DEBUGLINMIN
                   2188:     if(xxs <1.0)
                   2189:       printf(" before xi[%d]=%12.8f", j,xi[j]);
                   2190: #endif
                   2191:     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) */
                   2192: #ifdef DEBUGLINMIN
                   2193:     if(xxs <1.0)
                   2194:       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 );
                   2195: #endif
                   2196: #endif
1.187     brouard  2197:     p[j] += xi[j]; /* Parameters values are updated accordingly */
1.126     brouard  2198:   } 
1.191     brouard  2199: #ifdef DEBUGLINMIN
1.203     brouard  2200:   printf("\n");
1.191     brouard  2201:   printf("Comparing last *frec(xmin=%12.8f)=%12.8f from Brent and frec(0.)=%12.8f \n", xmin, *fret, (*func)(p));
1.202     brouard  2202:   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  2203:   for (j=1;j<=n;j++) { 
1.202     brouard  2204:     printf(" xi[%d]= %14.10f p[%d]= %12.7f",j,xi[j],j,p[j]);
                   2205:     fprintf(ficlog," xi[%d]= %14.10f p[%d]= %12.7f",j,xi[j],j,p[j]);
                   2206:     if(j % ncovmodel == 0){
1.191     brouard  2207:       printf("\n");
1.202     brouard  2208:       fprintf(ficlog,"\n");
                   2209:     }
1.191     brouard  2210:   }
1.203     brouard  2211: #else
1.191     brouard  2212: #endif
1.126     brouard  2213:   free_vector(xicom,1,n); 
                   2214:   free_vector(pcom,1,n); 
                   2215: } 
                   2216: 
                   2217: 
                   2218: /*************** powell ************************/
1.162     brouard  2219: /*
                   2220: Minimization of a function func of n variables. Input consists of an initial starting point
                   2221: p[1..n] ; an initial matrix xi[1..n][1..n] , whose columns contain the initial set of di-
                   2222: rections (usually the n unit vectors); and ftol , the fractional tolerance in the function value
                   2223: such that failure to decrease by more than this amount on one iteration signals doneness. On
                   2224: output, p is set to the best point found, xi is the then-current direction set, fret is the returned
                   2225: function value at p , and iter is the number of iterations taken. The routine linmin is used.
                   2226:  */
1.224     brouard  2227: #ifdef LINMINORIGINAL
                   2228: #else
                   2229:        int *flatdir; /* Function is vanishing in that direction */
1.225     brouard  2230:        int flat=0, flatd=0; /* Function is vanishing in that direction */
1.224     brouard  2231: #endif
1.126     brouard  2232: void powell(double p[], double **xi, int n, double ftol, int *iter, double *fret, 
                   2233:            double (*func)(double [])) 
                   2234: { 
1.224     brouard  2235: #ifdef LINMINORIGINAL
                   2236:  void linmin(double p[], double xi[], int n, double *fret, 
1.126     brouard  2237:              double (*func)(double [])); 
1.224     brouard  2238: #else 
1.241     brouard  2239:  void linmin(double p[], double xi[], int n, double *fret,
                   2240:             double (*func)(double []),int *flat); 
1.224     brouard  2241: #endif
1.239     brouard  2242:  int i,ibig,j,jk,k; 
1.126     brouard  2243:   double del,t,*pt,*ptt,*xit;
1.181     brouard  2244:   double directest;
1.126     brouard  2245:   double fp,fptt;
                   2246:   double *xits;
                   2247:   int niterf, itmp;
1.224     brouard  2248: #ifdef LINMINORIGINAL
                   2249: #else
                   2250: 
                   2251:   flatdir=ivector(1,n); 
                   2252:   for (j=1;j<=n;j++) flatdir[j]=0; 
                   2253: #endif
1.126     brouard  2254: 
                   2255:   pt=vector(1,n); 
                   2256:   ptt=vector(1,n); 
                   2257:   xit=vector(1,n); 
                   2258:   xits=vector(1,n); 
                   2259:   *fret=(*func)(p); 
                   2260:   for (j=1;j<=n;j++) pt[j]=p[j]; 
1.202     brouard  2261:   rcurr_time = time(NULL);  
1.126     brouard  2262:   for (*iter=1;;++(*iter)) { 
1.187     brouard  2263:     fp=(*fret); /* From former iteration or initial value */
1.126     brouard  2264:     ibig=0; 
                   2265:     del=0.0; 
1.157     brouard  2266:     rlast_time=rcurr_time;
                   2267:     /* (void) gettimeofday(&curr_time,&tzp); */
                   2268:     rcurr_time = time(NULL);  
                   2269:     curr_time = *localtime(&rcurr_time);
                   2270:     printf("\nPowell iter=%d -2*LL=%.12f %ld sec. %ld sec.",*iter,*fret, rcurr_time-rlast_time, rcurr_time-rstart_time);fflush(stdout);
                   2271:     fprintf(ficlog,"\nPowell iter=%d -2*LL=%.12f %ld sec. %ld sec.",*iter,*fret,rcurr_time-rlast_time, rcurr_time-rstart_time); fflush(ficlog);
                   2272: /*     fprintf(ficrespow,"%d %.12f %ld",*iter,*fret,curr_time.tm_sec-start_time.tm_sec); */
1.192     brouard  2273:     for (i=1;i<=n;i++) {
1.126     brouard  2274:       fprintf(ficrespow," %.12lf", p[i]);
                   2275:     }
1.239     brouard  2276:     fprintf(ficrespow,"\n");fflush(ficrespow);
                   2277:     printf("\n#model=  1      +     age ");
                   2278:     fprintf(ficlog,"\n#model=  1      +     age ");
                   2279:     if(nagesqr==1){
1.241     brouard  2280:        printf("  + age*age  ");
                   2281:        fprintf(ficlog,"  + age*age  ");
1.239     brouard  2282:     }
                   2283:     for(j=1;j <=ncovmodel-2;j++){
                   2284:       if(Typevar[j]==0) {
                   2285:        printf("  +      V%d  ",Tvar[j]);
                   2286:        fprintf(ficlog,"  +      V%d  ",Tvar[j]);
                   2287:       }else if(Typevar[j]==1) {
                   2288:        printf("  +    V%d*age ",Tvar[j]);
                   2289:        fprintf(ficlog,"  +    V%d*age ",Tvar[j]);
                   2290:       }else if(Typevar[j]==2) {
                   2291:        printf("  +    V%d*V%d ",Tvard[Tposprod[j]][1],Tvard[Tposprod[j]][2]);
                   2292:        fprintf(ficlog,"  +    V%d*V%d ",Tvard[Tposprod[j]][1],Tvard[Tposprod[j]][2]);
                   2293:       }
                   2294:     }
1.126     brouard  2295:     printf("\n");
1.239     brouard  2296: /*     printf("12   47.0114589    0.0154322   33.2424412    0.3279905    2.3731903  */
                   2297: /* 13  -21.5392400    0.1118147    1.2680506    1.2973408   -1.0663662  */
1.126     brouard  2298:     fprintf(ficlog,"\n");
1.239     brouard  2299:     for(i=1,jk=1; i <=nlstate; i++){
                   2300:       for(k=1; k <=(nlstate+ndeath); k++){
                   2301:        if (k != i) {
                   2302:          printf("%d%d ",i,k);
                   2303:          fprintf(ficlog,"%d%d ",i,k);
                   2304:          for(j=1; j <=ncovmodel; j++){
                   2305:            printf("%12.7f ",p[jk]);
                   2306:            fprintf(ficlog,"%12.7f ",p[jk]);
                   2307:            jk++; 
                   2308:          }
                   2309:          printf("\n");
                   2310:          fprintf(ficlog,"\n");
                   2311:        }
                   2312:       }
                   2313:     }
1.241     brouard  2314:     if(*iter <=3 && *iter >1){
1.157     brouard  2315:       tml = *localtime(&rcurr_time);
                   2316:       strcpy(strcurr,asctime(&tml));
                   2317:       rforecast_time=rcurr_time; 
1.126     brouard  2318:       itmp = strlen(strcurr);
                   2319:       if(strcurr[itmp-1]=='\n')  /* Windows outputs with a new line */
1.241     brouard  2320:        strcurr[itmp-1]='\0';
1.162     brouard  2321:       printf("\nConsidering the time needed for the last iteration #%d: %ld seconds,\n",*iter,rcurr_time-rlast_time);
1.157     brouard  2322:       fprintf(ficlog,"\nConsidering the time needed for this last iteration #%d: %ld seconds,\n",*iter,rcurr_time-rlast_time);
1.126     brouard  2323:       for(niterf=10;niterf<=30;niterf+=10){
1.241     brouard  2324:        rforecast_time=rcurr_time+(niterf-*iter)*(rcurr_time-rlast_time);
                   2325:        forecast_time = *localtime(&rforecast_time);
                   2326:        strcpy(strfor,asctime(&forecast_time));
                   2327:        itmp = strlen(strfor);
                   2328:        if(strfor[itmp-1]=='\n')
                   2329:          strfor[itmp-1]='\0';
                   2330:        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);
                   2331:        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  2332:       }
                   2333:     }
1.187     brouard  2334:     for (i=1;i<=n;i++) { /* For each direction i */
                   2335:       for (j=1;j<=n;j++) xit[j]=xi[j][i]; /* Directions stored from previous iteration with previous scales */
1.126     brouard  2336:       fptt=(*fret); 
                   2337: #ifdef DEBUG
1.203     brouard  2338:       printf("fret=%lf, %lf, %lf \n", *fret, *fret, *fret);
                   2339:       fprintf(ficlog, "fret=%lf, %lf, %lf \n", *fret, *fret, *fret);
1.126     brouard  2340: #endif
1.203     brouard  2341:       printf("%d",i);fflush(stdout); /* print direction (parameter) i */
1.126     brouard  2342:       fprintf(ficlog,"%d",i);fflush(ficlog);
1.224     brouard  2343: #ifdef LINMINORIGINAL
1.188     brouard  2344:       linmin(p,xit,n,fret,func); /* Point p[n]. xit[n] has been loaded for direction i as input.*/
1.224     brouard  2345: #else
                   2346:       linmin(p,xit,n,fret,func,&flat); /* Point p[n]. xit[n] has been loaded for direction i as input.*/
                   2347:                        flatdir[i]=flat; /* Function is vanishing in that direction i */
                   2348: #endif
                   2349:                        /* Outputs are fret(new point p) p is updated and xit rescaled */
1.188     brouard  2350:       if (fabs(fptt-(*fret)) > del) { /* We are keeping the max gain on each of the n directions */
1.224     brouard  2351:                                /* because that direction will be replaced unless the gain del is small */
                   2352:                                /* in comparison with the 'probable' gain, mu^2, with the last average direction. */
                   2353:                                /* Unless the n directions are conjugate some gain in the determinant may be obtained */
                   2354:                                /* with the new direction. */
                   2355:                                del=fabs(fptt-(*fret)); 
                   2356:                                ibig=i; 
1.126     brouard  2357:       } 
                   2358: #ifdef DEBUG
                   2359:       printf("%d %.12e",i,(*fret));
                   2360:       fprintf(ficlog,"%d %.12e",i,(*fret));
                   2361:       for (j=1;j<=n;j++) {
1.224     brouard  2362:                                xits[j]=FMAX(fabs(p[j]-pt[j]),1.e-5);
                   2363:                                printf(" x(%d)=%.12e",j,xit[j]);
                   2364:                                fprintf(ficlog," x(%d)=%.12e",j,xit[j]);
1.126     brouard  2365:       }
                   2366:       for(j=1;j<=n;j++) {
1.225     brouard  2367:                                printf(" p(%d)=%.12e",j,p[j]);
                   2368:                                fprintf(ficlog," p(%d)=%.12e",j,p[j]);
1.126     brouard  2369:       }
                   2370:       printf("\n");
                   2371:       fprintf(ficlog,"\n");
                   2372: #endif
1.187     brouard  2373:     } /* end loop on each direction i */
                   2374:     /* Convergence test will use last linmin estimation (fret) and compare former iteration (fp) */ 
1.188     brouard  2375:     /* But p and xit have been updated at the end of linmin, *fret corresponds to new p, xit  */
1.187     brouard  2376:     /* New value of last point Pn is not computed, P(n-1) */
1.224     brouard  2377:       for(j=1;j<=n;j++) {
1.225     brouard  2378:                                if(flatdir[j] >0){
                   2379:                                        printf(" p(%d)=%lf flat=%d ",j,p[j],flatdir[j]);
                   2380:                                        fprintf(ficlog," p(%d)=%lf flat=%d ",j,p[j],flatdir[j]);
                   2381:                                }
                   2382:                                /* printf("\n"); */
                   2383:                                /* fprintf(ficlog,"\n"); */
                   2384:                        }
1.243     brouard  2385:     /* if (2.0*fabs(fp-(*fret)) <= ftol*(fabs(fp)+fabs(*fret))) { /\* Did we reach enough precision? *\/ */
                   2386:     if (2.0*fabs(fp-(*fret)) <= ftol) { /* Did we reach enough precision? */
1.188     brouard  2387:       /* We could compare with a chi^2. chisquare(0.95,ddl=1)=3.84 */
                   2388:       /* By adding age*age in a model, the new -2LL should be lower and the difference follows a */
                   2389:       /* a chisquare statistics with 1 degree. To be significant at the 95% level, it should have */
                   2390:       /* decreased of more than 3.84  */
                   2391:       /* By adding age*age and V1*age the gain (-2LL) should be more than 5.99 (ddl=2) */
                   2392:       /* By using V1+V2+V3, the gain should be  7.82, compared with basic 1+age. */
                   2393:       /* By adding 10 parameters more the gain should be 18.31 */
1.224     brouard  2394:                        
1.188     brouard  2395:       /* Starting the program with initial values given by a former maximization will simply change */
                   2396:       /* the scales of the directions and the directions, because the are reset to canonical directions */
                   2397:       /* Thus the first calls to linmin will give new points and better maximizations until fp-(*fret) is */
                   2398:       /* under the tolerance value. If the tolerance is very small 1.e-9, it could last long.  */
1.126     brouard  2399: #ifdef DEBUG
                   2400:       int k[2],l;
                   2401:       k[0]=1;
                   2402:       k[1]=-1;
                   2403:       printf("Max: %.12e",(*func)(p));
                   2404:       fprintf(ficlog,"Max: %.12e",(*func)(p));
                   2405:       for (j=1;j<=n;j++) {
                   2406:        printf(" %.12e",p[j]);
                   2407:        fprintf(ficlog," %.12e",p[j]);
                   2408:       }
                   2409:       printf("\n");
                   2410:       fprintf(ficlog,"\n");
                   2411:       for(l=0;l<=1;l++) {
                   2412:        for (j=1;j<=n;j++) {
                   2413:          ptt[j]=p[j]+(p[j]-pt[j])*k[l];
                   2414:          printf("l=%d j=%d ptt=%.12e, xits=%.12e, p=%.12e, xit=%.12e", l,j,ptt[j],xits[j],p[j],xit[j]);
                   2415:          fprintf(ficlog,"l=%d j=%d ptt=%.12e, xits=%.12e, p=%.12e, xit=%.12e", l,j,ptt[j],xits[j],p[j],xit[j]);
                   2416:        }
                   2417:        printf("func(ptt)=%.12e, deriv=%.12e\n",(*func)(ptt),(ptt[j]-p[j])/((*func)(ptt)-(*func)(p)));
                   2418:        fprintf(ficlog,"func(ptt)=%.12e, deriv=%.12e\n",(*func)(ptt),(ptt[j]-p[j])/((*func)(ptt)-(*func)(p)));
                   2419:       }
                   2420: #endif
                   2421: 
1.224     brouard  2422: #ifdef LINMINORIGINAL
                   2423: #else
                   2424:       free_ivector(flatdir,1,n); 
                   2425: #endif
1.126     brouard  2426:       free_vector(xit,1,n); 
                   2427:       free_vector(xits,1,n); 
                   2428:       free_vector(ptt,1,n); 
                   2429:       free_vector(pt,1,n); 
                   2430:       return; 
1.192     brouard  2431:     } /* enough precision */ 
1.240     brouard  2432:     if (*iter == ITMAX*n) nrerror("powell exceeding maximum iterations."); 
1.181     brouard  2433:     for (j=1;j<=n;j++) { /* Computes the extrapolated point P_0 + 2 (P_n-P_0) */
1.126     brouard  2434:       ptt[j]=2.0*p[j]-pt[j]; 
                   2435:       xit[j]=p[j]-pt[j]; 
                   2436:       pt[j]=p[j]; 
                   2437:     } 
1.181     brouard  2438:     fptt=(*func)(ptt); /* f_3 */
1.224     brouard  2439: #ifdef NODIRECTIONCHANGEDUNTILNITER  /* No change in drections until some iterations are done */
                   2440:                if (*iter <=4) {
1.225     brouard  2441: #else
                   2442: #endif
1.224     brouard  2443: #ifdef POWELLNOF3INFF1TEST    /* skips test F3 <F1 */
1.192     brouard  2444: #else
1.161     brouard  2445:     if (fptt < fp) { /* If extrapolated point is better, decide if we keep that new direction or not */
1.192     brouard  2446: #endif
1.162     brouard  2447:       /* (x1 f1=fp), (x2 f2=*fret), (x3 f3=fptt), (xm fm) */
1.161     brouard  2448:       /* From x1 (P0) distance of x2 is at h and x3 is 2h */
1.162     brouard  2449:       /* Let f"(x2) be the 2nd derivative equal everywhere.  */
                   2450:       /* Then the parabolic through (x1,f1), (x2,f2) and (x3,f3) */
                   2451:       /* will reach at f3 = fm + h^2/2 f"m  ; f" = (f1 -2f2 +f3 ) / h**2 */
1.224     brouard  2452:       /* Conditional for using this new direction is that mu^2 = (f1-2f2+f3)^2 /2 < del or directest <0 */
                   2453:       /* also  lamda^2=(f1-f2)^2/mu² is a parasite solution of powell */
                   2454:       /* For powell, inclusion of this average direction is only if t(del)<0 or del inbetween mu^2 and lambda^2 */
1.161     brouard  2455:       /* t=2.0*(fp-2.0*(*fret)+fptt)*SQR(fp-(*fret)-del)-del*SQR(fp-fptt); */
1.224     brouard  2456:       /*  Even if f3 <f1, directest can be negative and t >0 */
                   2457:       /* mu² and del² are equal when f3=f1 */
                   2458:                        /* f3 < f1 : mu² < del <= lambda^2 both test are equivalent */
                   2459:                        /* f3 < f1 : mu² < lambda^2 < del then directtest is negative and powell t is positive */
                   2460:                        /* f3 > f1 : lambda² < mu^2 < del then t is negative and directest >0  */
                   2461:                        /* f3 > f1 : lambda² < del < mu^2 then t is positive and directest >0  */
1.183     brouard  2462: #ifdef NRCORIGINAL
                   2463:       t=2.0*(fp-2.0*(*fret)+fptt)*SQR(fp-(*fret)-del)- del*SQR(fp-fptt); /* Original Numerical Recipes in C*/
                   2464: #else
                   2465:       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  2466:       t= t- del*SQR(fp-fptt);
1.183     brouard  2467: #endif
1.202     brouard  2468:       directest = fp-2.0*(*fret)+fptt - 2.0 * del; /* If delta was big enough we change it for a new direction */
1.161     brouard  2469: #ifdef DEBUG
1.181     brouard  2470:       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);
                   2471:       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  2472:       printf("t3= %.12lf, t4= %.12lf, t3*= %.12lf, t4*= %.12lf\n",SQR(fp-(*fret)-del),SQR(fp-fptt),
                   2473:             (fp-(*fret)-del)*(fp-(*fret)-del),(fp-fptt)*(fp-fptt));
                   2474:       fprintf(ficlog,"t3= %.12lf, t4= %.12lf, t3*= %.12lf, t4*= %.12lf\n",SQR(fp-(*fret)-del),SQR(fp-fptt),
                   2475:             (fp-(*fret)-del)*(fp-(*fret)-del),(fp-fptt)*(fp-fptt));
                   2476:       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);
                   2477:       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);
                   2478: #endif
1.183     brouard  2479: #ifdef POWELLORIGINAL
                   2480:       if (t < 0.0) { /* Then we use it for new direction */
                   2481: #else
1.182     brouard  2482:       if (directest*t < 0.0) { /* Contradiction between both tests */
1.224     brouard  2483:                                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  2484:         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  2485:         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  2486:         fprintf(ficlog,"f1-2f2+f3= %.12lf, f1-f2-del= %.12lf, f1-f3= %.12lf\n",fp-2.0*(*fret)+fptt, fp -(*fret) -del, fp-fptt);
                   2487:       } 
1.181     brouard  2488:       if (directest < 0.0) { /* Then we use it for new direction */
                   2489: #endif
1.191     brouard  2490: #ifdef DEBUGLINMIN
1.234     brouard  2491:        printf("Before linmin in direction P%d-P0\n",n);
                   2492:        for (j=1;j<=n;j++) {
                   2493:          printf(" Before xit[%d]= %12.7f p[%d]= %12.7f",j,xit[j],j,p[j]);
                   2494:          fprintf(ficlog," Before xit[%d]= %12.7f p[%d]= %12.7f",j,xit[j],j,p[j]);
                   2495:          if(j % ncovmodel == 0){
                   2496:            printf("\n");
                   2497:            fprintf(ficlog,"\n");
                   2498:          }
                   2499:        }
1.224     brouard  2500: #endif
                   2501: #ifdef LINMINORIGINAL
1.234     brouard  2502:        linmin(p,xit,n,fret,func); /* computes minimum on the extrapolated direction: changes p and rescales xit.*/
1.224     brouard  2503: #else
1.234     brouard  2504:        linmin(p,xit,n,fret,func,&flat); /* computes minimum on the extrapolated direction: changes p and rescales xit.*/
                   2505:        flatdir[i]=flat; /* Function is vanishing in that direction i */
1.191     brouard  2506: #endif
1.234     brouard  2507:        
1.191     brouard  2508: #ifdef DEBUGLINMIN
1.234     brouard  2509:        for (j=1;j<=n;j++) { 
                   2510:          printf("After xit[%d]= %12.7f p[%d]= %12.7f",j,xit[j],j,p[j]);
                   2511:          fprintf(ficlog,"After xit[%d]= %12.7f p[%d]= %12.7f",j,xit[j],j,p[j]);
                   2512:          if(j % ncovmodel == 0){
                   2513:            printf("\n");
                   2514:            fprintf(ficlog,"\n");
                   2515:          }
                   2516:        }
1.224     brouard  2517: #endif
1.234     brouard  2518:        for (j=1;j<=n;j++) { 
                   2519:          xi[j][ibig]=xi[j][n]; /* Replace direction with biggest decrease by last direction n */
                   2520:          xi[j][n]=xit[j];      /* and this nth direction by the by the average p_0 p_n */
                   2521:        }
1.224     brouard  2522: #ifdef LINMINORIGINAL
                   2523: #else
1.234     brouard  2524:        for (j=1, flatd=0;j<=n;j++) {
                   2525:          if(flatdir[j]>0)
                   2526:            flatd++;
                   2527:        }
                   2528:        if(flatd >0){
1.255     brouard  2529:          printf("%d flat directions: ",flatd);
                   2530:          fprintf(ficlog,"%d flat directions :",flatd);
1.234     brouard  2531:          for (j=1;j<=n;j++) { 
                   2532:            if(flatdir[j]>0){
                   2533:              printf("%d ",j);
                   2534:              fprintf(ficlog,"%d ",j);
                   2535:            }
                   2536:          }
                   2537:          printf("\n");
                   2538:          fprintf(ficlog,"\n");
                   2539:        }
1.191     brouard  2540: #endif
1.234     brouard  2541:        printf("Gaining to use new average direction of P0 P%d instead of biggest increase direction %d :\n",n,ibig);
                   2542:        fprintf(ficlog,"Gaining to use new average direction of P0 P%d instead of biggest increase direction %d :\n",n,ibig);
                   2543:        
1.126     brouard  2544: #ifdef DEBUG
1.234     brouard  2545:        printf("Direction changed  last moved %d in place of ibig=%d, new last is the average:\n",n,ibig);
                   2546:        fprintf(ficlog,"Direction changed  last moved %d in place of ibig=%d, new last is the average:\n",n,ibig);
                   2547:        for(j=1;j<=n;j++){
                   2548:          printf(" %lf",xit[j]);
                   2549:          fprintf(ficlog," %lf",xit[j]);
                   2550:        }
                   2551:        printf("\n");
                   2552:        fprintf(ficlog,"\n");
1.126     brouard  2553: #endif
1.192     brouard  2554:       } /* end of t or directest negative */
1.224     brouard  2555: #ifdef POWELLNOF3INFF1TEST
1.192     brouard  2556: #else
1.234     brouard  2557:       } /* end if (fptt < fp)  */
1.192     brouard  2558: #endif
1.225     brouard  2559: #ifdef NODIRECTIONCHANGEDUNTILNITER  /* No change in drections until some iterations are done */
1.234     brouard  2560:     } /*NODIRECTIONCHANGEDUNTILNITER  No change in drections until some iterations are done */
1.225     brouard  2561: #else
1.224     brouard  2562: #endif
1.234     brouard  2563:                } /* loop iteration */ 
1.126     brouard  2564: } 
1.234     brouard  2565:   
1.126     brouard  2566: /**** Prevalence limit (stable or period prevalence)  ****************/
1.234     brouard  2567:   
1.235     brouard  2568:   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  2569:   {
1.279     brouard  2570:     /**< Computes the prevalence limit in each live state at age x and for covariate combination ij 
                   2571:      *   (and selected quantitative values in nres)
                   2572:      *  by left multiplying the unit
                   2573:      *  matrix by transitions matrix until convergence is reached with precision ftolpl 
                   2574:      * Wx= Wx-1 Px-1= Wx-2 Px-2 Px-1  = Wx-n Px-n ... Px-2 Px-1 I
                   2575:      * Wx is row vector: population in state 1, population in state 2, population dead
                   2576:      * or prevalence in state 1, prevalence in state 2, 0
                   2577:      * newm is the matrix after multiplications, its rows are identical at a factor.
                   2578:      * Inputs are the parameter, age, a tolerance for the prevalence limit ftolpl.
                   2579:      * Output is prlim.
                   2580:      * Initial matrix pimij 
                   2581:      */
1.206     brouard  2582:   /* {0.85204250825084937, 0.13044499163996345, 0.017512500109187184, */
                   2583:   /* 0.090851990222114765, 0.88271245433047185, 0.026435555447413338, */
                   2584:   /*  0,                   0                  , 1} */
                   2585:   /*
                   2586:    * and after some iteration: */
                   2587:   /* {0.45504275246439968, 0.42731458730878791, 0.11764266022681241, */
                   2588:   /*  0.45201005341706885, 0.42865420071559901, 0.11933574586733192, */
                   2589:   /*  0,                   0                  , 1} */
                   2590:   /* And prevalence by suppressing the deaths are close to identical rows in prlim: */
                   2591:   /* {0.51571254859325999, 0.4842874514067399, */
                   2592:   /*  0.51326036147820708, 0.48673963852179264} */
                   2593:   /* If we start from prlim again, prlim tends to a constant matrix */
1.234     brouard  2594:     
1.126     brouard  2595:   int i, ii,j,k;
1.209     brouard  2596:   double *min, *max, *meandiff, maxmax,sumnew=0.;
1.145     brouard  2597:   /* double **matprod2(); */ /* test */
1.218     brouard  2598:   double **out, cov[NCOVMAX+1], **pmij(); /* **pmmij is a global variable feeded with oldms etc */
1.126     brouard  2599:   double **newm;
1.209     brouard  2600:   double agefin, delaymax=200. ; /* 100 Max number of years to converge */
1.203     brouard  2601:   int ncvloop=0;
1.288     brouard  2602:   int first=0;
1.169     brouard  2603:   
1.209     brouard  2604:   min=vector(1,nlstate);
                   2605:   max=vector(1,nlstate);
                   2606:   meandiff=vector(1,nlstate);
                   2607: 
1.218     brouard  2608:        /* Starting with matrix unity */
1.126     brouard  2609:   for (ii=1;ii<=nlstate+ndeath;ii++)
                   2610:     for (j=1;j<=nlstate+ndeath;j++){
                   2611:       oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   2612:     }
1.169     brouard  2613:   
                   2614:   cov[1]=1.;
                   2615:   
                   2616:   /* Even if hstepm = 1, at least one multiplication by the unit matrix */
1.202     brouard  2617:   /* Start at agefin= age, computes the matrix of passage and loops decreasing agefin until convergence is reached */
1.126     brouard  2618:   for(agefin=age-stepm/YEARM; agefin>=age-delaymax; agefin=agefin-stepm/YEARM){
1.202     brouard  2619:     ncvloop++;
1.126     brouard  2620:     newm=savm;
                   2621:     /* Covariates have to be included here again */
1.138     brouard  2622:     cov[2]=agefin;
1.187     brouard  2623:     if(nagesqr==1)
                   2624:       cov[3]= agefin*agefin;;
1.234     brouard  2625:     for (k=1; k<=nsd;k++) { /* For single dummy covariates only */
                   2626:                        /* Here comes the value of the covariate 'ij' after renumbering k with single dummy covariates */
                   2627:       cov[2+nagesqr+TvarsDind[k]]=nbcode[TvarsD[k]][codtabm(ij,k)];
1.235     brouard  2628:       /* 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  2629:     }
                   2630:     for (k=1; k<=nsq;k++) { /* For single varying covariates only */
                   2631:                        /* Here comes the value of quantitative after renumbering k with single quantitative covariates */
1.235     brouard  2632:       cov[2+nagesqr+TvarsQind[k]]=Tqresult[nres][k]; 
                   2633:       /* 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  2634:     }
1.237     brouard  2635:     for (k=1; k<=cptcovage;k++){  /* For product with age */
1.234     brouard  2636:       if(Dummy[Tvar[Tage[k]]]){
                   2637:        cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,k)]*cov[2];
                   2638:       } else{
1.235     brouard  2639:        cov[2+nagesqr+Tage[k]]=Tqresult[nres][k]; 
1.234     brouard  2640:       }
1.235     brouard  2641:       /* 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  2642:     }
1.237     brouard  2643:     for (k=1; k<=cptcovprod;k++){ /* For product without age */
1.235     brouard  2644:       /* 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  2645:       if(Dummy[Tvard[k][1]==0]){
                   2646:        if(Dummy[Tvard[k][2]==0]){
                   2647:          cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)] * nbcode[Tvard[k][2]][codtabm(ij,k)];
                   2648:        }else{
                   2649:          cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)] * Tqresult[nres][k];
                   2650:        }
                   2651:       }else{
                   2652:        if(Dummy[Tvard[k][2]==0]){
                   2653:          cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][2]][codtabm(ij,k)] * Tqinvresult[nres][Tvard[k][1]];
                   2654:        }else{
                   2655:          cov[2+nagesqr+Tprod[k]]=Tqinvresult[nres][Tvard[k][1]]*  Tqinvresult[nres][Tvard[k][2]];
                   2656:        }
                   2657:       }
1.234     brouard  2658:     }
1.138     brouard  2659:     /*printf("ij=%d cptcovprod=%d tvar=%d ", ij, cptcovprod, Tvar[1]);*/
                   2660:     /*printf("ij=%d cov[3]=%lf cov[4]=%lf \n",ij, cov[3],cov[4]);*/
                   2661:     /*printf("ij=%d cov[3]=%lf \n",ij, cov[3]);*/
1.145     brouard  2662:     /* savm=pmij(pmmij,cov,ncovmodel,x,nlstate); */
                   2663:     /* out=matprod2(newm, pmij(pmmij,cov,ncovmodel,x,nlstate),1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm); /\* Bug Valgrind *\/ */
1.218     brouard  2664:                /* age and covariate values of ij are in 'cov' */
1.142     brouard  2665:     out=matprod2(newm, pmij(pmmij,cov,ncovmodel,x,nlstate),1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm); /* Bug Valgrind */
1.138     brouard  2666:     
1.126     brouard  2667:     savm=oldm;
                   2668:     oldm=newm;
1.209     brouard  2669: 
                   2670:     for(j=1; j<=nlstate; j++){
                   2671:       max[j]=0.;
                   2672:       min[j]=1.;
                   2673:     }
                   2674:     for(i=1;i<=nlstate;i++){
                   2675:       sumnew=0;
                   2676:       for(k=1; k<=ndeath; k++) sumnew+=newm[i][nlstate+k];
                   2677:       for(j=1; j<=nlstate; j++){ 
                   2678:        prlim[i][j]= newm[i][j]/(1-sumnew);
                   2679:        max[j]=FMAX(max[j],prlim[i][j]);
                   2680:        min[j]=FMIN(min[j],prlim[i][j]);
                   2681:       }
                   2682:     }
                   2683: 
1.126     brouard  2684:     maxmax=0.;
1.209     brouard  2685:     for(j=1; j<=nlstate; j++){
                   2686:       meandiff[j]=(max[j]-min[j])/(max[j]+min[j])*2.; /* mean difference for each column */
                   2687:       maxmax=FMAX(maxmax,meandiff[j]);
                   2688:       /* 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  2689:     } /* j loop */
1.203     brouard  2690:     *ncvyear= (int)age- (int)agefin;
1.208     brouard  2691:     /* 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  2692:     if(maxmax < ftolpl){
1.209     brouard  2693:       /* printf("maxmax=%lf ncvloop=%ld, age=%d, agefin=%d ncvyear=%d \n", maxmax, ncvloop, (int)age, (int)agefin, *ncvyear); */
                   2694:       free_vector(min,1,nlstate);
                   2695:       free_vector(max,1,nlstate);
                   2696:       free_vector(meandiff,1,nlstate);
1.126     brouard  2697:       return prlim;
                   2698:     }
1.288     brouard  2699:   } /* agefin loop */
1.208     brouard  2700:     /* After some age loop it doesn't converge */
1.288     brouard  2701:   if(!first){
                   2702:     first=1;
                   2703:     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);
                   2704:   }
                   2705:   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);
                   2706: 
1.209     brouard  2707:   /* 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); */
                   2708:   free_vector(min,1,nlstate);
                   2709:   free_vector(max,1,nlstate);
                   2710:   free_vector(meandiff,1,nlstate);
1.208     brouard  2711:   
1.169     brouard  2712:   return prlim; /* should not reach here */
1.126     brouard  2713: }
                   2714: 
1.217     brouard  2715: 
                   2716:  /**** Back Prevalence limit (stable or period prevalence)  ****************/
                   2717: 
1.218     brouard  2718:  /* 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) */
                   2719:  /* 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  2720:   double **bprevalim(double **bprlim, double ***prevacurrent, int nlstate, double x[], double age, double ftolpl, int *ncvyear, int ij, int nres)
1.217     brouard  2721: {
1.264     brouard  2722:   /* 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  2723:      matrix by transitions matrix until convergence is reached with precision ftolpl */
                   2724:   /* Wx= Wx-1 Px-1= Wx-2 Px-2 Px-1  = Wx-n Px-n ... Px-2 Px-1 I */
                   2725:   /* Wx is row vector: population in state 1, population in state 2, population dead */
                   2726:   /* or prevalence in state 1, prevalence in state 2, 0 */
                   2727:   /* newm is the matrix after multiplications, its rows are identical at a factor */
                   2728:   /* Initial matrix pimij */
                   2729:   /* {0.85204250825084937, 0.13044499163996345, 0.017512500109187184, */
                   2730:   /* 0.090851990222114765, 0.88271245433047185, 0.026435555447413338, */
                   2731:   /*  0,                   0                  , 1} */
                   2732:   /*
                   2733:    * and after some iteration: */
                   2734:   /* {0.45504275246439968, 0.42731458730878791, 0.11764266022681241, */
                   2735:   /*  0.45201005341706885, 0.42865420071559901, 0.11933574586733192, */
                   2736:   /*  0,                   0                  , 1} */
                   2737:   /* And prevalence by suppressing the deaths are close to identical rows in prlim: */
                   2738:   /* {0.51571254859325999, 0.4842874514067399, */
                   2739:   /*  0.51326036147820708, 0.48673963852179264} */
                   2740:   /* If we start from prlim again, prlim tends to a constant matrix */
                   2741: 
                   2742:   int i, ii,j,k;
1.247     brouard  2743:   int first=0;
1.217     brouard  2744:   double *min, *max, *meandiff, maxmax,sumnew=0.;
                   2745:   /* double **matprod2(); */ /* test */
                   2746:   double **out, cov[NCOVMAX+1], **bmij();
                   2747:   double **newm;
1.218     brouard  2748:   double        **dnewm, **doldm, **dsavm;  /* for use */
                   2749:   double        **oldm, **savm;  /* for use */
                   2750: 
1.217     brouard  2751:   double agefin, delaymax=200. ; /* 100 Max number of years to converge */
                   2752:   int ncvloop=0;
                   2753:   
                   2754:   min=vector(1,nlstate);
                   2755:   max=vector(1,nlstate);
                   2756:   meandiff=vector(1,nlstate);
                   2757: 
1.266     brouard  2758:   dnewm=ddnewms; doldm=ddoldms; dsavm=ddsavms;
                   2759:   oldm=oldms; savm=savms;
                   2760:   
                   2761:   /* Starting with matrix unity */
                   2762:   for (ii=1;ii<=nlstate+ndeath;ii++)
                   2763:     for (j=1;j<=nlstate+ndeath;j++){
1.217     brouard  2764:       oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   2765:     }
                   2766:   
                   2767:   cov[1]=1.;
                   2768:   
                   2769:   /* Even if hstepm = 1, at least one multiplication by the unit matrix */
                   2770:   /* Start at agefin= age, computes the matrix of passage and loops decreasing agefin until convergence is reached */
1.218     brouard  2771:   /* for(agefin=age+stepm/YEARM; agefin<=age+delaymax; agefin=agefin+stepm/YEARM){ /\* A changer en age *\/ */
1.288     brouard  2772:   /* for(agefin=age; agefin<AGESUP; agefin=agefin+stepm/YEARM){ /\* A changer en age *\/ */
                   2773:   for(agefin=age; agefin<FMIN(AGESUP,age+delaymax); agefin=agefin+stepm/YEARM){ /* A changer en age */
1.217     brouard  2774:     ncvloop++;
1.218     brouard  2775:     newm=savm; /* oldm should be kept from previous iteration or unity at start */
                   2776:                /* newm points to the allocated table savm passed by the function it can be written, savm could be reallocated */
1.217     brouard  2777:     /* Covariates have to be included here again */
                   2778:     cov[2]=agefin;
                   2779:     if(nagesqr==1)
                   2780:       cov[3]= agefin*agefin;;
1.242     brouard  2781:     for (k=1; k<=nsd;k++) { /* For single dummy covariates only */
                   2782:                        /* Here comes the value of the covariate 'ij' after renumbering k with single dummy covariates */
                   2783:       cov[2+nagesqr+TvarsDind[k]]=nbcode[TvarsD[k]][codtabm(ij,k)];
1.264     brouard  2784:       /* 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  2785:     }
                   2786:     /* for (k=1; k<=cptcovn;k++) { */
                   2787:     /*   /\* cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,Tvar[k])]; *\/ */
                   2788:     /*   cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,k)]; */
                   2789:     /*   /\* 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])]); *\/ */
                   2790:     /* } */
                   2791:     for (k=1; k<=nsq;k++) { /* For single varying covariates only */
                   2792:                        /* Here comes the value of quantitative after renumbering k with single quantitative covariates */
                   2793:       cov[2+nagesqr+TvarsQind[k]]=Tqresult[nres][k]; 
                   2794:       /* 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]); */
                   2795:     }
                   2796:     /* for (k=1; k<=cptcovage;k++) cov[2+nagesqr+Tage[k]]=nbcode[Tvar[k]][codtabm(ij,k)]*cov[2]; */
                   2797:     /* for (k=1; k<=cptcovprod;k++) /\* Useless *\/ */
                   2798:     /*   /\* cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,Tvard[k][1])] * nbcode[Tvard[k][2]][codtabm(ij,Tvard[k][2])]; *\/ */
                   2799:     /*   cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)] * nbcode[Tvard[k][2]][codtabm(ij,k)]; */
                   2800:     for (k=1; k<=cptcovage;k++){  /* For product with age */
                   2801:       if(Dummy[Tvar[Tage[k]]]){
                   2802:        cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,k)]*cov[2];
                   2803:       } else{
                   2804:        cov[2+nagesqr+Tage[k]]=Tqresult[nres][k]; 
                   2805:       }
                   2806:       /* 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]); */
                   2807:     }
                   2808:     for (k=1; k<=cptcovprod;k++){ /* For product without age */
                   2809:       /* 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]); */
                   2810:       if(Dummy[Tvard[k][1]==0]){
                   2811:        if(Dummy[Tvard[k][2]==0]){
                   2812:          cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)] * nbcode[Tvard[k][2]][codtabm(ij,k)];
                   2813:        }else{
                   2814:          cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)] * Tqresult[nres][k];
                   2815:        }
                   2816:       }else{
                   2817:        if(Dummy[Tvard[k][2]==0]){
                   2818:          cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][2]][codtabm(ij,k)] * Tqinvresult[nres][Tvard[k][1]];
                   2819:        }else{
                   2820:          cov[2+nagesqr+Tprod[k]]=Tqinvresult[nres][Tvard[k][1]]*  Tqinvresult[nres][Tvard[k][2]];
                   2821:        }
                   2822:       }
1.217     brouard  2823:     }
                   2824:     
                   2825:     /*printf("ij=%d cptcovprod=%d tvar=%d ", ij, cptcovprod, Tvar[1]);*/
                   2826:     /*printf("ij=%d cov[3]=%lf cov[4]=%lf \n",ij, cov[3],cov[4]);*/
                   2827:     /*printf("ij=%d cov[3]=%lf \n",ij, cov[3]);*/
                   2828:     /* savm=pmij(pmmij,cov,ncovmodel,x,nlstate); */
                   2829:     /* out=matprod2(newm, pmij(pmmij,cov,ncovmodel,x,nlstate),1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm); /\* Bug Valgrind *\/ */
1.218     brouard  2830:                /* ij should be linked to the correct index of cov */
                   2831:                /* age and covariate values ij are in 'cov', but we need to pass
                   2832:                 * ij for the observed prevalence at age and status and covariate
                   2833:                 * number:  prevacurrent[(int)agefin][ii][ij]
                   2834:                 */
                   2835:     /* 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 *\/ */
                   2836:     /* 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 *\/ */
                   2837:     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  2838:     /* if((int)age == 86 || (int)age == 87){ */
1.266     brouard  2839:     /*   printf(" Backward prevalim age=%d agefin=%d \n", (int) age, (int) agefin); */
                   2840:     /*   for(i=1; i<=nlstate+ndeath; i++) { */
                   2841:     /*         printf("%d newm= ",i); */
                   2842:     /*         for(j=1;j<=nlstate+ndeath;j++) { */
                   2843:     /*           printf("%f ",newm[i][j]); */
                   2844:     /*         } */
                   2845:     /*         printf("oldm * "); */
                   2846:     /*         for(j=1;j<=nlstate+ndeath;j++) { */
                   2847:     /*           printf("%f ",oldm[i][j]); */
                   2848:     /*         } */
1.268     brouard  2849:     /*         printf(" bmmij "); */
1.266     brouard  2850:     /*         for(j=1;j<=nlstate+ndeath;j++) { */
                   2851:     /*           printf("%f ",pmmij[i][j]); */
                   2852:     /*         } */
                   2853:     /*         printf("\n"); */
                   2854:     /*   } */
                   2855:     /* } */
1.217     brouard  2856:     savm=oldm;
                   2857:     oldm=newm;
1.266     brouard  2858: 
1.217     brouard  2859:     for(j=1; j<=nlstate; j++){
                   2860:       max[j]=0.;
                   2861:       min[j]=1.;
                   2862:     }
                   2863:     for(j=1; j<=nlstate; j++){ 
                   2864:       for(i=1;i<=nlstate;i++){
1.234     brouard  2865:        /* bprlim[i][j]= newm[i][j]/(1-sumnew); */
                   2866:        bprlim[i][j]= newm[i][j];
                   2867:        max[i]=FMAX(max[i],bprlim[i][j]); /* Max in line */
                   2868:        min[i]=FMIN(min[i],bprlim[i][j]);
1.217     brouard  2869:       }
                   2870:     }
1.218     brouard  2871:                
1.217     brouard  2872:     maxmax=0.;
                   2873:     for(i=1; i<=nlstate; i++){
                   2874:       meandiff[i]=(max[i]-min[i])/(max[i]+min[i])*2.; /* mean difference for each column */
                   2875:       maxmax=FMAX(maxmax,meandiff[i]);
                   2876:       /* 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  2877:     } /* i loop */
1.217     brouard  2878:     *ncvyear= -( (int)age- (int)agefin);
1.268     brouard  2879:     /* printf("Back maxmax=%lf ncvloop=%d, age=%d, agefin=%d ncvyear=%d \n", maxmax, ncvloop, (int)age, (int)agefin, *ncvyear); */
1.217     brouard  2880:     if(maxmax < ftolpl){
1.220     brouard  2881:       /* printf("OK Back maxmax=%lf ncvloop=%d, age=%d, agefin=%d ncvyear=%d \n", maxmax, ncvloop, (int)age, (int)agefin, *ncvyear); */
1.217     brouard  2882:       free_vector(min,1,nlstate);
                   2883:       free_vector(max,1,nlstate);
                   2884:       free_vector(meandiff,1,nlstate);
                   2885:       return bprlim;
                   2886:     }
1.288     brouard  2887:   } /* agefin loop */
1.217     brouard  2888:     /* After some age loop it doesn't converge */
1.288     brouard  2889:   if(!first){
1.247     brouard  2890:     first=1;
                   2891:     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\
                   2892: 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);
                   2893:   }
                   2894:   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  2895: 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);
                   2896:   /* 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); */
                   2897:   free_vector(min,1,nlstate);
                   2898:   free_vector(max,1,nlstate);
                   2899:   free_vector(meandiff,1,nlstate);
                   2900:   
                   2901:   return bprlim; /* should not reach here */
                   2902: }
                   2903: 
1.126     brouard  2904: /*************** transition probabilities ***************/ 
                   2905: 
                   2906: double **pmij(double **ps, double *cov, int ncovmodel, double *x, int nlstate )
                   2907: {
1.138     brouard  2908:   /* According to parameters values stored in x and the covariate's values stored in cov,
1.266     brouard  2909:      computes the probability to be observed in state j (after stepm years) being in state i by appying the
1.138     brouard  2910:      model to the ncovmodel covariates (including constant and age).
                   2911:      lnpijopii=ln(pij/pii)= aij+bij*age+cij*v1+dij*v2+... = sum_nc=1^ncovmodel xij(nc)*cov[nc]
                   2912:      and, according on how parameters are entered, the position of the coefficient xij(nc) of the
                   2913:      ncth covariate in the global vector x is given by the formula:
                   2914:      j<i nc+((i-1)*(nlstate+ndeath-1)+j-1)*ncovmodel
                   2915:      j>=i nc + ((i-1)*(nlstate+ndeath-1)+(j-2))*ncovmodel
                   2916:      Computes ln(pij/pii) (lnpijopii), deduces pij/pii by exponentiation,
                   2917:      sums on j different of i to get 1-pii/pii, deduces pii, and then all pij.
1.266     brouard  2918:      Outputs ps[i][j] or probability to be observed in j being in i according to
1.138     brouard  2919:      the values of the covariates cov[nc] and corresponding parameter values x[nc+shiftij]
1.266     brouard  2920:      Sum on j ps[i][j] should equal to 1.
1.138     brouard  2921:   */
                   2922:   double s1, lnpijopii;
1.126     brouard  2923:   /*double t34;*/
1.164     brouard  2924:   int i,j, nc, ii, jj;
1.126     brouard  2925: 
1.223     brouard  2926:   for(i=1; i<= nlstate; i++){
                   2927:     for(j=1; j<i;j++){
                   2928:       for (nc=1, lnpijopii=0.;nc <=ncovmodel; nc++){
                   2929:        /*lnpijopii += param[i][j][nc]*cov[nc];*/
                   2930:        lnpijopii += x[nc+((i-1)*(nlstate+ndeath-1)+j-1)*ncovmodel]*cov[nc];
                   2931:        /*       printf("Int j<i s1=%.17e, lnpijopii=%.17e\n",s1,lnpijopii); */
                   2932:       }
                   2933:       ps[i][j]=lnpijopii; /* In fact ln(pij/pii) */
                   2934:       /*       printf("s1=%.17e, lnpijopii=%.17e\n",s1,lnpijopii); */
                   2935:     }
                   2936:     for(j=i+1; j<=nlstate+ndeath;j++){
                   2937:       for (nc=1, lnpijopii=0.;nc <=ncovmodel; nc++){
                   2938:        /*lnpijopii += x[(i-1)*nlstate*ncovmodel+(j-2)*ncovmodel+nc+(i-1)*(ndeath-1)*ncovmodel]*cov[nc];*/
                   2939:        lnpijopii += x[nc + ((i-1)*(nlstate+ndeath-1)+(j-2))*ncovmodel]*cov[nc];
                   2940:        /*        printf("Int j>i s1=%.17e, lnpijopii=%.17e %lx %lx\n",s1,lnpijopii,s1,lnpijopii); */
                   2941:       }
                   2942:       ps[i][j]=lnpijopii; /* In fact ln(pij/pii) */
                   2943:     }
                   2944:   }
1.218     brouard  2945:   
1.223     brouard  2946:   for(i=1; i<= nlstate; i++){
                   2947:     s1=0;
                   2948:     for(j=1; j<i; j++){
                   2949:       s1+=exp(ps[i][j]); /* In fact sums pij/pii */
                   2950:       /*printf("debug1 %d %d ps=%lf exp(ps)=%lf s1+=%lf\n",i,j,ps[i][j],exp(ps[i][j]),s1); */
                   2951:     }
                   2952:     for(j=i+1; j<=nlstate+ndeath; j++){
                   2953:       s1+=exp(ps[i][j]); /* In fact sums pij/pii */
                   2954:       /*printf("debug2 %d %d ps=%lf exp(ps)=%lf s1+=%lf\n",i,j,ps[i][j],exp(ps[i][j]),s1); */
                   2955:     }
                   2956:     /* s1= sum_{j<>i} pij/pii=(1-pii)/pii and thus pii is known from s1 */
                   2957:     ps[i][i]=1./(s1+1.);
                   2958:     /* Computing other pijs */
                   2959:     for(j=1; j<i; j++)
                   2960:       ps[i][j]= exp(ps[i][j])*ps[i][i];
                   2961:     for(j=i+1; j<=nlstate+ndeath; j++)
                   2962:       ps[i][j]= exp(ps[i][j])*ps[i][i];
                   2963:     /* ps[i][nlstate+1]=1.-s1- ps[i][i];*/ /* Sum should be 1 */
                   2964:   } /* end i */
1.218     brouard  2965:   
1.223     brouard  2966:   for(ii=nlstate+1; ii<= nlstate+ndeath; ii++){
                   2967:     for(jj=1; jj<= nlstate+ndeath; jj++){
                   2968:       ps[ii][jj]=0;
                   2969:       ps[ii][ii]=1;
                   2970:     }
                   2971:   }
1.294   ! brouard  2972: 
        !          2973: 
1.223     brouard  2974:   /* for(ii=1; ii<= nlstate+ndeath; ii++){ */
                   2975:   /*   for(jj=1; jj<= nlstate+ndeath; jj++){ */
                   2976:   /*   printf(" pmij  ps[%d][%d]=%lf ",ii,jj,ps[ii][jj]); */
                   2977:   /*   } */
                   2978:   /*   printf("\n "); */
                   2979:   /* } */
                   2980:   /* printf("\n ");printf("%lf ",cov[2]);*/
                   2981:   /*
                   2982:     for(i=1; i<= npar; i++) printf("%f ",x[i]);
1.218     brouard  2983:                goto end;*/
1.266     brouard  2984:   return ps; /* Pointer is unchanged since its call */
1.126     brouard  2985: }
                   2986: 
1.218     brouard  2987: /*************** backward transition probabilities ***************/ 
                   2988: 
                   2989:  /* 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 ) */
                   2990: /* double **bmij(double **ps, double *cov, int ncovmodel, double *x, int nlstate,  double ***prevacurrent, double ***dnewm, double **doldm, double **dsavm, int ij ) */
                   2991:  double **bmij(double **ps, double *cov, int ncovmodel, double *x, int nlstate,  double ***prevacurrent, int ij )
                   2992: {
1.266     brouard  2993:   /* Computes the backward probability at age agefin and covariate combination ij. In fact cov is already filled and x too.
                   2994:    * 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  2995:    */
1.218     brouard  2996:   int i, ii, j,k;
1.222     brouard  2997:   
                   2998:   double **out, **pmij();
                   2999:   double sumnew=0.;
1.218     brouard  3000:   double agefin;
1.292     brouard  3001:   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  3002:   double **dnewm, **dsavm, **doldm;
                   3003:   double **bbmij;
                   3004:   
1.218     brouard  3005:   doldm=ddoldms; /* global pointers */
1.222     brouard  3006:   dnewm=ddnewms;
                   3007:   dsavm=ddsavms;
                   3008:   
                   3009:   agefin=cov[2];
1.268     brouard  3010:   /* Bx = Diag(w_x) P_x Diag(Sum_i w^i_x p^ij_x */
1.222     brouard  3011:   /* bmij *//* age is cov[2], ij is included in cov, but we need for
1.266     brouard  3012:      the observed prevalence (with this covariate ij) at beginning of transition */
                   3013:   /* dsavm=pmij(pmmij,cov,ncovmodel,x,nlstate); */
1.268     brouard  3014: 
                   3015:   /* P_x */
1.266     brouard  3016:   pmmij=pmij(pmmij,cov,ncovmodel,x,nlstate); /*This is forward probability from agefin to agefin + stepm */
1.268     brouard  3017:   /* outputs pmmij which is a stochastic matrix in row */
                   3018: 
                   3019:   /* Diag(w_x) */
1.292     brouard  3020:   /* Rescaling the cross-sectional prevalence: Problem with prevacurrent which can be zero */
1.268     brouard  3021:   sumnew=0.;
1.269     brouard  3022:   /*for (ii=1;ii<=nlstate+ndeath;ii++){*/
1.268     brouard  3023:   for (ii=1;ii<=nlstate;ii++){ /* Only on live states */
1.269     brouard  3024:     /* printf(" agefin=%d, ii=%d, ij=%d, prev=%f\n",(int)agefin,ii, ij, prevacurrent[(int)agefin][ii][ij]);  */
1.268     brouard  3025:     sumnew+=prevacurrent[(int)agefin][ii][ij];
                   3026:   }
                   3027:   if(sumnew >0.01){  /* At least some value in the prevalence */
                   3028:     for (ii=1;ii<=nlstate+ndeath;ii++){
                   3029:       for (j=1;j<=nlstate+ndeath;j++)
1.269     brouard  3030:        doldm[ii][j]=(ii==j ? prevacurrent[(int)agefin][ii][ij]/sumnew : 0.0);
1.268     brouard  3031:     }
                   3032:   }else{
                   3033:     for (ii=1;ii<=nlstate+ndeath;ii++){
                   3034:       for (j=1;j<=nlstate+ndeath;j++)
                   3035:       doldm[ii][j]=(ii==j ? 1./nlstate : 0.0);
                   3036:     }
                   3037:     /* if(sumnew <0.9){ */
                   3038:     /*   printf("Problem internal bmij B: sum on i wi <0.9: j=%d, sum_i wi=%lf,agefin=%d\n",j,sumnew, (int)agefin); */
                   3039:     /* } */
                   3040:   }
                   3041:   k3=0.0;  /* We put the last diagonal to 0 */
                   3042:   for (ii=nlstate+1;ii<=nlstate+ndeath;ii++){
                   3043:       doldm[ii][ii]= k3;
                   3044:   }
                   3045:   /* End doldm, At the end doldm is diag[(w_i)] */
                   3046:   
1.292     brouard  3047:   /* Left product of this diag matrix by pmmij=Px (dnewm=dsavm*doldm): diag[(w_i)*Px */
                   3048:   bbmij=matprod2(dnewm, doldm,1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, pmmij); /* was a Bug Valgrind */
1.268     brouard  3049: 
1.292     brouard  3050:   /* Diag(Sum_i w^i_x p^ij_x, should be the prevalence at age x+stepm */
1.268     brouard  3051:   /* 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  3052:   for (j=1;j<=nlstate+ndeath;j++){
1.268     brouard  3053:     sumnew=0.;
1.222     brouard  3054:     for (ii=1;ii<=nlstate;ii++){
1.266     brouard  3055:       /* sumnew+=dsavm[ii][j]*prevacurrent[(int)agefin][ii][ij]; */
1.268     brouard  3056:       sumnew+=pmmij[ii][j]*doldm[ii][ii]; /* Yes prevalence at beginning of transition */
1.222     brouard  3057:     } /* sumnew is (N11+N21)/N..= N.1/N.. = sum on i of w_i pij */
1.268     brouard  3058:     for (ii=1;ii<=nlstate+ndeath;ii++){
1.222     brouard  3059:        /* if(agefin >= agemaxpar && agefin <= agemaxpar+stepm/YEARM){ */
1.268     brouard  3060:        /*      dsavm[ii][j]=(ii==j ? 1./sumnew : 0.0); */
1.222     brouard  3061:        /* }else if(agefin >= agemaxpar+stepm/YEARM){ */
1.268     brouard  3062:        /*      dsavm[ii][j]=(ii==j ? 1./sumnew : 0.0); */
1.222     brouard  3063:        /* }else */
1.268     brouard  3064:       dsavm[ii][j]=(ii==j ? 1./sumnew : 0.0);
                   3065:     } /*End ii */
                   3066:   } /* 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 */
                   3067: 
1.292     brouard  3068:   ps=matprod2(ps, dnewm,1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, dsavm); /* was a Bug Valgrind */
1.268     brouard  3069:   /* ps is now diag[w_i] * Px * diag [1/(w_1p1i+w_2 p2i)] */
1.222     brouard  3070:   /* end bmij */
1.266     brouard  3071:   return ps; /*pointer is unchanged */
1.218     brouard  3072: }
1.217     brouard  3073: /*************** transition probabilities ***************/ 
                   3074: 
1.218     brouard  3075: double **bpmij(double **ps, double *cov, int ncovmodel, double *x, int nlstate )
1.217     brouard  3076: {
                   3077:   /* According to parameters values stored in x and the covariate's values stored in cov,
                   3078:      computes the probability to be observed in state j being in state i by appying the
                   3079:      model to the ncovmodel covariates (including constant and age).
                   3080:      lnpijopii=ln(pij/pii)= aij+bij*age+cij*v1+dij*v2+... = sum_nc=1^ncovmodel xij(nc)*cov[nc]
                   3081:      and, according on how parameters are entered, the position of the coefficient xij(nc) of the
                   3082:      ncth covariate in the global vector x is given by the formula:
                   3083:      j<i nc+((i-1)*(nlstate+ndeath-1)+j-1)*ncovmodel
                   3084:      j>=i nc + ((i-1)*(nlstate+ndeath-1)+(j-2))*ncovmodel
                   3085:      Computes ln(pij/pii) (lnpijopii), deduces pij/pii by exponentiation,
                   3086:      sums on j different of i to get 1-pii/pii, deduces pii, and then all pij.
                   3087:      Outputs ps[i][j] the probability to be observed in j being in j according to
                   3088:      the values of the covariates cov[nc] and corresponding parameter values x[nc+shiftij]
                   3089:   */
                   3090:   double s1, lnpijopii;
                   3091:   /*double t34;*/
                   3092:   int i,j, nc, ii, jj;
                   3093: 
1.234     brouard  3094:   for(i=1; i<= nlstate; i++){
                   3095:     for(j=1; j<i;j++){
                   3096:       for (nc=1, lnpijopii=0.;nc <=ncovmodel; nc++){
                   3097:        /*lnpijopii += param[i][j][nc]*cov[nc];*/
                   3098:        lnpijopii += x[nc+((i-1)*(nlstate+ndeath-1)+j-1)*ncovmodel]*cov[nc];
                   3099:        /*       printf("Int j<i s1=%.17e, lnpijopii=%.17e\n",s1,lnpijopii); */
                   3100:       }
                   3101:       ps[i][j]=lnpijopii; /* In fact ln(pij/pii) */
                   3102:       /*       printf("s1=%.17e, lnpijopii=%.17e\n",s1,lnpijopii); */
                   3103:     }
                   3104:     for(j=i+1; j<=nlstate+ndeath;j++){
                   3105:       for (nc=1, lnpijopii=0.;nc <=ncovmodel; nc++){
                   3106:        /*lnpijopii += x[(i-1)*nlstate*ncovmodel+(j-2)*ncovmodel+nc+(i-1)*(ndeath-1)*ncovmodel]*cov[nc];*/
                   3107:        lnpijopii += x[nc + ((i-1)*(nlstate+ndeath-1)+(j-2))*ncovmodel]*cov[nc];
                   3108:        /*        printf("Int j>i s1=%.17e, lnpijopii=%.17e %lx %lx\n",s1,lnpijopii,s1,lnpijopii); */
                   3109:       }
                   3110:       ps[i][j]=lnpijopii; /* In fact ln(pij/pii) */
                   3111:     }
                   3112:   }
                   3113:   
                   3114:   for(i=1; i<= nlstate; i++){
                   3115:     s1=0;
                   3116:     for(j=1; j<i; j++){
                   3117:       s1+=exp(ps[i][j]); /* In fact sums pij/pii */
                   3118:       /*printf("debug1 %d %d ps=%lf exp(ps)=%lf s1+=%lf\n",i,j,ps[i][j],exp(ps[i][j]),s1); */
                   3119:     }
                   3120:     for(j=i+1; j<=nlstate+ndeath; j++){
                   3121:       s1+=exp(ps[i][j]); /* In fact sums pij/pii */
                   3122:       /*printf("debug2 %d %d ps=%lf exp(ps)=%lf s1+=%lf\n",i,j,ps[i][j],exp(ps[i][j]),s1); */
                   3123:     }
                   3124:     /* s1= sum_{j<>i} pij/pii=(1-pii)/pii and thus pii is known from s1 */
                   3125:     ps[i][i]=1./(s1+1.);
                   3126:     /* Computing other pijs */
                   3127:     for(j=1; j<i; j++)
                   3128:       ps[i][j]= exp(ps[i][j])*ps[i][i];
                   3129:     for(j=i+1; j<=nlstate+ndeath; j++)
                   3130:       ps[i][j]= exp(ps[i][j])*ps[i][i];
                   3131:     /* ps[i][nlstate+1]=1.-s1- ps[i][i];*/ /* Sum should be 1 */
                   3132:   } /* end i */
                   3133:   
                   3134:   for(ii=nlstate+1; ii<= nlstate+ndeath; ii++){
                   3135:     for(jj=1; jj<= nlstate+ndeath; jj++){
                   3136:       ps[ii][jj]=0;
                   3137:       ps[ii][ii]=1;
                   3138:     }
                   3139:   }
                   3140:   /* Added for backcast */ /* Transposed matrix too */
                   3141:   for(jj=1; jj<= nlstate+ndeath; jj++){
                   3142:     s1=0.;
                   3143:     for(ii=1; ii<= nlstate+ndeath; ii++){
                   3144:       s1+=ps[ii][jj];
                   3145:     }
                   3146:     for(ii=1; ii<= nlstate; ii++){
                   3147:       ps[ii][jj]=ps[ii][jj]/s1;
                   3148:     }
                   3149:   }
                   3150:   /* Transposition */
                   3151:   for(jj=1; jj<= nlstate+ndeath; jj++){
                   3152:     for(ii=jj; ii<= nlstate+ndeath; ii++){
                   3153:       s1=ps[ii][jj];
                   3154:       ps[ii][jj]=ps[jj][ii];
                   3155:       ps[jj][ii]=s1;
                   3156:     }
                   3157:   }
                   3158:   /* for(ii=1; ii<= nlstate+ndeath; ii++){ */
                   3159:   /*   for(jj=1; jj<= nlstate+ndeath; jj++){ */
                   3160:   /*   printf(" pmij  ps[%d][%d]=%lf ",ii,jj,ps[ii][jj]); */
                   3161:   /*   } */
                   3162:   /*   printf("\n "); */
                   3163:   /* } */
                   3164:   /* printf("\n ");printf("%lf ",cov[2]);*/
                   3165:   /*
                   3166:     for(i=1; i<= npar; i++) printf("%f ",x[i]);
                   3167:     goto end;*/
                   3168:   return ps;
1.217     brouard  3169: }
                   3170: 
                   3171: 
1.126     brouard  3172: /**************** Product of 2 matrices ******************/
                   3173: 
1.145     brouard  3174: double **matprod2(double **out, double **in,int nrl, int nrh, int ncl, int nch, int ncolol, int ncoloh, double **b)
1.126     brouard  3175: {
                   3176:   /* Computes the matrix product of in(1,nrh-nrl+1)(1,nch-ncl+1) times
                   3177:      b(1,nch-ncl+1)(1,ncoloh-ncolol+1) into out(...) */
                   3178:   /* in, b, out are matrice of pointers which should have been initialized 
                   3179:      before: only the contents of out is modified. The function returns
                   3180:      a pointer to pointers identical to out */
1.145     brouard  3181:   int i, j, k;
1.126     brouard  3182:   for(i=nrl; i<= nrh; i++)
1.145     brouard  3183:     for(k=ncolol; k<=ncoloh; k++){
                   3184:       out[i][k]=0.;
                   3185:       for(j=ncl; j<=nch; j++)
                   3186:        out[i][k] +=in[i][j]*b[j][k];
                   3187:     }
1.126     brouard  3188:   return out;
                   3189: }
                   3190: 
                   3191: 
                   3192: /************* Higher Matrix Product ***************/
                   3193: 
1.235     brouard  3194: 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  3195: {
1.218     brouard  3196:   /* Computes the transition matrix starting at age 'age' and combination of covariate values corresponding to ij over 
1.126     brouard  3197:      'nhstepm*hstepm*stepm' months (i.e. until
                   3198:      age (in years)  age+nhstepm*hstepm*stepm/12) by multiplying 
                   3199:      nhstepm*hstepm matrices. 
                   3200:      Output is stored in matrix po[i][j][h] for h every 'hstepm' step 
                   3201:      (typically every 2 years instead of every month which is too big 
                   3202:      for the memory).
                   3203:      Model is determined by parameters x and covariates have to be 
                   3204:      included manually here. 
                   3205: 
                   3206:      */
                   3207: 
                   3208:   int i, j, d, h, k;
1.131     brouard  3209:   double **out, cov[NCOVMAX+1];
1.126     brouard  3210:   double **newm;
1.187     brouard  3211:   double agexact;
1.214     brouard  3212:   double agebegin, ageend;
1.126     brouard  3213: 
                   3214:   /* Hstepm could be zero and should return the unit matrix */
                   3215:   for (i=1;i<=nlstate+ndeath;i++)
                   3216:     for (j=1;j<=nlstate+ndeath;j++){
                   3217:       oldm[i][j]=(i==j ? 1.0 : 0.0);
                   3218:       po[i][j][0]=(i==j ? 1.0 : 0.0);
                   3219:     }
                   3220:   /* Even if hstepm = 1, at least one multiplication by the unit matrix */
                   3221:   for(h=1; h <=nhstepm; h++){
                   3222:     for(d=1; d <=hstepm; d++){
                   3223:       newm=savm;
                   3224:       /* Covariates have to be included here again */
                   3225:       cov[1]=1.;
1.214     brouard  3226:       agexact=age+((h-1)*hstepm + (d-1))*stepm/YEARM; /* age just before transition */
1.187     brouard  3227:       cov[2]=agexact;
                   3228:       if(nagesqr==1)
1.227     brouard  3229:        cov[3]= agexact*agexact;
1.235     brouard  3230:       for (k=1; k<=nsd;k++) { /* For single dummy covariates only */
                   3231:                        /* Here comes the value of the covariate 'ij' after renumbering k with single dummy covariates */
                   3232:        cov[2+nagesqr+TvarsDind[k]]=nbcode[TvarsD[k]][codtabm(ij,k)];
                   3233:        /* 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)); */
                   3234:       }
                   3235:       for (k=1; k<=nsq;k++) { /* For single varying covariates only */
                   3236:        /* Here comes the value of quantitative after renumbering k with single quantitative covariates */
                   3237:        cov[2+nagesqr+TvarsQind[k]]=Tqresult[nres][k]; 
                   3238:        /* 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]); */
                   3239:       }
                   3240:       for (k=1; k<=cptcovage;k++){
                   3241:        if(Dummy[Tvar[Tage[k]]]){
                   3242:          cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,k)]*cov[2];
                   3243:        } else{
                   3244:          cov[2+nagesqr+Tage[k]]=Tqresult[nres][k]; 
                   3245:        }
                   3246:        /* 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]); */
                   3247:       }
                   3248:       for (k=1; k<=cptcovprod;k++){ /*  */
                   3249:        /* 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]); */
                   3250:        cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)] * nbcode[Tvard[k][2]][codtabm(ij,k)];
                   3251:       }
                   3252:       /* for (k=1; k<=cptcovn;k++)  */
                   3253:       /*       cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,k)]; */
                   3254:       /* for (k=1; k<=cptcovage;k++) /\* Should start at cptcovn+1 *\/ */
                   3255:       /*       cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,k)]*cov[2]; */
                   3256:       /* for (k=1; k<=cptcovprod;k++) /\* Useless because included in cptcovn *\/ */
                   3257:       /*       cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)]*nbcode[Tvard[k][2]][codtabm(ij,k)]; */
1.227     brouard  3258:       
                   3259:       
1.126     brouard  3260:       /*printf("hxi cptcov=%d cptcode=%d\n",cptcov,cptcode);*/
                   3261:       /*printf("h=%d d=%d age=%f cov=%f\n",h,d,age,cov[2]);*/
1.218     brouard  3262:                        /* right multiplication of oldm by the current matrix */
1.126     brouard  3263:       out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, 
                   3264:                   pmij(pmmij,cov,ncovmodel,x,nlstate));
1.217     brouard  3265:       /* if((int)age == 70){ */
                   3266:       /*       printf(" Forward hpxij age=%d agexact=%f d=%d nhstepm=%d hstepm=%d\n", (int) age, agexact, d, nhstepm, hstepm); */
                   3267:       /*       for(i=1; i<=nlstate+ndeath; i++) { */
                   3268:       /*         printf("%d pmmij ",i); */
                   3269:       /*         for(j=1;j<=nlstate+ndeath;j++) { */
                   3270:       /*           printf("%f ",pmmij[i][j]); */
                   3271:       /*         } */
                   3272:       /*         printf(" oldm "); */
                   3273:       /*         for(j=1;j<=nlstate+ndeath;j++) { */
                   3274:       /*           printf("%f ",oldm[i][j]); */
                   3275:       /*         } */
                   3276:       /*         printf("\n"); */
                   3277:       /*       } */
                   3278:       /* } */
1.126     brouard  3279:       savm=oldm;
                   3280:       oldm=newm;
                   3281:     }
                   3282:     for(i=1; i<=nlstate+ndeath; i++)
                   3283:       for(j=1;j<=nlstate+ndeath;j++) {
1.267     brouard  3284:        po[i][j][h]=newm[i][j];
                   3285:        /*if(h==nhstepm) printf("po[%d][%d][%d]=%f ",i,j,h,po[i][j][h]);*/
1.126     brouard  3286:       }
1.128     brouard  3287:     /*printf("h=%d ",h);*/
1.126     brouard  3288:   } /* end h */
1.267     brouard  3289:   /*     printf("\n H=%d \n",h); */
1.126     brouard  3290:   return po;
                   3291: }
                   3292: 
1.217     brouard  3293: /************* Higher Back Matrix Product ***************/
1.218     brouard  3294: /* 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  3295: 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  3296: {
1.266     brouard  3297:   /* For a combination of dummy covariate ij, computes the transition matrix starting at age 'age' over
1.217     brouard  3298:      'nhstepm*hstepm*stepm' months (i.e. until
1.218     brouard  3299:      age (in years)  age+nhstepm*hstepm*stepm/12) by multiplying
                   3300:      nhstepm*hstepm matrices.
                   3301:      Output is stored in matrix po[i][j][h] for h every 'hstepm' step
                   3302:      (typically every 2 years instead of every month which is too big
1.217     brouard  3303:      for the memory).
1.218     brouard  3304:      Model is determined by parameters x and covariates have to be
1.266     brouard  3305:      included manually here. Then we use a call to bmij(x and cov)
                   3306:      The addresss of po (p3mat allocated to the dimension of nhstepm) should be stored for output
1.222     brouard  3307:   */
1.217     brouard  3308: 
                   3309:   int i, j, d, h, k;
1.266     brouard  3310:   double **out, cov[NCOVMAX+1], **bmij();
                   3311:   double **newm, ***newmm;
1.217     brouard  3312:   double agexact;
                   3313:   double agebegin, ageend;
1.222     brouard  3314:   double **oldm, **savm;
1.217     brouard  3315: 
1.266     brouard  3316:   newmm=po; /* To be saved */
                   3317:   oldm=oldms;savm=savms; /* Global pointers */
1.217     brouard  3318:   /* Hstepm could be zero and should return the unit matrix */
                   3319:   for (i=1;i<=nlstate+ndeath;i++)
                   3320:     for (j=1;j<=nlstate+ndeath;j++){
                   3321:       oldm[i][j]=(i==j ? 1.0 : 0.0);
                   3322:       po[i][j][0]=(i==j ? 1.0 : 0.0);
                   3323:     }
                   3324:   /* Even if hstepm = 1, at least one multiplication by the unit matrix */
                   3325:   for(h=1; h <=nhstepm; h++){
                   3326:     for(d=1; d <=hstepm; d++){
                   3327:       newm=savm;
                   3328:       /* Covariates have to be included here again */
                   3329:       cov[1]=1.;
1.271     brouard  3330:       agexact=age-( (h-1)*hstepm + (d)  )*stepm/YEARM; /* age just before transition, d or d-1? */
1.217     brouard  3331:       /* agexact=age+((h-1)*hstepm + (d-1))*stepm/YEARM; /\* age just before transition *\/ */
                   3332:       cov[2]=agexact;
                   3333:       if(nagesqr==1)
1.222     brouard  3334:        cov[3]= agexact*agexact;
1.266     brouard  3335:       for (k=1; k<=cptcovn;k++){
                   3336:       /*       cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,k)]; */
                   3337:       /* /\* cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,Tvar[k])]; *\/ */
                   3338:        cov[2+nagesqr+TvarsDind[k]]=nbcode[TvarsD[k]][codtabm(ij,k)];
                   3339:         /* 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)); */
                   3340:       }
1.267     brouard  3341:       for (k=1; k<=nsq;k++) { /* For single varying covariates only */
                   3342:        /* Here comes the value of quantitative after renumbering k with single quantitative covariates */
                   3343:        cov[2+nagesqr+TvarsQind[k]]=Tqresult[nres][k]; 
                   3344:        /* 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]); */
                   3345:       }
                   3346:       for (k=1; k<=cptcovage;k++){ /* Should start at cptcovn+1 */
                   3347:        if(Dummy[Tvar[Tage[k]]]){
                   3348:          cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,k)]*cov[2];
                   3349:        } else{
                   3350:          cov[2+nagesqr+Tage[k]]=Tqresult[nres][k]; 
                   3351:        }
                   3352:        /* 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]); */
                   3353:       }
                   3354:       for (k=1; k<=cptcovprod;k++){ /* Useless because included in cptcovn */
1.222     brouard  3355:        cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)]*nbcode[Tvard[k][2]][codtabm(ij,k)];
1.267     brouard  3356:       }                        
1.217     brouard  3357:       /*printf("hxi cptcov=%d cptcode=%d\n",cptcov,cptcode);*/
                   3358:       /*printf("h=%d d=%d age=%f cov=%f\n",h,d,age,cov[2]);*/
1.267     brouard  3359: 
1.218     brouard  3360:       /* Careful transposed matrix */
1.266     brouard  3361:       /* age is in cov[2], prevacurrent at beginning of transition. */
1.218     brouard  3362:       /* out=matprod2(newm, bmij(pmmij,cov,ncovmodel,x,nlstate,prevacurrent, dnewm, doldm, dsavm,ij),\ */
1.222     brouard  3363:       /*                                                1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm); */
1.218     brouard  3364:       out=matprod2(newm, bmij(pmmij,cov,ncovmodel,x,nlstate,prevacurrent,ij),\
1.222     brouard  3365:                   1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm);
1.217     brouard  3366:       /* if((int)age == 70){ */
                   3367:       /*       printf(" Backward hbxij age=%d agexact=%f d=%d nhstepm=%d hstepm=%d\n", (int) age, agexact, d, nhstepm, hstepm); */
                   3368:       /*       for(i=1; i<=nlstate+ndeath; i++) { */
                   3369:       /*         printf("%d pmmij ",i); */
                   3370:       /*         for(j=1;j<=nlstate+ndeath;j++) { */
                   3371:       /*           printf("%f ",pmmij[i][j]); */
                   3372:       /*         } */
                   3373:       /*         printf(" oldm "); */
                   3374:       /*         for(j=1;j<=nlstate+ndeath;j++) { */
                   3375:       /*           printf("%f ",oldm[i][j]); */
                   3376:       /*         } */
                   3377:       /*         printf("\n"); */
                   3378:       /*       } */
                   3379:       /* } */
                   3380:       savm=oldm;
                   3381:       oldm=newm;
                   3382:     }
                   3383:     for(i=1; i<=nlstate+ndeath; i++)
                   3384:       for(j=1;j<=nlstate+ndeath;j++) {
1.222     brouard  3385:        po[i][j][h]=newm[i][j];
1.268     brouard  3386:        /* if(h==nhstepm) */
                   3387:        /*   printf("po[%d][%d][%d]=%f ",i,j,h,po[i][j][h]); */
1.217     brouard  3388:       }
1.268     brouard  3389:     /* printf("h=%d %.1f ",h, agexact); */
1.217     brouard  3390:   } /* end h */
1.268     brouard  3391:   /* printf("\n H=%d nhs=%d \n",h, nhstepm); */
1.217     brouard  3392:   return po;
                   3393: }
                   3394: 
                   3395: 
1.162     brouard  3396: #ifdef NLOPT
                   3397:   double  myfunc(unsigned n, const double *p1, double *grad, void *pd){
                   3398:   double fret;
                   3399:   double *xt;
                   3400:   int j;
                   3401:   myfunc_data *d2 = (myfunc_data *) pd;
                   3402: /* xt = (p1-1); */
                   3403:   xt=vector(1,n); 
                   3404:   for (j=1;j<=n;j++)   xt[j]=p1[j-1]; /* xt[1]=p1[0] */
                   3405: 
                   3406:   fret=(d2->function)(xt); /*  p xt[1]@8 is fine */
                   3407:   /* fret=(*func)(xt); /\*  p xt[1]@8 is fine *\/ */
                   3408:   printf("Function = %.12lf ",fret);
                   3409:   for (j=1;j<=n;j++) printf(" %d %.8lf", j, xt[j]); 
                   3410:   printf("\n");
                   3411:  free_vector(xt,1,n);
                   3412:   return fret;
                   3413: }
                   3414: #endif
1.126     brouard  3415: 
                   3416: /*************** log-likelihood *************/
                   3417: double func( double *x)
                   3418: {
1.226     brouard  3419:   int i, ii, j, k, mi, d, kk;
                   3420:   int ioffset=0;
                   3421:   double l, ll[NLSTATEMAX+1], cov[NCOVMAX+1];
                   3422:   double **out;
                   3423:   double lli; /* Individual log likelihood */
                   3424:   int s1, s2;
1.228     brouard  3425:   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  3426:   double bbh, survp;
                   3427:   long ipmx;
                   3428:   double agexact;
                   3429:   /*extern weight */
                   3430:   /* We are differentiating ll according to initial status */
                   3431:   /*  for (i=1;i<=npar;i++) printf("%f ", x[i]);*/
                   3432:   /*for(i=1;i<imx;i++) 
                   3433:     printf(" %d\n",s[4][i]);
                   3434:   */
1.162     brouard  3435: 
1.226     brouard  3436:   ++countcallfunc;
1.162     brouard  3437: 
1.226     brouard  3438:   cov[1]=1.;
1.126     brouard  3439: 
1.226     brouard  3440:   for(k=1; k<=nlstate; k++) ll[k]=0.;
1.224     brouard  3441:   ioffset=0;
1.226     brouard  3442:   if(mle==1){
                   3443:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
                   3444:       /* Computes the values of the ncovmodel covariates of the model
                   3445:         depending if the covariates are fixed or varying (age dependent) and stores them in cov[]
                   3446:         Then computes with function pmij which return a matrix p[i][j] giving the elementary probability
                   3447:         to be observed in j being in i according to the model.
                   3448:       */
1.243     brouard  3449:       ioffset=2+nagesqr ;
1.233     brouard  3450:    /* Fixed */
1.234     brouard  3451:       for (k=1; k<=ncovf;k++){ /* Simple and product fixed covariates without age* products */
                   3452:        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)*/
                   3453:       }
1.226     brouard  3454:       /* In model V2+V1*V4+age*V3+V3*V2 Tvar[1] is V2, Tvar[2=V1*V4] 
                   3455:         is 6, Tvar[3=age*V3] should not be computed because of age Tvar[4=V3*V2] 
                   3456:         has been calculated etc */
                   3457:       /* For an individual i, wav[i] gives the number of effective waves */
                   3458:       /* We compute the contribution to Likelihood of each effective transition
                   3459:         mw[mi][i] is real wave of the mi th effectve wave */
                   3460:       /* Then statuses are computed at each begin and end of an effective wave s1=s[ mw[mi][i] ][i];
                   3461:         s2=s[mw[mi+1][i]][i];
                   3462:         And the iv th varying covariate is the cotvar[mw[mi+1][i]][iv][i]
                   3463:         But if the variable is not in the model TTvar[iv] is the real variable effective in the model:
                   3464:         meaning that decodemodel should be used cotvar[mw[mi+1][i]][TTvar[iv]][i]
                   3465:       */
                   3466:       for(mi=1; mi<= wav[i]-1; mi++){
1.234     brouard  3467:        for(k=1; k <= ncovv ; k++){ /* Varying  covariates (single and product but no age )*/
1.242     brouard  3468:          /* cov[ioffset+TvarVind[k]]=cotvar[mw[mi][i]][Tvar[TvarVind[k]]][i]; */
                   3469:          cov[ioffset+TvarVind[k]]=cotvar[mw[mi][i]][Tvar[TvarVind[k]]-ncovcol-nqv][i];
1.234     brouard  3470:        }
                   3471:        for (ii=1;ii<=nlstate+ndeath;ii++)
                   3472:          for (j=1;j<=nlstate+ndeath;j++){
                   3473:            oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   3474:            savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   3475:          }
                   3476:        for(d=0; d<dh[mi][i]; d++){
                   3477:          newm=savm;
                   3478:          agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
                   3479:          cov[2]=agexact;
                   3480:          if(nagesqr==1)
                   3481:            cov[3]= agexact*agexact;  /* Should be changed here */
                   3482:          for (kk=1; kk<=cptcovage;kk++) {
1.242     brouard  3483:          if(!FixedV[Tvar[Tage[kk]]])
1.234     brouard  3484:            cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact; /* Tage[kk] gives the data-covariate associated with age */
1.242     brouard  3485:          else
                   3486:            cov[Tage[kk]+2+nagesqr]=cotvar[mw[mi][i]][Tvar[Tage[kk]]-ncovcol-nqv][i]*agexact;
1.234     brouard  3487:          }
                   3488:          out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   3489:                       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   3490:          savm=oldm;
                   3491:          oldm=newm;
                   3492:        } /* end mult */
                   3493:        
                   3494:        /*lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]);*/ /* Original formula */
                   3495:        /* But now since version 0.9 we anticipate for bias at large stepm.
                   3496:         * If stepm is larger than one month (smallest stepm) and if the exact delay 
                   3497:         * (in months) between two waves is not a multiple of stepm, we rounded to 
                   3498:         * the nearest (and in case of equal distance, to the lowest) interval but now
                   3499:         * we keep into memory the bias bh[mi][i] and also the previous matrix product
                   3500:         * (i.e to dh[mi][i]-1) saved in 'savm'. Then we inter(extra)polate the
                   3501:         * probability in order to take into account the bias as a fraction of the way
1.231     brouard  3502:                                 * from savm to out if bh is negative or even beyond if bh is positive. bh varies
                   3503:                                 * -stepm/2 to stepm/2 .
                   3504:                                 * For stepm=1 the results are the same as for previous versions of Imach.
                   3505:                                 * For stepm > 1 the results are less biased than in previous versions. 
                   3506:                                 */
1.234     brouard  3507:        s1=s[mw[mi][i]][i];
                   3508:        s2=s[mw[mi+1][i]][i];
                   3509:        bbh=(double)bh[mi][i]/(double)stepm; 
                   3510:        /* bias bh is positive if real duration
                   3511:         * is higher than the multiple of stepm and negative otherwise.
                   3512:         */
                   3513:        /* lli= (savm[s1][s2]>1.e-8 ?(1.+bbh)*log(out[s1][s2])- bbh*log(savm[s1][s2]):log((1.+bbh)*out[s1][s2]));*/
                   3514:        if( s2 > nlstate){ 
                   3515:          /* i.e. if s2 is a death state and if the date of death is known 
                   3516:             then the contribution to the likelihood is the probability to 
                   3517:             die between last step unit time and current  step unit time, 
                   3518:             which is also equal to probability to die before dh 
                   3519:             minus probability to die before dh-stepm . 
                   3520:             In version up to 0.92 likelihood was computed
                   3521:             as if date of death was unknown. Death was treated as any other
                   3522:             health state: the date of the interview describes the actual state
                   3523:             and not the date of a change in health state. The former idea was
                   3524:             to consider that at each interview the state was recorded
                   3525:             (healthy, disable or death) and IMaCh was corrected; but when we
                   3526:             introduced the exact date of death then we should have modified
                   3527:             the contribution of an exact death to the likelihood. This new
                   3528:             contribution is smaller and very dependent of the step unit
                   3529:             stepm. It is no more the probability to die between last interview
                   3530:             and month of death but the probability to survive from last
                   3531:             interview up to one month before death multiplied by the
                   3532:             probability to die within a month. Thanks to Chris
                   3533:             Jackson for correcting this bug.  Former versions increased
                   3534:             mortality artificially. The bad side is that we add another loop
                   3535:             which slows down the processing. The difference can be up to 10%
                   3536:             lower mortality.
                   3537:          */
                   3538:          /* If, at the beginning of the maximization mostly, the
                   3539:             cumulative probability or probability to be dead is
                   3540:             constant (ie = 1) over time d, the difference is equal to
                   3541:             0.  out[s1][3] = savm[s1][3]: probability, being at state
                   3542:             s1 at precedent wave, to be dead a month before current
                   3543:             wave is equal to probability, being at state s1 at
                   3544:             precedent wave, to be dead at mont of the current
                   3545:             wave. Then the observed probability (that this person died)
                   3546:             is null according to current estimated parameter. In fact,
                   3547:             it should be very low but not zero otherwise the log go to
                   3548:             infinity.
                   3549:          */
1.183     brouard  3550: /* #ifdef INFINITYORIGINAL */
                   3551: /*         lli=log(out[s1][s2] - savm[s1][s2]); */
                   3552: /* #else */
                   3553: /*       if ((out[s1][s2] - savm[s1][s2]) < mytinydouble)  */
                   3554: /*         lli=log(mytinydouble); */
                   3555: /*       else */
                   3556: /*         lli=log(out[s1][s2] - savm[s1][s2]); */
                   3557: /* #endif */
1.226     brouard  3558:          lli=log(out[s1][s2] - savm[s1][s2]);
1.216     brouard  3559:          
1.226     brouard  3560:        } else if  ( s2==-1 ) { /* alive */
                   3561:          for (j=1,survp=0. ; j<=nlstate; j++) 
                   3562:            survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
                   3563:          /*survp += out[s1][j]; */
                   3564:          lli= log(survp);
                   3565:        }
                   3566:        else if  (s2==-4) { 
                   3567:          for (j=3,survp=0. ; j<=nlstate; j++)  
                   3568:            survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
                   3569:          lli= log(survp); 
                   3570:        } 
                   3571:        else if  (s2==-5) { 
                   3572:          for (j=1,survp=0. ; j<=2; j++)  
                   3573:            survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
                   3574:          lli= log(survp); 
                   3575:        } 
                   3576:        else{
                   3577:          lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */
                   3578:          /*  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 */
                   3579:        } 
                   3580:        /*lli=(1.+bbh)*log(out[s1][s2])- bbh*log(savm[s1][s2]);*/
                   3581:        /*if(lli ==000.0)*/
                   3582:        /*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); */
                   3583:        ipmx +=1;
                   3584:        sw += weight[i];
                   3585:        ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
                   3586:        /* if (lli < log(mytinydouble)){ */
                   3587:        /*   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); */
                   3588:        /*   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]); */
                   3589:        /* } */
                   3590:       } /* end of wave */
                   3591:     } /* end of individual */
                   3592:   }  else if(mle==2){
                   3593:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
                   3594:       for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i];
                   3595:       for(mi=1; mi<= wav[i]-1; mi++){
                   3596:        for (ii=1;ii<=nlstate+ndeath;ii++)
                   3597:          for (j=1;j<=nlstate+ndeath;j++){
                   3598:            oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   3599:            savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   3600:          }
                   3601:        for(d=0; d<=dh[mi][i]; d++){
                   3602:          newm=savm;
                   3603:          agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
                   3604:          cov[2]=agexact;
                   3605:          if(nagesqr==1)
                   3606:            cov[3]= agexact*agexact;
                   3607:          for (kk=1; kk<=cptcovage;kk++) {
                   3608:            cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact;
                   3609:          }
                   3610:          out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   3611:                       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   3612:          savm=oldm;
                   3613:          oldm=newm;
                   3614:        } /* end mult */
                   3615:       
                   3616:        s1=s[mw[mi][i]][i];
                   3617:        s2=s[mw[mi+1][i]][i];
                   3618:        bbh=(double)bh[mi][i]/(double)stepm; 
                   3619:        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 */
                   3620:        ipmx +=1;
                   3621:        sw += weight[i];
                   3622:        ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
                   3623:       } /* end of wave */
                   3624:     } /* end of individual */
                   3625:   }  else if(mle==3){  /* exponential inter-extrapolation */
                   3626:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
                   3627:       for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i];
                   3628:       for(mi=1; mi<= wav[i]-1; mi++){
                   3629:        for (ii=1;ii<=nlstate+ndeath;ii++)
                   3630:          for (j=1;j<=nlstate+ndeath;j++){
                   3631:            oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   3632:            savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   3633:          }
                   3634:        for(d=0; d<dh[mi][i]; d++){
                   3635:          newm=savm;
                   3636:          agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
                   3637:          cov[2]=agexact;
                   3638:          if(nagesqr==1)
                   3639:            cov[3]= agexact*agexact;
                   3640:          for (kk=1; kk<=cptcovage;kk++) {
                   3641:            cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact;
                   3642:          }
                   3643:          out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   3644:                       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   3645:          savm=oldm;
                   3646:          oldm=newm;
                   3647:        } /* end mult */
                   3648:       
                   3649:        s1=s[mw[mi][i]][i];
                   3650:        s2=s[mw[mi+1][i]][i];
                   3651:        bbh=(double)bh[mi][i]/(double)stepm; 
                   3652:        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 */
                   3653:        ipmx +=1;
                   3654:        sw += weight[i];
                   3655:        ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
                   3656:       } /* end of wave */
                   3657:     } /* end of individual */
                   3658:   }else if (mle==4){  /* ml=4 no inter-extrapolation */
                   3659:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
                   3660:       for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i];
                   3661:       for(mi=1; mi<= wav[i]-1; mi++){
                   3662:        for (ii=1;ii<=nlstate+ndeath;ii++)
                   3663:          for (j=1;j<=nlstate+ndeath;j++){
                   3664:            oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   3665:            savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   3666:          }
                   3667:        for(d=0; d<dh[mi][i]; d++){
                   3668:          newm=savm;
                   3669:          agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
                   3670:          cov[2]=agexact;
                   3671:          if(nagesqr==1)
                   3672:            cov[3]= agexact*agexact;
                   3673:          for (kk=1; kk<=cptcovage;kk++) {
                   3674:            cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact;
                   3675:          }
1.126     brouard  3676:        
1.226     brouard  3677:          out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   3678:                       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   3679:          savm=oldm;
                   3680:          oldm=newm;
                   3681:        } /* end mult */
                   3682:       
                   3683:        s1=s[mw[mi][i]][i];
                   3684:        s2=s[mw[mi+1][i]][i];
                   3685:        if( s2 > nlstate){ 
                   3686:          lli=log(out[s1][s2] - savm[s1][s2]);
                   3687:        } else if  ( s2==-1 ) { /* alive */
                   3688:          for (j=1,survp=0. ; j<=nlstate; j++) 
                   3689:            survp += out[s1][j];
                   3690:          lli= log(survp);
                   3691:        }else{
                   3692:          lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]); /* Original formula */
                   3693:        }
                   3694:        ipmx +=1;
                   3695:        sw += weight[i];
                   3696:        ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
1.126     brouard  3697: /*     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  3698:       } /* end of wave */
                   3699:     } /* end of individual */
                   3700:   }else{  /* ml=5 no inter-extrapolation no jackson =0.8a */
                   3701:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
                   3702:       for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i];
                   3703:       for(mi=1; mi<= wav[i]-1; mi++){
                   3704:        for (ii=1;ii<=nlstate+ndeath;ii++)
                   3705:          for (j=1;j<=nlstate+ndeath;j++){
                   3706:            oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   3707:            savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   3708:          }
                   3709:        for(d=0; d<dh[mi][i]; d++){
                   3710:          newm=savm;
                   3711:          agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
                   3712:          cov[2]=agexact;
                   3713:          if(nagesqr==1)
                   3714:            cov[3]= agexact*agexact;
                   3715:          for (kk=1; kk<=cptcovage;kk++) {
                   3716:            cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact;
                   3717:          }
1.126     brouard  3718:        
1.226     brouard  3719:          out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   3720:                       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   3721:          savm=oldm;
                   3722:          oldm=newm;
                   3723:        } /* end mult */
                   3724:       
                   3725:        s1=s[mw[mi][i]][i];
                   3726:        s2=s[mw[mi+1][i]][i];
                   3727:        lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]); /* Original formula */
                   3728:        ipmx +=1;
                   3729:        sw += weight[i];
                   3730:        ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
                   3731:        /*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]);*/
                   3732:       } /* end of wave */
                   3733:     } /* end of individual */
                   3734:   } /* End of if */
                   3735:   for(k=1,l=0.; k<=nlstate; k++) l += ll[k];
                   3736:   /* printf("l1=%f l2=%f ",ll[1],ll[2]); */
                   3737:   l= l*ipmx/sw; /* To get the same order of magnitude as if weight=1 for every body */
                   3738:   return -l;
1.126     brouard  3739: }
                   3740: 
                   3741: /*************** log-likelihood *************/
                   3742: double funcone( double *x)
                   3743: {
1.228     brouard  3744:   /* Same as func but slower because of a lot of printf and if */
1.126     brouard  3745:   int i, ii, j, k, mi, d, kk;
1.228     brouard  3746:   int ioffset=0;
1.131     brouard  3747:   double l, ll[NLSTATEMAX+1], cov[NCOVMAX+1];
1.126     brouard  3748:   double **out;
                   3749:   double lli; /* Individual log likelihood */
                   3750:   double llt;
                   3751:   int s1, s2;
1.228     brouard  3752:   int iv=0, iqv=0, itv=0, iqtv=0 ; /* Index of varying covariate, fixed quantitative cov, time varying covariate, quantitative time varying covariate */
                   3753: 
1.126     brouard  3754:   double bbh, survp;
1.187     brouard  3755:   double agexact;
1.214     brouard  3756:   double agebegin, ageend;
1.126     brouard  3757:   /*extern weight */
                   3758:   /* We are differentiating ll according to initial status */
                   3759:   /*  for (i=1;i<=npar;i++) printf("%f ", x[i]);*/
                   3760:   /*for(i=1;i<imx;i++) 
                   3761:     printf(" %d\n",s[4][i]);
                   3762:   */
                   3763:   cov[1]=1.;
                   3764: 
                   3765:   for(k=1; k<=nlstate; k++) ll[k]=0.;
1.224     brouard  3766:   ioffset=0;
                   3767:   for (i=1,ipmx=0, sw=0.; i<=imx; i++){
1.243     brouard  3768:     /* ioffset=2+nagesqr+cptcovage; */
                   3769:     ioffset=2+nagesqr;
1.232     brouard  3770:     /* Fixed */
1.224     brouard  3771:     /* for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i]; */
1.232     brouard  3772:     /* for (k=1; k<=ncoveff;k++){ /\* Simple and product fixed Dummy covariates without age* products *\/ */
                   3773:     for (k=1; k<=ncovf;k++){ /* Simple and product fixed covariates without age* products */
                   3774:       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)*/
                   3775: /*    cov[ioffset+TvarFind[1]]=covar[Tvar[TvarFind[1]]][i];  */
                   3776: /*    cov[2+6]=covar[Tvar[6]][i];  */
                   3777: /*    cov[2+6]=covar[2][i]; V2  */
                   3778: /*    cov[TvarFind[2]]=covar[Tvar[TvarFind[2]]][i];  */
                   3779: /*    cov[2+7]=covar[Tvar[7]][i];  */
                   3780: /*    cov[2+7]=covar[7][i]; V7=V1*V2  */
                   3781: /*    cov[TvarFind[3]]=covar[Tvar[TvarFind[3]]][i];  */
                   3782: /*    cov[2+9]=covar[Tvar[9]][i];  */
                   3783: /*    cov[2+9]=covar[1][i]; V1  */
1.225     brouard  3784:     }
1.232     brouard  3785:     /* for (k=1; k<=nqfveff;k++){ /\* Simple and product fixed Quantitative covariates without age* products *\/ */
                   3786:     /*   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?)*\/ */
                   3787:     /* } */
1.231     brouard  3788:     /* for(iqv=1; iqv <= nqfveff; iqv++){ /\* Quantitative fixed covariates *\/ */
                   3789:     /*   cov[++ioffset]=coqvar[Tvar[iqv]][i]; /\* Only V2 k=6 and V1*V2 7 *\/ */
                   3790:     /* } */
1.225     brouard  3791:     
1.233     brouard  3792: 
                   3793:     for(mi=1; mi<= wav[i]-1; mi++){  /* Varying with waves */
1.232     brouard  3794:     /* Wave varying (but not age varying) */
                   3795:       for(k=1; k <= ncovv ; k++){ /* Varying  covariates (single and product but no age )*/
1.242     brouard  3796:        /* cov[ioffset+TvarVind[k]]=cotvar[mw[mi][i]][Tvar[TvarVind[k]]][i]; */
                   3797:        cov[ioffset+TvarVind[k]]=cotvar[mw[mi][i]][Tvar[TvarVind[k]]-ncovcol-nqv][i];
                   3798:       }
1.232     brouard  3799:       /* for(itv=1; itv <= ntveff; itv++){ /\* Varying dummy covariates (single??)*\/ */
1.242     brouard  3800:       /* iv= Tvar[Tmodelind[ioffset-2-nagesqr-cptcovage+itv]]-ncovcol-nqv; /\* Counting the # varying covariate from 1 to ntveff *\/ */
                   3801:       /* cov[ioffset+iv]=cotvar[mw[mi][i]][iv][i]; */
                   3802:       /* k=ioffset-2-nagesqr-cptcovage+itv; /\* position in simple model *\/ */
                   3803:       /* cov[ioffset+itv]=cotvar[mw[mi][i]][TmodelInvind[itv]][i]; */
                   3804:       /* 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  3805:       /* for(iqtv=1; iqtv <= nqtveff; iqtv++){ /\* Varying quantitatives covariates *\/ */
1.242     brouard  3806:       /*       iv=TmodelInvQind[iqtv]; /\* Counting the # varying covariate from 1 to ntveff *\/ */
                   3807:       /*       /\* 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]); *\/ */
                   3808:       /*       cov[ioffset+ntveff+iqtv]=cotqvar[mw[mi][i]][TmodelInvQind[iqtv]][i]; */
1.232     brouard  3809:       /* } */
1.126     brouard  3810:       for (ii=1;ii<=nlstate+ndeath;ii++)
1.242     brouard  3811:        for (j=1;j<=nlstate+ndeath;j++){
                   3812:          oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   3813:          savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   3814:        }
1.214     brouard  3815:       
                   3816:       agebegin=agev[mw[mi][i]][i]; /* Age at beginning of effective wave */
                   3817:       ageend=agev[mw[mi][i]][i] + (dh[mi][i])*stepm/YEARM; /* Age at end of effective wave and at the end of transition */
                   3818:       for(d=0; d<dh[mi][i]; d++){  /* Delay between two effective waves */
1.247     brouard  3819:       /* for(d=0; d<=0; d++){  /\* Delay between two effective waves Only one matrix to speed up*\/ */
1.242     brouard  3820:        /*dh[m][i] or dh[mw[mi][i]][i] is the delay between two effective waves m=mw[mi][i]
                   3821:          and mw[mi+1][i]. dh depends on stepm.*/
                   3822:        newm=savm;
1.247     brouard  3823:        agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;  /* Here d is needed */
1.242     brouard  3824:        cov[2]=agexact;
                   3825:        if(nagesqr==1)
                   3826:          cov[3]= agexact*agexact;
                   3827:        for (kk=1; kk<=cptcovage;kk++) {
                   3828:          if(!FixedV[Tvar[Tage[kk]]])
                   3829:            cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact;
                   3830:          else
                   3831:            cov[Tage[kk]+2+nagesqr]=cotvar[mw[mi][i]][Tvar[Tage[kk]]-ncovcol-nqv][i]*agexact;
                   3832:        }
                   3833:        /* printf("i=%d,mi=%d,d=%d,mw[mi][i]=%d\n",i, mi,d,mw[mi][i]); */
                   3834:        /* savm=pmij(pmmij,cov,ncovmodel,x,nlstate); */
                   3835:        out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   3836:                     1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   3837:        /* out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath, */
                   3838:        /*           1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate)); */
                   3839:        savm=oldm;
                   3840:        oldm=newm;
1.126     brouard  3841:       } /* end mult */
                   3842:       
                   3843:       s1=s[mw[mi][i]][i];
                   3844:       s2=s[mw[mi+1][i]][i];
1.217     brouard  3845:       /* if(s2==-1){ */
1.268     brouard  3846:       /*       printf(" ERROR s1=%d, s2=%d i=%d \n", s1, s2, i); */
1.217     brouard  3847:       /*       /\* exit(1); *\/ */
                   3848:       /* } */
1.126     brouard  3849:       bbh=(double)bh[mi][i]/(double)stepm; 
                   3850:       /* bias is positive if real duration
                   3851:        * is higher than the multiple of stepm and negative otherwise.
                   3852:        */
                   3853:       if( s2 > nlstate && (mle <5) ){  /* Jackson */
1.242     brouard  3854:        lli=log(out[s1][s2] - savm[s1][s2]);
1.216     brouard  3855:       } else if  ( s2==-1 ) { /* alive */
1.242     brouard  3856:        for (j=1,survp=0. ; j<=nlstate; j++) 
                   3857:          survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
                   3858:        lli= log(survp);
1.126     brouard  3859:       }else if (mle==1){
1.242     brouard  3860:        lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */
1.126     brouard  3861:       } else if(mle==2){
1.242     brouard  3862:        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  3863:       } else if(mle==3){  /* exponential inter-extrapolation */
1.242     brouard  3864:        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  3865:       } else if (mle==4){  /* mle=4 no inter-extrapolation */
1.242     brouard  3866:        lli=log(out[s1][s2]); /* Original formula */
1.136     brouard  3867:       } else{  /* mle=0 back to 1 */
1.242     brouard  3868:        lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */
                   3869:        /*lli=log(out[s1][s2]); */ /* Original formula */
1.126     brouard  3870:       } /* End of if */
                   3871:       ipmx +=1;
                   3872:       sw += weight[i];
                   3873:       ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
1.132     brouard  3874:       /*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  3875:       if(globpr){
1.246     brouard  3876:        fprintf(ficresilk,"%09ld %6.1f %6.1f %6d %2d %2d %2d %2d %3d %15.6f %8.4f %8.3f\
1.126     brouard  3877:  %11.6f %11.6f %11.6f ", \
1.242     brouard  3878:                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  3879:                2*weight[i]*lli,(s2==-1? -1: out[s1][s2]),(s2==-1? -1: savm[s1][s2]));
1.242     brouard  3880:        for(k=1,llt=0.,l=0.; k<=nlstate; k++){
                   3881:          llt +=ll[k]*gipmx/gsw;
                   3882:          fprintf(ficresilk," %10.6f",-ll[k]*gipmx/gsw);
                   3883:        }
                   3884:        fprintf(ficresilk," %10.6f\n", -llt);
1.126     brouard  3885:       }
1.232     brouard  3886:        } /* end of wave */
                   3887: } /* end of individual */
                   3888: for(k=1,l=0.; k<=nlstate; k++) l += ll[k];
                   3889: /* printf("l1=%f l2=%f ",ll[1],ll[2]); */
                   3890: l= l*ipmx/sw; /* To get the same order of magnitude as if weight=1 for every body */
                   3891: if(globpr==0){ /* First time we count the contributions and weights */
                   3892:        gipmx=ipmx;
                   3893:        gsw=sw;
                   3894: }
                   3895: return -l;
1.126     brouard  3896: }
                   3897: 
                   3898: 
                   3899: /*************** function likelione ***********/
1.292     brouard  3900: void likelione(FILE *ficres,double p[], int npar, int nlstate, int *globpri, long *ipmx, double *sw, double *fretone, double (*func)(double []))
1.126     brouard  3901: {
                   3902:   /* This routine should help understanding what is done with 
                   3903:      the selection of individuals/waves and
                   3904:      to check the exact contribution to the likelihood.
                   3905:      Plotting could be done.
                   3906:    */
                   3907:   int k;
                   3908: 
                   3909:   if(*globpri !=0){ /* Just counts and sums, no printings */
1.201     brouard  3910:     strcpy(fileresilk,"ILK_"); 
1.202     brouard  3911:     strcat(fileresilk,fileresu);
1.126     brouard  3912:     if((ficresilk=fopen(fileresilk,"w"))==NULL) {
                   3913:       printf("Problem with resultfile: %s\n", fileresilk);
                   3914:       fprintf(ficlog,"Problem with resultfile: %s\n", fileresilk);
                   3915:     }
1.214     brouard  3916:     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");
                   3917:     fprintf(ficresilk, "#num_i ageb agend i s1 s2 mi mw dh likeli weight %%weight 2wlli out sav ");
1.126     brouard  3918:     /*         i,s1,s2,mi,mw[mi][i],dh[mi][i],exp(lli),weight[i],2*weight[i]*lli,out[s1][s2],savm[s1][s2]); */
                   3919:     for(k=1; k<=nlstate; k++) 
                   3920:       fprintf(ficresilk," -2*gipw/gsw*weight*ll[%d]++",k);
                   3921:     fprintf(ficresilk," -2*gipw/gsw*weight*ll(total)\n");
                   3922:   }
                   3923: 
1.292     brouard  3924:   *fretone=(*func)(p);
1.126     brouard  3925:   if(*globpri !=0){
                   3926:     fclose(ficresilk);
1.205     brouard  3927:     if (mle ==0)
                   3928:       fprintf(fichtm,"\n<br>File of contributions to the likelihood computed with initial parameters and mle = %d.",mle);
                   3929:     else if(mle >=1)
                   3930:       fprintf(fichtm,"\n<br>File of contributions to the likelihood computed with optimized parameters mle = %d.",mle);
                   3931:     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  3932:     fprintf(fichtm,"\n<br>Equation of the model: <b>model=1+age+%s</b><br>\n",model); 
1.208     brouard  3933:       
                   3934:     for (k=1; k<= nlstate ; k++) {
1.211     brouard  3935:       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  3936: <img src=\"%s-p%dj.png\">",k,k,subdirf2(optionfilefiname,"ILK_"),k,subdirf2(optionfilefiname,"ILK_"),k,subdirf2(optionfilefiname,"ILK_"),k);
                   3937:     }
1.207     brouard  3938:     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  3939: <img src=\"%s-ori.png\">",subdirf2(optionfilefiname,"ILK_"),subdirf2(optionfilefiname,"ILK_"),subdirf2(optionfilefiname,"ILK_"));
1.207     brouard  3940:     fprintf(fichtm,"<br>- and by state of destination <a href=\"%s-dest.png\">%s-dest.png</a><br> \
1.204     brouard  3941: <img src=\"%s-dest.png\">",subdirf2(optionfilefiname,"ILK_"),subdirf2(optionfilefiname,"ILK_"),subdirf2(optionfilefiname,"ILK_"));
1.207     brouard  3942:     fflush(fichtm);
1.205     brouard  3943:   }
1.126     brouard  3944:   return;
                   3945: }
                   3946: 
                   3947: 
                   3948: /*********** Maximum Likelihood Estimation ***************/
                   3949: 
                   3950: void mlikeli(FILE *ficres,double p[], int npar, int ncovmodel, int nlstate, double ftol, double (*func)(double []))
                   3951: {
1.165     brouard  3952:   int i,j, iter=0;
1.126     brouard  3953:   double **xi;
                   3954:   double fret;
                   3955:   double fretone; /* Only one call to likelihood */
                   3956:   /*  char filerespow[FILENAMELENGTH];*/
1.162     brouard  3957: 
                   3958: #ifdef NLOPT
                   3959:   int creturn;
                   3960:   nlopt_opt opt;
                   3961:   /* double lb[9] = { -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL }; /\* lower bounds *\/ */
                   3962:   double *lb;
                   3963:   double minf; /* the minimum objective value, upon return */
                   3964:   double * p1; /* Shifted parameters from 0 instead of 1 */
                   3965:   myfunc_data dinst, *d = &dinst;
                   3966: #endif
                   3967: 
                   3968: 
1.126     brouard  3969:   xi=matrix(1,npar,1,npar);
                   3970:   for (i=1;i<=npar;i++)
                   3971:     for (j=1;j<=npar;j++)
                   3972:       xi[i][j]=(i==j ? 1.0 : 0.0);
                   3973:   printf("Powell\n");  fprintf(ficlog,"Powell\n");
1.201     brouard  3974:   strcpy(filerespow,"POW_"); 
1.126     brouard  3975:   strcat(filerespow,fileres);
                   3976:   if((ficrespow=fopen(filerespow,"w"))==NULL) {
                   3977:     printf("Problem with resultfile: %s\n", filerespow);
                   3978:     fprintf(ficlog,"Problem with resultfile: %s\n", filerespow);
                   3979:   }
                   3980:   fprintf(ficrespow,"# Powell\n# iter -2*LL");
                   3981:   for (i=1;i<=nlstate;i++)
                   3982:     for(j=1;j<=nlstate+ndeath;j++)
                   3983:       if(j!=i)fprintf(ficrespow," p%1d%1d",i,j);
                   3984:   fprintf(ficrespow,"\n");
1.162     brouard  3985: #ifdef POWELL
1.126     brouard  3986:   powell(p,xi,npar,ftol,&iter,&fret,func);
1.162     brouard  3987: #endif
1.126     brouard  3988: 
1.162     brouard  3989: #ifdef NLOPT
                   3990: #ifdef NEWUOA
                   3991:   opt = nlopt_create(NLOPT_LN_NEWUOA,npar);
                   3992: #else
                   3993:   opt = nlopt_create(NLOPT_LN_BOBYQA,npar);
                   3994: #endif
                   3995:   lb=vector(0,npar-1);
                   3996:   for (i=0;i<npar;i++) lb[i]= -HUGE_VAL;
                   3997:   nlopt_set_lower_bounds(opt, lb);
                   3998:   nlopt_set_initial_step1(opt, 0.1);
                   3999:   
                   4000:   p1= (p+1); /*  p *(p+1)@8 and p *(p1)@8 are equal p1[0]=p[1] */
                   4001:   d->function = func;
                   4002:   printf(" Func %.12lf \n",myfunc(npar,p1,NULL,d));
                   4003:   nlopt_set_min_objective(opt, myfunc, d);
                   4004:   nlopt_set_xtol_rel(opt, ftol);
                   4005:   if ((creturn=nlopt_optimize(opt, p1, &minf)) < 0) {
                   4006:     printf("nlopt failed! %d\n",creturn); 
                   4007:   }
                   4008:   else {
                   4009:     printf("found minimum after %d evaluations (NLOPT=%d)\n", countcallfunc ,NLOPT);
                   4010:     printf("found minimum at f(%g,%g) = %0.10g\n", p[0], p[1], minf);
                   4011:     iter=1; /* not equal */
                   4012:   }
                   4013:   nlopt_destroy(opt);
                   4014: #endif
1.126     brouard  4015:   free_matrix(xi,1,npar,1,npar);
                   4016:   fclose(ficrespow);
1.203     brouard  4017:   printf("\n#Number of iterations & function calls = %d & %d, -2 Log likelihood = %.12f\n",iter, countcallfunc,func(p));
                   4018:   fprintf(ficlog,"\n#Number of iterations & function calls = %d & %d, -2 Log likelihood = %.12f\n",iter, countcallfunc,func(p));
1.180     brouard  4019:   fprintf(ficres,"#Number of iterations & function calls = %d & %d, -2 Log likelihood = %.12f\n",iter, countcallfunc,func(p));
1.126     brouard  4020: 
                   4021: }
                   4022: 
                   4023: /**** Computes Hessian and covariance matrix ***/
1.203     brouard  4024: void hesscov(double **matcov, double **hess, double p[], int npar, double delti[], double ftolhess, double (*func)(double []))
1.126     brouard  4025: {
                   4026:   double  **a,**y,*x,pd;
1.203     brouard  4027:   /* double **hess; */
1.164     brouard  4028:   int i, j;
1.126     brouard  4029:   int *indx;
                   4030: 
                   4031:   double hessii(double p[], double delta, int theta, double delti[],double (*func)(double []),int npar);
1.203     brouard  4032:   double hessij(double p[], double **hess, double delti[], int i, int j,double (*func)(double []),int npar);
1.126     brouard  4033:   void lubksb(double **a, int npar, int *indx, double b[]) ;
                   4034:   void ludcmp(double **a, int npar, int *indx, double *d) ;
                   4035:   double gompertz(double p[]);
1.203     brouard  4036:   /* hess=matrix(1,npar,1,npar); */
1.126     brouard  4037: 
                   4038:   printf("\nCalculation of the hessian matrix. Wait...\n");
                   4039:   fprintf(ficlog,"\nCalculation of the hessian matrix. Wait...\n");
                   4040:   for (i=1;i<=npar;i++){
1.203     brouard  4041:     printf("%d-",i);fflush(stdout);
                   4042:     fprintf(ficlog,"%d-",i);fflush(ficlog);
1.126     brouard  4043:    
                   4044:      hess[i][i]=hessii(p,ftolhess,i,delti,func,npar);
                   4045:     
                   4046:     /*  printf(" %f ",p[i]);
                   4047:        printf(" %lf %lf %lf",hess[i][i],ftolhess,delti[i]);*/
                   4048:   }
                   4049:   
                   4050:   for (i=1;i<=npar;i++) {
                   4051:     for (j=1;j<=npar;j++)  {
                   4052:       if (j>i) { 
1.203     brouard  4053:        printf(".%d-%d",i,j);fflush(stdout);
                   4054:        fprintf(ficlog,".%d-%d",i,j);fflush(ficlog);
                   4055:        hess[i][j]=hessij(p,hess, delti,i,j,func,npar);
1.126     brouard  4056:        
                   4057:        hess[j][i]=hess[i][j];    
                   4058:        /*printf(" %lf ",hess[i][j]);*/
                   4059:       }
                   4060:     }
                   4061:   }
                   4062:   printf("\n");
                   4063:   fprintf(ficlog,"\n");
                   4064: 
                   4065:   printf("\nInverting the hessian to get the covariance matrix. Wait...\n");
                   4066:   fprintf(ficlog,"\nInverting the hessian to get the covariance matrix. Wait...\n");
                   4067:   
                   4068:   a=matrix(1,npar,1,npar);
                   4069:   y=matrix(1,npar,1,npar);
                   4070:   x=vector(1,npar);
                   4071:   indx=ivector(1,npar);
                   4072:   for (i=1;i<=npar;i++)
                   4073:     for (j=1;j<=npar;j++) a[i][j]=hess[i][j];
                   4074:   ludcmp(a,npar,indx,&pd);
                   4075: 
                   4076:   for (j=1;j<=npar;j++) {
                   4077:     for (i=1;i<=npar;i++) x[i]=0;
                   4078:     x[j]=1;
                   4079:     lubksb(a,npar,indx,x);
                   4080:     for (i=1;i<=npar;i++){ 
                   4081:       matcov[i][j]=x[i];
                   4082:     }
                   4083:   }
                   4084: 
                   4085:   printf("\n#Hessian matrix#\n");
                   4086:   fprintf(ficlog,"\n#Hessian matrix#\n");
                   4087:   for (i=1;i<=npar;i++) { 
                   4088:     for (j=1;j<=npar;j++) { 
1.203     brouard  4089:       printf("%.6e ",hess[i][j]);
                   4090:       fprintf(ficlog,"%.6e ",hess[i][j]);
1.126     brouard  4091:     }
                   4092:     printf("\n");
                   4093:     fprintf(ficlog,"\n");
                   4094:   }
                   4095: 
1.203     brouard  4096:   /* printf("\n#Covariance matrix#\n"); */
                   4097:   /* fprintf(ficlog,"\n#Covariance matrix#\n"); */
                   4098:   /* for (i=1;i<=npar;i++) {  */
                   4099:   /*   for (j=1;j<=npar;j++) {  */
                   4100:   /*     printf("%.6e ",matcov[i][j]); */
                   4101:   /*     fprintf(ficlog,"%.6e ",matcov[i][j]); */
                   4102:   /*   } */
                   4103:   /*   printf("\n"); */
                   4104:   /*   fprintf(ficlog,"\n"); */
                   4105:   /* } */
                   4106: 
1.126     brouard  4107:   /* Recompute Inverse */
1.203     brouard  4108:   /* for (i=1;i<=npar;i++) */
                   4109:   /*   for (j=1;j<=npar;j++) a[i][j]=matcov[i][j]; */
                   4110:   /* ludcmp(a,npar,indx,&pd); */
                   4111: 
                   4112:   /*  printf("\n#Hessian matrix recomputed#\n"); */
                   4113: 
                   4114:   /* for (j=1;j<=npar;j++) { */
                   4115:   /*   for (i=1;i<=npar;i++) x[i]=0; */
                   4116:   /*   x[j]=1; */
                   4117:   /*   lubksb(a,npar,indx,x); */
                   4118:   /*   for (i=1;i<=npar;i++){  */
                   4119:   /*     y[i][j]=x[i]; */
                   4120:   /*     printf("%.3e ",y[i][j]); */
                   4121:   /*     fprintf(ficlog,"%.3e ",y[i][j]); */
                   4122:   /*   } */
                   4123:   /*   printf("\n"); */
                   4124:   /*   fprintf(ficlog,"\n"); */
                   4125:   /* } */
                   4126: 
                   4127:   /* Verifying the inverse matrix */
                   4128: #ifdef DEBUGHESS
                   4129:   y=matprod2(y,hess,1,npar,1,npar,1,npar,matcov);
1.126     brouard  4130: 
1.203     brouard  4131:    printf("\n#Verification: multiplying the matrix of covariance by the Hessian matrix, should be unity:#\n");
                   4132:    fprintf(ficlog,"\n#Verification: multiplying the matrix of covariance by the Hessian matrix. Should be unity:#\n");
1.126     brouard  4133: 
                   4134:   for (j=1;j<=npar;j++) {
                   4135:     for (i=1;i<=npar;i++){ 
1.203     brouard  4136:       printf("%.2f ",y[i][j]);
                   4137:       fprintf(ficlog,"%.2f ",y[i][j]);
1.126     brouard  4138:     }
                   4139:     printf("\n");
                   4140:     fprintf(ficlog,"\n");
                   4141:   }
1.203     brouard  4142: #endif
1.126     brouard  4143: 
                   4144:   free_matrix(a,1,npar,1,npar);
                   4145:   free_matrix(y,1,npar,1,npar);
                   4146:   free_vector(x,1,npar);
                   4147:   free_ivector(indx,1,npar);
1.203     brouard  4148:   /* free_matrix(hess,1,npar,1,npar); */
1.126     brouard  4149: 
                   4150: 
                   4151: }
                   4152: 
                   4153: /*************** hessian matrix ****************/
                   4154: double hessii(double x[], double delta, int theta, double delti[], double (*func)(double []), int npar)
1.203     brouard  4155: { /* Around values of x, computes the function func and returns the scales delti and hessian */
1.126     brouard  4156:   int i;
                   4157:   int l=1, lmax=20;
1.203     brouard  4158:   double k1,k2, res, fx;
1.132     brouard  4159:   double p2[MAXPARM+1]; /* identical to x */
1.126     brouard  4160:   double delt=0.0001, delts, nkhi=10.,nkhif=1., khi=1.e-4;
                   4161:   int k=0,kmax=10;
                   4162:   double l1;
                   4163: 
                   4164:   fx=func(x);
                   4165:   for (i=1;i<=npar;i++) p2[i]=x[i];
1.145     brouard  4166:   for(l=0 ; l <=lmax; l++){  /* Enlarging the zone around the Maximum */
1.126     brouard  4167:     l1=pow(10,l);
                   4168:     delts=delt;
                   4169:     for(k=1 ; k <kmax; k=k+1){
                   4170:       delt = delta*(l1*k);
                   4171:       p2[theta]=x[theta] +delt;
1.145     brouard  4172:       k1=func(p2)-fx;   /* Might be negative if too close to the theoretical maximum */
1.126     brouard  4173:       p2[theta]=x[theta]-delt;
                   4174:       k2=func(p2)-fx;
                   4175:       /*res= (k1-2.0*fx+k2)/delt/delt; */
1.203     brouard  4176:       res= (k1+k2)/delt/delt/2.; /* Divided by 2 because L and not 2*L */
1.126     brouard  4177:       
1.203     brouard  4178: #ifdef DEBUGHESSII
1.126     brouard  4179:       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);
                   4180:       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);
                   4181: #endif
                   4182:       /*if(fabs(k1-2.0*fx+k2) <1.e-13){ */
                   4183:       if((k1 <khi/nkhi/2.) || (k2 <khi/nkhi/2.)){
                   4184:        k=kmax;
                   4185:       }
                   4186:       else if((k1 >khi/nkhif) || (k2 >khi/nkhif)){ /* Keeps lastvalue before 3.84/2 KHI2 5% 1d.f. */
1.164     brouard  4187:        k=kmax; l=lmax*10;
1.126     brouard  4188:       }
                   4189:       else if((k1 >khi/nkhi) || (k2 >khi/nkhi)){ 
                   4190:        delts=delt;
                   4191:       }
1.203     brouard  4192:     } /* End loop k */
1.126     brouard  4193:   }
                   4194:   delti[theta]=delts;
                   4195:   return res; 
                   4196:   
                   4197: }
                   4198: 
1.203     brouard  4199: double hessij( double x[], double **hess, double delti[], int thetai,int thetaj,double (*func)(double []),int npar)
1.126     brouard  4200: {
                   4201:   int i;
1.164     brouard  4202:   int l=1, lmax=20;
1.126     brouard  4203:   double k1,k2,k3,k4,res,fx;
1.132     brouard  4204:   double p2[MAXPARM+1];
1.203     brouard  4205:   int k, kmax=1;
                   4206:   double v1, v2, cv12, lc1, lc2;
1.208     brouard  4207: 
                   4208:   int firstime=0;
1.203     brouard  4209:   
1.126     brouard  4210:   fx=func(x);
1.203     brouard  4211:   for (k=1; k<=kmax; k=k+10) {
1.126     brouard  4212:     for (i=1;i<=npar;i++) p2[i]=x[i];
1.203     brouard  4213:     p2[thetai]=x[thetai]+delti[thetai]*k;
                   4214:     p2[thetaj]=x[thetaj]+delti[thetaj]*k;
1.126     brouard  4215:     k1=func(p2)-fx;
                   4216:   
1.203     brouard  4217:     p2[thetai]=x[thetai]+delti[thetai]*k;
                   4218:     p2[thetaj]=x[thetaj]-delti[thetaj]*k;
1.126     brouard  4219:     k2=func(p2)-fx;
                   4220:   
1.203     brouard  4221:     p2[thetai]=x[thetai]-delti[thetai]*k;
                   4222:     p2[thetaj]=x[thetaj]+delti[thetaj]*k;
1.126     brouard  4223:     k3=func(p2)-fx;
                   4224:   
1.203     brouard  4225:     p2[thetai]=x[thetai]-delti[thetai]*k;
                   4226:     p2[thetaj]=x[thetaj]-delti[thetaj]*k;
1.126     brouard  4227:     k4=func(p2)-fx;
1.203     brouard  4228:     res=(k1-k2-k3+k4)/4.0/delti[thetai]/k/delti[thetaj]/k/2.; /* Because of L not 2*L */
                   4229:     if(k1*k2*k3*k4 <0.){
1.208     brouard  4230:       firstime=1;
1.203     brouard  4231:       kmax=kmax+10;
1.208     brouard  4232:     }
                   4233:     if(kmax >=10 || firstime ==1){
1.246     brouard  4234:       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);
                   4235:       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  4236:       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);
                   4237:       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);
                   4238:     }
                   4239: #ifdef DEBUGHESSIJ
                   4240:     v1=hess[thetai][thetai];
                   4241:     v2=hess[thetaj][thetaj];
                   4242:     cv12=res;
                   4243:     /* Computing eigen value of Hessian matrix */
                   4244:     lc1=((v1+v2)+sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
                   4245:     lc2=((v1+v2)-sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
                   4246:     if ((lc2 <0) || (lc1 <0) ){
                   4247:       printf("Warning: sub Hessian matrix '%d%d' does not have positive eigen values \n",thetai,thetaj);
                   4248:       fprintf(ficlog, "Warning: sub Hessian matrix '%d%d' does not have positive eigen values \n",thetai,thetaj);
                   4249:       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);
                   4250:       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);
                   4251:     }
1.126     brouard  4252: #endif
                   4253:   }
                   4254:   return res;
                   4255: }
                   4256: 
1.203     brouard  4257:     /* Not done yet: Was supposed to fix if not exactly at the maximum */
                   4258: /* double hessij( double x[], double delti[], int thetai,int thetaj,double (*func)(double []),int npar) */
                   4259: /* { */
                   4260: /*   int i; */
                   4261: /*   int l=1, lmax=20; */
                   4262: /*   double k1,k2,k3,k4,res,fx; */
                   4263: /*   double p2[MAXPARM+1]; */
                   4264: /*   double delt=0.0001, delts, nkhi=10.,nkhif=1., khi=1.e-4; */
                   4265: /*   int k=0,kmax=10; */
                   4266: /*   double l1; */
                   4267:   
                   4268: /*   fx=func(x); */
                   4269: /*   for(l=0 ; l <=lmax; l++){  /\* Enlarging the zone around the Maximum *\/ */
                   4270: /*     l1=pow(10,l); */
                   4271: /*     delts=delt; */
                   4272: /*     for(k=1 ; k <kmax; k=k+1){ */
                   4273: /*       delt = delti*(l1*k); */
                   4274: /*       for (i=1;i<=npar;i++) p2[i]=x[i]; */
                   4275: /*       p2[thetai]=x[thetai]+delti[thetai]/k; */
                   4276: /*       p2[thetaj]=x[thetaj]+delti[thetaj]/k; */
                   4277: /*       k1=func(p2)-fx; */
                   4278:       
                   4279: /*       p2[thetai]=x[thetai]+delti[thetai]/k; */
                   4280: /*       p2[thetaj]=x[thetaj]-delti[thetaj]/k; */
                   4281: /*       k2=func(p2)-fx; */
                   4282:       
                   4283: /*       p2[thetai]=x[thetai]-delti[thetai]/k; */
                   4284: /*       p2[thetaj]=x[thetaj]+delti[thetaj]/k; */
                   4285: /*       k3=func(p2)-fx; */
                   4286:       
                   4287: /*       p2[thetai]=x[thetai]-delti[thetai]/k; */
                   4288: /*       p2[thetaj]=x[thetaj]-delti[thetaj]/k; */
                   4289: /*       k4=func(p2)-fx; */
                   4290: /*       res=(k1-k2-k3+k4)/4.0/delti[thetai]*k/delti[thetaj]*k/2.; /\* Because of L not 2*L *\/ */
                   4291: /* #ifdef DEBUGHESSIJ */
                   4292: /*       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); */
                   4293: /*       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); */
                   4294: /* #endif */
                   4295: /*       if((k1 <khi/nkhi/2.) || (k2 <khi/nkhi/2.)|| (k4 <khi/nkhi/2.)|| (k4 <khi/nkhi/2.)){ */
                   4296: /*     k=kmax; */
                   4297: /*       } */
                   4298: /*       else if((k1 >khi/nkhif) || (k2 >khi/nkhif) || (k4 >khi/nkhif) || (k4 >khi/nkhif)){ /\* Keeps lastvalue before 3.84/2 KHI2 5% 1d.f. *\/ */
                   4299: /*     k=kmax; l=lmax*10; */
                   4300: /*       } */
                   4301: /*       else if((k1 >khi/nkhi) || (k2 >khi/nkhi)){  */
                   4302: /*     delts=delt; */
                   4303: /*       } */
                   4304: /*     } /\* End loop k *\/ */
                   4305: /*   } */
                   4306: /*   delti[theta]=delts; */
                   4307: /*   return res;  */
                   4308: /* } */
                   4309: 
                   4310: 
1.126     brouard  4311: /************** Inverse of matrix **************/
                   4312: void ludcmp(double **a, int n, int *indx, double *d) 
                   4313: { 
                   4314:   int i,imax,j,k; 
                   4315:   double big,dum,sum,temp; 
                   4316:   double *vv; 
                   4317:  
                   4318:   vv=vector(1,n); 
                   4319:   *d=1.0; 
                   4320:   for (i=1;i<=n;i++) { 
                   4321:     big=0.0; 
                   4322:     for (j=1;j<=n;j++) 
                   4323:       if ((temp=fabs(a[i][j])) > big) big=temp; 
1.256     brouard  4324:     if (big == 0.0){
                   4325:       printf(" Singular Hessian matrix at row %d:\n",i);
                   4326:       for (j=1;j<=n;j++) {
                   4327:        printf(" a[%d][%d]=%f,",i,j,a[i][j]);
                   4328:        fprintf(ficlog," a[%d][%d]=%f,",i,j,a[i][j]);
                   4329:       }
                   4330:       fflush(ficlog);
                   4331:       fclose(ficlog);
                   4332:       nrerror("Singular matrix in routine ludcmp"); 
                   4333:     }
1.126     brouard  4334:     vv[i]=1.0/big; 
                   4335:   } 
                   4336:   for (j=1;j<=n;j++) { 
                   4337:     for (i=1;i<j;i++) { 
                   4338:       sum=a[i][j]; 
                   4339:       for (k=1;k<i;k++) sum -= a[i][k]*a[k][j]; 
                   4340:       a[i][j]=sum; 
                   4341:     } 
                   4342:     big=0.0; 
                   4343:     for (i=j;i<=n;i++) { 
                   4344:       sum=a[i][j]; 
                   4345:       for (k=1;k<j;k++) 
                   4346:        sum -= a[i][k]*a[k][j]; 
                   4347:       a[i][j]=sum; 
                   4348:       if ( (dum=vv[i]*fabs(sum)) >= big) { 
                   4349:        big=dum; 
                   4350:        imax=i; 
                   4351:       } 
                   4352:     } 
                   4353:     if (j != imax) { 
                   4354:       for (k=1;k<=n;k++) { 
                   4355:        dum=a[imax][k]; 
                   4356:        a[imax][k]=a[j][k]; 
                   4357:        a[j][k]=dum; 
                   4358:       } 
                   4359:       *d = -(*d); 
                   4360:       vv[imax]=vv[j]; 
                   4361:     } 
                   4362:     indx[j]=imax; 
                   4363:     if (a[j][j] == 0.0) a[j][j]=TINY; 
                   4364:     if (j != n) { 
                   4365:       dum=1.0/(a[j][j]); 
                   4366:       for (i=j+1;i<=n;i++) a[i][j] *= dum; 
                   4367:     } 
                   4368:   } 
                   4369:   free_vector(vv,1,n);  /* Doesn't work */
                   4370: ;
                   4371: } 
                   4372: 
                   4373: void lubksb(double **a, int n, int *indx, double b[]) 
                   4374: { 
                   4375:   int i,ii=0,ip,j; 
                   4376:   double sum; 
                   4377:  
                   4378:   for (i=1;i<=n;i++) { 
                   4379:     ip=indx[i]; 
                   4380:     sum=b[ip]; 
                   4381:     b[ip]=b[i]; 
                   4382:     if (ii) 
                   4383:       for (j=ii;j<=i-1;j++) sum -= a[i][j]*b[j]; 
                   4384:     else if (sum) ii=i; 
                   4385:     b[i]=sum; 
                   4386:   } 
                   4387:   for (i=n;i>=1;i--) { 
                   4388:     sum=b[i]; 
                   4389:     for (j=i+1;j<=n;j++) sum -= a[i][j]*b[j]; 
                   4390:     b[i]=sum/a[i][i]; 
                   4391:   } 
                   4392: } 
                   4393: 
                   4394: void pstamp(FILE *fichier)
                   4395: {
1.196     brouard  4396:   fprintf(fichier,"# %s.%s\n#IMaCh version %s, %s\n#%s\n# %s", optionfilefiname,optionfilext,version,copyright, fullversion, strstart);
1.126     brouard  4397: }
                   4398: 
1.253     brouard  4399: 
                   4400: 
1.126     brouard  4401: /************ Frequencies ********************/
1.251     brouard  4402: void  freqsummary(char fileres[], double p[], double pstart[], int iagemin, int iagemax, int **s, double **agev, int nlstate, int imx, \
1.226     brouard  4403:                  int *Tvaraff, int *invalidvarcomb, int **nbcode, int *ncodemax,double **mint,double **anint, char strstart[], \
                   4404:                  int firstpass,  int lastpass, int stepm, int weightopt, char model[])
1.250     brouard  4405: {  /* Some frequencies as well as proposing some starting values */
1.226     brouard  4406:   
1.265     brouard  4407:   int i, m, jk, j1, bool, z1,j, nj, nl, k, iv, jj=0, s1=1, s2=1;
1.226     brouard  4408:   int iind=0, iage=0;
                   4409:   int mi; /* Effective wave */
                   4410:   int first;
                   4411:   double ***freq; /* Frequencies */
1.268     brouard  4412:   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 */
                   4413:   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  4414:   double *meanq, *stdq, *idq;
1.226     brouard  4415:   double **meanqt;
                   4416:   double *pp, **prop, *posprop, *pospropt;
                   4417:   double pos=0., posproptt=0., pospropta=0., k2, dateintsum=0,k2cpt=0;
                   4418:   char fileresp[FILENAMELENGTH], fileresphtm[FILENAMELENGTH], fileresphtmfr[FILENAMELENGTH];
                   4419:   double agebegin, ageend;
                   4420:     
                   4421:   pp=vector(1,nlstate);
1.251     brouard  4422:   prop=matrix(1,nlstate,iagemin-AGEMARGE,iagemax+4+AGEMARGE); 
1.226     brouard  4423:   posprop=vector(1,nlstate); /* Counting the number of transition starting from a live state per age */ 
                   4424:   pospropt=vector(1,nlstate); /* Counting the number of transition starting from a live state */ 
                   4425:   /* prop=matrix(1,nlstate,iagemin,iagemax+3); */
                   4426:   meanq=vector(1,nqfveff); /* Number of Quantitative Fixed Variables Effective */
1.284     brouard  4427:   stdq=vector(1,nqfveff); /* Number of Quantitative Fixed Variables Effective */
1.283     brouard  4428:   idq=vector(1,nqfveff); /* Number of Quantitative Fixed Variables Effective */
1.226     brouard  4429:   meanqt=matrix(1,lastpass,1,nqtveff);
                   4430:   strcpy(fileresp,"P_");
                   4431:   strcat(fileresp,fileresu);
                   4432:   /*strcat(fileresphtm,fileresu);*/
                   4433:   if((ficresp=fopen(fileresp,"w"))==NULL) {
                   4434:     printf("Problem with prevalence resultfile: %s\n", fileresp);
                   4435:     fprintf(ficlog,"Problem with prevalence resultfile: %s\n", fileresp);
                   4436:     exit(0);
                   4437:   }
1.240     brouard  4438:   
1.226     brouard  4439:   strcpy(fileresphtm,subdirfext(optionfilefiname,"PHTM_",".htm"));
                   4440:   if((ficresphtm=fopen(fileresphtm,"w"))==NULL) {
                   4441:     printf("Problem with prevalence HTM resultfile '%s' with errno='%s'\n",fileresphtm,strerror(errno));
                   4442:     fprintf(ficlog,"Problem with prevalence HTM resultfile '%s' with errno='%s'\n",fileresphtm,strerror(errno));
                   4443:     fflush(ficlog);
                   4444:     exit(70); 
                   4445:   }
                   4446:   else{
                   4447:     fprintf(ficresphtm,"<html><head>\n<title>IMaCh PHTM_ %s</title></head>\n <body><font size=\"2\">%s <br> %s</font> \
1.240     brouard  4448: <hr size=\"2\" color=\"#EC5E5E\"> \n                                   \
1.214     brouard  4449: Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=1+age+%s<br>\n",\
1.226     brouard  4450:            fileresphtm,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model);
                   4451:   }
1.237     brouard  4452:   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  4453:   
1.226     brouard  4454:   strcpy(fileresphtmfr,subdirfext(optionfilefiname,"PHTMFR_",".htm"));
                   4455:   if((ficresphtmfr=fopen(fileresphtmfr,"w"))==NULL) {
                   4456:     printf("Problem with frequency table HTM resultfile '%s' with errno='%s'\n",fileresphtmfr,strerror(errno));
                   4457:     fprintf(ficlog,"Problem with frequency table HTM resultfile '%s' with errno='%s'\n",fileresphtmfr,strerror(errno));
                   4458:     fflush(ficlog);
                   4459:     exit(70); 
1.240     brouard  4460:   } else{
1.226     brouard  4461:     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  4462: <hr size=\"2\" color=\"#EC5E5E\"> \n                                   \
1.214     brouard  4463: Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=1+age+%s<br>\n",\
1.226     brouard  4464:            fileresphtmfr,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model);
                   4465:   }
1.240     brouard  4466:   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);
                   4467:   
1.253     brouard  4468:   y= vector(iagemin-AGEMARGE,iagemax+4+AGEMARGE);
                   4469:   x= vector(iagemin-AGEMARGE,iagemax+4+AGEMARGE);
1.251     brouard  4470:   freq= ma3x(-5,nlstate+ndeath,-5,nlstate+ndeath,iagemin-AGEMARGE,iagemax+4+AGEMARGE);
1.226     brouard  4471:   j1=0;
1.126     brouard  4472:   
1.227     brouard  4473:   /* j=ncoveff;  /\* Only fixed dummy covariates *\/ */
                   4474:   j=cptcoveff;  /* Only dummy covariates of the model */
1.226     brouard  4475:   if (cptcovn<1) {j=1;ncodemax[1]=1;}
1.240     brouard  4476:   
                   4477:   
1.226     brouard  4478:   /* Detects if a combination j1 is empty: for a multinomial variable like 3 education levels:
                   4479:      reference=low_education V1=0,V2=0
                   4480:      med_educ                V1=1 V2=0, 
                   4481:      high_educ               V1=0 V2=1
                   4482:      Then V1=1 and V2=1 is a noisy combination that we want to exclude for the list 2**cptcoveff 
                   4483:   */
1.249     brouard  4484:   dateintsum=0;
                   4485:   k2cpt=0;
                   4486: 
1.253     brouard  4487:   if(cptcoveff == 0 )
1.265     brouard  4488:     nl=1;  /* Constant and age model only */
1.253     brouard  4489:   else
                   4490:     nl=2;
1.265     brouard  4491: 
                   4492:   /* if a constant only model, one pass to compute frequency tables and to write it on ficresp */
                   4493:   /* Loop on nj=1 or 2 if dummy covariates j!=0
                   4494:    *   Loop on j1(1 to 2**cptcoveff) covariate combination
                   4495:    *     freq[s1][s2][iage] =0.
                   4496:    *     Loop on iind
                   4497:    *       ++freq[s1][s2][iage] weighted
                   4498:    *     end iind
                   4499:    *     if covariate and j!0
                   4500:    *       headers Variable on one line
                   4501:    *     endif cov j!=0
                   4502:    *     header of frequency table by age
                   4503:    *     Loop on age
                   4504:    *       pp[s1]+=freq[s1][s2][iage] weighted
                   4505:    *       pos+=freq[s1][s2][iage] weighted
                   4506:    *       Loop on s1 initial state
                   4507:    *         fprintf(ficresp
                   4508:    *       end s1
                   4509:    *     end age
                   4510:    *     if j!=0 computes starting values
                   4511:    *     end compute starting values
                   4512:    *   end j1
                   4513:    * end nl 
                   4514:    */
1.253     brouard  4515:   for (nj = 1; nj <= nl; nj++){   /* nj= 1 constant model, nl number of loops. */
                   4516:     if(nj==1)
                   4517:       j=0;  /* First pass for the constant */
1.265     brouard  4518:     else{
1.253     brouard  4519:       j=cptcoveff; /* Other passes for the covariate values */
1.265     brouard  4520:     }
1.251     brouard  4521:     first=1;
1.265     brouard  4522:     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  4523:       posproptt=0.;
                   4524:       /*printf("cptcoveff=%d Tvaraff=%d", cptcoveff,Tvaraff[1]);
                   4525:        scanf("%d", i);*/
                   4526:       for (i=-5; i<=nlstate+ndeath; i++)  
1.265     brouard  4527:        for (s2=-5; s2<=nlstate+ndeath; s2++)  
1.251     brouard  4528:          for(m=iagemin; m <= iagemax+3; m++)
1.265     brouard  4529:            freq[i][s2][m]=0;
1.251     brouard  4530:       
                   4531:       for (i=1; i<=nlstate; i++)  {
1.240     brouard  4532:        for(m=iagemin; m <= iagemax+3; m++)
1.251     brouard  4533:          prop[i][m]=0;
                   4534:        posprop[i]=0;
                   4535:        pospropt[i]=0;
                   4536:       }
1.283     brouard  4537:       for (z1=1; z1<= nqfveff; z1++) { /* zeroing for each combination j1 as well as for the total */
1.284     brouard  4538:         idq[z1]=0.;
                   4539:         meanq[z1]=0.;
                   4540:         stdq[z1]=0.;
1.283     brouard  4541:       }
                   4542:       /* for (z1=1; z1<= nqtveff; z1++) { */
1.251     brouard  4543:       /*   for(m=1;m<=lastpass;m++){ */
1.283     brouard  4544:       /*         meanqt[m][z1]=0.; */
                   4545:       /*       } */
                   4546:       /* }       */
1.251     brouard  4547:       /* dateintsum=0; */
                   4548:       /* k2cpt=0; */
                   4549:       
1.265     brouard  4550:       /* For that combination of covariates j1 (V4=1 V3=0 for example), we count and print the frequencies in one pass */
1.251     brouard  4551:       for (iind=1; iind<=imx; iind++) { /* For each individual iind */
                   4552:        bool=1;
                   4553:        if(j !=0){
                   4554:          if(anyvaryingduminmodel==0){ /* If All fixed covariates */
                   4555:            if (cptcoveff >0) { /* Filter is here: Must be looked at for model=V1+V2+V3+V4 */
                   4556:              for (z1=1; z1<=cptcoveff; z1++) { /* loops on covariates in the model */
                   4557:                /* if(Tvaraff[z1] ==-20){ */
                   4558:                /*       /\* sumnew+=cotvar[mw[mi][iind]][z1][iind]; *\/ */
                   4559:                /* }else  if(Tvaraff[z1] ==-10){ */
                   4560:                /*       /\* sumnew+=coqvar[z1][iind]; *\/ */
                   4561:                /* }else  */
                   4562:                if (covar[Tvaraff[z1]][iind]!= nbcode[Tvaraff[z1]][codtabm(j1,z1)]){ /* for combination j1 of covariates */
1.265     brouard  4563:                  /* Tests if the value of the covariate z1 for this individual iind responded to combination j1 (V4=1 V3=0) */
1.251     brouard  4564:                  bool=0; /* bool should be equal to 1 to be selected, one covariate value failed */
                   4565:                  /* 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", 
                   4566:                     bool,i,z1, z1, Tvaraff[z1],i,covar[Tvaraff[z1]][i],j1,z1,codtabm(j1,z1),
                   4567:                     j1,z1,nbcode[Tvaraff[z1]][codtabm(j1,z1)],j1);*/
                   4568:                  /* For j1=7 in V1+V2+V3+V4 = 0 1 1 0 and codtabm(7,3)=1 and nbcde[3][?]=1*/
                   4569:                } /* Onlyf fixed */
                   4570:              } /* end z1 */
                   4571:            } /* cptcovn > 0 */
                   4572:          } /* end any */
                   4573:        }/* end j==0 */
1.265     brouard  4574:        if (bool==1){ /* We selected an individual iind satisfying combination j1 (V4=1 V3=0) or all fixed covariates */
1.251     brouard  4575:          /* for(m=firstpass; m<=lastpass; m++){ */
1.284     brouard  4576:          for(mi=1; mi<wav[iind];mi++){ /* For each wave */
1.251     brouard  4577:            m=mw[mi][iind];
                   4578:            if(j!=0){
                   4579:              if(anyvaryingduminmodel==1){ /* Some are varying covariates */
                   4580:                for (z1=1; z1<=cptcoveff; z1++) {
                   4581:                  if( Fixed[Tmodelind[z1]]==1){
                   4582:                    iv= Tvar[Tmodelind[z1]]-ncovcol-nqv;
                   4583:                    if (cotvar[m][iv][iind]!= nbcode[Tvaraff[z1]][codtabm(j1,z1)]) /* iv=1 to ntv, right modality. If covariate's 
                   4584:                                                                                      value is -1, we don't select. It differs from the 
                   4585:                                                                                      constant and age model which counts them. */
                   4586:                      bool=0; /* not selected */
                   4587:                  }else if( Fixed[Tmodelind[z1]]== 0) { /* fixed */
                   4588:                    if (covar[Tvaraff[z1]][iind]!= nbcode[Tvaraff[z1]][codtabm(j1,z1)]) {
                   4589:                      bool=0;
                   4590:                    }
                   4591:                  }
                   4592:                }
                   4593:              }/* Some are varying covariates, we tried to speed up if all fixed covariates in the model, avoiding waves loop  */
                   4594:            } /* end j==0 */
                   4595:            /* bool =0 we keep that guy which corresponds to the combination of dummy values */
1.284     brouard  4596:            if(bool==1){ /*Selected */
1.251     brouard  4597:              /* dh[m][iind] or dh[mw[mi][iind]][iind] is the delay between two effective (mi) waves m=mw[mi][iind]
                   4598:                 and mw[mi+1][iind]. dh depends on stepm. */
                   4599:              agebegin=agev[m][iind]; /* Age at beginning of wave before transition*/
                   4600:              ageend=agev[m][iind]+(dh[m][iind])*stepm/YEARM; /* Age at end of wave and transition */
                   4601:              if(m >=firstpass && m <=lastpass){
                   4602:                k2=anint[m][iind]+(mint[m][iind]/12.);
                   4603:                /*if ((k2>=dateprev1) && (k2<=dateprev2)) {*/
                   4604:                if(agev[m][iind]==0) agev[m][iind]=iagemax+1;  /* All ages equal to 0 are in iagemax+1 */
                   4605:                if(agev[m][iind]==1) agev[m][iind]=iagemax+2;  /* All ages equal to 1 are in iagemax+2 */
                   4606:                if (s[m][iind]>0 && s[m][iind]<=nlstate)  /* If status at wave m is known and a live state */
                   4607:                  prop[s[m][iind]][(int)agev[m][iind]] += weight[iind];  /* At age of beginning of transition, where status is known */
                   4608:                if (m<lastpass) {
                   4609:                  /* if(s[m][iind]==4 && s[m+1][iind]==4) */
                   4610:                  /*   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]); */
                   4611:                  if(s[m][iind]==-1)
                   4612:                    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.));
                   4613:                  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  4614:                  for (z1=1; z1<= nqfveff; z1++) { /* Quantitative variables, calculating mean */
                   4615:                    idq[z1]=idq[z1]+weight[iind];
                   4616:                    meanq[z1]+=covar[ncovcol+z1][iind]*weight[iind];  /* Computes mean of quantitative with selected filter */
                   4617:                    stdq[z1]+=covar[ncovcol+z1][iind]*covar[ncovcol+z1][iind]*weight[iind]*weight[iind]; /* *weight[iind];*/  /* Computes mean of quantitative with selected filter */
                   4618:                  }
1.251     brouard  4619:                  /* if((int)agev[m][iind] == 55) */
                   4620:                  /*   printf("j=%d, j1=%d Age %d, iind=%d, num=%09ld m=%d\n",j,j1,(int)agev[m][iind],iind, num[iind],m); */
                   4621:                  /* freq[s[m][iind]][s[m+1][iind]][(int)((agebegin+ageend)/2.)] += weight[iind]; */
                   4622:                  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  4623:                }
1.251     brouard  4624:              } /* end if between passes */  
                   4625:              if ((agev[m][iind]>1) && (agev[m][iind]< (iagemax+3)) && (anint[m][iind]!=9999) && (mint[m][iind]!=99) && (j==0)) {
                   4626:                dateintsum=dateintsum+k2; /* on all covariates ?*/
                   4627:                k2cpt++;
                   4628:                /* printf("iind=%ld dateintmean = %lf dateintsum=%lf k2cpt=%lf k2=%lf\n",iind, dateintsum/k2cpt, dateintsum,k2cpt, k2); */
1.234     brouard  4629:              }
1.251     brouard  4630:            }else{
                   4631:              bool=1;
                   4632:            }/* end bool 2 */
                   4633:          } /* end m */
1.284     brouard  4634:          /* for (z1=1; z1<= nqfveff; z1++) { /\* Quantitative variables, calculating mean *\/ */
                   4635:          /*   idq[z1]=idq[z1]+weight[iind]; */
                   4636:          /*   meanq[z1]+=covar[ncovcol+z1][iind]*weight[iind];  /\* Computes mean of quantitative with selected filter *\/ */
                   4637:          /*   stdq[z1]+=covar[ncovcol+z1][iind]*covar[ncovcol+z1][iind]*weight[iind]*weight[iind]; /\* *weight[iind];*\/  /\* Computes mean of quantitative with selected filter *\/ */
                   4638:          /* } */
1.251     brouard  4639:        } /* end bool */
                   4640:       } /* end iind = 1 to imx */
                   4641:       /* prop[s][age] is feeded for any initial and valid live state as well as
                   4642:         freq[s1][s2][age] at single age of beginning the transition, for a combination j1 */
                   4643:       
                   4644:       
                   4645:       /*      fprintf(ficresp, "#Count between %.lf/%.lf/%.lf and %.lf/%.lf/%.lf\n",jprev1, mprev1,anprev1,jprev2, mprev2,anprev2);*/
1.265     brouard  4646:       if(cptcoveff==0 && nj==1) /* no covariate and first pass */
                   4647:         pstamp(ficresp);
1.251     brouard  4648:       if  (cptcoveff>0 && j!=0){
1.265     brouard  4649:         pstamp(ficresp);
1.251     brouard  4650:        printf( "\n#********** Variable "); 
                   4651:        fprintf(ficresp, "\n#********** Variable "); 
                   4652:        fprintf(ficresphtm, "\n<br/><br/><h3>********** Variable "); 
                   4653:        fprintf(ficresphtmfr, "\n<br/><br/><h3>********** Variable "); 
                   4654:        fprintf(ficlog, "\n#********** Variable "); 
                   4655:        for (z1=1; z1<=cptcoveff; z1++){
                   4656:          if(!FixedV[Tvaraff[z1]]){
                   4657:            printf( "V%d(fixed)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
                   4658:            fprintf(ficresp, "V%d(fixed)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
                   4659:            fprintf(ficresphtm, "V%d(fixed)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
                   4660:            fprintf(ficresphtmfr, "V%d(fixed)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
                   4661:            fprintf(ficlog, "V%d(fixed)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
1.250     brouard  4662:          }else{
1.251     brouard  4663:            printf( "V%d(varying)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
                   4664:            fprintf(ficresp, "V%d(varying)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
                   4665:            fprintf(ficresphtm, "V%d(varying)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
                   4666:            fprintf(ficresphtmfr, "V%d(varying)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
                   4667:            fprintf(ficlog, "V%d(varying)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
                   4668:          }
                   4669:        }
                   4670:        printf( "**********\n#");
                   4671:        fprintf(ficresp, "**********\n#");
                   4672:        fprintf(ficresphtm, "**********</h3>\n");
                   4673:        fprintf(ficresphtmfr, "**********</h3>\n");
                   4674:        fprintf(ficlog, "**********\n");
                   4675:       }
1.284     brouard  4676:       /*
                   4677:        Printing means of quantitative variables if any
                   4678:       */
                   4679:       for (z1=1; z1<= nqfveff; z1++) {
1.285     brouard  4680:        fprintf(ficlog,"Mean of fixed quantitative variable V%d on %.0f individuals sum=%f", ncovcol+z1, idq[z1], meanq[z1]);
1.284     brouard  4681:        fprintf(ficlog,", mean=%.3g\n",meanq[z1]/idq[z1]);
                   4682:        if(weightopt==1){
                   4683:          printf(" Weighted mean and standard deviation of");
                   4684:          fprintf(ficlog," Weighted mean and standard deviation of");
                   4685:          fprintf(ficresphtmfr," Weighted mean and standard deviation of");
                   4686:        }
1.285     brouard  4687:        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]));
                   4688:        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]));
                   4689:        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  4690:       }
                   4691:       /* for (z1=1; z1<= nqtveff; z1++) { */
                   4692:       /*       for(m=1;m<=lastpass;m++){ */
                   4693:       /*         fprintf(ficresphtmfr,"V quantitative id %d, pass id=%d, mean=%f<p>\n", z1, m, meanqt[m][z1]); */
                   4694:       /*   } */
                   4695:       /* } */
1.283     brouard  4696: 
1.251     brouard  4697:       fprintf(ficresphtm,"<table style=\"text-align:center; border: 1px solid\">");
1.265     brouard  4698:       if((cptcoveff==0 && nj==1)|| nj==2 ) /* no covariate and first pass */
                   4699:         fprintf(ficresp, " Age");
                   4700:       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  4701:       for(i=1; i<=nlstate;i++) {
1.265     brouard  4702:        if((cptcoveff==0 && nj==1)|| nj==2 ) fprintf(ficresp," Prev(%d)  N(%d)  N  ",i,i);
1.251     brouard  4703:        fprintf(ficresphtm, "<th>Age</th><th>Prev(%d)</th><th>N(%d)</th><th>N</th>",i,i);
                   4704:       }
1.265     brouard  4705:       if((cptcoveff==0 && nj==1)|| nj==2 ) fprintf(ficresp, "\n");
1.251     brouard  4706:       fprintf(ficresphtm, "\n");
                   4707:       
                   4708:       /* Header of frequency table by age */
                   4709:       fprintf(ficresphtmfr,"<table style=\"text-align:center; border: 1px solid\">");
                   4710:       fprintf(ficresphtmfr,"<th>Age</th> ");
1.265     brouard  4711:       for(s2=-1; s2 <=nlstate+ndeath; s2++){
1.251     brouard  4712:        for(m=-1; m <=nlstate+ndeath; m++){
1.265     brouard  4713:          if(s2!=0 && m!=0)
                   4714:            fprintf(ficresphtmfr,"<th>%d%d</th> ",s2,m);
1.240     brouard  4715:        }
1.226     brouard  4716:       }
1.251     brouard  4717:       fprintf(ficresphtmfr, "\n");
                   4718:     
                   4719:       /* For each age */
                   4720:       for(iage=iagemin; iage <= iagemax+3; iage++){
                   4721:        fprintf(ficresphtm,"<tr>");
                   4722:        if(iage==iagemax+1){
                   4723:          fprintf(ficlog,"1");
                   4724:          fprintf(ficresphtmfr,"<tr><th>0</th> ");
                   4725:        }else if(iage==iagemax+2){
                   4726:          fprintf(ficlog,"0");
                   4727:          fprintf(ficresphtmfr,"<tr><th>Unknown</th> ");
                   4728:        }else if(iage==iagemax+3){
                   4729:          fprintf(ficlog,"Total");
                   4730:          fprintf(ficresphtmfr,"<tr><th>Total</th> ");
                   4731:        }else{
1.240     brouard  4732:          if(first==1){
1.251     brouard  4733:            first=0;
                   4734:            printf("See log file for details...\n");
                   4735:          }
                   4736:          fprintf(ficresphtmfr,"<tr><th>%d</th> ",iage);
                   4737:          fprintf(ficlog,"Age %d", iage);
                   4738:        }
1.265     brouard  4739:        for(s1=1; s1 <=nlstate ; s1++){
                   4740:          for(m=-1, pp[s1]=0; m <=nlstate+ndeath ; m++)
                   4741:            pp[s1] += freq[s1][m][iage]; 
1.251     brouard  4742:        }
1.265     brouard  4743:        for(s1=1; s1 <=nlstate ; s1++){
1.251     brouard  4744:          for(m=-1, pos=0; m <=0 ; m++)
1.265     brouard  4745:            pos += freq[s1][m][iage];
                   4746:          if(pp[s1]>=1.e-10){
1.251     brouard  4747:            if(first==1){
1.265     brouard  4748:              printf(" %d.=%.0f loss[%d]=%.1f%%",s1,pp[s1],s1,100*pos/pp[s1]);
1.251     brouard  4749:            }
1.265     brouard  4750:            fprintf(ficlog," %d.=%.0f loss[%d]=%.1f%%",s1,pp[s1],s1,100*pos/pp[s1]);
1.251     brouard  4751:          }else{
                   4752:            if(first==1)
1.265     brouard  4753:              printf(" %d.=%.0f loss[%d]=NaNQ%%",s1,pp[s1],s1);
                   4754:            fprintf(ficlog," %d.=%.0f loss[%d]=NaNQ%%",s1,pp[s1],s1);
1.240     brouard  4755:          }
                   4756:        }
                   4757:       
1.265     brouard  4758:        for(s1=1; s1 <=nlstate ; s1++){ 
                   4759:          /* posprop[s1]=0; */
                   4760:          for(m=0, pp[s1]=0; m <=nlstate+ndeath; m++)/* Summing on all ages */
                   4761:            pp[s1] += freq[s1][m][iage];
                   4762:        }       /* pp[s1] is the total number of transitions starting from state s1 and any ending status until this age */
                   4763:       
                   4764:        for(s1=1,pos=0, pospropta=0.; s1 <=nlstate ; s1++){
                   4765:          pos += pp[s1]; /* pos is the total number of transitions until this age */
                   4766:          posprop[s1] += prop[s1][iage]; /* prop is the number of transitions from a live state
                   4767:                                            from s1 at age iage prop[s[m][iind]][(int)agev[m][iind]] += weight[iind] */
                   4768:          pospropta += prop[s1][iage]; /* prop is the number of transitions from a live state
                   4769:                                          from s1 at age iage prop[s[m][iind]][(int)agev[m][iind]] += weight[iind] */
                   4770:        }
                   4771:        
                   4772:        /* Writing ficresp */
                   4773:        if(cptcoveff==0 && nj==1){ /* no covariate and first pass */
                   4774:           if( iage <= iagemax){
                   4775:            fprintf(ficresp," %d",iage);
                   4776:           }
                   4777:         }else if( nj==2){
                   4778:           if( iage <= iagemax){
                   4779:            fprintf(ficresp," %d",iage);
                   4780:             for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresp, " %d %d",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
                   4781:           }
1.240     brouard  4782:        }
1.265     brouard  4783:        for(s1=1; s1 <=nlstate ; s1++){
1.240     brouard  4784:          if(pos>=1.e-5){
1.251     brouard  4785:            if(first==1)
1.265     brouard  4786:              printf(" %d.=%.0f prev[%d]=%.1f%%",s1,pp[s1],s1,100*pp[s1]/pos);
                   4787:            fprintf(ficlog," %d.=%.0f prev[%d]=%.1f%%",s1,pp[s1],s1,100*pp[s1]/pos);
1.251     brouard  4788:          }else{
                   4789:            if(first==1)
1.265     brouard  4790:              printf(" %d.=%.0f prev[%d]=NaNQ%%",s1,pp[s1],s1);
                   4791:            fprintf(ficlog," %d.=%.0f prev[%d]=NaNQ%%",s1,pp[s1],s1);
1.251     brouard  4792:          }
                   4793:          if( iage <= iagemax){
                   4794:            if(pos>=1.e-5){
1.265     brouard  4795:              if(cptcoveff==0 && nj==1){ /* no covariate and first pass */
                   4796:                fprintf(ficresp," %.5f %.0f %.0f",prop[s1][iage]/pospropta, prop[s1][iage],pospropta);
                   4797:               }else if( nj==2){
                   4798:                fprintf(ficresp," %.5f %.0f %.0f",prop[s1][iage]/pospropta, prop[s1][iage],pospropta);
                   4799:               }
                   4800:              fprintf(ficresphtm,"<th>%d</th><td>%.5f</td><td>%.0f</td><td>%.0f</td>",iage,prop[s1][iage]/pospropta, prop[s1][iage],pospropta);
                   4801:              /*probs[iage][s1][j1]= pp[s1]/pos;*/
                   4802:              /*printf("\niage=%d s1=%d j1=%d %.5f %.0f %.0f %f",iage,s1,j1,pp[s1]/pos, pp[s1],pos,probs[iage][s1][j1]);*/
                   4803:            } else{
                   4804:              if((cptcoveff==0 && nj==1)|| nj==2 ) fprintf(ficresp," NaNq %.0f %.0f",prop[s1][iage],pospropta);
                   4805:              fprintf(ficresphtm,"<th>%d</th><td>NaNq</td><td>%.0f</td><td>%.0f</td>",iage, prop[s1][iage],pospropta);
1.251     brouard  4806:            }
1.240     brouard  4807:          }
1.265     brouard  4808:          pospropt[s1] +=posprop[s1];
                   4809:        } /* end loop s1 */
1.251     brouard  4810:        /* pospropt=0.; */
1.265     brouard  4811:        for(s1=-1; s1 <=nlstate+ndeath; s1++){
1.251     brouard  4812:          for(m=-1; m <=nlstate+ndeath; m++){
1.265     brouard  4813:            if(freq[s1][m][iage] !=0 ) { /* minimizing output */
1.251     brouard  4814:              if(first==1){
1.265     brouard  4815:                printf(" %d%d=%.0f",s1,m,freq[s1][m][iage]);
1.251     brouard  4816:              }
1.265     brouard  4817:              /* printf(" %d%d=%.0f",s1,m,freq[s1][m][iage]); */
                   4818:              fprintf(ficlog," %d%d=%.0f",s1,m,freq[s1][m][iage]);
1.251     brouard  4819:            }
1.265     brouard  4820:            if(s1!=0 && m!=0)
                   4821:              fprintf(ficresphtmfr,"<td>%.0f</td> ",freq[s1][m][iage]);
1.240     brouard  4822:          }
1.265     brouard  4823:        } /* end loop s1 */
1.251     brouard  4824:        posproptt=0.; 
1.265     brouard  4825:        for(s1=1; s1 <=nlstate; s1++){
                   4826:          posproptt += pospropt[s1];
1.251     brouard  4827:        }
                   4828:        fprintf(ficresphtmfr,"</tr>\n ");
1.265     brouard  4829:        fprintf(ficresphtm,"</tr>\n");
                   4830:        if((cptcoveff==0 && nj==1)|| nj==2 ) {
                   4831:          if(iage <= iagemax)
                   4832:            fprintf(ficresp,"\n");
1.240     brouard  4833:        }
1.251     brouard  4834:        if(first==1)
                   4835:          printf("Others in log...\n");
                   4836:        fprintf(ficlog,"\n");
                   4837:       } /* end loop age iage */
1.265     brouard  4838:       
1.251     brouard  4839:       fprintf(ficresphtm,"<tr><th>Tot</th>");
1.265     brouard  4840:       for(s1=1; s1 <=nlstate ; s1++){
1.251     brouard  4841:        if(posproptt < 1.e-5){
1.265     brouard  4842:          fprintf(ficresphtm,"<td>Nanq</td><td>%.0f</td><td>%.0f</td>",pospropt[s1],posproptt); 
1.251     brouard  4843:        }else{
1.265     brouard  4844:          fprintf(ficresphtm,"<td>%.5f</td><td>%.0f</td><td>%.0f</td>",pospropt[s1]/posproptt,pospropt[s1],posproptt);  
1.240     brouard  4845:        }
1.226     brouard  4846:       }
1.251     brouard  4847:       fprintf(ficresphtm,"</tr>\n");
                   4848:       fprintf(ficresphtm,"</table>\n");
                   4849:       fprintf(ficresphtmfr,"</table>\n");
1.226     brouard  4850:       if(posproptt < 1.e-5){
1.251     brouard  4851:        fprintf(ficresphtm,"\n <p><b> This combination (%d) is not valid and no result will be produced</b></p>",j1);
                   4852:        fprintf(ficresphtmfr,"\n <p><b> This combination (%d) is not valid and no result will be produced</b></p>",j1);
1.260     brouard  4853:        fprintf(ficlog,"#  This combination (%d) is not valid and no result will be produced\n",j1);
                   4854:        printf("#  This combination (%d) is not valid and no result will be produced\n",j1);
1.251     brouard  4855:        invalidvarcomb[j1]=1;
1.226     brouard  4856:       }else{
1.251     brouard  4857:        fprintf(ficresphtm,"\n <p> This combination (%d) is valid and result will be produced.</p>",j1);
                   4858:        invalidvarcomb[j1]=0;
1.226     brouard  4859:       }
1.251     brouard  4860:       fprintf(ficresphtmfr,"</table>\n");
                   4861:       fprintf(ficlog,"\n");
                   4862:       if(j!=0){
                   4863:        printf("#Freqsummary: Starting values for combination j1=%d:\n", j1);
1.265     brouard  4864:        for(i=1,s1=1; i <=nlstate; i++){
1.251     brouard  4865:          for(k=1; k <=(nlstate+ndeath); k++){
                   4866:            if (k != i) {
1.265     brouard  4867:              for(jj=1; jj <=ncovmodel; jj++){ /* For counting s1 */
1.253     brouard  4868:                if(jj==1){  /* Constant case (in fact cste + age) */
1.251     brouard  4869:                  if(j1==1){ /* All dummy covariates to zero */
                   4870:                    freq[i][k][iagemax+4]=freq[i][k][iagemax+3]; /* Stores case 0 0 0 */
                   4871:                    freq[i][i][iagemax+4]=freq[i][i][iagemax+3]; /* Stores case 0 0 0 */
1.252     brouard  4872:                    printf("%d%d ",i,k);
                   4873:                    fprintf(ficlog,"%d%d ",i,k);
1.265     brouard  4874:                    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]));
                   4875:                    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]));
                   4876:                    pstart[s1]= log(freq[i][k][iagemax+3]/freq[i][i][iagemax+3]);
1.251     brouard  4877:                  }
1.253     brouard  4878:                }else if((j1==1) && (jj==2 || nagesqr==1)){ /* age or age*age parameter without covariate V4*age (to be done later) */
                   4879:                  for(iage=iagemin; iage <= iagemax+3; iage++){
                   4880:                    x[iage]= (double)iage;
                   4881:                    y[iage]= log(freq[i][k][iage]/freq[i][i][iage]);
1.265     brouard  4882:                    /* 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  4883:                  }
1.268     brouard  4884:                  /* Some are not finite, but linreg will ignore these ages */
                   4885:                  no=0;
1.253     brouard  4886:                  linreg(iagemin,iagemax,&no,x,y,&a,&b,&r, &sa, &sb ); /* y= a+b*x with standard errors */
1.265     brouard  4887:                  pstart[s1]=b;
                   4888:                  pstart[s1-1]=a;
1.252     brouard  4889:                }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 */ 
                   4890:                  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]);
                   4891:                  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  4892:                  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  4893:                  printf("%d%d ",i,k);
                   4894:                  fprintf(ficlog,"%d%d ",i,k);
1.265     brouard  4895:                  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  4896:                }else{ /* Other cases, like quantitative fixed or varying covariates */
                   4897:                  ;
                   4898:                }
                   4899:                /* printf("%12.7f )", param[i][jj][k]); */
                   4900:                /* fprintf(ficlog,"%12.7f )", param[i][jj][k]); */
1.265     brouard  4901:                s1++; 
1.251     brouard  4902:              } /* end jj */
                   4903:            } /* end k!= i */
                   4904:          } /* end k */
1.265     brouard  4905:        } /* end i, s1 */
1.251     brouard  4906:       } /* end j !=0 */
                   4907:     } /* end selected combination of covariate j1 */
                   4908:     if(j==0){ /* We can estimate starting values from the occurences in each case */
                   4909:       printf("#Freqsummary: Starting values for the constants:\n");
                   4910:       fprintf(ficlog,"\n");
1.265     brouard  4911:       for(i=1,s1=1; i <=nlstate; i++){
1.251     brouard  4912:        for(k=1; k <=(nlstate+ndeath); k++){
                   4913:          if (k != i) {
                   4914:            printf("%d%d ",i,k);
                   4915:            fprintf(ficlog,"%d%d ",i,k);
                   4916:            for(jj=1; jj <=ncovmodel; jj++){
1.265     brouard  4917:              pstart[s1]=p[s1]; /* Setting pstart to p values by default */
1.253     brouard  4918:              if(jj==1){ /* Age has to be done */
1.265     brouard  4919:                pstart[s1]= log(freq[i][k][iagemax+3]/freq[i][i][iagemax+3]);
                   4920:                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]));
                   4921:                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  4922:              }
                   4923:              /* printf("%12.7f )", param[i][jj][k]); */
                   4924:              /* fprintf(ficlog,"%12.7f )", param[i][jj][k]); */
1.265     brouard  4925:              s1++; 
1.250     brouard  4926:            }
1.251     brouard  4927:            printf("\n");
                   4928:            fprintf(ficlog,"\n");
1.250     brouard  4929:          }
                   4930:        }
1.284     brouard  4931:       } /* end of state i */
1.251     brouard  4932:       printf("#Freqsummary\n");
                   4933:       fprintf(ficlog,"\n");
1.265     brouard  4934:       for(s1=-1; s1 <=nlstate+ndeath; s1++){
                   4935:        for(s2=-1; s2 <=nlstate+ndeath; s2++){
                   4936:          /* param[i]|j][k]= freq[s1][s2][iagemax+3] */
                   4937:          printf(" %d%d=%.0f",s1,s2,freq[s1][s2][iagemax+3]);
                   4938:          fprintf(ficlog," %d%d=%.0f",s1,s2,freq[s1][s2][iagemax+3]);
                   4939:          /* if(freq[s1][s2][iage] !=0 ) { /\* minimizing output *\/ */
                   4940:          /*   printf(" %d%d=%.0f",s1,s2,freq[s1][s2][iagemax+3]); */
                   4941:          /*   fprintf(ficlog," %d%d=%.0f",s1,s2,freq[s1][s2][iagemax+3]); */
1.251     brouard  4942:          /* } */
                   4943:        }
1.265     brouard  4944:       } /* end loop s1 */
1.251     brouard  4945:       
                   4946:       printf("\n");
                   4947:       fprintf(ficlog,"\n");
                   4948:     } /* end j=0 */
1.249     brouard  4949:   } /* end j */
1.252     brouard  4950: 
1.253     brouard  4951:   if(mle == -2){  /* We want to use these values as starting values */
1.252     brouard  4952:     for(i=1, jk=1; i <=nlstate; i++){
                   4953:       for(j=1; j <=nlstate+ndeath; j++){
                   4954:        if(j!=i){
                   4955:          /*ca[0]= k+'a'-1;ca[1]='\0';*/
                   4956:          printf("%1d%1d",i,j);
                   4957:          fprintf(ficparo,"%1d%1d",i,j);
                   4958:          for(k=1; k<=ncovmodel;k++){
                   4959:            /*    printf(" %lf",param[i][j][k]); */
                   4960:            /*    fprintf(ficparo," %lf",param[i][j][k]); */
                   4961:            p[jk]=pstart[jk];
                   4962:            printf(" %f ",pstart[jk]);
                   4963:            fprintf(ficparo," %f ",pstart[jk]);
                   4964:            jk++;
                   4965:          }
                   4966:          printf("\n");
                   4967:          fprintf(ficparo,"\n");
                   4968:        }
                   4969:       }
                   4970:     }
                   4971:   } /* end mle=-2 */
1.226     brouard  4972:   dateintmean=dateintsum/k2cpt; 
1.240     brouard  4973:   
1.226     brouard  4974:   fclose(ficresp);
                   4975:   fclose(ficresphtm);
                   4976:   fclose(ficresphtmfr);
1.283     brouard  4977:   free_vector(idq,1,nqfveff);
1.226     brouard  4978:   free_vector(meanq,1,nqfveff);
1.284     brouard  4979:   free_vector(stdq,1,nqfveff);
1.226     brouard  4980:   free_matrix(meanqt,1,lastpass,1,nqtveff);
1.253     brouard  4981:   free_vector(x, iagemin-AGEMARGE, iagemax+4+AGEMARGE);
                   4982:   free_vector(y, iagemin-AGEMARGE, iagemax+4+AGEMARGE);
1.251     brouard  4983:   free_ma3x(freq,-5,nlstate+ndeath,-5,nlstate+ndeath, iagemin-AGEMARGE, iagemax+4+AGEMARGE);
1.226     brouard  4984:   free_vector(pospropt,1,nlstate);
                   4985:   free_vector(posprop,1,nlstate);
1.251     brouard  4986:   free_matrix(prop,1,nlstate,iagemin-AGEMARGE, iagemax+4+AGEMARGE);
1.226     brouard  4987:   free_vector(pp,1,nlstate);
                   4988:   /* End of freqsummary */
                   4989: }
1.126     brouard  4990: 
1.268     brouard  4991: /* Simple linear regression */
                   4992: int linreg(int ifi, int ila, int *no, const double x[], const double y[], double* a, double* b, double* r, double* sa, double * sb) {
                   4993: 
                   4994:   /* y=a+bx regression */
                   4995:   double   sumx = 0.0;                        /* sum of x                      */
                   4996:   double   sumx2 = 0.0;                       /* sum of x**2                   */
                   4997:   double   sumxy = 0.0;                       /* sum of x * y                  */
                   4998:   double   sumy = 0.0;                        /* sum of y                      */
                   4999:   double   sumy2 = 0.0;                       /* sum of y**2                   */
                   5000:   double   sume2 = 0.0;                       /* sum of square or residuals */
                   5001:   double yhat;
                   5002:   
                   5003:   double denom=0;
                   5004:   int i;
                   5005:   int ne=*no;
                   5006:   
                   5007:   for ( i=ifi, ne=0;i<=ila;i++) {
                   5008:     if(!isfinite(x[i]) || !isfinite(y[i])){
                   5009:       /* printf(" x[%d]=%f, y[%d]=%f\n",i,x[i],i,y[i]); */
                   5010:       continue;
                   5011:     }
                   5012:     ne=ne+1;
                   5013:     sumx  += x[i];       
                   5014:     sumx2 += x[i]*x[i];  
                   5015:     sumxy += x[i] * y[i];
                   5016:     sumy  += y[i];      
                   5017:     sumy2 += y[i]*y[i]; 
                   5018:     denom = (ne * sumx2 - sumx*sumx);
                   5019:     /* 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); */
                   5020:   } 
                   5021:   
                   5022:   denom = (ne * sumx2 - sumx*sumx);
                   5023:   if (denom == 0) {
                   5024:     // vertical, slope m is infinity
                   5025:     *b = INFINITY;
                   5026:     *a = 0;
                   5027:     if (r) *r = 0;
                   5028:     return 1;
                   5029:   }
                   5030:   
                   5031:   *b = (ne * sumxy  -  sumx * sumy) / denom;
                   5032:   *a = (sumy * sumx2  -  sumx * sumxy) / denom;
                   5033:   if (r!=NULL) {
                   5034:     *r = (sumxy - sumx * sumy / ne) /          /* compute correlation coeff     */
                   5035:       sqrt((sumx2 - sumx*sumx/ne) *
                   5036:           (sumy2 - sumy*sumy/ne));
                   5037:   }
                   5038:   *no=ne;
                   5039:   for ( i=ifi, ne=0;i<=ila;i++) {
                   5040:     if(!isfinite(x[i]) || !isfinite(y[i])){
                   5041:       /* printf(" x[%d]=%f, y[%d]=%f\n",i,x[i],i,y[i]); */
                   5042:       continue;
                   5043:     }
                   5044:     ne=ne+1;
                   5045:     yhat = y[i] - *a -*b* x[i];
                   5046:     sume2  += yhat * yhat ;       
                   5047:     
                   5048:     denom = (ne * sumx2 - sumx*sumx);
                   5049:     /* 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); */
                   5050:   } 
                   5051:   *sb = sqrt(sume2/(double)(ne-2)/(sumx2 - sumx * sumx /(double)ne));
                   5052:   *sa= *sb * sqrt(sumx2/ne);
                   5053:   
                   5054:   return 0; 
                   5055: }
                   5056: 
1.126     brouard  5057: /************ Prevalence ********************/
1.227     brouard  5058: 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)
                   5059: {  
                   5060:   /* Compute observed prevalence between dateprev1 and dateprev2 by counting the number of people
                   5061:      in each health status at the date of interview (if between dateprev1 and dateprev2).
                   5062:      We still use firstpass and lastpass as another selection.
                   5063:   */
1.126     brouard  5064:  
1.227     brouard  5065:   int i, m, jk, j1, bool, z1,j, iv;
                   5066:   int mi; /* Effective wave */
                   5067:   int iage;
                   5068:   double agebegin, ageend;
                   5069: 
                   5070:   double **prop;
                   5071:   double posprop; 
                   5072:   double  y2; /* in fractional years */
                   5073:   int iagemin, iagemax;
                   5074:   int first; /** to stop verbosity which is redirected to log file */
                   5075: 
                   5076:   iagemin= (int) agemin;
                   5077:   iagemax= (int) agemax;
                   5078:   /*pp=vector(1,nlstate);*/
1.251     brouard  5079:   prop=matrix(1,nlstate,iagemin-AGEMARGE,iagemax+4+AGEMARGE); 
1.227     brouard  5080:   /*  freq=ma3x(-1,nlstate+ndeath,-1,nlstate+ndeath,iagemin,iagemax+3);*/
                   5081:   j1=0;
1.222     brouard  5082:   
1.227     brouard  5083:   /*j=cptcoveff;*/
                   5084:   if (cptcovn<1) {j=1;ncodemax[1]=1;}
1.222     brouard  5085:   
1.288     brouard  5086:   first=0;
1.227     brouard  5087:   for(j1=1; j1<= (int) pow(2,cptcoveff);j1++){ /* For each combination of covariate */
                   5088:     for (i=1; i<=nlstate; i++)  
1.251     brouard  5089:       for(iage=iagemin-AGEMARGE; iage <= iagemax+4+AGEMARGE; iage++)
1.227     brouard  5090:        prop[i][iage]=0.0;
                   5091:     printf("Prevalence combination of varying and fixed dummies %d\n",j1);
                   5092:     /* fprintf(ficlog," V%d=%d ",Tvaraff[j1],nbcode[Tvaraff[j1]][codtabm(k,j1)]); */
                   5093:     fprintf(ficlog,"Prevalence combination of varying and fixed dummies %d\n",j1);
                   5094:     
                   5095:     for (i=1; i<=imx; i++) { /* Each individual */
                   5096:       bool=1;
                   5097:       /* for(m=firstpass; m<=lastpass; m++){/\* Other selection (we can limit to certain interviews*\/ */
                   5098:       for(mi=1; mi<wav[i];mi++){ /* For this wave too look where individual can be counted V4=0 V3=0 */
                   5099:        m=mw[mi][i];
                   5100:        /* Tmodelind[z1]=k is the position of the varying covariate in the model, but which # within 1 to ntv? */
                   5101:        /* Tvar[Tmodelind[z1]] is the n of Vn; n-ncovcol-nqv is the first time varying covariate or iv */
                   5102:        for (z1=1; z1<=cptcoveff; z1++){
                   5103:          if( Fixed[Tmodelind[z1]]==1){
                   5104:            iv= Tvar[Tmodelind[z1]]-ncovcol-nqv;
                   5105:            if (cotvar[m][iv][i]!= nbcode[Tvaraff[z1]][codtabm(j1,z1)]) /* iv=1 to ntv, right modality */
                   5106:              bool=0;
                   5107:          }else if( Fixed[Tmodelind[z1]]== 0)  /* fixed */
                   5108:            if (covar[Tvaraff[z1]][i]!= nbcode[Tvaraff[z1]][codtabm(j1,z1)]) {
                   5109:              bool=0;
                   5110:            }
                   5111:        }
                   5112:        if(bool==1){ /* Otherwise we skip that wave/person */
                   5113:          agebegin=agev[m][i]; /* Age at beginning of wave before transition*/
                   5114:          /* ageend=agev[m][i]+(dh[m][i])*stepm/YEARM; /\* Age at end of wave and transition *\/ */
                   5115:          if(m >=firstpass && m <=lastpass){
                   5116:            y2=anint[m][i]+(mint[m][i]/12.); /* Fractional date in year */
                   5117:            if ((y2>=dateprev1) && (y2<=dateprev2)) { /* Here is the main selection (fractional years) */
                   5118:              if(agev[m][i]==0) agev[m][i]=iagemax+1;
                   5119:              if(agev[m][i]==1) agev[m][i]=iagemax+2;
1.251     brouard  5120:              if((int)agev[m][i] <iagemin-AGEMARGE || (int)agev[m][i] >iagemax+4+AGEMARGE){
1.227     brouard  5121:                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); 
                   5122:                exit(1);
                   5123:              }
                   5124:              if (s[m][i]>0 && s[m][i]<=nlstate) { 
                   5125:                /*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]]);*/
                   5126:                prop[s[m][i]][(int)agev[m][i]] += weight[i];/* At age of beginning of transition, where status is known */
                   5127:                prop[s[m][i]][iagemax+3] += weight[i]; 
                   5128:              } /* end valid statuses */ 
                   5129:            } /* end selection of dates */
                   5130:          } /* end selection of waves */
                   5131:        } /* end bool */
                   5132:       } /* end wave */
                   5133:     } /* end individual */
                   5134:     for(i=iagemin; i <= iagemax+3; i++){  
                   5135:       for(jk=1,posprop=0; jk <=nlstate ; jk++) { 
                   5136:        posprop += prop[jk][i]; 
                   5137:       } 
                   5138:       
                   5139:       for(jk=1; jk <=nlstate ; jk++){      
                   5140:        if( i <=  iagemax){ 
                   5141:          if(posprop>=1.e-5){ 
                   5142:            probs[i][jk][j1]= prop[jk][i]/posprop;
                   5143:          } else{
1.288     brouard  5144:            if(!first){
                   5145:              first=1;
1.266     brouard  5146:              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]);
                   5147:            }else{
1.288     brouard  5148:              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  5149:            }
                   5150:          }
                   5151:        } 
                   5152:       }/* end jk */ 
                   5153:     }/* end i */ 
1.222     brouard  5154:      /*} *//* end i1 */
1.227     brouard  5155:   } /* end j1 */
1.222     brouard  5156:   
1.227     brouard  5157:   /*  free_ma3x(freq,-1,nlstate+ndeath,-1,nlstate+ndeath, iagemin, iagemax+3);*/
                   5158:   /*free_vector(pp,1,nlstate);*/
1.251     brouard  5159:   free_matrix(prop,1,nlstate, iagemin-AGEMARGE,iagemax+4+AGEMARGE);
1.227     brouard  5160: }  /* End of prevalence */
1.126     brouard  5161: 
                   5162: /************* Waves Concatenation ***************/
                   5163: 
                   5164: 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)
                   5165: {
                   5166:   /* Concatenates waves: wav[i] is the number of effective (useful waves) of individual i.
                   5167:      Death is a valid wave (if date is known).
                   5168:      mw[mi][i] is the mi (mi=1 to wav[i])  effective wave of individual i
                   5169:      dh[m][i] or dh[mw[mi][i]][i] is the delay between two effective waves m=mw[mi][i]
                   5170:      and mw[mi+1][i]. dh depends on stepm.
1.227     brouard  5171:   */
1.126     brouard  5172: 
1.224     brouard  5173:   int i=0, mi=0, m=0, mli=0;
1.126     brouard  5174:   /* int j, k=0,jk, ju, jl,jmin=1e+5, jmax=-1;
                   5175:      double sum=0., jmean=0.;*/
1.224     brouard  5176:   int first=0, firstwo=0, firsthree=0, firstfour=0, firstfiv=0;
1.126     brouard  5177:   int j, k=0,jk, ju, jl;
                   5178:   double sum=0.;
                   5179:   first=0;
1.214     brouard  5180:   firstwo=0;
1.217     brouard  5181:   firsthree=0;
1.218     brouard  5182:   firstfour=0;
1.164     brouard  5183:   jmin=100000;
1.126     brouard  5184:   jmax=-1;
                   5185:   jmean=0.;
1.224     brouard  5186: 
                   5187: /* Treating live states */
1.214     brouard  5188:   for(i=1; i<=imx; i++){  /* For simple cases and if state is death */
1.224     brouard  5189:     mi=0;  /* First valid wave */
1.227     brouard  5190:     mli=0; /* Last valid wave */
1.126     brouard  5191:     m=firstpass;
1.214     brouard  5192:     while(s[m][i] <= nlstate){  /* a live state */
1.227     brouard  5193:       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 */
                   5194:        mli=m-1;/* mw[++mi][i]=m-1; */
                   5195:       }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 */
                   5196:        mw[++mi][i]=m;
                   5197:        mli=m;
1.224     brouard  5198:       } /* else might be a useless wave  -1 and mi is not incremented and mw[mi] not updated */
                   5199:       if(m < lastpass){ /* m < lastpass, standard case */
1.227     brouard  5200:        m++; /* mi gives the "effective" current wave, m the current wave, go to next wave by incrementing m */
1.216     brouard  5201:       }
1.227     brouard  5202:       else{ /* m >= lastpass, eventual special issue with warning */
1.224     brouard  5203: #ifdef UNKNOWNSTATUSNOTCONTRIBUTING
1.227     brouard  5204:        break;
1.224     brouard  5205: #else
1.227     brouard  5206:        if(s[m][i]==-1 && (int) andc[i] == 9999 && (int)anint[m][i] != 9999){
                   5207:          if(firsthree == 0){
1.262     brouard  5208:            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  5209:            firsthree=1;
                   5210:          }
1.262     brouard  5211:          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  5212:          mw[++mi][i]=m;
                   5213:          mli=m;
                   5214:        }
                   5215:        if(s[m][i]==-2){ /* Vital status is really unknown */
                   5216:          nbwarn++;
                   5217:          if((int)anint[m][i] == 9999){  /*  Has the vital status really been verified? */
                   5218:            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);
                   5219:            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);
                   5220:          }
                   5221:          break;
                   5222:        }
                   5223:        break;
1.224     brouard  5224: #endif
1.227     brouard  5225:       }/* End m >= lastpass */
1.126     brouard  5226:     }/* end while */
1.224     brouard  5227: 
1.227     brouard  5228:     /* 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  5229:     /* After last pass */
1.224     brouard  5230: /* Treating death states */
1.214     brouard  5231:     if (s[m][i] > nlstate){  /* In a death state */
1.227     brouard  5232:       /* if( mint[m][i]==mdc[m][i] && anint[m][i]==andc[m][i]){ /\* same date of death and date of interview *\/ */
                   5233:       /* } */
1.126     brouard  5234:       mi++;    /* Death is another wave */
                   5235:       /* if(mi==0)  never been interviewed correctly before death */
1.227     brouard  5236:       /* Only death is a correct wave */
1.126     brouard  5237:       mw[mi][i]=m;
1.257     brouard  5238:     } /* else not in a death state */
1.224     brouard  5239: #ifndef DISPATCHINGKNOWNDEATHAFTERLASTWAVE
1.257     brouard  5240:     else if ((int) andc[i] != 9999) {  /* Date of death is known */
1.218     brouard  5241:       if ((int)anint[m][i]!= 9999) { /* date of last interview is known */
1.227     brouard  5242:        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 */
                   5243:          nbwarn++;
                   5244:          if(firstfiv==0){
                   5245:            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 );
                   5246:            firstfiv=1;
                   5247:          }else{
                   5248:            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 );
                   5249:          }
                   5250:        }else{ /* Death occured afer last wave potential bias */
                   5251:          nberr++;
                   5252:          if(firstwo==0){
1.257     brouard  5253:            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  5254:            firstwo=1;
                   5255:          }
1.257     brouard  5256:          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  5257:        }
1.257     brouard  5258:       }else{ /* if date of interview is unknown */
1.227     brouard  5259:        /* death is known but not confirmed by death status at any wave */
                   5260:        if(firstfour==0){
                   5261:          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 );
                   5262:          firstfour=1;
                   5263:        }
                   5264:        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  5265:       }
1.224     brouard  5266:     } /* end if date of death is known */
                   5267: #endif
                   5268:     wav[i]=mi; /* mi should be the last effective wave (or mli) */
                   5269:     /* wav[i]=mw[mi][i]; */
1.126     brouard  5270:     if(mi==0){
                   5271:       nbwarn++;
                   5272:       if(first==0){
1.227     brouard  5273:        printf("Warning! No valid information for individual %ld line=%d (skipped) and may be others, see log file\n",num[i],i);
                   5274:        first=1;
1.126     brouard  5275:       }
                   5276:       if(first==1){
1.227     brouard  5277:        fprintf(ficlog,"Warning! No valid information for individual %ld line=%d (skipped)\n",num[i],i);
1.126     brouard  5278:       }
                   5279:     } /* end mi==0 */
                   5280:   } /* End individuals */
1.214     brouard  5281:   /* wav and mw are no more changed */
1.223     brouard  5282:        
1.214     brouard  5283:   
1.126     brouard  5284:   for(i=1; i<=imx; i++){
                   5285:     for(mi=1; mi<wav[i];mi++){
                   5286:       if (stepm <=0)
1.227     brouard  5287:        dh[mi][i]=1;
1.126     brouard  5288:       else{
1.260     brouard  5289:        if (s[mw[mi+1][i]][i] > nlstate) { /* A death, but what if date is unknown? */
1.227     brouard  5290:          if (agedc[i] < 2*AGESUP) {
                   5291:            j= rint(agedc[i]*12-agev[mw[mi][i]][i]*12); 
                   5292:            if(j==0) j=1;  /* Survives at least one month after exam */
                   5293:            else if(j<0){
                   5294:              nberr++;
                   5295:              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]);
                   5296:              j=1; /* Temporary Dangerous patch */
                   5297:              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);
                   5298:              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]);
                   5299:              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);
                   5300:            }
                   5301:            k=k+1;
                   5302:            if (j >= jmax){
                   5303:              jmax=j;
                   5304:              ijmax=i;
                   5305:            }
                   5306:            if (j <= jmin){
                   5307:              jmin=j;
                   5308:              ijmin=i;
                   5309:            }
                   5310:            sum=sum+j;
                   5311:            /*if (j<0) printf("j=%d num=%d \n",j,i);*/
                   5312:            /*    printf("%d %d %d %d\n", s[mw[mi][i]][i] ,s[mw[mi+1][i]][i],j,i);*/
                   5313:          }
                   5314:        }
                   5315:        else{
                   5316:          j= rint( (agev[mw[mi+1][i]][i]*12 - agev[mw[mi][i]][i]*12));
1.126     brouard  5317: /*       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  5318:                                        
1.227     brouard  5319:          k=k+1;
                   5320:          if (j >= jmax) {
                   5321:            jmax=j;
                   5322:            ijmax=i;
                   5323:          }
                   5324:          else if (j <= jmin){
                   5325:            jmin=j;
                   5326:            ijmin=i;
                   5327:          }
                   5328:          /*        if (j<10) printf("j=%d jmin=%d num=%d ",j,jmin,i); */
                   5329:          /*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]);*/
                   5330:          if(j<0){
                   5331:            nberr++;
                   5332:            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]);
                   5333:            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]);
                   5334:          }
                   5335:          sum=sum+j;
                   5336:        }
                   5337:        jk= j/stepm;
                   5338:        jl= j -jk*stepm;
                   5339:        ju= j -(jk+1)*stepm;
                   5340:        if(mle <=1){ /* only if we use a the linear-interpoloation pseudo-likelihood */
                   5341:          if(jl==0){
                   5342:            dh[mi][i]=jk;
                   5343:            bh[mi][i]=0;
                   5344:          }else{ /* We want a negative bias in order to only have interpolation ie
                   5345:                  * to avoid the price of an extra matrix product in likelihood */
                   5346:            dh[mi][i]=jk+1;
                   5347:            bh[mi][i]=ju;
                   5348:          }
                   5349:        }else{
                   5350:          if(jl <= -ju){
                   5351:            dh[mi][i]=jk;
                   5352:            bh[mi][i]=jl;       /* bias is positive if real duration
                   5353:                                 * is higher than the multiple of stepm and negative otherwise.
                   5354:                                 */
                   5355:          }
                   5356:          else{
                   5357:            dh[mi][i]=jk+1;
                   5358:            bh[mi][i]=ju;
                   5359:          }
                   5360:          if(dh[mi][i]==0){
                   5361:            dh[mi][i]=1; /* At least one step */
                   5362:            bh[mi][i]=ju; /* At least one step */
                   5363:            /*  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);*/
                   5364:          }
                   5365:        } /* end if mle */
1.126     brouard  5366:       }
                   5367:     } /* end wave */
                   5368:   }
                   5369:   jmean=sum/k;
                   5370:   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  5371:   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  5372: }
1.126     brouard  5373: 
                   5374: /*********** Tricode ****************************/
1.220     brouard  5375:  void tricode(int *cptcov, int *Tvar, int **nbcode, int imx, int *Ndum)
1.242     brouard  5376:  {
                   5377:    /**< Uses cptcovn+2*cptcovprod as the number of covariates */
                   5378:    /*    Tvar[i]=atoi(stre);  find 'n' in Vn and stores in Tvar. If model=V2+V1 Tvar[1]=2 and Tvar[2]=1 
                   5379:     * Boring subroutine which should only output nbcode[Tvar[j]][k]
                   5380:     * Tvar[5] in V2+V1+V3*age+V2*V4 is 4 (V4) even it is a time varying or quantitative variable
                   5381:     * nbcode[Tvar[5]][1]= nbcode[4][1]=0, nbcode[4][2]=1 (usually);
                   5382:     */
1.130     brouard  5383: 
1.242     brouard  5384:    int ij=1, k=0, j=0, i=0, maxncov=NCOVMAX;
                   5385:    int modmaxcovj=0; /* Modality max of covariates j */
                   5386:    int cptcode=0; /* Modality max of covariates j */
                   5387:    int modmincovj=0; /* Modality min of covariates j */
1.145     brouard  5388: 
                   5389: 
1.242     brouard  5390:    /* cptcoveff=0;  */
                   5391:    /* *cptcov=0; */
1.126     brouard  5392:  
1.242     brouard  5393:    for (k=1; k <= maxncov; k++) ncodemax[k]=0; /* Horrible constant again replaced by NCOVMAX */
1.285     brouard  5394:    for (k=1; k <= maxncov; k++)
                   5395:      for(j=1; j<=2; j++)
                   5396:        nbcode[k][j]=0; /* Valgrind */
1.126     brouard  5397: 
1.242     brouard  5398:    /* Loop on covariates without age and products and no quantitative variable */
                   5399:    for (k=1; k<=cptcovt; k++) { /* From model V1 + V2*age + V3 + V3*V4 keeps V1 + V3 = 2 only */
                   5400:      for (j=-1; (j < maxncov); j++) Ndum[j]=0;
                   5401:      if(Dummy[k]==0 && Typevar[k] !=1){ /* Dummy covariate and not age product */ 
                   5402:        switch(Fixed[k]) {
                   5403:        case 0: /* Testing on fixed dummy covariate, simple or product of fixed */
                   5404:         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*/
                   5405:           ij=(int)(covar[Tvar[k]][i]);
                   5406:           /* ij=0 or 1 or -1. Value of the covariate Tvar[j] for individual i
                   5407:            * If product of Vn*Vm, still boolean *:
                   5408:            * If it was coded 1, 2, 3, 4 should be splitted into 3 boolean variables
                   5409:            * 1 => 0 0 0, 2 => 0 0 1, 3 => 0 1 1, 4=1 0 0   */
                   5410:           /* Finds for covariate j, n=Tvar[j] of Vn . ij is the
                   5411:              modality of the nth covariate of individual i. */
                   5412:           if (ij > modmaxcovj)
                   5413:             modmaxcovj=ij; 
                   5414:           else if (ij < modmincovj) 
                   5415:             modmincovj=ij; 
1.287     brouard  5416:           if (ij <0 || ij >1 ){
                   5417:             printf("Information, IMaCh doesn't treat covariate with missing values (-1), individual %d will be skipped.\n",i);
                   5418:             fprintf(ficlog,"Information, currently IMaCh doesn't treat covariate with missing values (-1), individual %d will be skipped.\n",i);
                   5419:           }
                   5420:           if ((ij < -1) || (ij > NCOVMAX)){
1.242     brouard  5421:             printf( "Error: minimal is less than -1 or maximal is bigger than %d. Exiting. \n", NCOVMAX );
                   5422:             exit(1);
                   5423:           }else
                   5424:             Ndum[ij]++; /*counts and stores the occurence of this modality 0, 1, -1*/
                   5425:           /*  If coded 1, 2, 3 , counts the number of 1 Ndum[1], number of 2, Ndum[2], etc */
                   5426:           /*printf("i=%d ij=%d Ndum[ij]=%d imx=%d",i,ij,Ndum[ij],imx);*/
                   5427:           /* getting the maximum value of the modality of the covariate
                   5428:              (should be 0 or 1 now) Tvar[j]. If V=sex and male is coded 0 and
                   5429:              female ies 1, then modmaxcovj=1.
                   5430:           */
                   5431:         } /* end for loop on individuals i */
                   5432:         printf(" Minimal and maximal values of %d th (fixed) covariate V%d: min=%d max=%d \n", k, Tvar[k], modmincovj, modmaxcovj);
                   5433:         fprintf(ficlog," Minimal and maximal values of %d th (fixed) covariate V%d: min=%d max=%d \n", k, Tvar[k], modmincovj, modmaxcovj);
                   5434:         cptcode=modmaxcovj;
                   5435:         /* Ndum[0] = frequency of 0 for model-covariate j, Ndum[1] frequency of 1 etc. */
                   5436:         /*for (i=0; i<=cptcode; i++) {*/
                   5437:         for (j=modmincovj;  j<=modmaxcovj; j++) { /* j=-1 ? 0 and 1*//* For each value j of the modality of model-cov k */
                   5438:           printf("Frequencies of (fixed) covariate %d ie V%d with value %d: %d\n", k, Tvar[k], j, Ndum[j]);
                   5439:           fprintf(ficlog, "Frequencies of (fixed) covariate %d ie V%d with value %d: %d\n", k, Tvar[k], j, Ndum[j]);
                   5440:           if( Ndum[j] != 0 ){ /* Counts if nobody answered modality j ie empty modality, we skip it and reorder */
                   5441:             if( j != -1){
                   5442:               ncodemax[k]++;  /* ncodemax[k]= Number of modalities of the k th
                   5443:                                  covariate for which somebody answered excluding 
                   5444:                                  undefined. Usually 2: 0 and 1. */
                   5445:             }
                   5446:             ncodemaxwundef[k]++; /* ncodemax[j]= Number of modalities of the k th
                   5447:                                     covariate for which somebody answered including 
                   5448:                                     undefined. Usually 3: -1, 0 and 1. */
                   5449:           }    /* In fact  ncodemax[k]=2 (dichotom. variables only) but it could be more for
                   5450:                 * historical reasons: 3 if coded 1, 2, 3 and 4 and Ndum[2]=0 */
                   5451:         } /* Ndum[-1] number of undefined modalities */
1.231     brouard  5452:                        
1.242     brouard  5453:         /* j is a covariate, n=Tvar[j] of Vn; Fills nbcode */
                   5454:         /* For covariate j, modalities could be 1, 2, 3, 4, 5, 6, 7. */
                   5455:         /* If Ndum[1]=0, Ndum[2]=0, Ndum[3]= 635, Ndum[4]=0, Ndum[5]=0, Ndum[6]=27, Ndum[7]=125; */
                   5456:         /* modmincovj=3; modmaxcovj = 7; */
                   5457:         /* There are only 3 modalities non empty 3, 6, 7 (or 2 if 27 is too few) : ncodemax[j]=3; */
                   5458:         /* which will be coded 0, 1, 2 which in binary on 2=3-1 digits are 0=00 1=01, 2=10; */
                   5459:         /*              defining two dummy variables: variables V1_1 and V1_2.*/
                   5460:         /* nbcode[Tvar[j]][ij]=k; */
                   5461:         /* nbcode[Tvar[j]][1]=0; */
                   5462:         /* nbcode[Tvar[j]][2]=1; */
                   5463:         /* nbcode[Tvar[j]][3]=2; */
                   5464:         /* To be continued (not working yet). */
                   5465:         ij=0; /* ij is similar to i but can jump over null modalities */
1.287     brouard  5466: 
                   5467:         /* 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*/
                   5468:         /* Skipping the case of missing values by reducing nbcode to 0 and 1 and not -1, 0, 1 */
                   5469:         /* model=V1+V2+V3, if V2=-1, 0 or 1, then nbcode[2][1]=0 and nbcode[2][2]=1 instead of
                   5470:          * nbcode[2][1]=-1, nbcode[2][2]=0 and nbcode[2][3]=1 */
                   5471:         /*, could be restored in the future */
                   5472:         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  5473:           if (Ndum[i] == 0) { /* If nobody responded to this modality k */
                   5474:             break;
                   5475:           }
                   5476:           ij++;
1.287     brouard  5477:           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  5478:           cptcode = ij; /* New max modality for covar j */
                   5479:         } /* end of loop on modality i=-1 to 1 or more */
                   5480:         break;
                   5481:        case 1: /* Testing on varying covariate, could be simple and
                   5482:                * should look at waves or product of fixed *
                   5483:                * varying. No time to test -1, assuming 0 and 1 only */
                   5484:         ij=0;
                   5485:         for(i=0; i<=1;i++){
                   5486:           nbcode[Tvar[k]][++ij]=i;
                   5487:         }
                   5488:         break;
                   5489:        default:
                   5490:         break;
                   5491:        } /* end switch */
                   5492:      } /* end dummy test */
1.287     brouard  5493:    } /* 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  5494:   
                   5495:    for (k=-1; k< maxncov; k++) Ndum[k]=0; 
                   5496:    /* Look at fixed dummy (single or product) covariates to check empty modalities */
                   5497:    for (i=1; i<=ncovmodel-2-nagesqr; i++) { /* -2, cste and age and eventually age*age */ 
                   5498:      /* Listing of all covariables in statement model to see if some covariates appear twice. For example, V1 appears twice in V1+V1*V2.*/ 
                   5499:      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 */ 
                   5500:      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 */
                   5501:      /* V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1,  {2, 1, 1, 1, 2, 1, 1, 0, 0} */
                   5502:    } /* V4+V3+V5, Ndum[1]@5={0, 0, 1, 1, 1} */
                   5503:   
                   5504:    ij=0;
                   5505:    /* for (i=0; i<=  maxncov-1; i++) { /\* modmaxcovj is unknown here. Only Ndum[2(V2),3(age*V3), 5(V3*V2) 6(V1*V4) *\/ */
                   5506:    for (k=1; k<=  cptcovt; k++) { /* modmaxcovj is unknown here. Only Ndum[2(V2),3(age*V3), 5(V3*V2) 6(V1*V4) */
                   5507:      /*printf("Ndum[%d]=%d\n",i, Ndum[i]);*/
                   5508:      /* if((Ndum[i]!=0) && (i<=ncovcol)){  /\* Tvar[i] <= ncovmodel ? *\/ */
                   5509:      if(Ndum[Tvar[k]]!=0 && Dummy[k] == 0 && Typevar[k]==0){  /* Only Dummy and non empty in the model */
                   5510:        /* If product not in single variable we don't print results */
                   5511:        /*printf("diff Ndum[%d]=%d\n",i, Ndum[i]);*/
                   5512:        ++ij;/* V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1, */
                   5513:        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*/
                   5514:        Tmodelind[ij]=k; /* Tmodelind: index in model of dummies Tmodelind[1]=2 V4: pos=2; V3: pos=3, V1=9 {2, 3, 9, ?, ?,} */
                   5515:        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 */
                   5516:        if(Fixed[k]!=0)
                   5517:         anyvaryingduminmodel=1;
                   5518:        /* }else if((Ndum[i]!=0) && (i<=ncovcol+nqv)){ */
                   5519:        /*   Tvaraff[++ij]=-10; /\* Dont'n know how to treat quantitative variables yet *\/ */
                   5520:        /* }else if((Ndum[i]!=0) && (i<=ncovcol+nqv+ntv)){ */
                   5521:        /*   Tvaraff[++ij]=i; /\*For printing (unclear) *\/ */
                   5522:        /* }else if((Ndum[i]!=0) && (i<=ncovcol+nqv+ntv+nqtv)){ */
                   5523:        /*   Tvaraff[++ij]=-20; /\* Dont'n know how to treat quantitative variables yet *\/ */
                   5524:      } 
                   5525:    } /* Tvaraff[1]@5 {3, 4, -20, 0, 0} Very strange */
                   5526:    /* ij--; */
                   5527:    /* cptcoveff=ij; /\*Number of total covariates*\/ */
                   5528:    *cptcov=ij; /*Number of total real effective covariates: effective
                   5529:                * because they can be excluded from the model and real
                   5530:                * if in the model but excluded because missing values, but how to get k from ij?*/
                   5531:    for(j=ij+1; j<= cptcovt; j++){
                   5532:      Tvaraff[j]=0;
                   5533:      Tmodelind[j]=0;
                   5534:    }
                   5535:    for(j=ntveff+1; j<= cptcovt; j++){
                   5536:      TmodelInvind[j]=0;
                   5537:    }
                   5538:    /* To be sorted */
                   5539:    ;
                   5540:  }
1.126     brouard  5541: 
1.145     brouard  5542: 
1.126     brouard  5543: /*********** Health Expectancies ****************/
                   5544: 
1.235     brouard  5545:  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  5546: 
                   5547: {
                   5548:   /* Health expectancies, no variances */
1.164     brouard  5549:   int i, j, nhstepm, hstepm, h, nstepm;
1.126     brouard  5550:   int nhstepma, nstepma; /* Decreasing with age */
                   5551:   double age, agelim, hf;
                   5552:   double ***p3mat;
                   5553:   double eip;
                   5554: 
1.238     brouard  5555:   /* pstamp(ficreseij); */
1.126     brouard  5556:   fprintf(ficreseij,"# (a) Life expectancies by health status at initial age and (b) health expectancies by health status at initial age\n");
                   5557:   fprintf(ficreseij,"# Age");
                   5558:   for(i=1; i<=nlstate;i++){
                   5559:     for(j=1; j<=nlstate;j++){
                   5560:       fprintf(ficreseij," e%1d%1d ",i,j);
                   5561:     }
                   5562:     fprintf(ficreseij," e%1d. ",i);
                   5563:   }
                   5564:   fprintf(ficreseij,"\n");
                   5565: 
                   5566:   
                   5567:   if(estepm < stepm){
                   5568:     printf ("Problem %d lower than %d\n",estepm, stepm);
                   5569:   }
                   5570:   else  hstepm=estepm;   
                   5571:   /* We compute the life expectancy from trapezoids spaced every estepm months
                   5572:    * This is mainly to measure the difference between two models: for example
                   5573:    * if stepm=24 months pijx are given only every 2 years and by summing them
                   5574:    * we are calculating an estimate of the Life Expectancy assuming a linear 
                   5575:    * progression in between and thus overestimating or underestimating according
                   5576:    * to the curvature of the survival function. If, for the same date, we 
                   5577:    * estimate the model with stepm=1 month, we can keep estepm to 24 months
                   5578:    * to compare the new estimate of Life expectancy with the same linear 
                   5579:    * hypothesis. A more precise result, taking into account a more precise
                   5580:    * curvature will be obtained if estepm is as small as stepm. */
                   5581: 
                   5582:   /* For example we decided to compute the life expectancy with the smallest unit */
                   5583:   /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm. 
                   5584:      nhstepm is the number of hstepm from age to agelim 
                   5585:      nstepm is the number of stepm from age to agelin. 
1.270     brouard  5586:      Look at hpijx to understand the reason which relies in memory size consideration
1.126     brouard  5587:      and note for a fixed period like estepm months */
                   5588:   /* We decided (b) to get a life expectancy respecting the most precise curvature of the
                   5589:      survival function given by stepm (the optimization length). Unfortunately it
                   5590:      means that if the survival funtion is printed only each two years of age and if
                   5591:      you sum them up and add 1 year (area under the trapezoids) you won't get the same 
                   5592:      results. So we changed our mind and took the option of the best precision.
                   5593:   */
                   5594:   hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */ 
                   5595: 
                   5596:   agelim=AGESUP;
                   5597:   /* If stepm=6 months */
                   5598:     /* Computed by stepm unit matrices, product of hstepm matrices, stored
                   5599:        in an array of nhstepm length: nhstepm=10, hstepm=4, stepm=6 months */
                   5600:     
                   5601: /* nhstepm age range expressed in number of stepm */
                   5602:   nstepm=(int) rint((agelim-bage)*YEARM/stepm); /* Biggest nstepm */
                   5603:   /* Typically if 20 years nstepm = 20*12/6=40 stepm */ 
                   5604:   /* if (stepm >= YEARM) hstepm=1;*/
                   5605:   nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
                   5606:   p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   5607: 
                   5608:   for (age=bage; age<=fage; age ++){ 
                   5609:     nstepma=(int) rint((agelim-bage)*YEARM/stepm); /* Biggest nstepm */
                   5610:     /* Typically if 20 years nstepm = 20*12/6=40 stepm */ 
                   5611:     /* if (stepm >= YEARM) hstepm=1;*/
                   5612:     nhstepma = nstepma/hstepm;/* Expressed in hstepm, typically nhstepma=40/4=10 */
                   5613: 
                   5614:     /* If stepm=6 months */
                   5615:     /* Computed by stepm unit matrices, product of hstepma matrices, stored
                   5616:        in an array of nhstepma length: nhstepma=10, hstepm=4, stepm=6 months */
                   5617:     
1.235     brouard  5618:     hpxij(p3mat,nhstepma,age,hstepm,x,nlstate,stepm,oldm, savm, cij, nres);  
1.126     brouard  5619:     
                   5620:     hf=hstepm*stepm/YEARM;  /* Duration of hstepm expressed in year unit. */
                   5621:     
                   5622:     printf("%d|",(int)age);fflush(stdout);
                   5623:     fprintf(ficlog,"%d|",(int)age);fflush(ficlog);
                   5624:     
                   5625:     /* Computing expectancies */
                   5626:     for(i=1; i<=nlstate;i++)
                   5627:       for(j=1; j<=nlstate;j++)
                   5628:        for (h=0, eij[i][j][(int)age]=0; h<=nhstepm-1; h++){
                   5629:          eij[i][j][(int)age] += (p3mat[i][j][h]+p3mat[i][j][h+1])/2.0*hf;
                   5630:          
                   5631:          /* 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]);*/
                   5632: 
                   5633:        }
                   5634: 
                   5635:     fprintf(ficreseij,"%3.0f",age );
                   5636:     for(i=1; i<=nlstate;i++){
                   5637:       eip=0;
                   5638:       for(j=1; j<=nlstate;j++){
                   5639:        eip +=eij[i][j][(int)age];
                   5640:        fprintf(ficreseij,"%9.4f", eij[i][j][(int)age] );
                   5641:       }
                   5642:       fprintf(ficreseij,"%9.4f", eip );
                   5643:     }
                   5644:     fprintf(ficreseij,"\n");
                   5645:     
                   5646:   }
                   5647:   free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   5648:   printf("\n");
                   5649:   fprintf(ficlog,"\n");
                   5650:   
                   5651: }
                   5652: 
1.235     brouard  5653:  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  5654: 
                   5655: {
                   5656:   /* Covariances of health expectancies eij and of total life expectancies according
1.222     brouard  5657:      to initial status i, ei. .
1.126     brouard  5658:   */
                   5659:   int i, j, nhstepm, hstepm, h, nstepm, k, cptj, cptj2, i2, j2, ij, ji;
                   5660:   int nhstepma, nstepma; /* Decreasing with age */
                   5661:   double age, agelim, hf;
                   5662:   double ***p3matp, ***p3matm, ***varhe;
                   5663:   double **dnewm,**doldm;
                   5664:   double *xp, *xm;
                   5665:   double **gp, **gm;
                   5666:   double ***gradg, ***trgradg;
                   5667:   int theta;
                   5668: 
                   5669:   double eip, vip;
                   5670: 
                   5671:   varhe=ma3x(1,nlstate*nlstate,1,nlstate*nlstate,(int) bage, (int) fage);
                   5672:   xp=vector(1,npar);
                   5673:   xm=vector(1,npar);
                   5674:   dnewm=matrix(1,nlstate*nlstate,1,npar);
                   5675:   doldm=matrix(1,nlstate*nlstate,1,nlstate*nlstate);
                   5676:   
                   5677:   pstamp(ficresstdeij);
                   5678:   fprintf(ficresstdeij,"# Health expectancies with standard errors\n");
                   5679:   fprintf(ficresstdeij,"# Age");
                   5680:   for(i=1; i<=nlstate;i++){
                   5681:     for(j=1; j<=nlstate;j++)
                   5682:       fprintf(ficresstdeij," e%1d%1d (SE)",i,j);
                   5683:     fprintf(ficresstdeij," e%1d. ",i);
                   5684:   }
                   5685:   fprintf(ficresstdeij,"\n");
                   5686: 
                   5687:   pstamp(ficrescveij);
                   5688:   fprintf(ficrescveij,"# Subdiagonal matrix of covariances of health expectancies by age: cov(eij,ekl)\n");
                   5689:   fprintf(ficrescveij,"# Age");
                   5690:   for(i=1; i<=nlstate;i++)
                   5691:     for(j=1; j<=nlstate;j++){
                   5692:       cptj= (j-1)*nlstate+i;
                   5693:       for(i2=1; i2<=nlstate;i2++)
                   5694:        for(j2=1; j2<=nlstate;j2++){
                   5695:          cptj2= (j2-1)*nlstate+i2;
                   5696:          if(cptj2 <= cptj)
                   5697:            fprintf(ficrescveij,"  %1d%1d,%1d%1d",i,j,i2,j2);
                   5698:        }
                   5699:     }
                   5700:   fprintf(ficrescveij,"\n");
                   5701:   
                   5702:   if(estepm < stepm){
                   5703:     printf ("Problem %d lower than %d\n",estepm, stepm);
                   5704:   }
                   5705:   else  hstepm=estepm;   
                   5706:   /* We compute the life expectancy from trapezoids spaced every estepm months
                   5707:    * This is mainly to measure the difference between two models: for example
                   5708:    * if stepm=24 months pijx are given only every 2 years and by summing them
                   5709:    * we are calculating an estimate of the Life Expectancy assuming a linear 
                   5710:    * progression in between and thus overestimating or underestimating according
                   5711:    * to the curvature of the survival function. If, for the same date, we 
                   5712:    * estimate the model with stepm=1 month, we can keep estepm to 24 months
                   5713:    * to compare the new estimate of Life expectancy with the same linear 
                   5714:    * hypothesis. A more precise result, taking into account a more precise
                   5715:    * curvature will be obtained if estepm is as small as stepm. */
                   5716: 
                   5717:   /* For example we decided to compute the life expectancy with the smallest unit */
                   5718:   /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm. 
                   5719:      nhstepm is the number of hstepm from age to agelim 
                   5720:      nstepm is the number of stepm from age to agelin. 
                   5721:      Look at hpijx to understand the reason of that which relies in memory size
                   5722:      and note for a fixed period like estepm months */
                   5723:   /* We decided (b) to get a life expectancy respecting the most precise curvature of the
                   5724:      survival function given by stepm (the optimization length). Unfortunately it
                   5725:      means that if the survival funtion is printed only each two years of age and if
                   5726:      you sum them up and add 1 year (area under the trapezoids) you won't get the same 
                   5727:      results. So we changed our mind and took the option of the best precision.
                   5728:   */
                   5729:   hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */ 
                   5730: 
                   5731:   /* If stepm=6 months */
                   5732:   /* nhstepm age range expressed in number of stepm */
                   5733:   agelim=AGESUP;
                   5734:   nstepm=(int) rint((agelim-bage)*YEARM/stepm); 
                   5735:   /* Typically if 20 years nstepm = 20*12/6=40 stepm */ 
                   5736:   /* if (stepm >= YEARM) hstepm=1;*/
                   5737:   nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
                   5738:   
                   5739:   p3matp=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   5740:   p3matm=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   5741:   gradg=ma3x(0,nhstepm,1,npar,1,nlstate*nlstate);
                   5742:   trgradg =ma3x(0,nhstepm,1,nlstate*nlstate,1,npar);
                   5743:   gp=matrix(0,nhstepm,1,nlstate*nlstate);
                   5744:   gm=matrix(0,nhstepm,1,nlstate*nlstate);
                   5745: 
                   5746:   for (age=bage; age<=fage; age ++){ 
                   5747:     nstepma=(int) rint((agelim-bage)*YEARM/stepm); /* Biggest nstepm */
                   5748:     /* Typically if 20 years nstepm = 20*12/6=40 stepm */ 
                   5749:     /* if (stepm >= YEARM) hstepm=1;*/
                   5750:     nhstepma = nstepma/hstepm;/* Expressed in hstepm, typically nhstepma=40/4=10 */
1.218     brouard  5751:                
1.126     brouard  5752:     /* If stepm=6 months */
                   5753:     /* Computed by stepm unit matrices, product of hstepma matrices, stored
                   5754:        in an array of nhstepma length: nhstepma=10, hstepm=4, stepm=6 months */
                   5755:     
                   5756:     hf=hstepm*stepm/YEARM;  /* Duration of hstepm expressed in year unit. */
1.218     brouard  5757:                
1.126     brouard  5758:     /* Computing  Variances of health expectancies */
                   5759:     /* Gradient is computed with plus gp and minus gm. Code is duplicated in order to
                   5760:        decrease memory allocation */
                   5761:     for(theta=1; theta <=npar; theta++){
                   5762:       for(i=1; i<=npar; i++){ 
1.222     brouard  5763:        xp[i] = x[i] + (i==theta ?delti[theta]:0);
                   5764:        xm[i] = x[i] - (i==theta ?delti[theta]:0);
1.126     brouard  5765:       }
1.235     brouard  5766:       hpxij(p3matp,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, cij, nres);  
                   5767:       hpxij(p3matm,nhstepm,age,hstepm,xm,nlstate,stepm,oldm,savm, cij, nres);  
1.218     brouard  5768:                        
1.126     brouard  5769:       for(j=1; j<= nlstate; j++){
1.222     brouard  5770:        for(i=1; i<=nlstate; i++){
                   5771:          for(h=0; h<=nhstepm-1; h++){
                   5772:            gp[h][(j-1)*nlstate + i] = (p3matp[i][j][h]+p3matp[i][j][h+1])/2.;
                   5773:            gm[h][(j-1)*nlstate + i] = (p3matm[i][j][h]+p3matm[i][j][h+1])/2.;
                   5774:          }
                   5775:        }
1.126     brouard  5776:       }
1.218     brouard  5777:                        
1.126     brouard  5778:       for(ij=1; ij<= nlstate*nlstate; ij++)
1.222     brouard  5779:        for(h=0; h<=nhstepm-1; h++){
                   5780:          gradg[h][theta][ij]= (gp[h][ij]-gm[h][ij])/2./delti[theta];
                   5781:        }
1.126     brouard  5782:     }/* End theta */
                   5783:     
                   5784:     
                   5785:     for(h=0; h<=nhstepm-1; h++)
                   5786:       for(j=1; j<=nlstate*nlstate;j++)
1.222     brouard  5787:        for(theta=1; theta <=npar; theta++)
                   5788:          trgradg[h][j][theta]=gradg[h][theta][j];
1.126     brouard  5789:     
1.218     brouard  5790:                
1.222     brouard  5791:     for(ij=1;ij<=nlstate*nlstate;ij++)
1.126     brouard  5792:       for(ji=1;ji<=nlstate*nlstate;ji++)
1.222     brouard  5793:        varhe[ij][ji][(int)age] =0.;
1.218     brouard  5794:                
1.222     brouard  5795:     printf("%d|",(int)age);fflush(stdout);
                   5796:     fprintf(ficlog,"%d|",(int)age);fflush(ficlog);
                   5797:     for(h=0;h<=nhstepm-1;h++){
1.126     brouard  5798:       for(k=0;k<=nhstepm-1;k++){
1.222     brouard  5799:        matprod2(dnewm,trgradg[h],1,nlstate*nlstate,1,npar,1,npar,matcov);
                   5800:        matprod2(doldm,dnewm,1,nlstate*nlstate,1,npar,1,nlstate*nlstate,gradg[k]);
                   5801:        for(ij=1;ij<=nlstate*nlstate;ij++)
                   5802:          for(ji=1;ji<=nlstate*nlstate;ji++)
                   5803:            varhe[ij][ji][(int)age] += doldm[ij][ji]*hf*hf;
1.126     brouard  5804:       }
                   5805:     }
1.218     brouard  5806:                
1.126     brouard  5807:     /* Computing expectancies */
1.235     brouard  5808:     hpxij(p3matm,nhstepm,age,hstepm,x,nlstate,stepm,oldm, savm, cij,nres);  
1.126     brouard  5809:     for(i=1; i<=nlstate;i++)
                   5810:       for(j=1; j<=nlstate;j++)
1.222     brouard  5811:        for (h=0, eij[i][j][(int)age]=0; h<=nhstepm-1; h++){
                   5812:          eij[i][j][(int)age] += (p3matm[i][j][h]+p3matm[i][j][h+1])/2.0*hf;
1.218     brouard  5813:                                        
1.222     brouard  5814:          /* 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  5815:                                        
1.222     brouard  5816:        }
1.269     brouard  5817: 
                   5818:     /* Standard deviation of expectancies ij */                
1.126     brouard  5819:     fprintf(ficresstdeij,"%3.0f",age );
                   5820:     for(i=1; i<=nlstate;i++){
                   5821:       eip=0.;
                   5822:       vip=0.;
                   5823:       for(j=1; j<=nlstate;j++){
1.222     brouard  5824:        eip += eij[i][j][(int)age];
                   5825:        for(k=1; k<=nlstate;k++) /* Sum on j and k of cov(eij,eik) */
                   5826:          vip += varhe[(j-1)*nlstate+i][(k-1)*nlstate+i][(int)age];
                   5827:        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  5828:       }
                   5829:       fprintf(ficresstdeij," %9.4f (%.4f)", eip, sqrt(vip));
                   5830:     }
                   5831:     fprintf(ficresstdeij,"\n");
1.218     brouard  5832:                
1.269     brouard  5833:     /* Variance of expectancies ij */          
1.126     brouard  5834:     fprintf(ficrescveij,"%3.0f",age );
                   5835:     for(i=1; i<=nlstate;i++)
                   5836:       for(j=1; j<=nlstate;j++){
1.222     brouard  5837:        cptj= (j-1)*nlstate+i;
                   5838:        for(i2=1; i2<=nlstate;i2++)
                   5839:          for(j2=1; j2<=nlstate;j2++){
                   5840:            cptj2= (j2-1)*nlstate+i2;
                   5841:            if(cptj2 <= cptj)
                   5842:              fprintf(ficrescveij," %.4f", varhe[cptj][cptj2][(int)age]);
                   5843:          }
1.126     brouard  5844:       }
                   5845:     fprintf(ficrescveij,"\n");
1.218     brouard  5846:                
1.126     brouard  5847:   }
                   5848:   free_matrix(gm,0,nhstepm,1,nlstate*nlstate);
                   5849:   free_matrix(gp,0,nhstepm,1,nlstate*nlstate);
                   5850:   free_ma3x(gradg,0,nhstepm,1,npar,1,nlstate*nlstate);
                   5851:   free_ma3x(trgradg,0,nhstepm,1,nlstate*nlstate,1,npar);
                   5852:   free_ma3x(p3matm,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   5853:   free_ma3x(p3matp,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   5854:   printf("\n");
                   5855:   fprintf(ficlog,"\n");
1.218     brouard  5856:        
1.126     brouard  5857:   free_vector(xm,1,npar);
                   5858:   free_vector(xp,1,npar);
                   5859:   free_matrix(dnewm,1,nlstate*nlstate,1,npar);
                   5860:   free_matrix(doldm,1,nlstate*nlstate,1,nlstate*nlstate);
                   5861:   free_ma3x(varhe,1,nlstate*nlstate,1,nlstate*nlstate,(int) bage, (int)fage);
                   5862: }
1.218     brouard  5863:  
1.126     brouard  5864: /************ Variance ******************/
1.235     brouard  5865:  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  5866:  {
1.279     brouard  5867:    /** Variance of health expectancies 
                   5868:     *  double **prevalim(double **prlim, int nlstate, double *xp, double age, double **oldm, double ** savm,double ftolpl);
                   5869:     * double **newm;
                   5870:     * int movingaverage(double ***probs, double bage,double fage, double ***mobaverage, int mobilav) 
                   5871:     */
1.218     brouard  5872:   
                   5873:    /* int movingaverage(); */
                   5874:    double **dnewm,**doldm;
                   5875:    double **dnewmp,**doldmp;
                   5876:    int i, j, nhstepm, hstepm, h, nstepm ;
1.288     brouard  5877:    int first=0;
1.218     brouard  5878:    int k;
                   5879:    double *xp;
1.279     brouard  5880:    double **gp, **gm;  /**< for var eij */
                   5881:    double ***gradg, ***trgradg; /**< for var eij */
                   5882:    double **gradgp, **trgradgp; /**< for var p point j */
                   5883:    double *gpp, *gmp; /**< for var p point j */
                   5884:    double **varppt; /**< for var p point j nlstate to nlstate+ndeath */
1.218     brouard  5885:    double ***p3mat;
                   5886:    double age,agelim, hf;
                   5887:    /* double ***mobaverage; */
                   5888:    int theta;
                   5889:    char digit[4];
                   5890:    char digitp[25];
                   5891: 
                   5892:    char fileresprobmorprev[FILENAMELENGTH];
                   5893: 
                   5894:    if(popbased==1){
                   5895:      if(mobilav!=0)
                   5896:        strcpy(digitp,"-POPULBASED-MOBILAV_");
                   5897:      else strcpy(digitp,"-POPULBASED-NOMOBIL_");
                   5898:    }
                   5899:    else 
                   5900:      strcpy(digitp,"-STABLBASED_");
1.126     brouard  5901: 
1.218     brouard  5902:    /* if (mobilav!=0) { */
                   5903:    /*   mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX); */
                   5904:    /*   if (movingaverage(probs, bage, fage, mobaverage,mobilav)!=0){ */
                   5905:    /*     fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav); */
                   5906:    /*     printf(" Error in movingaverage mobilav=%d\n",mobilav); */
                   5907:    /*   } */
                   5908:    /* } */
                   5909: 
                   5910:    strcpy(fileresprobmorprev,"PRMORPREV-"); 
                   5911:    sprintf(digit,"%-d",ij);
                   5912:    /*printf("DIGIT=%s, ij=%d ijr=%-d|\n",digit, ij,ij);*/
                   5913:    strcat(fileresprobmorprev,digit); /* Tvar to be done */
                   5914:    strcat(fileresprobmorprev,digitp); /* Popbased or not, mobilav or not */
                   5915:    strcat(fileresprobmorprev,fileresu);
                   5916:    if((ficresprobmorprev=fopen(fileresprobmorprev,"w"))==NULL) {
                   5917:      printf("Problem with resultfile: %s\n", fileresprobmorprev);
                   5918:      fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobmorprev);
                   5919:    }
                   5920:    printf("Computing total mortality p.j=w1*p1j+w2*p2j+..: result on file '%s' \n",fileresprobmorprev);
                   5921:    fprintf(ficlog,"Computing total mortality p.j=w1*p1j+w2*p2j+..: result on file '%s' \n",fileresprobmorprev);
                   5922:    pstamp(ficresprobmorprev);
                   5923:    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  5924:    fprintf(ficresprobmorprev,"# Selected quantitative variables and dummies");
                   5925:    for (j=1; j<= nsq; j++){ /* For each selected (single) quantitative value */
                   5926:      fprintf(ficresprobmorprev," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]);
                   5927:    }
                   5928:    for(j=1;j<=cptcoveff;j++) 
                   5929:      fprintf(ficresprobmorprev,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(ij,j)]);
                   5930:    fprintf(ficresprobmorprev,"\n");
                   5931: 
1.218     brouard  5932:    fprintf(ficresprobmorprev,"# Age cov=%-d",ij);
                   5933:    for(j=nlstate+1; j<=(nlstate+ndeath);j++){
                   5934:      fprintf(ficresprobmorprev," p.%-d SE",j);
                   5935:      for(i=1; i<=nlstate;i++)
                   5936:        fprintf(ficresprobmorprev," w%1d p%-d%-d",i,i,j);
                   5937:    }  
                   5938:    fprintf(ficresprobmorprev,"\n");
                   5939:   
                   5940:    fprintf(ficgp,"\n# Routine varevsij");
                   5941:    fprintf(ficgp,"\nunset title \n");
                   5942:    /* fprintf(fichtm, "#Local time at start: %s", strstart);*/
                   5943:    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");
                   5944:    fprintf(fichtm,"\n<br>%s  <br>\n",digitp);
1.279     brouard  5945: 
1.218     brouard  5946:    varppt = matrix(nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
                   5947:    pstamp(ficresvij);
                   5948:    fprintf(ficresvij,"# Variance and covariance of health expectancies e.j \n#  (weighted average of eij where weights are ");
                   5949:    if(popbased==1)
                   5950:      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);
                   5951:    else
                   5952:      fprintf(ficresvij,"the age specific period (stable) prevalences in each health state \n");
                   5953:    fprintf(ficresvij,"# Age");
                   5954:    for(i=1; i<=nlstate;i++)
                   5955:      for(j=1; j<=nlstate;j++)
                   5956:        fprintf(ficresvij," Cov(e.%1d, e.%1d)",i,j);
                   5957:    fprintf(ficresvij,"\n");
                   5958: 
                   5959:    xp=vector(1,npar);
                   5960:    dnewm=matrix(1,nlstate,1,npar);
                   5961:    doldm=matrix(1,nlstate,1,nlstate);
                   5962:    dnewmp= matrix(nlstate+1,nlstate+ndeath,1,npar);
                   5963:    doldmp= matrix(nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
                   5964: 
                   5965:    gradgp=matrix(1,npar,nlstate+1,nlstate+ndeath);
                   5966:    gpp=vector(nlstate+1,nlstate+ndeath);
                   5967:    gmp=vector(nlstate+1,nlstate+ndeath);
                   5968:    trgradgp =matrix(nlstate+1,nlstate+ndeath,1,npar); /* mu or p point j*/
1.126     brouard  5969:   
1.218     brouard  5970:    if(estepm < stepm){
                   5971:      printf ("Problem %d lower than %d\n",estepm, stepm);
                   5972:    }
                   5973:    else  hstepm=estepm;   
                   5974:    /* For example we decided to compute the life expectancy with the smallest unit */
                   5975:    /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm. 
                   5976:       nhstepm is the number of hstepm from age to agelim 
                   5977:       nstepm is the number of stepm from age to agelim. 
                   5978:       Look at function hpijx to understand why because of memory size limitations, 
                   5979:       we decided (b) to get a life expectancy respecting the most precise curvature of the
                   5980:       survival function given by stepm (the optimization length). Unfortunately it
                   5981:       means that if the survival funtion is printed every two years of age and if
                   5982:       you sum them up and add 1 year (area under the trapezoids) you won't get the same 
                   5983:       results. So we changed our mind and took the option of the best precision.
                   5984:    */
                   5985:    hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */ 
                   5986:    agelim = AGESUP;
                   5987:    for (age=bage; age<=fage; age ++){ /* If stepm=6 months */
                   5988:      nstepm=(int) rint((agelim-age)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */ 
                   5989:      nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
                   5990:      p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   5991:      gradg=ma3x(0,nhstepm,1,npar,1,nlstate);
                   5992:      gp=matrix(0,nhstepm,1,nlstate);
                   5993:      gm=matrix(0,nhstepm,1,nlstate);
                   5994:                
                   5995:                
                   5996:      for(theta=1; theta <=npar; theta++){
                   5997:        for(i=1; i<=npar; i++){ /* Computes gradient x + delta*/
                   5998:         xp[i] = x[i] + (i==theta ?delti[theta]:0);
                   5999:        }
1.279     brouard  6000:        /**< Computes the prevalence limit with parameter theta shifted of delta up to ftolpl precision and 
                   6001:        * returns into prlim .
1.288     brouard  6002:        */
1.242     brouard  6003:        prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp,ij, nres);
1.279     brouard  6004: 
                   6005:        /* If popbased = 1 we use crossection prevalences. Previous step is useless but prlim is created */
1.218     brouard  6006:        if (popbased==1) {
                   6007:         if(mobilav ==0){
                   6008:           for(i=1; i<=nlstate;i++)
                   6009:             prlim[i][i]=probs[(int)age][i][ij];
                   6010:         }else{ /* mobilav */ 
                   6011:           for(i=1; i<=nlstate;i++)
                   6012:             prlim[i][i]=mobaverage[(int)age][i][ij];
                   6013:         }
                   6014:        }
1.279     brouard  6015:        /**< Computes the shifted transition matrix \f$ {}{h}_p^{ij}_x\f$ at horizon h.
                   6016:        */                      
                   6017:        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  6018:        /**< 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  6019:        * at horizon h in state j including mortality.
                   6020:        */
1.218     brouard  6021:        for(j=1; j<= nlstate; j++){
                   6022:         for(h=0; h<=nhstepm; h++){
                   6023:           for(i=1, gp[h][j]=0.;i<=nlstate;i++)
                   6024:             gp[h][j] += prlim[i][i]*p3mat[i][j][h];
                   6025:         }
                   6026:        }
1.279     brouard  6027:        /* Next for computing shifted+ probability of death (h=1 means
1.218     brouard  6028:          computed over hstepm matrices product = hstepm*stepm months) 
1.279     brouard  6029:          as a weighted average of prlim(i) * p(i,j) p.3=w1*p13 + w2*p23 .
1.218     brouard  6030:        */
                   6031:        for(j=nlstate+1;j<=nlstate+ndeath;j++){
                   6032:         for(i=1,gpp[j]=0.; i<= nlstate; i++)
                   6033:           gpp[j] += prlim[i][i]*p3mat[i][j][1];
1.279     brouard  6034:        }
                   6035:        
                   6036:        /* Again with minus shift */
1.218     brouard  6037:                        
                   6038:        for(i=1; i<=npar; i++) /* Computes gradient x - delta */
                   6039:         xp[i] = x[i] - (i==theta ?delti[theta]:0);
1.288     brouard  6040: 
1.242     brouard  6041:        prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp, ij, nres);
1.218     brouard  6042:                        
                   6043:        if (popbased==1) {
                   6044:         if(mobilav ==0){
                   6045:           for(i=1; i<=nlstate;i++)
                   6046:             prlim[i][i]=probs[(int)age][i][ij];
                   6047:         }else{ /* mobilav */ 
                   6048:           for(i=1; i<=nlstate;i++)
                   6049:             prlim[i][i]=mobaverage[(int)age][i][ij];
                   6050:         }
                   6051:        }
                   6052:                        
1.235     brouard  6053:        hpxij(p3mat,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, ij,nres);  
1.218     brouard  6054:                        
                   6055:        for(j=1; j<= nlstate; j++){  /* Sum of wi * eij = e.j */
                   6056:         for(h=0; h<=nhstepm; h++){
                   6057:           for(i=1, gm[h][j]=0.;i<=nlstate;i++)
                   6058:             gm[h][j] += prlim[i][i]*p3mat[i][j][h];
                   6059:         }
                   6060:        }
                   6061:        /* This for computing probability of death (h=1 means
                   6062:          computed over hstepm matrices product = hstepm*stepm months) 
                   6063:          as a weighted average of prlim.
                   6064:        */
                   6065:        for(j=nlstate+1;j<=nlstate+ndeath;j++){
                   6066:         for(i=1,gmp[j]=0.; i<= nlstate; i++)
                   6067:           gmp[j] += prlim[i][i]*p3mat[i][j][1];
                   6068:        }    
1.279     brouard  6069:        /* end shifting computations */
                   6070: 
                   6071:        /**< Computing gradient matrix at horizon h 
                   6072:        */
1.218     brouard  6073:        for(j=1; j<= nlstate; j++) /* vareij */
                   6074:         for(h=0; h<=nhstepm; h++){
                   6075:           gradg[h][theta][j]= (gp[h][j]-gm[h][j])/2./delti[theta];
                   6076:         }
1.279     brouard  6077:        /**< Gradient of overall mortality p.3 (or p.j) 
                   6078:        */
                   6079:        for(j=nlstate+1; j<= nlstate+ndeath; j++){ /* var mu mortality from j */
1.218     brouard  6080:         gradgp[theta][j]= (gpp[j]-gmp[j])/2./delti[theta];
                   6081:        }
                   6082:                        
                   6083:      } /* End theta */
1.279     brouard  6084:      
                   6085:      /* We got the gradient matrix for each theta and state j */               
1.218     brouard  6086:      trgradg =ma3x(0,nhstepm,1,nlstate,1,npar); /* veij */
                   6087:                
                   6088:      for(h=0; h<=nhstepm; h++) /* veij */
                   6089:        for(j=1; j<=nlstate;j++)
                   6090:         for(theta=1; theta <=npar; theta++)
                   6091:           trgradg[h][j][theta]=gradg[h][theta][j];
                   6092:                
                   6093:      for(j=nlstate+1; j<=nlstate+ndeath;j++) /* mu */
                   6094:        for(theta=1; theta <=npar; theta++)
                   6095:         trgradgp[j][theta]=gradgp[theta][j];
1.279     brouard  6096:      /**< as well as its transposed matrix 
                   6097:       */               
1.218     brouard  6098:                
                   6099:      hf=hstepm*stepm/YEARM;  /* Duration of hstepm expressed in year unit. */
                   6100:      for(i=1;i<=nlstate;i++)
                   6101:        for(j=1;j<=nlstate;j++)
                   6102:         vareij[i][j][(int)age] =0.;
1.279     brouard  6103: 
                   6104:      /* Computing trgradg by matcov by gradg at age and summing over h
                   6105:       * and k (nhstepm) formula 15 of article
                   6106:       * Lievre-Brouard-Heathcote
                   6107:       */
                   6108:      
1.218     brouard  6109:      for(h=0;h<=nhstepm;h++){
                   6110:        for(k=0;k<=nhstepm;k++){
                   6111:         matprod2(dnewm,trgradg[h],1,nlstate,1,npar,1,npar,matcov);
                   6112:         matprod2(doldm,dnewm,1,nlstate,1,npar,1,nlstate,gradg[k]);
                   6113:         for(i=1;i<=nlstate;i++)
                   6114:           for(j=1;j<=nlstate;j++)
                   6115:             vareij[i][j][(int)age] += doldm[i][j]*hf*hf;
                   6116:        }
                   6117:      }
                   6118:                
1.279     brouard  6119:      /* pptj is p.3 or p.j = trgradgp by cov by gradgp, variance of
                   6120:       * p.j overall mortality formula 49 but computed directly because
                   6121:       * we compute the grad (wix pijx) instead of grad (pijx),even if
                   6122:       * wix is independent of theta.
                   6123:       */
1.218     brouard  6124:      matprod2(dnewmp,trgradgp,nlstate+1,nlstate+ndeath,1,npar,1,npar,matcov);
                   6125:      matprod2(doldmp,dnewmp,nlstate+1,nlstate+ndeath,1,npar,nlstate+1,nlstate+ndeath,gradgp);
                   6126:      for(j=nlstate+1;j<=nlstate+ndeath;j++)
                   6127:        for(i=nlstate+1;i<=nlstate+ndeath;i++)
                   6128:         varppt[j][i]=doldmp[j][i];
                   6129:      /* end ppptj */
                   6130:      /*  x centered again */
                   6131:                
1.242     brouard  6132:      prevalim(prlim,nlstate,x,age,oldm,savm,ftolpl,ncvyearp,ij, nres);
1.218     brouard  6133:                
                   6134:      if (popbased==1) {
                   6135:        if(mobilav ==0){
                   6136:         for(i=1; i<=nlstate;i++)
                   6137:           prlim[i][i]=probs[(int)age][i][ij];
                   6138:        }else{ /* mobilav */ 
                   6139:         for(i=1; i<=nlstate;i++)
                   6140:           prlim[i][i]=mobaverage[(int)age][i][ij];
                   6141:        }
                   6142:      }
                   6143:                
                   6144:      /* This for computing probability of death (h=1 means
                   6145:        computed over hstepm (estepm) matrices product = hstepm*stepm months) 
                   6146:        as a weighted average of prlim.
                   6147:      */
1.235     brouard  6148:      hpxij(p3mat,nhstepm,age,hstepm,x,nlstate,stepm,oldm,savm, ij, nres);  
1.218     brouard  6149:      for(j=nlstate+1;j<=nlstate+ndeath;j++){
                   6150:        for(i=1,gmp[j]=0.;i<= nlstate; i++) 
                   6151:         gmp[j] += prlim[i][i]*p3mat[i][j][1]; 
                   6152:      }    
                   6153:      /* end probability of death */
                   6154:                
                   6155:      fprintf(ficresprobmorprev,"%3d %d ",(int) age, ij);
                   6156:      for(j=nlstate+1; j<=(nlstate+ndeath);j++){
                   6157:        fprintf(ficresprobmorprev," %11.3e %11.3e",gmp[j], sqrt(varppt[j][j]));
                   6158:        for(i=1; i<=nlstate;i++){
                   6159:         fprintf(ficresprobmorprev," %11.3e %11.3e ",prlim[i][i],p3mat[i][j][1]);
                   6160:        }
                   6161:      } 
                   6162:      fprintf(ficresprobmorprev,"\n");
                   6163:                
                   6164:      fprintf(ficresvij,"%.0f ",age );
                   6165:      for(i=1; i<=nlstate;i++)
                   6166:        for(j=1; j<=nlstate;j++){
                   6167:         fprintf(ficresvij," %.4f", vareij[i][j][(int)age]);
                   6168:        }
                   6169:      fprintf(ficresvij,"\n");
                   6170:      free_matrix(gp,0,nhstepm,1,nlstate);
                   6171:      free_matrix(gm,0,nhstepm,1,nlstate);
                   6172:      free_ma3x(gradg,0,nhstepm,1,npar,1,nlstate);
                   6173:      free_ma3x(trgradg,0,nhstepm,1,nlstate,1,npar);
                   6174:      free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   6175:    } /* End age */
                   6176:    free_vector(gpp,nlstate+1,nlstate+ndeath);
                   6177:    free_vector(gmp,nlstate+1,nlstate+ndeath);
                   6178:    free_matrix(gradgp,1,npar,nlstate+1,nlstate+ndeath);
                   6179:    free_matrix(trgradgp,nlstate+1,nlstate+ndeath,1,npar); /* mu or p point j*/
                   6180:    /* fprintf(ficgp,"\nunset parametric;unset label; set ter png small size 320, 240"); */
                   6181:    fprintf(ficgp,"\nunset parametric;unset label; set ter svg size 640, 480");
                   6182:    /* for(j=nlstate+1; j<= nlstate+ndeath; j++){ *//* Only the first actually */
                   6183:    fprintf(ficgp,"\n set log y; unset log x;set xlabel \"Age\"; set ylabel \"Force of mortality (year-1)\";");
                   6184:    fprintf(ficgp,"\nset out \"%s%s.svg\";",subdirf3(optionfilefiname,"VARMUPTJGR-",digitp),digit);
                   6185:    /*   fprintf(ficgp,"\n plot \"%s\"  u 1:($3*%6.3f) not w l 1 ",fileresprobmorprev,YEARM/estepm); */
                   6186:    /*   fprintf(ficgp,"\n replot \"%s\"  u 1:(($3+1.96*$4)*%6.3f) t \"95\%% interval\" w l 2 ",fileresprobmorprev,YEARM/estepm); */
                   6187:    /*   fprintf(ficgp,"\n replot \"%s\"  u 1:(($3-1.96*$4)*%6.3f) not w l 2 ",fileresprobmorprev,YEARM/estepm); */
                   6188:    fprintf(ficgp,"\n plot \"%s\"  u 1:($3) not w l lt 1 ",subdirf(fileresprobmorprev));
                   6189:    fprintf(ficgp,"\n replot \"%s\"  u 1:(($3+1.96*$4)) t \"95%% interval\" w l lt 2 ",subdirf(fileresprobmorprev));
                   6190:    fprintf(ficgp,"\n replot \"%s\"  u 1:(($3-1.96*$4)) not w l lt 2 ",subdirf(fileresprobmorprev));
                   6191:    fprintf(fichtm,"\n<br> File (multiple files are possible if covariates are present): <A href=\"%s\">%s</a>\n",subdirf(fileresprobmorprev),subdirf(fileresprobmorprev));
                   6192:    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);
                   6193:    /*  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  6194:     */
1.218     brouard  6195:    /*   fprintf(ficgp,"\nset out \"varmuptjgr%s%s%s.svg\";replot;",digitp,optionfilefiname,digit); */
                   6196:    fprintf(ficgp,"\nset out;\nset out \"%s%s.svg\";replot;set out;\n",subdirf3(optionfilefiname,"VARMUPTJGR-",digitp),digit);
1.126     brouard  6197: 
1.218     brouard  6198:    free_vector(xp,1,npar);
                   6199:    free_matrix(doldm,1,nlstate,1,nlstate);
                   6200:    free_matrix(dnewm,1,nlstate,1,npar);
                   6201:    free_matrix(doldmp,nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
                   6202:    free_matrix(dnewmp,nlstate+1,nlstate+ndeath,1,npar);
                   6203:    free_matrix(varppt,nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
                   6204:    /* if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX); */
                   6205:    fclose(ficresprobmorprev);
                   6206:    fflush(ficgp);
                   6207:    fflush(fichtm); 
                   6208:  }  /* end varevsij */
1.126     brouard  6209: 
                   6210: /************ Variance of prevlim ******************/
1.269     brouard  6211:  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  6212: {
1.205     brouard  6213:   /* Variance of prevalence limit  for each state ij using current parameters x[] and estimates of neighbourhood give by delti*/
1.126     brouard  6214:   /*  double **prevalim(double **prlim, int nlstate, double *xp, double age, double **oldm, double **savm,double ftolpl);*/
1.164     brouard  6215: 
1.268     brouard  6216:   double **dnewmpar,**doldm;
1.126     brouard  6217:   int i, j, nhstepm, hstepm;
                   6218:   double *xp;
                   6219:   double *gp, *gm;
                   6220:   double **gradg, **trgradg;
1.208     brouard  6221:   double **mgm, **mgp;
1.126     brouard  6222:   double age,agelim;
                   6223:   int theta;
                   6224:   
                   6225:   pstamp(ficresvpl);
1.288     brouard  6226:   fprintf(ficresvpl,"# Standard deviation of period (forward stable) prevalences \n");
1.241     brouard  6227:   fprintf(ficresvpl,"# Age ");
                   6228:   if(nresult >=1)
                   6229:     fprintf(ficresvpl," Result# ");
1.126     brouard  6230:   for(i=1; i<=nlstate;i++)
                   6231:       fprintf(ficresvpl," %1d-%1d",i,i);
                   6232:   fprintf(ficresvpl,"\n");
                   6233: 
                   6234:   xp=vector(1,npar);
1.268     brouard  6235:   dnewmpar=matrix(1,nlstate,1,npar);
1.126     brouard  6236:   doldm=matrix(1,nlstate,1,nlstate);
                   6237:   
                   6238:   hstepm=1*YEARM; /* Every year of age */
                   6239:   hstepm=hstepm/stepm; /* Typically in stepm units, if j= 2 years, = 2/6 months = 4 */ 
                   6240:   agelim = AGESUP;
                   6241:   for (age=bage; age<=fage; age ++){ /* If stepm=6 months */
                   6242:     nhstepm=(int) rint((agelim-age)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */ 
                   6243:     if (stepm >= YEARM) hstepm=1;
                   6244:     nhstepm = nhstepm/hstepm; /* Typically 40/4=10 */
                   6245:     gradg=matrix(1,npar,1,nlstate);
1.208     brouard  6246:     mgp=matrix(1,npar,1,nlstate);
                   6247:     mgm=matrix(1,npar,1,nlstate);
1.126     brouard  6248:     gp=vector(1,nlstate);
                   6249:     gm=vector(1,nlstate);
                   6250: 
                   6251:     for(theta=1; theta <=npar; theta++){
                   6252:       for(i=1; i<=npar; i++){ /* Computes gradient */
                   6253:        xp[i] = x[i] + (i==theta ?delti[theta]:0);
                   6254:       }
1.288     brouard  6255:       /* if((int)age==79 ||(int)age== 80 ||(int)age== 81 ) */
                   6256:       /*       prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp,ij,nres); */
                   6257:       /* else */
                   6258:       prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp,ij,nres);
1.208     brouard  6259:       for(i=1;i<=nlstate;i++){
1.126     brouard  6260:        gp[i] = prlim[i][i];
1.208     brouard  6261:        mgp[theta][i] = prlim[i][i];
                   6262:       }
1.126     brouard  6263:       for(i=1; i<=npar; i++) /* Computes gradient */
                   6264:        xp[i] = x[i] - (i==theta ?delti[theta]:0);
1.288     brouard  6265:       /* if((int)age==79 ||(int)age== 80 ||(int)age== 81 ) */
                   6266:       /*       prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp,ij,nres); */
                   6267:       /* else */
                   6268:       prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp,ij,nres);
1.208     brouard  6269:       for(i=1;i<=nlstate;i++){
1.126     brouard  6270:        gm[i] = prlim[i][i];
1.208     brouard  6271:        mgm[theta][i] = prlim[i][i];
                   6272:       }
1.126     brouard  6273:       for(i=1;i<=nlstate;i++)
                   6274:        gradg[theta][i]= (gp[i]-gm[i])/2./delti[theta];
1.209     brouard  6275:       /* gradg[theta][2]= -gradg[theta][1]; */ /* For testing if nlstate=2 */
1.126     brouard  6276:     } /* End theta */
                   6277: 
                   6278:     trgradg =matrix(1,nlstate,1,npar);
                   6279: 
                   6280:     for(j=1; j<=nlstate;j++)
                   6281:       for(theta=1; theta <=npar; theta++)
                   6282:        trgradg[j][theta]=gradg[theta][j];
1.209     brouard  6283:     /* if((int)age==79 ||(int)age== 80 ||(int)age== 81 ){ */
                   6284:     /*   printf("\nmgm mgp %d ",(int)age); */
                   6285:     /*   for(j=1; j<=nlstate;j++){ */
                   6286:     /*         printf(" %d ",j); */
                   6287:     /*         for(theta=1; theta <=npar; theta++) */
                   6288:     /*           printf(" %d %lf %lf",theta,mgm[theta][j],mgp[theta][j]); */
                   6289:     /*         printf("\n "); */
                   6290:     /*   } */
                   6291:     /* } */
                   6292:     /* if((int)age==79 ||(int)age== 80 ||(int)age== 81 ){ */
                   6293:     /*   printf("\n gradg %d ",(int)age); */
                   6294:     /*   for(j=1; j<=nlstate;j++){ */
                   6295:     /*         printf("%d ",j); */
                   6296:     /*         for(theta=1; theta <=npar; theta++) */
                   6297:     /*           printf("%d %lf ",theta,gradg[theta][j]); */
                   6298:     /*         printf("\n "); */
                   6299:     /*   } */
                   6300:     /* } */
1.126     brouard  6301: 
                   6302:     for(i=1;i<=nlstate;i++)
                   6303:       varpl[i][(int)age] =0.;
1.209     brouard  6304:     if((int)age==79 ||(int)age== 80  ||(int)age== 81){
1.268     brouard  6305:     matprod2(dnewmpar,trgradg,1,nlstate,1,npar,1,npar,matcov);
                   6306:     matprod2(doldm,dnewmpar,1,nlstate,1,npar,1,nlstate,gradg);
1.205     brouard  6307:     }else{
1.268     brouard  6308:     matprod2(dnewmpar,trgradg,1,nlstate,1,npar,1,npar,matcov);
                   6309:     matprod2(doldm,dnewmpar,1,nlstate,1,npar,1,nlstate,gradg);
1.205     brouard  6310:     }
1.126     brouard  6311:     for(i=1;i<=nlstate;i++)
                   6312:       varpl[i][(int)age] = doldm[i][i]; /* Covariances are useless */
                   6313: 
                   6314:     fprintf(ficresvpl,"%.0f ",age );
1.241     brouard  6315:     if(nresult >=1)
                   6316:       fprintf(ficresvpl,"%d ",nres );
1.288     brouard  6317:     for(i=1; i<=nlstate;i++){
1.126     brouard  6318:       fprintf(ficresvpl," %.5f (%.5f)",prlim[i][i],sqrt(varpl[i][(int)age]));
1.288     brouard  6319:       /* for(j=1;j<=nlstate;j++) */
                   6320:       /*       fprintf(ficresvpl," %d %.5f ",j,prlim[j][i]); */
                   6321:     }
1.126     brouard  6322:     fprintf(ficresvpl,"\n");
                   6323:     free_vector(gp,1,nlstate);
                   6324:     free_vector(gm,1,nlstate);
1.208     brouard  6325:     free_matrix(mgm,1,npar,1,nlstate);
                   6326:     free_matrix(mgp,1,npar,1,nlstate);
1.126     brouard  6327:     free_matrix(gradg,1,npar,1,nlstate);
                   6328:     free_matrix(trgradg,1,nlstate,1,npar);
                   6329:   } /* End age */
                   6330: 
                   6331:   free_vector(xp,1,npar);
                   6332:   free_matrix(doldm,1,nlstate,1,npar);
1.268     brouard  6333:   free_matrix(dnewmpar,1,nlstate,1,nlstate);
                   6334: 
                   6335: }
                   6336: 
                   6337: 
                   6338: /************ Variance of backprevalence limit ******************/
1.269     brouard  6339:  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  6340: {
                   6341:   /* Variance of backward prevalence limit  for each state ij using current parameters x[] and estimates of neighbourhood give by delti*/
                   6342:   /*  double **prevalim(double **prlim, int nlstate, double *xp, double age, double **oldm, double **savm,double ftolpl);*/
                   6343: 
                   6344:   double **dnewmpar,**doldm;
                   6345:   int i, j, nhstepm, hstepm;
                   6346:   double *xp;
                   6347:   double *gp, *gm;
                   6348:   double **gradg, **trgradg;
                   6349:   double **mgm, **mgp;
                   6350:   double age,agelim;
                   6351:   int theta;
                   6352:   
                   6353:   pstamp(ficresvbl);
                   6354:   fprintf(ficresvbl,"# Standard deviation of back (stable) prevalences \n");
                   6355:   fprintf(ficresvbl,"# Age ");
                   6356:   if(nresult >=1)
                   6357:     fprintf(ficresvbl," Result# ");
                   6358:   for(i=1; i<=nlstate;i++)
                   6359:       fprintf(ficresvbl," %1d-%1d",i,i);
                   6360:   fprintf(ficresvbl,"\n");
                   6361: 
                   6362:   xp=vector(1,npar);
                   6363:   dnewmpar=matrix(1,nlstate,1,npar);
                   6364:   doldm=matrix(1,nlstate,1,nlstate);
                   6365:   
                   6366:   hstepm=1*YEARM; /* Every year of age */
                   6367:   hstepm=hstepm/stepm; /* Typically in stepm units, if j= 2 years, = 2/6 months = 4 */ 
                   6368:   agelim = AGEINF;
                   6369:   for (age=fage; age>=bage; age --){ /* If stepm=6 months */
                   6370:     nhstepm=(int) rint((age-agelim)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */ 
                   6371:     if (stepm >= YEARM) hstepm=1;
                   6372:     nhstepm = nhstepm/hstepm; /* Typically 40/4=10 */
                   6373:     gradg=matrix(1,npar,1,nlstate);
                   6374:     mgp=matrix(1,npar,1,nlstate);
                   6375:     mgm=matrix(1,npar,1,nlstate);
                   6376:     gp=vector(1,nlstate);
                   6377:     gm=vector(1,nlstate);
                   6378: 
                   6379:     for(theta=1; theta <=npar; theta++){
                   6380:       for(i=1; i<=npar; i++){ /* Computes gradient */
                   6381:        xp[i] = x[i] + (i==theta ?delti[theta]:0);
                   6382:       }
                   6383:       if(mobilavproj > 0 )
                   6384:        bprevalim(bprlim, mobaverage,nlstate,xp,age,ftolpl,ncvyearp,ij,nres);
                   6385:       else
                   6386:        bprevalim(bprlim, mobaverage,nlstate,xp,age,ftolpl,ncvyearp,ij,nres);
                   6387:       for(i=1;i<=nlstate;i++){
                   6388:        gp[i] = bprlim[i][i];
                   6389:        mgp[theta][i] = bprlim[i][i];
                   6390:       }
                   6391:      for(i=1; i<=npar; i++) /* Computes gradient */
                   6392:        xp[i] = x[i] - (i==theta ?delti[theta]:0);
                   6393:        if(mobilavproj > 0 )
                   6394:        bprevalim(bprlim, mobaverage,nlstate,xp,age,ftolpl,ncvyearp,ij,nres);
                   6395:        else
                   6396:        bprevalim(bprlim, mobaverage,nlstate,xp,age,ftolpl,ncvyearp,ij,nres);
                   6397:       for(i=1;i<=nlstate;i++){
                   6398:        gm[i] = bprlim[i][i];
                   6399:        mgm[theta][i] = bprlim[i][i];
                   6400:       }
                   6401:       for(i=1;i<=nlstate;i++)
                   6402:        gradg[theta][i]= (gp[i]-gm[i])/2./delti[theta];
                   6403:       /* gradg[theta][2]= -gradg[theta][1]; */ /* For testing if nlstate=2 */
                   6404:     } /* End theta */
                   6405: 
                   6406:     trgradg =matrix(1,nlstate,1,npar);
                   6407: 
                   6408:     for(j=1; j<=nlstate;j++)
                   6409:       for(theta=1; theta <=npar; theta++)
                   6410:        trgradg[j][theta]=gradg[theta][j];
                   6411:     /* if((int)age==79 ||(int)age== 80 ||(int)age== 81 ){ */
                   6412:     /*   printf("\nmgm mgp %d ",(int)age); */
                   6413:     /*   for(j=1; j<=nlstate;j++){ */
                   6414:     /*         printf(" %d ",j); */
                   6415:     /*         for(theta=1; theta <=npar; theta++) */
                   6416:     /*           printf(" %d %lf %lf",theta,mgm[theta][j],mgp[theta][j]); */
                   6417:     /*         printf("\n "); */
                   6418:     /*   } */
                   6419:     /* } */
                   6420:     /* if((int)age==79 ||(int)age== 80 ||(int)age== 81 ){ */
                   6421:     /*   printf("\n gradg %d ",(int)age); */
                   6422:     /*   for(j=1; j<=nlstate;j++){ */
                   6423:     /*         printf("%d ",j); */
                   6424:     /*         for(theta=1; theta <=npar; theta++) */
                   6425:     /*           printf("%d %lf ",theta,gradg[theta][j]); */
                   6426:     /*         printf("\n "); */
                   6427:     /*   } */
                   6428:     /* } */
                   6429: 
                   6430:     for(i=1;i<=nlstate;i++)
                   6431:       varbpl[i][(int)age] =0.;
                   6432:     if((int)age==79 ||(int)age== 80  ||(int)age== 81){
                   6433:     matprod2(dnewmpar,trgradg,1,nlstate,1,npar,1,npar,matcov);
                   6434:     matprod2(doldm,dnewmpar,1,nlstate,1,npar,1,nlstate,gradg);
                   6435:     }else{
                   6436:     matprod2(dnewmpar,trgradg,1,nlstate,1,npar,1,npar,matcov);
                   6437:     matprod2(doldm,dnewmpar,1,nlstate,1,npar,1,nlstate,gradg);
                   6438:     }
                   6439:     for(i=1;i<=nlstate;i++)
                   6440:       varbpl[i][(int)age] = doldm[i][i]; /* Covariances are useless */
                   6441: 
                   6442:     fprintf(ficresvbl,"%.0f ",age );
                   6443:     if(nresult >=1)
                   6444:       fprintf(ficresvbl,"%d ",nres );
                   6445:     for(i=1; i<=nlstate;i++)
                   6446:       fprintf(ficresvbl," %.5f (%.5f)",bprlim[i][i],sqrt(varbpl[i][(int)age]));
                   6447:     fprintf(ficresvbl,"\n");
                   6448:     free_vector(gp,1,nlstate);
                   6449:     free_vector(gm,1,nlstate);
                   6450:     free_matrix(mgm,1,npar,1,nlstate);
                   6451:     free_matrix(mgp,1,npar,1,nlstate);
                   6452:     free_matrix(gradg,1,npar,1,nlstate);
                   6453:     free_matrix(trgradg,1,nlstate,1,npar);
                   6454:   } /* End age */
                   6455: 
                   6456:   free_vector(xp,1,npar);
                   6457:   free_matrix(doldm,1,nlstate,1,npar);
                   6458:   free_matrix(dnewmpar,1,nlstate,1,nlstate);
1.126     brouard  6459: 
                   6460: }
                   6461: 
                   6462: /************ Variance of one-step probabilities  ******************/
                   6463: 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  6464:  {
                   6465:    int i, j=0,  k1, l1, tj;
                   6466:    int k2, l2, j1,  z1;
                   6467:    int k=0, l;
                   6468:    int first=1, first1, first2;
                   6469:    double cv12, mu1, mu2, lc1, lc2, v12, v21, v11, v22,v1,v2, c12, tnalp;
                   6470:    double **dnewm,**doldm;
                   6471:    double *xp;
                   6472:    double *gp, *gm;
                   6473:    double **gradg, **trgradg;
                   6474:    double **mu;
                   6475:    double age, cov[NCOVMAX+1];
                   6476:    double std=2.0; /* Number of standard deviation wide of confidence ellipsoids */
                   6477:    int theta;
                   6478:    char fileresprob[FILENAMELENGTH];
                   6479:    char fileresprobcov[FILENAMELENGTH];
                   6480:    char fileresprobcor[FILENAMELENGTH];
                   6481:    double ***varpij;
                   6482: 
                   6483:    strcpy(fileresprob,"PROB_"); 
                   6484:    strcat(fileresprob,fileres);
                   6485:    if((ficresprob=fopen(fileresprob,"w"))==NULL) {
                   6486:      printf("Problem with resultfile: %s\n", fileresprob);
                   6487:      fprintf(ficlog,"Problem with resultfile: %s\n", fileresprob);
                   6488:    }
                   6489:    strcpy(fileresprobcov,"PROBCOV_"); 
                   6490:    strcat(fileresprobcov,fileresu);
                   6491:    if((ficresprobcov=fopen(fileresprobcov,"w"))==NULL) {
                   6492:      printf("Problem with resultfile: %s\n", fileresprobcov);
                   6493:      fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobcov);
                   6494:    }
                   6495:    strcpy(fileresprobcor,"PROBCOR_"); 
                   6496:    strcat(fileresprobcor,fileresu);
                   6497:    if((ficresprobcor=fopen(fileresprobcor,"w"))==NULL) {
                   6498:      printf("Problem with resultfile: %s\n", fileresprobcor);
                   6499:      fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobcor);
                   6500:    }
                   6501:    printf("Computing standard deviation of one-step probabilities: result on file '%s' \n",fileresprob);
                   6502:    fprintf(ficlog,"Computing standard deviation of one-step probabilities: result on file '%s' \n",fileresprob);
                   6503:    printf("Computing matrix of variance covariance of one-step probabilities: result on file '%s' \n",fileresprobcov);
                   6504:    fprintf(ficlog,"Computing matrix of variance covariance of one-step probabilities: result on file '%s' \n",fileresprobcov);
                   6505:    printf("and correlation matrix of one-step probabilities: result on file '%s' \n",fileresprobcor);
                   6506:    fprintf(ficlog,"and correlation matrix of one-step probabilities: result on file '%s' \n",fileresprobcor);
                   6507:    pstamp(ficresprob);
                   6508:    fprintf(ficresprob,"#One-step probabilities and stand. devi in ()\n");
                   6509:    fprintf(ficresprob,"# Age");
                   6510:    pstamp(ficresprobcov);
                   6511:    fprintf(ficresprobcov,"#One-step probabilities and covariance matrix\n");
                   6512:    fprintf(ficresprobcov,"# Age");
                   6513:    pstamp(ficresprobcor);
                   6514:    fprintf(ficresprobcor,"#One-step probabilities and correlation matrix\n");
                   6515:    fprintf(ficresprobcor,"# Age");
1.126     brouard  6516: 
                   6517: 
1.222     brouard  6518:    for(i=1; i<=nlstate;i++)
                   6519:      for(j=1; j<=(nlstate+ndeath);j++){
                   6520:        fprintf(ficresprob," p%1d-%1d (SE)",i,j);
                   6521:        fprintf(ficresprobcov," p%1d-%1d ",i,j);
                   6522:        fprintf(ficresprobcor," p%1d-%1d ",i,j);
                   6523:      }  
                   6524:    /* fprintf(ficresprob,"\n");
                   6525:       fprintf(ficresprobcov,"\n");
                   6526:       fprintf(ficresprobcor,"\n");
                   6527:    */
                   6528:    xp=vector(1,npar);
                   6529:    dnewm=matrix(1,(nlstate)*(nlstate+ndeath),1,npar);
                   6530:    doldm=matrix(1,(nlstate)*(nlstate+ndeath),1,(nlstate)*(nlstate+ndeath));
                   6531:    mu=matrix(1,(nlstate)*(nlstate+ndeath), (int) bage, (int)fage);
                   6532:    varpij=ma3x(1,nlstate*(nlstate+ndeath),1,nlstate*(nlstate+ndeath),(int) bage, (int) fage);
                   6533:    first=1;
                   6534:    fprintf(ficgp,"\n# Routine varprob");
                   6535:    fprintf(fichtm,"\n<li><h4> Computing and drawing one step probabilities with their confidence intervals</h4></li>\n");
                   6536:    fprintf(fichtm,"\n");
                   6537: 
1.288     brouard  6538:    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  6539:    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);
                   6540:    fprintf(fichtmcov,"\nEllipsoids of confidence centered on point (p<inf>ij</inf>, p<inf>kl</inf>) are estimated \
1.126     brouard  6541: and drawn. It helps understanding how is the covariance between two incidences.\
                   6542:  They are expressed in year<sup>-1</sup> in order to be less dependent of stepm.<br>\n");
1.222     brouard  6543:    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  6544: It can be understood this way: if pij and pkl where uncorrelated the (2x2) matrix of covariance \
                   6545: would have been (1/(var pij), 0 , 0, 1/(var pkl)), and the confidence interval would be 2 \
                   6546: standard deviations wide on each axis. <br>\
                   6547:  Now, if both incidences are correlated (usual case) we diagonalised the inverse of the covariance matrix\
                   6548:  and made the appropriate rotation to look at the uncorrelated principal directions.<br>\
                   6549: To be simple, these graphs help to understand the significativity of each parameter in relation to a second other one.<br> \n");
                   6550: 
1.222     brouard  6551:    cov[1]=1;
                   6552:    /* tj=cptcoveff; */
1.225     brouard  6553:    tj = (int) pow(2,cptcoveff);
1.222     brouard  6554:    if (cptcovn<1) {tj=1;ncodemax[1]=1;}
                   6555:    j1=0;
1.224     brouard  6556:    for(j1=1; j1<=tj;j1++){  /* For each valid combination of covariates or only once*/
1.222     brouard  6557:      if  (cptcovn>0) {
                   6558:        fprintf(ficresprob, "\n#********** Variable "); 
1.225     brouard  6559:        for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresprob, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
1.222     brouard  6560:        fprintf(ficresprob, "**********\n#\n");
                   6561:        fprintf(ficresprobcov, "\n#********** Variable "); 
1.225     brouard  6562:        for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresprobcov, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
1.222     brouard  6563:        fprintf(ficresprobcov, "**********\n#\n");
1.220     brouard  6564:                        
1.222     brouard  6565:        fprintf(ficgp, "\n#********** Variable "); 
1.225     brouard  6566:        for (z1=1; z1<=cptcoveff; z1++) fprintf(ficgp, " V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
1.222     brouard  6567:        fprintf(ficgp, "**********\n#\n");
1.220     brouard  6568:                        
                   6569:                        
1.222     brouard  6570:        fprintf(fichtmcov, "\n<hr  size=\"2\" color=\"#EC5E5E\">********** Variable "); 
1.225     brouard  6571:        for (z1=1; z1<=cptcoveff; z1++) fprintf(fichtm, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
1.222     brouard  6572:        fprintf(fichtmcov, "**********\n<hr size=\"2\" color=\"#EC5E5E\">");
1.220     brouard  6573:                        
1.222     brouard  6574:        fprintf(ficresprobcor, "\n#********** Variable ");    
1.225     brouard  6575:        for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresprobcor, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
1.222     brouard  6576:        fprintf(ficresprobcor, "**********\n#");    
                   6577:        if(invalidvarcomb[j1]){
                   6578:         fprintf(ficgp,"\n#Combination (%d) ignored because no cases \n",j1); 
                   6579:         fprintf(fichtmcov,"\n<h3>Combination (%d) ignored because no cases </h3>\n",j1); 
                   6580:         continue;
                   6581:        }
                   6582:      }
                   6583:      gradg=matrix(1,npar,1,(nlstate)*(nlstate+ndeath));
                   6584:      trgradg=matrix(1,(nlstate)*(nlstate+ndeath),1,npar);
                   6585:      gp=vector(1,(nlstate)*(nlstate+ndeath));
                   6586:      gm=vector(1,(nlstate)*(nlstate+ndeath));
                   6587:      for (age=bage; age<=fage; age ++){ 
                   6588:        cov[2]=age;
                   6589:        if(nagesqr==1)
                   6590:         cov[3]= age*age;
                   6591:        for (k=1; k<=cptcovn;k++) {
                   6592:         cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(j1,k)];
                   6593:         /*cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(j1,Tvar[k])];*//* j1 1 2 3 4
                   6594:                                                                    * 1  1 1 1 1
                   6595:                                                                    * 2  2 1 1 1
                   6596:                                                                    * 3  1 2 1 1
                   6597:                                                                    */
                   6598:         /* nbcode[1][1]=0 nbcode[1][2]=1;*/
                   6599:        }
                   6600:        /* for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2]; */
                   6601:        for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,k)]*cov[2];
                   6602:        for (k=1; k<=cptcovprod;k++)
                   6603:         cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)]*nbcode[Tvard[k][2]][codtabm(ij,k)];
1.220     brouard  6604:                        
                   6605:                        
1.222     brouard  6606:        for(theta=1; theta <=npar; theta++){
                   6607:         for(i=1; i<=npar; i++)
                   6608:           xp[i] = x[i] + (i==theta ?delti[theta]:(double)0);
1.220     brouard  6609:                                
1.222     brouard  6610:         pmij(pmmij,cov,ncovmodel,xp,nlstate);
1.220     brouard  6611:                                
1.222     brouard  6612:         k=0;
                   6613:         for(i=1; i<= (nlstate); i++){
                   6614:           for(j=1; j<=(nlstate+ndeath);j++){
                   6615:             k=k+1;
                   6616:             gp[k]=pmmij[i][j];
                   6617:           }
                   6618:         }
1.220     brouard  6619:                                
1.222     brouard  6620:         for(i=1; i<=npar; i++)
                   6621:           xp[i] = x[i] - (i==theta ?delti[theta]:(double)0);
1.220     brouard  6622:                                
1.222     brouard  6623:         pmij(pmmij,cov,ncovmodel,xp,nlstate);
                   6624:         k=0;
                   6625:         for(i=1; i<=(nlstate); i++){
                   6626:           for(j=1; j<=(nlstate+ndeath);j++){
                   6627:             k=k+1;
                   6628:             gm[k]=pmmij[i][j];
                   6629:           }
                   6630:         }
1.220     brouard  6631:                                
1.222     brouard  6632:         for(i=1; i<= (nlstate)*(nlstate+ndeath); i++) 
                   6633:           gradg[theta][i]=(gp[i]-gm[i])/(double)2./delti[theta];  
                   6634:        }
1.126     brouard  6635: 
1.222     brouard  6636:        for(j=1; j<=(nlstate)*(nlstate+ndeath);j++)
                   6637:         for(theta=1; theta <=npar; theta++)
                   6638:           trgradg[j][theta]=gradg[theta][j];
1.220     brouard  6639:                        
1.222     brouard  6640:        matprod2(dnewm,trgradg,1,(nlstate)*(nlstate+ndeath),1,npar,1,npar,matcov); 
                   6641:        matprod2(doldm,dnewm,1,(nlstate)*(nlstate+ndeath),1,npar,1,(nlstate)*(nlstate+ndeath),gradg);
1.220     brouard  6642:                        
1.222     brouard  6643:        pmij(pmmij,cov,ncovmodel,x,nlstate);
1.220     brouard  6644:                        
1.222     brouard  6645:        k=0;
                   6646:        for(i=1; i<=(nlstate); i++){
                   6647:         for(j=1; j<=(nlstate+ndeath);j++){
                   6648:           k=k+1;
                   6649:           mu[k][(int) age]=pmmij[i][j];
                   6650:         }
                   6651:        }
                   6652:        for(i=1;i<=(nlstate)*(nlstate+ndeath);i++)
                   6653:         for(j=1;j<=(nlstate)*(nlstate+ndeath);j++)
                   6654:           varpij[i][j][(int)age] = doldm[i][j];
1.220     brouard  6655:                        
1.222     brouard  6656:        /*printf("\n%d ",(int)age);
                   6657:         for (i=1; i<=(nlstate)*(nlstate+ndeath);i++){
                   6658:         printf("%e [%e ;%e] ",gm[i],gm[i]-2*sqrt(doldm[i][i]),gm[i]+2*sqrt(doldm[i][i]));
                   6659:         fprintf(ficlog,"%e [%e ;%e] ",gm[i],gm[i]-2*sqrt(doldm[i][i]),gm[i]+2*sqrt(doldm[i][i]));
                   6660:         }*/
1.220     brouard  6661:                        
1.222     brouard  6662:        fprintf(ficresprob,"\n%d ",(int)age);
                   6663:        fprintf(ficresprobcov,"\n%d ",(int)age);
                   6664:        fprintf(ficresprobcor,"\n%d ",(int)age);
1.220     brouard  6665:                        
1.222     brouard  6666:        for (i=1; i<=(nlstate)*(nlstate+ndeath);i++)
                   6667:         fprintf(ficresprob,"%11.3e (%11.3e) ",mu[i][(int) age],sqrt(varpij[i][i][(int)age]));
                   6668:        for (i=1; i<=(nlstate)*(nlstate+ndeath);i++){
                   6669:         fprintf(ficresprobcov,"%11.3e ",mu[i][(int) age]);
                   6670:         fprintf(ficresprobcor,"%11.3e ",mu[i][(int) age]);
                   6671:        }
                   6672:        i=0;
                   6673:        for (k=1; k<=(nlstate);k++){
                   6674:         for (l=1; l<=(nlstate+ndeath);l++){ 
                   6675:           i++;
                   6676:           fprintf(ficresprobcov,"\n%d %d-%d",(int)age,k,l);
                   6677:           fprintf(ficresprobcor,"\n%d %d-%d",(int)age,k,l);
                   6678:           for (j=1; j<=i;j++){
                   6679:             /* printf(" k=%d l=%d i=%d j=%d\n",k,l,i,j);fflush(stdout); */
                   6680:             fprintf(ficresprobcov," %11.3e",varpij[i][j][(int)age]);
                   6681:             fprintf(ficresprobcor," %11.3e",varpij[i][j][(int) age]/sqrt(varpij[i][i][(int) age])/sqrt(varpij[j][j][(int)age]));
                   6682:           }
                   6683:         }
                   6684:        }/* end of loop for state */
                   6685:      } /* end of loop for age */
                   6686:      free_vector(gp,1,(nlstate+ndeath)*(nlstate+ndeath));
                   6687:      free_vector(gm,1,(nlstate+ndeath)*(nlstate+ndeath));
                   6688:      free_matrix(trgradg,1,(nlstate+ndeath)*(nlstate+ndeath),1,npar);
                   6689:      free_matrix(gradg,1,(nlstate+ndeath)*(nlstate+ndeath),1,npar);
                   6690:     
                   6691:      /* Confidence intervalle of pij  */
                   6692:      /*
                   6693:        fprintf(ficgp,"\nunset parametric;unset label");
                   6694:        fprintf(ficgp,"\nset log y;unset log x; set xlabel \"Age\";set ylabel \"probability (year-1)\"");
                   6695:        fprintf(ficgp,"\nset ter png small\nset size 0.65,0.65");
                   6696:        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);
                   6697:        fprintf(fichtm,"\n<br><img src=\"pijgr%s.png\"> ",optionfilefiname);
                   6698:        fprintf(ficgp,"\nset out \"pijgr%s.png\"",optionfilefiname);
                   6699:        fprintf(ficgp,"\nplot \"%s\" every :::%d::%d u 1:2 \"\%%lf",k1,k2,xfilevarprob);
                   6700:      */
                   6701:                
                   6702:      /* Drawing ellipsoids of confidence of two variables p(k1-l1,k2-l2)*/
                   6703:      first1=1;first2=2;
                   6704:      for (k2=1; k2<=(nlstate);k2++){
                   6705:        for (l2=1; l2<=(nlstate+ndeath);l2++){ 
                   6706:         if(l2==k2) continue;
                   6707:         j=(k2-1)*(nlstate+ndeath)+l2;
                   6708:         for (k1=1; k1<=(nlstate);k1++){
                   6709:           for (l1=1; l1<=(nlstate+ndeath);l1++){ 
                   6710:             if(l1==k1) continue;
                   6711:             i=(k1-1)*(nlstate+ndeath)+l1;
                   6712:             if(i<=j) continue;
                   6713:             for (age=bage; age<=fage; age ++){ 
                   6714:               if ((int)age %5==0){
                   6715:                 v1=varpij[i][i][(int)age]/stepm*YEARM/stepm*YEARM;
                   6716:                 v2=varpij[j][j][(int)age]/stepm*YEARM/stepm*YEARM;
                   6717:                 cv12=varpij[i][j][(int)age]/stepm*YEARM/stepm*YEARM;
                   6718:                 mu1=mu[i][(int) age]/stepm*YEARM ;
                   6719:                 mu2=mu[j][(int) age]/stepm*YEARM;
                   6720:                 c12=cv12/sqrt(v1*v2);
                   6721:                 /* Computing eigen value of matrix of covariance */
                   6722:                 lc1=((v1+v2)+sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
                   6723:                 lc2=((v1+v2)-sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
                   6724:                 if ((lc2 <0) || (lc1 <0) ){
                   6725:                   if(first2==1){
                   6726:                     first1=0;
                   6727:                     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);
                   6728:                   }
                   6729:                   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);
                   6730:                   /* lc1=fabs(lc1); */ /* If we want to have them positive */
                   6731:                   /* lc2=fabs(lc2); */
                   6732:                 }
1.220     brouard  6733:                                                                
1.222     brouard  6734:                 /* Eigen vectors */
1.280     brouard  6735:                 if(1+(v1-lc1)*(v1-lc1)/cv12/cv12 <1.e-5){
                   6736:                   printf(" Error sqrt of a negative number: %lf\n",1+(v1-lc1)*(v1-lc1)/cv12/cv12);
                   6737:                   fprintf(ficlog," Error sqrt of a negative number: %lf\n",1+(v1-lc1)*(v1-lc1)/cv12/cv12);
                   6738:                   v11=(1./sqrt(fabs(1+(v1-lc1)*(v1-lc1)/cv12/cv12)));
                   6739:                 }else
                   6740:                   v11=(1./sqrt(1+(v1-lc1)*(v1-lc1)/cv12/cv12));
1.222     brouard  6741:                 /*v21=sqrt(1.-v11*v11); *//* error */
                   6742:                 v21=(lc1-v1)/cv12*v11;
                   6743:                 v12=-v21;
                   6744:                 v22=v11;
                   6745:                 tnalp=v21/v11;
                   6746:                 if(first1==1){
                   6747:                   first1=0;
                   6748:                   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);
                   6749:                 }
                   6750:                 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);
                   6751:                 /*printf(fignu*/
                   6752:                 /* mu1+ v11*lc1*cost + v12*lc2*sin(t) */
                   6753:                 /* mu2+ v21*lc1*cost + v22*lc2*sin(t) */
                   6754:                 if(first==1){
                   6755:                   first=0;
                   6756:                   fprintf(ficgp,"\n# Ellipsoids of confidence\n#\n");
                   6757:                   fprintf(ficgp,"\nset parametric;unset label");
                   6758:                   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);
                   6759:                   fprintf(ficgp,"\nset ter svg size 640, 480");
1.266     brouard  6760:                   fprintf(fichtmcov,"\n<p><br>Ellipsoids of confidence cov(p%1d%1d,p%1d%1d) expressed in year<sup>-1</sup>\
1.220     brouard  6761:  :<a href=\"%s_%d%1d%1d-%1d%1d.svg\">                                                                                                                                          \
1.201     brouard  6762: %s_%d%1d%1d-%1d%1d.svg</A>, ",k1,l1,k2,l2,\
1.222     brouard  6763:                           subdirf2(optionfilefiname,"VARPIJGR_"), j1,k1,l1,k2,l2,      \
                   6764:                           subdirf2(optionfilefiname,"VARPIJGR_"), j1,k1,l1,k2,l2);
                   6765:                   fprintf(fichtmcov,"\n<br><img src=\"%s_%d%1d%1d-%1d%1d.svg\"> ",subdirf2(optionfilefiname,"VARPIJGR_"), j1,k1,l1,k2,l2);
                   6766:                   fprintf(fichtmcov,"\n<br> Correlation at age %d (%.3f),",(int) age, c12);
                   6767:                   fprintf(ficgp,"\nset out \"%s_%d%1d%1d-%1d%1d.svg\"",subdirf2(optionfilefiname,"VARPIJGR_"), j1,k1,l1,k2,l2);
                   6768:                   fprintf(ficgp,"\nset label \"%d\" at %11.3e,%11.3e center",(int) age, mu1,mu2);
                   6769:                   fprintf(ficgp,"\n# Age %d, p%1d%1d - p%1d%1d",(int) age, k1,l1,k2,l2);
                   6770:                   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  6771:                           mu1,std,v11,sqrt(fabs(lc1)),v12,sqrt(fabs(lc2)), \
                   6772:                           mu2,std,v21,sqrt(fabs(lc1)),v22,sqrt(fabs(lc2))); /* For gnuplot only */
1.222     brouard  6773:                 }else{
                   6774:                   first=0;
                   6775:                   fprintf(fichtmcov," %d (%.3f),",(int) age, c12);
                   6776:                   fprintf(ficgp,"\n# Age %d, p%1d%1d - p%1d%1d",(int) age, k1,l1,k2,l2);
                   6777:                   fprintf(ficgp,"\nset label \"%d\" at %11.3e,%11.3e center",(int) age, mu1,mu2);
                   6778:                   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  6779:                           mu1,std,v11,sqrt(lc1),v12,sqrt(fabs(lc2)),   \
                   6780:                           mu2,std,v21,sqrt(lc1),v22,sqrt(fabs(lc2)));
1.222     brouard  6781:                 }/* if first */
                   6782:               } /* age mod 5 */
                   6783:             } /* end loop age */
                   6784:             fprintf(ficgp,"\nset out;\nset out \"%s_%d%1d%1d-%1d%1d.svg\";replot;set out;",subdirf2(optionfilefiname,"VARPIJGR_"), j1,k1,l1,k2,l2);
                   6785:             first=1;
                   6786:           } /*l12 */
                   6787:         } /* k12 */
                   6788:        } /*l1 */
                   6789:      }/* k1 */
                   6790:    }  /* loop on combination of covariates j1 */
                   6791:    free_ma3x(varpij,1,nlstate,1,nlstate+ndeath,(int) bage, (int)fage);
                   6792:    free_matrix(mu,1,(nlstate+ndeath)*(nlstate+ndeath),(int) bage, (int)fage);
                   6793:    free_matrix(doldm,1,(nlstate)*(nlstate+ndeath),1,(nlstate)*(nlstate+ndeath));
                   6794:    free_matrix(dnewm,1,(nlstate)*(nlstate+ndeath),1,npar);
                   6795:    free_vector(xp,1,npar);
                   6796:    fclose(ficresprob);
                   6797:    fclose(ficresprobcov);
                   6798:    fclose(ficresprobcor);
                   6799:    fflush(ficgp);
                   6800:    fflush(fichtmcov);
                   6801:  }
1.126     brouard  6802: 
                   6803: 
                   6804: /******************* Printing html file ***********/
1.201     brouard  6805: void printinghtml(char fileresu[], char title[], char datafile[], int firstpass, \
1.126     brouard  6806:                  int lastpass, int stepm, int weightopt, char model[],\
                   6807:                  int imx,int jmin, int jmax, double jmeanint,char rfileres[],\
1.258     brouard  6808:                  int popforecast, int mobilav, int prevfcast, int mobilavproj, int backcast, int estepm , \
1.273     brouard  6809:                  double jprev1, double mprev1,double anprev1, double dateprev1, double dateproj1, double dateback1, \
                   6810:                  double jprev2, double mprev2,double anprev2, double dateprev2, double dateproj2, double dateback2){
1.237     brouard  6811:   int jj1, k1, i1, cpt, k4, nres;
1.126     brouard  6812: 
                   6813:    fprintf(fichtm,"<ul><li><a href='#firstorder'>Result files (first order: no variance)</a>\n \
                   6814:    <li><a href='#secondorder'>Result files (second order (variance)</a>\n \
                   6815: </ul>");
1.237     brouard  6816:    fprintf(fichtm,"<ul><li> model=1+age+%s\n \
                   6817: </ul>", model);
1.214     brouard  6818:    fprintf(fichtm,"<ul><li><h4><a name='firstorder'>Result files (first order: no variance)</a></h4>\n");
                   6819:    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",
                   6820:           jprev1, mprev1,anprev1,jprev2, mprev2,anprev2,subdirfext3(optionfilefiname,"PHTMFR_",".htm"),subdirfext3(optionfilefiname,"PHTMFR_",".htm"));
                   6821:    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  6822:           jprev1, mprev1,anprev1,jprev2, mprev2,anprev2,subdirfext3(optionfilefiname,"PHTM_",".htm"),subdirfext3(optionfilefiname,"PHTM_",".htm"));
                   6823:    fprintf(fichtm,",  <a href=\"%s\">%s</a> (text file) <br>\n",subdirf2(fileresu,"P_"),subdirf2(fileresu,"P_"));
1.126     brouard  6824:    fprintf(fichtm,"\
                   6825:  - Estimated transition probabilities over %d (stepm) months: <a href=\"%s\">%s</a><br>\n ",
1.201     brouard  6826:           stepm,subdirf2(fileresu,"PIJ_"),subdirf2(fileresu,"PIJ_"));
1.126     brouard  6827:    fprintf(fichtm,"\
1.217     brouard  6828:  - Estimated back transition probabilities over %d (stepm) months: <a href=\"%s\">%s</a><br>\n ",
                   6829:           stepm,subdirf2(fileresu,"PIJB_"),subdirf2(fileresu,"PIJB_"));
                   6830:    fprintf(fichtm,"\
1.288     brouard  6831:  - Period (forward) prevalence in each health state: <a href=\"%s\">%s</a> <br>\n",
1.201     brouard  6832:           subdirf2(fileresu,"PL_"),subdirf2(fileresu,"PL_"));
1.126     brouard  6833:    fprintf(fichtm,"\
1.288     brouard  6834:  - Backward prevalence in each health state: <a href=\"%s\">%s</a> <br>\n",
1.217     brouard  6835:           subdirf2(fileresu,"PLB_"),subdirf2(fileresu,"PLB_"));
                   6836:    fprintf(fichtm,"\
1.211     brouard  6837:  - (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  6838:    <a href=\"%s\">%s</a> <br>\n",
1.201     brouard  6839:           estepm,subdirf2(fileresu,"E_"),subdirf2(fileresu,"E_"));
1.211     brouard  6840:    if(prevfcast==1){
                   6841:      fprintf(fichtm,"\
                   6842:  - Prevalence projections by age and states:                           \
1.201     brouard  6843:    <a href=\"%s\">%s</a> <br>\n</li>", subdirf2(fileresu,"F_"),subdirf2(fileresu,"F_"));
1.211     brouard  6844:    }
1.126     brouard  6845: 
                   6846: 
1.225     brouard  6847:    m=pow(2,cptcoveff);
1.222     brouard  6848:    if (cptcovn < 1) {m=1;ncodemax[1]=1;}
1.126     brouard  6849: 
1.264     brouard  6850:    fprintf(fichtm," \n<ul><li><b>Graphs</b></li><p>");
                   6851: 
                   6852:    jj1=0;
                   6853: 
                   6854:    fprintf(fichtm," \n<ul>");
                   6855:    for(nres=1; nres <= nresult; nres++) /* For each resultline */
                   6856:    for(k1=1; k1<=m;k1++){ /* For each combination of covariate */
                   6857:      if(m != 1 && TKresult[nres]!= k1)
                   6858:        continue;
                   6859:      jj1++;
                   6860:      if (cptcovn > 0) {
                   6861:        fprintf(fichtm,"\n<li><a  size=\"1\" color=\"#EC5E5E\" href=\"#rescov");
                   6862:        for (cpt=1; cpt<=cptcoveff;cpt++){ 
                   6863:         fprintf(fichtm,"_V%d=%d_",Tvresult[nres][cpt],(int)Tresult[nres][cpt]);
                   6864:        }
                   6865:        for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
                   6866:         fprintf(fichtm,"_V%d=%f_",Tvqresult[nres][k4],Tqresult[nres][k4]);
                   6867:        }
                   6868:        fprintf(fichtm,"\">");
                   6869:        
                   6870:        /* if(nqfveff+nqtveff 0) */ /* Test to be done */
                   6871:        fprintf(fichtm,"************ Results for covariates");
                   6872:        for (cpt=1; cpt<=cptcoveff;cpt++){ 
                   6873:         fprintf(fichtm," V%d=%d ",Tvresult[nres][cpt],(int)Tresult[nres][cpt]);
                   6874:        }
                   6875:        for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
                   6876:         fprintf(fichtm," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
                   6877:        }
                   6878:        if(invalidvarcomb[k1]){
                   6879:         fprintf(fichtm," Warning Combination (%d) ignored because no cases ",k1); 
                   6880:         continue;
                   6881:        }
                   6882:        fprintf(fichtm,"</a></li>");
                   6883:      } /* cptcovn >0 */
                   6884:    }
                   6885:      fprintf(fichtm," \n</ul>");
                   6886: 
1.222     brouard  6887:    jj1=0;
1.237     brouard  6888: 
                   6889:    for(nres=1; nres <= nresult; nres++) /* For each resultline */
1.241     brouard  6890:    for(k1=1; k1<=m;k1++){ /* For each combination of covariate */
1.253     brouard  6891:      if(m != 1 && TKresult[nres]!= k1)
1.237     brouard  6892:        continue;
1.220     brouard  6893: 
1.222     brouard  6894:      /* for(i1=1; i1<=ncodemax[k1];i1++){ */
                   6895:      jj1++;
                   6896:      if (cptcovn > 0) {
1.264     brouard  6897:        fprintf(fichtm,"\n<p><a name=\"rescov");
                   6898:        for (cpt=1; cpt<=cptcoveff;cpt++){ 
                   6899:         fprintf(fichtm,"_V%d=%d_",Tvresult[nres][cpt],(int)Tresult[nres][cpt]);
                   6900:        }
                   6901:        for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
                   6902:         fprintf(fichtm,"_V%d=%f_",Tvqresult[nres][k4],Tqresult[nres][k4]);
                   6903:        }
                   6904:        fprintf(fichtm,"\"</a>");
                   6905:  
1.222     brouard  6906:        fprintf(fichtm,"<hr  size=\"2\" color=\"#EC5E5E\">************ Results for covariates");
1.225     brouard  6907:        for (cpt=1; cpt<=cptcoveff;cpt++){ 
1.237     brouard  6908:         fprintf(fichtm," V%d=%d ",Tvresult[nres][cpt],(int)Tresult[nres][cpt]);
                   6909:         printf(" V%d=%d ",Tvresult[nres][cpt],Tresult[nres][cpt]);fflush(stdout);
                   6910:         /* fprintf(fichtm," V%d=%d ",Tvaraff[cpt],nbcode[Tvaraff[cpt]][codtabm(jj1,cpt)]); */
                   6911:         /* printf(" V%d=%d ",Tvaraff[cpt],nbcode[Tvaraff[cpt]][codtabm(jj1,cpt)]);fflush(stdout); */
1.222     brouard  6912:        }
1.237     brouard  6913:        for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
                   6914:        fprintf(fichtm," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
                   6915:        printf(" V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);fflush(stdout);
                   6916:       }
                   6917:        
1.230     brouard  6918:        /* if(nqfveff+nqtveff 0) */ /* Test to be done */
1.222     brouard  6919:        fprintf(fichtm," ************\n<hr size=\"2\" color=\"#EC5E5E\">");
                   6920:        if(invalidvarcomb[k1]){
                   6921:         fprintf(fichtm,"\n<h3>Combination (%d) ignored because no cases </h3>\n",k1); 
                   6922:         printf("\nCombination (%d) ignored because no cases \n",k1); 
                   6923:         continue;
                   6924:        }
                   6925:      }
                   6926:      /* aij, bij */
1.259     brouard  6927:      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  6928: <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  6929:      /* Pij */
1.241     brouard  6930:      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> \
                   6931: <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  6932:      /* Quasi-incidences */
                   6933:      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  6934:  before but expressed in per year i.e. quasi incidences if stepm is small and probabilities too, \
1.211     brouard  6935:  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  6936: 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> \
                   6937: <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  6938:      /* Survival functions (period) in state j */
                   6939:      for(cpt=1; cpt<=nlstate;cpt++){
1.292     brouard  6940:        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  6941: <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  6942:      }
                   6943:      /* State specific survival functions (period) */
                   6944:      for(cpt=1; cpt<=nlstate;cpt++){
1.292     brouard  6945:        fprintf(fichtm,"<br>\n- Survival functions in state %d and in any other live state (total).\
                   6946:  And probability to be observed in various states (up to %d) being in state %d at different ages.      \
1.283     brouard  6947:  <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  6948:      }
1.288     brouard  6949:      /* Period (forward stable) prevalence in each health state */
1.222     brouard  6950:      for(cpt=1; cpt<=nlstate;cpt++){
1.264     brouard  6951:        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> \
                   6952: <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  6953:      }
                   6954:      if(backcast==1){
1.288     brouard  6955:        /* Backward prevalence in each health state */
1.222     brouard  6956:        for(cpt=1; cpt<=nlstate;cpt++){
1.264     brouard  6957:         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  6958: <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  6959:        }
1.217     brouard  6960:      }
1.222     brouard  6961:      if(prevfcast==1){
1.288     brouard  6962:        /* Projection of prevalence up to period (forward stable) prevalence in each health state */
1.222     brouard  6963:        for(cpt=1; cpt<=nlstate;cpt++){
1.288     brouard  6964:         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.273     brouard  6965: <img src=\"%s_%d-%d-%d.svg\">", dateprev1, dateprev2, mobilavproj, dateproj1, dateproj2, cpt, cpt, nlstate, subdirf2(optionfilefiname,"PROJ_"),cpt,k1,nres,subdirf2(optionfilefiname,"PROJ_"),cpt,k1,nres,subdirf2(optionfilefiname,"PROJ_"),cpt,k1,nres);
1.222     brouard  6966:        }
                   6967:      }
1.268     brouard  6968:      if(backcast==1){
                   6969:       /* Back projection of prevalence up to stable (mixed) back-prevalence in each health state */
                   6970:        for(cpt=1; cpt<=nlstate;cpt++){
1.273     brouard  6971:         fprintf(fichtm,"<br>\n- Back projection of cross-sectional prevalence (estimated with cases observed from %.1f to %.1f and mobil_average=%d), \
                   6972:  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 \
                   6973:  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) \
                   6974: with weights corresponding to observed prevalence at different ages. <a href=\"%s_%d-%d-%d.svg\">%s_%d-%d-%d.svg</a><br> \
                   6975:  <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  6976:        }
                   6977:      }
1.220     brouard  6978:         
1.222     brouard  6979:      for(cpt=1; cpt<=nlstate;cpt++) {
1.241     brouard  6980:        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> \
                   6981: <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  6982:      }
                   6983:      /* } /\* end i1 *\/ */
                   6984:    }/* End k1 */
                   6985:    fprintf(fichtm,"</ul>");
1.126     brouard  6986: 
1.222     brouard  6987:    fprintf(fichtm,"\
1.126     brouard  6988: \n<br><li><h4> <a name='secondorder'>Result files (second order: variances)</a></h4>\n\
1.193     brouard  6989:  - Parameter file with estimated parameters and covariance matrix: <a href=\"%s\">%s</a> <br> \
1.203     brouard  6990:  - 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  6991: But because parameters are usually highly correlated (a higher incidence of disability \
                   6992: and a higher incidence of recovery can give very close observed transition) it might \
                   6993: be very useful to look not only at linear confidence intervals estimated from the \
                   6994: variances but at the covariance matrix. And instead of looking at the estimated coefficients \
                   6995: (parameters) of the logistic regression, it might be more meaningful to visualize the \
                   6996: covariance matrix of the one-step probabilities. \
                   6997: See page 'Matrix of variance-covariance of one-step probabilities' below. \n", rfileres,rfileres);
1.126     brouard  6998: 
1.222     brouard  6999:    fprintf(fichtm," - Standard deviation of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
                   7000:           subdirf2(fileresu,"PROB_"),subdirf2(fileresu,"PROB_"));
                   7001:    fprintf(fichtm,"\
1.126     brouard  7002:  - Variance-covariance of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
1.222     brouard  7003:           subdirf2(fileresu,"PROBCOV_"),subdirf2(fileresu,"PROBCOV_"));
1.126     brouard  7004: 
1.222     brouard  7005:    fprintf(fichtm,"\
1.126     brouard  7006:  - Correlation matrix of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
1.222     brouard  7007:           subdirf2(fileresu,"PROBCOR_"),subdirf2(fileresu,"PROBCOR_"));
                   7008:    fprintf(fichtm,"\
1.126     brouard  7009:  - 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): \
                   7010:    <a href=\"%s\">%s</a> <br>\n</li>",
1.201     brouard  7011:           estepm,subdirf2(fileresu,"CVE_"),subdirf2(fileresu,"CVE_"));
1.222     brouard  7012:    fprintf(fichtm,"\
1.126     brouard  7013:  - (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): \
                   7014:    <a href=\"%s\">%s</a> <br>\n</li>",
1.201     brouard  7015:           estepm,subdirf2(fileresu,"STDE_"),subdirf2(fileresu,"STDE_"));
1.222     brouard  7016:    fprintf(fichtm,"\
1.288     brouard  7017:  - 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  7018:           estepm, subdirf2(fileresu,"V_"),subdirf2(fileresu,"V_"));
                   7019:    fprintf(fichtm,"\
1.128     brouard  7020:  - 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  7021:           estepm, subdirf2(fileresu,"T_"),subdirf2(fileresu,"T_"));
                   7022:    fprintf(fichtm,"\
1.288     brouard  7023:  - Standard deviation of forward (period) prevalences: <a href=\"%s\">%s</a> <br>\n",\
1.222     brouard  7024:           subdirf2(fileresu,"VPL_"),subdirf2(fileresu,"VPL_"));
1.126     brouard  7025: 
                   7026: /*  if(popforecast==1) fprintf(fichtm,"\n */
                   7027: /*  - Prevalences forecasting: <a href=\"f%s\">f%s</a> <br>\n */
                   7028: /*  - Population forecasting (if popforecast=1): <a href=\"pop%s\">pop%s</a> <br>\n */
                   7029: /*     <br>",fileres,fileres,fileres,fileres); */
                   7030: /*  else  */
                   7031: /*    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  7032:    fflush(fichtm);
                   7033:    fprintf(fichtm," <ul><li><b>Graphs</b></li><p>");
1.126     brouard  7034: 
1.225     brouard  7035:    m=pow(2,cptcoveff);
1.222     brouard  7036:    if (cptcovn < 1) {m=1;ncodemax[1]=1;}
1.126     brouard  7037: 
1.222     brouard  7038:    jj1=0;
1.237     brouard  7039: 
1.241     brouard  7040:    for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.222     brouard  7041:    for(k1=1; k1<=m;k1++){
1.253     brouard  7042:      if(m != 1 && TKresult[nres]!= k1)
1.237     brouard  7043:        continue;
1.222     brouard  7044:      /* for(i1=1; i1<=ncodemax[k1];i1++){ */
                   7045:      jj1++;
1.126     brouard  7046:      if (cptcovn > 0) {
                   7047:        fprintf(fichtm,"<hr  size=\"2\" color=\"#EC5E5E\">************ Results for covariates");
1.225     brouard  7048:        for (cpt=1; cpt<=cptcoveff;cpt++)  /**< cptcoveff number of variables */
1.237     brouard  7049:         fprintf(fichtm," V%d=%d ",Tvresult[nres][cpt],Tresult[nres][cpt]);
                   7050:         /* fprintf(fichtm," V%d=%d ",Tvaraff[cpt],nbcode[Tvaraff[cpt]][codtabm(jj1,cpt)]); */
                   7051:        for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
                   7052:        fprintf(fichtm," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
                   7053:       }
                   7054: 
1.126     brouard  7055:        fprintf(fichtm," ************\n<hr size=\"2\" color=\"#EC5E5E\">");
1.220     brouard  7056: 
1.222     brouard  7057:        if(invalidvarcomb[k1]){
                   7058:         fprintf(fichtm,"\n<h4>Combination (%d) ignored because no cases </h4>\n",k1); 
                   7059:         continue;
                   7060:        }
1.126     brouard  7061:      }
                   7062:      for(cpt=1; cpt<=nlstate;cpt++) {
1.258     brouard  7063:        fprintf(fichtm,"\n<br>- Observed (cross-sectional with mov_average=%d) and period (incidence based) \
1.241     brouard  7064: 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  7065: <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  7066:      }
                   7067:      fprintf(fichtm,"\n<br>- Total life expectancy by age and \
1.128     brouard  7068: health expectancies in states (1) and (2). If popbased=1 the smooth (due to the model) \
                   7069: true period expectancies (those weighted with period prevalences are also\
                   7070:  drawn in addition to the population based expectancies computed using\
1.241     brouard  7071:  observed and cahotic prevalences:  <a href=\"%s_%d-%d.svg\">%s_%d-%d.svg</a>\n<br>\
                   7072: <img src=\"%s_%d-%d.svg\">",subdirf2(optionfilefiname,"E_"),k1,nres,subdirf2(optionfilefiname,"E_"),k1,nres,subdirf2(optionfilefiname,"E_"),k1,nres);
1.222     brouard  7073:      /* } /\* end i1 *\/ */
                   7074:    }/* End k1 */
1.241     brouard  7075:   }/* End nres */
1.222     brouard  7076:    fprintf(fichtm,"</ul>");
                   7077:    fflush(fichtm);
1.126     brouard  7078: }
                   7079: 
                   7080: /******************* Gnuplot file **************/
1.270     brouard  7081: void printinggnuplot(char fileresu[], char optionfilefiname[], double ageminpar, double agemaxpar, double bage, double fage , int prevfcast, int backcast, char pathc[], double p[], int offyear, int offbyear){
1.126     brouard  7082: 
                   7083:   char dirfileres[132],optfileres[132];
1.264     brouard  7084:   char gplotcondition[132], gplotlabel[132];
1.237     brouard  7085:   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  7086:   int lv=0, vlv=0, kl=0;
1.130     brouard  7087:   int ng=0;
1.201     brouard  7088:   int vpopbased;
1.223     brouard  7089:   int ioffset; /* variable offset for columns */
1.270     brouard  7090:   int iyearc=1; /* variable column for year of projection  */
                   7091:   int iagec=1; /* variable column for age of projection  */
1.235     brouard  7092:   int nres=0; /* Index of resultline */
1.266     brouard  7093:   int istart=1; /* For starting graphs in projections */
1.219     brouard  7094: 
1.126     brouard  7095: /*   if((ficgp=fopen(optionfilegnuplot,"a"))==NULL) { */
                   7096: /*     printf("Problem with file %s",optionfilegnuplot); */
                   7097: /*     fprintf(ficlog,"Problem with file %s",optionfilegnuplot); */
                   7098: /*   } */
                   7099: 
                   7100:   /*#ifdef windows */
                   7101:   fprintf(ficgp,"cd \"%s\" \n",pathc);
1.223     brouard  7102:   /*#endif */
1.225     brouard  7103:   m=pow(2,cptcoveff);
1.126     brouard  7104: 
1.274     brouard  7105:   /* diagram of the model */
                   7106:   fprintf(ficgp,"\n#Diagram of the model \n");
                   7107:   fprintf(ficgp,"\ndelta=0.03;delta2=0.07;unset arrow;\n");
                   7108:   fprintf(ficgp,"yoff=(%d > 2? 0:1);\n",nlstate);
                   7109:   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);
                   7110: 
                   7111:   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);
                   7112:   fprintf(ficgp,"\n#show arrow\nunset label\n");
                   7113:   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);
                   7114:   fprintf(ficgp,"\nset label %d+1 sprintf(\"State %%d\",%d+1) center at 0.,0.  font \"helvetica, 16\" tc rgbcolor \"red\"\n",nlstate,nlstate);
                   7115:   fprintf(ficgp,"\n#show label\nunset border;unset xtics; unset ytics;\n");
                   7116:   fprintf(ficgp,"\n\nset ter svg size 640, 480;set out \"%s_.svg\" \n",subdirf2(optionfilefiname,"D_"));
                   7117:   fprintf(ficgp,"unset log y; plot [-1.2:1.2][yoff-1.2:1.2] 1/0 not; set out;reset;\n");
                   7118: 
1.202     brouard  7119:   /* Contribution to likelihood */
                   7120:   /* Plot the probability implied in the likelihood */
1.223     brouard  7121:   fprintf(ficgp,"\n# Contributions to the Likelihood, mle >=1. For mle=4 no interpolation, pure matrix products.\n#\n");
                   7122:   fprintf(ficgp,"\n set log y; unset log x;set xlabel \"Age\"; set ylabel \"Likelihood (-2Log(L))\";");
                   7123:   /* fprintf(ficgp,"\nset ter svg size 640, 480"); */ /* Too big for svg */
                   7124:   fprintf(ficgp,"\nset ter pngcairo size 640, 480");
1.204     brouard  7125: /* nice for mle=4 plot by number of matrix products.
1.202     brouard  7126:    replot  "rrtest1/toto.txt" u 2:($4 == 1 && $5==2 ? $9 : 1/0):5 t "p12" with point lc 1 */
                   7127: /* replot exp(p1+p2*x)/(1+exp(p1+p2*x)+exp(p3+p4*x)+exp(p5+p6*x)) t "p12(x)"  */
1.223     brouard  7128:   /* fprintf(ficgp,"\nset out \"%s.svg\";",subdirf2(optionfilefiname,"ILK_")); */
                   7129:   fprintf(ficgp,"\nset out \"%s-dest.png\";",subdirf2(optionfilefiname,"ILK_"));
                   7130:   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));
                   7131:   fprintf(ficgp,"\nset out \"%s-ori.png\";",subdirf2(optionfilefiname,"ILK_"));
                   7132:   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));
                   7133:   for (i=1; i<= nlstate ; i ++) {
                   7134:     fprintf(ficgp,"\nset out \"%s-p%dj.png\";set ylabel \"Probability for each individual/wave\";",subdirf2(optionfilefiname,"ILK_"),i);
                   7135:     fprintf(ficgp,"unset log;\n# plot weighted, mean weight should have point size of 0.5\n plot  \"%s\"",subdirf(fileresilk));
                   7136:     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);
                   7137:     for (j=2; j<= nlstate+ndeath ; j ++) {
                   7138:       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);
                   7139:     }
                   7140:     fprintf(ficgp,";\nset out; unset ylabel;\n"); 
                   7141:   }
                   7142:   /* 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 */               
                   7143:   /* fprintf(ficgp,"\nset log y;plot  \"%s\" u 2:(-$11):3 t \"All sample, all transitions\" with dots lc variable",subdirf(fileresilk)); */
                   7144:   /* fprintf(ficgp,"\nreplot  \"%s\" u 2:($3 <= 3 ? -$11 : 1/0):3 t \"First 3 individuals\" with line lc variable", subdirf(fileresilk)); */
                   7145:   fprintf(ficgp,"\nset out;unset log\n");
                   7146:   /* fprintf(ficgp,"\nset out \"%s.svg\"; replot; set out; # bug gnuplot",subdirf2(optionfilefiname,"ILK_")); */
1.202     brouard  7147: 
1.126     brouard  7148:   strcpy(dirfileres,optionfilefiname);
                   7149:   strcpy(optfileres,"vpl");
1.223     brouard  7150:   /* 1eme*/
1.238     brouard  7151:   for (cpt=1; cpt<= nlstate ; cpt ++){ /* For each live state */
                   7152:     for (k1=1; k1<= m ; k1 ++){ /* For each valid combination of covariate */
1.236     brouard  7153:       for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.238     brouard  7154:        /* plot [100000000000000000000:-100000000000000000000] "mysbiaspar/vplrmysbiaspar.txt to check */
1.253     brouard  7155:        if(m != 1 && TKresult[nres]!= k1)
1.238     brouard  7156:          continue;
                   7157:        /* We are interested in selected combination by the resultline */
1.246     brouard  7158:        /* printf("\n# 1st: Period (stable) prevalence with CI: 'VPL_' files and live state =%d ", cpt); */
1.288     brouard  7159:        fprintf(ficgp,"\n# 1st: Forward (stable period) prevalence with CI: 'VPL_' files  and live state =%d ", cpt);
1.264     brouard  7160:        strcpy(gplotlabel,"(");
1.238     brouard  7161:        for (k=1; k<=cptcoveff; k++){    /* For each covariate k get corresponding value lv for combination k1 */
                   7162:          lv= decodtabm(k1,k,cptcoveff); /* Should be the value of the covariate corresponding to k1 combination */
                   7163:          /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   7164:          /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   7165:          /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
                   7166:          vlv= nbcode[Tvaraff[k]][lv]; /* vlv is the value of the covariate lv, 0 or 1 */
                   7167:          /* For each combination of covariate k1 (V1=1, V3=0), we printed the current covariate k and its value vlv */
1.246     brouard  7168:          /* printf(" V%d=%d ",Tvaraff[k],vlv); */
1.238     brouard  7169:          fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv);
1.264     brouard  7170:          sprintf(gplotlabel+strlen(gplotlabel)," V%d=%d ",Tvaraff[k],vlv);
1.238     brouard  7171:        }
                   7172:        for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
1.246     brouard  7173:          /* printf(" V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]); */
1.238     brouard  7174:          fprintf(ficgp," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
1.264     brouard  7175:          sprintf(gplotlabel+strlen(gplotlabel)," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
                   7176:        }
                   7177:        strcpy(gplotlabel+strlen(gplotlabel),")");
1.246     brouard  7178:        /* printf("\n#\n"); */
1.238     brouard  7179:        fprintf(ficgp,"\n#\n");
                   7180:        if(invalidvarcomb[k1]){
1.260     brouard  7181:           /*k1=k1-1;*/ /* To be checked */
1.238     brouard  7182:          fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   7183:          continue;
                   7184:        }
1.235     brouard  7185:       
1.241     brouard  7186:        fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" \n",subdirf2(optionfilefiname,"V_"),cpt,k1,nres);
                   7187:        fprintf(ficgp,"\n#set out \"V_%s_%d-%d-%d.svg\" \n",optionfilefiname,cpt,k1,nres);
1.276     brouard  7188:        /* fprintf(ficgp,"set label \"Alive state %d %s\" at graph 0.98,0.5 center rotate font \"Helvetica,12\"\n",cpt,gplotlabel); */
                   7189:        fprintf(ficgp,"set title \"Alive state %d %s\" font \"Helvetica,12\"\n",cpt,gplotlabel);
1.260     brouard  7190:        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);
                   7191:        /* 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); */
                   7192:       /* k1-1 error should be nres-1*/
1.238     brouard  7193:        for (i=1; i<= nlstate ; i ++) {
                   7194:          if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
                   7195:          else        fprintf(ficgp," %%*lf (%%*lf)");
                   7196:        }
1.288     brouard  7197:        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  7198:        for (i=1; i<= nlstate ; i ++) {
                   7199:          if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
                   7200:          else fprintf(ficgp," %%*lf (%%*lf)");
                   7201:        } 
1.260     brouard  7202:        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  7203:        for (i=1; i<= nlstate ; i ++) {
                   7204:          if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
                   7205:          else fprintf(ficgp," %%*lf (%%*lf)");
                   7206:        }  
1.265     brouard  7207:        /* 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)); */
                   7208:        
                   7209:        fprintf(ficgp,"\" t\"\" w l lt 1,\"%s\" u 1:((",subdirf2(fileresu,"P_"));
                   7210:         if(cptcoveff ==0){
1.271     brouard  7211:          fprintf(ficgp,"$%d)) t 'Observed prevalence in state %d' with line lt 3",      2+3*(cpt-1),  cpt );
1.265     brouard  7212:        }else{
                   7213:          kl=0;
                   7214:          for (k=1; k<=cptcoveff; k++){    /* For each combination of covariate  */
                   7215:            lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate value corresponding to k1 combination and kth covariate */
                   7216:            /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   7217:            /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   7218:            /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
                   7219:            vlv= nbcode[Tvaraff[k]][lv];
                   7220:            kl++;
                   7221:            /* 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 *\/ */
                   7222:            /*6+(cpt-1)*(nlstate+1)+1+(i-1)+(nlstate+1)*nlstate; 6+(1-1)*(2+1)+1+(1-1) +(2+1)*2=13 */ 
                   7223:            /*6+1+(i-1)+(nlstate+1)*nlstate; 6+1+(1-1) +(2+1)*2=13 */ 
                   7224:            /* ''  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*/
                   7225:            if(k==cptcoveff){
                   7226:              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], \
                   7227:                      2+cptcoveff*2+3*(cpt-1),  cpt );  /* 4 or 6 ?*/
                   7228:            }else{
                   7229:              fprintf(ficgp,"$%d==%d && $%d==%d && ",kl+1, Tvaraff[k],kl+1+1,nbcode[Tvaraff[k]][lv]);
                   7230:              kl++;
                   7231:            }
                   7232:          } /* end covariate */
                   7233:        } /* end if no covariate */
                   7234: 
1.238     brouard  7235:        if(backcast==1){ /* We need to get the corresponding values of the covariates involved in this combination k1 */
                   7236:          /* 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  7237:          fprintf(ficgp,",\"%s\" u 1:((",subdirf2(fileresu,"PLB_")); /* Age is in 1, nres in 2 to be fixed */
1.238     brouard  7238:          if(cptcoveff ==0){
1.245     brouard  7239:            fprintf(ficgp,"$%d)) t 'Backward prevalence in state %d' with line lt 3",    2+(cpt-1),  cpt );
1.238     brouard  7240:          }else{
                   7241:            kl=0;
                   7242:            for (k=1; k<=cptcoveff; k++){    /* For each combination of covariate  */
                   7243:              lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate value corresponding to k1 combination and kth covariate */
                   7244:              /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   7245:              /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   7246:              /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
                   7247:              vlv= nbcode[Tvaraff[k]][lv];
1.223     brouard  7248:              kl++;
1.238     brouard  7249:              /* 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 *\/ */
                   7250:              /*6+(cpt-1)*(nlstate+1)+1+(i-1)+(nlstate+1)*nlstate; 6+(1-1)*(2+1)+1+(1-1) +(2+1)*2=13 */ 
                   7251:              /*6+1+(i-1)+(nlstate+1)*nlstate; 6+1+(1-1) +(2+1)*2=13 */ 
                   7252:              /* ''  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*/
                   7253:              if(k==cptcoveff){
1.245     brouard  7254:                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  7255:                        2+cptcoveff*2+(cpt-1),  cpt );  /* 4 or 6 ?*/
1.238     brouard  7256:              }else{
                   7257:                fprintf(ficgp,"$%d==%d && $%d==%d && ",kl+1, Tvaraff[k],kl+1+1,nbcode[Tvaraff[k]][lv]);
                   7258:                kl++;
                   7259:              }
                   7260:            } /* end covariate */
                   7261:          } /* end if no covariate */
1.268     brouard  7262:          if(backcast == 1){
                   7263:            fprintf(ficgp,", \"%s\" every :::%d::%d u 1:($2==%d ? $3:1/0) \"%%lf %%lf",subdirf2(fileresu,"VBL_"),nres-1,nres-1,nres);
                   7264:            /* k1-1 error should be nres-1*/
                   7265:            for (i=1; i<= nlstate ; i ++) {
                   7266:              if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
                   7267:              else        fprintf(ficgp," %%*lf (%%*lf)");
                   7268:            }
1.271     brouard  7269:            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  7270:            for (i=1; i<= nlstate ; i ++) {
                   7271:              if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
                   7272:              else fprintf(ficgp," %%*lf (%%*lf)");
                   7273:            } 
1.276     brouard  7274:            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  7275:            for (i=1; i<= nlstate ; i ++) {
                   7276:              if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
                   7277:              else fprintf(ficgp," %%*lf (%%*lf)");
                   7278:            } 
1.274     brouard  7279:            fprintf(ficgp,"\" t\"\" w l lt 4");
1.268     brouard  7280:          } /* end if backprojcast */
1.238     brouard  7281:        } /* end if backcast */
1.276     brouard  7282:        /* fprintf(ficgp,"\nset out ;unset label;\n"); */
                   7283:        fprintf(ficgp,"\nset out ;unset title;\n");
1.238     brouard  7284:       } /* nres */
1.201     brouard  7285:     } /* k1 */
                   7286:   } /* cpt */
1.235     brouard  7287: 
                   7288:   
1.126     brouard  7289:   /*2 eme*/
1.238     brouard  7290:   for (k1=1; k1<= m ; k1 ++){  
                   7291:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.253     brouard  7292:       if(m != 1 && TKresult[nres]!= k1)
1.238     brouard  7293:        continue;
                   7294:       fprintf(ficgp,"\n# 2nd: Total life expectancy with CI: 't' files ");
1.264     brouard  7295:       strcpy(gplotlabel,"(");
1.238     brouard  7296:       for (k=1; k<=cptcoveff; k++){    /* For each covariate and each value */
1.225     brouard  7297:        lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate number corresponding to k1 combination */
1.223     brouard  7298:        /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   7299:        /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   7300:        /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
                   7301:        vlv= nbcode[Tvaraff[k]][lv];
                   7302:        fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv);
1.264     brouard  7303:        sprintf(gplotlabel+strlen(gplotlabel)," V%d=%d ",Tvaraff[k],vlv);
1.211     brouard  7304:       }
1.237     brouard  7305:       /* for(k=1; k <= ncovds; k++){ */
1.236     brouard  7306:       for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
1.238     brouard  7307:        printf(" V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
1.236     brouard  7308:        fprintf(ficgp," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
1.264     brouard  7309:        sprintf(gplotlabel+strlen(gplotlabel)," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
1.238     brouard  7310:       }
1.264     brouard  7311:       strcpy(gplotlabel+strlen(gplotlabel),")");
1.211     brouard  7312:       fprintf(ficgp,"\n#\n");
1.223     brouard  7313:       if(invalidvarcomb[k1]){
                   7314:        fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   7315:        continue;
                   7316:       }
1.219     brouard  7317:                        
1.241     brouard  7318:       fprintf(ficgp,"\nset out \"%s_%d-%d.svg\" \n",subdirf2(optionfilefiname,"E_"),k1,nres);
1.238     brouard  7319:       for(vpopbased=0; vpopbased <= popbased; vpopbased++){ /* Done for vpopbased=0 and vpopbased=1 if popbased==1*/
1.264     brouard  7320:        fprintf(ficgp,"\nset label \"popbased %d %s\" at graph 0.98,0.5 center rotate font \"Helvetica,12\"\n",vpopbased,gplotlabel);
                   7321:        if(vpopbased==0){
1.238     brouard  7322:          fprintf(ficgp,"set ylabel \"Years\" \nset ter svg size 640, 480\nplot [%.f:%.f] ",ageminpar,fage);
1.264     brouard  7323:        }else
1.238     brouard  7324:          fprintf(ficgp,"\nreplot ");
                   7325:        for (i=1; i<= nlstate+1 ; i ++) {
                   7326:          k=2*i;
1.261     brouard  7327:          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  7328:          for (j=1; j<= nlstate+1 ; j ++) {
                   7329:            if (j==i) fprintf(ficgp," %%lf (%%lf)");
                   7330:            else fprintf(ficgp," %%*lf (%%*lf)");
                   7331:          }   
                   7332:          if (i== 1) fprintf(ficgp,"\" t\"TLE\" w l lt %d, \\\n",i);
                   7333:          else fprintf(ficgp,"\" t\"LE in state (%d)\" w l lt %d, \\\n",i-1,i+1);
1.261     brouard  7334:          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  7335:          for (j=1; j<= nlstate+1 ; j ++) {
                   7336:            if (j==i) fprintf(ficgp," %%lf (%%lf)");
                   7337:            else fprintf(ficgp," %%*lf (%%*lf)");
                   7338:          }   
                   7339:          fprintf(ficgp,"\" t\"\" w l lt 0,");
1.261     brouard  7340:          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  7341:          for (j=1; j<= nlstate+1 ; j ++) {
                   7342:            if (j==i) fprintf(ficgp," %%lf (%%lf)");
                   7343:            else fprintf(ficgp," %%*lf (%%*lf)");
                   7344:          }   
                   7345:          if (i== (nlstate+1)) fprintf(ficgp,"\" t\"\" w l lt 0");
                   7346:          else fprintf(ficgp,"\" t\"\" w l lt 0,\\\n");
                   7347:        } /* state */
                   7348:       } /* vpopbased */
1.264     brouard  7349:       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  7350:     } /* end nres */
                   7351:   } /* k1 end 2 eme*/
                   7352:        
                   7353:        
                   7354:   /*3eme*/
                   7355:   for (k1=1; k1<= m ; k1 ++){
                   7356:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.253     brouard  7357:       if(m != 1 && TKresult[nres]!= k1)
1.238     brouard  7358:        continue;
                   7359: 
                   7360:       for (cpt=1; cpt<= nlstate ; cpt ++) {
1.261     brouard  7361:        fprintf(ficgp,"\n\n# 3d: Life expectancy with EXP_ files:  combination=%d state=%d",k1, cpt);
1.264     brouard  7362:        strcpy(gplotlabel,"(");
1.238     brouard  7363:        for (k=1; k<=cptcoveff; k++){    /* For each covariate and each value */
                   7364:          lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate number corresponding to k1 combination */
                   7365:          /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   7366:          /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   7367:          /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
                   7368:          vlv= nbcode[Tvaraff[k]][lv];
                   7369:          fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv);
1.264     brouard  7370:          sprintf(gplotlabel+strlen(gplotlabel)," V%d=%d ",Tvaraff[k],vlv);
1.238     brouard  7371:        }
                   7372:        for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
                   7373:          fprintf(ficgp," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
1.264     brouard  7374:          sprintf(gplotlabel+strlen(gplotlabel)," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
1.238     brouard  7375:        }       
1.264     brouard  7376:        strcpy(gplotlabel+strlen(gplotlabel),")");
1.238     brouard  7377:        fprintf(ficgp,"\n#\n");
                   7378:        if(invalidvarcomb[k1]){
                   7379:          fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   7380:          continue;
                   7381:        }
                   7382:                        
                   7383:        /*       k=2+nlstate*(2*cpt-2); */
                   7384:        k=2+(nlstate+1)*(cpt-1);
1.241     brouard  7385:        fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" \n",subdirf2(optionfilefiname,"EXP_"),cpt,k1,nres);
1.264     brouard  7386:        fprintf(ficgp,"set label \"%s\" at graph 0.98,0.5 center rotate font \"Helvetica,12\"\n",gplotlabel);
1.238     brouard  7387:        fprintf(ficgp,"set ter svg size 640, 480\n\
1.261     brouard  7388: 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  7389:        /*fprintf(ficgp,",\"e%s\" every :::%d::%d u 1:($%d-2*$%d) \"\%%lf ",fileres,k1-1,k1-1,k,k+1);
                   7390:          for (i=1; i<= nlstate*2 ; i ++) fprintf(ficgp,"\%%lf (\%%lf) ");
                   7391:          fprintf(ficgp,"\" t \"e%d1\" w l",cpt);
                   7392:          fprintf(ficgp,",\"e%s\" every :::%d::%d u 1:($%d+2*$%d) \"\%%lf ",fileres,k1-1,k1-1,k,k+1);
                   7393:          for (i=1; i<= nlstate*2 ; i ++) fprintf(ficgp,"\%%lf (\%%lf) ");
                   7394:          fprintf(ficgp,"\" t \"e%d1\" w l",cpt);
1.219     brouard  7395:                                
1.238     brouard  7396:        */
                   7397:        for (i=1; i< nlstate ; i ++) {
1.261     brouard  7398:          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  7399:          /*    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  7400:                                
1.238     brouard  7401:        } 
1.261     brouard  7402:        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  7403:       }
1.264     brouard  7404:       fprintf(ficgp,"\nunset label;\n");
1.238     brouard  7405:     } /* end nres */
                   7406:   } /* end kl 3eme */
1.126     brouard  7407:   
1.223     brouard  7408:   /* 4eme */
1.201     brouard  7409:   /* Survival functions (period) from state i in state j by initial state i */
1.238     brouard  7410:   for (k1=1; k1<=m; k1++){    /* For each covariate and each value */
                   7411:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.253     brouard  7412:       if(m != 1 && TKresult[nres]!= k1)
1.223     brouard  7413:        continue;
1.238     brouard  7414:       for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each life state cpt*/
1.264     brouard  7415:        strcpy(gplotlabel,"(");
1.238     brouard  7416:        fprintf(ficgp,"\n#\n#\n# Survival functions in state j : 'LIJ_' files, cov=%d state=%d",k1, cpt);
                   7417:        for (k=1; k<=cptcoveff; k++){    /* For each covariate and each value */
                   7418:          lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate number corresponding to k1 combination */
                   7419:          /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   7420:          /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   7421:          /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
                   7422:          vlv= nbcode[Tvaraff[k]][lv];
                   7423:          fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv);
1.264     brouard  7424:          sprintf(gplotlabel+strlen(gplotlabel)," V%d=%d ",Tvaraff[k],vlv);
1.238     brouard  7425:        }
                   7426:        for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
                   7427:          fprintf(ficgp," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
1.264     brouard  7428:          sprintf(gplotlabel+strlen(gplotlabel)," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
1.238     brouard  7429:        }       
1.264     brouard  7430:        strcpy(gplotlabel+strlen(gplotlabel),")");
1.238     brouard  7431:        fprintf(ficgp,"\n#\n");
                   7432:        if(invalidvarcomb[k1]){
                   7433:          fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   7434:          continue;
1.223     brouard  7435:        }
1.238     brouard  7436:       
1.241     brouard  7437:        fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" \n",subdirf2(optionfilefiname,"LIJ_"),cpt,k1,nres);
1.264     brouard  7438:        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  7439:        fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Probability to be alive\" \n\
                   7440: set ter svg size 640, 480\nunset log y\nplot [%.f:%.f]  ", ageminpar, agemaxpar);
                   7441:        k=3;
                   7442:        for (i=1; i<= nlstate ; i ++){
                   7443:          if(i==1){
                   7444:            fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"PIJ_"));
                   7445:          }else{
                   7446:            fprintf(ficgp,", '' ");
                   7447:          }
                   7448:          l=(nlstate+ndeath)*(i-1)+1;
                   7449:          fprintf(ficgp," u ($1==%d ? ($3):1/0):($%d/($%d",k1,k+l+(cpt-1),k+l);
                   7450:          for (j=2; j<= nlstate+ndeath ; j ++)
                   7451:            fprintf(ficgp,"+$%d",k+l+j-1);
                   7452:          fprintf(ficgp,")) t \"l(%d,%d)\" w l",i,cpt);
                   7453:        } /* nlstate */
1.264     brouard  7454:        fprintf(ficgp,"\nset out; unset label;\n");
1.238     brouard  7455:       } /* end cpt state*/ 
                   7456:     } /* end nres */
                   7457:   } /* end covariate k1 */  
                   7458: 
1.220     brouard  7459: /* 5eme */
1.201     brouard  7460:   /* Survival functions (period) from state i in state j by final state j */
1.238     brouard  7461:   for (k1=1; k1<= m ; k1++){ /* For each covariate combination if any */
                   7462:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.253     brouard  7463:       if(m != 1 && TKresult[nres]!= k1)
1.227     brouard  7464:        continue;
1.238     brouard  7465:       for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each inital state  */
1.264     brouard  7466:        strcpy(gplotlabel,"(");
1.238     brouard  7467:        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);
                   7468:        for (k=1; k<=cptcoveff; k++){    /* For each covariate and each value */
                   7469:          lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate number corresponding to k1 combination */
                   7470:          /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   7471:          /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   7472:          /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
                   7473:          vlv= nbcode[Tvaraff[k]][lv];
                   7474:          fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv);
1.264     brouard  7475:          sprintf(gplotlabel+strlen(gplotlabel)," V%d=%d ",Tvaraff[k],vlv);
1.238     brouard  7476:        }
                   7477:        for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
                   7478:          fprintf(ficgp," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
1.264     brouard  7479:          sprintf(gplotlabel+strlen(gplotlabel)," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
1.238     brouard  7480:        }       
1.264     brouard  7481:        strcpy(gplotlabel+strlen(gplotlabel),")");
1.238     brouard  7482:        fprintf(ficgp,"\n#\n");
                   7483:        if(invalidvarcomb[k1]){
                   7484:          fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   7485:          continue;
                   7486:        }
1.227     brouard  7487:       
1.241     brouard  7488:        fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" \n",subdirf2(optionfilefiname,"LIJT_"),cpt,k1,nres);
1.264     brouard  7489:        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  7490:        fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Probability to be alive\" \n\
                   7491: set ter svg size 640, 480\nunset log y\nplot [%.f:%.f]  ", ageminpar, agemaxpar);
                   7492:        k=3;
                   7493:        for (j=1; j<= nlstate ; j ++){ /* Lived in state j */
                   7494:          if(j==1)
                   7495:            fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"PIJ_"));
                   7496:          else
                   7497:            fprintf(ficgp,", '' ");
                   7498:          l=(nlstate+ndeath)*(cpt-1) +j;
                   7499:          fprintf(ficgp," u (($1==%d && (floor($2)%%5 == 0)) ? ($3):1/0):($%d",k1,k+l);
                   7500:          /* for (i=2; i<= nlstate+ndeath ; i ++) */
                   7501:          /*   fprintf(ficgp,"+$%d",k+l+i-1); */
                   7502:          fprintf(ficgp,") t \"l(%d,%d)\" w l",cpt,j);
                   7503:        } /* nlstate */
                   7504:        fprintf(ficgp,", '' ");
                   7505:        fprintf(ficgp," u (($1==%d && (floor($2)%%5 == 0)) ? ($3):1/0):(",k1);
                   7506:        for (j=1; j<= nlstate ; j ++){ /* Lived in state j */
                   7507:          l=(nlstate+ndeath)*(cpt-1) +j;
                   7508:          if(j < nlstate)
                   7509:            fprintf(ficgp,"$%d +",k+l);
                   7510:          else
                   7511:            fprintf(ficgp,"$%d) t\"l(%d,.)\" w l",k+l,cpt);
                   7512:        }
1.264     brouard  7513:        fprintf(ficgp,"\nset out; unset label;\n");
1.238     brouard  7514:       } /* end cpt state*/ 
                   7515:     } /* end covariate */  
                   7516:   } /* end nres */
1.227     brouard  7517:   
1.220     brouard  7518: /* 6eme */
1.202     brouard  7519:   /* CV preval stable (period) for each covariate */
1.237     brouard  7520:   for (k1=1; k1<= m ; k1 ++) /* For each covariate combination if any */
                   7521:   for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.253     brouard  7522:     if(m != 1 && TKresult[nres]!= k1)
1.237     brouard  7523:       continue;
1.255     brouard  7524:     for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each life state of arrival */
1.264     brouard  7525:       strcpy(gplotlabel,"(");      
1.288     brouard  7526:       fprintf(ficgp,"\n#\n#\n#CV preval stable (forward): 'pij' files, covariatecombination#=%d state=%d",k1, cpt);
1.225     brouard  7527:       for (k=1; k<=cptcoveff; k++){    /* For each covariate and each value */
1.227     brouard  7528:        lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate number corresponding to k1 combination */
                   7529:        /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   7530:        /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   7531:        /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
                   7532:        vlv= nbcode[Tvaraff[k]][lv];
                   7533:        fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv);
1.264     brouard  7534:        sprintf(gplotlabel+strlen(gplotlabel)," V%d=%d ",Tvaraff[k],vlv);
1.211     brouard  7535:       }
1.237     brouard  7536:       for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
                   7537:        fprintf(ficgp," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
1.264     brouard  7538:        sprintf(gplotlabel+strlen(gplotlabel)," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
1.237     brouard  7539:       }        
1.264     brouard  7540:       strcpy(gplotlabel+strlen(gplotlabel),")");
1.211     brouard  7541:       fprintf(ficgp,"\n#\n");
1.223     brouard  7542:       if(invalidvarcomb[k1]){
1.227     brouard  7543:        fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   7544:        continue;
1.223     brouard  7545:       }
1.227     brouard  7546:       
1.241     brouard  7547:       fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" \n",subdirf2(optionfilefiname,"P_"),cpt,k1,nres);
1.264     brouard  7548:       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  7549:       fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Probability\" \n\
1.238     brouard  7550: set ter svg size 640, 480\nunset log y\nplot [%.f:%.f]  ", ageminpar, agemaxpar);
1.211     brouard  7551:       k=3; /* Offset */
1.255     brouard  7552:       for (i=1; i<= nlstate ; i ++){ /* State of origin */
1.227     brouard  7553:        if(i==1)
                   7554:          fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"PIJ_"));
                   7555:        else
                   7556:          fprintf(ficgp,", '' ");
1.255     brouard  7557:        l=(nlstate+ndeath)*(i-1)+1; /* 1, 1+ nlstate+ndeath, 1+2*(nlstate+ndeath) */
1.227     brouard  7558:        fprintf(ficgp," u ($1==%d ? ($3):1/0):($%d/($%d",k1,k+l+(cpt-1),k+l);
                   7559:        for (j=2; j<= nlstate ; j ++)
                   7560:          fprintf(ficgp,"+$%d",k+l+j-1);
                   7561:        fprintf(ficgp,")) t \"prev(%d,%d)\" w l",i,cpt);
1.153     brouard  7562:       } /* nlstate */
1.264     brouard  7563:       fprintf(ficgp,"\nset out; unset label;\n");
1.153     brouard  7564:     } /* end cpt state*/ 
                   7565:   } /* end covariate */  
1.227     brouard  7566:   
                   7567:   
1.220     brouard  7568: /* 7eme */
1.218     brouard  7569:   if(backcast == 1){
1.288     brouard  7570:     /* CV backward prevalence  for each covariate */
1.237     brouard  7571:     for (k1=1; k1<= m ; k1 ++) /* For each covariate combination if any */
                   7572:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.253     brouard  7573:       if(m != 1 && TKresult[nres]!= k1)
1.237     brouard  7574:        continue;
1.268     brouard  7575:       for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each life origin state */
1.264     brouard  7576:        strcpy(gplotlabel,"(");      
1.288     brouard  7577:        fprintf(ficgp,"\n#\n#\n#CV Backward stable prevalence: 'pijb' files, covariatecombination#=%d state=%d",k1, cpt);
1.227     brouard  7578:        for (k=1; k<=cptcoveff; k++){    /* For each covariate and each value */
                   7579:          lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate number corresponding to k1 combination */
                   7580:          /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   7581:          /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
1.223     brouard  7582:          /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
1.227     brouard  7583:          vlv= nbcode[Tvaraff[k]][lv];
                   7584:          fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv);
1.264     brouard  7585:          sprintf(gplotlabel+strlen(gplotlabel)," V%d=%d ",Tvaraff[k],vlv);
1.227     brouard  7586:        }
1.237     brouard  7587:        for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
                   7588:          fprintf(ficgp," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
1.264     brouard  7589:          sprintf(gplotlabel+strlen(gplotlabel)," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
1.237     brouard  7590:        }       
1.264     brouard  7591:        strcpy(gplotlabel+strlen(gplotlabel),")");
1.227     brouard  7592:        fprintf(ficgp,"\n#\n");
                   7593:        if(invalidvarcomb[k1]){
                   7594:          fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   7595:          continue;
                   7596:        }
                   7597:        
1.241     brouard  7598:        fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" \n",subdirf2(optionfilefiname,"PB_"),cpt,k1,nres);
1.268     brouard  7599:        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  7600:        fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Probability\" \n\
1.238     brouard  7601: set ter svg size 640, 480\nunset log y\nplot [%.f:%.f]  ", ageminpar, agemaxpar);
1.227     brouard  7602:        k=3; /* Offset */
1.268     brouard  7603:        for (i=1; i<= nlstate ; i ++){ /* State of arrival */
1.227     brouard  7604:          if(i==1)
                   7605:            fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"PIJB_"));
                   7606:          else
                   7607:            fprintf(ficgp,", '' ");
                   7608:          /* l=(nlstate+ndeath)*(i-1)+1; */
1.255     brouard  7609:          l=(nlstate+ndeath)*(cpt-1)+1; /* fixed for i; cpt=1 1, cpt=2 1+ nlstate+ndeath, 1+2*(nlstate+ndeath) */
1.227     brouard  7610:          /* fprintf(ficgp," u ($1==%d ? ($3):1/0):($%d/($%d",k1,k+l+(cpt-1),k+l); /\* a vérifier *\/ */
                   7611:          /* 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  7612:          fprintf(ficgp," u ($1==%d ? ($3):1/0):($%d",k1,k+l+i-1); /* To be verified */
1.227     brouard  7613:          /* for (j=2; j<= nlstate ; j ++) */
                   7614:          /*    fprintf(ficgp,"+$%d",k+l+j-1); */
                   7615:          /*    /\* fprintf(ficgp,"+$%d",k+l+j-1); *\/ */
1.268     brouard  7616:          fprintf(ficgp,") t \"bprev(%d,%d)\" w l",cpt,i);
1.227     brouard  7617:        } /* nlstate */
1.264     brouard  7618:        fprintf(ficgp,"\nset out; unset label;\n");
1.218     brouard  7619:       } /* end cpt state*/ 
                   7620:     } /* end covariate */  
                   7621:   } /* End if backcast */
                   7622:   
1.223     brouard  7623:   /* 8eme */
1.218     brouard  7624:   if(prevfcast==1){
1.288     brouard  7625:     /* Projection from cross-sectional to forward stable (period) prevalence for each covariate */
1.218     brouard  7626:     
1.237     brouard  7627:     for (k1=1; k1<= m ; k1 ++) /* For each covariate combination if any */
                   7628:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.253     brouard  7629:       if(m != 1 && TKresult[nres]!= k1)
1.237     brouard  7630:        continue;
1.211     brouard  7631:       for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each life state */
1.264     brouard  7632:        strcpy(gplotlabel,"(");      
1.288     brouard  7633:        fprintf(ficgp,"\n#\n#\n#Projection of prevalence to forward stable prevalence (period): 'PROJ_' files, covariatecombination#=%d state=%d",k1, cpt);
1.227     brouard  7634:        for (k=1; k<=cptcoveff; k++){    /* For each correspondig covariate value  */
                   7635:          lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate value corresponding to k1 combination and kth covariate */
                   7636:          /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   7637:          /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   7638:          /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
                   7639:          vlv= nbcode[Tvaraff[k]][lv];
                   7640:          fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv);
1.264     brouard  7641:          sprintf(gplotlabel+strlen(gplotlabel)," V%d=%d ",Tvaraff[k],vlv);
1.227     brouard  7642:        }
1.237     brouard  7643:        for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
                   7644:          fprintf(ficgp," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
1.264     brouard  7645:          sprintf(gplotlabel+strlen(gplotlabel)," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
1.237     brouard  7646:        }       
1.264     brouard  7647:        strcpy(gplotlabel+strlen(gplotlabel),")");
1.227     brouard  7648:        fprintf(ficgp,"\n#\n");
                   7649:        if(invalidvarcomb[k1]){
                   7650:          fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   7651:          continue;
                   7652:        }
                   7653:        
                   7654:        fprintf(ficgp,"# hpijx=probability over h years, hp.jx is weighted by observed prev\n ");
1.241     brouard  7655:        fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" \n",subdirf2(optionfilefiname,"PROJ_"),cpt,k1,nres);
1.264     brouard  7656:        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  7657:        fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Prevalence\" \n\
1.238     brouard  7658: set ter svg size 640, 480\nunset log y\nplot [%.f:%.f]  ", ageminpar, agemaxpar);
1.266     brouard  7659: 
                   7660:        /* for (i=1; i<= nlstate+1 ; i ++){  /\* nlstate +1 p11 p21 p.1 *\/ */
                   7661:        istart=nlstate+1; /* Could be one if by state, but nlstate+1 is w.i projection only */
                   7662:        /*istart=1;*/ /* Could be one if by state, but nlstate+1 is w.i projection only */
                   7663:        for (i=istart; i<= nlstate+1 ; i ++){  /* nlstate +1 p11 p21 p.1 */
1.227     brouard  7664:          /*#  V1  = 1  V2 =  0 yearproj age p11 p21 p.1 p12 p22 p.2 p13 p23 p.3*/
                   7665:          /*#   1    2   3    4    5      6  7   8   9   10   11 12  13   14  15 */   
                   7666:          /*# yearproj age p11 p21 p.1 p12 p22 p.2 p13 p23 p.3*/
                   7667:          /*#   1       2   3    4    5      6  7   8   9   10   11 12  13   14  15 */   
1.266     brouard  7668:          if(i==istart){
1.227     brouard  7669:            fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"F_"));
                   7670:          }else{
                   7671:            fprintf(ficgp,",\\\n '' ");
                   7672:          }
                   7673:          if(cptcoveff ==0){ /* No covariate */
                   7674:            ioffset=2; /* Age is in 2 */
                   7675:            /*# yearproj age p11 p21 p31 p.1 p12 p22 p32 p.2 p13 p23 p33 p.3 p14 p24 p34 p.4*/
                   7676:            /*#   1       2   3   4   5  6    7  8   9   10  11  12  13  14  15  16  17  18 */
                   7677:            /*# V1  = 1 yearproj age p11 p21 p31 p.1 p12 p22 p32 p.2 p13 p23 p33 p.3 p14 p24 p34 p.4*/
                   7678:            /*#  1    2        3   4   5  6    7  8   9   10  11  12  13  14  15  16  17  18 */
                   7679:            fprintf(ficgp," u %d:(", ioffset); 
1.266     brouard  7680:            if(i==nlstate+1){
1.270     brouard  7681:              fprintf(ficgp," $%d/(1.-$%d)):1 t 'pw.%d' with line lc variable ",        \
1.266     brouard  7682:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1),  ioffset+1+(i-1)+(nlstate+1)*nlstate,cpt );
                   7683:              fprintf(ficgp,",\\\n '' ");
                   7684:              fprintf(ficgp," u %d:(",ioffset); 
1.270     brouard  7685:              fprintf(ficgp," (($1-$2) == %d ) ? $%d/(1.-$%d) : 1/0):1 with labels center not ", \
1.266     brouard  7686:                     offyear,                           \
1.268     brouard  7687:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1),  ioffset+1+(i-1)+(nlstate+1)*nlstate );
1.266     brouard  7688:            }else
1.227     brouard  7689:              fprintf(ficgp," $%d/(1.-$%d)) t 'p%d%d' with line ",      \
                   7690:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1),  ioffset+1+(i-1)+(nlstate+1)*nlstate,i,cpt );
                   7691:          }else{ /* more than 2 covariates */
1.270     brouard  7692:            ioffset=2*cptcoveff+2; /* Age is in 4 or 6 or etc.*/
                   7693:            /*#  V1  = 1  V2 =  0 yearproj age p11 p21 p.1 p12 p22 p.2 p13 p23 p.3*/
                   7694:            /*#   1    2   3    4    5      6  7   8   9   10   11 12  13   14  15 */
                   7695:            iyearc=ioffset-1;
                   7696:            iagec=ioffset;
1.227     brouard  7697:            fprintf(ficgp," u %d:(",ioffset); 
                   7698:            kl=0;
                   7699:            strcpy(gplotcondition,"(");
                   7700:            for (k=1; k<=cptcoveff; k++){    /* For each covariate writing the chain of conditions */
                   7701:              lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate value corresponding to combination k1 and covariate k */
                   7702:              /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   7703:              /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   7704:              /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
                   7705:              vlv= nbcode[Tvaraff[k]][lv]; /* Value of the modality of Tvaraff[k] */
                   7706:              kl++;
                   7707:              sprintf(gplotcondition+strlen(gplotcondition),"$%d==%d && $%d==%d " ,kl,Tvaraff[k], kl+1, nbcode[Tvaraff[k]][lv]);
                   7708:              kl++;
                   7709:              if(k <cptcoveff && cptcoveff>1)
                   7710:                sprintf(gplotcondition+strlen(gplotcondition)," && ");
                   7711:            }
                   7712:            strcpy(gplotcondition+strlen(gplotcondition),")");
                   7713:            /* 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 *\/ */
                   7714:            /*6+(cpt-1)*(nlstate+1)+1+(i-1)+(nlstate+1)*nlstate; 6+(1-1)*(2+1)+1+(1-1) +(2+1)*2=13 */ 
                   7715:            /*6+1+(i-1)+(nlstate+1)*nlstate; 6+1+(1-1) +(2+1)*2=13 */ 
                   7716:            /* ''  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*/
                   7717:            if(i==nlstate+1){
1.270     brouard  7718:              fprintf(ficgp,"%s ? $%d/(1.-$%d) : 1/0):%d t 'p.%d' with line lc variable", gplotcondition, \
                   7719:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1),  ioffset+1+(i-1)+(nlstate+1)*nlstate,iyearc, cpt );
1.266     brouard  7720:              fprintf(ficgp,",\\\n '' ");
1.270     brouard  7721:              fprintf(ficgp," u %d:(",iagec); 
                   7722:              fprintf(ficgp,"%s && (($%d-$%d) == %d ) ? $%d/(1.-$%d) : 1/0):%d with labels center not ", gplotcondition, \
                   7723:                      iyearc, iagec, offyear,                           \
                   7724:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1),  ioffset+1+(i-1)+(nlstate+1)*nlstate, iyearc );
1.266     brouard  7725: /*  '' 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  7726:            }else{
                   7727:              fprintf(ficgp,"%s ? $%d/(1.-$%d) : 1/0) t 'p%d%d' with line ", gplotcondition, \
                   7728:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1), ioffset +1+(i-1)+(nlstate+1)*nlstate,i,cpt );
                   7729:            }
                   7730:          } /* end if covariate */
                   7731:        } /* nlstate */
1.264     brouard  7732:        fprintf(ficgp,"\nset out; unset label;\n");
1.223     brouard  7733:       } /* end cpt state*/
                   7734:     } /* end covariate */
                   7735:   } /* End if prevfcast */
1.227     brouard  7736:   
1.268     brouard  7737:   if(backcast==1){
                   7738:     /* Back projection from cross-sectional to stable (mixed) for each covariate */
                   7739:     
                   7740:     for (k1=1; k1<= m ; k1 ++) /* For each covariate combination if any */
                   7741:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
                   7742:       if(m != 1 && TKresult[nres]!= k1)
                   7743:        continue;
                   7744:       for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each life state */
                   7745:        strcpy(gplotlabel,"(");      
                   7746:        fprintf(ficgp,"\n#\n#\n#Back projection of prevalence to stable (mixed) back prevalence: 'BPROJ_' files, covariatecombination#=%d originstate=%d",k1, cpt);
                   7747:        for (k=1; k<=cptcoveff; k++){    /* For each correspondig covariate value  */
                   7748:          lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate value corresponding to k1 combination and kth covariate */
                   7749:          /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   7750:          /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   7751:          /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
                   7752:          vlv= nbcode[Tvaraff[k]][lv];
                   7753:          fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv);
                   7754:          sprintf(gplotlabel+strlen(gplotlabel)," V%d=%d ",Tvaraff[k],vlv);
                   7755:        }
                   7756:        for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
                   7757:          fprintf(ficgp," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
                   7758:          sprintf(gplotlabel+strlen(gplotlabel)," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
                   7759:        }       
                   7760:        strcpy(gplotlabel+strlen(gplotlabel),")");
                   7761:        fprintf(ficgp,"\n#\n");
                   7762:        if(invalidvarcomb[k1]){
                   7763:          fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   7764:          continue;
                   7765:        }
                   7766:        
                   7767:        fprintf(ficgp,"# hbijx=backprobability over h years, hb.jx is weighted by observed prev at destination state\n ");
                   7768:        fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" \n",subdirf2(optionfilefiname,"PROJB_"),cpt,k1,nres);
                   7769:        fprintf(ficgp,"set label \"Origin alive state %d %s\" at graph 0.98,0.5 center rotate font \"Helvetica,12\"\n",cpt,gplotlabel);
                   7770:        fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Prevalence\" \n\
                   7771: set ter svg size 640, 480\nunset log y\nplot [%.f:%.f]  ", ageminpar, agemaxpar);
                   7772: 
                   7773:        /* for (i=1; i<= nlstate+1 ; i ++){  /\* nlstate +1 p11 p21 p.1 *\/ */
                   7774:        istart=nlstate+1; /* Could be one if by state, but nlstate+1 is w.i projection only */
                   7775:        /*istart=1;*/ /* Could be one if by state, but nlstate+1 is w.i projection only */
                   7776:        for (i=istart; i<= nlstate+1 ; i ++){  /* nlstate +1 p11 p21 p.1 */
                   7777:          /*#  V1  = 1  V2 =  0 yearproj age p11 p21 p.1 p12 p22 p.2 p13 p23 p.3*/
                   7778:          /*#   1    2   3    4    5      6  7   8   9   10   11 12  13   14  15 */   
                   7779:          /*# yearproj age p11 p21 p.1 p12 p22 p.2 p13 p23 p.3*/
                   7780:          /*#   1       2   3    4    5      6  7   8   9   10   11 12  13   14  15 */   
                   7781:          if(i==istart){
                   7782:            fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"FB_"));
                   7783:          }else{
                   7784:            fprintf(ficgp,",\\\n '' ");
                   7785:          }
                   7786:          if(cptcoveff ==0){ /* No covariate */
                   7787:            ioffset=2; /* Age is in 2 */
                   7788:            /*# yearproj age p11 p21 p31 p.1 p12 p22 p32 p.2 p13 p23 p33 p.3 p14 p24 p34 p.4*/
                   7789:            /*#   1       2   3   4   5  6    7  8   9   10  11  12  13  14  15  16  17  18 */
                   7790:            /*# V1  = 1 yearproj age p11 p21 p31 p.1 p12 p22 p32 p.2 p13 p23 p33 p.3 p14 p24 p34 p.4*/
                   7791:            /*#  1    2        3   4   5  6    7  8   9   10  11  12  13  14  15  16  17  18 */
                   7792:            fprintf(ficgp," u %d:(", ioffset); 
                   7793:            if(i==nlstate+1){
1.270     brouard  7794:              fprintf(ficgp," $%d/(1.-$%d)):1 t 'bw%d' with line lc variable ", \
1.268     brouard  7795:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1),  ioffset+1+(i-1)+(nlstate+1)*nlstate,cpt );
                   7796:              fprintf(ficgp,",\\\n '' ");
                   7797:              fprintf(ficgp," u %d:(",ioffset); 
1.270     brouard  7798:              fprintf(ficgp," (($1-$2) == %d ) ? $%d : 1/0):1 with labels center not ", \
1.268     brouard  7799:                     offbyear,                          \
                   7800:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1) );
                   7801:            }else
                   7802:              fprintf(ficgp," $%d/(1.-$%d)) t 'b%d%d' with line ",      \
                   7803:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1),  ioffset+1+(i-1)+(nlstate+1)*nlstate,cpt,i );
                   7804:          }else{ /* more than 2 covariates */
1.270     brouard  7805:            ioffset=2*cptcoveff+2; /* Age is in 4 or 6 or etc.*/
                   7806:            /*#  V1  = 1  V2 =  0 yearproj age p11 p21 p.1 p12 p22 p.2 p13 p23 p.3*/
                   7807:            /*#   1    2   3    4    5      6  7   8   9   10   11 12  13   14  15 */
                   7808:            iyearc=ioffset-1;
                   7809:            iagec=ioffset;
1.268     brouard  7810:            fprintf(ficgp," u %d:(",ioffset); 
                   7811:            kl=0;
                   7812:            strcpy(gplotcondition,"(");
                   7813:            for (k=1; k<=cptcoveff; k++){    /* For each covariate writing the chain of conditions */
                   7814:              lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate value corresponding to combination k1 and covariate k */
                   7815:              /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   7816:              /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   7817:              /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
                   7818:              vlv= nbcode[Tvaraff[k]][lv]; /* Value of the modality of Tvaraff[k] */
                   7819:              kl++;
                   7820:              sprintf(gplotcondition+strlen(gplotcondition),"$%d==%d && $%d==%d " ,kl,Tvaraff[k], kl+1, nbcode[Tvaraff[k]][lv]);
                   7821:              kl++;
                   7822:              if(k <cptcoveff && cptcoveff>1)
                   7823:                sprintf(gplotcondition+strlen(gplotcondition)," && ");
                   7824:            }
                   7825:            strcpy(gplotcondition+strlen(gplotcondition),")");
                   7826:            /* 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 *\/ */
                   7827:            /*6+(cpt-1)*(nlstate+1)+1+(i-1)+(nlstate+1)*nlstate; 6+(1-1)*(2+1)+1+(1-1) +(2+1)*2=13 */ 
                   7828:            /*6+1+(i-1)+(nlstate+1)*nlstate; 6+1+(1-1) +(2+1)*2=13 */ 
                   7829:            /* ''  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*/
                   7830:            if(i==nlstate+1){
1.270     brouard  7831:              fprintf(ficgp,"%s ? $%d : 1/0):%d t 'bw%d' with line lc variable", gplotcondition, \
                   7832:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1),iyearc,cpt );
1.268     brouard  7833:              fprintf(ficgp,",\\\n '' ");
1.270     brouard  7834:              fprintf(ficgp," u %d:(",iagec); 
1.268     brouard  7835:              /* fprintf(ficgp,"%s && (($5-$6) == %d ) ? $%d/(1.-$%d) : 1/0):5 with labels center not ", gplotcondition, \ */
1.270     brouard  7836:              fprintf(ficgp,"%s && (($%d-$%d) == %d ) ? $%d : 1/0):%d with labels center not ", gplotcondition, \
                   7837:                      iyearc,iagec,offbyear,                            \
                   7838:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1), iyearc );
1.268     brouard  7839: /*  '' u 6:(($1==1 && $2==0  && $3==2 && $4==0) && (($5-$6) == 1947) ? $10/(1.-$22) : 1/0):5 with labels center boxed not*/
                   7840:            }else{
                   7841:              /* fprintf(ficgp,"%s ? $%d/(1.-$%d) : 1/0) t 'p%d%d' with line ", gplotcondition, \ */
                   7842:              fprintf(ficgp,"%s ? $%d : 1/0) t 'b%d%d' with line ", gplotcondition, \
                   7843:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1), cpt,i );
                   7844:            }
                   7845:          } /* end if covariate */
                   7846:        } /* nlstate */
                   7847:        fprintf(ficgp,"\nset out; unset label;\n");
                   7848:       } /* end cpt state*/
                   7849:     } /* end covariate */
                   7850:   } /* End if backcast */
                   7851:   
1.227     brouard  7852:   
1.238     brouard  7853:   /* 9eme writing MLE parameters */
                   7854:   fprintf(ficgp,"\n##############\n#9eme MLE estimated parameters\n#############\n");
1.126     brouard  7855:   for(i=1,jk=1; i <=nlstate; i++){
1.187     brouard  7856:     fprintf(ficgp,"# initial state %d\n",i);
1.126     brouard  7857:     for(k=1; k <=(nlstate+ndeath); k++){
                   7858:       if (k != i) {
1.227     brouard  7859:        fprintf(ficgp,"#   current state %d\n",k);
                   7860:        for(j=1; j <=ncovmodel; j++){
                   7861:          fprintf(ficgp,"p%d=%f; ",jk,p[jk]);
                   7862:          jk++; 
                   7863:        }
                   7864:        fprintf(ficgp,"\n");
1.126     brouard  7865:       }
                   7866:     }
1.223     brouard  7867:   }
1.187     brouard  7868:   fprintf(ficgp,"##############\n#\n");
1.227     brouard  7869:   
1.145     brouard  7870:   /*goto avoid;*/
1.238     brouard  7871:   /* 10eme Graphics of probabilities or incidences using written MLE parameters */
                   7872:   fprintf(ficgp,"\n##############\n#10eme Graphics of probabilities or incidences\n#############\n");
1.187     brouard  7873:   fprintf(ficgp,"# logi(p12/p11)=a12+b12*age+c12age*age+d12*V1+e12*V1*age\n");
                   7874:   fprintf(ficgp,"# logi(p12/p11)=p1 +p2*age +p3*age*age+ p4*V1+ p5*V1*age\n");
                   7875:   fprintf(ficgp,"# logi(p13/p11)=a13+b13*age+c13age*age+d13*V1+e13*V1*age\n");
                   7876:   fprintf(ficgp,"# logi(p13/p11)=p6 +p7*age +p8*age*age+ p9*V1+ p10*V1*age\n");
                   7877:   fprintf(ficgp,"# p12+p13+p14+p11=1=p11(1+exp(a12+b12*age+c12age*age+d12*V1+e12*V1*age)\n");
                   7878:   fprintf(ficgp,"#                      +exp(a13+b13*age+c13age*age+d13*V1+e13*V1*age)+...)\n");
                   7879:   fprintf(ficgp,"# p11=1/(1+exp(a12+b12*age+c12age*age+d12*V1+e12*V1*age)\n");
                   7880:   fprintf(ficgp,"#                      +exp(a13+b13*age+c13age*age+d13*V1+e13*V1*age)+...)\n");
                   7881:   fprintf(ficgp,"# p12=exp(a12+b12*age+c12age*age+d12*V1+e12*V1*age)/\n");
                   7882:   fprintf(ficgp,"#     (1+exp(a12+b12*age+c12age*age+d12*V1+e12*V1*age)\n");
                   7883:   fprintf(ficgp,"#       +exp(a13+b13*age+c13age*age+d13*V1+e13*V1*age))\n");
                   7884:   fprintf(ficgp,"#       +exp(a14+b14*age+c14age*age+d14*V1+e14*V1*age)+...)\n");
                   7885:   fprintf(ficgp,"#\n");
1.223     brouard  7886:   for(ng=1; ng<=3;ng++){ /* Number of graphics: first is logit, 2nd is probabilities, third is incidences per year*/
1.238     brouard  7887:     fprintf(ficgp,"#Number of graphics: first is logit, 2nd is probabilities, third is incidences per year\n");
1.237     brouard  7888:     fprintf(ficgp,"#model=%s \n",model);
1.238     brouard  7889:     fprintf(ficgp,"# Type of graphic ng=%d\n",ng);
1.264     brouard  7890:     fprintf(ficgp,"#   k1=1 to 2^%d=%d\n",cptcoveff,m);/* to be checked */
                   7891:     for(k1=1; k1 <=m; k1++)  /* For each combination of covariate */
1.237     brouard  7892:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.264     brouard  7893:       if(m != 1 && TKresult[nres]!= k1)
1.237     brouard  7894:        continue;
1.264     brouard  7895:       fprintf(ficgp,"\n\n# Combination of dummy  k1=%d which is ",k1);
                   7896:       strcpy(gplotlabel,"(");
1.276     brouard  7897:       /*sprintf(gplotlabel+strlen(gplotlabel)," Dummy combination %d ",k1);*/
1.264     brouard  7898:       for (k=1; k<=cptcoveff; k++){    /* For each correspondig covariate value  */
                   7899:        lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate value corresponding to k1 combination and kth covariate */
                   7900:        /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   7901:        /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   7902:        /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
                   7903:        vlv= nbcode[Tvaraff[k]][lv];
                   7904:        fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv);
                   7905:        sprintf(gplotlabel+strlen(gplotlabel)," V%d=%d ",Tvaraff[k],vlv);
                   7906:       }
1.237     brouard  7907:       for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
                   7908:        fprintf(ficgp," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
1.264     brouard  7909:        sprintf(gplotlabel+strlen(gplotlabel)," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
1.237     brouard  7910:       }        
1.264     brouard  7911:       strcpy(gplotlabel+strlen(gplotlabel),")");
1.237     brouard  7912:       fprintf(ficgp,"\n#\n");
1.264     brouard  7913:       fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" ",subdirf2(optionfilefiname,"PE_"),k1,ng,nres);
1.276     brouard  7914:       fprintf(ficgp,"\nset key outside ");
                   7915:       /* fprintf(ficgp,"\nset label \"%s\" at graph 1.2,0.5 center rotate font \"Helvetica,12\"\n",gplotlabel); */
                   7916:       fprintf(ficgp,"\nset title \"%s\" font \"Helvetica,12\"\n",gplotlabel);
1.223     brouard  7917:       fprintf(ficgp,"\nset ter svg size 640, 480 ");
                   7918:       if (ng==1){
                   7919:        fprintf(ficgp,"\nset ylabel \"Value of the logit of the model\"\n"); /* exp(a12+b12*x) could be nice */
                   7920:        fprintf(ficgp,"\nunset log y");
                   7921:       }else if (ng==2){
                   7922:        fprintf(ficgp,"\nset ylabel \"Probability\"\n");
                   7923:        fprintf(ficgp,"\nset log y");
                   7924:       }else if (ng==3){
                   7925:        fprintf(ficgp,"\nset ylabel \"Quasi-incidence per year\"\n");
                   7926:        fprintf(ficgp,"\nset log y");
                   7927:       }else
                   7928:        fprintf(ficgp,"\nunset title ");
                   7929:       fprintf(ficgp,"\nplot  [%.f:%.f] ",ageminpar,agemaxpar);
                   7930:       i=1;
                   7931:       for(k2=1; k2<=nlstate; k2++) {
                   7932:        k3=i;
                   7933:        for(k=1; k<=(nlstate+ndeath); k++) {
                   7934:          if (k != k2){
                   7935:            switch( ng) {
                   7936:            case 1:
                   7937:              if(nagesqr==0)
                   7938:                fprintf(ficgp," p%d+p%d*x",i,i+1);
                   7939:              else /* nagesqr =1 */
                   7940:                fprintf(ficgp," p%d+p%d*x+p%d*x*x",i,i+1,i+1+nagesqr);
                   7941:              break;
                   7942:            case 2: /* ng=2 */
                   7943:              if(nagesqr==0)
                   7944:                fprintf(ficgp," exp(p%d+p%d*x",i,i+1);
                   7945:              else /* nagesqr =1 */
                   7946:                fprintf(ficgp," exp(p%d+p%d*x+p%d*x*x",i,i+1,i+1+nagesqr);
                   7947:              break;
                   7948:            case 3:
                   7949:              if(nagesqr==0)
                   7950:                fprintf(ficgp," %f*exp(p%d+p%d*x",YEARM/stepm,i,i+1);
                   7951:              else /* nagesqr =1 */
                   7952:                fprintf(ficgp," %f*exp(p%d+p%d*x+p%d*x*x",YEARM/stepm,i,i+1,i+1+nagesqr);
                   7953:              break;
                   7954:            }
                   7955:            ij=1;/* To be checked else nbcode[0][0] wrong */
1.237     brouard  7956:            ijp=1; /* product no age */
                   7957:            /* for(j=3; j <=ncovmodel-nagesqr; j++) { */
                   7958:            for(j=1; j <=cptcovt; j++) { /* For each covariate of the simplified model */
1.223     brouard  7959:              /* printf("Tage[%d]=%d, j=%d\n", ij, Tage[ij], j); */
1.268     brouard  7960:              if(cptcovage >0){ /* V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1, 2 V5 and V1 */
                   7961:                if(j==Tage[ij]) { /* Product by age  To be looked at!!*/
                   7962:                  if(ij <=cptcovage) { /* V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1, 2 V5 and V1 */
                   7963:                    if(DummyV[j]==0){
                   7964:                      fprintf(ficgp,"+p%d*%d*x",i+j+2+nagesqr-1,Tinvresult[nres][Tvar[j]]);;
                   7965:                    }else{ /* quantitative */
                   7966:                      fprintf(ficgp,"+p%d*%f*x",i+j+2+nagesqr-1,Tqinvresult[nres][Tvar[j]]); /* Tqinvresult in decoderesult */
                   7967:                      /* fprintf(ficgp,"+p%d*%d*x",i+j+nagesqr-1,nbcode[Tvar[j-2]][codtabm(k1,Tvar[j-2])]); */
                   7968:                    }
                   7969:                    ij++;
1.237     brouard  7970:                  }
1.268     brouard  7971:                } 
                   7972:              }else if(cptcovprod >0){
                   7973:                if(j==Tprod[ijp]) { /* */ 
                   7974:                  /* printf("Tprod[%d]=%d, j=%d\n", ij, Tprod[ijp], j); */
                   7975:                  if(ijp <=cptcovprod) { /* Product */
                   7976:                    if(DummyV[Tvard[ijp][1]]==0){/* Vn is dummy */
                   7977:                      if(DummyV[Tvard[ijp][2]]==0){/* Vn and Vm are dummy */
                   7978:                        /* 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)]); */
                   7979:                        fprintf(ficgp,"+p%d*%d*%d",i+j+2+nagesqr-1,Tinvresult[nres][Tvard[ijp][1]],Tinvresult[nres][Tvard[ijp][2]]);
                   7980:                      }else{ /* Vn is dummy and Vm is quanti */
                   7981:                        /* fprintf(ficgp,"+p%d*%d*%f",i+j+2+nagesqr-1,nbcode[Tvard[ijp][1]][codtabm(k1,j)],Tqinvresult[nres][Tvard[ijp][2]]); */
                   7982:                        fprintf(ficgp,"+p%d*%d*%f",i+j+2+nagesqr-1,Tinvresult[nres][Tvard[ijp][1]],Tqinvresult[nres][Tvard[ijp][2]]);
                   7983:                      }
                   7984:                    }else{ /* Vn*Vm Vn is quanti */
                   7985:                      if(DummyV[Tvard[ijp][2]]==0){
                   7986:                        fprintf(ficgp,"+p%d*%d*%f",i+j+2+nagesqr-1,Tinvresult[nres][Tvard[ijp][2]],Tqinvresult[nres][Tvard[ijp][1]]);
                   7987:                      }else{ /* Both quanti */
                   7988:                        fprintf(ficgp,"+p%d*%f*%f",i+j+2+nagesqr-1,Tqinvresult[nres][Tvard[ijp][1]],Tqinvresult[nres][Tvard[ijp][2]]);
                   7989:                      }
1.237     brouard  7990:                    }
1.268     brouard  7991:                    ijp++;
1.237     brouard  7992:                  }
1.268     brouard  7993:                } /* end Tprod */
1.237     brouard  7994:              } else{  /* simple covariate */
1.264     brouard  7995:                /* fprintf(ficgp,"+p%d*%d",i+j+2+nagesqr-1,nbcode[Tvar[j]][codtabm(k1,j)]); /\* Valgrind bug nbcode *\/ */
1.237     brouard  7996:                if(Dummy[j]==0){
                   7997:                  fprintf(ficgp,"+p%d*%d",i+j+2+nagesqr-1,Tinvresult[nres][Tvar[j]]); /*  */
                   7998:                }else{ /* quantitative */
                   7999:                  fprintf(ficgp,"+p%d*%f",i+j+2+nagesqr-1,Tqinvresult[nres][Tvar[j]]); /* */
1.264     brouard  8000:                  /* fprintf(ficgp,"+p%d*%d*x",i+j+nagesqr-1,nbcode[Tvar[j-2]][codtabm(k1,Tvar[j-2])]); */
1.223     brouard  8001:                }
1.237     brouard  8002:              } /* end simple */
                   8003:            } /* end j */
1.223     brouard  8004:          }else{
                   8005:            i=i-ncovmodel;
                   8006:            if(ng !=1 ) /* For logit formula of log p11 is more difficult to get */
                   8007:              fprintf(ficgp," (1.");
                   8008:          }
1.227     brouard  8009:          
1.223     brouard  8010:          if(ng != 1){
                   8011:            fprintf(ficgp,")/(1");
1.227     brouard  8012:            
1.264     brouard  8013:            for(cpt=1; cpt <=nlstate; cpt++){ 
1.223     brouard  8014:              if(nagesqr==0)
1.264     brouard  8015:                fprintf(ficgp,"+exp(p%d+p%d*x",k3+(cpt-1)*ncovmodel,k3+(cpt-1)*ncovmodel+1);
1.223     brouard  8016:              else /* nagesqr =1 */
1.264     brouard  8017:                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  8018:               
1.223     brouard  8019:              ij=1;
                   8020:              for(j=3; j <=ncovmodel-nagesqr; j++){
1.268     brouard  8021:                 if(cptcovage >0){ 
                   8022:                   if((j-2)==Tage[ij]) { /* Bug valgrind */
                   8023:                     if(ij <=cptcovage) { /* Bug valgrind */
                   8024:                       fprintf(ficgp,"+p%d*%d*x",k3+(cpt-1)*ncovmodel+1+j-2+nagesqr,nbcode[Tvar[j-2]][codtabm(k1,j-2)]);
                   8025:                       /* fprintf(ficgp,"+p%d*%d*x",k3+(cpt-1)*ncovmodel+1+j-2+nagesqr,nbcode[Tvar[j-2]][codtabm(k1,Tvar[j-2])]); */
                   8026:                       ij++;
                   8027:                     }
                   8028:                   }
                   8029:                 }else
                   8030:                   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  8031:              }
                   8032:              fprintf(ficgp,")");
                   8033:            }
                   8034:            fprintf(ficgp,")");
                   8035:            if(ng ==2)
1.276     brouard  8036:              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  8037:            else /* ng= 3 */
1.276     brouard  8038:              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  8039:          }else{ /* end ng <> 1 */
                   8040:            if( k !=k2) /* logit p11 is hard to draw */
1.276     brouard  8041:              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  8042:          }
                   8043:          if ((k+k2)!= (nlstate*2+ndeath) && ng != 1)
                   8044:            fprintf(ficgp,",");
                   8045:          if (ng == 1 && k!=k2 && (k+k2)!= (nlstate*2+ndeath))
                   8046:            fprintf(ficgp,",");
                   8047:          i=i+ncovmodel;
                   8048:        } /* end k */
                   8049:       } /* end k2 */
1.276     brouard  8050:       /* fprintf(ficgp,"\n set out; unset label;set key default;\n"); */
                   8051:       fprintf(ficgp,"\n set out; unset title;set key default;\n");
1.264     brouard  8052:     } /* end k1 */
1.223     brouard  8053:   } /* end ng */
                   8054:   /* avoid: */
                   8055:   fflush(ficgp); 
1.126     brouard  8056: }  /* end gnuplot */
                   8057: 
                   8058: 
                   8059: /*************** Moving average **************/
1.219     brouard  8060: /* int movingaverage(double ***probs, double bage, double fage, double ***mobaverage, int mobilav, double bageout, double fageout){ */
1.222     brouard  8061:  int movingaverage(double ***probs, double bage, double fage, double ***mobaverage, int mobilav){
1.218     brouard  8062:    
1.222     brouard  8063:    int i, cpt, cptcod;
                   8064:    int modcovmax =1;
                   8065:    int mobilavrange, mob;
                   8066:    int iage=0;
1.288     brouard  8067:    int firstA1=0, firstA2=0;
1.222     brouard  8068: 
1.266     brouard  8069:    double sum=0., sumr=0.;
1.222     brouard  8070:    double age;
1.266     brouard  8071:    double *sumnewp, *sumnewm, *sumnewmr;
                   8072:    double *agemingood, *agemaxgood; 
                   8073:    double *agemingoodr, *agemaxgoodr; 
1.222     brouard  8074:   
                   8075:   
1.278     brouard  8076:    /* modcovmax=2*cptcoveff;  Max number of modalities. We suppose  */
                   8077:    /*             a covariate has 2 modalities, should be equal to ncovcombmax   */
1.222     brouard  8078: 
                   8079:    sumnewp = vector(1,ncovcombmax);
                   8080:    sumnewm = vector(1,ncovcombmax);
1.266     brouard  8081:    sumnewmr = vector(1,ncovcombmax);
1.222     brouard  8082:    agemingood = vector(1,ncovcombmax); 
1.266     brouard  8083:    agemingoodr = vector(1,ncovcombmax);        
1.222     brouard  8084:    agemaxgood = vector(1,ncovcombmax);
1.266     brouard  8085:    agemaxgoodr = vector(1,ncovcombmax);
1.222     brouard  8086: 
                   8087:    for (cptcod=1;cptcod<=ncovcombmax;cptcod++){
1.266     brouard  8088:      sumnewm[cptcod]=0.; sumnewmr[cptcod]=0.;
1.222     brouard  8089:      sumnewp[cptcod]=0.;
1.266     brouard  8090:      agemingood[cptcod]=0, agemingoodr[cptcod]=0;
                   8091:      agemaxgood[cptcod]=0, agemaxgoodr[cptcod]=0;
1.222     brouard  8092:    }
                   8093:    if (cptcovn<1) ncovcombmax=1; /* At least 1 pass */
                   8094:   
1.266     brouard  8095:    if(mobilav==-1 || mobilav==1||mobilav ==3 ||mobilav==5 ||mobilav== 7){
                   8096:      if(mobilav==1 || mobilav==-1) mobilavrange=5; /* default */
1.222     brouard  8097:      else mobilavrange=mobilav;
                   8098:      for (age=bage; age<=fage; age++)
                   8099:        for (i=1; i<=nlstate;i++)
                   8100:         for (cptcod=1;cptcod<=ncovcombmax;cptcod++)
                   8101:           mobaverage[(int)age][i][cptcod]=probs[(int)age][i][cptcod];
                   8102:      /* We keep the original values on the extreme ages bage, fage and for 
                   8103:        fage+1 and bage-1 we use a 3 terms moving average; for fage+2 bage+2
                   8104:        we use a 5 terms etc. until the borders are no more concerned. 
                   8105:      */ 
                   8106:      for (mob=3;mob <=mobilavrange;mob=mob+2){
                   8107:        for (age=bage+(mob-1)/2; age<=fage-(mob-1)/2; age++){
1.266     brouard  8108:         for (cptcod=1;cptcod<=ncovcombmax;cptcod++){
                   8109:           sumnewm[cptcod]=0.;
                   8110:           for (i=1; i<=nlstate;i++){
1.222     brouard  8111:             mobaverage[(int)age][i][cptcod] =probs[(int)age][i][cptcod];
                   8112:             for (cpt=1;cpt<=(mob-1)/2;cpt++){
                   8113:               mobaverage[(int)age][i][cptcod] +=probs[(int)age-cpt][i][cptcod];
                   8114:               mobaverage[(int)age][i][cptcod] +=probs[(int)age+cpt][i][cptcod];
                   8115:             }
                   8116:             mobaverage[(int)age][i][cptcod]=mobaverage[(int)age][i][cptcod]/mob;
1.266     brouard  8117:             sumnewm[cptcod]+=mobaverage[(int)age][i][cptcod];
                   8118:           } /* end i */
                   8119:           if(sumnewm[cptcod] >1.e-3) mobaverage[(int)age][i][cptcod]=mobaverage[(int)age][i][cptcod]/sumnewm[cptcod]; /* Rescaling to sum one */
                   8120:         } /* end cptcod */
1.222     brouard  8121:        }/* end age */
                   8122:      }/* end mob */
1.266     brouard  8123:    }else{
                   8124:      printf("Error internal in movingaverage, mobilav=%d.\n",mobilav);
1.222     brouard  8125:      return -1;
1.266     brouard  8126:    }
                   8127: 
                   8128:    for (cptcod=1;cptcod<=ncovcombmax;cptcod++){ /* for each combination */
1.222     brouard  8129:      /* for (age=bage+(mob-1)/2; age<=fage-(mob-1)/2; age++){ */
                   8130:      if(invalidvarcomb[cptcod]){
                   8131:        printf("\nCombination (%d) ignored because no cases \n",cptcod); 
                   8132:        continue;
                   8133:      }
1.219     brouard  8134: 
1.266     brouard  8135:      for (age=fage-(mob-1)/2; age>=bage+(mob-1)/2; age--){ /*looking for the youngest and oldest good age */
                   8136:        sumnewm[cptcod]=0.;
                   8137:        sumnewmr[cptcod]=0.;
                   8138:        for (i=1; i<=nlstate;i++){
                   8139:         sumnewm[cptcod]+=mobaverage[(int)age][i][cptcod];
                   8140:         sumnewmr[cptcod]+=probs[(int)age][i][cptcod];
                   8141:        }
                   8142:        if(fabs(sumnewmr[cptcod] - 1.) <= 1.e-3) { /* good without smoothing */
                   8143:         agemingoodr[cptcod]=age;
                   8144:        }
                   8145:        if(fabs(sumnewm[cptcod] - 1.) <= 1.e-3) { /* good */
                   8146:           agemingood[cptcod]=age;
                   8147:        }
                   8148:      } /* age */
                   8149:      for (age=bage+(mob-1)/2; age<=fage-(mob-1)/2; age++){ /*looking for the youngest and oldest good age */
1.222     brouard  8150:        sumnewm[cptcod]=0.;
1.266     brouard  8151:        sumnewmr[cptcod]=0.;
1.222     brouard  8152:        for (i=1; i<=nlstate;i++){
                   8153:         sumnewm[cptcod]+=mobaverage[(int)age][i][cptcod];
1.266     brouard  8154:         sumnewmr[cptcod]+=probs[(int)age][i][cptcod];
                   8155:        }
                   8156:        if(fabs(sumnewmr[cptcod] - 1.) <= 1.e-3) { /* good without smoothing */
                   8157:         agemaxgoodr[cptcod]=age;
1.222     brouard  8158:        }
                   8159:        if(fabs(sumnewm[cptcod] - 1.) <= 1.e-3) { /* good */
1.266     brouard  8160:         agemaxgood[cptcod]=age;
                   8161:        }
                   8162:      } /* age */
                   8163:      /* Thus we have agemingood and agemaxgood as well as goodr for raw (preobs) */
                   8164:      /* but they will change */
1.288     brouard  8165:      firstA1=0;firstA2=0;
1.266     brouard  8166:      for (age=fage-(mob-1)/2; age>=bage; age--){/* From oldest to youngest, filling up to the youngest */
                   8167:        sumnewm[cptcod]=0.;
                   8168:        sumnewmr[cptcod]=0.;
                   8169:        for (i=1; i<=nlstate;i++){
                   8170:         sumnewm[cptcod]+=mobaverage[(int)age][i][cptcod];
                   8171:         sumnewmr[cptcod]+=probs[(int)age][i][cptcod];
                   8172:        }
                   8173:        if(mobilav==-1){ /* Forcing raw ages if good else agemingood */
                   8174:         if(fabs(sumnewmr[cptcod] - 1.) <= 1.e-3) { /* good without smoothing */
                   8175:           agemaxgoodr[cptcod]=age;  /* age min */
                   8176:           for (i=1; i<=nlstate;i++)
                   8177:             mobaverage[(int)age][i][cptcod]=probs[(int)age][i][cptcod];
                   8178:         }else{ /* bad we change the value with the values of good ages */
                   8179:           for (i=1; i<=nlstate;i++){
                   8180:             mobaverage[(int)age][i][cptcod]=mobaverage[(int)agemaxgoodr[cptcod]][i][cptcod];
                   8181:           } /* i */
                   8182:         } /* end bad */
                   8183:        }else{
                   8184:         if(fabs(sumnewm[cptcod] - 1.) <= 1.e-3) { /* good */
                   8185:           agemaxgood[cptcod]=age;
                   8186:         }else{ /* bad we change the value with the values of good ages */
                   8187:           for (i=1; i<=nlstate;i++){
                   8188:             mobaverage[(int)age][i][cptcod]=mobaverage[(int)agemaxgood[cptcod]][i][cptcod];
                   8189:           } /* i */
                   8190:         } /* end bad */
                   8191:        }/* end else */
                   8192:        sum=0.;sumr=0.;
                   8193:        for (i=1; i<=nlstate;i++){
                   8194:         sum+=mobaverage[(int)age][i][cptcod];
                   8195:         sumr+=probs[(int)age][i][cptcod];
                   8196:        }
                   8197:        if(fabs(sum - 1.) > 1.e-3) { /* bad */
1.288     brouard  8198:         if(!firstA1){
                   8199:           firstA1=1;
                   8200:           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);
                   8201:         }
                   8202:         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  8203:        } /* end bad */
                   8204:        /* else{ /\* We found some ages summing to one, we will smooth the oldest *\/ */
                   8205:        if(fabs(sumr - 1.) > 1.e-3) { /* bad */
1.288     brouard  8206:         if(!firstA2){
                   8207:           firstA2=1;
                   8208:           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);
                   8209:         }
                   8210:         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  8211:        } /* end bad */
                   8212:      }/* age */
1.266     brouard  8213: 
                   8214:      for (age=bage+(mob-1)/2; age<=fage; age++){/* From youngest, finding the oldest wrong */
1.222     brouard  8215:        sumnewm[cptcod]=0.;
1.266     brouard  8216:        sumnewmr[cptcod]=0.;
1.222     brouard  8217:        for (i=1; i<=nlstate;i++){
                   8218:         sumnewm[cptcod]+=mobaverage[(int)age][i][cptcod];
1.266     brouard  8219:         sumnewmr[cptcod]+=probs[(int)age][i][cptcod];
                   8220:        } 
                   8221:        if(mobilav==-1){ /* Forcing raw ages if good else agemingood */
                   8222:         if(fabs(sumnewmr[cptcod] - 1.) <= 1.e-3) { /* good */
                   8223:           agemingoodr[cptcod]=age;
                   8224:           for (i=1; i<=nlstate;i++)
                   8225:             mobaverage[(int)age][i][cptcod]=probs[(int)age][i][cptcod];
                   8226:         }else{ /* bad we change the value with the values of good ages */
                   8227:           for (i=1; i<=nlstate;i++){
                   8228:             mobaverage[(int)age][i][cptcod]=mobaverage[(int)agemingoodr[cptcod]][i][cptcod];
                   8229:           } /* i */
                   8230:         } /* end bad */
                   8231:        }else{
                   8232:         if(fabs(sumnewm[cptcod] - 1.) <= 1.e-3) { /* good */
                   8233:           agemingood[cptcod]=age;
                   8234:         }else{ /* bad */
                   8235:           for (i=1; i<=nlstate;i++){
                   8236:             mobaverage[(int)age][i][cptcod]=mobaverage[(int)agemingood[cptcod]][i][cptcod];
                   8237:           } /* i */
                   8238:         } /* end bad */
                   8239:        }/* end else */
                   8240:        sum=0.;sumr=0.;
                   8241:        for (i=1; i<=nlstate;i++){
                   8242:         sum+=mobaverage[(int)age][i][cptcod];
                   8243:         sumr+=mobaverage[(int)age][i][cptcod];
1.222     brouard  8244:        }
1.266     brouard  8245:        if(fabs(sum - 1.) > 1.e-3) { /* bad */
1.268     brouard  8246:         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  8247:        } /* end bad */
                   8248:        /* else{ /\* We found some ages summing to one, we will smooth the oldest *\/ */
                   8249:        if(fabs(sumr - 1.) > 1.e-3) { /* bad */
1.268     brouard  8250:         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  8251:        } /* end bad */
                   8252:      }/* age */
1.266     brouard  8253: 
1.222     brouard  8254:                
                   8255:      for (age=bage; age<=fage; age++){
1.235     brouard  8256:        /* printf("%d %d ", cptcod, (int)age); */
1.222     brouard  8257:        sumnewp[cptcod]=0.;
                   8258:        sumnewm[cptcod]=0.;
                   8259:        for (i=1; i<=nlstate;i++){
                   8260:         sumnewp[cptcod]+=probs[(int)age][i][cptcod];
                   8261:         sumnewm[cptcod]+=mobaverage[(int)age][i][cptcod];
                   8262:         /* printf("%.4f %.4f ",probs[(int)age][i][cptcod], mobaverage[(int)age][i][cptcod]); */
                   8263:        }
                   8264:        /* printf("%.4f %.4f \n",sumnewp[cptcod], sumnewm[cptcod]); */
                   8265:      }
                   8266:      /* printf("\n"); */
                   8267:      /* } */
1.266     brouard  8268: 
1.222     brouard  8269:      /* brutal averaging */
1.266     brouard  8270:      /* for (i=1; i<=nlstate;i++){ */
                   8271:      /*   for (age=1; age<=bage; age++){ */
                   8272:      /*         mobaverage[(int)age][i][cptcod]=mobaverage[(int)agemingood[cptcod]][i][cptcod]; */
                   8273:      /*         /\* printf("age=%d i=%d cptcod=%d mobaverage=%.4f \n",(int)age,i, cptcod, mobaverage[(int)age][i][cptcod]); *\/ */
                   8274:      /*   }     */
                   8275:      /*   for (age=fage; age<=AGESUP; age++){ */
                   8276:      /*         mobaverage[(int)age][i][cptcod]=mobaverage[(int)agemaxgood[cptcod]][i][cptcod]; */
                   8277:      /*         /\* printf("age=%d i=%d cptcod=%d mobaverage=%.4f \n",(int)age,i, cptcod, mobaverage[(int)age][i][cptcod]); *\/ */
                   8278:      /*   } */
                   8279:      /* } /\* end i status *\/ */
                   8280:      /* for (i=nlstate+1; i<=nlstate+ndeath;i++){ */
                   8281:      /*   for (age=1; age<=AGESUP; age++){ */
                   8282:      /*         /\*printf("i=%d, age=%d, cptcod=%d\n",i, (int)age, cptcod);*\/ */
                   8283:      /*         mobaverage[(int)age][i][cptcod]=0.; */
                   8284:      /*   } */
                   8285:      /* } */
1.222     brouard  8286:    }/* end cptcod */
1.266     brouard  8287:    free_vector(agemaxgoodr,1, ncovcombmax);
                   8288:    free_vector(agemaxgood,1, ncovcombmax);
                   8289:    free_vector(agemingood,1, ncovcombmax);
                   8290:    free_vector(agemingoodr,1, ncovcombmax);
                   8291:    free_vector(sumnewmr,1, ncovcombmax);
1.222     brouard  8292:    free_vector(sumnewm,1, ncovcombmax);
                   8293:    free_vector(sumnewp,1, ncovcombmax);
                   8294:    return 0;
                   8295:  }/* End movingaverage */
1.218     brouard  8296:  
1.126     brouard  8297: 
                   8298: /************** Forecasting ******************/
1.269     brouard  8299:  void prevforecast(char fileres[], double anproj1, double mproj1, double jproj1, double ageminpar, double agemax, double dateprev1, double dateprev2, int mobilav, double ***prev, double bage, double fage, int firstpass, int lastpass, double anproj2, double p[], int cptcoveff){
1.126     brouard  8300:   /* proj1, year, month, day of starting projection 
                   8301:      agemin, agemax range of age
                   8302:      dateprev1 dateprev2 range of dates during which prevalence is computed
                   8303:      anproj2 year of en of projection (same day and month as proj1).
                   8304:   */
1.267     brouard  8305:   int yearp, stepsize, hstepm, nhstepm, j, k, cptcod, i, h, i1, k4, nres=0;
1.126     brouard  8306:   double agec; /* generic age */
                   8307:   double agelim, ppij, yp,yp1,yp2,jprojmean,mprojmean,anprojmean;
                   8308:   double *popeffectif,*popcount;
                   8309:   double ***p3mat;
1.218     brouard  8310:   /* double ***mobaverage; */
1.126     brouard  8311:   char fileresf[FILENAMELENGTH];
                   8312: 
                   8313:   agelim=AGESUP;
1.211     brouard  8314:   /* Compute observed prevalence between dateprev1 and dateprev2 by counting the number of people
                   8315:      in each health status at the date of interview (if between dateprev1 and dateprev2).
                   8316:      We still use firstpass and lastpass as another selection.
                   8317:   */
1.214     brouard  8318:   /* freqsummary(fileres, agemin, agemax, s, agev, nlstate, imx,Tvaraff,nbcode, ncodemax,mint,anint,strstart,\ */
                   8319:   /*         firstpass, lastpass,  stepm,  weightopt, model); */
1.126     brouard  8320:  
1.201     brouard  8321:   strcpy(fileresf,"F_"); 
                   8322:   strcat(fileresf,fileresu);
1.126     brouard  8323:   if((ficresf=fopen(fileresf,"w"))==NULL) {
                   8324:     printf("Problem with forecast resultfile: %s\n", fileresf);
                   8325:     fprintf(ficlog,"Problem with forecast resultfile: %s\n", fileresf);
                   8326:   }
1.235     brouard  8327:   printf("\nComputing forecasting: result on file '%s', please wait... \n", fileresf);
                   8328:   fprintf(ficlog,"\nComputing forecasting: result on file '%s', please wait... \n", fileresf);
1.126     brouard  8329: 
1.225     brouard  8330:   if (cptcoveff==0) ncodemax[cptcoveff]=1;
1.126     brouard  8331: 
                   8332: 
                   8333:   stepsize=(int) (stepm+YEARM-1)/YEARM;
                   8334:   if (stepm<=12) stepsize=1;
                   8335:   if(estepm < stepm){
                   8336:     printf ("Problem %d lower than %d\n",estepm, stepm);
                   8337:   }
1.270     brouard  8338:   else{
                   8339:     hstepm=estepm;   
                   8340:   }
                   8341:   if(estepm > stepm){ /* Yes every two year */
                   8342:     stepsize=2;
                   8343:   }
1.126     brouard  8344: 
                   8345:   hstepm=hstepm/stepm; 
                   8346:   yp1=modf(dateintmean,&yp);/* extracts integral of datemean in yp  and
                   8347:                                fractional in yp1 */
                   8348:   anprojmean=yp;
                   8349:   yp2=modf((yp1*12),&yp);
                   8350:   mprojmean=yp;
                   8351:   yp1=modf((yp2*30.5),&yp);
                   8352:   jprojmean=yp;
                   8353:   if(jprojmean==0) jprojmean=1;
                   8354:   if(mprojmean==0) jprojmean=1;
                   8355: 
1.227     brouard  8356:   i1=pow(2,cptcoveff);
1.126     brouard  8357:   if (cptcovn < 1){i1=1;}
                   8358:   
                   8359:   fprintf(ficresf,"# Mean day of interviews %.lf/%.lf/%.lf (%.2f) between %.2f and %.2f \n",jprojmean,mprojmean,anprojmean,dateintmean,dateprev1,dateprev2); 
                   8360:   
                   8361:   fprintf(ficresf,"#****** Routine prevforecast **\n");
1.227     brouard  8362:   
1.126     brouard  8363: /*           if (h==(int)(YEARM*yearp)){ */
1.235     brouard  8364:   for(nres=1; nres <= nresult; nres++) /* For each resultline */
                   8365:   for(k=1; k<=i1;k++){
1.253     brouard  8366:     if(i1 != 1 && TKresult[nres]!= k)
1.235     brouard  8367:       continue;
1.227     brouard  8368:     if(invalidvarcomb[k]){
                   8369:       printf("\nCombination (%d) projection ignored because no cases \n",k); 
                   8370:       continue;
                   8371:     }
                   8372:     fprintf(ficresf,"\n#****** hpijx=probability over h years, hp.jx is weighted by observed prev \n#");
                   8373:     for(j=1;j<=cptcoveff;j++) {
                   8374:       fprintf(ficresf," V%d (=) %d",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   8375:     }
1.235     brouard  8376:     for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
1.238     brouard  8377:       fprintf(ficresf," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
1.235     brouard  8378:     }
1.227     brouard  8379:     fprintf(ficresf," yearproj age");
                   8380:     for(j=1; j<=nlstate+ndeath;j++){ 
                   8381:       for(i=1; i<=nlstate;i++)               
                   8382:        fprintf(ficresf," p%d%d",i,j);
                   8383:       fprintf(ficresf," wp.%d",j);
                   8384:     }
                   8385:     for (yearp=0; yearp<=(anproj2-anproj1);yearp +=stepsize) {
                   8386:       fprintf(ficresf,"\n");
                   8387:       fprintf(ficresf,"\n# Forecasting at date %.lf/%.lf/%.lf ",jproj1,mproj1,anproj1+yearp);   
1.270     brouard  8388:       /* for (agec=fage; agec>=(ageminpar-1); agec--){  */
                   8389:       for (agec=fage; agec>=(bage); agec--){ 
1.227     brouard  8390:        nhstepm=(int) rint((agelim-agec)*YEARM/stepm); 
                   8391:        nhstepm = nhstepm/hstepm; 
                   8392:        p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   8393:        oldm=oldms;savm=savms;
1.268     brouard  8394:        /* We compute pii at age agec over nhstepm);*/
1.235     brouard  8395:        hpxij(p3mat,nhstepm,agec,hstepm,p,nlstate,stepm,oldm,savm, k,nres);
1.268     brouard  8396:        /* Then we print p3mat for h corresponding to the right agec+h*stepms=yearp */
1.227     brouard  8397:        for (h=0; h<=nhstepm; h++){
                   8398:          if (h*hstepm/YEARM*stepm ==yearp) {
1.268     brouard  8399:            break;
                   8400:          }
                   8401:        }
                   8402:        fprintf(ficresf,"\n");
                   8403:        for(j=1;j<=cptcoveff;j++) 
                   8404:          fprintf(ficresf,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   8405:        fprintf(ficresf,"%.f %.f ",anproj1+yearp,agec+h*hstepm/YEARM*stepm);
                   8406:        
                   8407:        for(j=1; j<=nlstate+ndeath;j++) {
                   8408:          ppij=0.;
                   8409:          for(i=1; i<=nlstate;i++) {
1.278     brouard  8410:            if (mobilav>=1)
                   8411:             ppij=ppij+p3mat[i][j][h]*prev[(int)agec][i][k];
                   8412:            else { /* even if mobilav==-1 we use mobaverage, probs may not sums to 1 */
                   8413:                ppij=ppij+p3mat[i][j][h]*probs[(int)(agec)][i][k];
                   8414:            }
1.268     brouard  8415:            fprintf(ficresf," %.3f", p3mat[i][j][h]);
                   8416:          } /* end i */
                   8417:          fprintf(ficresf," %.3f", ppij);
                   8418:        }/* end j */
1.227     brouard  8419:        free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   8420:       } /* end agec */
1.266     brouard  8421:       /* diffyear=(int) anproj1+yearp-ageminpar-1; */
                   8422:       /*printf("Prevforecast %d+%d-%d=diffyear=%d\n",(int) anproj1, (int)yearp,(int)ageminpar,(int) anproj1-(int)ageminpar);*/
1.227     brouard  8423:     } /* end yearp */
                   8424:   } /* end  k */
1.219     brouard  8425:        
1.126     brouard  8426:   fclose(ficresf);
1.215     brouard  8427:   printf("End of Computing forecasting \n");
                   8428:   fprintf(ficlog,"End of Computing forecasting\n");
                   8429: 
1.126     brouard  8430: }
                   8431: 
1.269     brouard  8432: /************** Back Forecasting ******************/
                   8433:  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){
1.267     brouard  8434:   /* back1, year, month, day of starting backection
                   8435:      agemin, agemax range of age
                   8436:      dateprev1 dateprev2 range of dates during which prevalence is computed
1.269     brouard  8437:      anback2 year of end of backprojection (same day and month as back1).
                   8438:      prevacurrent and prev are prevalences.
1.267     brouard  8439:   */
                   8440:   int yearp, stepsize, hstepm, nhstepm, j, k, cptcod, i, h, i1, k4, nres=0;
                   8441:   double agec; /* generic age */
1.268     brouard  8442:   double agelim, ppij, ppi, yp,yp1,yp2,jprojmean,mprojmean,anprojmean;
1.267     brouard  8443:   double *popeffectif,*popcount;
                   8444:   double ***p3mat;
                   8445:   /* double ***mobaverage; */
                   8446:   char fileresfb[FILENAMELENGTH];
                   8447:  
1.268     brouard  8448:   agelim=AGEINF;
1.267     brouard  8449:   /* Compute observed prevalence between dateprev1 and dateprev2 by counting the number of people
                   8450:      in each health status at the date of interview (if between dateprev1 and dateprev2).
                   8451:      We still use firstpass and lastpass as another selection.
                   8452:   */
                   8453:   /* freqsummary(fileres, agemin, agemax, s, agev, nlstate, imx,Tvaraff,nbcode, ncodemax,mint,anint,strstart,\ */
                   8454:   /*         firstpass, lastpass,  stepm,  weightopt, model); */
                   8455: 
                   8456:   /*Do we need to compute prevalence again?*/
                   8457: 
                   8458:   /* prevalence(probs, ageminpar, agemax, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass); */
                   8459:   
                   8460:   strcpy(fileresfb,"FB_");
                   8461:   strcat(fileresfb,fileresu);
                   8462:   if((ficresfb=fopen(fileresfb,"w"))==NULL) {
                   8463:     printf("Problem with back forecast resultfile: %s\n", fileresfb);
                   8464:     fprintf(ficlog,"Problem with back forecast resultfile: %s\n", fileresfb);
                   8465:   }
                   8466:   printf("\nComputing back forecasting: result on file '%s', please wait... \n", fileresfb);
                   8467:   fprintf(ficlog,"\nComputing back forecasting: result on file '%s', please wait... \n", fileresfb);
                   8468:   
                   8469:   if (cptcoveff==0) ncodemax[cptcoveff]=1;
                   8470:   
                   8471:    
                   8472:   stepsize=(int) (stepm+YEARM-1)/YEARM;
                   8473:   if (stepm<=12) stepsize=1;
                   8474:   if(estepm < stepm){
                   8475:     printf ("Problem %d lower than %d\n",estepm, stepm);
                   8476:   }
1.270     brouard  8477:   else{
                   8478:     hstepm=estepm;   
                   8479:   }
                   8480:   if(estepm >= stepm){ /* Yes every two year */
                   8481:     stepsize=2;
                   8482:   }
1.267     brouard  8483:   
                   8484:   hstepm=hstepm/stepm;
                   8485:   yp1=modf(dateintmean,&yp);/* extracts integral of datemean in yp  and
                   8486:                                fractional in yp1 */
                   8487:   anprojmean=yp;
                   8488:   yp2=modf((yp1*12),&yp);
                   8489:   mprojmean=yp;
                   8490:   yp1=modf((yp2*30.5),&yp);
                   8491:   jprojmean=yp;
                   8492:   if(jprojmean==0) jprojmean=1;
                   8493:   if(mprojmean==0) jprojmean=1;
                   8494:   
                   8495:   i1=pow(2,cptcoveff);
                   8496:   if (cptcovn < 1){i1=1;}
                   8497:   
                   8498:   fprintf(ficresfb,"# Mean day of interviews %.lf/%.lf/%.lf (%.2f) between %.2f and %.2f \n",jprojmean,mprojmean,anprojmean,dateintmean,dateprev1,dateprev2);
1.268     brouard  8499:   printf("# Mean day of interviews %.lf/%.lf/%.lf (%.2f) between %.2f and %.2f \n",jprojmean,mprojmean,anprojmean,dateintmean,dateprev1,dateprev2);
1.267     brouard  8500:   
                   8501:   fprintf(ficresfb,"#****** Routine prevbackforecast **\n");
                   8502:   
                   8503:   for(nres=1; nres <= nresult; nres++) /* For each resultline */
                   8504:   for(k=1; k<=i1;k++){
                   8505:     if(i1 != 1 && TKresult[nres]!= k)
                   8506:       continue;
                   8507:     if(invalidvarcomb[k]){
                   8508:       printf("\nCombination (%d) projection ignored because no cases \n",k); 
                   8509:       continue;
                   8510:     }
1.268     brouard  8511:     fprintf(ficresfb,"\n#****** hbijx=probability over h years, hb.jx is weighted by observed prev \n#");
1.267     brouard  8512:     for(j=1;j<=cptcoveff;j++) {
                   8513:       fprintf(ficresfb," V%d (=) %d",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   8514:     }
                   8515:     for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
                   8516:       fprintf(ficresf," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
                   8517:     }
                   8518:     fprintf(ficresfb," yearbproj age");
                   8519:     for(j=1; j<=nlstate+ndeath;j++){
                   8520:       for(i=1; i<=nlstate;i++)
1.268     brouard  8521:        fprintf(ficresfb," b%d%d",i,j);
                   8522:       fprintf(ficresfb," b.%d",j);
1.267     brouard  8523:     }
                   8524:     for (yearp=0; yearp>=(anback2-anback1);yearp -=stepsize) {
                   8525:       /* for (yearp=0; yearp<=(anproj2-anproj1);yearp +=stepsize) {  */
                   8526:       fprintf(ficresfb,"\n");
                   8527:       fprintf(ficresfb,"\n# Back Forecasting at date %.lf/%.lf/%.lf ",jback1,mback1,anback1+yearp);
1.273     brouard  8528:       /* printf("\n# Back Forecasting at date %.lf/%.lf/%.lf ",jback1,mback1,anback1+yearp); */
1.270     brouard  8529:       /* for (agec=bage; agec<=agemax-1; agec++){  /\* testing *\/ */
                   8530:       for (agec=bage; agec<=fage; agec++){  /* testing */
1.268     brouard  8531:        /* We compute bij at age agec over nhstepm, nhstepm decreases when agec increases because of agemax;*/
1.271     brouard  8532:        nhstepm=(int) (agec-agelim) *YEARM/stepm;/*     nhstepm=(int) rint((agec-agelim)*YEARM/stepm);*/
1.267     brouard  8533:        nhstepm = nhstepm/hstepm;
                   8534:        p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   8535:        oldm=oldms;savm=savms;
1.268     brouard  8536:        /* computes hbxij at age agec over 1 to nhstepm */
1.271     brouard  8537:        /* printf("####prevbackforecast debug  agec=%.2f nhstepm=%d\n",agec, nhstepm);fflush(stdout); */
1.267     brouard  8538:        hbxij(p3mat,nhstepm,agec,hstepm,p,prevacurrent,nlstate,stepm, k, nres);
1.268     brouard  8539:        /* hpxij(p3mat,nhstepm,agec,hstepm,p,             nlstate,stepm,oldm,savm, k,nres); */
                   8540:        /* Then we print p3mat for h corresponding to the right agec+h*stepms=yearp */
                   8541:        /* printf(" agec=%.2f\n",agec);fflush(stdout); */
1.267     brouard  8542:        for (h=0; h<=nhstepm; h++){
1.268     brouard  8543:          if (h*hstepm/YEARM*stepm ==-yearp) {
                   8544:            break;
                   8545:          }
                   8546:        }
                   8547:        fprintf(ficresfb,"\n");
                   8548:        for(j=1;j<=cptcoveff;j++)
                   8549:          fprintf(ficresfb,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   8550:        fprintf(ficresfb,"%.f %.f ",anback1+yearp,agec-h*hstepm/YEARM*stepm);
                   8551:        for(i=1; i<=nlstate+ndeath;i++) {
                   8552:          ppij=0.;ppi=0.;
                   8553:          for(j=1; j<=nlstate;j++) {
                   8554:            /* if (mobilav==1) */
1.269     brouard  8555:            ppij=ppij+p3mat[i][j][h]*prevacurrent[(int)agec][j][k];
                   8556:            ppi=ppi+prevacurrent[(int)agec][j][k];
                   8557:            /* ppij=ppij+p3mat[i][j][h]*mobaverage[(int)agec][j][k]; */
                   8558:            /* ppi=ppi+mobaverage[(int)agec][j][k]; */
1.267     brouard  8559:              /* else { */
                   8560:              /*        ppij=ppij+p3mat[i][j][h]*probs[(int)(agec)][i][k]; */
                   8561:              /* } */
1.268     brouard  8562:            fprintf(ficresfb," %.3f", p3mat[i][j][h]);
                   8563:          } /* end j */
                   8564:          if(ppi <0.99){
                   8565:            printf("Error in prevbackforecast, prevalence doesn't sum to 1 for state %d: %3f\n",i, ppi);
                   8566:            fprintf(ficlog,"Error in prevbackforecast, prevalence doesn't sum to 1 for state %d: %3f\n",i, ppi);
                   8567:          }
                   8568:          fprintf(ficresfb," %.3f", ppij);
                   8569:        }/* end j */
1.267     brouard  8570:        free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   8571:       } /* end agec */
                   8572:     } /* end yearp */
                   8573:   } /* end k */
1.217     brouard  8574:   
1.267     brouard  8575:   /* if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX); */
1.217     brouard  8576:   
1.267     brouard  8577:   fclose(ficresfb);
                   8578:   printf("End of Computing Back forecasting \n");
                   8579:   fprintf(ficlog,"End of Computing Back forecasting\n");
1.218     brouard  8580:        
1.267     brouard  8581: }
1.217     brouard  8582: 
1.269     brouard  8583: /* Variance of prevalence limit: varprlim */
                   8584:  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  8585:     /*------- Variance of forward period (stable) prevalence------*/   
1.269     brouard  8586:  
                   8587:    char fileresvpl[FILENAMELENGTH];  
                   8588:    FILE *ficresvpl;
                   8589:    double **oldm, **savm;
                   8590:    double **varpl; /* Variances of prevalence limits by age */   
                   8591:    int i1, k, nres, j ;
                   8592:    
                   8593:     strcpy(fileresvpl,"VPL_");
                   8594:     strcat(fileresvpl,fileresu);
                   8595:     if((ficresvpl=fopen(fileresvpl,"w"))==NULL) {
1.288     brouard  8596:       printf("Problem with variance of forward period (stable) prevalence  resultfile: %s\n", fileresvpl);
1.269     brouard  8597:       exit(0);
                   8598:     }
1.288     brouard  8599:     printf("Computing Variance-covariance of forward period (stable) prevalence: file '%s' ...", fileresvpl);fflush(stdout);
                   8600:     fprintf(ficlog, "Computing Variance-covariance of forward period (stable) prevalence: file '%s' ...", fileresvpl);fflush(ficlog);
1.269     brouard  8601:     
                   8602:     /*for(cptcov=1,k=0;cptcov<=i1;cptcov++){
                   8603:       for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*/
                   8604:     
                   8605:     i1=pow(2,cptcoveff);
                   8606:     if (cptcovn < 1){i1=1;}
                   8607: 
                   8608:     for(nres=1; nres <= nresult; nres++) /* For each resultline */
                   8609:     for(k=1; k<=i1;k++){
                   8610:       if(i1 != 1 && TKresult[nres]!= k)
                   8611:        continue;
                   8612:       fprintf(ficresvpl,"\n#****** ");
                   8613:       printf("\n#****** ");
                   8614:       fprintf(ficlog,"\n#****** ");
                   8615:       for(j=1;j<=cptcoveff;j++) {
                   8616:        fprintf(ficresvpl,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   8617:        fprintf(ficlog,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   8618:        printf("V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   8619:       }
                   8620:       for (j=1; j<= nsq; j++){ /* For each selected (single) quantitative value */
                   8621:        printf(" V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]);
                   8622:        fprintf(ficresvpl," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]);
                   8623:        fprintf(ficlog," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]);
                   8624:       }        
                   8625:       fprintf(ficresvpl,"******\n");
                   8626:       printf("******\n");
                   8627:       fprintf(ficlog,"******\n");
                   8628:       
                   8629:       varpl=matrix(1,nlstate,(int) bage, (int) fage);
                   8630:       oldm=oldms;savm=savms;
                   8631:       varprevlim(fileresvpl, ficresvpl, varpl, matcov, p, delti, nlstate, stepm, (int) bage, (int) fage, oldm, savm, prlim, ftolpl, ncvyearp, k, strstart, nres);
                   8632:       free_matrix(varpl,1,nlstate,(int) bage, (int)fage);
                   8633:       /*}*/
                   8634:     }
                   8635:     
                   8636:     fclose(ficresvpl);
1.288     brouard  8637:     printf("done variance-covariance of forward period prevalence\n");fflush(stdout);
                   8638:     fprintf(ficlog,"done variance-covariance of forward period prevalence\n");fflush(ficlog);
1.269     brouard  8639: 
                   8640:  }
                   8641: /* Variance of back prevalence: varbprlim */
                   8642:  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){
                   8643:       /*------- Variance of back (stable) prevalence------*/
                   8644: 
                   8645:    char fileresvbl[FILENAMELENGTH];  
                   8646:    FILE  *ficresvbl;
                   8647: 
                   8648:    double **oldm, **savm;
                   8649:    double **varbpl; /* Variances of back prevalence limits by age */   
                   8650:    int i1, k, nres, j ;
                   8651: 
                   8652:    strcpy(fileresvbl,"VBL_");
                   8653:    strcat(fileresvbl,fileresu);
                   8654:    if((ficresvbl=fopen(fileresvbl,"w"))==NULL) {
                   8655:      printf("Problem with variance of back (stable) prevalence  resultfile: %s\n", fileresvbl);
                   8656:      exit(0);
                   8657:    }
                   8658:    printf("Computing Variance-covariance of back (stable) prevalence: file '%s' ...", fileresvbl);fflush(stdout);
                   8659:    fprintf(ficlog, "Computing Variance-covariance of back (stable) prevalence: file '%s' ...", fileresvbl);fflush(ficlog);
                   8660:    
                   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(ficresvbl,"\n#****** ");
                   8670:        printf("\n#****** ");
                   8671:        fprintf(ficlog,"\n#****** ");
                   8672:        for(j=1;j<=cptcoveff;j++) {
                   8673:         fprintf(ficresvbl,"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(ficresvbl," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]);
                   8680:         fprintf(ficlog," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]);
                   8681:        }
                   8682:        fprintf(ficresvbl,"******\n");
                   8683:        printf("******\n");
                   8684:        fprintf(ficlog,"******\n");
                   8685:        
                   8686:        varbpl=matrix(1,nlstate,(int) bage, (int) fage);
                   8687:        oldm=oldms;savm=savms;
                   8688:        
                   8689:        varbrevlim(fileresvbl, ficresvbl, varbpl, matcov, p, delti, nlstate, stepm, (int) bage, (int) fage, oldm, savm, bprlim, ftolpl, mobilavproj, ncvyearp, k, strstart, nres);
                   8690:        free_matrix(varbpl,1,nlstate,(int) bage, (int)fage);
                   8691:        /*}*/
                   8692:      }
                   8693:    
                   8694:    fclose(ficresvbl);
                   8695:    printf("done variance-covariance of back prevalence\n");fflush(stdout);
                   8696:    fprintf(ficlog,"done variance-covariance of back prevalence\n");fflush(ficlog);
                   8697: 
                   8698:  } /* End of varbprlim */
                   8699: 
1.126     brouard  8700: /************** Forecasting *****not tested NB*************/
1.227     brouard  8701: /* 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  8702:   
1.227     brouard  8703: /*   int cpt, stepsize, hstepm, nhstepm, j,k,c, cptcod, i,h; */
                   8704: /*   int *popage; */
                   8705: /*   double calagedatem, agelim, kk1, kk2; */
                   8706: /*   double *popeffectif,*popcount; */
                   8707: /*   double ***p3mat,***tabpop,***tabpopprev; */
                   8708: /*   /\* double ***mobaverage; *\/ */
                   8709: /*   char filerespop[FILENAMELENGTH]; */
1.126     brouard  8710: 
1.227     brouard  8711: /*   tabpop= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX); */
                   8712: /*   tabpopprev= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX); */
                   8713: /*   agelim=AGESUP; */
                   8714: /*   calagedatem=(anpyram+mpyram/12.+jpyram/365.-dateintmean)*YEARM; */
1.126     brouard  8715:   
1.227     brouard  8716: /*   prevalence(probs, ageminpar, agemax, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass); */
1.126     brouard  8717:   
                   8718:   
1.227     brouard  8719: /*   strcpy(filerespop,"POP_");  */
                   8720: /*   strcat(filerespop,fileresu); */
                   8721: /*   if((ficrespop=fopen(filerespop,"w"))==NULL) { */
                   8722: /*     printf("Problem with forecast resultfile: %s\n", filerespop); */
                   8723: /*     fprintf(ficlog,"Problem with forecast resultfile: %s\n", filerespop); */
                   8724: /*   } */
                   8725: /*   printf("Computing forecasting: result on file '%s' \n", filerespop); */
                   8726: /*   fprintf(ficlog,"Computing forecasting: result on file '%s' \n", filerespop); */
1.126     brouard  8727: 
1.227     brouard  8728: /*   if (cptcoveff==0) ncodemax[cptcoveff]=1; */
1.126     brouard  8729: 
1.227     brouard  8730: /*   /\* if (mobilav!=0) { *\/ */
                   8731: /*   /\*   mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX); *\/ */
                   8732: /*   /\*   if (movingaverage(probs, ageminpar, fage, mobaverage,mobilav)!=0){ *\/ */
                   8733: /*   /\*     fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav); *\/ */
                   8734: /*   /\*     printf(" Error in movingaverage mobilav=%d\n",mobilav); *\/ */
                   8735: /*   /\*   } *\/ */
                   8736: /*   /\* } *\/ */
1.126     brouard  8737: 
1.227     brouard  8738: /*   stepsize=(int) (stepm+YEARM-1)/YEARM; */
                   8739: /*   if (stepm<=12) stepsize=1; */
1.126     brouard  8740:   
1.227     brouard  8741: /*   agelim=AGESUP; */
1.126     brouard  8742:   
1.227     brouard  8743: /*   hstepm=1; */
                   8744: /*   hstepm=hstepm/stepm;  */
1.218     brouard  8745:        
1.227     brouard  8746: /*   if (popforecast==1) { */
                   8747: /*     if((ficpop=fopen(popfile,"r"))==NULL) { */
                   8748: /*       printf("Problem with population file : %s\n",popfile);exit(0); */
                   8749: /*       fprintf(ficlog,"Problem with population file : %s\n",popfile);exit(0); */
                   8750: /*     }  */
                   8751: /*     popage=ivector(0,AGESUP); */
                   8752: /*     popeffectif=vector(0,AGESUP); */
                   8753: /*     popcount=vector(0,AGESUP); */
1.126     brouard  8754:     
1.227     brouard  8755: /*     i=1;    */
                   8756: /*     while ((c=fscanf(ficpop,"%d %lf\n",&popage[i],&popcount[i])) != EOF) i=i+1; */
1.218     brouard  8757:     
1.227     brouard  8758: /*     imx=i; */
                   8759: /*     for (i=1; i<imx;i++) popeffectif[popage[i]]=popcount[i]; */
                   8760: /*   } */
1.218     brouard  8761:   
1.227     brouard  8762: /*   for(cptcov=1,k=0;cptcov<=i2;cptcov++){ */
                   8763: /*     for(cptcod=1;cptcod<=ncodemax[cptcoveff];cptcod++){ */
                   8764: /*       k=k+1; */
                   8765: /*       fprintf(ficrespop,"\n#******"); */
                   8766: /*       for(j=1;j<=cptcoveff;j++) { */
                   8767: /*     fprintf(ficrespop," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]); */
                   8768: /*       } */
                   8769: /*       fprintf(ficrespop,"******\n"); */
                   8770: /*       fprintf(ficrespop,"# Age"); */
                   8771: /*       for(j=1; j<=nlstate+ndeath;j++) fprintf(ficrespop," P.%d",j); */
                   8772: /*       if (popforecast==1)  fprintf(ficrespop," [Population]"); */
1.126     brouard  8773:       
1.227     brouard  8774: /*       for (cpt=0; cpt<=0;cpt++) {  */
                   8775: /*     fprintf(ficrespop,"\n\n# Forecasting at date %.lf/%.lf/%.lf ",jpyram,mpyram,anpyram+cpt);    */
1.126     brouard  8776:        
1.227     brouard  8777: /*     for (agedeb=(fage-((int)calagedatem %12/12.)); agedeb>=(ageminpar-((int)calagedatem %12)/12.); agedeb--){  */
                   8778: /*       nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm);  */
                   8779: /*       nhstepm = nhstepm/hstepm;  */
1.126     brouard  8780:          
1.227     brouard  8781: /*       p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm); */
                   8782: /*       oldm=oldms;savm=savms; */
                   8783: /*       hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);   */
1.218     brouard  8784:          
1.227     brouard  8785: /*       for (h=0; h<=nhstepm; h++){ */
                   8786: /*         if (h==(int) (calagedatem+YEARM*cpt)) { */
                   8787: /*           fprintf(ficrespop,"\n %3.f ",agedeb+h*hstepm/YEARM*stepm); */
                   8788: /*         }  */
                   8789: /*         for(j=1; j<=nlstate+ndeath;j++) { */
                   8790: /*           kk1=0.;kk2=0; */
                   8791: /*           for(i=1; i<=nlstate;i++) {               */
                   8792: /*             if (mobilav==1)  */
                   8793: /*               kk1=kk1+p3mat[i][j][h]*mobaverage[(int)agedeb+1][i][cptcod]; */
                   8794: /*             else { */
                   8795: /*               kk1=kk1+p3mat[i][j][h]*probs[(int)(agedeb+1)][i][cptcod]; */
                   8796: /*             } */
                   8797: /*           } */
                   8798: /*           if (h==(int)(calagedatem+12*cpt)){ */
                   8799: /*             tabpop[(int)(agedeb)][j][cptcod]=kk1; */
                   8800: /*             /\*fprintf(ficrespop," %.3f", kk1); */
                   8801: /*               if (popforecast==1) fprintf(ficrespop," [%.f]", kk1*popeffectif[(int)agedeb+1]);*\/ */
                   8802: /*           } */
                   8803: /*         } */
                   8804: /*         for(i=1; i<=nlstate;i++){ */
                   8805: /*           kk1=0.; */
                   8806: /*           for(j=1; j<=nlstate;j++){ */
                   8807: /*             kk1= kk1+tabpop[(int)(agedeb)][j][cptcod];  */
                   8808: /*           } */
                   8809: /*           tabpopprev[(int)(agedeb)][i][cptcod]=tabpop[(int)(agedeb)][i][cptcod]/kk1*popeffectif[(int)(agedeb+(calagedatem+12*cpt)*hstepm/YEARM*stepm-1)]; */
                   8810: /*         } */
1.218     brouard  8811:            
1.227     brouard  8812: /*         if (h==(int)(calagedatem+12*cpt)) */
                   8813: /*           for(j=1; j<=nlstate;j++)  */
                   8814: /*             fprintf(ficrespop," %15.2f",tabpopprev[(int)(agedeb+1)][j][cptcod]); */
                   8815: /*       } */
                   8816: /*       free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm); */
                   8817: /*     } */
                   8818: /*       } */
1.218     brouard  8819:       
1.227     brouard  8820: /*       /\******\/ */
1.218     brouard  8821:       
1.227     brouard  8822: /*       for (cpt=1; cpt<=(anpyram1-anpyram);cpt++) {  */
                   8823: /*     fprintf(ficrespop,"\n\n# Forecasting at date %.lf/%.lf/%.lf ",jpyram,mpyram,anpyram+cpt);    */
                   8824: /*     for (agedeb=(fage-((int)calagedatem %12/12.)); agedeb>=(ageminpar-((int)calagedatem %12)/12.); agedeb--){  */
                   8825: /*       nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm);  */
                   8826: /*       nhstepm = nhstepm/hstepm;  */
1.126     brouard  8827:          
1.227     brouard  8828: /*       p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm); */
                   8829: /*       oldm=oldms;savm=savms; */
                   8830: /*       hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);   */
                   8831: /*       for (h=0; h<=nhstepm; h++){ */
                   8832: /*         if (h==(int) (calagedatem+YEARM*cpt)) { */
                   8833: /*           fprintf(ficresf,"\n %3.f ",agedeb+h*hstepm/YEARM*stepm); */
                   8834: /*         }  */
                   8835: /*         for(j=1; j<=nlstate+ndeath;j++) { */
                   8836: /*           kk1=0.;kk2=0; */
                   8837: /*           for(i=1; i<=nlstate;i++) {               */
                   8838: /*             kk1=kk1+p3mat[i][j][h]*tabpopprev[(int)agedeb+1][i][cptcod];     */
                   8839: /*           } */
                   8840: /*           if (h==(int)(calagedatem+12*cpt)) fprintf(ficresf," %15.2f", kk1);         */
                   8841: /*         } */
                   8842: /*       } */
                   8843: /*       free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm); */
                   8844: /*     } */
                   8845: /*       } */
                   8846: /*     }  */
                   8847: /*   } */
1.218     brouard  8848:   
1.227     brouard  8849: /*   /\* if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX); *\/ */
1.218     brouard  8850:   
1.227     brouard  8851: /*   if (popforecast==1) { */
                   8852: /*     free_ivector(popage,0,AGESUP); */
                   8853: /*     free_vector(popeffectif,0,AGESUP); */
                   8854: /*     free_vector(popcount,0,AGESUP); */
                   8855: /*   } */
                   8856: /*   free_ma3x(tabpop,1, AGESUP,1,NCOVMAX, 1,NCOVMAX); */
                   8857: /*   free_ma3x(tabpopprev,1, AGESUP,1,NCOVMAX, 1,NCOVMAX); */
                   8858: /*   fclose(ficrespop); */
                   8859: /* } /\* End of popforecast *\/ */
1.218     brouard  8860:  
1.126     brouard  8861: int fileappend(FILE *fichier, char *optionfich)
                   8862: {
                   8863:   if((fichier=fopen(optionfich,"a"))==NULL) {
                   8864:     printf("Problem with file: %s\n", optionfich);
                   8865:     fprintf(ficlog,"Problem with file: %s\n", optionfich);
                   8866:     return (0);
                   8867:   }
                   8868:   fflush(fichier);
                   8869:   return (1);
                   8870: }
                   8871: 
                   8872: 
                   8873: /**************** function prwizard **********************/
                   8874: void prwizard(int ncovmodel, int nlstate, int ndeath,  char model[], FILE *ficparo)
                   8875: {
                   8876: 
                   8877:   /* Wizard to print covariance matrix template */
                   8878: 
1.164     brouard  8879:   char ca[32], cb[32];
                   8880:   int i,j, k, li, lj, lk, ll, jj, npar, itimes;
1.126     brouard  8881:   int numlinepar;
                   8882: 
                   8883:   printf("# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
                   8884:   fprintf(ficparo,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
                   8885:   for(i=1; i <=nlstate; i++){
                   8886:     jj=0;
                   8887:     for(j=1; j <=nlstate+ndeath; j++){
                   8888:       if(j==i) continue;
                   8889:       jj++;
                   8890:       /*ca[0]= k+'a'-1;ca[1]='\0';*/
                   8891:       printf("%1d%1d",i,j);
                   8892:       fprintf(ficparo,"%1d%1d",i,j);
                   8893:       for(k=1; k<=ncovmodel;k++){
                   8894:        /*        printf(" %lf",param[i][j][k]); */
                   8895:        /*        fprintf(ficparo," %lf",param[i][j][k]); */
                   8896:        printf(" 0.");
                   8897:        fprintf(ficparo," 0.");
                   8898:       }
                   8899:       printf("\n");
                   8900:       fprintf(ficparo,"\n");
                   8901:     }
                   8902:   }
                   8903:   printf("# Scales (for hessian or gradient estimation)\n");
                   8904:   fprintf(ficparo,"# Scales (for hessian or gradient estimation)\n");
                   8905:   npar= (nlstate+ndeath-1)*nlstate*ncovmodel; /* Number of parameters*/ 
                   8906:   for(i=1; i <=nlstate; i++){
                   8907:     jj=0;
                   8908:     for(j=1; j <=nlstate+ndeath; j++){
                   8909:       if(j==i) continue;
                   8910:       jj++;
                   8911:       fprintf(ficparo,"%1d%1d",i,j);
                   8912:       printf("%1d%1d",i,j);
                   8913:       fflush(stdout);
                   8914:       for(k=1; k<=ncovmodel;k++){
                   8915:        /*      printf(" %le",delti3[i][j][k]); */
                   8916:        /*      fprintf(ficparo," %le",delti3[i][j][k]); */
                   8917:        printf(" 0.");
                   8918:        fprintf(ficparo," 0.");
                   8919:       }
                   8920:       numlinepar++;
                   8921:       printf("\n");
                   8922:       fprintf(ficparo,"\n");
                   8923:     }
                   8924:   }
                   8925:   printf("# Covariance matrix\n");
                   8926: /* # 121 Var(a12)\n\ */
                   8927: /* # 122 Cov(b12,a12) Var(b12)\n\ */
                   8928: /* # 131 Cov(a13,a12) Cov(a13,b12, Var(a13)\n\ */
                   8929: /* # 132 Cov(b13,a12) Cov(b13,b12, Cov(b13,a13) Var(b13)\n\ */
                   8930: /* # 212 Cov(a21,a12) Cov(a21,b12, Cov(a21,a13) Cov(a21,b13) Var(a21)\n\ */
                   8931: /* # 212 Cov(b21,a12) Cov(b21,b12, Cov(b21,a13) Cov(b21,b13) Cov(b21,a21) Var(b21)\n\ */
                   8932: /* # 232 Cov(a23,a12) Cov(a23,b12, Cov(a23,a13) Cov(a23,b13) Cov(a23,a21) Cov(a23,b21) Var(a23)\n\ */
                   8933: /* # 232 Cov(b23,a12) Cov(b23,b12) ... Var (b23)\n" */
                   8934:   fflush(stdout);
                   8935:   fprintf(ficparo,"# Covariance matrix\n");
                   8936:   /* # 121 Var(a12)\n\ */
                   8937:   /* # 122 Cov(b12,a12) Var(b12)\n\ */
                   8938:   /* #   ...\n\ */
                   8939:   /* # 232 Cov(b23,a12)  Cov(b23,b12) ... Var (b23)\n" */
                   8940:   
                   8941:   for(itimes=1;itimes<=2;itimes++){
                   8942:     jj=0;
                   8943:     for(i=1; i <=nlstate; i++){
                   8944:       for(j=1; j <=nlstate+ndeath; j++){
                   8945:        if(j==i) continue;
                   8946:        for(k=1; k<=ncovmodel;k++){
                   8947:          jj++;
                   8948:          ca[0]= k+'a'-1;ca[1]='\0';
                   8949:          if(itimes==1){
                   8950:            printf("#%1d%1d%d",i,j,k);
                   8951:            fprintf(ficparo,"#%1d%1d%d",i,j,k);
                   8952:          }else{
                   8953:            printf("%1d%1d%d",i,j,k);
                   8954:            fprintf(ficparo,"%1d%1d%d",i,j,k);
                   8955:            /*  printf(" %.5le",matcov[i][j]); */
                   8956:          }
                   8957:          ll=0;
                   8958:          for(li=1;li <=nlstate; li++){
                   8959:            for(lj=1;lj <=nlstate+ndeath; lj++){
                   8960:              if(lj==li) continue;
                   8961:              for(lk=1;lk<=ncovmodel;lk++){
                   8962:                ll++;
                   8963:                if(ll<=jj){
                   8964:                  cb[0]= lk +'a'-1;cb[1]='\0';
                   8965:                  if(ll<jj){
                   8966:                    if(itimes==1){
                   8967:                      printf(" Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
                   8968:                      fprintf(ficparo," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
                   8969:                    }else{
                   8970:                      printf(" 0.");
                   8971:                      fprintf(ficparo," 0.");
                   8972:                    }
                   8973:                  }else{
                   8974:                    if(itimes==1){
                   8975:                      printf(" Var(%s%1d%1d)",ca,i,j);
                   8976:                      fprintf(ficparo," Var(%s%1d%1d)",ca,i,j);
                   8977:                    }else{
                   8978:                      printf(" 0.");
                   8979:                      fprintf(ficparo," 0.");
                   8980:                    }
                   8981:                  }
                   8982:                }
                   8983:              } /* end lk */
                   8984:            } /* end lj */
                   8985:          } /* end li */
                   8986:          printf("\n");
                   8987:          fprintf(ficparo,"\n");
                   8988:          numlinepar++;
                   8989:        } /* end k*/
                   8990:       } /*end j */
                   8991:     } /* end i */
                   8992:   } /* end itimes */
                   8993: 
                   8994: } /* end of prwizard */
                   8995: /******************* Gompertz Likelihood ******************************/
                   8996: double gompertz(double x[])
                   8997: { 
                   8998:   double A,B,L=0.0,sump=0.,num=0.;
                   8999:   int i,n=0; /* n is the size of the sample */
                   9000: 
1.220     brouard  9001:   for (i=1;i<=imx ; i++) {
1.126     brouard  9002:     sump=sump+weight[i];
                   9003:     /*    sump=sump+1;*/
                   9004:     num=num+1;
                   9005:   }
                   9006:  
                   9007:  
                   9008:   /* for (i=0; i<=imx; i++) 
                   9009:      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]);*/
                   9010: 
                   9011:   for (i=1;i<=imx ; i++)
                   9012:     {
                   9013:       if (cens[i] == 1 && wav[i]>1)
                   9014:        A=-x[1]/(x[2])*(exp(x[2]*(agecens[i]-agegomp))-exp(x[2]*(ageexmed[i]-agegomp)));
                   9015:       
                   9016:       if (cens[i] == 0 && wav[i]>1)
                   9017:        A=-x[1]/(x[2])*(exp(x[2]*(agedc[i]-agegomp))-exp(x[2]*(ageexmed[i]-agegomp)))
                   9018:             +log(x[1]/YEARM)+x[2]*(agedc[i]-agegomp)+log(YEARM);  
                   9019:       
                   9020:       /*if (wav[i] > 1 && agecens[i] > 15) {*/ /* ??? */
                   9021:       if (wav[i] > 1 ) { /* ??? */
                   9022:        L=L+A*weight[i];
                   9023:        /*      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]);*/
                   9024:       }
                   9025:     }
                   9026: 
                   9027:  /*printf("x1=%2.9f x2=%2.9f x3=%2.9f L=%f\n",x[1],x[2],x[3],L);*/
                   9028:  
                   9029:   return -2*L*num/sump;
                   9030: }
                   9031: 
1.136     brouard  9032: #ifdef GSL
                   9033: /******************* Gompertz_f Likelihood ******************************/
                   9034: double gompertz_f(const gsl_vector *v, void *params)
                   9035: { 
                   9036:   double A,B,LL=0.0,sump=0.,num=0.;
                   9037:   double *x= (double *) v->data;
                   9038:   int i,n=0; /* n is the size of the sample */
                   9039: 
                   9040:   for (i=0;i<=imx-1 ; i++) {
                   9041:     sump=sump+weight[i];
                   9042:     /*    sump=sump+1;*/
                   9043:     num=num+1;
                   9044:   }
                   9045:  
                   9046:  
                   9047:   /* for (i=0; i<=imx; i++) 
                   9048:      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]);*/
                   9049:   printf("x[0]=%lf x[1]=%lf\n",x[0],x[1]);
                   9050:   for (i=1;i<=imx ; i++)
                   9051:     {
                   9052:       if (cens[i] == 1 && wav[i]>1)
                   9053:        A=-x[0]/(x[1])*(exp(x[1]*(agecens[i]-agegomp))-exp(x[1]*(ageexmed[i]-agegomp)));
                   9054:       
                   9055:       if (cens[i] == 0 && wav[i]>1)
                   9056:        A=-x[0]/(x[1])*(exp(x[1]*(agedc[i]-agegomp))-exp(x[1]*(ageexmed[i]-agegomp)))
                   9057:             +log(x[0]/YEARM)+x[1]*(agedc[i]-agegomp)+log(YEARM);  
                   9058:       
                   9059:       /*if (wav[i] > 1 && agecens[i] > 15) {*/ /* ??? */
                   9060:       if (wav[i] > 1 ) { /* ??? */
                   9061:        LL=LL+A*weight[i];
                   9062:        /*      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]);*/
                   9063:       }
                   9064:     }
                   9065: 
                   9066:  /*printf("x1=%2.9f x2=%2.9f x3=%2.9f L=%f\n",x[1],x[2],x[3],L);*/
                   9067:   printf("x[0]=%lf x[1]=%lf -2*LL*num/sump=%lf\n",x[0],x[1],-2*LL*num/sump);
                   9068:  
                   9069:   return -2*LL*num/sump;
                   9070: }
                   9071: #endif
                   9072: 
1.126     brouard  9073: /******************* Printing html file ***********/
1.201     brouard  9074: void printinghtmlmort(char fileresu[], char title[], char datafile[], int firstpass, \
1.126     brouard  9075:                  int lastpass, int stepm, int weightopt, char model[],\
                   9076:                  int imx,  double p[],double **matcov,double agemortsup){
                   9077:   int i,k;
                   9078: 
                   9079:   fprintf(fichtm,"<ul><li><h4>Result files </h4>\n Force of mortality. Parameters of the Gompertz fit (with confidence interval in brackets):<br>");
                   9080:   fprintf(fichtm,"  mu(age) =%lf*exp(%lf*(age-%d)) per year<br><br>",p[1],p[2],agegomp);
                   9081:   for (i=1;i<=2;i++) 
                   9082:     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  9083:   fprintf(fichtm,"<br><br><img src=\"graphmort.svg\">");
1.126     brouard  9084:   fprintf(fichtm,"</ul>");
                   9085: 
                   9086: fprintf(fichtm,"<ul><li><h4>Life table</h4>\n <br>");
                   9087: 
                   9088:  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>");
                   9089: 
                   9090:  for (k=agegomp;k<(agemortsup-2);k++) 
                   9091:    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]);
                   9092: 
                   9093:  
                   9094:   fflush(fichtm);
                   9095: }
                   9096: 
                   9097: /******************* Gnuplot file **************/
1.201     brouard  9098: void printinggnuplotmort(char fileresu[], char optionfilefiname[], double ageminpar, double agemaxpar, double fage , char pathc[], double p[]){
1.126     brouard  9099: 
                   9100:   char dirfileres[132],optfileres[132];
1.164     brouard  9101: 
1.126     brouard  9102:   int ng;
                   9103: 
                   9104: 
                   9105:   /*#ifdef windows */
                   9106:   fprintf(ficgp,"cd \"%s\" \n",pathc);
                   9107:     /*#endif */
                   9108: 
                   9109: 
                   9110:   strcpy(dirfileres,optionfilefiname);
                   9111:   strcpy(optfileres,"vpl");
1.199     brouard  9112:   fprintf(ficgp,"set out \"graphmort.svg\"\n "); 
1.126     brouard  9113:   fprintf(ficgp,"set xlabel \"Age\"\n set ylabel \"Force of mortality (per year)\" \n "); 
1.199     brouard  9114:   fprintf(ficgp, "set ter svg size 640, 480\n set log y\n"); 
1.145     brouard  9115:   /* fprintf(ficgp, "set size 0.65,0.65\n"); */
1.126     brouard  9116:   fprintf(ficgp,"plot [%d:100] %lf*exp(%lf*(x-%d))",agegomp,p[1],p[2],agegomp);
                   9117: 
                   9118: } 
                   9119: 
1.136     brouard  9120: int readdata(char datafile[], int firstobs, int lastobs, int *imax)
                   9121: {
1.126     brouard  9122: 
1.136     brouard  9123:   /*-------- data file ----------*/
                   9124:   FILE *fic;
                   9125:   char dummy[]="                         ";
1.240     brouard  9126:   int i=0, j=0, n=0, iv=0, v;
1.223     brouard  9127:   int lstra;
1.136     brouard  9128:   int linei, month, year,iout;
                   9129:   char line[MAXLINE], linetmp[MAXLINE];
1.164     brouard  9130:   char stra[MAXLINE], strb[MAXLINE];
1.136     brouard  9131:   char *stratrunc;
1.223     brouard  9132: 
1.240     brouard  9133:   DummyV=ivector(1,NCOVMAX); /* 1 to 3 */
                   9134:   FixedV=ivector(1,NCOVMAX); /* 1 to 3 */
1.126     brouard  9135: 
1.240     brouard  9136:   for(v=1; v <=ncovcol;v++){
                   9137:     DummyV[v]=0;
                   9138:     FixedV[v]=0;
                   9139:   }
                   9140:   for(v=ncovcol+1; v <=ncovcol+nqv;v++){
                   9141:     DummyV[v]=1;
                   9142:     FixedV[v]=0;
                   9143:   }
                   9144:   for(v=ncovcol+nqv+1; v <=ncovcol+nqv+ntv;v++){
                   9145:     DummyV[v]=0;
                   9146:     FixedV[v]=1;
                   9147:   }
                   9148:   for(v=ncovcol+nqv+ntv+1; v <=ncovcol+nqv+ntv+nqtv;v++){
                   9149:     DummyV[v]=1;
                   9150:     FixedV[v]=1;
                   9151:   }
                   9152:   for(v=1; v <=ncovcol+nqv+ntv+nqtv;v++){
                   9153:     printf("Covariate type in the data: V%d, DummyV(V%d)=%d, FixedV(V%d)=%d\n",v,v,DummyV[v],v,FixedV[v]);
                   9154:     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]);
                   9155:   }
1.126     brouard  9156: 
1.136     brouard  9157:   if((fic=fopen(datafile,"r"))==NULL)    {
1.218     brouard  9158:     printf("Problem while opening datafile: %s with errno='%s'\n", datafile,strerror(errno));fflush(stdout);
                   9159:     fprintf(ficlog,"Problem while opening datafile: %s with errno='%s'\n", datafile,strerror(errno));fflush(ficlog);return 1;
1.136     brouard  9160:   }
1.126     brouard  9161: 
1.136     brouard  9162:   i=1;
                   9163:   linei=0;
                   9164:   while ((fgets(line, MAXLINE, fic) != NULL) &&((i >= firstobs) && (i <=lastobs))) {
                   9165:     linei=linei+1;
                   9166:     for(j=strlen(line); j>=0;j--){  /* Untabifies line */
                   9167:       if(line[j] == '\t')
                   9168:        line[j] = ' ';
                   9169:     }
                   9170:     for(j=strlen(line)-1; (line[j]==' ')||(line[j]==10)||(line[j]==13);j--){
                   9171:       ;
                   9172:     };
                   9173:     line[j+1]=0;  /* Trims blanks at end of line */
                   9174:     if(line[0]=='#'){
                   9175:       fprintf(ficlog,"Comment line\n%s\n",line);
                   9176:       printf("Comment line\n%s\n",line);
                   9177:       continue;
                   9178:     }
                   9179:     trimbb(linetmp,line); /* Trims multiple blanks in line */
1.164     brouard  9180:     strcpy(line, linetmp);
1.223     brouard  9181:     
                   9182:     /* Loops on waves */
                   9183:     for (j=maxwav;j>=1;j--){
                   9184:       for (iv=nqtv;iv>=1;iv--){  /* Loop  on time varying quantitative variables */
1.238     brouard  9185:        cutv(stra, strb, line, ' '); 
                   9186:        if(strb[0]=='.') { /* Missing value */
                   9187:          lval=-1;
                   9188:          cotqvar[j][iv][i]=-1; /* 0.0/0.0 */
                   9189:          cotvar[j][ntv+iv][i]=-1; /* For performance reasons */
                   9190:          if(isalpha(strb[1])) { /* .m or .d Really Missing value */
                   9191:            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);
                   9192:            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);
                   9193:            return 1;
                   9194:          }
                   9195:        }else{
                   9196:          errno=0;
                   9197:          /* what_kind_of_number(strb); */
                   9198:          dval=strtod(strb,&endptr); 
                   9199:          /* if( strb[0]=='\0' || (*endptr != '\0')){ */
                   9200:          /* if(strb != endptr && *endptr == '\0') */
                   9201:          /*    dval=dlval; */
                   9202:          /* if (errno == ERANGE && (lval == LONG_MAX || lval == LONG_MIN)) */
                   9203:          if( strb[0]=='\0' || (*endptr != '\0')){
                   9204:            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);
                   9205:            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);
                   9206:            return 1;
                   9207:          }
                   9208:          cotqvar[j][iv][i]=dval; 
                   9209:          cotvar[j][ntv+iv][i]=dval; 
                   9210:        }
                   9211:        strcpy(line,stra);
1.223     brouard  9212:       }/* end loop ntqv */
1.225     brouard  9213:       
1.223     brouard  9214:       for (iv=ntv;iv>=1;iv--){  /* Loop  on time varying dummies */
1.238     brouard  9215:        cutv(stra, strb, line, ' '); 
                   9216:        if(strb[0]=='.') { /* Missing value */
                   9217:          lval=-1;
                   9218:        }else{
                   9219:          errno=0;
                   9220:          lval=strtol(strb,&endptr,10); 
                   9221:          /*    if (errno == ERANGE && (lval == LONG_MAX || lval == LONG_MIN))*/
                   9222:          if( strb[0]=='\0' || (*endptr != '\0')){
                   9223:            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);
                   9224:            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);
                   9225:            return 1;
                   9226:          }
                   9227:        }
                   9228:        if(lval <-1 || lval >1){
                   9229:          printf("Error reading data around '%ld' at line number %d for individual %d, '%s'\n \
1.223     brouard  9230:  Should be a value of %d(nth) covariate (0 should be the value for the reference and 1\n \
                   9231:  for the alternative. IMaCh does not build design variables automatically, do it yourself.\n \
1.238     brouard  9232:  For example, for multinomial values like 1, 2 and 3,\n                        \
                   9233:  build V1=0 V2=0 for the reference value (1),\n                                \
                   9234:         V1=1 V2=0 for (2) \n                                           \
1.223     brouard  9235:  and V1=0 V2=1 for (3). V1=1 V2=1 should not exist and the corresponding\n \
1.238     brouard  9236:  output of IMaCh is often meaningless.\n                               \
1.223     brouard  9237:  Exiting.\n",lval,linei, i,line,j);
1.238     brouard  9238:          fprintf(ficlog,"Error reading data around '%ld' at line number %d for individual %d, '%s'\n \
1.223     brouard  9239:  Should be a value of %d(nth) covariate (0 should be the value for the reference and 1\n \
                   9240:  for the alternative. IMaCh does not build design variables automatically, do it yourself.\n \
1.238     brouard  9241:  For example, for multinomial values like 1, 2 and 3,\n                        \
                   9242:  build V1=0 V2=0 for the reference value (1),\n                                \
                   9243:         V1=1 V2=0 for (2) \n                                           \
1.223     brouard  9244:  and V1=0 V2=1 for (3). V1=1 V2=1 should not exist and the corresponding\n \
1.238     brouard  9245:  output of IMaCh is often meaningless.\n                               \
1.223     brouard  9246:  Exiting.\n",lval,linei, i,line,j);fflush(ficlog);
1.238     brouard  9247:          return 1;
                   9248:        }
                   9249:        cotvar[j][iv][i]=(double)(lval);
                   9250:        strcpy(line,stra);
1.223     brouard  9251:       }/* end loop ntv */
1.225     brouard  9252:       
1.223     brouard  9253:       /* Statuses  at wave */
1.137     brouard  9254:       cutv(stra, strb, line, ' '); 
1.223     brouard  9255:       if(strb[0]=='.') { /* Missing value */
1.238     brouard  9256:        lval=-1;
1.136     brouard  9257:       }else{
1.238     brouard  9258:        errno=0;
                   9259:        lval=strtol(strb,&endptr,10); 
                   9260:        /*      if (errno == ERANGE && (lval == LONG_MAX || lval == LONG_MIN))*/
                   9261:        if( strb[0]=='\0' || (*endptr != '\0')){
                   9262:          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);
                   9263:          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);
                   9264:          return 1;
                   9265:        }
1.136     brouard  9266:       }
1.225     brouard  9267:       
1.136     brouard  9268:       s[j][i]=lval;
1.225     brouard  9269:       
1.223     brouard  9270:       /* Date of Interview */
1.136     brouard  9271:       strcpy(line,stra);
                   9272:       cutv(stra, strb,line,' ');
1.169     brouard  9273:       if( (iout=sscanf(strb,"%d/%d",&month, &year)) != 0){
1.136     brouard  9274:       }
1.169     brouard  9275:       else  if( (iout=sscanf(strb,"%s.",dummy)) != 0){
1.225     brouard  9276:        month=99;
                   9277:        year=9999;
1.136     brouard  9278:       }else{
1.225     brouard  9279:        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);
                   9280:        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);
                   9281:        return 1;
1.136     brouard  9282:       }
                   9283:       anint[j][i]= (double) year; 
                   9284:       mint[j][i]= (double)month; 
                   9285:       strcpy(line,stra);
1.223     brouard  9286:     } /* End loop on waves */
1.225     brouard  9287:     
1.223     brouard  9288:     /* Date of death */
1.136     brouard  9289:     cutv(stra, strb,line,' '); 
1.169     brouard  9290:     if( (iout=sscanf(strb,"%d/%d",&month, &year)) != 0){
1.136     brouard  9291:     }
1.169     brouard  9292:     else  if( (iout=sscanf(strb,"%s.",dummy)) != 0){
1.136     brouard  9293:       month=99;
                   9294:       year=9999;
                   9295:     }else{
1.141     brouard  9296:       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  9297:       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);
                   9298:       return 1;
1.136     brouard  9299:     }
                   9300:     andc[i]=(double) year; 
                   9301:     moisdc[i]=(double) month; 
                   9302:     strcpy(line,stra);
                   9303:     
1.223     brouard  9304:     /* Date of birth */
1.136     brouard  9305:     cutv(stra, strb,line,' '); 
1.169     brouard  9306:     if( (iout=sscanf(strb,"%d/%d",&month, &year)) != 0){
1.136     brouard  9307:     }
1.169     brouard  9308:     else  if( (iout=sscanf(strb,"%s.", dummy)) != 0){
1.136     brouard  9309:       month=99;
                   9310:       year=9999;
                   9311:     }else{
1.141     brouard  9312:       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);
                   9313:       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  9314:       return 1;
1.136     brouard  9315:     }
                   9316:     if (year==9999) {
1.141     brouard  9317:       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);
                   9318:       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  9319:       return 1;
                   9320:       
1.136     brouard  9321:     }
                   9322:     annais[i]=(double)(year);
                   9323:     moisnais[i]=(double)(month); 
                   9324:     strcpy(line,stra);
1.225     brouard  9325:     
1.223     brouard  9326:     /* Sample weight */
1.136     brouard  9327:     cutv(stra, strb,line,' '); 
                   9328:     errno=0;
                   9329:     dval=strtod(strb,&endptr); 
                   9330:     if( strb[0]=='\0' || (*endptr != '\0')){
1.141     brouard  9331:       printf("Error reading data around '%f' at line number %d, \"%s\" for individual %d\nShould be a weight.  Exiting.\n",dval, i,line,linei);
                   9332:       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  9333:       fflush(ficlog);
                   9334:       return 1;
                   9335:     }
                   9336:     weight[i]=dval; 
                   9337:     strcpy(line,stra);
1.225     brouard  9338:     
1.223     brouard  9339:     for (iv=nqv;iv>=1;iv--){  /* Loop  on fixed quantitative variables */
                   9340:       cutv(stra, strb, line, ' '); 
                   9341:       if(strb[0]=='.') { /* Missing value */
1.225     brouard  9342:        lval=-1;
1.223     brouard  9343:       }else{
1.225     brouard  9344:        errno=0;
                   9345:        /* what_kind_of_number(strb); */
                   9346:        dval=strtod(strb,&endptr);
                   9347:        /* if(strb != endptr && *endptr == '\0') */
                   9348:        /*   dval=dlval; */
                   9349:        /* if (errno == ERANGE && (lval == LONG_MAX || lval == LONG_MIN)) */
                   9350:        if( strb[0]=='\0' || (*endptr != '\0')){
                   9351:          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);
                   9352:          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);
                   9353:          return 1;
                   9354:        }
                   9355:        coqvar[iv][i]=dval; 
1.226     brouard  9356:        covar[ncovcol+iv][i]=dval; /* including qvar in standard covar for performance reasons */ 
1.223     brouard  9357:       }
                   9358:       strcpy(line,stra);
                   9359:     }/* end loop nqv */
1.136     brouard  9360:     
1.223     brouard  9361:     /* Covariate values */
1.136     brouard  9362:     for (j=ncovcol;j>=1;j--){
                   9363:       cutv(stra, strb,line,' '); 
1.223     brouard  9364:       if(strb[0]=='.') { /* Missing covariate value */
1.225     brouard  9365:        lval=-1;
1.136     brouard  9366:       }else{
1.225     brouard  9367:        errno=0;
                   9368:        lval=strtol(strb,&endptr,10); 
                   9369:        if( strb[0]=='\0' || (*endptr != '\0')){
                   9370:          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);
                   9371:          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);
                   9372:          return 1;
                   9373:        }
1.136     brouard  9374:       }
                   9375:       if(lval <-1 || lval >1){
1.225     brouard  9376:        printf("Error reading data around '%ld' at line number %d for individual %d, '%s'\n \
1.136     brouard  9377:  Should be a value of %d(nth) covariate (0 should be the value for the reference and 1\n \
                   9378:  for the alternative. IMaCh does not build design variables automatically, do it yourself.\n \
1.225     brouard  9379:  For example, for multinomial values like 1, 2 and 3,\n                        \
                   9380:  build V1=0 V2=0 for the reference value (1),\n                                \
                   9381:         V1=1 V2=0 for (2) \n                                           \
1.136     brouard  9382:  and V1=0 V2=1 for (3). V1=1 V2=1 should not exist and the corresponding\n \
1.225     brouard  9383:  output of IMaCh is often meaningless.\n                               \
1.136     brouard  9384:  Exiting.\n",lval,linei, i,line,j);
1.225     brouard  9385:        fprintf(ficlog,"Error reading data around '%ld' at line number %d for individual %d, '%s'\n \
1.136     brouard  9386:  Should be a value of %d(nth) covariate (0 should be the value for the reference and 1\n \
                   9387:  for the alternative. IMaCh does not build design variables automatically, do it yourself.\n \
1.225     brouard  9388:  For example, for multinomial values like 1, 2 and 3,\n                        \
                   9389:  build V1=0 V2=0 for the reference value (1),\n                                \
                   9390:         V1=1 V2=0 for (2) \n                                           \
1.136     brouard  9391:  and V1=0 V2=1 for (3). V1=1 V2=1 should not exist and the corresponding\n \
1.225     brouard  9392:  output of IMaCh is often meaningless.\n                               \
1.136     brouard  9393:  Exiting.\n",lval,linei, i,line,j);fflush(ficlog);
1.225     brouard  9394:        return 1;
1.136     brouard  9395:       }
                   9396:       covar[j][i]=(double)(lval);
                   9397:       strcpy(line,stra);
                   9398:     }  
                   9399:     lstra=strlen(stra);
1.225     brouard  9400:     
1.136     brouard  9401:     if(lstra > 9){ /* More than 2**32 or max of what printf can write with %ld */
                   9402:       stratrunc = &(stra[lstra-9]);
                   9403:       num[i]=atol(stratrunc);
                   9404:     }
                   9405:     else
                   9406:       num[i]=atol(stra);
                   9407:     /*if((s[2][i]==2) && (s[3][i]==-1)&&(s[4][i]==9)){
                   9408:       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;}*/
                   9409:     
                   9410:     i=i+1;
                   9411:   } /* End loop reading  data */
1.225     brouard  9412:   
1.136     brouard  9413:   *imax=i-1; /* Number of individuals */
                   9414:   fclose(fic);
1.225     brouard  9415:   
1.136     brouard  9416:   return (0);
1.164     brouard  9417:   /* endread: */
1.225     brouard  9418:   printf("Exiting readdata: ");
                   9419:   fclose(fic);
                   9420:   return (1);
1.223     brouard  9421: }
1.126     brouard  9422: 
1.234     brouard  9423: void removefirstspace(char **stri){/*, char stro[]) {*/
1.230     brouard  9424:   char *p1 = *stri, *p2 = *stri;
1.235     brouard  9425:   while (*p2 == ' ')
1.234     brouard  9426:     p2++; 
                   9427:   /* while ((*p1++ = *p2++) !=0) */
                   9428:   /*   ; */
                   9429:   /* do */
                   9430:   /*   while (*p2 == ' ') */
                   9431:   /*     p2++; */
                   9432:   /* while (*p1++ == *p2++); */
                   9433:   *stri=p2; 
1.145     brouard  9434: }
                   9435: 
1.235     brouard  9436: int decoderesult ( char resultline[], int nres)
1.230     brouard  9437: /**< This routine decode one result line and returns the combination # of dummy covariates only **/
                   9438: {
1.235     brouard  9439:   int j=0, k=0, k1=0, k2=0, k3=0, k4=0, match=0, k2q=0, k3q=0, k4q=0;
1.230     brouard  9440:   char resultsav[MAXLINE];
1.234     brouard  9441:   int resultmodel[MAXLINE];
                   9442:   int modelresult[MAXLINE];
1.230     brouard  9443:   char stra[80], strb[80], strc[80], strd[80],stre[80];
                   9444: 
1.234     brouard  9445:   removefirstspace(&resultline);
1.233     brouard  9446:   printf("decoderesult:%s\n",resultline);
1.230     brouard  9447: 
                   9448:   if (strstr(resultline,"v") !=0){
                   9449:     printf("Error. 'v' must be in upper case 'V' result: %s ",resultline);
                   9450:     fprintf(ficlog,"Error. 'v' must be in upper case result: %s ",resultline);fflush(ficlog);
                   9451:     return 1;
                   9452:   }
                   9453:   trimbb(resultsav, resultline);
                   9454:   if (strlen(resultsav) >1){
                   9455:     j=nbocc(resultsav,'='); /**< j=Number of covariate values'=' */
                   9456:   }
1.253     brouard  9457:   if(j == 0){ /* Resultline but no = */
                   9458:     TKresult[nres]=0; /* Combination for the nresult and the model */
                   9459:     return (0);
                   9460:   }
                   9461:     
1.234     brouard  9462:   if( j != cptcovs ){ /* Be careful if a variable is in a product but not single */
                   9463:     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);
                   9464:     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);
                   9465:   }
                   9466:   for(k=1; k<=j;k++){ /* Loop on any covariate of the result line */
                   9467:     if(nbocc(resultsav,'=') >1){
                   9468:        cutl(stra,strb,resultsav,' '); /* keeps in strb after the first ' ' 
                   9469:                                      resultsav= V4=1 V5=25.1 V3=0 strb=V3=0 stra= V4=1 V5=25.1 */
                   9470:        cutl(strc,strd,strb,'=');  /* strb:V4=1 strc=1 strd=V4 */
                   9471:     }else
                   9472:       cutl(strc,strd,resultsav,'=');
1.230     brouard  9473:     Tvalsel[k]=atof(strc); /* 1 */
1.234     brouard  9474:     
1.230     brouard  9475:     cutl(strc,stre,strd,'V'); /* strd='V4' strc=4 stre='V' */;
                   9476:     Tvarsel[k]=atoi(strc);
                   9477:     /* Typevarsel[k]=1;  /\* 1 for age product *\/ */
                   9478:     /* cptcovsel++;     */
                   9479:     if (nbocc(stra,'=') >0)
                   9480:       strcpy(resultsav,stra); /* and analyzes it */
                   9481:   }
1.235     brouard  9482:   /* Checking for missing or useless values in comparison of current model needs */
1.236     brouard  9483:   for(k1=1; k1<= cptcovt ;k1++){ /* model line V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
                   9484:     if(Typevar[k1]==0){ /* Single covariate in model */
1.234     brouard  9485:       match=0;
1.236     brouard  9486:       for(k2=1; k2 <=j;k2++){/* result line V4=1 V5=24.1 V3=1  V2=8 V1=0 */
1.237     brouard  9487:        if(Tvar[k1]==Tvarsel[k2]) {/* Tvar[1]=5 == Tvarsel[2]=5   */
1.236     brouard  9488:          modelresult[k2]=k1;/* modelresult[2]=1 modelresult[1]=2  modelresult[3]=3  modelresult[6]=4 modelresult[9]=5 */
1.234     brouard  9489:          match=1;
                   9490:          break;
                   9491:        }
                   9492:       }
                   9493:       if(match == 0){
                   9494:        printf("Error in result line: %d value missing; result: %s, model=%s\n",k1, resultline, model);
                   9495:       }
                   9496:     }
                   9497:   }
1.235     brouard  9498:   /* Checking for missing or useless values in comparison of current model needs */
                   9499:   for(k2=1; k2 <=j;k2++){ /* result line V4=1 V5=24.1 V3=1  V2=8 V1=0 */
1.234     brouard  9500:     match=0;
1.235     brouard  9501:     for(k1=1; k1<= cptcovt ;k1++){ /* model line V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
                   9502:       if(Typevar[k1]==0){ /* Single */
1.237     brouard  9503:        if(Tvar[k1]==Tvarsel[k2]) { /* Tvar[2]=4 == Tvarsel[1]=4   */
1.235     brouard  9504:          resultmodel[k1]=k2;  /* resultmodel[2]=1 resultmodel[1]=2  resultmodel[3]=3  resultmodel[6]=4 resultmodel[9]=5 */
1.234     brouard  9505:          ++match;
                   9506:        }
                   9507:       }
                   9508:     }
                   9509:     if(match == 0){
                   9510:       printf("Error in result line: %d value missing; result: %s, model=%s\n",k1, resultline, model);
                   9511:     }else if(match > 1){
                   9512:       printf("Error in result line: %d doubled; result: %s, model=%s\n",k2, resultline, model);
                   9513:     }
                   9514:   }
1.235     brouard  9515:       
1.234     brouard  9516:   /* We need to deduce which combination number is chosen and save quantitative values */
1.235     brouard  9517:   /* model line V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
                   9518:   /* result line V4=1 V5=25.1 V3=0  V2=8 V1=1 */
                   9519:   /* should give a combination of dummy V4=1, V3=0, V1=1 => V4*2**(0) + V3*2**(1) + V1*2**(2) = 5 + (1offset) = 6*/
                   9520:   /* result line V4=1 V5=24.1 V3=1  V2=8 V1=0 */
                   9521:   /* should give a combination of dummy V4=1, V3=1, V1=0 => V4*2**(0) + V3*2**(1) + V1*2**(2) = 3 + (1offset) = 4*/
                   9522:   /*    1 0 0 0 */
                   9523:   /*    2 1 0 0 */
                   9524:   /*    3 0 1 0 */ 
                   9525:   /*    4 1 1 0 */ /* V4=1, V3=1, V1=0 */
                   9526:   /*    5 0 0 1 */
                   9527:   /*    6 1 0 1 */ /* V4=1, V3=0, V1=1 */
                   9528:   /*    7 0 1 1 */
                   9529:   /*    8 1 1 1 */
1.237     brouard  9530:   /* V(Tvresult)=Tresult V4=1 V3=0 V1=1 Tresult[nres=1][2]=0 */
                   9531:   /* V(Tvqresult)=Tqresult V5=25.1 V2=8 Tqresult[nres=1][1]=25.1 */
                   9532:   /* V5*age V5 known which value for nres?  */
                   9533:   /* Tqinvresult[2]=8 Tqinvresult[1]=25.1  */
1.235     brouard  9534:   for(k1=1, k=0, k4=0, k4q=0; k1 <=cptcovt;k1++){ /* model line */
                   9535:     if( Dummy[k1]==0 && Typevar[k1]==0 ){ /* Single dummy */
1.237     brouard  9536:       k3= resultmodel[k1]; /* resultmodel[2(V4)] = 1=k3 */
1.235     brouard  9537:       k2=(int)Tvarsel[k3]; /*  Tvarsel[resultmodel[2]]= Tvarsel[1] = 4=k2 */
                   9538:       k+=Tvalsel[k3]*pow(2,k4);  /*  Tvalsel[1]=1  */
1.237     brouard  9539:       Tresult[nres][k4+1]=Tvalsel[k3];/* Tresult[nres][1]=1(V4=1)  Tresult[nres][2]=0(V3=0) */
                   9540:       Tvresult[nres][k4+1]=(int)Tvarsel[k3];/* Tvresult[nres][1]=4 Tvresult[nres][3]=1 */
                   9541:       Tinvresult[nres][(int)Tvarsel[k3]]=Tvalsel[k3]; /* Tinvresult[nres][4]=1 */
1.235     brouard  9542:       printf("Decoderesult Dummy k=%d, V(k2=V%d)= Tvalsel[%d]=%d, 2**(%d)\n",k, k2, k3, (int)Tvalsel[k3], k4);
                   9543:       k4++;;
                   9544:     }  else if( Dummy[k1]==1 && Typevar[k1]==0 ){ /* Single quantitative */
                   9545:       k3q= resultmodel[k1]; /* resultmodel[2] = 1=k3 */
                   9546:       k2q=(int)Tvarsel[k3q]; /*  Tvarsel[resultmodel[2]]= Tvarsel[1] = 4=k2 */
1.237     brouard  9547:       Tqresult[nres][k4q+1]=Tvalsel[k3q]; /* Tqresult[nres][1]=25.1 */
                   9548:       Tvqresult[nres][k4q+1]=(int)Tvarsel[k3q]; /* Tvqresult[nres][1]=5 */
                   9549:       Tqinvresult[nres][(int)Tvarsel[k3q]]=Tvalsel[k3q]; /* Tqinvresult[nres][5]=25.1 */
1.235     brouard  9550:       printf("Decoderesult Quantitative nres=%d, V(k2q=V%d)= Tvalsel[%d]=%d, Tvarsel[%d]=%f\n",nres, k2q, k3q, Tvarsel[k3q], k3q, Tvalsel[k3q]);
                   9551:       k4q++;;
                   9552:     }
                   9553:   }
1.234     brouard  9554:   
1.235     brouard  9555:   TKresult[nres]=++k; /* Combination for the nresult and the model */
1.230     brouard  9556:   return (0);
                   9557: }
1.235     brouard  9558: 
1.230     brouard  9559: int decodemodel( char model[], int lastobs)
                   9560:  /**< This routine decodes the model and returns:
1.224     brouard  9561:        * Model  V1+V2+V3+V8+V7*V8+V5*V6+V8*age+V3*age+age*age
                   9562:        * - nagesqr = 1 if age*age in the model, otherwise 0.
                   9563:        * - cptcovt total number of covariates of the model nbocc(+)+1 = 8 excepting constant and age and age*age
                   9564:        * - cptcovn or number of covariates k of the models excluding age*products =6 and age*age
                   9565:        * - cptcovage number of covariates with age*products =2
                   9566:        * - cptcovs number of simple covariates
                   9567:        * - 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
                   9568:        *     which is a new column after the 9 (ncovcol) variables. 
                   9569:        * - if k is a product Vn*Vm covar[k][i] is filled with correct values for each individual
                   9570:        * - Tprod[l] gives the kth covariates of the product Vn*Vm l=1 to cptcovprod-cptcovage
                   9571:        *    Tprod[1]@2 {5, 6}: position of first product V7*V8 is 5, and second V5*V6 is 6.
                   9572:        * - Tvard[k]  p Tvard[1][1]@4 {7, 8, 5, 6} for V7*V8 and V5*V6 .
                   9573:        */
1.136     brouard  9574: {
1.238     brouard  9575:   int i, j, k, ks, v;
1.227     brouard  9576:   int  j1, k1, k2, k3, k4;
1.136     brouard  9577:   char modelsav[80];
1.145     brouard  9578:   char stra[80], strb[80], strc[80], strd[80],stre[80];
1.187     brouard  9579:   char *strpt;
1.136     brouard  9580: 
1.145     brouard  9581:   /*removespace(model);*/
1.136     brouard  9582:   if (strlen(model) >1){ /* If there is at least 1 covariate */
1.145     brouard  9583:     j=0, j1=0, k1=0, k2=-1, ks=0, cptcovn=0;
1.137     brouard  9584:     if (strstr(model,"AGE") !=0){
1.192     brouard  9585:       printf("Error. AGE must be in lower case 'age' model=1+age+%s. ",model);
                   9586:       fprintf(ficlog,"Error. AGE must be in lower case model=1+age+%s. ",model);fflush(ficlog);
1.136     brouard  9587:       return 1;
                   9588:     }
1.141     brouard  9589:     if (strstr(model,"v") !=0){
                   9590:       printf("Error. 'v' must be in upper case 'V' model=%s ",model);
                   9591:       fprintf(ficlog,"Error. 'v' must be in upper case model=%s ",model);fflush(ficlog);
                   9592:       return 1;
                   9593:     }
1.187     brouard  9594:     strcpy(modelsav,model); 
                   9595:     if ((strpt=strstr(model,"age*age")) !=0){
                   9596:       printf(" strpt=%s, model=%s\n",strpt, model);
                   9597:       if(strpt != model){
1.234     brouard  9598:        printf("Error in model: 'model=%s'; 'age*age' should in first place before other covariates\n \
1.192     brouard  9599:  'model=1+age+age*age+V1.' or 'model=1+age+age*age+V1+V1*age.', please swap as well as \n \
1.187     brouard  9600:  corresponding column of parameters.\n",model);
1.234     brouard  9601:        fprintf(ficlog,"Error in model: 'model=%s'; 'age*age' should in first place before other covariates\n \
1.192     brouard  9602:  'model=1+age+age*age+V1.' or 'model=1+age+age*age+V1+V1*age.', please swap as well as \n \
1.187     brouard  9603:  corresponding column of parameters.\n",model); fflush(ficlog);
1.234     brouard  9604:        return 1;
1.225     brouard  9605:       }
1.187     brouard  9606:       nagesqr=1;
                   9607:       if (strstr(model,"+age*age") !=0)
1.234     brouard  9608:        substrchaine(modelsav, model, "+age*age");
1.187     brouard  9609:       else if (strstr(model,"age*age+") !=0)
1.234     brouard  9610:        substrchaine(modelsav, model, "age*age+");
1.187     brouard  9611:       else 
1.234     brouard  9612:        substrchaine(modelsav, model, "age*age");
1.187     brouard  9613:     }else
                   9614:       nagesqr=0;
                   9615:     if (strlen(modelsav) >1){
                   9616:       j=nbocc(modelsav,'+'); /**< j=Number of '+' */
                   9617:       j1=nbocc(modelsav,'*'); /**< j1=Number of '*' */
1.224     brouard  9618:       cptcovs=j+1-j1; /**<  Number of simple covariates V1+V1*age+V3 +V3*V4+age*age=> V1 + V3 =5-3=2  */
1.187     brouard  9619:       cptcovt= j+1; /* Number of total covariates in the model, not including
1.225     brouard  9620:                     * cst, age and age*age 
                   9621:                     * V1+V1*age+ V3 + V3*V4+age*age=> 3+1=4*/
                   9622:       /* including age products which are counted in cptcovage.
                   9623:        * but the covariates which are products must be treated 
                   9624:        * separately: ncovn=4- 2=2 (V1+V3). */
1.187     brouard  9625:       cptcovprod=j1; /**< Number of products  V1*V2 +v3*age = 2 */
                   9626:       cptcovprodnoage=0; /**< Number of covariate products without age: V3*V4 =1  */
1.225     brouard  9627:       
                   9628:       
1.187     brouard  9629:       /*   Design
                   9630:        *  V1   V2   V3   V4  V5  V6  V7  V8  V9 Weight
                   9631:        *  <          ncovcol=8                >
                   9632:        * Model V2 + V1 + V3*age + V3 + V5*V6 + V7*V8 + V8*age + V8
                   9633:        *   k=  1    2      3       4     5       6      7        8
                   9634:        *  cptcovn number of covariates (not including constant and age ) = # of + plus 1 = 7+1=8
                   9635:        *  covar[k,i], value of kth covariate if not including age for individual i:
1.224     brouard  9636:        *       covar[1][i]= (V1), covar[4][i]=(V4), covar[8][i]=(V8)
                   9637:        *  Tvar[k] # of the kth covariate:  Tvar[1]=2  Tvar[2]=1 Tvar[4]=3 Tvar[8]=8
1.187     brouard  9638:        *       if multiplied by age: V3*age Tvar[3=V3*age]=3 (V3) Tvar[7]=8 and 
                   9639:        *  Tage[++cptcovage]=k
                   9640:        *       if products, new covar are created after ncovcol with k1
                   9641:        *  Tvar[k]=ncovcol+k1; # of the kth covariate product:  Tvar[5]=ncovcol+1=10  Tvar[6]=ncovcol+1=11
                   9642:        *  Tprod[k1]=k; Tprod[1]=5 Tprod[2]= 6; gives the position of the k1th product
                   9643:        *  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
                   9644:        *  Tvar[cptcovn+k2]=Tvard[k1][1];Tvar[cptcovn+k2+1]=Tvard[k1][2];
                   9645:        *  Tvar[8+1]=5;Tvar[8+2]=6;Tvar[8+3]=7;Tvar[8+4]=8 inverted
                   9646:        *  V1   V2   V3   V4  V5  V6  V7  V8  V9  V10  V11
                   9647:        *  <          ncovcol=8                >
                   9648:        *       Model V2 + V1 + V3*age + V3 + V5*V6 + V7*V8 + V8*age + V8    d1   d1   d2  d2
                   9649:        *          k=  1    2      3       4     5       6      7        8    9   10   11  12
                   9650:        *     Tvar[k]= 2    1      3       3    10      11      8        8    5    6    7   8
                   9651:        * p Tvar[1]@12={2,   1,     3,      3,   11,     10,     8,       8,   7,   8,   5,  6}
                   9652:        * p Tprod[1]@2={                         6, 5}
                   9653:        *p Tvard[1][1]@4= {7, 8, 5, 6}
                   9654:        * covar[k][i]= V2   V1      ?      V3    V5*V6?   V7*V8?  ?       V8   
                   9655:        *  cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];
                   9656:        *How to reorganize?
                   9657:        * Model V1 + V2 + V3 + V8 + V5*V6 + V7*V8 + V3*age + V8*age
                   9658:        * Tvars {2,   1,     3,      3,   11,     10,     8,       8,   7,   8,   5,  6}
                   9659:        *       {2,   1,     4,      8,    5,      6,     3,       7}
                   9660:        * Struct []
                   9661:        */
1.225     brouard  9662:       
1.187     brouard  9663:       /* This loop fills the array Tvar from the string 'model'.*/
                   9664:       /* j is the number of + signs in the model V1+V2+V3 j=2 i=3 to 1 */
                   9665:       /*   modelsav=V2+V1+V4+age*V3 strb=age*V3 stra=V2+V1+V4  */
                   9666:       /*       k=4 (age*V3) Tvar[k=4]= 3 (from V3) Tage[cptcovage=1]=4 */
                   9667:       /*       k=3 V4 Tvar[k=3]= 4 (from V4) */
                   9668:       /*       k=2 V1 Tvar[k=2]= 1 (from V1) */
                   9669:       /*       k=1 Tvar[1]=2 (from V2) */
                   9670:       /*       k=5 Tvar[5] */
                   9671:       /* for (k=1; k<=cptcovn;k++) { */
1.198     brouard  9672:       /*       cov[2+k]=nbcode[Tvar[k]][codtabm(ij,Tvar[k])]; */
1.187     brouard  9673:       /*       } */
1.198     brouard  9674:       /* for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,Tvar[Tage[k])]]*cov[2]; */
1.187     brouard  9675:       /*
                   9676:        * Treating invertedly V2+V1+V3*age+V2*V4 is as if written V2*V4 +V3*age + V1 + V2 */
1.227     brouard  9677:       for(k=cptcovt; k>=1;k--){ /**< Number of covariates not including constant and age, neither age*age*/
                   9678:         Tvar[k]=0; Tprod[k]=0; Tposprod[k]=0;
                   9679:       }
1.187     brouard  9680:       cptcovage=0;
                   9681:       for(k=1; k<=cptcovt;k++){ /* Loop on total covariates of the model */
1.234     brouard  9682:        cutl(stra,strb,modelsav,'+'); /* keeps in strb after the first '+' 
1.225     brouard  9683:                                         modelsav==V2+V1+V4+V3*age strb=V3*age stra=V2+V1+V4 */ 
1.234     brouard  9684:        if (nbocc(modelsav,'+')==0) strcpy(strb,modelsav); /* and analyzes it */
                   9685:        /*      printf("i=%d a=%s b=%s sav=%s\n",i, stra,strb,modelsav);*/
                   9686:        /*scanf("%d",i);*/
                   9687:        if (strchr(strb,'*')) {  /**< Model includes a product V2+V1+V4+V3*age strb=V3*age */
                   9688:          cutl(strc,strd,strb,'*'); /**< strd*strc  Vm*Vn: strb=V3*age(input) strc=age strd=V3 ; V3*V2 strc=V2, strd=V3 */
                   9689:          if (strcmp(strc,"age")==0) { /**< Model includes age: Vn*age */
                   9690:            /* covar is not filled and then is empty */
                   9691:            cptcovprod--;
                   9692:            cutl(stre,strb,strd,'V'); /* strd=V3(input): stre="3" */
                   9693:            Tvar[k]=atoi(stre);  /* V2+V1+V4+V3*age Tvar[4]=3 ; V1+V2*age Tvar[2]=2; V1+V1*age Tvar[2]=1 */
                   9694:            Typevar[k]=1;  /* 1 for age product */
                   9695:            cptcovage++; /* Sums the number of covariates which include age as a product */
                   9696:            Tage[cptcovage]=k;  /* Tvar[4]=3, Tage[1] = 4 or V1+V1*age Tvar[2]=1, Tage[1]=2 */
                   9697:            /*printf("stre=%s ", stre);*/
                   9698:          } else if (strcmp(strd,"age")==0) { /* or age*Vn */
                   9699:            cptcovprod--;
                   9700:            cutl(stre,strb,strc,'V');
                   9701:            Tvar[k]=atoi(stre);
                   9702:            Typevar[k]=1;  /* 1 for age product */
                   9703:            cptcovage++;
                   9704:            Tage[cptcovage]=k;
                   9705:          } else {  /* Age is not in the model product V2+V1+V1*V4+V3*age+V3*V2  strb=V3*V2*/
                   9706:            /* loops on k1=1 (V3*V2) and k1=2 V4*V3 */
                   9707:            cptcovn++;
                   9708:            cptcovprodnoage++;k1++;
                   9709:            cutl(stre,strb,strc,'V'); /* strc= Vn, stre is n; strb=V3*V2 stre=3 strc=*/
                   9710:            Tvar[k]=ncovcol+nqv+ntv+nqtv+k1; /* For model-covariate k tells which data-covariate to use but
                   9711:                                                because this model-covariate is a construction we invent a new column
                   9712:                                                which is after existing variables ncovcol+nqv+ntv+nqtv + k1
                   9713:                                                If already ncovcol=4 and model=V2+V1+V1*V4+age*V3+V3*V2
                   9714:                                                Tvar[3=V1*V4]=4+1 Tvar[5=V3*V2]=4 + 2= 6, etc */
                   9715:            Typevar[k]=2;  /* 2 for double fixed dummy covariates */
                   9716:            cutl(strc,strb,strd,'V'); /* strd was Vm, strc is m */
                   9717:            Tprod[k1]=k;  /* Tprod[1]=3(=V1*V4) for V2+V1+V1*V4+age*V3+V3*V2  */
                   9718:            Tposprod[k]=k1; /* Tpsprod[3]=1, Tposprod[2]=5 */
                   9719:            Tvard[k1][1] =atoi(strc); /* m 1 for V1*/
                   9720:            Tvard[k1][2] =atoi(stre); /* n 4 for V4*/
                   9721:            k2=k2+2;  /* k2 is initialize to -1, We want to store the n and m in Vn*Vm at the end of Tvar */
                   9722:            /* Tvar[cptcovt+k2]=Tvard[k1][1]; /\* Tvar[(cptcovt=4+k2=1)=5]= 1 (V1) *\/ */
                   9723:            /* Tvar[cptcovt+k2+1]=Tvard[k1][2];  /\* Tvar[(cptcovt=4+(k2=1)+1)=6]= 4 (V4) *\/ */
1.225     brouard  9724:             /*ncovcol=4 and model=V2+V1+V1*V4+age*V3+V3*V2, Tvar[3]=5, Tvar[4]=6, cptcovt=5 */
1.234     brouard  9725:            /*                     1  2   3      4     5 | Tvar[5+1)=1, Tvar[7]=2   */
                   9726:            for (i=1; i<=lastobs;i++){
                   9727:              /* Computes the new covariate which is a product of
                   9728:                 covar[n][i]* covar[m][i] and stores it at ncovol+k1 May not be defined */
                   9729:              covar[ncovcol+k1][i]=covar[atoi(stre)][i]*covar[atoi(strc)][i];
                   9730:            }
                   9731:          } /* End age is not in the model */
                   9732:        } /* End if model includes a product */
                   9733:        else { /* no more sum */
                   9734:          /*printf("d=%s c=%s b=%s\n", strd,strc,strb);*/
                   9735:          /*  scanf("%d",i);*/
                   9736:          cutl(strd,strc,strb,'V');
                   9737:          ks++; /**< Number of simple covariates dummy or quantitative, fixe or varying */
                   9738:          cptcovn++; /** V4+V3+V5: V4 and V3 timevarying dummy covariates, V5 timevarying quantitative */
                   9739:          Tvar[k]=atoi(strd);
                   9740:          Typevar[k]=0;  /* 0 for simple covariates */
                   9741:        }
                   9742:        strcpy(modelsav,stra);  /* modelsav=V2+V1+V4 stra=V2+V1+V4 */ 
1.223     brouard  9743:                                /*printf("a=%s b=%s sav=%s\n", stra,strb,modelsav);
1.225     brouard  9744:                                  scanf("%d",i);*/
1.187     brouard  9745:       } /* end of loop + on total covariates */
                   9746:     } /* end if strlen(modelsave == 0) age*age might exist */
                   9747:   } /* end if strlen(model == 0) */
1.136     brouard  9748:   
                   9749:   /*The number n of Vn is stored in Tvar. cptcovage =number of age covariate. Tage gives the position of age. cptcovprod= number of products.
                   9750:     If model=V1+V1*age then Tvar[1]=1 Tvar[2]=1 cptcovage=1 Tage[1]=2 cptcovprod=0*/
1.225     brouard  9751:   
1.136     brouard  9752:   /* printf("tvar1=%d tvar2=%d tvar3=%d cptcovage=%d Tage=%d",Tvar[1],Tvar[2],Tvar[3],cptcovage,Tage[1]);
1.225     brouard  9753:      printf("cptcovprod=%d ", cptcovprod);
                   9754:      fprintf(ficlog,"cptcovprod=%d ", cptcovprod);
                   9755:      scanf("%d ",i);*/
                   9756: 
                   9757: 
1.230     brouard  9758: /* Until here, decodemodel knows only the grammar (simple, product, age*) of the model but not what kind
                   9759:    of variable (dummy vs quantitative, fixed vs time varying) is behind. But we know the # of each. */
1.226     brouard  9760: /* ncovcol= 1, nqv=1 | ntv=2, nqtv= 1  = 5 possible variables data: 2 fixed 3, varying
                   9761:    model=        V5 + V4 +V3 + V4*V3 + V5*age + V2 + V1*V2 + V1*age + V5*age, V1 is not used saving its place
                   9762:    k =           1    2   3     4       5       6      7      8        9
                   9763:    Tvar[k]=      5    4   3 1+1+2+1+1=6 5       2      7      1        5
                   9764:    Typevar[k]=   0    0   0     2       1       0      2      1        1
1.227     brouard  9765:    Fixed[k]      1    1   1     1       3       0    0 or 2   2        3
                   9766:    Dummy[k]      1    0   0     0       3       1      1      2        3
                   9767:          Tmodelind[combination of covar]=k;
1.225     brouard  9768: */  
                   9769: /* Dispatching between quantitative and time varying covariates */
1.226     brouard  9770:   /* If Tvar[k] >ncovcol it is a product */
1.225     brouard  9771:   /* 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  9772:        /* Computing effective variables, ie used by the model, that is from the cptcovt variables */
1.227     brouard  9773:   printf("Model=%s\n\
                   9774: Typevar: 0 for simple covariate (dummy, quantitative, fixed or varying), 1 for age product, 2 for  product \n\
                   9775: Fixed[k] 0=fixed (product or simple), 1 varying, 2 fixed with age product, 3 varying with age product \n\
                   9776: 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);
                   9777:   fprintf(ficlog,"Model=%s\n\
                   9778: Typevar: 0 for simple covariate (dummy, quantitative, fixed or varying), 1 for age product, 2 for  product \n\
                   9779: Fixed[k] 0=fixed (product or simple), 1 varying, 2 fixed with age product, 3 varying with age product \n\
                   9780: 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  9781:   for(k=-1;k<=cptcovt; k++){ Fixed[k]=0; Dummy[k]=0;}
1.234     brouard  9782:   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 */
                   9783:     if (Tvar[k] <=ncovcol && Typevar[k]==0 ){ /* Simple fixed dummy (<=ncovcol) covariates */
1.227     brouard  9784:       Fixed[k]= 0;
                   9785:       Dummy[k]= 0;
1.225     brouard  9786:       ncoveff++;
1.232     brouard  9787:       ncovf++;
1.234     brouard  9788:       nsd++;
                   9789:       modell[k].maintype= FTYPE;
                   9790:       TvarsD[nsd]=Tvar[k];
                   9791:       TvarsDind[nsd]=k;
                   9792:       TvarF[ncovf]=Tvar[k];
                   9793:       TvarFind[ncovf]=k;
                   9794:       TvarFD[ncoveff]=Tvar[k]; /* TvarFD[1]=V1 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
                   9795:       TvarFDind[ncoveff]=k; /* TvarFDind[1]=9 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
                   9796:     }else if( Tvar[k] <=ncovcol &&  Typevar[k]==2){ /* Product of fixed dummy (<=ncovcol) covariates */
                   9797:       Fixed[k]= 0;
                   9798:       Dummy[k]= 0;
                   9799:       ncoveff++;
                   9800:       ncovf++;
                   9801:       modell[k].maintype= FTYPE;
                   9802:       TvarF[ncovf]=Tvar[k];
                   9803:       TvarFind[ncovf]=k;
1.230     brouard  9804:       TvarFD[ncoveff]=Tvar[k]; /* TvarFD[1]=V1 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
1.231     brouard  9805:       TvarFDind[ncoveff]=k; /* TvarFDind[1]=9 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
1.240     brouard  9806:     }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  9807:       Fixed[k]= 0;
                   9808:       Dummy[k]= 1;
1.230     brouard  9809:       nqfveff++;
1.234     brouard  9810:       modell[k].maintype= FTYPE;
                   9811:       modell[k].subtype= FQ;
                   9812:       nsq++;
                   9813:       TvarsQ[nsq]=Tvar[k];
                   9814:       TvarsQind[nsq]=k;
1.232     brouard  9815:       ncovf++;
1.234     brouard  9816:       TvarF[ncovf]=Tvar[k];
                   9817:       TvarFind[ncovf]=k;
1.231     brouard  9818:       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  9819:       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  9820:     }else if( Tvar[k] <=ncovcol+nqv+ntv && Typevar[k]==0){/* Only simple time varying dummy variables */
1.227     brouard  9821:       Fixed[k]= 1;
                   9822:       Dummy[k]= 0;
1.225     brouard  9823:       ntveff++; /* Only simple time varying dummy variable */
1.234     brouard  9824:       modell[k].maintype= VTYPE;
                   9825:       modell[k].subtype= VD;
                   9826:       nsd++;
                   9827:       TvarsD[nsd]=Tvar[k];
                   9828:       TvarsDind[nsd]=k;
                   9829:       ncovv++; /* Only simple time varying variables */
                   9830:       TvarV[ncovv]=Tvar[k];
1.242     brouard  9831:       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  9832:       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 */
                   9833:       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  9834:       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);
                   9835:       printf("Quasi TmodelInvind[%d]=%d\n",k,Tvar[k]- ncovcol-nqv);
1.231     brouard  9836:     }else if( Tvar[k] <=ncovcol+nqv+ntv+nqtv  && Typevar[k]==0){ /* Only simple time varying quantitative variable V5*/
1.234     brouard  9837:       Fixed[k]= 1;
                   9838:       Dummy[k]= 1;
                   9839:       nqtveff++;
                   9840:       modell[k].maintype= VTYPE;
                   9841:       modell[k].subtype= VQ;
                   9842:       ncovv++; /* Only simple time varying variables */
                   9843:       nsq++;
                   9844:       TvarsQ[nsq]=Tvar[k];
                   9845:       TvarsQind[nsq]=k;
                   9846:       TvarV[ncovv]=Tvar[k];
1.242     brouard  9847:       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  9848:       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 */
                   9849:       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  9850:       TmodelInvQind[nqtveff]=Tvar[k]- ncovcol-nqv-ntv;/* Only simple time varying quantitative variable */
                   9851:       /* Tmodeliqind[k]=nqtveff;/\* Only simple time varying quantitative variable *\/ */
                   9852:       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  9853:       printf("Quasi TmodelInvQind[%d]=%d\n",k,Tvar[k]- ncovcol-nqv-ntv);
1.227     brouard  9854:     }else if (Typevar[k] == 1) {  /* product with age */
1.234     brouard  9855:       ncova++;
                   9856:       TvarA[ncova]=Tvar[k];
                   9857:       TvarAind[ncova]=k;
1.231     brouard  9858:       if (Tvar[k] <=ncovcol ){ /* Product age with fixed dummy covariatee */
1.240     brouard  9859:        Fixed[k]= 2;
                   9860:        Dummy[k]= 2;
                   9861:        modell[k].maintype= ATYPE;
                   9862:        modell[k].subtype= APFD;
                   9863:        /* ncoveff++; */
1.227     brouard  9864:       }else if( Tvar[k] <=ncovcol+nqv) { /* Remind that product Vn*Vm are added in k*/
1.240     brouard  9865:        Fixed[k]= 2;
                   9866:        Dummy[k]= 3;
                   9867:        modell[k].maintype= ATYPE;
                   9868:        modell[k].subtype= APFQ;                /*      Product age * fixed quantitative */
                   9869:        /* nqfveff++;  /\* Only simple fixed quantitative variable *\/ */
1.227     brouard  9870:       }else if( Tvar[k] <=ncovcol+nqv+ntv ){
1.240     brouard  9871:        Fixed[k]= 3;
                   9872:        Dummy[k]= 2;
                   9873:        modell[k].maintype= ATYPE;
                   9874:        modell[k].subtype= APVD;                /*      Product age * varying dummy */
                   9875:        /* ntveff++; /\* Only simple time varying dummy variable *\/ */
1.227     brouard  9876:       }else if( Tvar[k] <=ncovcol+nqv+ntv+nqtv){
1.240     brouard  9877:        Fixed[k]= 3;
                   9878:        Dummy[k]= 3;
                   9879:        modell[k].maintype= ATYPE;
                   9880:        modell[k].subtype= APVQ;                /*      Product age * varying quantitative */
                   9881:        /* nqtveff++;/\* Only simple time varying quantitative variable *\/ */
1.227     brouard  9882:       }
                   9883:     }else if (Typevar[k] == 2) {  /* product without age */
                   9884:       k1=Tposprod[k];
                   9885:       if(Tvard[k1][1] <=ncovcol){
1.240     brouard  9886:        if(Tvard[k1][2] <=ncovcol){
                   9887:          Fixed[k]= 1;
                   9888:          Dummy[k]= 0;
                   9889:          modell[k].maintype= FTYPE;
                   9890:          modell[k].subtype= FPDD;              /*      Product fixed dummy * fixed dummy */
                   9891:          ncovf++; /* Fixed variables without age */
                   9892:          TvarF[ncovf]=Tvar[k];
                   9893:          TvarFind[ncovf]=k;
                   9894:        }else if(Tvard[k1][2] <=ncovcol+nqv){
                   9895:          Fixed[k]= 0;  /* or 2 ?*/
                   9896:          Dummy[k]= 1;
                   9897:          modell[k].maintype= FTYPE;
                   9898:          modell[k].subtype= FPDQ;              /*      Product fixed dummy * fixed quantitative */
                   9899:          ncovf++; /* Varying variables without age */
                   9900:          TvarF[ncovf]=Tvar[k];
                   9901:          TvarFind[ncovf]=k;
                   9902:        }else if(Tvard[k1][2] <=ncovcol+nqv+ntv){
                   9903:          Fixed[k]= 1;
                   9904:          Dummy[k]= 0;
                   9905:          modell[k].maintype= VTYPE;
                   9906:          modell[k].subtype= VPDD;              /*      Product fixed dummy * varying dummy */
                   9907:          ncovv++; /* Varying variables without age */
                   9908:          TvarV[ncovv]=Tvar[k];
                   9909:          TvarVind[ncovv]=k;
                   9910:        }else if(Tvard[k1][2] <=ncovcol+nqv+ntv+nqtv){
                   9911:          Fixed[k]= 1;
                   9912:          Dummy[k]= 1;
                   9913:          modell[k].maintype= VTYPE;
                   9914:          modell[k].subtype= VPDQ;              /*      Product fixed dummy * varying quantitative */
                   9915:          ncovv++; /* Varying variables without age */
                   9916:          TvarV[ncovv]=Tvar[k];
                   9917:          TvarVind[ncovv]=k;
                   9918:        }
1.227     brouard  9919:       }else if(Tvard[k1][1] <=ncovcol+nqv){
1.240     brouard  9920:        if(Tvard[k1][2] <=ncovcol){
                   9921:          Fixed[k]= 0;  /* or 2 ?*/
                   9922:          Dummy[k]= 1;
                   9923:          modell[k].maintype= FTYPE;
                   9924:          modell[k].subtype= FPDQ;              /*      Product fixed quantitative * fixed dummy */
                   9925:          ncovf++; /* Fixed variables without age */
                   9926:          TvarF[ncovf]=Tvar[k];
                   9927:          TvarFind[ncovf]=k;
                   9928:        }else if(Tvard[k1][2] <=ncovcol+nqv+ntv){
                   9929:          Fixed[k]= 1;
                   9930:          Dummy[k]= 1;
                   9931:          modell[k].maintype= VTYPE;
                   9932:          modell[k].subtype= VPDQ;              /*      Product fixed quantitative * varying dummy */
                   9933:          ncovv++; /* Varying variables without age */
                   9934:          TvarV[ncovv]=Tvar[k];
                   9935:          TvarVind[ncovv]=k;
                   9936:        }else if(Tvard[k1][2] <=ncovcol+nqv+ntv+nqtv){
                   9937:          Fixed[k]= 1;
                   9938:          Dummy[k]= 1;
                   9939:          modell[k].maintype= VTYPE;
                   9940:          modell[k].subtype= VPQQ;              /*      Product fixed quantitative * varying quantitative */
                   9941:          ncovv++; /* Varying variables without age */
                   9942:          TvarV[ncovv]=Tvar[k];
                   9943:          TvarVind[ncovv]=k;
                   9944:          ncovv++; /* Varying variables without age */
                   9945:          TvarV[ncovv]=Tvar[k];
                   9946:          TvarVind[ncovv]=k;
                   9947:        }
1.227     brouard  9948:       }else if(Tvard[k1][1] <=ncovcol+nqv+ntv){
1.240     brouard  9949:        if(Tvard[k1][2] <=ncovcol){
                   9950:          Fixed[k]= 1;
                   9951:          Dummy[k]= 1;
                   9952:          modell[k].maintype= VTYPE;
                   9953:          modell[k].subtype= VPDD;              /*      Product time varying dummy * fixed dummy */
                   9954:          ncovv++; /* Varying variables without age */
                   9955:          TvarV[ncovv]=Tvar[k];
                   9956:          TvarVind[ncovv]=k;
                   9957:        }else if(Tvard[k1][2] <=ncovcol+nqv){
                   9958:          Fixed[k]= 1;
                   9959:          Dummy[k]= 1;
                   9960:          modell[k].maintype= VTYPE;
                   9961:          modell[k].subtype= VPDQ;              /*      Product time varying dummy * fixed quantitative */
                   9962:          ncovv++; /* Varying variables without age */
                   9963:          TvarV[ncovv]=Tvar[k];
                   9964:          TvarVind[ncovv]=k;
                   9965:        }else if(Tvard[k1][2] <=ncovcol+nqv+ntv){
                   9966:          Fixed[k]= 1;
                   9967:          Dummy[k]= 0;
                   9968:          modell[k].maintype= VTYPE;
                   9969:          modell[k].subtype= VPDD;              /*      Product time varying dummy * time varying dummy */
                   9970:          ncovv++; /* Varying variables without age */
                   9971:          TvarV[ncovv]=Tvar[k];
                   9972:          TvarVind[ncovv]=k;
                   9973:        }else if(Tvard[k1][2] <=ncovcol+nqv+ntv+nqtv){
                   9974:          Fixed[k]= 1;
                   9975:          Dummy[k]= 1;
                   9976:          modell[k].maintype= VTYPE;
                   9977:          modell[k].subtype= VPDQ;              /*      Product time varying dummy * time varying quantitative */
                   9978:          ncovv++; /* Varying variables without age */
                   9979:          TvarV[ncovv]=Tvar[k];
                   9980:          TvarVind[ncovv]=k;
                   9981:        }
1.227     brouard  9982:       }else if(Tvard[k1][1] <=ncovcol+nqv+ntv+nqtv){
1.240     brouard  9983:        if(Tvard[k1][2] <=ncovcol){
                   9984:          Fixed[k]= 1;
                   9985:          Dummy[k]= 1;
                   9986:          modell[k].maintype= VTYPE;
                   9987:          modell[k].subtype= VPDQ;              /*      Product time varying quantitative * fixed dummy */
                   9988:          ncovv++; /* Varying variables without age */
                   9989:          TvarV[ncovv]=Tvar[k];
                   9990:          TvarVind[ncovv]=k;
                   9991:        }else if(Tvard[k1][2] <=ncovcol+nqv){
                   9992:          Fixed[k]= 1;
                   9993:          Dummy[k]= 1;
                   9994:          modell[k].maintype= VTYPE;
                   9995:          modell[k].subtype= VPQQ;              /*      Product time varying quantitative * fixed quantitative */
                   9996:          ncovv++; /* Varying variables without age */
                   9997:          TvarV[ncovv]=Tvar[k];
                   9998:          TvarVind[ncovv]=k;
                   9999:        }else if(Tvard[k1][2] <=ncovcol+nqv+ntv){
                   10000:          Fixed[k]= 1;
                   10001:          Dummy[k]= 1;
                   10002:          modell[k].maintype= VTYPE;
                   10003:          modell[k].subtype= VPDQ;              /*      Product time varying quantitative * time varying dummy */
                   10004:          ncovv++; /* Varying variables without age */
                   10005:          TvarV[ncovv]=Tvar[k];
                   10006:          TvarVind[ncovv]=k;
                   10007:        }else if(Tvard[k1][2] <=ncovcol+nqv+ntv+nqtv){
                   10008:          Fixed[k]= 1;
                   10009:          Dummy[k]= 1;
                   10010:          modell[k].maintype= VTYPE;
                   10011:          modell[k].subtype= VPQQ;              /*      Product time varying quantitative * time varying quantitative */
                   10012:          ncovv++; /* Varying variables without age */
                   10013:          TvarV[ncovv]=Tvar[k];
                   10014:          TvarVind[ncovv]=k;
                   10015:        }
1.227     brouard  10016:       }else{
1.240     brouard  10017:        printf("Error unknown type of covariate: Tvard[%d][1]=%d,Tvard[%d][2]=%d\n",k1,Tvard[k1][1],k1,Tvard[k1][2]);
                   10018:        fprintf(ficlog,"Error unknown type of covariate: Tvard[%d][1]=%d,Tvard[%d][2]=%d\n",k1,Tvard[k1][1],k1,Tvard[k1][2]);
                   10019:       } /*end k1*/
1.225     brouard  10020:     }else{
1.226     brouard  10021:       printf("Error, current version can't treat for performance reasons, Tvar[%d]=%d, Typevar[%d]=%d\n", k, Tvar[k], k, Typevar[k]);
                   10022:       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  10023:     }
1.227     brouard  10024:     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  10025:     printf("           modell[%d].maintype=%d, modell[%d].subtype=%d\n",k,modell[k].maintype,k,modell[k].subtype);
1.227     brouard  10026:     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]);
                   10027:   }
                   10028:   /* Searching for doublons in the model */
                   10029:   for(k1=1; k1<= cptcovt;k1++){
                   10030:     for(k2=1; k2 <k1;k2++){
1.285     brouard  10031:       /* if((Typevar[k1]==Typevar[k2]) && (Fixed[Tvar[k1]]==Fixed[Tvar[k2]]) && (Dummy[Tvar[k1]]==Dummy[Tvar[k2]] )){ */
                   10032:       if((Typevar[k1]==Typevar[k2]) && (Fixed[k1]==Fixed[k2]) && (Dummy[k1]==Dummy[k2] )){
1.234     brouard  10033:        if((Typevar[k1] == 0 || Typevar[k1] == 1)){ /* Simple or age product */
                   10034:          if(Tvar[k1]==Tvar[k2]){
1.285     brouard  10035:            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]);
                   10036:            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  10037:            return(1);
                   10038:          }
                   10039:        }else if (Typevar[k1] ==2){
                   10040:          k3=Tposprod[k1];
                   10041:          k4=Tposprod[k2];
                   10042:          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])) ){
                   10043:            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]]);
                   10044:            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);
                   10045:            return(1);
                   10046:          }
                   10047:        }
1.227     brouard  10048:       }
                   10049:     }
1.225     brouard  10050:   }
                   10051:   printf("ncoveff=%d, nqfveff=%d, ntveff=%d, nqtveff=%d, cptcovn=%d\n",ncoveff,nqfveff,ntveff,nqtveff,cptcovn);
                   10052:   fprintf(ficlog,"ncoveff=%d, nqfveff=%d, ntveff=%d, nqtveff=%d, cptcovn=%d\n",ncoveff,nqfveff,ntveff,nqtveff,cptcovn);
1.234     brouard  10053:   printf("ncovf=%d, ncovv=%d, ncova=%d, nsd=%d, nsq=%d\n",ncovf,ncovv,ncova,nsd,nsq);
                   10054:   fprintf(ficlog,"ncovf=%d, ncovv=%d, ncova=%d, nsd=%d, nsq=%d\n",ncovf,ncovv,ncova,nsd, nsq);
1.137     brouard  10055:   return (0); /* with covar[new additional covariate if product] and Tage if age */ 
1.164     brouard  10056:   /*endread:*/
1.225     brouard  10057:   printf("Exiting decodemodel: ");
                   10058:   return (1);
1.136     brouard  10059: }
                   10060: 
1.169     brouard  10061: int calandcheckages(int imx, int maxwav, double *agemin, double *agemax, int *nberr, int *nbwarn )
1.248     brouard  10062: {/* Check ages at death */
1.136     brouard  10063:   int i, m;
1.218     brouard  10064:   int firstone=0;
                   10065:   
1.136     brouard  10066:   for (i=1; i<=imx; i++) {
                   10067:     for(m=2; (m<= maxwav); m++) {
                   10068:       if (((int)mint[m][i]== 99) && (s[m][i] <= nlstate)){
                   10069:        anint[m][i]=9999;
1.216     brouard  10070:        if (s[m][i] != -2) /* Keeping initial status of unknown vital status */
                   10071:          s[m][i]=-1;
1.136     brouard  10072:       }
                   10073:       if((int)moisdc[i]==99 && (int)andc[i]==9999 && s[m][i]>nlstate){
1.260     brouard  10074:        *nberr = *nberr + 1;
1.218     brouard  10075:        if(firstone == 0){
                   10076:          firstone=1;
1.260     brouard  10077:        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  10078:        }
1.262     brouard  10079:        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  10080:        s[m][i]=-1;  /* Droping the death status */
1.136     brouard  10081:       }
                   10082:       if((int)moisdc[i]==99 && (int)andc[i]!=9999 && s[m][i]>nlstate){
1.169     brouard  10083:        (*nberr)++;
1.259     brouard  10084:        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  10085:        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  10086:        s[m][i]=-2; /* We prefer to skip it (and to skip it in version 0.8a1 too */
1.136     brouard  10087:       }
                   10088:     }
                   10089:   }
                   10090: 
                   10091:   for (i=1; i<=imx; i++)  {
                   10092:     agedc[i]=(moisdc[i]/12.+andc[i])-(moisnais[i]/12.+annais[i]);
                   10093:     for(m=firstpass; (m<= lastpass); m++){
1.214     brouard  10094:       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  10095:        if (s[m][i] >= nlstate+1) {
1.169     brouard  10096:          if(agedc[i]>0){
                   10097:            if((int)moisdc[i]!=99 && (int)andc[i]!=9999){
1.136     brouard  10098:              agev[m][i]=agedc[i];
1.214     brouard  10099:              /*if(moisdc[i]==99 && andc[i]==9999) s[m][i]=-1;*/
1.169     brouard  10100:            }else {
1.136     brouard  10101:              if ((int)andc[i]!=9999){
                   10102:                nbwarn++;
                   10103:                printf("Warning negative age at death: %ld line:%d\n",num[i],i);
                   10104:                fprintf(ficlog,"Warning negative age at death: %ld line:%d\n",num[i],i);
                   10105:                agev[m][i]=-1;
                   10106:              }
                   10107:            }
1.169     brouard  10108:          } /* agedc > 0 */
1.214     brouard  10109:        } /* end if */
1.136     brouard  10110:        else if(s[m][i] !=9){ /* Standard case, age in fractional
                   10111:                                 years but with the precision of a month */
                   10112:          agev[m][i]=(mint[m][i]/12.+1./24.+anint[m][i])-(moisnais[i]/12.+1./24.+annais[i]);
                   10113:          if((int)mint[m][i]==99 || (int)anint[m][i]==9999)
                   10114:            agev[m][i]=1;
                   10115:          else if(agev[m][i] < *agemin){ 
                   10116:            *agemin=agev[m][i];
                   10117:            printf(" Min anint[%d][%d]=%.2f annais[%d]=%.2f, agemin=%.2f\n",m,i,anint[m][i], i,annais[i], *agemin);
                   10118:          }
                   10119:          else if(agev[m][i] >*agemax){
                   10120:            *agemax=agev[m][i];
1.156     brouard  10121:            /* printf(" Max anint[%d][%d]=%.0f annais[%d]=%.0f, agemax=%.2f\n",m,i,anint[m][i], i,annais[i], *agemax);*/
1.136     brouard  10122:          }
                   10123:          /*agev[m][i]=anint[m][i]-annais[i];*/
                   10124:          /*     agev[m][i] = age[i]+2*m;*/
1.214     brouard  10125:        } /* en if 9*/
1.136     brouard  10126:        else { /* =9 */
1.214     brouard  10127:          /* printf("Debug num[%d]=%ld s[%d][%d]=%d\n",i,num[i], m,i, s[m][i]); */
1.136     brouard  10128:          agev[m][i]=1;
                   10129:          s[m][i]=-1;
                   10130:        }
                   10131:       }
1.214     brouard  10132:       else if(s[m][i]==0) /*= 0 Unknown */
1.136     brouard  10133:        agev[m][i]=1;
1.214     brouard  10134:       else{
                   10135:        printf("Warning, num[%d]=%ld, s[%d][%d]=%d\n", i, num[i], m, i,s[m][i]); 
                   10136:        fprintf(ficlog, "Warning, num[%d]=%ld, s[%d][%d]=%d\n", i, num[i], m, i,s[m][i]); 
                   10137:        agev[m][i]=0;
                   10138:       }
                   10139:     } /* End for lastpass */
                   10140:   }
1.136     brouard  10141:     
                   10142:   for (i=1; i<=imx; i++)  {
                   10143:     for(m=firstpass; (m<=lastpass); m++){
                   10144:       if (s[m][i] > (nlstate+ndeath)) {
1.169     brouard  10145:        (*nberr)++;
1.136     brouard  10146:        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);     
                   10147:        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);     
                   10148:        return 1;
                   10149:       }
                   10150:     }
                   10151:   }
                   10152: 
                   10153:   /*for (i=1; i<=imx; i++){
                   10154:   for (m=firstpass; (m<lastpass); m++){
                   10155:      printf("%ld %d %.lf %d %d\n", num[i],(covar[1][i]),agev[m][i],s[m][i],s[m+1][i]);
                   10156: }
                   10157: 
                   10158: }*/
                   10159: 
                   10160: 
1.139     brouard  10161:   printf("Total number of individuals= %d, Agemin = %.2f, Agemax= %.2f\n\n", imx, *agemin, *agemax);
                   10162:   fprintf(ficlog,"Total number of individuals= %d, Agemin = %.2f, Agemax= %.2f\n\n", imx, *agemin, *agemax); 
1.136     brouard  10163: 
                   10164:   return (0);
1.164     brouard  10165:  /* endread:*/
1.136     brouard  10166:     printf("Exiting calandcheckages: ");
                   10167:     return (1);
                   10168: }
                   10169: 
1.172     brouard  10170: #if defined(_MSC_VER)
                   10171: /*printf("Visual C++ compiler: %s \n;", _MSC_FULL_VER);*/
                   10172: /*fprintf(ficlog, "Visual C++ compiler: %s \n;", _MSC_FULL_VER);*/
                   10173: //#include "stdafx.h"
                   10174: //#include <stdio.h>
                   10175: //#include <tchar.h>
                   10176: //#include <windows.h>
                   10177: //#include <iostream>
                   10178: typedef BOOL(WINAPI *LPFN_ISWOW64PROCESS) (HANDLE, PBOOL);
                   10179: 
                   10180: LPFN_ISWOW64PROCESS fnIsWow64Process;
                   10181: 
                   10182: BOOL IsWow64()
                   10183: {
                   10184:        BOOL bIsWow64 = FALSE;
                   10185: 
                   10186:        //typedef BOOL (APIENTRY *LPFN_ISWOW64PROCESS)
                   10187:        //  (HANDLE, PBOOL);
                   10188: 
                   10189:        //LPFN_ISWOW64PROCESS fnIsWow64Process;
                   10190: 
                   10191:        HMODULE module = GetModuleHandle(_T("kernel32"));
                   10192:        const char funcName[] = "IsWow64Process";
                   10193:        fnIsWow64Process = (LPFN_ISWOW64PROCESS)
                   10194:                GetProcAddress(module, funcName);
                   10195: 
                   10196:        if (NULL != fnIsWow64Process)
                   10197:        {
                   10198:                if (!fnIsWow64Process(GetCurrentProcess(),
                   10199:                        &bIsWow64))
                   10200:                        //throw std::exception("Unknown error");
                   10201:                        printf("Unknown error\n");
                   10202:        }
                   10203:        return bIsWow64 != FALSE;
                   10204: }
                   10205: #endif
1.177     brouard  10206: 
1.191     brouard  10207: void syscompilerinfo(int logged)
1.292     brouard  10208: {
                   10209: #include <stdint.h>
                   10210: 
                   10211:   /* #include "syscompilerinfo.h"*/
1.185     brouard  10212:    /* command line Intel compiler 32bit windows, XP compatible:*/
                   10213:    /* /GS /W3 /Gy
                   10214:       /Zc:wchar_t /Zi /O2 /Fd"Release\vc120.pdb" /D "WIN32" /D "NDEBUG" /D
                   10215:       "_CONSOLE" /D "_LIB" /D "_USING_V110_SDK71_" /D "_UNICODE" /D
                   10216:       "UNICODE" /Qipo /Zc:forScope /Gd /Oi /MT /Fa"Release\" /EHsc /nologo
1.186     brouard  10217:       /Fo"Release\" /Qprof-dir "Release\" /Fp"Release\IMaCh.pch"
                   10218:    */ 
                   10219:    /* 64 bits */
1.185     brouard  10220:    /*
                   10221:      /GS /W3 /Gy
                   10222:      /Zc:wchar_t /Zi /O2 /Fd"x64\Release\vc120.pdb" /D "WIN32" /D "NDEBUG"
                   10223:      /D "_CONSOLE" /D "_LIB" /D "_UNICODE" /D "UNICODE" /Qipo /Zc:forScope
                   10224:      /Oi /MD /Fa"x64\Release\" /EHsc /nologo /Fo"x64\Release\" /Qprof-dir
                   10225:      "x64\Release\" /Fp"x64\Release\IMaCh.pch" */
                   10226:    /* Optimization are useless and O3 is slower than O2 */
                   10227:    /*
                   10228:      /GS /W3 /Gy /Zc:wchar_t /Zi /O3 /Fd"x64\Release\vc120.pdb" /D "WIN32" 
                   10229:      /D "NDEBUG" /D "_CONSOLE" /D "_LIB" /D "_UNICODE" /D "UNICODE" /Qipo 
                   10230:      /Zc:forScope /Oi /MD /Fa"x64\Release\" /EHsc /nologo /Qparallel 
                   10231:      /Fo"x64\Release\" /Qprof-dir "x64\Release\" /Fp"x64\Release\IMaCh.pch" 
                   10232:    */
1.186     brouard  10233:    /* Link is */ /* /OUT:"visual studio
1.185     brouard  10234:       2013\Projects\IMaCh\Release\IMaCh.exe" /MANIFEST /NXCOMPAT
                   10235:       /PDB:"visual studio
                   10236:       2013\Projects\IMaCh\Release\IMaCh.pdb" /DYNAMICBASE
                   10237:       "kernel32.lib" "user32.lib" "gdi32.lib" "winspool.lib"
                   10238:       "comdlg32.lib" "advapi32.lib" "shell32.lib" "ole32.lib"
                   10239:       "oleaut32.lib" "uuid.lib" "odbc32.lib" "odbccp32.lib"
                   10240:       /MACHINE:X86 /OPT:REF /SAFESEH /INCREMENTAL:NO
                   10241:       /SUBSYSTEM:CONSOLE",5.01" /MANIFESTUAC:"level='asInvoker'
                   10242:       uiAccess='false'"
                   10243:       /ManifestFile:"Release\IMaCh.exe.intermediate.manifest" /OPT:ICF
                   10244:       /NOLOGO /TLBID:1
                   10245:    */
1.292     brouard  10246: 
                   10247: 
1.177     brouard  10248: #if defined __INTEL_COMPILER
1.178     brouard  10249: #if defined(__GNUC__)
                   10250:        struct utsname sysInfo;  /* For Intel on Linux and OS/X */
                   10251: #endif
1.177     brouard  10252: #elif defined(__GNUC__) 
1.179     brouard  10253: #ifndef  __APPLE__
1.174     brouard  10254: #include <gnu/libc-version.h>  /* Only on gnu */
1.179     brouard  10255: #endif
1.177     brouard  10256:    struct utsname sysInfo;
1.178     brouard  10257:    int cross = CROSS;
                   10258:    if (cross){
                   10259:           printf("Cross-");
1.191     brouard  10260:           if(logged) fprintf(ficlog, "Cross-");
1.178     brouard  10261:    }
1.174     brouard  10262: #endif
                   10263: 
1.191     brouard  10264:    printf("Compiled with:");if(logged)fprintf(ficlog,"Compiled with:");
1.169     brouard  10265: #if defined(__clang__)
1.191     brouard  10266:    printf(" Clang/LLVM");if(logged)fprintf(ficlog," Clang/LLVM");      /* Clang/LLVM. ---------------------------------------------- */
1.169     brouard  10267: #endif
                   10268: #if defined(__ICC) || defined(__INTEL_COMPILER)
1.191     brouard  10269:    printf(" Intel ICC/ICPC");if(logged)fprintf(ficlog," Intel ICC/ICPC");/* Intel ICC/ICPC. ------------------------------------------ */
1.169     brouard  10270: #endif
                   10271: #if defined(__GNUC__) || defined(__GNUG__)
1.191     brouard  10272:    printf(" GNU GCC/G++");if(logged)fprintf(ficlog," GNU GCC/G++");/* GNU GCC/G++. --------------------------------------------- */
1.169     brouard  10273: #endif
                   10274: #if defined(__HP_cc) || defined(__HP_aCC)
1.191     brouard  10275:    printf(" Hewlett-Packard C/aC++");if(logged)fprintf(fcilog," Hewlett-Packard C/aC++"); /* Hewlett-Packard C/aC++. ---------------------------------- */
1.169     brouard  10276: #endif
                   10277: #if defined(__IBMC__) || defined(__IBMCPP__)
1.191     brouard  10278:    printf(" IBM XL C/C++"); if(logged) fprintf(ficlog," IBM XL C/C++");/* IBM XL C/C++. -------------------------------------------- */
1.169     brouard  10279: #endif
                   10280: #if defined(_MSC_VER)
1.191     brouard  10281:    printf(" Microsoft Visual Studio");if(logged)fprintf(ficlog," Microsoft Visual Studio");/* Microsoft Visual Studio. --------------------------------- */
1.169     brouard  10282: #endif
                   10283: #if defined(__PGI)
1.191     brouard  10284:    printf(" Portland Group PGCC/PGCPP");if(logged) fprintf(ficlog," Portland Group PGCC/PGCPP");/* Portland Group PGCC/PGCPP. ------------------------------- */
1.169     brouard  10285: #endif
                   10286: #if defined(__SUNPRO_C) || defined(__SUNPRO_CC)
1.191     brouard  10287:    printf(" Oracle Solaris Studio");if(logged)fprintf(ficlog," Oracle Solaris Studio\n");/* Oracle Solaris Studio. ----------------------------------- */
1.167     brouard  10288: #endif
1.191     brouard  10289:    printf(" for "); if (logged) fprintf(ficlog, " for ");
1.169     brouard  10290:    
1.167     brouard  10291: // http://stackoverflow.com/questions/4605842/how-to-identify-platform-compiler-from-preprocessor-macros
                   10292: #ifdef _WIN32 // note the underscore: without it, it's not msdn official!
                   10293:     // Windows (x64 and x86)
1.191     brouard  10294:    printf("Windows (x64 and x86) ");if(logged) fprintf(ficlog,"Windows (x64 and x86) ");
1.167     brouard  10295: #elif __unix__ // all unices, not all compilers
                   10296:     // Unix
1.191     brouard  10297:    printf("Unix ");if(logged) fprintf(ficlog,"Unix ");
1.167     brouard  10298: #elif __linux__
                   10299:     // linux
1.191     brouard  10300:    printf("linux ");if(logged) fprintf(ficlog,"linux ");
1.167     brouard  10301: #elif __APPLE__
1.174     brouard  10302:     // Mac OS, not sure if this is covered by __posix__ and/or __unix__ though..
1.191     brouard  10303:    printf("Mac OS ");if(logged) fprintf(ficlog,"Mac OS ");
1.167     brouard  10304: #endif
                   10305: 
                   10306: /*  __MINGW32__          */
                   10307: /*  __CYGWIN__  */
                   10308: /* __MINGW64__  */
                   10309: // http://msdn.microsoft.com/en-us/library/b0084kay.aspx
                   10310: /* _MSC_VER  //the Visual C++ compiler is 17.00.51106.1, the _MSC_VER macro evaluates to 1700. Type cl /?  */
                   10311: /* _MSC_FULL_VER //the Visual C++ compiler is 15.00.20706.01, the _MSC_FULL_VER macro evaluates to 150020706 */
                   10312: /* _WIN64  // Defined for applications for Win64. */
                   10313: /* _M_X64 // Defined for compilations that target x64 processors. */
                   10314: /* _DEBUG // Defined when you compile with /LDd, /MDd, and /MTd. */
1.171     brouard  10315: 
1.167     brouard  10316: #if UINTPTR_MAX == 0xffffffff
1.191     brouard  10317:    printf(" 32-bit"); if(logged) fprintf(ficlog," 32-bit");/* 32-bit */
1.167     brouard  10318: #elif UINTPTR_MAX == 0xffffffffffffffff
1.191     brouard  10319:    printf(" 64-bit"); if(logged) fprintf(ficlog," 64-bit");/* 64-bit */
1.167     brouard  10320: #else
1.191     brouard  10321:    printf(" wtf-bit"); if(logged) fprintf(ficlog," wtf-bit");/* wtf */
1.167     brouard  10322: #endif
                   10323: 
1.169     brouard  10324: #if defined(__GNUC__)
                   10325: # if defined(__GNUC_PATCHLEVEL__)
                   10326: #  define __GNUC_VERSION__ (__GNUC__ * 10000 \
                   10327:                             + __GNUC_MINOR__ * 100 \
                   10328:                             + __GNUC_PATCHLEVEL__)
                   10329: # else
                   10330: #  define __GNUC_VERSION__ (__GNUC__ * 10000 \
                   10331:                             + __GNUC_MINOR__ * 100)
                   10332: # endif
1.174     brouard  10333:    printf(" using GNU C version %d.\n", __GNUC_VERSION__);
1.191     brouard  10334:    if(logged) fprintf(ficlog, " using GNU C version %d.\n", __GNUC_VERSION__);
1.176     brouard  10335: 
                   10336:    if (uname(&sysInfo) != -1) {
                   10337:      printf("Running on: %s %s %s %s %s\n",sysInfo.sysname, sysInfo.nodename, sysInfo.release, sysInfo.version, sysInfo.machine);
1.191     brouard  10338:         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  10339:    }
                   10340:    else
                   10341:       perror("uname() error");
1.179     brouard  10342:    //#ifndef __INTEL_COMPILER 
                   10343: #if !defined (__INTEL_COMPILER) && !defined(__APPLE__)
1.174     brouard  10344:    printf("GNU libc version: %s\n", gnu_get_libc_version()); 
1.191     brouard  10345:    if(logged) fprintf(ficlog,"GNU libc version: %s\n", gnu_get_libc_version());
1.177     brouard  10346: #endif
1.169     brouard  10347: #endif
1.172     brouard  10348: 
1.286     brouard  10349:    //   void main ()
1.172     brouard  10350:    //   {
1.169     brouard  10351: #if defined(_MSC_VER)
1.174     brouard  10352:    if (IsWow64()){
1.191     brouard  10353:           printf("\nThe program (probably compiled for 32bit) is running under WOW64 (64bit) emulation.\n");
                   10354:           if (logged) fprintf(ficlog, "\nThe program (probably compiled for 32bit) is running under WOW64 (64bit) emulation.\n");
1.174     brouard  10355:    }
                   10356:    else{
1.191     brouard  10357:           printf("\nThe program is not running under WOW64 (i.e probably on a 64bit Windows).\n");
                   10358:           if (logged) fprintf(ficlog, "\nThe programm is not running under WOW64 (i.e probably on a 64bit Windows).\n");
1.174     brouard  10359:    }
1.172     brouard  10360:    //     printf("\nPress Enter to continue...");
                   10361:    //     getchar();
                   10362:    //   }
                   10363: 
1.169     brouard  10364: #endif
                   10365:    
1.167     brouard  10366: 
1.219     brouard  10367: }
1.136     brouard  10368: 
1.219     brouard  10369: int prevalence_limit(double *p, double **prlim, double ageminpar, double agemaxpar, double ftolpl, int *ncvyearp){
1.288     brouard  10370:   /*--------------- Prevalence limit  (forward period or forward stable prevalence) --------------*/
1.235     brouard  10371:   int i, j, k, i1, k4=0, nres=0 ;
1.202     brouard  10372:   /* double ftolpl = 1.e-10; */
1.180     brouard  10373:   double age, agebase, agelim;
1.203     brouard  10374:   double tot;
1.180     brouard  10375: 
1.202     brouard  10376:   strcpy(filerespl,"PL_");
                   10377:   strcat(filerespl,fileresu);
                   10378:   if((ficrespl=fopen(filerespl,"w"))==NULL) {
1.288     brouard  10379:     printf("Problem with forward period (stable) prevalence resultfile: %s\n", filerespl);return 1;
                   10380:     fprintf(ficlog,"Problem with forward period (stable) prevalence resultfile: %s\n", filerespl);return 1;
1.202     brouard  10381:   }
1.288     brouard  10382:   printf("\nComputing forward period (stable) prevalence: result on file '%s' \n", filerespl);
                   10383:   fprintf(ficlog,"\nComputing forward period (stable) prevalence: result on file '%s' \n", filerespl);
1.202     brouard  10384:   pstamp(ficrespl);
1.288     brouard  10385:   fprintf(ficrespl,"# Forward period (stable) prevalence. Precision given by ftolpl=%g \n", ftolpl);
1.202     brouard  10386:   fprintf(ficrespl,"#Age ");
                   10387:   for(i=1; i<=nlstate;i++) fprintf(ficrespl,"%d-%d ",i,i);
                   10388:   fprintf(ficrespl,"\n");
1.180     brouard  10389:   
1.219     brouard  10390:   /* prlim=matrix(1,nlstate,1,nlstate);*/ /* back in main */
1.180     brouard  10391: 
1.219     brouard  10392:   agebase=ageminpar;
                   10393:   agelim=agemaxpar;
1.180     brouard  10394: 
1.227     brouard  10395:   /* i1=pow(2,ncoveff); */
1.234     brouard  10396:   i1=pow(2,cptcoveff); /* Number of combination of dummy covariates */
1.219     brouard  10397:   if (cptcovn < 1){i1=1;}
1.180     brouard  10398: 
1.238     brouard  10399:   for(k=1; k<=i1;k++){ /* For each combination k of dummy covariates in the model */
                   10400:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.253     brouard  10401:       if(i1 != 1 && TKresult[nres]!= k)
1.238     brouard  10402:        continue;
1.235     brouard  10403: 
1.238     brouard  10404:       /* for(cptcov=1,k=0;cptcov<=i1;cptcov++){ */
                   10405:       /* for(cptcov=1,k=0;cptcov<=1;cptcov++){ */
                   10406:       //for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){
                   10407:       /* k=k+1; */
                   10408:       /* to clean */
                   10409:       //printf("cptcov=%d cptcod=%d codtab=%d\n",cptcov, cptcod,codtabm(cptcod,cptcov));
                   10410:       fprintf(ficrespl,"#******");
                   10411:       printf("#******");
                   10412:       fprintf(ficlog,"#******");
                   10413:       for(j=1;j<=cptcoveff ;j++) {/* all covariates */
                   10414:        fprintf(ficrespl," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]); /* Here problem for varying dummy*/
                   10415:        printf(" V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   10416:        fprintf(ficlog," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   10417:       }
                   10418:       for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
                   10419:        printf(" V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
                   10420:        fprintf(ficrespl," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
                   10421:        fprintf(ficlog," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
                   10422:       }
                   10423:       fprintf(ficrespl,"******\n");
                   10424:       printf("******\n");
                   10425:       fprintf(ficlog,"******\n");
                   10426:       if(invalidvarcomb[k]){
                   10427:        printf("\nCombination (%d) ignored because no case \n",k); 
                   10428:        fprintf(ficrespl,"#Combination (%d) ignored because no case \n",k); 
                   10429:        fprintf(ficlog,"\nCombination (%d) ignored because no case \n",k); 
                   10430:        continue;
                   10431:       }
1.219     brouard  10432: 
1.238     brouard  10433:       fprintf(ficrespl,"#Age ");
                   10434:       for(j=1;j<=cptcoveff;j++) {
                   10435:        fprintf(ficrespl,"V%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   10436:       }
                   10437:       for(i=1; i<=nlstate;i++) fprintf(ficrespl,"  %d-%d   ",i,i);
                   10438:       fprintf(ficrespl,"Total Years_to_converge\n");
1.227     brouard  10439:     
1.238     brouard  10440:       for (age=agebase; age<=agelim; age++){
                   10441:        /* for (age=agebase; age<=agebase; age++){ */
                   10442:        prevalim(prlim, nlstate, p, age, oldm, savm, ftolpl, ncvyearp, k, nres);
                   10443:        fprintf(ficrespl,"%.0f ",age );
                   10444:        for(j=1;j<=cptcoveff;j++)
                   10445:          fprintf(ficrespl,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   10446:        tot=0.;
                   10447:        for(i=1; i<=nlstate;i++){
                   10448:          tot +=  prlim[i][i];
                   10449:          fprintf(ficrespl," %.5f", prlim[i][i]);
                   10450:        }
                   10451:        fprintf(ficrespl," %.3f %d\n", tot, *ncvyearp);
                   10452:       } /* Age */
                   10453:       /* was end of cptcod */
                   10454:     } /* cptcov */
                   10455:   } /* nres */
1.219     brouard  10456:   return 0;
1.180     brouard  10457: }
                   10458: 
1.218     brouard  10459: 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  10460:        /*--------------- Back Prevalence limit  (backward stable prevalence) --------------*/
1.218     brouard  10461:        
                   10462:        /* Computes the back prevalence limit  for any combination      of covariate values 
                   10463:    * at any age between ageminpar and agemaxpar
                   10464:         */
1.235     brouard  10465:   int i, j, k, i1, nres=0 ;
1.217     brouard  10466:   /* double ftolpl = 1.e-10; */
                   10467:   double age, agebase, agelim;
                   10468:   double tot;
1.218     brouard  10469:   /* double ***mobaverage; */
                   10470:   /* double     **dnewm, **doldm, **dsavm;  /\* for use *\/ */
1.217     brouard  10471: 
                   10472:   strcpy(fileresplb,"PLB_");
                   10473:   strcat(fileresplb,fileresu);
                   10474:   if((ficresplb=fopen(fileresplb,"w"))==NULL) {
1.288     brouard  10475:     printf("Problem with backward prevalence resultfile: %s\n", fileresplb);return 1;
                   10476:     fprintf(ficlog,"Problem with backward prevalence resultfile: %s\n", fileresplb);return 1;
1.217     brouard  10477:   }
1.288     brouard  10478:   printf("Computing backward prevalence: result on file '%s' \n", fileresplb);
                   10479:   fprintf(ficlog,"Computing backward prevalence: result on file '%s' \n", fileresplb);
1.217     brouard  10480:   pstamp(ficresplb);
1.288     brouard  10481:   fprintf(ficresplb,"# Backward prevalence. Precision given by ftolpl=%g \n", ftolpl);
1.217     brouard  10482:   fprintf(ficresplb,"#Age ");
                   10483:   for(i=1; i<=nlstate;i++) fprintf(ficresplb,"%d-%d ",i,i);
                   10484:   fprintf(ficresplb,"\n");
                   10485:   
1.218     brouard  10486:   
                   10487:   /* prlim=matrix(1,nlstate,1,nlstate);*/ /* back in main */
                   10488:   
                   10489:   agebase=ageminpar;
                   10490:   agelim=agemaxpar;
                   10491:   
                   10492:   
1.227     brouard  10493:   i1=pow(2,cptcoveff);
1.218     brouard  10494:   if (cptcovn < 1){i1=1;}
1.227     brouard  10495:   
1.238     brouard  10496:   for(nres=1; nres <= nresult; nres++){ /* For each resultline */
                   10497:     for(k=1; k<=i1;k++){ /* For any combination of dummy covariates, fixed and varying */
1.253     brouard  10498:      if(i1 != 1 && TKresult[nres]!= k)
1.238     brouard  10499:        continue;
                   10500:       //printf("cptcov=%d cptcod=%d codtab=%d\n",cptcov, cptcod,codtabm(cptcod,cptcov));
                   10501:       fprintf(ficresplb,"#******");
                   10502:       printf("#******");
                   10503:       fprintf(ficlog,"#******");
                   10504:       for(j=1;j<=cptcoveff ;j++) {/* all covariates */
                   10505:        fprintf(ficresplb," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   10506:        printf(" V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   10507:        fprintf(ficlog," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   10508:       }
                   10509:       for (j=1; j<= nsq; j++){ /* For each selected (single) quantitative value */
                   10510:        printf(" V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]);
                   10511:        fprintf(ficresplb," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]);
                   10512:        fprintf(ficlog," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]);
                   10513:       }
                   10514:       fprintf(ficresplb,"******\n");
                   10515:       printf("******\n");
                   10516:       fprintf(ficlog,"******\n");
                   10517:       if(invalidvarcomb[k]){
                   10518:        printf("\nCombination (%d) ignored because no cases \n",k); 
                   10519:        fprintf(ficresplb,"#Combination (%d) ignored because no cases \n",k); 
                   10520:        fprintf(ficlog,"\nCombination (%d) ignored because no cases \n",k); 
                   10521:        continue;
                   10522:       }
1.218     brouard  10523:     
1.238     brouard  10524:       fprintf(ficresplb,"#Age ");
                   10525:       for(j=1;j<=cptcoveff;j++) {
                   10526:        fprintf(ficresplb,"V%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   10527:       }
                   10528:       for(i=1; i<=nlstate;i++) fprintf(ficresplb,"  %d-%d   ",i,i);
                   10529:       fprintf(ficresplb,"Total Years_to_converge\n");
1.218     brouard  10530:     
                   10531:     
1.238     brouard  10532:       for (age=agebase; age<=agelim; age++){
                   10533:        /* for (age=agebase; age<=agebase; age++){ */
                   10534:        if(mobilavproj > 0){
                   10535:          /* bprevalim(bprlim, mobaverage, nlstate, p, age, ageminpar, agemaxpar, oldm, savm, doldm, dsavm, ftolpl, ncvyearp, k); */
                   10536:          /* bprevalim(bprlim, mobaverage, nlstate, p, age, oldm, savm, dnewm, doldm, dsavm, ftolpl, ncvyearp, k); */
1.242     brouard  10537:          bprevalim(bprlim, mobaverage, nlstate, p, age, ftolpl, ncvyearp, k, nres);
1.238     brouard  10538:        }else if (mobilavproj == 0){
                   10539:          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);
                   10540:          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);
                   10541:          exit(1);
                   10542:        }else{
                   10543:          /* bprevalim(bprlim, probs, nlstate, p, age, oldm, savm, dnewm, doldm, dsavm, ftolpl, ncvyearp, k); */
1.242     brouard  10544:          bprevalim(bprlim, probs, nlstate, p, age, ftolpl, ncvyearp, k,nres);
1.266     brouard  10545:          /* printf("TOTOT\n"); */
                   10546:           /* exit(1); */
1.238     brouard  10547:        }
                   10548:        fprintf(ficresplb,"%.0f ",age );
                   10549:        for(j=1;j<=cptcoveff;j++)
                   10550:          fprintf(ficresplb,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   10551:        tot=0.;
                   10552:        for(i=1; i<=nlstate;i++){
                   10553:          tot +=  bprlim[i][i];
                   10554:          fprintf(ficresplb," %.5f", bprlim[i][i]);
                   10555:        }
                   10556:        fprintf(ficresplb," %.3f %d\n", tot, *ncvyearp);
                   10557:       } /* Age */
                   10558:       /* was end of cptcod */
1.255     brouard  10559:       /*fprintf(ficresplb,"\n");*/ /* Seems to be necessary for gnuplot only if two result lines and no covariate. */
1.238     brouard  10560:     } /* end of any combination */
                   10561:   } /* end of nres */  
1.218     brouard  10562:   /* hBijx(p, bage, fage); */
                   10563:   /* fclose(ficrespijb); */
                   10564:   
                   10565:   return 0;
1.217     brouard  10566: }
1.218     brouard  10567:  
1.180     brouard  10568: int hPijx(double *p, int bage, int fage){
                   10569:     /*------------- h Pij x at various ages ------------*/
                   10570: 
                   10571:   int stepsize;
                   10572:   int agelim;
                   10573:   int hstepm;
                   10574:   int nhstepm;
1.235     brouard  10575:   int h, i, i1, j, k, k4, nres=0;
1.180     brouard  10576: 
                   10577:   double agedeb;
                   10578:   double ***p3mat;
                   10579: 
1.201     brouard  10580:     strcpy(filerespij,"PIJ_");  strcat(filerespij,fileresu);
1.180     brouard  10581:     if((ficrespij=fopen(filerespij,"w"))==NULL) {
                   10582:       printf("Problem with Pij resultfile: %s\n", filerespij); return 1;
                   10583:       fprintf(ficlog,"Problem with Pij resultfile: %s\n", filerespij); return 1;
                   10584:     }
                   10585:     printf("Computing pij: result on file '%s' \n", filerespij);
                   10586:     fprintf(ficlog,"Computing pij: result on file '%s' \n", filerespij);
                   10587:   
                   10588:     stepsize=(int) (stepm+YEARM-1)/YEARM;
                   10589:     /*if (stepm<=24) stepsize=2;*/
                   10590: 
                   10591:     agelim=AGESUP;
                   10592:     hstepm=stepsize*YEARM; /* Every year of age */
                   10593:     hstepm=hstepm/stepm; /* Typically 2 years, = 2/6 months = 4 */ 
1.218     brouard  10594:                
1.180     brouard  10595:     /* hstepm=1;   aff par mois*/
                   10596:     pstamp(ficrespij);
                   10597:     fprintf(ficrespij,"#****** h Pij x Probability to be in state j at age x+h being in i at x ");
1.227     brouard  10598:     i1= pow(2,cptcoveff);
1.218     brouard  10599:                /* for(cptcov=1,k=0;cptcov<=i1;cptcov++){ */
                   10600:                /*    /\*for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*\/ */
                   10601:                /*      k=k+1;  */
1.235     brouard  10602:     for(nres=1; nres <= nresult; nres++) /* For each resultline */
                   10603:     for(k=1; k<=i1;k++){
1.253     brouard  10604:       if(i1 != 1 && TKresult[nres]!= k)
1.235     brouard  10605:        continue;
1.183     brouard  10606:       fprintf(ficrespij,"\n#****** ");
1.227     brouard  10607:       for(j=1;j<=cptcoveff;j++) 
1.198     brouard  10608:        fprintf(ficrespij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
1.235     brouard  10609:       for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
                   10610:        printf(" V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
                   10611:        fprintf(ficrespij," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
                   10612:       }
1.183     brouard  10613:       fprintf(ficrespij,"******\n");
                   10614:       
                   10615:       for (agedeb=fage; agedeb>=bage; agedeb--){ /* If stepm=6 months */
                   10616:        nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */ 
                   10617:        nhstepm = nhstepm/hstepm; /* Typically 40/4=10 */
                   10618:        
                   10619:        /*        nhstepm=nhstepm*YEARM; aff par mois*/
1.180     brouard  10620:        
1.183     brouard  10621:        p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   10622:        oldm=oldms;savm=savms;
1.235     brouard  10623:        hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k, nres);  
1.183     brouard  10624:        fprintf(ficrespij,"# Cov Agex agex+h hpijx with i,j=");
                   10625:        for(i=1; i<=nlstate;i++)
                   10626:          for(j=1; j<=nlstate+ndeath;j++)
                   10627:            fprintf(ficrespij," %1d-%1d",i,j);
                   10628:        fprintf(ficrespij,"\n");
                   10629:        for (h=0; h<=nhstepm; h++){
                   10630:          /*agedebphstep = agedeb + h*hstepm/YEARM*stepm;*/
                   10631:          fprintf(ficrespij,"%d %3.f %3.f",k, agedeb, agedeb + h*hstepm/YEARM*stepm );
1.180     brouard  10632:          for(i=1; i<=nlstate;i++)
                   10633:            for(j=1; j<=nlstate+ndeath;j++)
1.183     brouard  10634:              fprintf(ficrespij," %.5f", p3mat[i][j][h]);
1.180     brouard  10635:          fprintf(ficrespij,"\n");
                   10636:        }
1.183     brouard  10637:        free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   10638:        fprintf(ficrespij,"\n");
                   10639:       }
1.180     brouard  10640:       /*}*/
                   10641:     }
1.218     brouard  10642:     return 0;
1.180     brouard  10643: }
1.218     brouard  10644:  
                   10645:  int hBijx(double *p, int bage, int fage, double ***prevacurrent){
1.217     brouard  10646:     /*------------- h Bij x at various ages ------------*/
                   10647: 
                   10648:   int stepsize;
1.218     brouard  10649:   /* int agelim; */
                   10650:        int ageminl;
1.217     brouard  10651:   int hstepm;
                   10652:   int nhstepm;
1.238     brouard  10653:   int h, i, i1, j, k, nres;
1.218     brouard  10654:        
1.217     brouard  10655:   double agedeb;
                   10656:   double ***p3mat;
1.218     brouard  10657:        
                   10658:   strcpy(filerespijb,"PIJB_");  strcat(filerespijb,fileresu);
                   10659:   if((ficrespijb=fopen(filerespijb,"w"))==NULL) {
                   10660:     printf("Problem with Pij back resultfile: %s\n", filerespijb); return 1;
                   10661:     fprintf(ficlog,"Problem with Pij back resultfile: %s\n", filerespijb); return 1;
                   10662:   }
                   10663:   printf("Computing pij back: result on file '%s' \n", filerespijb);
                   10664:   fprintf(ficlog,"Computing pij back: result on file '%s' \n", filerespijb);
                   10665:   
                   10666:   stepsize=(int) (stepm+YEARM-1)/YEARM;
                   10667:   /*if (stepm<=24) stepsize=2;*/
1.217     brouard  10668:   
1.218     brouard  10669:   /* agelim=AGESUP; */
1.289     brouard  10670:   ageminl=AGEINF; /* was 30 */
1.218     brouard  10671:   hstepm=stepsize*YEARM; /* Every year of age */
                   10672:   hstepm=hstepm/stepm; /* Typically 2 years, = 2/6 months = 4 */
                   10673:   
                   10674:   /* hstepm=1;   aff par mois*/
                   10675:   pstamp(ficrespijb);
1.255     brouard  10676:   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  10677:   i1= pow(2,cptcoveff);
1.218     brouard  10678:   /* for(cptcov=1,k=0;cptcov<=i1;cptcov++){ */
                   10679:   /*    /\*for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*\/ */
                   10680:   /*   k=k+1;  */
1.238     brouard  10681:   for(nres=1; nres <= nresult; nres++){ /* For each resultline */
                   10682:     for(k=1; k<=i1;k++){ /* For any combination of dummy covariates, fixed and varying */
1.253     brouard  10683:       if(i1 != 1 && TKresult[nres]!= k)
1.238     brouard  10684:        continue;
                   10685:       fprintf(ficrespijb,"\n#****** ");
                   10686:       for(j=1;j<=cptcoveff;j++)
                   10687:        fprintf(ficrespijb,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   10688:       for (j=1; j<= nsq; j++){ /* For each selected (single) quantitative value */
                   10689:        fprintf(ficrespijb," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]);
                   10690:       }
                   10691:       fprintf(ficrespijb,"******\n");
1.264     brouard  10692:       if(invalidvarcomb[k]){  /* Is it necessary here? */
1.238     brouard  10693:        fprintf(ficrespijb,"\n#Combination (%d) ignored because no cases \n",k); 
                   10694:        continue;
                   10695:       }
                   10696:       
                   10697:       /* for (agedeb=fage; agedeb>=bage; agedeb--){ /\* If stepm=6 months *\/ */
                   10698:       for (agedeb=bage; agedeb<=fage; agedeb++){ /* If stepm=6 months and estepm=24 (2 years) */
                   10699:        /* nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm); /\* Typically 20 years = 20*12/6=40 *\/ */
                   10700:        nhstepm=(int) rint((agedeb-ageminl)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */
                   10701:        nhstepm = nhstepm/hstepm; /* Typically 40/4=10, because estepm=24 stepm=6 => hstepm=24/6=4 */
                   10702:        
                   10703:        /*        nhstepm=nhstepm*YEARM; aff par mois*/
                   10704:        
1.266     brouard  10705:        p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm); /* We can't have it at an upper level because of nhstepm */
                   10706:        /* and memory limitations if stepm is small */
                   10707: 
1.238     brouard  10708:        /* oldm=oldms;savm=savms; */
                   10709:        /* hbxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);   */
1.267     brouard  10710:        hbxij(p3mat,nhstepm,agedeb,hstepm,p,prevacurrent,nlstate,stepm, k, nres);
1.238     brouard  10711:        /* hbxij(p3mat,nhstepm,agedeb,hstepm,p,prevacurrent,nlstate,stepm,oldm,savm, dnewm, doldm, dsavm, k); */
1.255     brouard  10712:        fprintf(ficrespijb,"# Cov Agex agex-h hbijx with i,j=");
1.217     brouard  10713:        for(i=1; i<=nlstate;i++)
                   10714:          for(j=1; j<=nlstate+ndeath;j++)
1.238     brouard  10715:            fprintf(ficrespijb," %1d-%1d",i,j);
1.217     brouard  10716:        fprintf(ficrespijb,"\n");
1.238     brouard  10717:        for (h=0; h<=nhstepm; h++){
                   10718:          /*agedebphstep = agedeb + h*hstepm/YEARM*stepm;*/
                   10719:          fprintf(ficrespijb,"%d %3.f %3.f",k, agedeb, agedeb - h*hstepm/YEARM*stepm );
                   10720:          /* fprintf(ficrespijb,"%d %3.f %3.f",k, agedeb, agedeb + h*hstepm/YEARM*stepm ); */
                   10721:          for(i=1; i<=nlstate;i++)
                   10722:            for(j=1; j<=nlstate+ndeath;j++)
                   10723:              fprintf(ficrespijb," %.5f", p3mat[i][j][h]);
                   10724:          fprintf(ficrespijb,"\n");
                   10725:        }
                   10726:        free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   10727:        fprintf(ficrespijb,"\n");
                   10728:       } /* end age deb */
                   10729:     } /* end combination */
                   10730:   } /* end nres */
1.218     brouard  10731:   return 0;
                   10732:  } /*  hBijx */
1.217     brouard  10733: 
1.180     brouard  10734: 
1.136     brouard  10735: /***********************************************/
                   10736: /**************** Main Program *****************/
                   10737: /***********************************************/
                   10738: 
                   10739: int main(int argc, char *argv[])
                   10740: {
                   10741: #ifdef GSL
                   10742:   const gsl_multimin_fminimizer_type *T;
                   10743:   size_t iteri = 0, it;
                   10744:   int rval = GSL_CONTINUE;
                   10745:   int status = GSL_SUCCESS;
                   10746:   double ssval;
                   10747: #endif
                   10748:   int movingaverage(double ***probs, double bage,double fage, double ***mobaverage, int mobilav);
1.290     brouard  10749:   int i,j, k, iter=0,m,size=100, cptcod; /* Suppressing because nobs */
                   10750:   /* int i,j, k, n=MAXN,iter=0,m,size=100, cptcod; */
1.209     brouard  10751:   int ncvyear=0; /* Number of years needed for the period prevalence to converge */
1.164     brouard  10752:   int jj, ll, li, lj, lk;
1.136     brouard  10753:   int numlinepar=0; /* Current linenumber of parameter file */
1.197     brouard  10754:   int num_filled;
1.136     brouard  10755:   int itimes;
                   10756:   int NDIM=2;
                   10757:   int vpopbased=0;
1.235     brouard  10758:   int nres=0;
1.258     brouard  10759:   int endishere=0;
1.277     brouard  10760:   int noffset=0;
1.274     brouard  10761:   int ncurrv=0; /* Temporary variable */
                   10762:   
1.164     brouard  10763:   char ca[32], cb[32];
1.136     brouard  10764:   /*  FILE *fichtm; *//* Html File */
                   10765:   /* FILE *ficgp;*/ /*Gnuplot File */
                   10766:   struct stat info;
1.191     brouard  10767:   double agedeb=0.;
1.194     brouard  10768: 
                   10769:   double ageminpar=AGEOVERFLOW,agemin=AGEOVERFLOW, agemaxpar=-AGEOVERFLOW, agemax=-AGEOVERFLOW;
1.219     brouard  10770:   double ageminout=-AGEOVERFLOW,agemaxout=AGEOVERFLOW; /* Smaller Age range redefined after movingaverage */
1.136     brouard  10771: 
1.165     brouard  10772:   double fret;
1.191     brouard  10773:   double dum=0.; /* Dummy variable */
1.136     brouard  10774:   double ***p3mat;
1.218     brouard  10775:   /* double ***mobaverage; */
1.164     brouard  10776: 
                   10777:   char line[MAXLINE];
1.197     brouard  10778:   char path[MAXLINE],pathc[MAXLINE],pathcd[MAXLINE],pathtot[MAXLINE];
                   10779: 
1.234     brouard  10780:   char  modeltemp[MAXLINE];
1.230     brouard  10781:   char resultline[MAXLINE];
                   10782:   
1.136     brouard  10783:   char pathr[MAXLINE], pathimach[MAXLINE]; 
1.164     brouard  10784:   char *tok, *val; /* pathtot */
1.290     brouard  10785:   int firstobs=1, lastobs=10; /* nobs = lastobs-firstobs declared globally ;*/
1.195     brouard  10786:   int c,  h , cpt, c2;
1.191     brouard  10787:   int jl=0;
                   10788:   int i1, j1, jk, stepsize=0;
1.194     brouard  10789:   int count=0;
                   10790: 
1.164     brouard  10791:   int *tab; 
1.136     brouard  10792:   int mobilavproj=0 , prevfcast=0 ; /* moving average of prev, If prevfcast=1 prevalence projection */
1.293     brouard  10793:   int backcast=0; /* defined as global for mlikeli and mle*/
1.136     brouard  10794:   int mobilav=0,popforecast=0;
1.191     brouard  10795:   int hstepm=0, nhstepm=0;
1.136     brouard  10796:   int agemortsup;
                   10797:   float  sumlpop=0.;
                   10798:   double jprev1=1, mprev1=1,anprev1=2000,jprev2=1, mprev2=1,anprev2=2000;
                   10799:   double jpyram=1, mpyram=1,anpyram=2000,jpyram1=1, mpyram1=1,anpyram1=2000;
                   10800: 
1.191     brouard  10801:   double bage=0, fage=110., age, agelim=0., agebase=0.;
1.136     brouard  10802:   double ftolpl=FTOL;
                   10803:   double **prlim;
1.217     brouard  10804:   double **bprlim;
1.136     brouard  10805:   double ***param; /* Matrix of parameters */
1.251     brouard  10806:   double ***paramstart; /* Matrix of starting parameter values */
                   10807:   double  *p, *pstart; /* p=param[1][1] pstart is for starting values guessed by freqsummary */
1.136     brouard  10808:   double **matcov; /* Matrix of covariance */
1.203     brouard  10809:   double **hess; /* Hessian matrix */
1.136     brouard  10810:   double ***delti3; /* Scale */
                   10811:   double *delti; /* Scale */
                   10812:   double ***eij, ***vareij;
                   10813:   double **varpl; /* Variances of prevalence limits by age */
1.269     brouard  10814: 
1.136     brouard  10815:   double *epj, vepp;
1.164     brouard  10816: 
1.273     brouard  10817:   double dateprev1, dateprev2;
                   10818:   double jproj1=1,mproj1=1,anproj1=2000,jproj2=1,mproj2=1,anproj2=2000, dateproj1=0, dateproj2=0;
                   10819:   double jback1=1,mback1=1,anback1=2000,jback2=1,mback2=1,anback2=2000, dateback1=0, dateback2=0;
1.217     brouard  10820: 
1.136     brouard  10821:   double **ximort;
1.145     brouard  10822:   char *alph[]={"a","a","b","c","d","e"}, str[4]="1234";
1.136     brouard  10823:   int *dcwave;
                   10824: 
1.164     brouard  10825:   char z[1]="c";
1.136     brouard  10826: 
                   10827:   /*char  *strt;*/
                   10828:   char strtend[80];
1.126     brouard  10829: 
1.164     brouard  10830: 
1.126     brouard  10831: /*   setlocale (LC_ALL, ""); */
                   10832: /*   bindtextdomain (PACKAGE, LOCALEDIR); */
                   10833: /*   textdomain (PACKAGE); */
                   10834: /*   setlocale (LC_CTYPE, ""); */
                   10835: /*   setlocale (LC_MESSAGES, ""); */
                   10836: 
                   10837:   /*   gettimeofday(&start_time, (struct timezone*)0); */ /* at first time */
1.157     brouard  10838:   rstart_time = time(NULL);  
                   10839:   /*  (void) gettimeofday(&start_time,&tzp);*/
                   10840:   start_time = *localtime(&rstart_time);
1.126     brouard  10841:   curr_time=start_time;
1.157     brouard  10842:   /*tml = *localtime(&start_time.tm_sec);*/
                   10843:   /* strcpy(strstart,asctime(&tml)); */
                   10844:   strcpy(strstart,asctime(&start_time));
1.126     brouard  10845: 
                   10846: /*  printf("Localtime (at start)=%s",strstart); */
1.157     brouard  10847: /*  tp.tm_sec = tp.tm_sec +86400; */
                   10848: /*  tm = *localtime(&start_time.tm_sec); */
1.126     brouard  10849: /*   tmg.tm_year=tmg.tm_year +dsign*dyear; */
                   10850: /*   tmg.tm_mon=tmg.tm_mon +dsign*dmonth; */
                   10851: /*   tmg.tm_hour=tmg.tm_hour + 1; */
1.157     brouard  10852: /*   tp.tm_sec = mktime(&tmg); */
1.126     brouard  10853: /*   strt=asctime(&tmg); */
                   10854: /*   printf("Time(after) =%s",strstart);  */
                   10855: /*  (void) time (&time_value);
                   10856: *  printf("time=%d,t-=%d\n",time_value,time_value-86400);
                   10857: *  tm = *localtime(&time_value);
                   10858: *  strstart=asctime(&tm);
                   10859: *  printf("tim_value=%d,asctime=%s\n",time_value,strstart); 
                   10860: */
                   10861: 
                   10862:   nberr=0; /* Number of errors and warnings */
                   10863:   nbwarn=0;
1.184     brouard  10864: #ifdef WIN32
                   10865:   _getcwd(pathcd, size);
                   10866: #else
1.126     brouard  10867:   getcwd(pathcd, size);
1.184     brouard  10868: #endif
1.191     brouard  10869:   syscompilerinfo(0);
1.196     brouard  10870:   printf("\nIMaCh version %s, %s\n%s",version, copyright, fullversion);
1.126     brouard  10871:   if(argc <=1){
                   10872:     printf("\nEnter the parameter file name: ");
1.205     brouard  10873:     if(!fgets(pathr,FILENAMELENGTH,stdin)){
                   10874:       printf("ERROR Empty parameter file name\n");
                   10875:       goto end;
                   10876:     }
1.126     brouard  10877:     i=strlen(pathr);
                   10878:     if(pathr[i-1]=='\n')
                   10879:       pathr[i-1]='\0';
1.156     brouard  10880:     i=strlen(pathr);
1.205     brouard  10881:     if(i >= 1 && pathr[i-1]==' ') {/* This may happen when dragging on oS/X! */
1.156     brouard  10882:       pathr[i-1]='\0';
1.205     brouard  10883:     }
                   10884:     i=strlen(pathr);
                   10885:     if( i==0 ){
                   10886:       printf("ERROR Empty parameter file name\n");
                   10887:       goto end;
                   10888:     }
                   10889:     for (tok = pathr; tok != NULL; ){
1.126     brouard  10890:       printf("Pathr |%s|\n",pathr);
                   10891:       while ((val = strsep(&tok, "\"" )) != NULL && *val == '\0');
                   10892:       printf("val= |%s| pathr=%s\n",val,pathr);
                   10893:       strcpy (pathtot, val);
                   10894:       if(pathr[0] == '\0') break; /* Dirty */
                   10895:     }
                   10896:   }
1.281     brouard  10897:   else if (argc<=2){
                   10898:     strcpy(pathtot,argv[1]);
                   10899:   }
1.126     brouard  10900:   else{
                   10901:     strcpy(pathtot,argv[1]);
1.281     brouard  10902:     strcpy(z,argv[2]);
                   10903:     printf("\nargv[2]=%s z=%c\n",argv[2],z[0]);
1.126     brouard  10904:   }
                   10905:   /*if(getcwd(pathcd, MAXLINE)!= NULL)printf ("Error pathcd\n");*/
                   10906:   /*cygwin_split_path(pathtot,path,optionfile);
                   10907:     printf("pathtot=%s, path=%s, optionfile=%s\n",pathtot,path,optionfile);*/
                   10908:   /* cutv(path,optionfile,pathtot,'\\');*/
                   10909: 
                   10910:   /* Split argv[0], imach program to get pathimach */
                   10911:   printf("\nargv[0]=%s argv[1]=%s, \n",argv[0],argv[1]);
                   10912:   split(argv[0],pathimach,optionfile,optionfilext,optionfilefiname);
                   10913:   printf("\nargv[0]=%s pathimach=%s, \noptionfile=%s \noptionfilext=%s \noptionfilefiname=%s\n",argv[0],pathimach,optionfile,optionfilext,optionfilefiname);
                   10914:  /*   strcpy(pathimach,argv[0]); */
                   10915:   /* Split argv[1]=pathtot, parameter file name to get path, optionfile, extension and name */
                   10916:   split(pathtot,path,optionfile,optionfilext,optionfilefiname);
                   10917:   printf("\npathtot=%s,\npath=%s,\noptionfile=%s \noptionfilext=%s \noptionfilefiname=%s\n",pathtot,path,optionfile,optionfilext,optionfilefiname);
1.184     brouard  10918: #ifdef WIN32
                   10919:   _chdir(path); /* Can be a relative path */
                   10920:   if(_getcwd(pathcd,MAXLINE) > 0) /* So pathcd is the full path */
                   10921: #else
1.126     brouard  10922:   chdir(path); /* Can be a relative path */
1.184     brouard  10923:   if (getcwd(pathcd, MAXLINE) > 0) /* So pathcd is the full path */
                   10924: #endif
                   10925:   printf("Current directory %s!\n",pathcd);
1.126     brouard  10926:   strcpy(command,"mkdir ");
                   10927:   strcat(command,optionfilefiname);
                   10928:   if((outcmd=system(command)) != 0){
1.169     brouard  10929:     printf("Directory already exists (or can't create it) %s%s, err=%d\n",path,optionfilefiname,outcmd);
1.126     brouard  10930:     /* fprintf(ficlog,"Problem creating directory %s%s\n",path,optionfilefiname); */
                   10931:     /* fclose(ficlog); */
                   10932: /*     exit(1); */
                   10933:   }
                   10934: /*   if((imk=mkdir(optionfilefiname))<0){ */
                   10935: /*     perror("mkdir"); */
                   10936: /*   } */
                   10937: 
                   10938:   /*-------- arguments in the command line --------*/
                   10939: 
1.186     brouard  10940:   /* Main Log file */
1.126     brouard  10941:   strcat(filelog, optionfilefiname);
                   10942:   strcat(filelog,".log");    /* */
                   10943:   if((ficlog=fopen(filelog,"w"))==NULL)    {
                   10944:     printf("Problem with logfile %s\n",filelog);
                   10945:     goto end;
                   10946:   }
                   10947:   fprintf(ficlog,"Log filename:%s\n",filelog);
1.197     brouard  10948:   fprintf(ficlog,"Version %s %s",version,fullversion);
1.126     brouard  10949:   fprintf(ficlog,"\nEnter the parameter file name: \n");
                   10950:   fprintf(ficlog,"pathimach=%s\npathtot=%s\n\
                   10951:  path=%s \n\
                   10952:  optionfile=%s\n\
                   10953:  optionfilext=%s\n\
1.156     brouard  10954:  optionfilefiname='%s'\n",pathimach,pathtot,path,optionfile,optionfilext,optionfilefiname);
1.126     brouard  10955: 
1.197     brouard  10956:   syscompilerinfo(1);
1.167     brouard  10957: 
1.126     brouard  10958:   printf("Local time (at start):%s",strstart);
                   10959:   fprintf(ficlog,"Local time (at start): %s",strstart);
                   10960:   fflush(ficlog);
                   10961: /*   (void) gettimeofday(&curr_time,&tzp); */
1.157     brouard  10962: /*   printf("Elapsed time %d\n", asc_diff_time(curr_time.tm_sec-start_time.tm_sec,tmpout)); */
1.126     brouard  10963: 
                   10964:   /* */
                   10965:   strcpy(fileres,"r");
                   10966:   strcat(fileres, optionfilefiname);
1.201     brouard  10967:   strcat(fileresu, optionfilefiname); /* Without r in front */
1.126     brouard  10968:   strcat(fileres,".txt");    /* Other files have txt extension */
1.201     brouard  10969:   strcat(fileresu,".txt");    /* Other files have txt extension */
1.126     brouard  10970: 
1.186     brouard  10971:   /* Main ---------arguments file --------*/
1.126     brouard  10972: 
                   10973:   if((ficpar=fopen(optionfile,"r"))==NULL)    {
1.155     brouard  10974:     printf("Problem with optionfile '%s' with errno='%s'\n",optionfile,strerror(errno));
                   10975:     fprintf(ficlog,"Problem with optionfile '%s' with errno='%s'\n",optionfile,strerror(errno));
1.126     brouard  10976:     fflush(ficlog);
1.149     brouard  10977:     /* goto end; */
                   10978:     exit(70); 
1.126     brouard  10979:   }
                   10980: 
                   10981:   strcpy(filereso,"o");
1.201     brouard  10982:   strcat(filereso,fileresu);
1.126     brouard  10983:   if((ficparo=fopen(filereso,"w"))==NULL) { /* opened on subdirectory */
                   10984:     printf("Problem with Output resultfile: %s\n", filereso);
                   10985:     fprintf(ficlog,"Problem with Output resultfile: %s\n", filereso);
                   10986:     fflush(ficlog);
                   10987:     goto end;
                   10988:   }
1.278     brouard  10989:       /*-------- Rewriting parameter file ----------*/
                   10990:   strcpy(rfileres,"r");    /* "Rparameterfile */
                   10991:   strcat(rfileres,optionfilefiname);    /* Parameter file first name */
                   10992:   strcat(rfileres,".");    /* */
                   10993:   strcat(rfileres,optionfilext);    /* Other files have txt extension */
                   10994:   if((ficres =fopen(rfileres,"w"))==NULL) {
                   10995:     printf("Problem writing new parameter file: %s\n", rfileres);goto end;
                   10996:     fprintf(ficlog,"Problem writing new parameter file: %s\n", rfileres);goto end;
                   10997:     fflush(ficlog);
                   10998:     goto end;
                   10999:   }
                   11000:   fprintf(ficres,"#IMaCh %s\n",version);
1.126     brouard  11001: 
1.278     brouard  11002:                                      
1.126     brouard  11003:   /* Reads comments: lines beginning with '#' */
                   11004:   numlinepar=0;
1.277     brouard  11005:   /* Is it a BOM UTF-8 Windows file? */
                   11006:   /* First parameter line */
1.197     brouard  11007:   while(fgets(line, MAXLINE, ficpar)) {
1.277     brouard  11008:     noffset=0;
                   11009:     if( line[0] == (char)0xEF && line[1] == (char)0xBB) /* EF BB BF */
                   11010:     {
                   11011:       noffset=noffset+3;
                   11012:       printf("# File is an UTF8 Bom.\n"); // 0xBF
                   11013:     }
                   11014:     else if( line[0] == (char)0xFE && line[1] == (char)0xFF)
                   11015:     {
                   11016:       noffset=noffset+2;
                   11017:       printf("# File is an UTF16BE BOM file\n");
                   11018:     }
                   11019:     else if( line[0] == 0 && line[1] == 0)
                   11020:     {
                   11021:       if( line[2] == (char)0xFE && line[3] == (char)0xFF){
                   11022:        noffset=noffset+4;
                   11023:        printf("# File is an UTF16BE BOM file\n");
                   11024:       }
                   11025:     } else{
                   11026:       ;/*printf(" Not a BOM file\n");*/
                   11027:     }
                   11028:   
1.197     brouard  11029:     /* If line starts with a # it is a comment */
1.277     brouard  11030:     if (line[noffset] == '#') {
1.197     brouard  11031:       numlinepar++;
                   11032:       fputs(line,stdout);
                   11033:       fputs(line,ficparo);
1.278     brouard  11034:       fputs(line,ficres);
1.197     brouard  11035:       fputs(line,ficlog);
                   11036:       continue;
                   11037:     }else
                   11038:       break;
                   11039:   }
                   11040:   if((num_filled=sscanf(line,"title=%s datafile=%s lastobs=%d firstpass=%d lastpass=%d\n", \
                   11041:                        title, datafile, &lastobs, &firstpass,&lastpass)) !=EOF){
                   11042:     if (num_filled != 5) {
                   11043:       printf("Should be 5 parameters\n");
1.283     brouard  11044:       fprintf(ficlog,"Should be 5 parameters\n");
1.197     brouard  11045:     }
1.126     brouard  11046:     numlinepar++;
1.197     brouard  11047:     printf("title=%s datafile=%s lastobs=%d firstpass=%d lastpass=%d\n", title, datafile, lastobs, firstpass,lastpass);
1.283     brouard  11048:     fprintf(ficparo,"title=%s datafile=%s lastobs=%d firstpass=%d lastpass=%d\n", title, datafile, lastobs, firstpass,lastpass);
                   11049:     fprintf(ficres,"title=%s datafile=%s lastobs=%d firstpass=%d lastpass=%d\n", title, datafile, lastobs, firstpass,lastpass);
                   11050:     fprintf(ficlog,"title=%s datafile=%s lastobs=%d firstpass=%d lastpass=%d\n", title, datafile, lastobs, firstpass,lastpass);
1.197     brouard  11051:   }
                   11052:   /* Second parameter line */
                   11053:   while(fgets(line, MAXLINE, ficpar)) {
1.283     brouard  11054:     /* while(fscanf(ficpar,"%[^\n]", line)) { */
                   11055:     /* If line starts with a # it is a comment. Strangely fgets reads the EOL and fputs doesn't */
1.197     brouard  11056:     if (line[0] == '#') {
                   11057:       numlinepar++;
1.283     brouard  11058:       printf("%s",line);
                   11059:       fprintf(ficres,"%s",line);
                   11060:       fprintf(ficparo,"%s",line);
                   11061:       fprintf(ficlog,"%s",line);
1.197     brouard  11062:       continue;
                   11063:     }else
                   11064:       break;
                   11065:   }
1.223     brouard  11066:   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", \
                   11067:                        &ftol, &stepm, &ncovcol, &nqv, &ntv, &nqtv, &nlstate, &ndeath, &maxwav, &mle, &weightopt)) !=EOF){
                   11068:     if (num_filled != 11) {
                   11069:       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  11070:       printf("but line=%s\n",line);
1.283     brouard  11071:       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");
                   11072:       fprintf(ficlog,"but line=%s\n",line);
1.197     brouard  11073:     }
1.286     brouard  11074:     if( lastpass > maxwav){
                   11075:       printf("Error (lastpass = %d) > (maxwav = %d)\n",lastpass, maxwav);
                   11076:       fprintf(ficlog,"Error (lastpass = %d) > (maxwav = %d)\n",lastpass, maxwav);
                   11077:       fflush(ficlog);
                   11078:       goto end;
                   11079:     }
                   11080:       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  11081:     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  11082:     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  11083:     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  11084:   }
1.203     brouard  11085:   /* ftolpl=6*ftol*1.e5; /\* 6.e-3 make convergences in less than 80 loops for the prevalence limit *\/ */
1.209     brouard  11086:   /*ftolpl=6.e-4; *//* 6.e-3 make convergences in less than 80 loops for the prevalence limit */
1.197     brouard  11087:   /* Third parameter line */
                   11088:   while(fgets(line, MAXLINE, ficpar)) {
                   11089:     /* If line starts with a # it is a comment */
                   11090:     if (line[0] == '#') {
                   11091:       numlinepar++;
1.283     brouard  11092:       printf("%s",line);
                   11093:       fprintf(ficres,"%s",line);
                   11094:       fprintf(ficparo,"%s",line);
                   11095:       fprintf(ficlog,"%s",line);
1.197     brouard  11096:       continue;
                   11097:     }else
                   11098:       break;
                   11099:   }
1.201     brouard  11100:   if((num_filled=sscanf(line,"model=1+age%[^.\n]", model)) !=EOF){
1.279     brouard  11101:     if (num_filled != 1){
                   11102:       printf("ERROR %d: Model should be at minimum 'model=1+age' %s\n",num_filled, line);
                   11103:       fprintf(ficlog,"ERROR %d: Model should be at minimum 'model=1+age' %s\n",num_filled, line);
1.197     brouard  11104:       model[0]='\0';
                   11105:       goto end;
                   11106:     }
                   11107:     else{
                   11108:       if (model[0]=='+'){
                   11109:        for(i=1; i<=strlen(model);i++)
                   11110:          modeltemp[i-1]=model[i];
1.201     brouard  11111:        strcpy(model,modeltemp); 
1.197     brouard  11112:       }
                   11113:     }
1.199     brouard  11114:     /* printf(" model=1+age%s modeltemp= %s, model=%s\n",model, modeltemp, model);fflush(stdout); */
1.203     brouard  11115:     printf("model=1+age+%s\n",model);fflush(stdout);
1.283     brouard  11116:     fprintf(ficparo,"model=1+age+%s\n",model);fflush(stdout);
                   11117:     fprintf(ficres,"model=1+age+%s\n",model);fflush(stdout);
                   11118:     fprintf(ficlog,"model=1+age+%s\n",model);fflush(stdout);
1.197     brouard  11119:   }
                   11120:   /* 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); */
                   11121:   /* numlinepar=numlinepar+3; /\* In general *\/ */
                   11122:   /* 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  11123:   /* 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); */
                   11124:   /* 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  11125:   fflush(ficlog);
1.190     brouard  11126:   /* if(model[0]=='#'|| model[0]== '\0'){ */
                   11127:   if(model[0]=='#'){
1.279     brouard  11128:     printf("Error in 'model' line: model should start with 'model=1+age+' and end without space \n \
                   11129:  'model=1+age+' or 'model=1+age+V1.' or 'model=1+age+age*age+V1+V1*age' or \n \
                   11130:  'model=1+age+V1+V2' or 'model=1+age+V1+V2+V1*V2' etc. \n");           \
1.187     brouard  11131:     if(mle != -1){
1.279     brouard  11132:       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  11133:       exit(1);
                   11134:     }
                   11135:   }
1.126     brouard  11136:   while((c=getc(ficpar))=='#' && c!= EOF){
                   11137:     ungetc(c,ficpar);
                   11138:     fgets(line, MAXLINE, ficpar);
                   11139:     numlinepar++;
1.195     brouard  11140:     if(line[1]=='q'){ /* This #q will quit imach (the answer is q) */
                   11141:       z[0]=line[1];
                   11142:     }
                   11143:     /* printf("****line [1] = %c \n",line[1]); */
1.141     brouard  11144:     fputs(line, stdout);
                   11145:     //puts(line);
1.126     brouard  11146:     fputs(line,ficparo);
                   11147:     fputs(line,ficlog);
                   11148:   }
                   11149:   ungetc(c,ficpar);
                   11150: 
                   11151:    
1.290     brouard  11152:   covar=matrix(0,NCOVMAX,firstobs,lastobs);  /**< used in readdata */
                   11153:   if(nqv>=1)coqvar=matrix(1,nqv,firstobs,lastobs);  /**< Fixed quantitative covariate */
                   11154:   if(nqtv>=1)cotqvar=ma3x(1,maxwav,1,nqtv,firstobs,lastobs);  /**< Time varying quantitative covariate */
                   11155:   if(ntv+nqtv>=1)cotvar=ma3x(1,maxwav,1,ntv+nqtv,firstobs,lastobs);  /**< Time varying covariate (dummy and quantitative)*/
1.136     brouard  11156:   cptcovn=0; /*Number of covariates, i.e. number of '+' in model statement plus one, indepently of n in Vn*/
                   11157:   /* v1+v2+v3+v2*v4+v5*age makes cptcovn = 5
                   11158:      v1+v2*age+v2*v3 makes cptcovn = 3
                   11159:   */
                   11160:   if (strlen(model)>1) 
1.187     brouard  11161:     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  11162:   else
1.187     brouard  11163:     ncovmodel=2; /* Constant and age */
1.133     brouard  11164:   nforce= (nlstate+ndeath-1)*nlstate; /* Number of forces ij from state i to j */
                   11165:   npar= nforce*ncovmodel; /* Number of parameters like aij*/
1.131     brouard  11166:   if(npar >MAXPARM || nlstate >NLSTATEMAX || ndeath >NDEATHMAX || ncovmodel>NCOVMAX){
                   11167:     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);
                   11168:     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);
                   11169:     fflush(stdout);
                   11170:     fclose (ficlog);
                   11171:     goto end;
                   11172:   }
1.126     brouard  11173:   delti3= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
                   11174:   delti=delti3[1][1];
                   11175:   /*delti=vector(1,npar); *//* Scale of each paramater (output from hesscov)*/
                   11176:   if(mle==-1){ /* Print a wizard for help writing covariance matrix */
1.247     brouard  11177: /* We could also provide initial parameters values giving by simple logistic regression 
                   11178:  * only one way, that is without matrix product. We will have nlstate maximizations */
                   11179:       /* for(i=1;i<nlstate;i++){ */
                   11180:       /*       /\*reducing xi for 1 to npar to 1 to ncovmodel; *\/ */
                   11181:       /*    mlikeli(ficres,p, ncovmodel, ncovmodel, nlstate, ftol, funcnoprod); */
                   11182:       /* } */
1.126     brouard  11183:     prwizard(ncovmodel, nlstate, ndeath, model, ficparo);
1.191     brouard  11184:     printf(" You chose mle=-1, look at file %s for a template of covariance matrix \n",filereso);
                   11185:     fprintf(ficlog," You chose mle=-1, look at file %s for a template of covariance matrix \n",filereso);
1.126     brouard  11186:     free_ma3x(delti3,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel); 
                   11187:     fclose (ficparo);
                   11188:     fclose (ficlog);
                   11189:     goto end;
                   11190:     exit(0);
1.220     brouard  11191:   }  else if(mle==-5) { /* Main Wizard */
1.126     brouard  11192:     prwizard(ncovmodel, nlstate, ndeath, model, ficparo);
1.192     brouard  11193:     printf(" You chose mle=-3, look at file %s for a template of covariance matrix \n",filereso);
                   11194:     fprintf(ficlog," You chose mle=-3, look at file %s for a template of covariance matrix \n",filereso);
1.126     brouard  11195:     param= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
                   11196:     matcov=matrix(1,npar,1,npar);
1.203     brouard  11197:     hess=matrix(1,npar,1,npar);
1.220     brouard  11198:   }  else{ /* Begin of mle != -1 or -5 */
1.145     brouard  11199:     /* Read guessed parameters */
1.126     brouard  11200:     /* Reads comments: lines beginning with '#' */
                   11201:     while((c=getc(ficpar))=='#' && c!= EOF){
                   11202:       ungetc(c,ficpar);
                   11203:       fgets(line, MAXLINE, ficpar);
                   11204:       numlinepar++;
1.141     brouard  11205:       fputs(line,stdout);
1.126     brouard  11206:       fputs(line,ficparo);
                   11207:       fputs(line,ficlog);
                   11208:     }
                   11209:     ungetc(c,ficpar);
                   11210:     
                   11211:     param= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
1.251     brouard  11212:     paramstart= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
1.126     brouard  11213:     for(i=1; i <=nlstate; i++){
1.234     brouard  11214:       j=0;
1.126     brouard  11215:       for(jj=1; jj <=nlstate+ndeath; jj++){
1.234     brouard  11216:        if(jj==i) continue;
                   11217:        j++;
1.292     brouard  11218:        while((c=getc(ficpar))=='#' && c!= EOF){
                   11219:          ungetc(c,ficpar);
                   11220:          fgets(line, MAXLINE, ficpar);
                   11221:          numlinepar++;
                   11222:          fputs(line,stdout);
                   11223:          fputs(line,ficparo);
                   11224:          fputs(line,ficlog);
                   11225:        }
                   11226:        ungetc(c,ficpar);
1.234     brouard  11227:        fscanf(ficpar,"%1d%1d",&i1,&j1);
                   11228:        if ((i1 != i) || (j1 != jj)){
                   11229:          printf("Error in line parameters number %d, %1d%1d instead of %1d%1d \n \
1.126     brouard  11230: It might be a problem of design; if ncovcol and the model are correct\n \
                   11231: run imach with mle=-1 to get a correct template of the parameter file.\n",numlinepar, i,j, i1, j1);
1.234     brouard  11232:          exit(1);
                   11233:        }
                   11234:        fprintf(ficparo,"%1d%1d",i1,j1);
                   11235:        if(mle==1)
                   11236:          printf("%1d%1d",i,jj);
                   11237:        fprintf(ficlog,"%1d%1d",i,jj);
                   11238:        for(k=1; k<=ncovmodel;k++){
                   11239:          fscanf(ficpar," %lf",&param[i][j][k]);
                   11240:          if(mle==1){
                   11241:            printf(" %lf",param[i][j][k]);
                   11242:            fprintf(ficlog," %lf",param[i][j][k]);
                   11243:          }
                   11244:          else
                   11245:            fprintf(ficlog," %lf",param[i][j][k]);
                   11246:          fprintf(ficparo," %lf",param[i][j][k]);
                   11247:        }
                   11248:        fscanf(ficpar,"\n");
                   11249:        numlinepar++;
                   11250:        if(mle==1)
                   11251:          printf("\n");
                   11252:        fprintf(ficlog,"\n");
                   11253:        fprintf(ficparo,"\n");
1.126     brouard  11254:       }
                   11255:     }  
                   11256:     fflush(ficlog);
1.234     brouard  11257:     
1.251     brouard  11258:     /* Reads parameters values */
1.126     brouard  11259:     p=param[1][1];
1.251     brouard  11260:     pstart=paramstart[1][1];
1.126     brouard  11261:     
                   11262:     /* Reads comments: lines beginning with '#' */
                   11263:     while((c=getc(ficpar))=='#' && c!= EOF){
                   11264:       ungetc(c,ficpar);
                   11265:       fgets(line, MAXLINE, ficpar);
                   11266:       numlinepar++;
1.141     brouard  11267:       fputs(line,stdout);
1.126     brouard  11268:       fputs(line,ficparo);
                   11269:       fputs(line,ficlog);
                   11270:     }
                   11271:     ungetc(c,ficpar);
                   11272: 
                   11273:     for(i=1; i <=nlstate; i++){
                   11274:       for(j=1; j <=nlstate+ndeath-1; j++){
1.234     brouard  11275:        fscanf(ficpar,"%1d%1d",&i1,&j1);
                   11276:        if ( (i1-i) * (j1-j) != 0){
                   11277:          printf("Error in line parameters number %d, %1d%1d instead of %1d%1d \n",numlinepar, i,j, i1, j1);
                   11278:          exit(1);
                   11279:        }
                   11280:        printf("%1d%1d",i,j);
                   11281:        fprintf(ficparo,"%1d%1d",i1,j1);
                   11282:        fprintf(ficlog,"%1d%1d",i1,j1);
                   11283:        for(k=1; k<=ncovmodel;k++){
                   11284:          fscanf(ficpar,"%le",&delti3[i][j][k]);
                   11285:          printf(" %le",delti3[i][j][k]);
                   11286:          fprintf(ficparo," %le",delti3[i][j][k]);
                   11287:          fprintf(ficlog," %le",delti3[i][j][k]);
                   11288:        }
                   11289:        fscanf(ficpar,"\n");
                   11290:        numlinepar++;
                   11291:        printf("\n");
                   11292:        fprintf(ficparo,"\n");
                   11293:        fprintf(ficlog,"\n");
1.126     brouard  11294:       }
                   11295:     }
                   11296:     fflush(ficlog);
1.234     brouard  11297:     
1.145     brouard  11298:     /* Reads covariance matrix */
1.126     brouard  11299:     delti=delti3[1][1];
1.220     brouard  11300:                
                   11301:                
1.126     brouard  11302:     /* 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  11303:                
1.126     brouard  11304:     /* Reads comments: lines beginning with '#' */
                   11305:     while((c=getc(ficpar))=='#' && c!= EOF){
                   11306:       ungetc(c,ficpar);
                   11307:       fgets(line, MAXLINE, ficpar);
                   11308:       numlinepar++;
1.141     brouard  11309:       fputs(line,stdout);
1.126     brouard  11310:       fputs(line,ficparo);
                   11311:       fputs(line,ficlog);
                   11312:     }
                   11313:     ungetc(c,ficpar);
1.220     brouard  11314:                
1.126     brouard  11315:     matcov=matrix(1,npar,1,npar);
1.203     brouard  11316:     hess=matrix(1,npar,1,npar);
1.131     brouard  11317:     for(i=1; i <=npar; i++)
                   11318:       for(j=1; j <=npar; j++) matcov[i][j]=0.;
1.220     brouard  11319:                
1.194     brouard  11320:     /* Scans npar lines */
1.126     brouard  11321:     for(i=1; i <=npar; i++){
1.226     brouard  11322:       count=fscanf(ficpar,"%1d%1d%d",&i1,&j1,&jk);
1.194     brouard  11323:       if(count != 3){
1.226     brouard  11324:        printf("Error! Error in parameter file %s at line %d after line starting with %1d%1d%1d\n\
1.194     brouard  11325: This is probably because your covariance matrix doesn't \n  contain exactly %d lines corresponding to your model line '1+age+%s'.\n\
                   11326: Please run with mle=-1 to get a correct covariance matrix.\n",optionfile,numlinepar, i1,j1,jk, npar, model);
1.226     brouard  11327:        fprintf(ficlog,"Error! Error in parameter file %s at line %d after line starting with %1d%1d%1d\n\
1.194     brouard  11328: This is probably because your covariance matrix doesn't \n  contain exactly %d lines corresponding to your model line '1+age+%s'.\n\
                   11329: Please run with mle=-1 to get a correct covariance matrix.\n",optionfile,numlinepar, i1,j1,jk, npar, model);
1.226     brouard  11330:        exit(1);
1.220     brouard  11331:       }else{
1.226     brouard  11332:        if(mle==1)
                   11333:          printf("%1d%1d%d",i1,j1,jk);
                   11334:       }
                   11335:       fprintf(ficlog,"%1d%1d%d",i1,j1,jk);
                   11336:       fprintf(ficparo,"%1d%1d%d",i1,j1,jk);
1.126     brouard  11337:       for(j=1; j <=i; j++){
1.226     brouard  11338:        fscanf(ficpar," %le",&matcov[i][j]);
                   11339:        if(mle==1){
                   11340:          printf(" %.5le",matcov[i][j]);
                   11341:        }
                   11342:        fprintf(ficlog," %.5le",matcov[i][j]);
                   11343:        fprintf(ficparo," %.5le",matcov[i][j]);
1.126     brouard  11344:       }
                   11345:       fscanf(ficpar,"\n");
                   11346:       numlinepar++;
                   11347:       if(mle==1)
1.220     brouard  11348:                                printf("\n");
1.126     brouard  11349:       fprintf(ficlog,"\n");
                   11350:       fprintf(ficparo,"\n");
                   11351:     }
1.194     brouard  11352:     /* End of read covariance matrix npar lines */
1.126     brouard  11353:     for(i=1; i <=npar; i++)
                   11354:       for(j=i+1;j<=npar;j++)
1.226     brouard  11355:        matcov[i][j]=matcov[j][i];
1.126     brouard  11356:     
                   11357:     if(mle==1)
                   11358:       printf("\n");
                   11359:     fprintf(ficlog,"\n");
                   11360:     
                   11361:     fflush(ficlog);
                   11362:     
                   11363:   }    /* End of mle != -3 */
1.218     brouard  11364:   
1.186     brouard  11365:   /*  Main data
                   11366:    */
1.290     brouard  11367:   nobs=lastobs-firstobs+1; /* was = lastobs;*/
                   11368:   /* num=lvector(1,n); */
                   11369:   /* moisnais=vector(1,n); */
                   11370:   /* annais=vector(1,n); */
                   11371:   /* moisdc=vector(1,n); */
                   11372:   /* andc=vector(1,n); */
                   11373:   /* weight=vector(1,n); */
                   11374:   /* agedc=vector(1,n); */
                   11375:   /* cod=ivector(1,n); */
                   11376:   /* for(i=1;i<=n;i++){ */
                   11377:   num=lvector(firstobs,lastobs);
                   11378:   moisnais=vector(firstobs,lastobs);
                   11379:   annais=vector(firstobs,lastobs);
                   11380:   moisdc=vector(firstobs,lastobs);
                   11381:   andc=vector(firstobs,lastobs);
                   11382:   weight=vector(firstobs,lastobs);
                   11383:   agedc=vector(firstobs,lastobs);
                   11384:   cod=ivector(firstobs,lastobs);
                   11385:   for(i=firstobs;i<=lastobs;i++){
1.234     brouard  11386:     num[i]=0;
                   11387:     moisnais[i]=0;
                   11388:     annais[i]=0;
                   11389:     moisdc[i]=0;
                   11390:     andc[i]=0;
                   11391:     agedc[i]=0;
                   11392:     cod[i]=0;
                   11393:     weight[i]=1.0; /* Equal weights, 1 by default */
                   11394:   }
1.290     brouard  11395:   mint=matrix(1,maxwav,firstobs,lastobs);
                   11396:   anint=matrix(1,maxwav,firstobs,lastobs);
                   11397:   s=imatrix(1,maxwav+1,firstobs,lastobs); /* s[i][j] health state for wave i and individual j */ 
1.126     brouard  11398:   tab=ivector(1,NCOVMAX);
1.144     brouard  11399:   ncodemax=ivector(1,NCOVMAX); /* Number of code per covariate; if O and 1 only, 2**ncov; V1+V2+V3+V4=>16 */
1.192     brouard  11400:   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  11401: 
1.136     brouard  11402:   /* Reads data from file datafile */
                   11403:   if (readdata(datafile, firstobs, lastobs, &imx)==1)
                   11404:     goto end;
                   11405: 
                   11406:   /* Calculation of the number of parameters from char model */
1.234     brouard  11407:   /*    modelsav=V2+V1+V4+age*V3 strb=age*V3 stra=V2+V1+V4 
1.137     brouard  11408:        k=4 (age*V3) Tvar[k=4]= 3 (from V3) Tag[cptcovage=1]=4
                   11409:        k=3 V4 Tvar[k=3]= 4 (from V4)
                   11410:        k=2 V1 Tvar[k=2]= 1 (from V1)
                   11411:        k=1 Tvar[1]=2 (from V2)
1.234     brouard  11412:   */
                   11413:   
                   11414:   Tvar=ivector(1,NCOVMAX); /* Was 15 changed to NCOVMAX. */
                   11415:   TvarsDind=ivector(1,NCOVMAX); /*  */
                   11416:   TvarsD=ivector(1,NCOVMAX); /*  */
                   11417:   TvarsQind=ivector(1,NCOVMAX); /*  */
                   11418:   TvarsQ=ivector(1,NCOVMAX); /*  */
1.232     brouard  11419:   TvarF=ivector(1,NCOVMAX); /*  */
                   11420:   TvarFind=ivector(1,NCOVMAX); /*  */
                   11421:   TvarV=ivector(1,NCOVMAX); /*  */
                   11422:   TvarVind=ivector(1,NCOVMAX); /*  */
                   11423:   TvarA=ivector(1,NCOVMAX); /*  */
                   11424:   TvarAind=ivector(1,NCOVMAX); /*  */
1.231     brouard  11425:   TvarFD=ivector(1,NCOVMAX); /*  */
                   11426:   TvarFDind=ivector(1,NCOVMAX); /*  */
                   11427:   TvarFQ=ivector(1,NCOVMAX); /*  */
                   11428:   TvarFQind=ivector(1,NCOVMAX); /*  */
                   11429:   TvarVD=ivector(1,NCOVMAX); /*  */
                   11430:   TvarVDind=ivector(1,NCOVMAX); /*  */
                   11431:   TvarVQ=ivector(1,NCOVMAX); /*  */
                   11432:   TvarVQind=ivector(1,NCOVMAX); /*  */
                   11433: 
1.230     brouard  11434:   Tvalsel=vector(1,NCOVMAX); /*  */
1.233     brouard  11435:   Tvarsel=ivector(1,NCOVMAX); /*  */
1.226     brouard  11436:   Typevar=ivector(-1,NCOVMAX); /* -1 to 2 */
                   11437:   Fixed=ivector(-1,NCOVMAX); /* -1 to 3 */
                   11438:   Dummy=ivector(-1,NCOVMAX); /* -1 to 3 */
1.137     brouard  11439:   /*  V2+V1+V4+age*V3 is a model with 4 covariates (3 plus signs). 
                   11440:       For each model-covariate stores the data-covariate id. Tvar[1]=2, Tvar[2]=1, Tvar[3]=4, 
                   11441:       Tvar[4=age*V3] is 3 and 'age' is recorded in Tage.
                   11442:   */
                   11443:   /* For model-covariate k tells which data-covariate to use but
                   11444:     because this model-covariate is a construction we invent a new column
                   11445:     ncovcol + k1
                   11446:     If already ncovcol=4 and model=V2+V1+V1*V4+age*V3
                   11447:     Tvar[3=V1*V4]=4+1 etc */
1.227     brouard  11448:   Tprod=ivector(1,NCOVMAX); /* Gives the k position of the k1 product */
                   11449:   Tposprod=ivector(1,NCOVMAX); /* Gives the k1 product from the k position */
1.137     brouard  11450:   /* Tprod[k1=1]=3(=V1*V4) for V2+V1+V1*V4+age*V3
                   11451:      if  V2+V1+V1*V4+age*V3+V3*V2   TProd[k1=2]=5 (V3*V2)
1.227     brouard  11452:      Tposprod[k]=k1 , Tposprod[3]=1, Tposprod[5]=2 
1.137     brouard  11453:   */
1.145     brouard  11454:   Tvaraff=ivector(1,NCOVMAX); /* Unclear */
                   11455:   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  11456:                            * For V3*V2 (in V2+V1+V1*V4+age*V3+V3*V2), V3*V2 position is 2nd. 
                   11457:                            * Tvard[k1=2][1]=3 (V3) Tvard[k1=2][2]=2(V2) */
1.145     brouard  11458:   Tage=ivector(1,NCOVMAX); /* Gives the covariate id of covariates associated with age: V2 + V1 + age*V4 + V3*age
1.137     brouard  11459:                         4 covariates (3 plus signs)
                   11460:                         Tage[1=V3*age]= 4; Tage[2=age*V4] = 3
                   11461:                      */  
1.230     brouard  11462:   Tmodelind=ivector(1,NCOVMAX);/** gives the k model position of an
1.227     brouard  11463:                                * individual dummy, fixed or varying:
                   11464:                                * Tmodelind[Tvaraff[3]]=9,Tvaraff[1]@9={4,
                   11465:                                * 3, 1, 0, 0, 0, 0, 0, 0},
1.230     brouard  11466:                                * model=V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 , 
                   11467:                                * V1 df, V2 qf, V3 & V4 dv, V5 qv
                   11468:                                * Tmodelind[1]@9={9,0,3,2,}*/
                   11469:   TmodelInvind=ivector(1,NCOVMAX); /* TmodelInvind=Tvar[k]- ncovcol-nqv={5-2-1=2,*/
                   11470:   TmodelInvQind=ivector(1,NCOVMAX);/** gives the k model position of an
1.228     brouard  11471:                                * individual quantitative, fixed or varying:
                   11472:                                * Tmodelqind[1]=1,Tvaraff[1]@9={4,
                   11473:                                * 3, 1, 0, 0, 0, 0, 0, 0},
                   11474:                                * model=V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1*/
1.186     brouard  11475: /* Main decodemodel */
                   11476: 
1.187     brouard  11477: 
1.223     brouard  11478:   if(decodemodel(model, lastobs) == 1) /* In order to get Tvar[k] V4+V3+V5 p Tvar[1]@3  = {4, 3, 5}*/
1.136     brouard  11479:     goto end;
                   11480: 
1.137     brouard  11481:   if((double)(lastobs-imx)/(double)imx > 1.10){
                   11482:     nbwarn++;
                   11483:     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); 
                   11484:     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); 
                   11485:   }
1.136     brouard  11486:     /*  if(mle==1){*/
1.137     brouard  11487:   if (weightopt != 1) { /* Maximisation without weights. We can have weights different from 1 but want no weight*/
                   11488:     for(i=1;i<=imx;i++) weight[i]=1.0; /* changed to imx */
1.136     brouard  11489:   }
                   11490: 
                   11491:     /*-calculation of age at interview from date of interview and age at death -*/
                   11492:   agev=matrix(1,maxwav,1,imx);
                   11493: 
                   11494:   if(calandcheckages(imx, maxwav, &agemin, &agemax, &nberr, &nbwarn) == 1)
                   11495:     goto end;
                   11496: 
1.126     brouard  11497: 
1.136     brouard  11498:   agegomp=(int)agemin;
1.290     brouard  11499:   free_vector(moisnais,firstobs,lastobs);
                   11500:   free_vector(annais,firstobs,lastobs);
1.126     brouard  11501:   /* free_matrix(mint,1,maxwav,1,n);
                   11502:      free_matrix(anint,1,maxwav,1,n);*/
1.215     brouard  11503:   /* free_vector(moisdc,1,n); */
                   11504:   /* free_vector(andc,1,n); */
1.145     brouard  11505:   /* */
                   11506:   
1.126     brouard  11507:   wav=ivector(1,imx);
1.214     brouard  11508:   /* dh=imatrix(1,lastpass-firstpass+1,1,imx); */
                   11509:   /* bh=imatrix(1,lastpass-firstpass+1,1,imx); */
                   11510:   /* mw=imatrix(1,lastpass-firstpass+1,1,imx); */
                   11511:   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.*/
                   11512:   bh=imatrix(1,lastpass-firstpass+2,1,imx);
                   11513:   mw=imatrix(1,lastpass-firstpass+2,1,imx);
1.126     brouard  11514:    
                   11515:   /* Concatenates waves */
1.214     brouard  11516:   /* Concatenates waves: wav[i] is the number of effective (useful waves) of individual i.
                   11517:      Death is a valid wave (if date is known).
                   11518:      mw[mi][i] is the number of (mi=1 to wav[i]) effective wave out of mi of individual i
                   11519:      dh[m][i] or dh[mw[mi][i]][i] is the delay between two effective waves m=mw[mi][i]
                   11520:      and mw[mi+1][i]. dh depends on stepm.
                   11521:   */
                   11522: 
1.126     brouard  11523:   concatwav(wav, dh, bh, mw, s, agedc, agev,  firstpass, lastpass, imx, nlstate, stepm);
1.248     brouard  11524:   /* Concatenates waves */
1.145     brouard  11525:  
1.290     brouard  11526:   free_vector(moisdc,firstobs,lastobs);
                   11527:   free_vector(andc,firstobs,lastobs);
1.215     brouard  11528: 
1.126     brouard  11529:   /* Routine tricode is to calculate cptcoveff (real number of unique covariates) and to associate covariable number and modality */
                   11530:   nbcode=imatrix(0,NCOVMAX,0,NCOVMAX); 
                   11531:   ncodemax[1]=1;
1.145     brouard  11532:   Ndum =ivector(-1,NCOVMAX);  
1.225     brouard  11533:   cptcoveff=0;
1.220     brouard  11534:   if (ncovmodel-nagesqr > 2 ){ /* That is if covariate other than cst, age and age*age */
                   11535:     tricode(&cptcoveff,Tvar,nbcode,imx, Ndum); /**< Fills nbcode[Tvar[j]][l]; */
1.227     brouard  11536:   }
                   11537:   
                   11538:   ncovcombmax=pow(2,cptcoveff);
                   11539:   invalidvarcomb=ivector(1, ncovcombmax); 
                   11540:   for(i=1;i<ncovcombmax;i++)
                   11541:     invalidvarcomb[i]=0;
                   11542:   
1.211     brouard  11543:   /* Nbcode gives the value of the lth modality (currently 1 to 2) of jth covariate, in
1.186     brouard  11544:      V2+V1*age, there are 3 covariates Tvar[2]=1 (V1).*/
1.211     brouard  11545:   /* 1 to ncodemax[j] which is the maximum value of this jth covariate */
1.227     brouard  11546:   
1.200     brouard  11547:   /*  codtab=imatrix(1,100,1,10);*/ /* codtab[h,k]=( (h-1) - mod(k-1,2**(k-1) )/2**(k-1) */
1.198     brouard  11548:   /*printf(" codtab[1,1],codtab[100,10]=%d,%d\n", codtab[1][1],codtabm(100,10));*/
1.186     brouard  11549:   /* codtab gives the value 1 or 2 of the hth combination of k covariates (1 or 2).*/
1.211     brouard  11550:   /* nbcode[Tvaraff[j]][codtabm(h,j)]) : if there are only 2 modalities for a covariate j, 
                   11551:    * codtabm(h,j) gives its value classified at position h and nbcode gives how it is coded 
                   11552:    * (currently 0 or 1) in the data.
                   11553:    * In a loop on h=1 to 2**k, and a loop on j (=1 to k), we get the value of 
                   11554:    * corresponding modality (h,j).
                   11555:    */
                   11556: 
1.145     brouard  11557:   h=0;
                   11558:   /*if (cptcovn > 0) */
1.126     brouard  11559:   m=pow(2,cptcoveff);
                   11560:  
1.144     brouard  11561:          /**< codtab(h,k)  k   = codtab[h,k]=( (h-1) - mod(k-1,2**(k-1) )/2**(k-1) + 1
1.211     brouard  11562:           * For k=4 covariates, h goes from 1 to m=2**k
                   11563:           * codtabm(h,k)=  (1 & (h-1) >> (k-1)) + 1;
                   11564:            * #define codtabm(h,k)  (1 & (h-1) >> (k-1))+1
1.186     brouard  11565:           *     h\k   1     2     3     4
1.143     brouard  11566:           *______________________________  
                   11567:           *     1 i=1 1 i=1 1 i=1 1 i=1 1
                   11568:           *     2     2     1     1     1
                   11569:           *     3 i=2 1     2     1     1
                   11570:           *     4     2     2     1     1
                   11571:           *     5 i=3 1 i=2 1     2     1
                   11572:           *     6     2     1     2     1
                   11573:           *     7 i=4 1     2     2     1
                   11574:           *     8     2     2     2     1
1.197     brouard  11575:           *     9 i=5 1 i=3 1 i=2 1     2
                   11576:           *    10     2     1     1     2
                   11577:           *    11 i=6 1     2     1     2
                   11578:           *    12     2     2     1     2
                   11579:           *    13 i=7 1 i=4 1     2     2    
                   11580:           *    14     2     1     2     2
                   11581:           *    15 i=8 1     2     2     2
                   11582:           *    16     2     2     2     2
1.143     brouard  11583:           */
1.212     brouard  11584:   /* How to do the opposite? From combination h (=1 to 2**k) how to get the value on the covariates? */
1.211     brouard  11585:      /* from h=5 and m, we get then number of covariates k=log(m)/log(2)=4
                   11586:      * and the value of each covariate?
                   11587:      * V1=1, V2=1, V3=2, V4=1 ?
                   11588:      * h-1=4 and 4 is 0100 or reverse 0010, and +1 is 1121 ok.
                   11589:      * h=6, 6-1=5, 5 is 0101, 1010, 2121, V1=2nd, V2=1st, V3=2nd, V4=1st.
                   11590:      * In order to get the real value in the data, we use nbcode
                   11591:      * nbcode[Tvar[3][2nd]]=1 and nbcode[Tvar[4][1]]=0
                   11592:      * We are keeping this crazy system in order to be able (in the future?) 
                   11593:      * to have more than 2 values (0 or 1) for a covariate.
                   11594:      * #define codtabm(h,k)  (1 & (h-1) >> (k-1))+1
                   11595:      * h=6, k=2? h-1=5=0101, reverse 1010, +1=2121, k=2nd position: value is 1: codtabm(6,2)=1
                   11596:      *              bbbbbbbb
                   11597:      *              76543210     
                   11598:      *   h-1        00000101 (6-1=5)
1.219     brouard  11599:      *(h-1)>>(k-1)= 00000010 >> (2-1) = 1 right shift
1.211     brouard  11600:      *           &
                   11601:      *     1        00000001 (1)
1.219     brouard  11602:      *              00000000        = 1 & ((h-1) >> (k-1))
                   11603:      *          +1= 00000001 =1 
1.211     brouard  11604:      *
                   11605:      * h=14, k=3 => h'=h-1=13, k'=k-1=2
                   11606:      *          h'      1101 =2^3+2^2+0x2^1+2^0
                   11607:      *    >>k'            11
                   11608:      *          &   00000001
                   11609:      *            = 00000001
                   11610:      *      +1    = 00000010=2    =  codtabm(14,3)   
                   11611:      * Reverse h=6 and m=16?
                   11612:      * cptcoveff=log(16)/log(2)=4 covariate: 6-1=5=0101 reversed=1010 +1=2121 =>V1=2, V2=1, V3=2, V4=1.
                   11613:      * for (j=1 to cptcoveff) Vj=decodtabm(j,h,cptcoveff)
                   11614:      * decodtabm(h,j,cptcoveff)= (((h-1) >> (j-1)) & 1) +1 
                   11615:      * decodtabm(h,j,cptcoveff)= (h <= (1<<cptcoveff)?(((h-1) >> (j-1)) & 1) +1 : -1)
                   11616:      * V3=decodtabm(14,3,2**4)=2
                   11617:      *          h'=13   1101 =2^3+2^2+0x2^1+2^0
                   11618:      *(h-1) >> (j-1)    0011 =13 >> 2
                   11619:      *          &1 000000001
                   11620:      *           = 000000001
                   11621:      *         +1= 000000010 =2
                   11622:      *                  2211
                   11623:      *                  V1=1+1, V2=0+1, V3=1+1, V4=1+1
                   11624:      *                  V3=2
1.220     brouard  11625:                 * codtabm and decodtabm are identical
1.211     brouard  11626:      */
                   11627: 
1.145     brouard  11628: 
                   11629:  free_ivector(Ndum,-1,NCOVMAX);
                   11630: 
                   11631: 
1.126     brouard  11632:     
1.186     brouard  11633:   /* Initialisation of ----------- gnuplot -------------*/
1.126     brouard  11634:   strcpy(optionfilegnuplot,optionfilefiname);
                   11635:   if(mle==-3)
1.201     brouard  11636:     strcat(optionfilegnuplot,"-MORT_");
1.126     brouard  11637:   strcat(optionfilegnuplot,".gp");
                   11638: 
                   11639:   if((ficgp=fopen(optionfilegnuplot,"w"))==NULL) {
                   11640:     printf("Problem with file %s",optionfilegnuplot);
                   11641:   }
                   11642:   else{
1.204     brouard  11643:     fprintf(ficgp,"\n# IMaCh-%s\n", version); 
1.126     brouard  11644:     fprintf(ficgp,"# %s\n", optionfilegnuplot); 
1.141     brouard  11645:     //fprintf(ficgp,"set missing 'NaNq'\n");
                   11646:     fprintf(ficgp,"set datafile missing 'NaNq'\n");
1.126     brouard  11647:   }
                   11648:   /*  fclose(ficgp);*/
1.186     brouard  11649: 
                   11650: 
                   11651:   /* Initialisation of --------- index.htm --------*/
1.126     brouard  11652: 
                   11653:   strcpy(optionfilehtm,optionfilefiname); /* Main html file */
                   11654:   if(mle==-3)
1.201     brouard  11655:     strcat(optionfilehtm,"-MORT_");
1.126     brouard  11656:   strcat(optionfilehtm,".htm");
                   11657:   if((fichtm=fopen(optionfilehtm,"w"))==NULL)    {
1.131     brouard  11658:     printf("Problem with %s \n",optionfilehtm);
                   11659:     exit(0);
1.126     brouard  11660:   }
                   11661: 
                   11662:   strcpy(optionfilehtmcov,optionfilefiname); /* Only for matrix of covariance */
                   11663:   strcat(optionfilehtmcov,"-cov.htm");
                   11664:   if((fichtmcov=fopen(optionfilehtmcov,"w"))==NULL)    {
                   11665:     printf("Problem with %s \n",optionfilehtmcov), exit(0);
                   11666:   }
                   11667:   else{
                   11668:   fprintf(fichtmcov,"<html><head>\n<title>IMaCh Cov %s</title></head>\n <body><font size=\"2\">%s <br> %s</font> \
                   11669: <hr size=\"2\" color=\"#EC5E5E\"> \n\
1.204     brouard  11670: Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=1+age+%s<br>\n",\
1.126     brouard  11671:          optionfilehtmcov,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model);
                   11672:   }
                   11673: 
1.213     brouard  11674:   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  11675: <hr size=\"2\" color=\"#EC5E5E\"> \n\
                   11676: <font size=\"2\">IMaCh-%s <br> %s</font> \
1.126     brouard  11677: <hr size=\"2\" color=\"#EC5E5E\"> \n\
1.204     brouard  11678: Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=1+age+%s<br>\n\
1.126     brouard  11679: \n\
                   11680: <hr  size=\"2\" color=\"#EC5E5E\">\
                   11681:  <ul><li><h4>Parameter files</h4>\n\
                   11682:  - Parameter file: <a href=\"%s.%s\">%s.%s</a><br>\n\
                   11683:  - Copy of the parameter file: <a href=\"o%s\">o%s</a><br>\n\
                   11684:  - Log file of the run: <a href=\"%s\">%s</a><br>\n\
                   11685:  - Gnuplot file name: <a href=\"%s\">%s</a><br>\n\
                   11686:  - Date and time at start: %s</ul>\n",\
                   11687:          optionfilehtm,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model,\
                   11688:          optionfilefiname,optionfilext,optionfilefiname,optionfilext,\
                   11689:          fileres,fileres,\
                   11690:          filelog,filelog,optionfilegnuplot,optionfilegnuplot,strstart);
                   11691:   fflush(fichtm);
                   11692: 
                   11693:   strcpy(pathr,path);
                   11694:   strcat(pathr,optionfilefiname);
1.184     brouard  11695: #ifdef WIN32
                   11696:   _chdir(optionfilefiname); /* Move to directory named optionfile */
                   11697: #else
1.126     brouard  11698:   chdir(optionfilefiname); /* Move to directory named optionfile */
1.184     brouard  11699: #endif
                   11700:          
1.126     brouard  11701:   
1.220     brouard  11702:   /* Calculates basic frequencies. Computes observed prevalence at single age 
                   11703:                 and for any valid combination of covariates
1.126     brouard  11704:      and prints on file fileres'p'. */
1.251     brouard  11705:   freqsummary(fileres, p, pstart, agemin, agemax, s, agev, nlstate, imx, Tvaraff, invalidvarcomb, nbcode, ncodemax,mint,anint,strstart, \
1.227     brouard  11706:              firstpass, lastpass,  stepm,  weightopt, model);
1.126     brouard  11707: 
                   11708:   fprintf(fichtm,"\n");
1.286     brouard  11709:   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  11710:          ftol, stepm);
                   11711:   fprintf(fichtm,"\n<li>Number of fixed dummy covariates: ncovcol=%d ", ncovcol);
                   11712:   ncurrv=1;
                   11713:   for(i=ncurrv; i <=ncovcol; i++) fprintf(fichtm,"V%d ", i);
                   11714:   fprintf(fichtm,"\n<li> Number of fixed quantitative variables: nqv=%d ", nqv); 
                   11715:   ncurrv=i;
                   11716:   for(i=ncurrv; i <=ncurrv-1+nqv; i++) fprintf(fichtm,"V%d ", i);
1.290     brouard  11717:   fprintf(fichtm,"\n<li> Number of time varying (wave varying) dummy covariates: ntv=%d ", ntv);
1.274     brouard  11718:   ncurrv=i;
                   11719:   for(i=ncurrv; i <=ncurrv-1+ntv; i++) fprintf(fichtm,"V%d ", i);
1.290     brouard  11720:   fprintf(fichtm,"\n<li>Number of time varying  quantitative covariates: nqtv=%d ", nqtv);
1.274     brouard  11721:   ncurrv=i;
                   11722:   for(i=ncurrv; i <=ncurrv-1+nqtv; i++) fprintf(fichtm,"V%d ", i);
                   11723:   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", \
                   11724:           nlstate, ndeath, maxwav, mle, weightopt);
                   11725: 
                   11726:   fprintf(fichtm,"<h4> Diagram of states <a href=\"%s_.svg\">%s_.svg</a></h4> \n\
                   11727: <img src=\"%s_.svg\">", subdirf2(optionfilefiname,"D_"),subdirf2(optionfilefiname,"D_"),subdirf2(optionfilefiname,"D_"));
                   11728: 
                   11729:   
                   11730:   fprintf(fichtm,"\n<h4>Some descriptive statistics </h4>\n<br>Total number of observations=%d <br>\n\
1.126     brouard  11731: Youngest age at first (selected) pass %.2f, oldest age %.2f<br>\n\
                   11732: Interval (in months) between two waves: Min=%d Max=%d Mean=%.2lf<br>\n",\
1.274     brouard  11733:   imx,agemin,agemax,jmin,jmax,jmean);
1.126     brouard  11734:   pmmij= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
1.268     brouard  11735:   oldms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
                   11736:   newms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
                   11737:   savms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
                   11738:   oldm=oldms; newm=newms; savm=savms; /* Keeps fixed addresses to free */
1.218     brouard  11739: 
1.126     brouard  11740:   /* For Powell, parameters are in a vector p[] starting at p[1]
                   11741:      so we point p on param[1][1] so that p[1] maps on param[1][1][1] */
                   11742:   p=param[1][1]; /* *(*(*(param +1)+1)+0) */
                   11743: 
                   11744:   globpr=0; /* To get the number ipmx of contributions and the sum of weights*/
1.186     brouard  11745:   /* For mortality only */
1.126     brouard  11746:   if (mle==-3){
1.136     brouard  11747:     ximort=matrix(1,NDIM,1,NDIM); 
1.248     brouard  11748:     for(i=1;i<=NDIM;i++)
                   11749:       for(j=1;j<=NDIM;j++)
                   11750:        ximort[i][j]=0.;
1.186     brouard  11751:     /*     ximort=gsl_matrix_alloc(1,NDIM,1,NDIM); */
1.290     brouard  11752:     cens=ivector(firstobs,lastobs);
                   11753:     ageexmed=vector(firstobs,lastobs);
                   11754:     agecens=vector(firstobs,lastobs);
                   11755:     dcwave=ivector(firstobs,lastobs);
1.223     brouard  11756:                
1.126     brouard  11757:     for (i=1; i<=imx; i++){
                   11758:       dcwave[i]=-1;
                   11759:       for (m=firstpass; m<=lastpass; m++)
1.226     brouard  11760:        if (s[m][i]>nlstate) {
                   11761:          dcwave[i]=m;
                   11762:          /*    printf("i=%d j=%d s=%d dcwave=%d\n",i,j, s[j][i],dcwave[i]);*/
                   11763:          break;
                   11764:        }
1.126     brouard  11765:     }
1.226     brouard  11766:     
1.126     brouard  11767:     for (i=1; i<=imx; i++) {
                   11768:       if (wav[i]>0){
1.226     brouard  11769:        ageexmed[i]=agev[mw[1][i]][i];
                   11770:        j=wav[i];
                   11771:        agecens[i]=1.; 
                   11772:        
                   11773:        if (ageexmed[i]> 1 && wav[i] > 0){
                   11774:          agecens[i]=agev[mw[j][i]][i];
                   11775:          cens[i]= 1;
                   11776:        }else if (ageexmed[i]< 1) 
                   11777:          cens[i]= -1;
                   11778:        if (agedc[i]< AGESUP && agedc[i]>1 && dcwave[i]>firstpass && dcwave[i]<=lastpass)
                   11779:          cens[i]=0 ;
1.126     brouard  11780:       }
                   11781:       else cens[i]=-1;
                   11782:     }
                   11783:     
                   11784:     for (i=1;i<=NDIM;i++) {
                   11785:       for (j=1;j<=NDIM;j++)
1.226     brouard  11786:        ximort[i][j]=(i == j ? 1.0 : 0.0);
1.126     brouard  11787:     }
                   11788:     
1.145     brouard  11789:     /*p[1]=0.0268; p[NDIM]=0.083;*/
1.126     brouard  11790:     /*printf("%lf %lf", p[1], p[2]);*/
                   11791:     
                   11792:     
1.136     brouard  11793: #ifdef GSL
                   11794:     printf("GSL optimization\n");  fprintf(ficlog,"Powell\n");
1.162     brouard  11795: #else
1.126     brouard  11796:     printf("Powell\n");  fprintf(ficlog,"Powell\n");
1.136     brouard  11797: #endif
1.201     brouard  11798:     strcpy(filerespow,"POW-MORT_"); 
                   11799:     strcat(filerespow,fileresu);
1.126     brouard  11800:     if((ficrespow=fopen(filerespow,"w"))==NULL) {
                   11801:       printf("Problem with resultfile: %s\n", filerespow);
                   11802:       fprintf(ficlog,"Problem with resultfile: %s\n", filerespow);
                   11803:     }
1.136     brouard  11804: #ifdef GSL
                   11805:     fprintf(ficrespow,"# GSL optimization\n# iter -2*LL");
1.162     brouard  11806: #else
1.126     brouard  11807:     fprintf(ficrespow,"# Powell\n# iter -2*LL");
1.136     brouard  11808: #endif
1.126     brouard  11809:     /*  for (i=1;i<=nlstate;i++)
                   11810:        for(j=1;j<=nlstate+ndeath;j++)
                   11811:        if(j!=i)fprintf(ficrespow," p%1d%1d",i,j);
                   11812:     */
                   11813:     fprintf(ficrespow,"\n");
1.136     brouard  11814: #ifdef GSL
                   11815:     /* gsl starts here */ 
                   11816:     T = gsl_multimin_fminimizer_nmsimplex;
                   11817:     gsl_multimin_fminimizer *sfm = NULL;
                   11818:     gsl_vector *ss, *x;
                   11819:     gsl_multimin_function minex_func;
                   11820: 
                   11821:     /* Initial vertex size vector */
                   11822:     ss = gsl_vector_alloc (NDIM);
                   11823:     
                   11824:     if (ss == NULL){
                   11825:       GSL_ERROR_VAL ("failed to allocate space for ss", GSL_ENOMEM, 0);
                   11826:     }
                   11827:     /* Set all step sizes to 1 */
                   11828:     gsl_vector_set_all (ss, 0.001);
                   11829: 
                   11830:     /* Starting point */
1.126     brouard  11831:     
1.136     brouard  11832:     x = gsl_vector_alloc (NDIM);
                   11833:     
                   11834:     if (x == NULL){
                   11835:       gsl_vector_free(ss);
                   11836:       GSL_ERROR_VAL ("failed to allocate space for x", GSL_ENOMEM, 0);
                   11837:     }
                   11838:   
                   11839:     /* Initialize method and iterate */
                   11840:     /*     p[1]=0.0268; p[NDIM]=0.083; */
1.186     brouard  11841:     /*     gsl_vector_set(x, 0, 0.0268); */
                   11842:     /*     gsl_vector_set(x, 1, 0.083); */
1.136     brouard  11843:     gsl_vector_set(x, 0, p[1]);
                   11844:     gsl_vector_set(x, 1, p[2]);
                   11845: 
                   11846:     minex_func.f = &gompertz_f;
                   11847:     minex_func.n = NDIM;
                   11848:     minex_func.params = (void *)&p; /* ??? */
                   11849:     
                   11850:     sfm = gsl_multimin_fminimizer_alloc (T, NDIM);
                   11851:     gsl_multimin_fminimizer_set (sfm, &minex_func, x, ss);
                   11852:     
                   11853:     printf("Iterations beginning .....\n\n");
                   11854:     printf("Iter. #    Intercept       Slope     -Log Likelihood     Simplex size\n");
                   11855: 
                   11856:     iteri=0;
                   11857:     while (rval == GSL_CONTINUE){
                   11858:       iteri++;
                   11859:       status = gsl_multimin_fminimizer_iterate(sfm);
                   11860:       
                   11861:       if (status) printf("error: %s\n", gsl_strerror (status));
                   11862:       fflush(0);
                   11863:       
                   11864:       if (status) 
                   11865:         break;
                   11866:       
                   11867:       rval = gsl_multimin_test_size (gsl_multimin_fminimizer_size (sfm), 1e-6);
                   11868:       ssval = gsl_multimin_fminimizer_size (sfm);
                   11869:       
                   11870:       if (rval == GSL_SUCCESS)
                   11871:         printf ("converged to a local maximum at\n");
                   11872:       
                   11873:       printf("%5d ", iteri);
                   11874:       for (it = 0; it < NDIM; it++){
                   11875:        printf ("%10.5f ", gsl_vector_get (sfm->x, it));
                   11876:       }
                   11877:       printf("f() = %-10.5f ssize = %.7f\n", sfm->fval, ssval);
                   11878:     }
                   11879:     
                   11880:     printf("\n\n Please note: Program should be run many times with varying starting points to detemine global maximum\n\n");
                   11881:     
                   11882:     gsl_vector_free(x); /* initial values */
                   11883:     gsl_vector_free(ss); /* inital step size */
                   11884:     for (it=0; it<NDIM; it++){
                   11885:       p[it+1]=gsl_vector_get(sfm->x,it);
                   11886:       fprintf(ficrespow," %.12lf", p[it]);
                   11887:     }
                   11888:     gsl_multimin_fminimizer_free (sfm); /* p *(sfm.x.data) et p *(sfm.x.data+1)  */
                   11889: #endif
                   11890: #ifdef POWELL
                   11891:      powell(p,ximort,NDIM,ftol,&iter,&fret,gompertz);
                   11892: #endif  
1.126     brouard  11893:     fclose(ficrespow);
                   11894:     
1.203     brouard  11895:     hesscov(matcov, hess, p, NDIM, delti, 1e-4, gompertz); 
1.126     brouard  11896: 
                   11897:     for(i=1; i <=NDIM; i++)
                   11898:       for(j=i+1;j<=NDIM;j++)
1.220     brouard  11899:                                matcov[i][j]=matcov[j][i];
1.126     brouard  11900:     
                   11901:     printf("\nCovariance matrix\n ");
1.203     brouard  11902:     fprintf(ficlog,"\nCovariance matrix\n ");
1.126     brouard  11903:     for(i=1; i <=NDIM; i++) {
                   11904:       for(j=1;j<=NDIM;j++){ 
1.220     brouard  11905:                                printf("%f ",matcov[i][j]);
                   11906:                                fprintf(ficlog,"%f ",matcov[i][j]);
1.126     brouard  11907:       }
1.203     brouard  11908:       printf("\n ");  fprintf(ficlog,"\n ");
1.126     brouard  11909:     }
                   11910:     
                   11911:     printf("iter=%d MLE=%f Eq=%lf*exp(%lf*(age-%d))\n",iter,-gompertz(p),p[1],p[2],agegomp);
1.193     brouard  11912:     for (i=1;i<=NDIM;i++) {
1.126     brouard  11913:       printf("%f [%f ; %f]\n",p[i],p[i]-2*sqrt(matcov[i][i]),p[i]+2*sqrt(matcov[i][i]));
1.193     brouard  11914:       fprintf(ficlog,"%f [%f ; %f]\n",p[i],p[i]-2*sqrt(matcov[i][i]),p[i]+2*sqrt(matcov[i][i]));
                   11915:     }
1.126     brouard  11916:     lsurv=vector(1,AGESUP);
                   11917:     lpop=vector(1,AGESUP);
                   11918:     tpop=vector(1,AGESUP);
                   11919:     lsurv[agegomp]=100000;
                   11920:     
                   11921:     for (k=agegomp;k<=AGESUP;k++) {
                   11922:       agemortsup=k;
                   11923:       if (p[1]*exp(p[2]*(k-agegomp))>1) break;
                   11924:     }
                   11925:     
                   11926:     for (k=agegomp;k<agemortsup;k++)
                   11927:       lsurv[k+1]=lsurv[k]-lsurv[k]*(p[1]*exp(p[2]*(k-agegomp)));
                   11928:     
                   11929:     for (k=agegomp;k<agemortsup;k++){
                   11930:       lpop[k]=(lsurv[k]+lsurv[k+1])/2.;
                   11931:       sumlpop=sumlpop+lpop[k];
                   11932:     }
                   11933:     
                   11934:     tpop[agegomp]=sumlpop;
                   11935:     for (k=agegomp;k<(agemortsup-3);k++){
                   11936:       /*  tpop[k+1]=2;*/
                   11937:       tpop[k+1]=tpop[k]-lpop[k];
                   11938:     }
                   11939:     
                   11940:     
                   11941:     printf("\nAge   lx     qx    dx    Lx     Tx     e(x)\n");
                   11942:     for (k=agegomp;k<(agemortsup-2);k++) 
                   11943:       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]);
                   11944:     
                   11945:     
                   11946:     replace_back_to_slash(pathc,pathcd); /* Even gnuplot wants a / */
1.220     brouard  11947:                ageminpar=50;
                   11948:                agemaxpar=100;
1.194     brouard  11949:     if(ageminpar == AGEOVERFLOW ||agemaxpar == AGEOVERFLOW){
                   11950:        printf("Warning! Error in gnuplot file with ageminpar %f or agemaxpar %f overflow\n\
                   11951: This is probably because your parameter file doesn't \n  contain the exact number of lines (or columns) corresponding to your model line.\n\
                   11952: Please run with mle=-1 to get a correct covariance matrix.\n",ageminpar,agemaxpar);
                   11953:        fprintf(ficlog,"Warning! Error in gnuplot file with ageminpar %f or agemaxpar %f overflow\n\
                   11954: This is probably because your parameter file doesn't \n  contain the exact number of lines (or columns) corresponding to your model line.\n\
                   11955: Please run with mle=-1 to get a correct covariance matrix.\n",ageminpar,agemaxpar);
1.220     brouard  11956:     }else{
                   11957:                        printf("Warning! ageminpar %f and agemaxpar %f have been fixed because for simplification until it is fixed...\n\n",ageminpar,agemaxpar);
                   11958:                        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  11959:       printinggnuplotmort(fileresu, optionfilefiname,ageminpar,agemaxpar,fage, pathc,p);
1.220     brouard  11960:                }
1.201     brouard  11961:     printinghtmlmort(fileresu,title,datafile, firstpass, lastpass, \
1.126     brouard  11962:                     stepm, weightopt,\
                   11963:                     model,imx,p,matcov,agemortsup);
                   11964:     
                   11965:     free_vector(lsurv,1,AGESUP);
                   11966:     free_vector(lpop,1,AGESUP);
                   11967:     free_vector(tpop,1,AGESUP);
1.220     brouard  11968:     free_matrix(ximort,1,NDIM,1,NDIM);
1.290     brouard  11969:     free_ivector(dcwave,firstobs,lastobs);
                   11970:     free_vector(agecens,firstobs,lastobs);
                   11971:     free_vector(ageexmed,firstobs,lastobs);
                   11972:     free_ivector(cens,firstobs,lastobs);
1.220     brouard  11973: #ifdef GSL
1.136     brouard  11974: #endif
1.186     brouard  11975:   } /* Endof if mle==-3 mortality only */
1.205     brouard  11976:   /* Standard  */
                   11977:   else{ /* For mle !=- 3, could be 0 or 1 or 4 etc. */
                   11978:     globpr=0;/* Computes sum of likelihood for globpr=1 and funcone */
                   11979:     /* Computes likelihood for initial parameters, uses funcone to compute gpimx and gsw */
1.132     brouard  11980:     likelione(ficres, p, npar, nlstate, &globpr, &ipmx, &sw, &fretone, funcone); /* Prints the contributions to the likelihood */
1.126     brouard  11981:     printf("First Likeli=%12.6f ipmx=%ld sw=%12.6f",fretone,ipmx,sw);
                   11982:     for (k=1; k<=npar;k++)
                   11983:       printf(" %d %8.5f",k,p[k]);
                   11984:     printf("\n");
1.205     brouard  11985:     if(mle>=1){ /* Could be 1 or 2, Real Maximization */
                   11986:       /* mlikeli uses func not funcone */
1.247     brouard  11987:       /* for(i=1;i<nlstate;i++){ */
                   11988:       /*       /\*reducing xi for 1 to npar to 1 to ncovmodel; *\/ */
                   11989:       /*    mlikeli(ficres,p, ncovmodel, ncovmodel, nlstate, ftol, funcnoprod); */
                   11990:       /* } */
1.205     brouard  11991:       mlikeli(ficres,p, npar, ncovmodel, nlstate, ftol, func);
                   11992:     }
                   11993:     if(mle==0) {/* No optimization, will print the likelihoods for the datafile */
                   11994:       globpr=0;/* Computes sum of likelihood for globpr=1 and funcone */
                   11995:       /* Computes likelihood for initial parameters, uses funcone to compute gpimx and gsw */
                   11996:       likelione(ficres, p, npar, nlstate, &globpr, &ipmx, &sw, &fretone, funcone); /* Prints the contributions to the likelihood */
                   11997:     }
                   11998:     globpr=1; /* again, to print the individual contributions using computed gpimx and gsw */
1.126     brouard  11999:     likelione(ficres, p, npar, nlstate, &globpr, &ipmx, &sw, &fretone, funcone); /* Prints the contributions to the likelihood */
                   12000:     printf("Second Likeli=%12.6f ipmx=%ld sw=%12.6f",fretone,ipmx,sw);
                   12001:     for (k=1; k<=npar;k++)
                   12002:       printf(" %d %8.5f",k,p[k]);
                   12003:     printf("\n");
                   12004:     
                   12005:     /*--------- results files --------------*/
1.283     brouard  12006:     /* 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  12007:     
                   12008:     
                   12009:     fprintf(ficres,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
                   12010:     printf("# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
                   12011:     fprintf(ficlog,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
                   12012:     for(i=1,jk=1; i <=nlstate; i++){
                   12013:       for(k=1; k <=(nlstate+ndeath); k++){
1.225     brouard  12014:        if (k != i) {
                   12015:          printf("%d%d ",i,k);
                   12016:          fprintf(ficlog,"%d%d ",i,k);
                   12017:          fprintf(ficres,"%1d%1d ",i,k);
                   12018:          for(j=1; j <=ncovmodel; j++){
                   12019:            printf("%12.7f ",p[jk]);
                   12020:            fprintf(ficlog,"%12.7f ",p[jk]);
                   12021:            fprintf(ficres,"%12.7f ",p[jk]);
                   12022:            jk++; 
                   12023:          }
                   12024:          printf("\n");
                   12025:          fprintf(ficlog,"\n");
                   12026:          fprintf(ficres,"\n");
                   12027:        }
1.126     brouard  12028:       }
                   12029:     }
1.203     brouard  12030:     if(mle != 0){
                   12031:       /* Computing hessian and covariance matrix only at a peak of the Likelihood, that is after optimization */
1.126     brouard  12032:       ftolhess=ftol; /* Usually correct */
1.203     brouard  12033:       hesscov(matcov, hess, p, npar, delti, ftolhess, func);
                   12034:       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");
                   12035:       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");
                   12036:       for(i=1,jk=1; i <=nlstate; i++){
1.225     brouard  12037:        for(k=1; k <=(nlstate+ndeath); k++){
                   12038:          if (k != i) {
                   12039:            printf("%d%d ",i,k);
                   12040:            fprintf(ficlog,"%d%d ",i,k);
                   12041:            for(j=1; j <=ncovmodel; j++){
                   12042:              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]));
                   12043:              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]));
                   12044:              jk++; 
                   12045:            }
                   12046:            printf("\n");
                   12047:            fprintf(ficlog,"\n");
                   12048:          }
                   12049:        }
1.193     brouard  12050:       }
1.203     brouard  12051:     } /* end of hesscov and Wald tests */
1.225     brouard  12052:     
1.203     brouard  12053:     /*  */
1.126     brouard  12054:     fprintf(ficres,"# Scales (for hessian or gradient estimation)\n");
                   12055:     printf("# Scales (for hessian or gradient estimation)\n");
                   12056:     fprintf(ficlog,"# Scales (for hessian or gradient estimation)\n");
                   12057:     for(i=1,jk=1; i <=nlstate; i++){
                   12058:       for(j=1; j <=nlstate+ndeath; j++){
1.225     brouard  12059:        if (j!=i) {
                   12060:          fprintf(ficres,"%1d%1d",i,j);
                   12061:          printf("%1d%1d",i,j);
                   12062:          fprintf(ficlog,"%1d%1d",i,j);
                   12063:          for(k=1; k<=ncovmodel;k++){
                   12064:            printf(" %.5e",delti[jk]);
                   12065:            fprintf(ficlog," %.5e",delti[jk]);
                   12066:            fprintf(ficres," %.5e",delti[jk]);
                   12067:            jk++;
                   12068:          }
                   12069:          printf("\n");
                   12070:          fprintf(ficlog,"\n");
                   12071:          fprintf(ficres,"\n");
                   12072:        }
1.126     brouard  12073:       }
                   12074:     }
                   12075:     
                   12076:     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  12077:     if(mle >= 1) /* To big for the screen */
1.126     brouard  12078:       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");
                   12079:     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");
                   12080:     /* # 121 Var(a12)\n\ */
                   12081:     /* # 122 Cov(b12,a12) Var(b12)\n\ */
                   12082:     /* # 131 Cov(a13,a12) Cov(a13,b12, Var(a13)\n\ */
                   12083:     /* # 132 Cov(b13,a12) Cov(b13,b12, Cov(b13,a13) Var(b13)\n\ */
                   12084:     /* # 212 Cov(a21,a12) Cov(a21,b12, Cov(a21,a13) Cov(a21,b13) Var(a21)\n\ */
                   12085:     /* # 212 Cov(b21,a12) Cov(b21,b12, Cov(b21,a13) Cov(b21,b13) Cov(b21,a21) Var(b21)\n\ */
                   12086:     /* # 232 Cov(a23,a12) Cov(a23,b12, Cov(a23,a13) Cov(a23,b13) Cov(a23,a21) Cov(a23,b21) Var(a23)\n\ */
                   12087:     /* # 232 Cov(b23,a12) Cov(b23,b12) ... Var (b23)\n" */
                   12088:     
                   12089:     
                   12090:     /* Just to have a covariance matrix which will be more understandable
                   12091:        even is we still don't want to manage dictionary of variables
                   12092:     */
                   12093:     for(itimes=1;itimes<=2;itimes++){
                   12094:       jj=0;
                   12095:       for(i=1; i <=nlstate; i++){
1.225     brouard  12096:        for(j=1; j <=nlstate+ndeath; j++){
                   12097:          if(j==i) continue;
                   12098:          for(k=1; k<=ncovmodel;k++){
                   12099:            jj++;
                   12100:            ca[0]= k+'a'-1;ca[1]='\0';
                   12101:            if(itimes==1){
                   12102:              if(mle>=1)
                   12103:                printf("#%1d%1d%d",i,j,k);
                   12104:              fprintf(ficlog,"#%1d%1d%d",i,j,k);
                   12105:              fprintf(ficres,"#%1d%1d%d",i,j,k);
                   12106:            }else{
                   12107:              if(mle>=1)
                   12108:                printf("%1d%1d%d",i,j,k);
                   12109:              fprintf(ficlog,"%1d%1d%d",i,j,k);
                   12110:              fprintf(ficres,"%1d%1d%d",i,j,k);
                   12111:            }
                   12112:            ll=0;
                   12113:            for(li=1;li <=nlstate; li++){
                   12114:              for(lj=1;lj <=nlstate+ndeath; lj++){
                   12115:                if(lj==li) continue;
                   12116:                for(lk=1;lk<=ncovmodel;lk++){
                   12117:                  ll++;
                   12118:                  if(ll<=jj){
                   12119:                    cb[0]= lk +'a'-1;cb[1]='\0';
                   12120:                    if(ll<jj){
                   12121:                      if(itimes==1){
                   12122:                        if(mle>=1)
                   12123:                          printf(" Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
                   12124:                        fprintf(ficlog," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
                   12125:                        fprintf(ficres," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
                   12126:                      }else{
                   12127:                        if(mle>=1)
                   12128:                          printf(" %.5e",matcov[jj][ll]); 
                   12129:                        fprintf(ficlog," %.5e",matcov[jj][ll]); 
                   12130:                        fprintf(ficres," %.5e",matcov[jj][ll]); 
                   12131:                      }
                   12132:                    }else{
                   12133:                      if(itimes==1){
                   12134:                        if(mle>=1)
                   12135:                          printf(" Var(%s%1d%1d)",ca,i,j);
                   12136:                        fprintf(ficlog," Var(%s%1d%1d)",ca,i,j);
                   12137:                        fprintf(ficres," Var(%s%1d%1d)",ca,i,j);
                   12138:                      }else{
                   12139:                        if(mle>=1)
                   12140:                          printf(" %.7e",matcov[jj][ll]); 
                   12141:                        fprintf(ficlog," %.7e",matcov[jj][ll]); 
                   12142:                        fprintf(ficres," %.7e",matcov[jj][ll]); 
                   12143:                      }
                   12144:                    }
                   12145:                  }
                   12146:                } /* end lk */
                   12147:              } /* end lj */
                   12148:            } /* end li */
                   12149:            if(mle>=1)
                   12150:              printf("\n");
                   12151:            fprintf(ficlog,"\n");
                   12152:            fprintf(ficres,"\n");
                   12153:            numlinepar++;
                   12154:          } /* end k*/
                   12155:        } /*end j */
1.126     brouard  12156:       } /* end i */
                   12157:     } /* end itimes */
                   12158:     
                   12159:     fflush(ficlog);
                   12160:     fflush(ficres);
1.225     brouard  12161:     while(fgets(line, MAXLINE, ficpar)) {
                   12162:       /* If line starts with a # it is a comment */
                   12163:       if (line[0] == '#') {
                   12164:        numlinepar++;
                   12165:        fputs(line,stdout);
                   12166:        fputs(line,ficparo);
                   12167:        fputs(line,ficlog);
                   12168:        continue;
                   12169:       }else
                   12170:        break;
                   12171:     }
                   12172:     
1.209     brouard  12173:     /* while((c=getc(ficpar))=='#' && c!= EOF){ */
                   12174:     /*   ungetc(c,ficpar); */
                   12175:     /*   fgets(line, MAXLINE, ficpar); */
                   12176:     /*   fputs(line,stdout); */
                   12177:     /*   fputs(line,ficparo); */
                   12178:     /* } */
                   12179:     /* ungetc(c,ficpar); */
1.126     brouard  12180:     
                   12181:     estepm=0;
1.209     brouard  12182:     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  12183:       
                   12184:       if (num_filled != 6) {
                   12185:        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);
                   12186:        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);
                   12187:        goto end;
                   12188:       }
                   12189:       printf("agemin=%lf agemax=%lf bage=%lf fage=%lf estepm=%d ftolpl=%lf\n",ageminpar,agemaxpar, bage, fage, estepm, ftolpl);
                   12190:     }
                   12191:     /* ftolpl=6*ftol*1.e5; /\* 6.e-3 make convergences in less than 80 loops for the prevalence limit *\/ */
                   12192:     /*ftolpl=6.e-4;*/ /* 6.e-3 make convergences in less than 80 loops for the prevalence limit */
                   12193:     
1.209     brouard  12194:     /* fscanf(ficpar,"agemin=%lf agemax=%lf bage=%lf fage=%lf estepm=%d ftolpl=%\n",&ageminpar,&agemaxpar, &bage, &fage, &estepm); */
1.126     brouard  12195:     if (estepm==0 || estepm < stepm) estepm=stepm;
                   12196:     if (fage <= 2) {
                   12197:       bage = ageminpar;
                   12198:       fage = agemaxpar;
                   12199:     }
                   12200:     
                   12201:     fprintf(ficres,"# agemin agemax for life expectancy, bage fage (if mle==0 ie no data nor Max likelihood).\n");
1.211     brouard  12202:     fprintf(ficres,"agemin=%.0f agemax=%.0f bage=%.0f fage=%.0f estepm=%d ftolpl=%e\n",ageminpar,agemaxpar,bage,fage, estepm, ftolpl);
                   12203:     fprintf(ficparo,"agemin=%.0f agemax=%.0f bage=%.0f fage=%.0f estepm=%d, ftolpl=%e\n",ageminpar,agemaxpar,bage,fage, estepm, ftolpl);
1.220     brouard  12204:                
1.186     brouard  12205:     /* Other stuffs, more or less useful */    
1.254     brouard  12206:     while(fgets(line, MAXLINE, ficpar)) {
                   12207:       /* If line starts with a # it is a comment */
                   12208:       if (line[0] == '#') {
                   12209:        numlinepar++;
                   12210:        fputs(line,stdout);
                   12211:        fputs(line,ficparo);
                   12212:        fputs(line,ficlog);
                   12213:        continue;
                   12214:       }else
                   12215:        break;
                   12216:     }
                   12217: 
                   12218:     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){
                   12219:       
                   12220:       if (num_filled != 7) {
                   12221:        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);
                   12222:        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);
                   12223:        goto end;
                   12224:       }
                   12225:       printf("begin-prev-date=%.lf/%.lf/%.lf end-prev-date=%.lf/%.lf/%.lf mov_average=%d\n",jprev1, mprev1,anprev1,jprev2, mprev2,anprev2,mobilav);
                   12226:       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);
                   12227:       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);
                   12228:       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  12229:     }
1.254     brouard  12230: 
                   12231:     while(fgets(line, MAXLINE, ficpar)) {
                   12232:       /* If line starts with a # it is a comment */
                   12233:       if (line[0] == '#') {
                   12234:        numlinepar++;
                   12235:        fputs(line,stdout);
                   12236:        fputs(line,ficparo);
                   12237:        fputs(line,ficlog);
                   12238:        continue;
                   12239:       }else
                   12240:        break;
1.126     brouard  12241:     }
                   12242:     
                   12243:     
                   12244:     dateprev1=anprev1+(mprev1-1)/12.+(jprev1-1)/365.;
                   12245:     dateprev2=anprev2+(mprev2-1)/12.+(jprev2-1)/365.;
                   12246:     
1.254     brouard  12247:     if((num_filled=sscanf(line,"pop_based=%d\n",&popbased)) !=EOF){
                   12248:       if (num_filled != 1) {
                   12249:        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);
                   12250:        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);
                   12251:        goto end;
                   12252:       }
                   12253:       printf("pop_based=%d\n",popbased);
                   12254:       fprintf(ficlog,"pop_based=%d\n",popbased);
                   12255:       fprintf(ficparo,"pop_based=%d\n",popbased);   
                   12256:       fprintf(ficres,"pop_based=%d\n",popbased);   
                   12257:     }
                   12258:      
1.258     brouard  12259:     /* Results */
                   12260:     nresult=0;
                   12261:     do{
                   12262:       if(!fgets(line, MAXLINE, ficpar)){
                   12263:        endishere=1;
                   12264:        parameterline=14;
                   12265:       }else if (line[0] == '#') {
                   12266:        /* If line starts with a # it is a comment */
1.254     brouard  12267:        numlinepar++;
                   12268:        fputs(line,stdout);
                   12269:        fputs(line,ficparo);
                   12270:        fputs(line,ficlog);
                   12271:        continue;
1.258     brouard  12272:       }else if(sscanf(line,"prevforecast=%[^\n]\n",modeltemp))
                   12273:        parameterline=11;
                   12274:       else if(sscanf(line,"backcast=%[^\n]\n",modeltemp))
                   12275:        parameterline=12;
                   12276:       else if(sscanf(line,"result:%[^\n]\n",modeltemp))
                   12277:        parameterline=13;
                   12278:       else{
                   12279:        parameterline=14;
1.254     brouard  12280:       }
1.258     brouard  12281:       switch (parameterline){ 
                   12282:       case 11:
                   12283:        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){
                   12284:          if (num_filled != 8) {
                   12285:            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\n, your line=%s . Probably you are running an older format.\n",num_filled,line);
                   12286:            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 mov_average=0\n, your line=%s . Probably you are running an older format.\n",num_filled,line);
                   12287:            goto end;
                   12288:          }
                   12289:          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);
                   12290:          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);
                   12291:          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);
                   12292:          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);
                   12293:          /* day and month of proj2 are not used but only year anproj2.*/
1.273     brouard  12294:          dateproj1=anproj1+(mproj1-1)/12.+(jproj1-1)/365.;
                   12295:          dateproj2=anproj2+(mproj2-1)/12.+(jproj2-1)/365.;
                   12296: 
1.258     brouard  12297:        }
1.254     brouard  12298:        break;
1.258     brouard  12299:       case 12:
                   12300:        /*fscanf(ficpar,"backcast=%d starting-back-date=%lf/%lf/%lf final-back-date=%lf/%lf/%lf mobil_average=%d\n",&backcast,&jback1,&mback1,&anback1,&jback2,&mback2,&anback2,&mobilavproj);*/
                   12301:        if((num_filled=sscanf(line,"backcast=%d starting-back-date=%lf/%lf/%lf final-back-date=%lf/%lf/%lf mobil_average=%d\n",&backcast,&jback1,&mback1,&anback1,&jback2,&mback2,&anback2,&mobilavproj)) !=EOF){
                   12302:          if (num_filled != 8) {
1.262     brouard  12303:            printf("Error: Not 8 (data)parameters in line but %d, for example:backcast=1 starting-back-date=1/1/1990 final-back-date=1/1/1970 mobil_average=1\n, your line=%s . Probably you are running an older format.\n",num_filled,line);
                   12304:            fprintf(ficlog,"Error: Not 8 (data)parameters in line but %d, for example:backcast=1 starting-back-date=1/1/1990 final-back-date=1/1/1970 mobil_average=1\n, your line=%s . Probably you are running an older format.\n",num_filled,line);
1.258     brouard  12305:            goto end;
                   12306:          }
                   12307:          printf("backcast=%d starting-back-date=%.lf/%.lf/%.lf final-back-date=%.lf/%.lf/%.lf mobil_average=%d\n",backcast,jback1,mback1,anback1,jback2,mback2,anback2,mobilavproj);
                   12308:          fprintf(ficparo,"backcast=%d starting-back-date=%.lf/%.lf/%.lf final-back-date=%.lf/%.lf/%.lf mobil_average=%d\n",backcast,jback1,mback1,anback1,jback2,mback2,anback2,mobilavproj);
                   12309:          fprintf(ficlog,"backcast=%d starting-back-date=%.lf/%.lf/%.lf final-back-date=%.lf/%.lf/%.lf mobil_average=%d\n",backcast,jback1,mback1,anback1,jback2,mback2,anback2,mobilavproj);
                   12310:          fprintf(ficres,"backcast=%d starting-back-date=%.lf/%.lf/%.lf final-back-date=%.lf/%.lf/%.lf mobil_average=%d\n",backcast,jback1,mback1,anback1,jback2,mback2,anback2,mobilavproj);
                   12311:          /* day and month of proj2 are not used but only year anproj2.*/
1.273     brouard  12312:          dateback1=anback1+(mback1-1)/12.+(jback1-1)/365.;
                   12313:          dateback2=anback2+(mback2-1)/12.+(jback2-1)/365.;
1.258     brouard  12314:        }
1.230     brouard  12315:        break;
1.258     brouard  12316:       case 13:
                   12317:        if((num_filled=sscanf(line,"result:%[^\n]\n",resultline)) !=EOF){
                   12318:          if (num_filled == 0){
                   12319:            resultline[0]='\0';
                   12320:            printf("Warning %d: no result line! It should be at minimum 'result: V2=0 V1=1 or result:.\n%s\n", num_filled, line);
                   12321:            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);
                   12322:            break;
                   12323:          } else if (num_filled != 1){
                   12324:            printf("ERROR %d: result line! It should be at minimum 'result: V2=0 V1=1 or result:.' %s\n",num_filled, line);
                   12325:            fprintf(ficlog,"ERROR %d: result line! It should be at minimum 'result: V2=0 V1=1 or result:.' %s\n",num_filled, line);
                   12326:          }
                   12327:          nresult++; /* Sum of resultlines */
                   12328:          printf("Result %d: result=%s\n",nresult, resultline);
                   12329:          if(nresult > MAXRESULTLINES){
                   12330:            printf("ERROR: Current version of IMaCh limits the number of resultlines to %d, you used %d\n",MAXRESULTLINES,nresult);
                   12331:            fprintf(ficlog,"ERROR: Current version of IMaCh limits the number of resultlines to %d, you used %d\n",MAXRESULTLINES,nresult);
                   12332:            goto end;
                   12333:          }
                   12334:          decoderesult(resultline, nresult); /* Fills TKresult[nresult] combination and Tresult[nresult][k4+1] combination values */
                   12335:          fprintf(ficparo,"result: %s\n",resultline);
                   12336:          fprintf(ficres,"result: %s\n",resultline);
                   12337:          fprintf(ficlog,"result: %s\n",resultline);
1.230     brouard  12338:          break;
1.258     brouard  12339:        case 14: 
1.259     brouard  12340:          if(ncovmodel >2 && nresult==0 ){
                   12341:            printf("ERROR: no result lines! It should be at minimum 'result: V2=0 V1=1 or result:.' %s\n",line);
1.258     brouard  12342:            goto end;
                   12343:          }
1.259     brouard  12344:          break;
1.258     brouard  12345:        default:
                   12346:          nresult=1;
                   12347:          decoderesult(".",nresult ); /* No covariate */
                   12348:        }
                   12349:       } /* End switch parameterline */
                   12350:     }while(endishere==0); /* End do */
1.126     brouard  12351:     
1.230     brouard  12352:     /* freqsummary(fileres, agemin, agemax, s, agev, nlstate, imx,Tvaraff,nbcode, ncodemax,mint,anint); */
1.145     brouard  12353:     /* ,dateprev1,dateprev2,jprev1, mprev1,anprev1,jprev2, mprev2,anprev2); */
1.126     brouard  12354:     
                   12355:     replace_back_to_slash(pathc,pathcd); /* Even gnuplot wants a / */
1.194     brouard  12356:     if(ageminpar == AGEOVERFLOW ||agemaxpar == -AGEOVERFLOW){
1.230     brouard  12357:       printf("Warning! Error in gnuplot file with ageminpar %f or agemaxpar %f overflow\n\
1.194     brouard  12358: This is probably because your parameter file doesn't \n  contain the exact number of lines (or columns) corresponding to your model line.\n\
                   12359: Please run with mle=-1 to get a correct covariance matrix.\n",ageminpar,agemaxpar);
1.230     brouard  12360:       fprintf(ficlog,"Warning! Error in gnuplot file with ageminpar %f or agemaxpar %f overflow\n\
1.194     brouard  12361: This is probably because your parameter file doesn't \n  contain the exact number of lines (or columns) corresponding to your model line.\n\
                   12362: Please run with mle=-1 to get a correct covariance matrix.\n",ageminpar,agemaxpar);
1.220     brouard  12363:     }else{
1.270     brouard  12364:       /* printinggnuplot(fileresu, optionfilefiname,ageminpar,agemaxpar,fage, prevfcast, backcast, pathc,p, (int)anproj1-(int)agemin, (int)anback1-(int)agemax+1); */
                   12365:       printinggnuplot(fileresu, optionfilefiname,ageminpar,agemaxpar,bage, fage, prevfcast, backcast, pathc,p, (int)anproj1-bage, (int)anback1-fage);
1.220     brouard  12366:     }
                   12367:     printinghtml(fileresu,title,datafile, firstpass, lastpass, stepm, weightopt, \
1.258     brouard  12368:                 model,imx,jmin,jmax,jmean,rfileres,popforecast,mobilav,prevfcast,mobilavproj,backcast, estepm, \
1.273     brouard  12369:                 jprev1,mprev1,anprev1,dateprev1, dateproj1, dateback1,jprev2,mprev2,anprev2,dateprev2,dateproj2, dateback2);
1.220     brouard  12370:                
1.225     brouard  12371:     /*------------ free_vector  -------------*/
                   12372:     /*  chdir(path); */
1.220     brouard  12373:                
1.215     brouard  12374:     /* free_ivector(wav,1,imx); */  /* Moved after last prevalence call */
                   12375:     /* free_imatrix(dh,1,lastpass-firstpass+2,1,imx); */
                   12376:     /* free_imatrix(bh,1,lastpass-firstpass+2,1,imx); */
                   12377:     /* free_imatrix(mw,1,lastpass-firstpass+2,1,imx);    */
1.290     brouard  12378:     free_lvector(num,firstobs,lastobs);
                   12379:     free_vector(agedc,firstobs,lastobs);
1.126     brouard  12380:     /*free_matrix(covar,0,NCOVMAX,1,n);*/
                   12381:     /*free_matrix(covar,1,NCOVMAX,1,n);*/
                   12382:     fclose(ficparo);
                   12383:     fclose(ficres);
1.220     brouard  12384:                
                   12385:                
1.186     brouard  12386:     /* Other results (useful)*/
1.220     brouard  12387:                
                   12388:                
1.126     brouard  12389:     /*--------------- Prevalence limit  (period or stable prevalence) --------------*/
1.180     brouard  12390:     /*#include "prevlim.h"*/  /* Use ficrespl, ficlog */
                   12391:     prlim=matrix(1,nlstate,1,nlstate);
1.209     brouard  12392:     prevalence_limit(p, prlim,  ageminpar, agemaxpar, ftolpl, &ncvyear);
1.126     brouard  12393:     fclose(ficrespl);
                   12394: 
                   12395:     /*------------- h Pij x at various ages ------------*/
1.180     brouard  12396:     /*#include "hpijx.h"*/
                   12397:     hPijx(p, bage, fage);
1.145     brouard  12398:     fclose(ficrespij);
1.227     brouard  12399:     
1.220     brouard  12400:     /* ncovcombmax=  pow(2,cptcoveff); */
1.219     brouard  12401:     /*-------------- Variance of one-step probabilities---*/
1.145     brouard  12402:     k=1;
1.126     brouard  12403:     varprob(optionfilefiname, matcov, p, delti, nlstate, bage, fage,k,Tvar,nbcode, ncodemax,strstart);
1.227     brouard  12404:     
1.269     brouard  12405:     /* Prevalence for each covariate combination in probs[age][status][cov] */
                   12406:     probs= ma3x(AGEINF,AGESUP,1,nlstate+ndeath, 1,ncovcombmax);
                   12407:     for(i=AGEINF;i<=AGESUP;i++)
1.219     brouard  12408:       for(j=1;j<=nlstate+ndeath;j++) /* ndeath is useless but a necessity to be compared with mobaverages */
1.225     brouard  12409:        for(k=1;k<=ncovcombmax;k++)
                   12410:          probs[i][j][k]=0.;
1.269     brouard  12411:     prevalence(probs, ageminpar, agemaxpar, s, agev, nlstate, imx, Tvar, nbcode, 
                   12412:               ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass);
1.219     brouard  12413:     if (mobilav!=0 ||mobilavproj !=0 ) {
1.269     brouard  12414:       mobaverages= ma3x(AGEINF, AGESUP,1,nlstate+ndeath, 1,ncovcombmax);
                   12415:       for(i=AGEINF;i<=AGESUP;i++)
1.268     brouard  12416:        for(j=1;j<=nlstate+ndeath;j++)
1.227     brouard  12417:          for(k=1;k<=ncovcombmax;k++)
                   12418:            mobaverages[i][j][k]=0.;
1.219     brouard  12419:       mobaverage=mobaverages;
                   12420:       if (mobilav!=0) {
1.235     brouard  12421:        printf("Movingaveraging observed prevalence\n");
1.258     brouard  12422:        fprintf(ficlog,"Movingaveraging observed prevalence\n");
1.227     brouard  12423:        if (movingaverage(probs, ageminpar, agemaxpar, mobaverage, mobilav)!=0){
                   12424:          fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);
                   12425:          printf(" Error in movingaverage mobilav=%d\n",mobilav);
                   12426:        }
1.269     brouard  12427:       } else if (mobilavproj !=0) {
1.235     brouard  12428:        printf("Movingaveraging projected observed prevalence\n");
1.258     brouard  12429:        fprintf(ficlog,"Movingaveraging projected observed prevalence\n");
1.227     brouard  12430:        if (movingaverage(probs, ageminpar, agemaxpar, mobaverage, mobilavproj)!=0){
                   12431:          fprintf(ficlog," Error in movingaverage mobilavproj=%d\n",mobilavproj);
                   12432:          printf(" Error in movingaverage mobilavproj=%d\n",mobilavproj);
                   12433:        }
1.269     brouard  12434:       }else{
                   12435:        printf("Internal error moving average\n");
                   12436:        fflush(stdout);
                   12437:        exit(1);
1.219     brouard  12438:       }
                   12439:     }/* end if moving average */
1.227     brouard  12440:     
1.126     brouard  12441:     /*---------- Forecasting ------------------*/
                   12442:     if(prevfcast==1){
                   12443:       /*    if(stepm ==1){*/
1.269     brouard  12444:       prevforecast(fileresu, anproj1, mproj1, jproj1, agemin, agemax, dateprev1, dateprev2, mobilavproj, mobaverage, bage, fage, firstpass, lastpass, anproj2, p, cptcoveff);
1.126     brouard  12445:     }
1.269     brouard  12446: 
                   12447:     /* Backcasting */
1.217     brouard  12448:     if(backcast==1){
1.219     brouard  12449:       ddnewms=matrix(1,nlstate+ndeath,1,nlstate+ndeath);       
                   12450:       ddoldms=matrix(1,nlstate+ndeath,1,nlstate+ndeath);       
                   12451:       ddsavms=matrix(1,nlstate+ndeath,1,nlstate+ndeath);
                   12452: 
                   12453:       /*--------------- Back Prevalence limit  (period or stable prevalence) --------------*/
                   12454: 
                   12455:       bprlim=matrix(1,nlstate,1,nlstate);
1.269     brouard  12456: 
1.219     brouard  12457:       back_prevalence_limit(p, bprlim,  ageminpar, agemaxpar, ftolpl, &ncvyear, dateprev1, dateprev2, firstpass, lastpass, mobilavproj);
                   12458:       fclose(ficresplb);
                   12459: 
1.222     brouard  12460:       hBijx(p, bage, fage, mobaverage);
                   12461:       fclose(ficrespijb);
1.219     brouard  12462: 
1.269     brouard  12463:       prevbackforecast(fileresu, mobaverage, anback1, mback1, jback1, agemin, agemax, dateprev1, dateprev2,
                   12464:                       mobilavproj, bage, fage, firstpass, lastpass, anback2, p, cptcoveff);
                   12465:       varbprlim(fileresu, nresult, mobaverage, mobilavproj, bage, fage, bprlim, &ncvyear, ftolpl, p, matcov, delti, stepm, cptcoveff);
1.268     brouard  12466: 
                   12467:       
1.269     brouard  12468:       free_matrix(bprlim,1,nlstate,1,nlstate); /*here or after loop ? */
1.219     brouard  12469:       free_matrix(ddnewms, 1, nlstate+ndeath, 1, nlstate+ndeath);
                   12470:       free_matrix(ddsavms, 1, nlstate+ndeath, 1, nlstate+ndeath);
                   12471:       free_matrix(ddoldms, 1, nlstate+ndeath, 1, nlstate+ndeath);
1.269     brouard  12472:     }    /* end  Backcasting */
1.268     brouard  12473:  
1.186     brouard  12474:  
                   12475:     /* ------ Other prevalence ratios------------ */
1.126     brouard  12476: 
1.215     brouard  12477:     free_ivector(wav,1,imx);
                   12478:     free_imatrix(dh,1,lastpass-firstpass+2,1,imx);
                   12479:     free_imatrix(bh,1,lastpass-firstpass+2,1,imx);
                   12480:     free_imatrix(mw,1,lastpass-firstpass+2,1,imx);   
1.218     brouard  12481:                
                   12482:                
1.127     brouard  12483:     /*---------- Health expectancies, no variances ------------*/
1.218     brouard  12484:                
1.201     brouard  12485:     strcpy(filerese,"E_");
                   12486:     strcat(filerese,fileresu);
1.126     brouard  12487:     if((ficreseij=fopen(filerese,"w"))==NULL) {
                   12488:       printf("Problem with Health Exp. resultfile: %s\n", filerese); exit(0);
                   12489:       fprintf(ficlog,"Problem with Health Exp. resultfile: %s\n", filerese); exit(0);
                   12490:     }
1.208     brouard  12491:     printf("Computing Health Expectancies: result on file '%s' ...", filerese);fflush(stdout);
                   12492:     fprintf(ficlog,"Computing Health Expectancies: result on file '%s' ...", filerese);fflush(ficlog);
1.238     brouard  12493: 
                   12494:     pstamp(ficreseij);
1.219     brouard  12495:                
1.235     brouard  12496:     i1=pow(2,cptcoveff); /* Number of combination of dummy covariates */
                   12497:     if (cptcovn < 1){i1=1;}
                   12498:     
                   12499:     for(nres=1; nres <= nresult; nres++) /* For each resultline */
                   12500:     for(k=1; k<=i1;k++){ /* For any combination of dummy covariates, fixed and varying */
1.253     brouard  12501:       if(i1 != 1 && TKresult[nres]!= k)
1.235     brouard  12502:        continue;
1.219     brouard  12503:       fprintf(ficreseij,"\n#****** ");
1.235     brouard  12504:       printf("\n#****** ");
1.225     brouard  12505:       for(j=1;j<=cptcoveff;j++) {
1.227     brouard  12506:        fprintf(ficreseij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
1.235     brouard  12507:        printf("V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   12508:       }
                   12509:       for (j=1; j<= nsq; j++){ /* For each selected (single) quantitative value */
                   12510:        printf(" V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]);
                   12511:        fprintf(ficreseij," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]);
1.219     brouard  12512:       }
                   12513:       fprintf(ficreseij,"******\n");
1.235     brouard  12514:       printf("******\n");
1.219     brouard  12515:       
                   12516:       eij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
                   12517:       oldm=oldms;savm=savms;
1.235     brouard  12518:       evsij(eij, p, nlstate, stepm, (int) bage, (int)fage, oldm, savm, k, estepm, strstart, nres);  
1.127     brouard  12519:       
1.219     brouard  12520:       free_ma3x(eij,1,nlstate,1,nlstate,(int) bage, (int)fage);
1.127     brouard  12521:     }
                   12522:     fclose(ficreseij);
1.208     brouard  12523:     printf("done evsij\n");fflush(stdout);
                   12524:     fprintf(ficlog,"done evsij\n");fflush(ficlog);
1.269     brouard  12525: 
1.218     brouard  12526:                
1.227     brouard  12527:     /*---------- State-specific expectancies and variances ------------*/
1.218     brouard  12528:                
1.201     brouard  12529:     strcpy(filerest,"T_");
                   12530:     strcat(filerest,fileresu);
1.127     brouard  12531:     if((ficrest=fopen(filerest,"w"))==NULL) {
                   12532:       printf("Problem with total LE resultfile: %s\n", filerest);goto end;
                   12533:       fprintf(ficlog,"Problem with total LE resultfile: %s\n", filerest);goto end;
                   12534:     }
1.208     brouard  12535:     printf("Computing Total Life expectancies with their standard errors: file '%s' ...\n", filerest); fflush(stdout);
                   12536:     fprintf(ficlog,"Computing Total Life expectancies with their standard errors: file '%s' ...\n", filerest); fflush(ficlog);
1.201     brouard  12537:     strcpy(fileresstde,"STDE_");
                   12538:     strcat(fileresstde,fileresu);
1.126     brouard  12539:     if((ficresstdeij=fopen(fileresstde,"w"))==NULL) {
1.227     brouard  12540:       printf("Problem with State specific Exp. and std errors resultfile: %s\n", fileresstde); exit(0);
                   12541:       fprintf(ficlog,"Problem with State specific Exp. and std errors resultfile: %s\n", fileresstde); exit(0);
1.126     brouard  12542:     }
1.227     brouard  12543:     printf("  Computing State-specific Expectancies and standard errors: result on file '%s' \n", fileresstde);
                   12544:     fprintf(ficlog,"  Computing State-specific Expectancies and standard errors: result on file '%s' \n", fileresstde);
1.126     brouard  12545: 
1.201     brouard  12546:     strcpy(filerescve,"CVE_");
                   12547:     strcat(filerescve,fileresu);
1.126     brouard  12548:     if((ficrescveij=fopen(filerescve,"w"))==NULL) {
1.227     brouard  12549:       printf("Problem with Covar. State-specific Exp. resultfile: %s\n", filerescve); exit(0);
                   12550:       fprintf(ficlog,"Problem with Covar. State-specific Exp. resultfile: %s\n", filerescve); exit(0);
1.126     brouard  12551:     }
1.227     brouard  12552:     printf("    Computing Covar. of State-specific Expectancies: result on file '%s' \n", filerescve);
                   12553:     fprintf(ficlog,"    Computing Covar. of State-specific Expectancies: result on file '%s' \n", filerescve);
1.126     brouard  12554: 
1.201     brouard  12555:     strcpy(fileresv,"V_");
                   12556:     strcat(fileresv,fileresu);
1.126     brouard  12557:     if((ficresvij=fopen(fileresv,"w"))==NULL) {
                   12558:       printf("Problem with variance resultfile: %s\n", fileresv);exit(0);
                   12559:       fprintf(ficlog,"Problem with variance resultfile: %s\n", fileresv);exit(0);
                   12560:     }
1.227     brouard  12561:     printf("      Computing Variance-covariance of State-specific Expectancies: file '%s' ... ", fileresv);fflush(stdout);
                   12562:     fprintf(ficlog,"      Computing Variance-covariance of State-specific Expectancies: file '%s' ... ", fileresv);fflush(ficlog);
1.126     brouard  12563: 
1.235     brouard  12564:     i1=pow(2,cptcoveff); /* Number of combination of dummy covariates */
                   12565:     if (cptcovn < 1){i1=1;}
                   12566:     
                   12567:     for(nres=1; nres <= nresult; nres++) /* For each resultline */
                   12568:     for(k=1; k<=i1;k++){ /* For any combination of dummy covariates, fixed and varying */
1.253     brouard  12569:       if(i1 != 1 && TKresult[nres]!= k)
1.235     brouard  12570:        continue;
1.242     brouard  12571:       printf("\n#****** Result for:");
                   12572:       fprintf(ficrest,"\n#****** Result for:");
                   12573:       fprintf(ficlog,"\n#****** Result for:");
1.227     brouard  12574:       for(j=1;j<=cptcoveff;j++){ 
                   12575:        printf("V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   12576:        fprintf(ficrest,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   12577:        fprintf(ficlog,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   12578:       }
1.235     brouard  12579:       for (j=1; j<= nsq; j++){ /* For each selected (single) quantitative value */
                   12580:        printf(" V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]);
                   12581:        fprintf(ficrest," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]);
                   12582:        fprintf(ficlog," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]);
                   12583:       }        
1.208     brouard  12584:       fprintf(ficrest,"******\n");
1.227     brouard  12585:       fprintf(ficlog,"******\n");
                   12586:       printf("******\n");
1.208     brouard  12587:       
                   12588:       fprintf(ficresstdeij,"\n#****** ");
                   12589:       fprintf(ficrescveij,"\n#****** ");
1.225     brouard  12590:       for(j=1;j<=cptcoveff;j++) {
1.227     brouard  12591:        fprintf(ficresstdeij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   12592:        fprintf(ficrescveij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
1.208     brouard  12593:       }
1.235     brouard  12594:       for (j=1; j<= nsq; j++){ /* For each selected (single) quantitative value */
                   12595:        fprintf(ficresstdeij," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]);
                   12596:        fprintf(ficrescveij," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]);
                   12597:       }        
1.208     brouard  12598:       fprintf(ficresstdeij,"******\n");
                   12599:       fprintf(ficrescveij,"******\n");
                   12600:       
                   12601:       fprintf(ficresvij,"\n#****** ");
1.238     brouard  12602:       /* pstamp(ficresvij); */
1.225     brouard  12603:       for(j=1;j<=cptcoveff;j++) 
1.227     brouard  12604:        fprintf(ficresvij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
1.235     brouard  12605:       for (j=1; j<= nsq; j++){ /* For each selected (single) quantitative value */
                   12606:        fprintf(ficresvij," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]);
                   12607:       }        
1.208     brouard  12608:       fprintf(ficresvij,"******\n");
                   12609:       
                   12610:       eij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
                   12611:       oldm=oldms;savm=savms;
1.235     brouard  12612:       printf(" cvevsij ");
                   12613:       fprintf(ficlog, " cvevsij ");
                   12614:       cvevsij(eij, p, nlstate, stepm, (int) bage, (int)fage, oldm, savm, k, estepm, delti, matcov, strstart, nres);
1.208     brouard  12615:       printf(" end cvevsij \n ");
                   12616:       fprintf(ficlog, " end cvevsij \n ");
                   12617:       
                   12618:       /*
                   12619:        */
                   12620:       /* goto endfree; */
                   12621:       
                   12622:       vareij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
                   12623:       pstamp(ficrest);
                   12624:       
1.269     brouard  12625:       epj=vector(1,nlstate+1);
1.208     brouard  12626:       for(vpopbased=0; vpopbased <= popbased; vpopbased++){ /* Done for vpopbased=0 and vpopbased=1 if popbased==1*/
1.227     brouard  12627:        oldm=oldms;savm=savms; /* ZZ Segmentation fault */
                   12628:        cptcod= 0; /* To be deleted */
                   12629:        printf("varevsij vpopbased=%d \n",vpopbased);
                   12630:        fprintf(ficlog, "varevsij vpopbased=%d \n",vpopbased);
1.235     brouard  12631:        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  12632:        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 ");
                   12633:        if(vpopbased==1)
                   12634:          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);
                   12635:        else
1.288     brouard  12636:          fprintf(ficrest,"the age specific forward period (stable) prevalences in each health state \n");
1.227     brouard  12637:        fprintf(ficrest,"# Age popbased mobilav e.. (std) ");
                   12638:        for (i=1;i<=nlstate;i++) fprintf(ficrest,"e.%d (std) ",i);
                   12639:        fprintf(ficrest,"\n");
                   12640:        /* printf("Which p?\n"); for(i=1;i<=npar;i++)printf("p[i=%d]=%lf,",i,p[i]);printf("\n"); */
1.288     brouard  12641:        printf("Computing age specific forward period (stable) prevalences in each health state \n");
                   12642:        fprintf(ficlog,"Computing age specific forward period (stable) prevalences in each health state \n");
1.227     brouard  12643:        for(age=bage; age <=fage ;age++){
1.235     brouard  12644:          prevalim(prlim, nlstate, p, age, oldm, savm, ftolpl, &ncvyear, k, nres); /*ZZ Is it the correct prevalim */
1.227     brouard  12645:          if (vpopbased==1) {
                   12646:            if(mobilav ==0){
                   12647:              for(i=1; i<=nlstate;i++)
                   12648:                prlim[i][i]=probs[(int)age][i][k];
                   12649:            }else{ /* mobilav */ 
                   12650:              for(i=1; i<=nlstate;i++)
                   12651:                prlim[i][i]=mobaverage[(int)age][i][k];
                   12652:            }
                   12653:          }
1.219     brouard  12654:          
1.227     brouard  12655:          fprintf(ficrest," %4.0f %d %d",age, vpopbased, mobilav);
                   12656:          /* fprintf(ficrest," %4.0f %d %d %d %d",age, vpopbased, mobilav,Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]); */ /* to be done */
                   12657:          /* printf(" age %4.0f ",age); */
                   12658:          for(j=1, epj[nlstate+1]=0.;j <=nlstate;j++){
                   12659:            for(i=1, epj[j]=0.;i <=nlstate;i++) {
                   12660:              epj[j] += prlim[i][i]*eij[i][j][(int)age];
                   12661:              /*ZZZ  printf("%lf %lf ", prlim[i][i] ,eij[i][j][(int)age]);*/
                   12662:              /* printf("%lf %lf ", prlim[i][i] ,eij[i][j][(int)age]); */
                   12663:            }
                   12664:            epj[nlstate+1] +=epj[j];
                   12665:          }
                   12666:          /* printf(" age %4.0f \n",age); */
1.219     brouard  12667:          
1.227     brouard  12668:          for(i=1, vepp=0.;i <=nlstate;i++)
                   12669:            for(j=1;j <=nlstate;j++)
                   12670:              vepp += vareij[i][j][(int)age];
                   12671:          fprintf(ficrest," %7.3f (%7.3f)", epj[nlstate+1],sqrt(vepp));
                   12672:          for(j=1;j <=nlstate;j++){
                   12673:            fprintf(ficrest," %7.3f (%7.3f)", epj[j],sqrt(vareij[j][j][(int)age]));
                   12674:          }
                   12675:          fprintf(ficrest,"\n");
                   12676:        }
1.208     brouard  12677:       } /* End vpopbased */
1.269     brouard  12678:       free_vector(epj,1,nlstate+1);
1.208     brouard  12679:       free_ma3x(eij,1,nlstate,1,nlstate,(int) bage, (int)fage);
                   12680:       free_ma3x(vareij,1,nlstate,1,nlstate,(int) bage, (int)fage);
1.235     brouard  12681:       printf("done selection\n");fflush(stdout);
                   12682:       fprintf(ficlog,"done selection\n");fflush(ficlog);
1.208     brouard  12683:       
1.235     brouard  12684:     } /* End k selection */
1.227     brouard  12685: 
                   12686:     printf("done State-specific expectancies\n");fflush(stdout);
                   12687:     fprintf(ficlog,"done State-specific expectancies\n");fflush(ficlog);
                   12688: 
1.288     brouard  12689:     /* variance-covariance of forward period prevalence*/
1.269     brouard  12690:     varprlim(fileresu, nresult, mobaverage, mobilavproj, bage, fage, prlim, &ncvyear, ftolpl, p, matcov, delti, stepm, cptcoveff);
1.268     brouard  12691: 
1.227     brouard  12692:     
1.290     brouard  12693:     free_vector(weight,firstobs,lastobs);
1.227     brouard  12694:     free_imatrix(Tvard,1,NCOVMAX,1,2);
1.290     brouard  12695:     free_imatrix(s,1,maxwav+1,firstobs,lastobs);
                   12696:     free_matrix(anint,1,maxwav,firstobs,lastobs); 
                   12697:     free_matrix(mint,1,maxwav,firstobs,lastobs);
                   12698:     free_ivector(cod,firstobs,lastobs);
1.227     brouard  12699:     free_ivector(tab,1,NCOVMAX);
                   12700:     fclose(ficresstdeij);
                   12701:     fclose(ficrescveij);
                   12702:     fclose(ficresvij);
                   12703:     fclose(ficrest);
                   12704:     fclose(ficpar);
                   12705:     
                   12706:     
1.126     brouard  12707:     /*---------- End : free ----------------*/
1.219     brouard  12708:     if (mobilav!=0 ||mobilavproj !=0)
1.269     brouard  12709:       free_ma3x(mobaverages,AGEINF, AGESUP,1,nlstate+ndeath, 1,ncovcombmax); /* We need to have a squared matrix with prevalence of the dead! */
                   12710:     free_ma3x(probs,AGEINF,AGESUP,1,nlstate+ndeath, 1,ncovcombmax);
1.220     brouard  12711:     free_matrix(prlim,1,nlstate,1,nlstate); /*here or after loop ? */
                   12712:     free_matrix(pmmij,1,nlstate+ndeath,1,nlstate+ndeath);
1.126     brouard  12713:   }  /* mle==-3 arrives here for freeing */
1.227     brouard  12714:   /* endfree:*/
                   12715:   free_matrix(oldms, 1,nlstate+ndeath,1,nlstate+ndeath);
                   12716:   free_matrix(newms, 1,nlstate+ndeath,1,nlstate+ndeath);
                   12717:   free_matrix(savms, 1,nlstate+ndeath,1,nlstate+ndeath);
1.290     brouard  12718:   if(ntv+nqtv>=1)free_ma3x(cotvar,1,maxwav,1,ntv+nqtv,firstobs,lastobs);
                   12719:   if(nqtv>=1)free_ma3x(cotqvar,1,maxwav,1,nqtv,firstobs,lastobs);
                   12720:   if(nqv>=1)free_matrix(coqvar,1,nqv,firstobs,lastobs);
                   12721:   free_matrix(covar,0,NCOVMAX,firstobs,lastobs);
1.227     brouard  12722:   free_matrix(matcov,1,npar,1,npar);
                   12723:   free_matrix(hess,1,npar,1,npar);
                   12724:   /*free_vector(delti,1,npar);*/
                   12725:   free_ma3x(delti3,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel); 
                   12726:   free_matrix(agev,1,maxwav,1,imx);
1.269     brouard  12727:   free_ma3x(paramstart,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel);
1.227     brouard  12728:   free_ma3x(param,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel);
                   12729:   
                   12730:   free_ivector(ncodemax,1,NCOVMAX);
                   12731:   free_ivector(ncodemaxwundef,1,NCOVMAX);
                   12732:   free_ivector(Dummy,-1,NCOVMAX);
                   12733:   free_ivector(Fixed,-1,NCOVMAX);
1.238     brouard  12734:   free_ivector(DummyV,1,NCOVMAX);
                   12735:   free_ivector(FixedV,1,NCOVMAX);
1.227     brouard  12736:   free_ivector(Typevar,-1,NCOVMAX);
                   12737:   free_ivector(Tvar,1,NCOVMAX);
1.234     brouard  12738:   free_ivector(TvarsQ,1,NCOVMAX);
                   12739:   free_ivector(TvarsQind,1,NCOVMAX);
                   12740:   free_ivector(TvarsD,1,NCOVMAX);
                   12741:   free_ivector(TvarsDind,1,NCOVMAX);
1.231     brouard  12742:   free_ivector(TvarFD,1,NCOVMAX);
                   12743:   free_ivector(TvarFDind,1,NCOVMAX);
1.232     brouard  12744:   free_ivector(TvarF,1,NCOVMAX);
                   12745:   free_ivector(TvarFind,1,NCOVMAX);
                   12746:   free_ivector(TvarV,1,NCOVMAX);
                   12747:   free_ivector(TvarVind,1,NCOVMAX);
                   12748:   free_ivector(TvarA,1,NCOVMAX);
                   12749:   free_ivector(TvarAind,1,NCOVMAX);
1.231     brouard  12750:   free_ivector(TvarFQ,1,NCOVMAX);
                   12751:   free_ivector(TvarFQind,1,NCOVMAX);
                   12752:   free_ivector(TvarVD,1,NCOVMAX);
                   12753:   free_ivector(TvarVDind,1,NCOVMAX);
                   12754:   free_ivector(TvarVQ,1,NCOVMAX);
                   12755:   free_ivector(TvarVQind,1,NCOVMAX);
1.230     brouard  12756:   free_ivector(Tvarsel,1,NCOVMAX);
                   12757:   free_vector(Tvalsel,1,NCOVMAX);
1.227     brouard  12758:   free_ivector(Tposprod,1,NCOVMAX);
                   12759:   free_ivector(Tprod,1,NCOVMAX);
                   12760:   free_ivector(Tvaraff,1,NCOVMAX);
                   12761:   free_ivector(invalidvarcomb,1,ncovcombmax);
                   12762:   free_ivector(Tage,1,NCOVMAX);
                   12763:   free_ivector(Tmodelind,1,NCOVMAX);
1.228     brouard  12764:   free_ivector(TmodelInvind,1,NCOVMAX);
                   12765:   free_ivector(TmodelInvQind,1,NCOVMAX);
1.227     brouard  12766:   
                   12767:   free_imatrix(nbcode,0,NCOVMAX,0,NCOVMAX);
                   12768:   /* free_imatrix(codtab,1,100,1,10); */
1.126     brouard  12769:   fflush(fichtm);
                   12770:   fflush(ficgp);
                   12771:   
1.227     brouard  12772:   
1.126     brouard  12773:   if((nberr >0) || (nbwarn>0)){
1.216     brouard  12774:     printf("End of Imach with %d errors and/or %d warnings. Please look at the log file for details.\n",nberr,nbwarn);
                   12775:     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  12776:   }else{
                   12777:     printf("End of Imach\n");
                   12778:     fprintf(ficlog,"End of Imach\n");
                   12779:   }
                   12780:   printf("See log file on %s\n",filelog);
                   12781:   /*  gettimeofday(&end_time, (struct timezone*)0);*/  /* after time */
1.157     brouard  12782:   /*(void) gettimeofday(&end_time,&tzp);*/
                   12783:   rend_time = time(NULL);  
                   12784:   end_time = *localtime(&rend_time);
                   12785:   /* tml = *localtime(&end_time.tm_sec); */
                   12786:   strcpy(strtend,asctime(&end_time));
1.126     brouard  12787:   printf("Local time at start %s\nLocal time at end   %s",strstart, strtend); 
                   12788:   fprintf(ficlog,"Local time at start %s\nLocal time at end   %s\n",strstart, strtend); 
1.157     brouard  12789:   printf("Total time used %s\n", asc_diff_time(rend_time -rstart_time,tmpout));
1.227     brouard  12790:   
1.157     brouard  12791:   printf("Total time was %.0lf Sec.\n", difftime(rend_time,rstart_time));
                   12792:   fprintf(ficlog,"Total time used %s\n", asc_diff_time(rend_time -rstart_time,tmpout));
                   12793:   fprintf(ficlog,"Total time was %.0lf Sec.\n", difftime(rend_time,rstart_time));
1.126     brouard  12794:   /*  printf("Total time was %d uSec.\n", total_usecs);*/
                   12795: /*   if(fileappend(fichtm,optionfilehtm)){ */
                   12796:   fprintf(fichtm,"<br>Local time at start %s<br>Local time at end   %s<br>\n</body></html>",strstart, strtend);
                   12797:   fclose(fichtm);
                   12798:   fprintf(fichtmcov,"<br>Local time at start %s<br>Local time at end   %s<br>\n</body></html>",strstart, strtend);
                   12799:   fclose(fichtmcov);
                   12800:   fclose(ficgp);
                   12801:   fclose(ficlog);
                   12802:   /*------ End -----------*/
1.227     brouard  12803:   
1.281     brouard  12804: 
                   12805: /* Executes gnuplot */
1.227     brouard  12806:   
                   12807:   printf("Before Current directory %s!\n",pathcd);
1.184     brouard  12808: #ifdef WIN32
1.227     brouard  12809:   if (_chdir(pathcd) != 0)
                   12810:     printf("Can't move to directory %s!\n",path);
                   12811:   if(_getcwd(pathcd,MAXLINE) > 0)
1.184     brouard  12812: #else
1.227     brouard  12813:     if(chdir(pathcd) != 0)
                   12814:       printf("Can't move to directory %s!\n", path);
                   12815:   if (getcwd(pathcd, MAXLINE) > 0)
1.184     brouard  12816: #endif 
1.126     brouard  12817:     printf("Current directory %s!\n",pathcd);
                   12818:   /*strcat(plotcmd,CHARSEPARATOR);*/
                   12819:   sprintf(plotcmd,"gnuplot");
1.157     brouard  12820: #ifdef _WIN32
1.126     brouard  12821:   sprintf(plotcmd,"\"%sgnuplot.exe\"",pathimach);
                   12822: #endif
                   12823:   if(!stat(plotcmd,&info)){
1.158     brouard  12824:     printf("Error or gnuplot program not found: '%s'\n",plotcmd);fflush(stdout);
1.126     brouard  12825:     if(!stat(getenv("GNUPLOTBIN"),&info)){
1.158     brouard  12826:       printf("Error or gnuplot program not found: '%s' Environment GNUPLOTBIN not set.\n",plotcmd);fflush(stdout);
1.126     brouard  12827:     }else
                   12828:       strcpy(pplotcmd,plotcmd);
1.157     brouard  12829: #ifdef __unix
1.126     brouard  12830:     strcpy(plotcmd,GNUPLOTPROGRAM);
                   12831:     if(!stat(plotcmd,&info)){
1.158     brouard  12832:       printf("Error gnuplot program not found: '%s'\n",plotcmd);fflush(stdout);
1.126     brouard  12833:     }else
                   12834:       strcpy(pplotcmd,plotcmd);
                   12835: #endif
                   12836:   }else
                   12837:     strcpy(pplotcmd,plotcmd);
                   12838:   
                   12839:   sprintf(plotcmd,"%s %s",pplotcmd, optionfilegnuplot);
1.158     brouard  12840:   printf("Starting graphs with: '%s'\n",plotcmd);fflush(stdout);
1.292     brouard  12841:   strcpy(pplotcmd,plotcmd);
1.227     brouard  12842:   
1.126     brouard  12843:   if((outcmd=system(plotcmd)) != 0){
1.292     brouard  12844:     printf("Error in gnuplot, command might not be in your path: '%s', err=%d\n", plotcmd, outcmd);
1.154     brouard  12845:     printf("\n Trying if gnuplot resides on the same directory that IMaCh\n");
1.152     brouard  12846:     sprintf(plotcmd,"%sgnuplot %s", pathimach, optionfilegnuplot);
1.292     brouard  12847:     if((outcmd=system(plotcmd)) != 0){
1.153     brouard  12848:       printf("\n Still a problem with gnuplot command %s, err=%d\n", plotcmd, outcmd);
1.292     brouard  12849:       strcpy(plotcmd,pplotcmd);
                   12850:     }
1.126     brouard  12851:   }
1.158     brouard  12852:   printf(" Successful, please wait...");
1.126     brouard  12853:   while (z[0] != 'q') {
                   12854:     /* chdir(path); */
1.154     brouard  12855:     printf("\nType e to edit results with your browser, g to graph again and q for exit: ");
1.126     brouard  12856:     scanf("%s",z);
                   12857: /*     if (z[0] == 'c') system("./imach"); */
                   12858:     if (z[0] == 'e') {
1.158     brouard  12859: #ifdef __APPLE__
1.152     brouard  12860:       sprintf(pplotcmd, "open %s", optionfilehtm);
1.157     brouard  12861: #elif __linux
                   12862:       sprintf(pplotcmd, "xdg-open %s", optionfilehtm);
1.153     brouard  12863: #else
1.152     brouard  12864:       sprintf(pplotcmd, "%s", optionfilehtm);
1.153     brouard  12865: #endif
                   12866:       printf("Starting browser with: %s",pplotcmd);fflush(stdout);
                   12867:       system(pplotcmd);
1.126     brouard  12868:     }
                   12869:     else if (z[0] == 'g') system(plotcmd);
                   12870:     else if (z[0] == 'q') exit(0);
                   12871:   }
1.227     brouard  12872: end:
1.126     brouard  12873:   while (z[0] != 'q') {
1.195     brouard  12874:     printf("\nType  q for exiting: "); fflush(stdout);
1.126     brouard  12875:     scanf("%s",z);
                   12876:   }
1.283     brouard  12877:   printf("End\n");
1.282     brouard  12878:   exit(0);
1.126     brouard  12879: }

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