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

1.293   ! brouard     1: /* $Id: imach.c,v 1.292 2019/05/09 14:17:20 brouard Exp $
1.126     brouard     2:   $State: Exp $
1.163     brouard     3:   $Log: imach.c,v $
1.293   ! brouard     4:   Revision 1.292  2019/05/09 14:17:20  brouard
        !             5:   Summary: Some updates
        !             6: 
1.292     brouard     7:   Revision 1.291  2019/05/09 13:44:18  brouard
                      8:   Summary: Before ncovmax
                      9: 
1.291     brouard    10:   Revision 1.290  2019/05/09 13:39:37  brouard
                     11:   Summary: 0.99r18 unlimited number of individuals
                     12: 
                     13:   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.
                     14: 
1.290     brouard    15:   Revision 1.289  2018/12/13 09:16:26  brouard
                     16:   Summary: Bug for young ages (<-30) will be in r17
                     17: 
1.289     brouard    18:   Revision 1.288  2018/05/02 20:58:27  brouard
                     19:   Summary: Some bugs fixed
                     20: 
1.288     brouard    21:   Revision 1.287  2018/05/01 17:57:25  brouard
                     22:   Summary: Bug fixed by providing frequencies only for non missing covariates
                     23: 
1.287     brouard    24:   Revision 1.286  2018/04/27 14:27:04  brouard
                     25:   Summary: some minor bugs
                     26: 
1.286     brouard    27:   Revision 1.285  2018/04/21 21:02:16  brouard
                     28:   Summary: Some bugs fixed, valgrind tested
                     29: 
1.285     brouard    30:   Revision 1.284  2018/04/20 05:22:13  brouard
                     31:   Summary: Computing mean and stdeviation of fixed quantitative variables
                     32: 
1.284     brouard    33:   Revision 1.283  2018/04/19 14:49:16  brouard
                     34:   Summary: Some minor bugs fixed
                     35: 
1.283     brouard    36:   Revision 1.282  2018/02/27 22:50:02  brouard
                     37:   *** empty log message ***
                     38: 
1.282     brouard    39:   Revision 1.281  2018/02/27 19:25:23  brouard
                     40:   Summary: Adding second argument for quitting
                     41: 
1.281     brouard    42:   Revision 1.280  2018/02/21 07:58:13  brouard
                     43:   Summary: 0.99r15
                     44: 
                     45:   New Makefile with recent VirtualBox 5.26. Bug in sqrt negatve in imach.c
                     46: 
1.280     brouard    47:   Revision 1.279  2017/07/20 13:35:01  brouard
                     48:   Summary: temporary working
                     49: 
1.279     brouard    50:   Revision 1.278  2017/07/19 14:09:02  brouard
                     51:   Summary: Bug for mobil_average=0 and prevforecast fixed(?)
                     52: 
1.278     brouard    53:   Revision 1.277  2017/07/17 08:53:49  brouard
                     54:   Summary: BOM files can be read now
                     55: 
1.277     brouard    56:   Revision 1.276  2017/06/30 15:48:31  brouard
                     57:   Summary: Graphs improvements
                     58: 
1.276     brouard    59:   Revision 1.275  2017/06/30 13:39:33  brouard
                     60:   Summary: Saito's color
                     61: 
1.275     brouard    62:   Revision 1.274  2017/06/29 09:47:08  brouard
                     63:   Summary: Version 0.99r14
                     64: 
1.274     brouard    65:   Revision 1.273  2017/06/27 11:06:02  brouard
                     66:   Summary: More documentation on projections
                     67: 
1.273     brouard    68:   Revision 1.272  2017/06/27 10:22:40  brouard
                     69:   Summary: Color of backprojection changed from 6 to 5(yellow)
                     70: 
1.272     brouard    71:   Revision 1.271  2017/06/27 10:17:50  brouard
                     72:   Summary: Some bug with rint
                     73: 
1.271     brouard    74:   Revision 1.270  2017/05/24 05:45:29  brouard
                     75:   *** empty log message ***
                     76: 
1.270     brouard    77:   Revision 1.269  2017/05/23 08:39:25  brouard
                     78:   Summary: Code into subroutine, cleanings
                     79: 
1.269     brouard    80:   Revision 1.268  2017/05/18 20:09:32  brouard
                     81:   Summary: backprojection and confidence intervals of backprevalence
                     82: 
1.268     brouard    83:   Revision 1.267  2017/05/13 10:25:05  brouard
                     84:   Summary: temporary save for backprojection
                     85: 
1.267     brouard    86:   Revision 1.266  2017/05/13 07:26:12  brouard
                     87:   Summary: Version 0.99r13 (improvements and bugs fixed)
                     88: 
1.266     brouard    89:   Revision 1.265  2017/04/26 16:22:11  brouard
                     90:   Summary: imach 0.99r13 Some bugs fixed
                     91: 
1.265     brouard    92:   Revision 1.264  2017/04/26 06:01:29  brouard
                     93:   Summary: Labels in graphs
                     94: 
1.264     brouard    95:   Revision 1.263  2017/04/24 15:23:15  brouard
                     96:   Summary: to save
                     97: 
1.263     brouard    98:   Revision 1.262  2017/04/18 16:48:12  brouard
                     99:   *** empty log message ***
                    100: 
1.262     brouard   101:   Revision 1.261  2017/04/05 10:14:09  brouard
                    102:   Summary: Bug in E_ as well as in T_ fixed nres-1 vs k1-1
                    103: 
1.261     brouard   104:   Revision 1.260  2017/04/04 17:46:59  brouard
                    105:   Summary: Gnuplot indexations fixed (humm)
                    106: 
1.260     brouard   107:   Revision 1.259  2017/04/04 13:01:16  brouard
                    108:   Summary: Some errors to warnings only if date of death is unknown but status is death we could set to pi3
                    109: 
1.259     brouard   110:   Revision 1.258  2017/04/03 10:17:47  brouard
                    111:   Summary: Version 0.99r12
                    112: 
                    113:   Some cleanings, conformed with updated documentation.
                    114: 
1.258     brouard   115:   Revision 1.257  2017/03/29 16:53:30  brouard
                    116:   Summary: Temp
                    117: 
1.257     brouard   118:   Revision 1.256  2017/03/27 05:50:23  brouard
                    119:   Summary: Temporary
                    120: 
1.256     brouard   121:   Revision 1.255  2017/03/08 16:02:28  brouard
                    122:   Summary: IMaCh version 0.99r10 bugs in gnuplot fixed
                    123: 
1.255     brouard   124:   Revision 1.254  2017/03/08 07:13:00  brouard
                    125:   Summary: Fixing data parameter line
                    126: 
1.254     brouard   127:   Revision 1.253  2016/12/15 11:59:41  brouard
                    128:   Summary: 0.99 in progress
                    129: 
1.253     brouard   130:   Revision 1.252  2016/09/15 21:15:37  brouard
                    131:   *** empty log message ***
                    132: 
1.252     brouard   133:   Revision 1.251  2016/09/15 15:01:13  brouard
                    134:   Summary: not working
                    135: 
1.251     brouard   136:   Revision 1.250  2016/09/08 16:07:27  brouard
                    137:   Summary: continue
                    138: 
1.250     brouard   139:   Revision 1.249  2016/09/07 17:14:18  brouard
                    140:   Summary: Starting values from frequencies
                    141: 
1.249     brouard   142:   Revision 1.248  2016/09/07 14:10:18  brouard
                    143:   *** empty log message ***
                    144: 
1.248     brouard   145:   Revision 1.247  2016/09/02 11:11:21  brouard
                    146:   *** empty log message ***
                    147: 
1.247     brouard   148:   Revision 1.246  2016/09/02 08:49:22  brouard
                    149:   *** empty log message ***
                    150: 
1.246     brouard   151:   Revision 1.245  2016/09/02 07:25:01  brouard
                    152:   *** empty log message ***
                    153: 
1.245     brouard   154:   Revision 1.244  2016/09/02 07:17:34  brouard
                    155:   *** empty log message ***
                    156: 
1.244     brouard   157:   Revision 1.243  2016/09/02 06:45:35  brouard
                    158:   *** empty log message ***
                    159: 
1.243     brouard   160:   Revision 1.242  2016/08/30 15:01:20  brouard
                    161:   Summary: Fixing a lots
                    162: 
1.242     brouard   163:   Revision 1.241  2016/08/29 17:17:25  brouard
                    164:   Summary: gnuplot problem in Back projection to fix
                    165: 
1.241     brouard   166:   Revision 1.240  2016/08/29 07:53:18  brouard
                    167:   Summary: Better
                    168: 
1.240     brouard   169:   Revision 1.239  2016/08/26 15:51:03  brouard
                    170:   Summary: Improvement in Powell output in order to copy and paste
                    171: 
                    172:   Author:
                    173: 
1.239     brouard   174:   Revision 1.238  2016/08/26 14:23:35  brouard
                    175:   Summary: Starting tests of 0.99
                    176: 
1.238     brouard   177:   Revision 1.237  2016/08/26 09:20:19  brouard
                    178:   Summary: to valgrind
                    179: 
1.237     brouard   180:   Revision 1.236  2016/08/25 10:50:18  brouard
                    181:   *** empty log message ***
                    182: 
1.236     brouard   183:   Revision 1.235  2016/08/25 06:59:23  brouard
                    184:   *** empty log message ***
                    185: 
1.235     brouard   186:   Revision 1.234  2016/08/23 16:51:20  brouard
                    187:   *** empty log message ***
                    188: 
1.234     brouard   189:   Revision 1.233  2016/08/23 07:40:50  brouard
                    190:   Summary: not working
                    191: 
1.233     brouard   192:   Revision 1.232  2016/08/22 14:20:21  brouard
                    193:   Summary: not working
                    194: 
1.232     brouard   195:   Revision 1.231  2016/08/22 07:17:15  brouard
                    196:   Summary: not working
                    197: 
1.231     brouard   198:   Revision 1.230  2016/08/22 06:55:53  brouard
                    199:   Summary: Not working
                    200: 
1.230     brouard   201:   Revision 1.229  2016/07/23 09:45:53  brouard
                    202:   Summary: Completing for func too
                    203: 
1.229     brouard   204:   Revision 1.228  2016/07/22 17:45:30  brouard
                    205:   Summary: Fixing some arrays, still debugging
                    206: 
1.227     brouard   207:   Revision 1.226  2016/07/12 18:42:34  brouard
                    208:   Summary: temp
                    209: 
1.226     brouard   210:   Revision 1.225  2016/07/12 08:40:03  brouard
                    211:   Summary: saving but not running
                    212: 
1.225     brouard   213:   Revision 1.224  2016/07/01 13:16:01  brouard
                    214:   Summary: Fixes
                    215: 
1.224     brouard   216:   Revision 1.223  2016/02/19 09:23:35  brouard
                    217:   Summary: temporary
                    218: 
1.223     brouard   219:   Revision 1.222  2016/02/17 08:14:50  brouard
                    220:   Summary: Probably last 0.98 stable version 0.98r6
                    221: 
1.222     brouard   222:   Revision 1.221  2016/02/15 23:35:36  brouard
                    223:   Summary: minor bug
                    224: 
1.220     brouard   225:   Revision 1.219  2016/02/15 00:48:12  brouard
                    226:   *** empty log message ***
                    227: 
1.219     brouard   228:   Revision 1.218  2016/02/12 11:29:23  brouard
                    229:   Summary: 0.99 Back projections
                    230: 
1.218     brouard   231:   Revision 1.217  2015/12/23 17:18:31  brouard
                    232:   Summary: Experimental backcast
                    233: 
1.217     brouard   234:   Revision 1.216  2015/12/18 17:32:11  brouard
                    235:   Summary: 0.98r4 Warning and status=-2
                    236: 
                    237:   Version 0.98r4 is now:
                    238:    - displaying an error when status is -1, date of interview unknown and date of death known;
                    239:    - permitting a status -2 when the vital status is unknown at a known date of right truncation.
                    240:   Older changes concerning s=-2, dating from 2005 have been supersed.
                    241: 
1.216     brouard   242:   Revision 1.215  2015/12/16 08:52:24  brouard
                    243:   Summary: 0.98r4 working
                    244: 
1.215     brouard   245:   Revision 1.214  2015/12/16 06:57:54  brouard
                    246:   Summary: temporary not working
                    247: 
1.214     brouard   248:   Revision 1.213  2015/12/11 18:22:17  brouard
                    249:   Summary: 0.98r4
                    250: 
1.213     brouard   251:   Revision 1.212  2015/11/21 12:47:24  brouard
                    252:   Summary: minor typo
                    253: 
1.212     brouard   254:   Revision 1.211  2015/11/21 12:41:11  brouard
                    255:   Summary: 0.98r3 with some graph of projected cross-sectional
                    256: 
                    257:   Author: Nicolas Brouard
                    258: 
1.211     brouard   259:   Revision 1.210  2015/11/18 17:41:20  brouard
1.252     brouard   260:   Summary: Start working on projected prevalences  Revision 1.209  2015/11/17 22:12:03  brouard
1.210     brouard   261:   Summary: Adding ftolpl parameter
                    262:   Author: N Brouard
                    263: 
                    264:   We had difficulties to get smoothed confidence intervals. It was due
                    265:   to the period prevalence which wasn't computed accurately. The inner
                    266:   parameter ftolpl is now an outer parameter of the .imach parameter
                    267:   file after estepm. If ftolpl is small 1.e-4 and estepm too,
                    268:   computation are long.
                    269: 
1.209     brouard   270:   Revision 1.208  2015/11/17 14:31:57  brouard
                    271:   Summary: temporary
                    272: 
1.208     brouard   273:   Revision 1.207  2015/10/27 17:36:57  brouard
                    274:   *** empty log message ***
                    275: 
1.207     brouard   276:   Revision 1.206  2015/10/24 07:14:11  brouard
                    277:   *** empty log message ***
                    278: 
1.206     brouard   279:   Revision 1.205  2015/10/23 15:50:53  brouard
                    280:   Summary: 0.98r3 some clarification for graphs on likelihood contributions
                    281: 
1.205     brouard   282:   Revision 1.204  2015/10/01 16:20:26  brouard
                    283:   Summary: Some new graphs of contribution to likelihood
                    284: 
1.204     brouard   285:   Revision 1.203  2015/09/30 17:45:14  brouard
                    286:   Summary: looking at better estimation of the hessian
                    287: 
                    288:   Also a better criteria for convergence to the period prevalence And
                    289:   therefore adding the number of years needed to converge. (The
                    290:   prevalence in any alive state shold sum to one
                    291: 
1.203     brouard   292:   Revision 1.202  2015/09/22 19:45:16  brouard
                    293:   Summary: Adding some overall graph on contribution to likelihood. Might change
                    294: 
1.202     brouard   295:   Revision 1.201  2015/09/15 17:34:58  brouard
                    296:   Summary: 0.98r0
                    297: 
                    298:   - Some new graphs like suvival functions
                    299:   - Some bugs fixed like model=1+age+V2.
                    300: 
1.201     brouard   301:   Revision 1.200  2015/09/09 16:53:55  brouard
                    302:   Summary: Big bug thanks to Flavia
                    303: 
                    304:   Even model=1+age+V2. did not work anymore
                    305: 
1.200     brouard   306:   Revision 1.199  2015/09/07 14:09:23  brouard
                    307:   Summary: 0.98q6 changing default small png format for graph to vectorized svg.
                    308: 
1.199     brouard   309:   Revision 1.198  2015/09/03 07:14:39  brouard
                    310:   Summary: 0.98q5 Flavia
                    311: 
1.198     brouard   312:   Revision 1.197  2015/09/01 18:24:39  brouard
                    313:   *** empty log message ***
                    314: 
1.197     brouard   315:   Revision 1.196  2015/08/18 23:17:52  brouard
                    316:   Summary: 0.98q5
                    317: 
1.196     brouard   318:   Revision 1.195  2015/08/18 16:28:39  brouard
                    319:   Summary: Adding a hack for testing purpose
                    320: 
                    321:   After reading the title, ftol and model lines, if the comment line has
                    322:   a q, starting with #q, the answer at the end of the run is quit. It
                    323:   permits to run test files in batch with ctest. The former workaround was
                    324:   $ echo q | imach foo.imach
                    325: 
1.195     brouard   326:   Revision 1.194  2015/08/18 13:32:00  brouard
                    327:   Summary:  Adding error when the covariance matrix doesn't contain the exact number of lines required by the model line.
                    328: 
1.194     brouard   329:   Revision 1.193  2015/08/04 07:17:42  brouard
                    330:   Summary: 0.98q4
                    331: 
1.193     brouard   332:   Revision 1.192  2015/07/16 16:49:02  brouard
                    333:   Summary: Fixing some outputs
                    334: 
1.192     brouard   335:   Revision 1.191  2015/07/14 10:00:33  brouard
                    336:   Summary: Some fixes
                    337: 
1.191     brouard   338:   Revision 1.190  2015/05/05 08:51:13  brouard
                    339:   Summary: Adding digits in output parameters (7 digits instead of 6)
                    340: 
                    341:   Fix 1+age+.
                    342: 
1.190     brouard   343:   Revision 1.189  2015/04/30 14:45:16  brouard
                    344:   Summary: 0.98q2
                    345: 
1.189     brouard   346:   Revision 1.188  2015/04/30 08:27:53  brouard
                    347:   *** empty log message ***
                    348: 
1.188     brouard   349:   Revision 1.187  2015/04/29 09:11:15  brouard
                    350:   *** empty log message ***
                    351: 
1.187     brouard   352:   Revision 1.186  2015/04/23 12:01:52  brouard
                    353:   Summary: V1*age is working now, version 0.98q1
                    354: 
                    355:   Some codes had been disabled in order to simplify and Vn*age was
                    356:   working in the optimization phase, ie, giving correct MLE parameters,
                    357:   but, as usual, outputs were not correct and program core dumped.
                    358: 
1.186     brouard   359:   Revision 1.185  2015/03/11 13:26:42  brouard
                    360:   Summary: Inclusion of compile and links command line for Intel Compiler
                    361: 
1.185     brouard   362:   Revision 1.184  2015/03/11 11:52:39  brouard
                    363:   Summary: Back from Windows 8. Intel Compiler
                    364: 
1.184     brouard   365:   Revision 1.183  2015/03/10 20:34:32  brouard
                    366:   Summary: 0.98q0, trying with directest, mnbrak fixed
                    367: 
                    368:   We use directest instead of original Powell test; probably no
                    369:   incidence on the results, but better justifications;
                    370:   We fixed Numerical Recipes mnbrak routine which was wrong and gave
                    371:   wrong results.
                    372: 
1.183     brouard   373:   Revision 1.182  2015/02/12 08:19:57  brouard
                    374:   Summary: Trying to keep directest which seems simpler and more general
                    375:   Author: Nicolas Brouard
                    376: 
1.182     brouard   377:   Revision 1.181  2015/02/11 23:22:24  brouard
                    378:   Summary: Comments on Powell added
                    379: 
                    380:   Author:
                    381: 
1.181     brouard   382:   Revision 1.180  2015/02/11 17:33:45  brouard
                    383:   Summary: Finishing move from main to function (hpijx and prevalence_limit)
                    384: 
1.180     brouard   385:   Revision 1.179  2015/01/04 09:57:06  brouard
                    386:   Summary: back to OS/X
                    387: 
1.179     brouard   388:   Revision 1.178  2015/01/04 09:35:48  brouard
                    389:   *** empty log message ***
                    390: 
1.178     brouard   391:   Revision 1.177  2015/01/03 18:40:56  brouard
                    392:   Summary: Still testing ilc32 on OSX
                    393: 
1.177     brouard   394:   Revision 1.176  2015/01/03 16:45:04  brouard
                    395:   *** empty log message ***
                    396: 
1.176     brouard   397:   Revision 1.175  2015/01/03 16:33:42  brouard
                    398:   *** empty log message ***
                    399: 
1.175     brouard   400:   Revision 1.174  2015/01/03 16:15:49  brouard
                    401:   Summary: Still in cross-compilation
                    402: 
1.174     brouard   403:   Revision 1.173  2015/01/03 12:06:26  brouard
                    404:   Summary: trying to detect cross-compilation
                    405: 
1.173     brouard   406:   Revision 1.172  2014/12/27 12:07:47  brouard
                    407:   Summary: Back from Visual Studio and Intel, options for compiling for Windows XP
                    408: 
1.172     brouard   409:   Revision 1.171  2014/12/23 13:26:59  brouard
                    410:   Summary: Back from Visual C
                    411: 
                    412:   Still problem with utsname.h on Windows
                    413: 
1.171     brouard   414:   Revision 1.170  2014/12/23 11:17:12  brouard
                    415:   Summary: Cleaning some \%% back to %%
                    416: 
                    417:   The escape was mandatory for a specific compiler (which one?), but too many warnings.
                    418: 
1.170     brouard   419:   Revision 1.169  2014/12/22 23:08:31  brouard
                    420:   Summary: 0.98p
                    421: 
                    422:   Outputs some informations on compiler used, OS etc. Testing on different platforms.
                    423: 
1.169     brouard   424:   Revision 1.168  2014/12/22 15:17:42  brouard
1.170     brouard   425:   Summary: update
1.169     brouard   426: 
1.168     brouard   427:   Revision 1.167  2014/12/22 13:50:56  brouard
                    428:   Summary: Testing uname and compiler version and if compiled 32 or 64
                    429: 
                    430:   Testing on Linux 64
                    431: 
1.167     brouard   432:   Revision 1.166  2014/12/22 11:40:47  brouard
                    433:   *** empty log message ***
                    434: 
1.166     brouard   435:   Revision 1.165  2014/12/16 11:20:36  brouard
                    436:   Summary: After compiling on Visual C
                    437: 
                    438:   * imach.c (Module): Merging 1.61 to 1.162
                    439: 
1.165     brouard   440:   Revision 1.164  2014/12/16 10:52:11  brouard
                    441:   Summary: Merging with Visual C after suppressing some warnings for unused variables. Also fixing Saito's bug 0.98Xn
                    442: 
                    443:   * imach.c (Module): Merging 1.61 to 1.162
                    444: 
1.164     brouard   445:   Revision 1.163  2014/12/16 10:30:11  brouard
                    446:   * imach.c (Module): Merging 1.61 to 1.162
                    447: 
1.163     brouard   448:   Revision 1.162  2014/09/25 11:43:39  brouard
                    449:   Summary: temporary backup 0.99!
                    450: 
1.162     brouard   451:   Revision 1.1  2014/09/16 11:06:58  brouard
                    452:   Summary: With some code (wrong) for nlopt
                    453: 
                    454:   Author:
                    455: 
                    456:   Revision 1.161  2014/09/15 20:41:41  brouard
                    457:   Summary: Problem with macro SQR on Intel compiler
                    458: 
1.161     brouard   459:   Revision 1.160  2014/09/02 09:24:05  brouard
                    460:   *** empty log message ***
                    461: 
1.160     brouard   462:   Revision 1.159  2014/09/01 10:34:10  brouard
                    463:   Summary: WIN32
                    464:   Author: Brouard
                    465: 
1.159     brouard   466:   Revision 1.158  2014/08/27 17:11:51  brouard
                    467:   *** empty log message ***
                    468: 
1.158     brouard   469:   Revision 1.157  2014/08/27 16:26:55  brouard
                    470:   Summary: Preparing windows Visual studio version
                    471:   Author: Brouard
                    472: 
                    473:   In order to compile on Visual studio, time.h is now correct and time_t
                    474:   and tm struct should be used. difftime should be used but sometimes I
                    475:   just make the differences in raw time format (time(&now).
                    476:   Trying to suppress #ifdef LINUX
                    477:   Add xdg-open for __linux in order to open default browser.
                    478: 
1.157     brouard   479:   Revision 1.156  2014/08/25 20:10:10  brouard
                    480:   *** empty log message ***
                    481: 
1.156     brouard   482:   Revision 1.155  2014/08/25 18:32:34  brouard
                    483:   Summary: New compile, minor changes
                    484:   Author: Brouard
                    485: 
1.155     brouard   486:   Revision 1.154  2014/06/20 17:32:08  brouard
                    487:   Summary: Outputs now all graphs of convergence to period prevalence
                    488: 
1.154     brouard   489:   Revision 1.153  2014/06/20 16:45:46  brouard
                    490:   Summary: If 3 live state, convergence to period prevalence on same graph
                    491:   Author: Brouard
                    492: 
1.153     brouard   493:   Revision 1.152  2014/06/18 17:54:09  brouard
                    494:   Summary: open browser, use gnuplot on same dir than imach if not found in the path
                    495: 
1.152     brouard   496:   Revision 1.151  2014/06/18 16:43:30  brouard
                    497:   *** empty log message ***
                    498: 
1.151     brouard   499:   Revision 1.150  2014/06/18 16:42:35  brouard
                    500:   Summary: If gnuplot is not in the path try on same directory than imach binary (OSX)
                    501:   Author: brouard
                    502: 
1.150     brouard   503:   Revision 1.149  2014/06/18 15:51:14  brouard
                    504:   Summary: Some fixes in parameter files errors
                    505:   Author: Nicolas Brouard
                    506: 
1.149     brouard   507:   Revision 1.148  2014/06/17 17:38:48  brouard
                    508:   Summary: Nothing new
                    509:   Author: Brouard
                    510: 
                    511:   Just a new packaging for OS/X version 0.98nS
                    512: 
1.148     brouard   513:   Revision 1.147  2014/06/16 10:33:11  brouard
                    514:   *** empty log message ***
                    515: 
1.147     brouard   516:   Revision 1.146  2014/06/16 10:20:28  brouard
                    517:   Summary: Merge
                    518:   Author: Brouard
                    519: 
                    520:   Merge, before building revised version.
                    521: 
1.146     brouard   522:   Revision 1.145  2014/06/10 21:23:15  brouard
                    523:   Summary: Debugging with valgrind
                    524:   Author: Nicolas Brouard
                    525: 
                    526:   Lot of changes in order to output the results with some covariates
                    527:   After the Edimburgh REVES conference 2014, it seems mandatory to
                    528:   improve the code.
                    529:   No more memory valgrind error but a lot has to be done in order to
                    530:   continue the work of splitting the code into subroutines.
                    531:   Also, decodemodel has been improved. Tricode is still not
                    532:   optimal. nbcode should be improved. Documentation has been added in
                    533:   the source code.
                    534: 
1.144     brouard   535:   Revision 1.143  2014/01/26 09:45:38  brouard
                    536:   Summary: Version 0.98nR (to be improved, but gives same optimization results as 0.98k. Nice, promising
                    537: 
                    538:   * imach.c (Module): Trying to merge old staffs together while being at Tokyo. Not tested...
                    539:   (Module): Version 0.98nR Running ok, but output format still only works for three covariates.
                    540: 
1.143     brouard   541:   Revision 1.142  2014/01/26 03:57:36  brouard
                    542:   Summary: gnuplot changed plot w l 1 has to be changed to plot w l lt 2
                    543: 
                    544:   * imach.c (Module): Trying to merge old staffs together while being at Tokyo. Not tested...
                    545: 
1.142     brouard   546:   Revision 1.141  2014/01/26 02:42:01  brouard
                    547:   * imach.c (Module): Trying to merge old staffs together while being at Tokyo. Not tested...
                    548: 
1.141     brouard   549:   Revision 1.140  2011/09/02 10:37:54  brouard
                    550:   Summary: times.h is ok with mingw32 now.
                    551: 
1.140     brouard   552:   Revision 1.139  2010/06/14 07:50:17  brouard
                    553:   After the theft of my laptop, I probably lost some lines of codes which were not uploaded to the CVS tree.
                    554:   I remember having already fixed agemin agemax which are pointers now but not cvs saved.
                    555: 
1.139     brouard   556:   Revision 1.138  2010/04/30 18:19:40  brouard
                    557:   *** empty log message ***
                    558: 
1.138     brouard   559:   Revision 1.137  2010/04/29 18:11:38  brouard
                    560:   (Module): Checking covariates for more complex models
                    561:   than V1+V2. A lot of change to be done. Unstable.
                    562: 
1.137     brouard   563:   Revision 1.136  2010/04/26 20:30:53  brouard
                    564:   (Module): merging some libgsl code. Fixing computation
                    565:   of likelione (using inter/intrapolation if mle = 0) in order to
                    566:   get same likelihood as if mle=1.
                    567:   Some cleaning of code and comments added.
                    568: 
1.136     brouard   569:   Revision 1.135  2009/10/29 15:33:14  brouard
                    570:   (Module): Now imach stops if date of birth, at least year of birth, is not given. Some cleaning of the code.
                    571: 
1.135     brouard   572:   Revision 1.134  2009/10/29 13:18:53  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.134     brouard   575:   Revision 1.133  2009/07/06 10:21:25  brouard
                    576:   just nforces
                    577: 
1.133     brouard   578:   Revision 1.132  2009/07/06 08:22:05  brouard
                    579:   Many tings
                    580: 
1.132     brouard   581:   Revision 1.131  2009/06/20 16:22:47  brouard
                    582:   Some dimensions resccaled
                    583: 
1.131     brouard   584:   Revision 1.130  2009/05/26 06:44:34  brouard
                    585:   (Module): Max Covariate is now set to 20 instead of 8. A
                    586:   lot of cleaning with variables initialized to 0. Trying to make
                    587:   V2+V3*age+V1+V4 strb=V3*age+V1+V4 working better.
                    588: 
1.130     brouard   589:   Revision 1.129  2007/08/31 13:49:27  lievre
                    590:   Modification of the way of exiting when the covariate is not binary in order to see on the window the error message before exiting
                    591: 
1.129     lievre    592:   Revision 1.128  2006/06/30 13:02:05  brouard
                    593:   (Module): Clarifications on computing e.j
                    594: 
1.128     brouard   595:   Revision 1.127  2006/04/28 18:11:50  brouard
                    596:   (Module): Yes the sum of survivors was wrong since
                    597:   imach-114 because nhstepm was no more computed in the age
                    598:   loop. Now we define nhstepma in the age loop.
                    599:   (Module): In order to speed up (in case of numerous covariates) we
                    600:   compute health expectancies (without variances) in a first step
                    601:   and then all the health expectancies with variances or standard
                    602:   deviation (needs data from the Hessian matrices) which slows the
                    603:   computation.
                    604:   In the future we should be able to stop the program is only health
                    605:   expectancies and graph are needed without standard deviations.
                    606: 
1.127     brouard   607:   Revision 1.126  2006/04/28 17:23:28  brouard
                    608:   (Module): Yes the sum of survivors was wrong since
                    609:   imach-114 because nhstepm was no more computed in the age
                    610:   loop. Now we define nhstepma in the age loop.
                    611:   Version 0.98h
                    612: 
1.126     brouard   613:   Revision 1.125  2006/04/04 15:20:31  lievre
                    614:   Errors in calculation of health expectancies. Age was not initialized.
                    615:   Forecasting file added.
                    616: 
                    617:   Revision 1.124  2006/03/22 17:13:53  lievre
                    618:   Parameters are printed with %lf instead of %f (more numbers after the comma).
                    619:   The log-likelihood is printed in the log file
                    620: 
                    621:   Revision 1.123  2006/03/20 10:52:43  brouard
                    622:   * imach.c (Module): <title> changed, corresponds to .htm file
                    623:   name. <head> headers where missing.
                    624: 
                    625:   * imach.c (Module): Weights can have a decimal point as for
                    626:   English (a comma might work with a correct LC_NUMERIC environment,
                    627:   otherwise the weight is truncated).
                    628:   Modification of warning when the covariates values are not 0 or
                    629:   1.
                    630:   Version 0.98g
                    631: 
                    632:   Revision 1.122  2006/03/20 09:45:41  brouard
                    633:   (Module): Weights can have a decimal point as for
                    634:   English (a comma might work with a correct LC_NUMERIC environment,
                    635:   otherwise the weight is truncated).
                    636:   Modification of warning when the covariates values are not 0 or
                    637:   1.
                    638:   Version 0.98g
                    639: 
                    640:   Revision 1.121  2006/03/16 17:45:01  lievre
                    641:   * imach.c (Module): Comments concerning covariates added
                    642: 
                    643:   * imach.c (Module): refinements in the computation of lli if
                    644:   status=-2 in order to have more reliable computation if stepm is
                    645:   not 1 month. Version 0.98f
                    646: 
                    647:   Revision 1.120  2006/03/16 15:10:38  lievre
                    648:   (Module): refinements in the computation of lli if
                    649:   status=-2 in order to have more reliable computation if stepm is
                    650:   not 1 month. Version 0.98f
                    651: 
                    652:   Revision 1.119  2006/03/15 17:42:26  brouard
                    653:   (Module): Bug if status = -2, the loglikelihood was
                    654:   computed as likelihood omitting the logarithm. Version O.98e
                    655: 
                    656:   Revision 1.118  2006/03/14 18:20:07  brouard
                    657:   (Module): varevsij Comments added explaining the second
                    658:   table of variances if popbased=1 .
                    659:   (Module): Covariances of eij, ekl added, graphs fixed, new html link.
                    660:   (Module): Function pstamp added
                    661:   (Module): Version 0.98d
                    662: 
                    663:   Revision 1.117  2006/03/14 17:16:22  brouard
                    664:   (Module): varevsij Comments added explaining the second
                    665:   table of variances if popbased=1 .
                    666:   (Module): Covariances of eij, ekl added, graphs fixed, new html link.
                    667:   (Module): Function pstamp added
                    668:   (Module): Version 0.98d
                    669: 
                    670:   Revision 1.116  2006/03/06 10:29:27  brouard
                    671:   (Module): Variance-covariance wrong links and
                    672:   varian-covariance of ej. is needed (Saito).
                    673: 
                    674:   Revision 1.115  2006/02/27 12:17:45  brouard
                    675:   (Module): One freematrix added in mlikeli! 0.98c
                    676: 
                    677:   Revision 1.114  2006/02/26 12:57:58  brouard
                    678:   (Module): Some improvements in processing parameter
                    679:   filename with strsep.
                    680: 
                    681:   Revision 1.113  2006/02/24 14:20:24  brouard
                    682:   (Module): Memory leaks checks with valgrind and:
                    683:   datafile was not closed, some imatrix were not freed and on matrix
                    684:   allocation too.
                    685: 
                    686:   Revision 1.112  2006/01/30 09:55:26  brouard
                    687:   (Module): Back to gnuplot.exe instead of wgnuplot.exe
                    688: 
                    689:   Revision 1.111  2006/01/25 20:38:18  brouard
                    690:   (Module): Lots of cleaning and bugs added (Gompertz)
                    691:   (Module): Comments can be added in data file. Missing date values
                    692:   can be a simple dot '.'.
                    693: 
                    694:   Revision 1.110  2006/01/25 00:51:50  brouard
                    695:   (Module): Lots of cleaning and bugs added (Gompertz)
                    696: 
                    697:   Revision 1.109  2006/01/24 19:37:15  brouard
                    698:   (Module): Comments (lines starting with a #) are allowed in data.
                    699: 
                    700:   Revision 1.108  2006/01/19 18:05:42  lievre
                    701:   Gnuplot problem appeared...
                    702:   To be fixed
                    703: 
                    704:   Revision 1.107  2006/01/19 16:20:37  brouard
                    705:   Test existence of gnuplot in imach path
                    706: 
                    707:   Revision 1.106  2006/01/19 13:24:36  brouard
                    708:   Some cleaning and links added in html output
                    709: 
                    710:   Revision 1.105  2006/01/05 20:23:19  lievre
                    711:   *** empty log message ***
                    712: 
                    713:   Revision 1.104  2005/09/30 16:11:43  lievre
                    714:   (Module): sump fixed, loop imx fixed, and simplifications.
                    715:   (Module): If the status is missing at the last wave but we know
                    716:   that the person is alive, then we can code his/her status as -2
                    717:   (instead of missing=-1 in earlier versions) and his/her
                    718:   contributions to the likelihood is 1 - Prob of dying from last
                    719:   health status (= 1-p13= p11+p12 in the easiest case of somebody in
                    720:   the healthy state at last known wave). Version is 0.98
                    721: 
                    722:   Revision 1.103  2005/09/30 15:54:49  lievre
                    723:   (Module): sump fixed, loop imx fixed, and simplifications.
                    724: 
                    725:   Revision 1.102  2004/09/15 17:31:30  brouard
                    726:   Add the possibility to read data file including tab characters.
                    727: 
                    728:   Revision 1.101  2004/09/15 10:38:38  brouard
                    729:   Fix on curr_time
                    730: 
                    731:   Revision 1.100  2004/07/12 18:29:06  brouard
                    732:   Add version for Mac OS X. Just define UNIX in Makefile
                    733: 
                    734:   Revision 1.99  2004/06/05 08:57:40  brouard
                    735:   *** empty log message ***
                    736: 
                    737:   Revision 1.98  2004/05/16 15:05:56  brouard
                    738:   New version 0.97 . First attempt to estimate force of mortality
                    739:   directly from the data i.e. without the need of knowing the health
                    740:   state at each age, but using a Gompertz model: log u =a + b*age .
                    741:   This is the basic analysis of mortality and should be done before any
                    742:   other analysis, in order to test if the mortality estimated from the
                    743:   cross-longitudinal survey is different from the mortality estimated
                    744:   from other sources like vital statistic data.
                    745: 
                    746:   The same imach parameter file can be used but the option for mle should be -3.
                    747: 
1.133     brouard   748:   Agnès, who wrote this part of the code, tried to keep most of the
1.126     brouard   749:   former routines in order to include the new code within the former code.
                    750: 
                    751:   The output is very simple: only an estimate of the intercept and of
                    752:   the slope with 95% confident intervals.
                    753: 
                    754:   Current limitations:
                    755:   A) Even if you enter covariates, i.e. with the
                    756:   model= V1+V2 equation for example, the programm does only estimate a unique global model without covariates.
                    757:   B) There is no computation of Life Expectancy nor Life Table.
                    758: 
                    759:   Revision 1.97  2004/02/20 13:25:42  lievre
                    760:   Version 0.96d. Population forecasting command line is (temporarily)
                    761:   suppressed.
                    762: 
                    763:   Revision 1.96  2003/07/15 15:38:55  brouard
                    764:   * imach.c (Repository): Errors in subdirf, 2, 3 while printing tmpout is
                    765:   rewritten within the same printf. Workaround: many printfs.
                    766: 
                    767:   Revision 1.95  2003/07/08 07:54:34  brouard
                    768:   * imach.c (Repository):
                    769:   (Repository): Using imachwizard code to output a more meaningful covariance
                    770:   matrix (cov(a12,c31) instead of numbers.
                    771: 
                    772:   Revision 1.94  2003/06/27 13:00:02  brouard
                    773:   Just cleaning
                    774: 
                    775:   Revision 1.93  2003/06/25 16:33:55  brouard
                    776:   (Module): On windows (cygwin) function asctime_r doesn't
                    777:   exist so I changed back to asctime which exists.
                    778:   (Module): Version 0.96b
                    779: 
                    780:   Revision 1.92  2003/06/25 16:30:45  brouard
                    781:   (Module): On windows (cygwin) function asctime_r doesn't
                    782:   exist so I changed back to asctime which exists.
                    783: 
                    784:   Revision 1.91  2003/06/25 15:30:29  brouard
                    785:   * imach.c (Repository): Duplicated warning errors corrected.
                    786:   (Repository): Elapsed time after each iteration is now output. It
                    787:   helps to forecast when convergence will be reached. Elapsed time
                    788:   is stamped in powell.  We created a new html file for the graphs
                    789:   concerning matrix of covariance. It has extension -cov.htm.
                    790: 
                    791:   Revision 1.90  2003/06/24 12:34:15  brouard
                    792:   (Module): Some bugs corrected for windows. Also, when
                    793:   mle=-1 a template is output in file "or"mypar.txt with the design
                    794:   of the covariance matrix to be input.
                    795: 
                    796:   Revision 1.89  2003/06/24 12:30:52  brouard
                    797:   (Module): Some bugs corrected for windows. Also, when
                    798:   mle=-1 a template is output in file "or"mypar.txt with the design
                    799:   of the covariance matrix to be input.
                    800: 
                    801:   Revision 1.88  2003/06/23 17:54:56  brouard
                    802:   * 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.
                    803: 
                    804:   Revision 1.87  2003/06/18 12:26:01  brouard
                    805:   Version 0.96
                    806: 
                    807:   Revision 1.86  2003/06/17 20:04:08  brouard
                    808:   (Module): Change position of html and gnuplot routines and added
                    809:   routine fileappend.
                    810: 
                    811:   Revision 1.85  2003/06/17 13:12:43  brouard
                    812:   * imach.c (Repository): Check when date of death was earlier that
                    813:   current date of interview. It may happen when the death was just
                    814:   prior to the death. In this case, dh was negative and likelihood
                    815:   was wrong (infinity). We still send an "Error" but patch by
                    816:   assuming that the date of death was just one stepm after the
                    817:   interview.
                    818:   (Repository): Because some people have very long ID (first column)
                    819:   we changed int to long in num[] and we added a new lvector for
                    820:   memory allocation. But we also truncated to 8 characters (left
                    821:   truncation)
                    822:   (Repository): No more line truncation errors.
                    823: 
                    824:   Revision 1.84  2003/06/13 21:44:43  brouard
                    825:   * imach.c (Repository): Replace "freqsummary" at a correct
                    826:   place. It differs from routine "prevalence" which may be called
                    827:   many times. Probs is memory consuming and must be used with
                    828:   parcimony.
                    829:   Version 0.95a3 (should output exactly the same maximization than 0.8a2)
                    830: 
                    831:   Revision 1.83  2003/06/10 13:39:11  lievre
                    832:   *** empty log message ***
                    833: 
                    834:   Revision 1.82  2003/06/05 15:57:20  brouard
                    835:   Add log in  imach.c and  fullversion number is now printed.
                    836: 
                    837: */
                    838: /*
                    839:    Interpolated Markov Chain
                    840: 
                    841:   Short summary of the programme:
                    842:   
1.227     brouard   843:   This program computes Healthy Life Expectancies or State-specific
                    844:   (if states aren't health statuses) Expectancies from
                    845:   cross-longitudinal data. Cross-longitudinal data consist in: 
                    846: 
                    847:   -1- a first survey ("cross") where individuals from different ages
                    848:   are interviewed on their health status or degree of disability (in
                    849:   the case of a health survey which is our main interest)
                    850: 
                    851:   -2- at least a second wave of interviews ("longitudinal") which
                    852:   measure each change (if any) in individual health status.  Health
                    853:   expectancies are computed from the time spent in each health state
                    854:   according to a model. More health states you consider, more time is
                    855:   necessary to reach the Maximum Likelihood of the parameters involved
                    856:   in the model.  The simplest model is the multinomial logistic model
                    857:   where pij is the probability to be observed in state j at the second
                    858:   wave conditional to be observed in state i at the first
                    859:   wave. Therefore the model is: log(pij/pii)= aij + bij*age+ cij*sex +
                    860:   etc , where 'age' is age and 'sex' is a covariate. If you want to
                    861:   have a more complex model than "constant and age", you should modify
                    862:   the program where the markup *Covariates have to be included here
                    863:   again* invites you to do it.  More covariates you add, slower the
1.126     brouard   864:   convergence.
                    865: 
                    866:   The advantage of this computer programme, compared to a simple
                    867:   multinomial logistic model, is clear when the delay between waves is not
                    868:   identical for each individual. Also, if a individual missed an
                    869:   intermediate interview, the information is lost, but taken into
                    870:   account using an interpolation or extrapolation.  
                    871: 
                    872:   hPijx is the probability to be observed in state i at age x+h
                    873:   conditional to the observed state i at age x. The delay 'h' can be
                    874:   split into an exact number (nh*stepm) of unobserved intermediate
                    875:   states. This elementary transition (by month, quarter,
                    876:   semester or year) is modelled as a multinomial logistic.  The hPx
                    877:   matrix is simply the matrix product of nh*stepm elementary matrices
                    878:   and the contribution of each individual to the likelihood is simply
                    879:   hPijx.
                    880: 
                    881:   Also this programme outputs the covariance matrix of the parameters but also
1.218     brouard   882:   of the life expectancies. It also computes the period (stable) prevalence.
                    883: 
                    884: Back prevalence and projections:
1.227     brouard   885: 
                    886:  - back_prevalence_limit(double *p, double **bprlim, double ageminpar,
                    887:    double agemaxpar, double ftolpl, int *ncvyearp, double
                    888:    dateprev1,double dateprev2, int firstpass, int lastpass, int
                    889:    mobilavproj)
                    890: 
                    891:     Computes the back prevalence limit for any combination of
                    892:     covariate values k at any age between ageminpar and agemaxpar and
                    893:     returns it in **bprlim. In the loops,
                    894: 
                    895:    - **bprevalim(**bprlim, ***mobaverage, nlstate, *p, age, **oldm,
                    896:        **savm, **dnewm, **doldm, **dsavm, ftolpl, ncvyearp, k);
                    897: 
                    898:    - hBijx Back Probability to be in state i at age x-h being in j at x
1.218     brouard   899:    Computes for any combination of covariates k and any age between bage and fage 
                    900:    p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                    901:                        oldm=oldms;savm=savms;
1.227     brouard   902: 
1.267     brouard   903:    - hbxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k, nres);
1.218     brouard   904:      Computes the transition matrix starting at age 'age' over
                    905:      'nhstepm*hstepm*stepm' months (i.e. until
                    906:      age (in years)  age+nhstepm*hstepm*stepm/12) by multiplying
1.227     brouard   907:      nhstepm*hstepm matrices. 
                    908: 
                    909:      Returns p3mat[i][j][h] after calling
                    910:      p3mat[i][j][h]=matprod2(newm,
                    911:      bmij(pmmij,cov,ncovmodel,x,nlstate,prevacurrent, dnewm, doldm,
                    912:      dsavm,ij),\ 1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath,
                    913:      oldm);
1.226     brouard   914: 
                    915: Important routines
                    916: 
                    917: - func (or funcone), computes logit (pij) distinguishing
                    918:   o fixed variables (single or product dummies or quantitative);
                    919:   o varying variables by:
                    920:    (1) wave (single, product dummies, quantitative), 
                    921:    (2) by age (can be month) age (done), age*age (done), age*Vn where Vn can be:
                    922:        % fixed dummy (treated) or quantitative (not done because time-consuming);
                    923:        % varying dummy (not done) or quantitative (not done);
                    924: - Tricode which tests the modality of dummy variables (in order to warn with wrong or empty modalities)
                    925:   and returns the number of efficient covariates cptcoveff and modalities nbcode[Tvar[k]][1]= 0 and nbcode[Tvar[k]][2]= 1 usually.
                    926: - printinghtml which outputs results like life expectancy in and from a state for a combination of modalities of dummy variables
                    927:   o There are 2*cptcoveff combinations of (0,1) for cptcoveff variables. Outputting only combinations with people, éliminating 1 1 if
                    928:     race White (0 0), Black vs White (1 0), Hispanic (0 1) and 1 1 being meaningless.
1.218     brouard   929: 
1.226     brouard   930: 
                    931:   
1.133     brouard   932:   Authors: Nicolas Brouard (brouard@ined.fr) and Agnès Lièvre (lievre@ined.fr).
                    933:            Institut national d'études démographiques, Paris.
1.126     brouard   934:   This software have been partly granted by Euro-REVES, a concerted action
                    935:   from the European Union.
                    936:   It is copyrighted identically to a GNU software product, ie programme and
                    937:   software can be distributed freely for non commercial use. Latest version
                    938:   can be accessed at http://euroreves.ined.fr/imach .
                    939: 
                    940:   Help to debug: LD_PRELOAD=/usr/local/lib/libnjamd.so ./imach foo.imach
                    941:   or better on gdb : set env LD_PRELOAD=/usr/local/lib/libnjamd.so
                    942:   
                    943:   **********************************************************************/
                    944: /*
                    945:   main
                    946:   read parameterfile
                    947:   read datafile
                    948:   concatwav
                    949:   freqsummary
                    950:   if (mle >= 1)
                    951:     mlikeli
                    952:   print results files
                    953:   if mle==1 
                    954:      computes hessian
                    955:   read end of parameter file: agemin, agemax, bage, fage, estepm
                    956:       begin-prev-date,...
                    957:   open gnuplot file
                    958:   open html file
1.145     brouard   959:   period (stable) prevalence      | pl_nom    1-1 2-2 etc by covariate
                    960:    for age prevalim()             | #****** V1=0  V2=1  V3=1  V4=0 ******
                    961:                                   | 65 1 0 2 1 3 1 4 0  0.96326 0.03674
                    962:     freexexit2 possible for memory heap.
                    963: 
                    964:   h Pij x                         | pij_nom  ficrestpij
                    965:    # Cov Agex agex+h hpijx with i,j= 1-1 1-2     1-3     2-1     2-2     2-3
                    966:        1  85   85    1.00000             0.00000 0.00000 0.00000 1.00000 0.00000
                    967:        1  85   86    0.68299             0.22291 0.09410 0.71093 0.00000 0.28907
                    968: 
                    969:        1  65   99    0.00364             0.00322 0.99314 0.00350 0.00310 0.99340
                    970:        1  65  100    0.00214             0.00204 0.99581 0.00206 0.00196 0.99597
                    971:   variance of p one-step probabilities varprob  | prob_nom   ficresprob #One-step probabilities and stand. devi in ()
                    972:    Standard deviation of one-step probabilities | probcor_nom   ficresprobcor #One-step probabilities and correlation matrix
                    973:    Matrix of variance covariance of one-step probabilities |  probcov_nom ficresprobcov #One-step probabilities and covariance matrix
                    974: 
1.126     brouard   975:   forecasting if prevfcast==1 prevforecast call prevalence()
                    976:   health expectancies
                    977:   Variance-covariance of DFLE
                    978:   prevalence()
                    979:    movingaverage()
                    980:   varevsij() 
                    981:   if popbased==1 varevsij(,popbased)
                    982:   total life expectancies
                    983:   Variance of period (stable) prevalence
                    984:  end
                    985: */
                    986: 
1.187     brouard   987: /* #define DEBUG */
                    988: /* #define DEBUGBRENT */
1.203     brouard   989: /* #define DEBUGLINMIN */
                    990: /* #define DEBUGHESS */
                    991: #define DEBUGHESSIJ
1.224     brouard   992: /* #define LINMINORIGINAL  /\* Don't use loop on scale in linmin (accepting nan) *\/ */
1.165     brouard   993: #define POWELL /* Instead of NLOPT */
1.224     brouard   994: #define POWELLNOF3INFF1TEST /* Skip test */
1.186     brouard   995: /* #define POWELLORIGINAL /\* Don't use Directest to decide new direction but original Powell test *\/ */
                    996: /* #define MNBRAKORIGINAL /\* Don't use mnbrak fix *\/ */
1.126     brouard   997: 
                    998: #include <math.h>
                    999: #include <stdio.h>
                   1000: #include <stdlib.h>
                   1001: #include <string.h>
1.226     brouard  1002: #include <ctype.h>
1.159     brouard  1003: 
                   1004: #ifdef _WIN32
                   1005: #include <io.h>
1.172     brouard  1006: #include <windows.h>
                   1007: #include <tchar.h>
1.159     brouard  1008: #else
1.126     brouard  1009: #include <unistd.h>
1.159     brouard  1010: #endif
1.126     brouard  1011: 
                   1012: #include <limits.h>
                   1013: #include <sys/types.h>
1.171     brouard  1014: 
                   1015: #if defined(__GNUC__)
                   1016: #include <sys/utsname.h> /* Doesn't work on Windows */
                   1017: #endif
                   1018: 
1.126     brouard  1019: #include <sys/stat.h>
                   1020: #include <errno.h>
1.159     brouard  1021: /* extern int errno; */
1.126     brouard  1022: 
1.157     brouard  1023: /* #ifdef LINUX */
                   1024: /* #include <time.h> */
                   1025: /* #include "timeval.h" */
                   1026: /* #else */
                   1027: /* #include <sys/time.h> */
                   1028: /* #endif */
                   1029: 
1.126     brouard  1030: #include <time.h>
                   1031: 
1.136     brouard  1032: #ifdef GSL
                   1033: #include <gsl/gsl_errno.h>
                   1034: #include <gsl/gsl_multimin.h>
                   1035: #endif
                   1036: 
1.167     brouard  1037: 
1.162     brouard  1038: #ifdef NLOPT
                   1039: #include <nlopt.h>
                   1040: typedef struct {
                   1041:   double (* function)(double [] );
                   1042: } myfunc_data ;
                   1043: #endif
                   1044: 
1.126     brouard  1045: /* #include <libintl.h> */
                   1046: /* #define _(String) gettext (String) */
                   1047: 
1.251     brouard  1048: #define MAXLINE 2048 /* Was 256 and 1024. Overflow with 312 with 2 states and 4 covariates. Should be ok */
1.126     brouard  1049: 
                   1050: #define GNUPLOTPROGRAM "gnuplot"
                   1051: /*#define GNUPLOTPROGRAM "..\\gp37mgw\\wgnuplot"*/
                   1052: #define FILENAMELENGTH 132
                   1053: 
                   1054: #define        GLOCK_ERROR_NOPATH              -1      /* empty path */
                   1055: #define        GLOCK_ERROR_GETCWD              -2      /* cannot get cwd */
                   1056: 
1.144     brouard  1057: #define MAXPARM 128 /**< Maximum number of parameters for the optimization */
                   1058: #define NPARMAX 64 /**< (nlstate+ndeath-1)*nlstate*ncovmodel */
1.126     brouard  1059: 
                   1060: #define NINTERVMAX 8
1.144     brouard  1061: #define NLSTATEMAX 8 /**< Maximum number of live states (for func) */
                   1062: #define NDEATHMAX 8 /**< Maximum number of dead states (for func) */
1.291     brouard  1063: #define NCOVMAX 20  /**< Maximum number of covariates, including generated covariates V1*V2 */
1.197     brouard  1064: #define codtabm(h,k)  (1 & (h-1) >> (k-1))+1
1.211     brouard  1065: /*#define decodtabm(h,k,cptcoveff)= (h <= (1<<cptcoveff)?(((h-1) >> (k-1)) & 1) +1 : -1)*/
                   1066: #define decodtabm(h,k,cptcoveff) (((h-1) >> (k-1)) & 1) +1 
1.290     brouard  1067: /*#define MAXN 20000 */ /* Should by replaced by nobs, real number of observations and unlimited */
1.144     brouard  1068: #define YEARM 12. /**< Number of months per year */
1.218     brouard  1069: /* #define AGESUP 130 */
1.288     brouard  1070: /* #define AGESUP 150 */
                   1071: #define AGESUP 200
1.268     brouard  1072: #define AGEINF 0
1.218     brouard  1073: #define AGEMARGE 25 /* Marge for agemin and agemax for(iage=agemin-AGEMARGE; iage <= agemax+3+AGEMARGE; iage++) */
1.126     brouard  1074: #define AGEBASE 40
1.194     brouard  1075: #define AGEOVERFLOW 1.e20
1.164     brouard  1076: #define AGEGOMP 10 /**< Minimal age for Gompertz adjustment */
1.157     brouard  1077: #ifdef _WIN32
                   1078: #define DIRSEPARATOR '\\'
                   1079: #define CHARSEPARATOR "\\"
                   1080: #define ODIRSEPARATOR '/'
                   1081: #else
1.126     brouard  1082: #define DIRSEPARATOR '/'
                   1083: #define CHARSEPARATOR "/"
                   1084: #define ODIRSEPARATOR '\\'
                   1085: #endif
                   1086: 
1.293   ! brouard  1087: /* $Id: imach.c,v 1.292 2019/05/09 14:17:20 brouard Exp $ */
1.126     brouard  1088: /* $State: Exp $ */
1.196     brouard  1089: #include "version.h"
                   1090: char version[]=__IMACH_VERSION__;
1.283     brouard  1091: 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.293   ! brouard  1092: char fullversion[]="$Revision: 1.292 $ $Date: 2019/05/09 14:17:20 $"; 
1.126     brouard  1093: char strstart[80];
                   1094: char optionfilext[10], optionfilefiname[FILENAMELENGTH];
1.130     brouard  1095: int erreur=0, nberr=0, nbwarn=0; /* Error number, number of errors number of warnings  */
1.187     brouard  1096: int nagesqr=0, nforce=0; /* nagesqr=1 if model is including age*age, number of forces */
1.145     brouard  1097: /* Number of covariates model=V2+V1+ V3*age+V2*V4 */
                   1098: int cptcovn=0; /**< cptcovn number of covariates added in the model (excepting constant and age and age*product) */
                   1099: int cptcovt=0; /**< cptcovt number of covariates added in the model (excepting constant and age) */
1.225     brouard  1100: int cptcovs=0; /**< cptcovs number of simple covariates in the model V2+V1 =2 */
                   1101: int cptcovsnq=0; /**< cptcovsnq number of simple covariates in the model but non quantitative V2+V1 =2 */
1.145     brouard  1102: int cptcovage=0; /**< Number of covariates with age: V3*age only =1 */
                   1103: int cptcovprodnoage=0; /**< Number of covariate products without age */   
                   1104: int cptcoveff=0; /* Total number of covariates to vary for printing results */
1.233     brouard  1105: int ncovf=0; /* Total number of effective fixed covariates (dummy or quantitative) in the model */
                   1106: int ncovv=0; /* Total number of effective (wave) varying covariates (dummy or quantitative) in the model */
1.232     brouard  1107: int ncova=0; /* Total number of effective (wave and stepm) varying with age covariates (dummy of quantitative) in the model */
1.234     brouard  1108: int nsd=0; /**< Total number of single dummy variables (output) */
                   1109: int nsq=0; /**< Total number of single quantitative variables (output) */
1.232     brouard  1110: int ncoveff=0; /* Total number of effective fixed dummy covariates in the model */
1.225     brouard  1111: int nqfveff=0; /**< nqfveff Number of Quantitative Fixed Variables Effective */
1.224     brouard  1112: int ntveff=0; /**< ntveff number of effective time varying variables */
                   1113: int nqtveff=0; /**< ntqveff number of effective time varying quantitative variables */
1.145     brouard  1114: int cptcov=0; /* Working variable */
1.290     brouard  1115: int nobs=10;  /* Number of observations in the data lastobs-firstobs */
1.218     brouard  1116: int ncovcombmax=NCOVMAX; /* Maximum calculated number of covariate combination = pow(2, cptcoveff) */
1.126     brouard  1117: int npar=NPARMAX;
                   1118: int nlstate=2; /* Number of live states */
                   1119: int ndeath=1; /* Number of dead states */
1.130     brouard  1120: int ncovmodel=0, ncovcol=0;     /* Total number of covariables including constant a12*1 +b12*x ncovmodel=2 */
1.223     brouard  1121: int  nqv=0, ntv=0, nqtv=0;    /* Total number of quantitative variables, time variable (dummy), quantitative and time variable */ 
1.126     brouard  1122: int popbased=0;
                   1123: 
                   1124: int *wav; /* Number of waves for this individuual 0 is possible */
1.130     brouard  1125: int maxwav=0; /* Maxim number of waves */
                   1126: int jmin=0, jmax=0; /* min, max spacing between 2 waves */
                   1127: int ijmin=0, ijmax=0; /* Individuals having jmin and jmax */ 
                   1128: int gipmx=0, gsw=0; /* Global variables on the number of contributions 
1.126     brouard  1129:                   to the likelihood and the sum of weights (done by funcone)*/
1.130     brouard  1130: int mle=1, weightopt=0;
1.126     brouard  1131: int **mw; /* mw[mi][i] is number of the mi wave for this individual */
                   1132: int **dh; /* dh[mi][i] is number of steps between mi,mi+1 for this individual */
                   1133: int **bh; /* bh[mi][i] is the bias (+ or -) for this individual if the delay between
                   1134:           * wave mi and wave mi+1 is not an exact multiple of stepm. */
1.162     brouard  1135: int countcallfunc=0;  /* Count the number of calls to func */
1.230     brouard  1136: int selected(int kvar); /* Is covariate kvar selected for printing results */
                   1137: 
1.130     brouard  1138: double jmean=1; /* Mean space between 2 waves */
1.145     brouard  1139: double **matprod2(); /* test */
1.126     brouard  1140: double **oldm, **newm, **savm; /* Working pointers to matrices */
                   1141: double **oldms, **newms, **savms; /* Fixed working pointers to matrices */
1.218     brouard  1142: double  **ddnewms, **ddoldms, **ddsavms; /* for freeing later */
                   1143: 
1.136     brouard  1144: /*FILE *fic ; */ /* Used in readdata only */
1.217     brouard  1145: FILE *ficpar, *ficparo,*ficres, *ficresp, *ficresphtm, *ficresphtmfr, *ficrespl, *ficresplb,*ficrespij, *ficrespijb, *ficrest,*ficresf, *ficresfb,*ficrespop;
1.126     brouard  1146: FILE *ficlog, *ficrespow;
1.130     brouard  1147: int globpr=0; /* Global variable for printing or not */
1.126     brouard  1148: double fretone; /* Only one call to likelihood */
1.130     brouard  1149: long ipmx=0; /* Number of contributions */
1.126     brouard  1150: double sw; /* Sum of weights */
                   1151: char filerespow[FILENAMELENGTH];
                   1152: char fileresilk[FILENAMELENGTH]; /* File of individual contributions to the likelihood */
                   1153: FILE *ficresilk;
                   1154: FILE *ficgp,*ficresprob,*ficpop, *ficresprobcov, *ficresprobcor;
                   1155: FILE *ficresprobmorprev;
                   1156: FILE *fichtm, *fichtmcov; /* Html File */
                   1157: FILE *ficreseij;
                   1158: char filerese[FILENAMELENGTH];
                   1159: FILE *ficresstdeij;
                   1160: char fileresstde[FILENAMELENGTH];
                   1161: FILE *ficrescveij;
                   1162: char filerescve[FILENAMELENGTH];
                   1163: FILE  *ficresvij;
                   1164: char fileresv[FILENAMELENGTH];
1.269     brouard  1165: 
1.126     brouard  1166: char title[MAXLINE];
1.234     brouard  1167: char model[MAXLINE]; /**< The model line */
1.217     brouard  1168: char optionfile[FILENAMELENGTH], datafile[FILENAMELENGTH],  filerespl[FILENAMELENGTH],  fileresplb[FILENAMELENGTH];
1.126     brouard  1169: char plotcmd[FILENAMELENGTH], pplotcmd[FILENAMELENGTH];
                   1170: char tmpout[FILENAMELENGTH],  tmpout2[FILENAMELENGTH]; 
                   1171: char command[FILENAMELENGTH];
                   1172: int  outcmd=0;
                   1173: 
1.217     brouard  1174: char fileres[FILENAMELENGTH], filerespij[FILENAMELENGTH], filerespijb[FILENAMELENGTH], filereso[FILENAMELENGTH], rfileres[FILENAMELENGTH];
1.202     brouard  1175: char fileresu[FILENAMELENGTH]; /* fileres without r in front */
1.126     brouard  1176: char filelog[FILENAMELENGTH]; /* Log file */
                   1177: char filerest[FILENAMELENGTH];
                   1178: char fileregp[FILENAMELENGTH];
                   1179: char popfile[FILENAMELENGTH];
                   1180: 
                   1181: char optionfilegnuplot[FILENAMELENGTH], optionfilehtm[FILENAMELENGTH], optionfilehtmcov[FILENAMELENGTH] ;
                   1182: 
1.157     brouard  1183: /* struct timeval start_time, end_time, curr_time, last_time, forecast_time; */
                   1184: /* struct timezone tzp; */
                   1185: /* extern int gettimeofday(); */
                   1186: struct tm tml, *gmtime(), *localtime();
                   1187: 
                   1188: extern time_t time();
                   1189: 
                   1190: struct tm start_time, end_time, curr_time, last_time, forecast_time;
                   1191: time_t  rstart_time, rend_time, rcurr_time, rlast_time, rforecast_time; /* raw time */
                   1192: struct tm tm;
                   1193: 
1.126     brouard  1194: char strcurr[80], strfor[80];
                   1195: 
                   1196: char *endptr;
                   1197: long lval;
                   1198: double dval;
                   1199: 
                   1200: #define NR_END 1
                   1201: #define FREE_ARG char*
                   1202: #define FTOL 1.0e-10
                   1203: 
                   1204: #define NRANSI 
1.240     brouard  1205: #define ITMAX 200
                   1206: #define ITPOWMAX 20 /* This is now multiplied by the number of parameters */ 
1.126     brouard  1207: 
                   1208: #define TOL 2.0e-4 
                   1209: 
                   1210: #define CGOLD 0.3819660 
                   1211: #define ZEPS 1.0e-10 
                   1212: #define SHFT(a,b,c,d) (a)=(b);(b)=(c);(c)=(d); 
                   1213: 
                   1214: #define GOLD 1.618034 
                   1215: #define GLIMIT 100.0 
                   1216: #define TINY 1.0e-20 
                   1217: 
                   1218: static double maxarg1,maxarg2;
                   1219: #define FMAX(a,b) (maxarg1=(a),maxarg2=(b),(maxarg1)>(maxarg2)? (maxarg1):(maxarg2))
                   1220: #define FMIN(a,b) (maxarg1=(a),maxarg2=(b),(maxarg1)<(maxarg2)? (maxarg1):(maxarg2))
                   1221:   
                   1222: #define SIGN(a,b) ((b)>0.0 ? fabs(a) : -fabs(a))
                   1223: #define rint(a) floor(a+0.5)
1.166     brouard  1224: /* http://www.thphys.uni-heidelberg.de/~robbers/cmbeasy/doc/html/myutils_8h-source.html */
1.183     brouard  1225: #define mytinydouble 1.0e-16
1.166     brouard  1226: /* #define DEQUAL(a,b) (fabs((a)-(b))<mytinydouble) */
                   1227: /* http://www.thphys.uni-heidelberg.de/~robbers/cmbeasy/doc/html/mynrutils_8h-source.html */
                   1228: /* static double dsqrarg; */
                   1229: /* #define DSQR(a) (DEQUAL((dsqrarg=(a)),0.0) ? 0.0 : dsqrarg*dsqrarg) */
1.126     brouard  1230: static double sqrarg;
                   1231: #define SQR(a) ((sqrarg=(a)) == 0.0 ? 0.0 :sqrarg*sqrarg)
                   1232: #define SWAP(a,b) {temp=(a);(a)=(b);(b)=temp;} 
                   1233: int agegomp= AGEGOMP;
                   1234: 
                   1235: int imx; 
                   1236: int stepm=1;
                   1237: /* Stepm, step in month: minimum step interpolation*/
                   1238: 
                   1239: int estepm;
                   1240: /* Estepm, step in month to interpolate survival function in order to approximate Life Expectancy*/
                   1241: 
                   1242: int m,nb;
                   1243: long *num;
1.197     brouard  1244: int firstpass=0, lastpass=4,*cod, *cens;
1.192     brouard  1245: int *ncodemax;  /* ncodemax[j]= Number of modalities of the j th
                   1246:                   covariate for which somebody answered excluding 
                   1247:                   undefined. Usually 2: 0 and 1. */
                   1248: int *ncodemaxwundef;  /* ncodemax[j]= Number of modalities of the j th
                   1249:                             covariate for which somebody answered including 
                   1250:                             undefined. Usually 3: -1, 0 and 1. */
1.126     brouard  1251: double **agev,*moisnais, *annais, *moisdc, *andc,**mint, **anint;
1.218     brouard  1252: double **pmmij, ***probs; /* Global pointer */
1.219     brouard  1253: double ***mobaverage, ***mobaverages; /* New global variable */
1.126     brouard  1254: double *ageexmed,*agecens;
                   1255: double dateintmean=0;
                   1256: 
                   1257: double *weight;
                   1258: int **s; /* Status */
1.141     brouard  1259: double *agedc;
1.145     brouard  1260: double  **covar; /**< covar[j,i], value of jth covariate for individual i,
1.141     brouard  1261:                  * covar=matrix(0,NCOVMAX,1,n); 
1.187     brouard  1262:                  * cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*age; */
1.268     brouard  1263: double **coqvar; /* Fixed quantitative covariate nqv */
                   1264: double ***cotvar; /* Time varying covariate ntv */
1.225     brouard  1265: double ***cotqvar; /* Time varying quantitative covariate itqv */
1.141     brouard  1266: double  idx; 
                   1267: int **nbcode, *Tvar; /**< model=V2 => Tvar[1]= 2 */
1.234     brouard  1268: /*           V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
                   1269: /*k          1  2   3   4     5    6    7     8    9 */
                   1270: /*Tvar[k]=   5  4   3   6     5    2    7     1    1 */
                   1271: /* Tndvar[k]    1   2   3               4          5 */
                   1272: /*TDvar         4   3   6               7          1 */ /* For outputs only; combination of dummies fixed or varying */
                   1273: /* Tns[k]    1  2   2              4               5 */ /* Number of single cova */
                   1274: /* TvarsD[k]    1   2                              3 */ /* Number of single dummy cova */
                   1275: /* TvarsDind    2   3                              9 */ /* position K of single dummy cova */
                   1276: /* TvarsQ[k] 1                     2                 */ /* Number of single quantitative cova */
                   1277: /* TvarsQind 1                     6                 */ /* position K of single quantitative cova */
                   1278: /* Tprod[i]=k           4               7            */
                   1279: /* Tage[i]=k                  5               8      */
                   1280: /* */
                   1281: /* Type                    */
                   1282: /* V         1  2  3  4  5 */
                   1283: /*           F  F  V  V  V */
                   1284: /*           D  Q  D  D  Q */
                   1285: /*                         */
                   1286: int *TvarsD;
                   1287: int *TvarsDind;
                   1288: int *TvarsQ;
                   1289: int *TvarsQind;
                   1290: 
1.235     brouard  1291: #define MAXRESULTLINES 10
                   1292: int nresult=0;
1.258     brouard  1293: int parameterline=0; /* # of the parameter (type) line */
1.235     brouard  1294: int TKresult[MAXRESULTLINES];
1.237     brouard  1295: int Tresult[MAXRESULTLINES][NCOVMAX];/* For dummy variable , value (output) */
                   1296: int Tinvresult[MAXRESULTLINES][NCOVMAX];/* For dummy variable , value (output) */
1.235     brouard  1297: int Tvresult[MAXRESULTLINES][NCOVMAX]; /* For dummy variable , variable # (output) */
                   1298: double Tqresult[MAXRESULTLINES][NCOVMAX]; /* For quantitative variable , value (output) */
1.237     brouard  1299: double Tqinvresult[MAXRESULTLINES][NCOVMAX]; /* For quantitative variable , value (output) */
1.235     brouard  1300: int Tvqresult[MAXRESULTLINES][NCOVMAX]; /* For quantitative variable , variable # (output) */
                   1301: 
1.234     brouard  1302: /* 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  1303: 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 */
                   1304: 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 */
                   1305: 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 */
                   1306: int *TvarVind; /**< TvarVind[1]=1, TvarVind[2]=2  in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
                   1307: 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 */
                   1308: 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  1309: int *TvarFD; /**< TvarFD[1]=V1 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
                   1310: int *TvarFDind; /* TvarFDind[1]=9 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
                   1311: int *TvarFQ; /* TvarFQ[1]=V2 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */ /* Only simple fixed quantitative variable */
                   1312: int *TvarFQind; /* TvarFQind[1]=6 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */ /* Only simple fixed quantitative variable */
                   1313: int *TvarVD; /* TvarVD[1]=V5 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */ /* Only simple fixed quantitative variable */
                   1314: int *TvarVDind; /* TvarVDind[1]=1 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */ /* Only simple fixed quantitative variable */
                   1315: 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 */
                   1316: 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 */
                   1317: 
1.230     brouard  1318: int *Tvarsel; /**< Selected covariates for output */
                   1319: double *Tvalsel; /**< Selected modality value of covariate for output */
1.226     brouard  1320: int *Typevar; /**< 0 for simple covariate (dummy, quantitative, fixed or varying), 1 for age product, 2 for  product */
1.227     brouard  1321: int *Fixed; /** Fixed[k] 0=fixed, 1 varying, 2 fixed with age product, 3 varying with age product */ 
                   1322: 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  1323: int *DummyV; /** Dummy[v] 0=dummy (0 1), 1 quantitative */
                   1324: int *FixedV; /** FixedV[v] 0 fixed, 1 varying */
1.197     brouard  1325: int *Tage;
1.227     brouard  1326: int anyvaryingduminmodel=0; /**< Any varying dummy in Model=1 yes, 0 no, to avoid a loop on waves in freq */ 
1.228     brouard  1327: 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  1328: 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*/ 
                   1329: 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  1330: int *Ndum; /** Freq of modality (tricode */
1.200     brouard  1331: /* int **codtab;*/ /**< codtab=imatrix(1,100,1,10); */
1.227     brouard  1332: int **Tvard;
                   1333: int *Tprod;/**< Gives the k position of the k1 product */
1.238     brouard  1334: /* Tprod[k1=1]=3(=V1*V4) for V2+V1+V1*V4+age*V3  */
1.227     brouard  1335: int *Tposprod; /**< Gives the k1 product from the k position */
1.238     brouard  1336:    /* if  V2+V1+V1*V4+age*V3+V3*V2   TProd[k1=2]=5 (V3*V2) */
                   1337:    /* Tposprod[k]=k1 , Tposprod[3]=1, Tposprod[5(V3*V2)]=2 (2nd product without age) */
1.227     brouard  1338: int cptcovprod, *Tvaraff, *invalidvarcomb;
1.126     brouard  1339: double *lsurv, *lpop, *tpop;
                   1340: 
1.231     brouard  1341: #define FD 1; /* Fixed dummy covariate */
                   1342: #define FQ 2; /* Fixed quantitative covariate */
                   1343: #define FP 3; /* Fixed product covariate */
                   1344: #define FPDD 7; /* Fixed product dummy*dummy covariate */
                   1345: #define FPDQ 8; /* Fixed product dummy*quantitative covariate */
                   1346: #define FPQQ 9; /* Fixed product quantitative*quantitative covariate */
                   1347: #define VD 10; /* Varying dummy covariate */
                   1348: #define VQ 11; /* Varying quantitative covariate */
                   1349: #define VP 12; /* Varying product covariate */
                   1350: #define VPDD 13; /* Varying product dummy*dummy covariate */
                   1351: #define VPDQ 14; /* Varying product dummy*quantitative covariate */
                   1352: #define VPQQ 15; /* Varying product quantitative*quantitative covariate */
                   1353: #define APFD 16; /* Age product * fixed dummy covariate */
                   1354: #define APFQ 17; /* Age product * fixed quantitative covariate */
                   1355: #define APVD 18; /* Age product * varying dummy covariate */
                   1356: #define APVQ 19; /* Age product * varying quantitative covariate */
                   1357: 
                   1358: #define FTYPE 1; /* Fixed covariate */
                   1359: #define VTYPE 2; /* Varying covariate (loop in wave) */
                   1360: #define ATYPE 2; /* Age product covariate (loop in dh within wave)*/
                   1361: 
                   1362: struct kmodel{
                   1363:        int maintype; /* main type */
                   1364:        int subtype; /* subtype */
                   1365: };
                   1366: struct kmodel modell[NCOVMAX];
                   1367: 
1.143     brouard  1368: double ftol=FTOL; /**< Tolerance for computing Max Likelihood */
                   1369: double ftolhess; /**< Tolerance for computing hessian */
1.126     brouard  1370: 
                   1371: /**************** split *************************/
                   1372: static int split( char *path, char *dirc, char *name, char *ext, char *finame )
                   1373: {
                   1374:   /* From a file name with (full) path (either Unix or Windows) we extract the directory (dirc)
                   1375:      the name of the file (name), its extension only (ext) and its first part of the name (finame)
                   1376:   */ 
                   1377:   char *ss;                            /* pointer */
1.186     brouard  1378:   int  l1=0, l2=0;                             /* length counters */
1.126     brouard  1379: 
                   1380:   l1 = strlen(path );                  /* length of path */
                   1381:   if ( l1 == 0 ) return( GLOCK_ERROR_NOPATH );
                   1382:   ss= strrchr( path, DIRSEPARATOR );           /* find last / */
                   1383:   if ( ss == NULL ) {                  /* no directory, so determine current directory */
                   1384:     strcpy( name, path );              /* we got the fullname name because no directory */
                   1385:     /*if(strrchr(path, ODIRSEPARATOR )==NULL)
                   1386:       printf("Warning you should use %s as a separator\n",DIRSEPARATOR);*/
                   1387:     /* get current working directory */
                   1388:     /*    extern  char* getcwd ( char *buf , int len);*/
1.184     brouard  1389: #ifdef WIN32
                   1390:     if (_getcwd( dirc, FILENAME_MAX ) == NULL ) {
                   1391: #else
                   1392:        if (getcwd(dirc, FILENAME_MAX) == NULL) {
                   1393: #endif
1.126     brouard  1394:       return( GLOCK_ERROR_GETCWD );
                   1395:     }
                   1396:     /* got dirc from getcwd*/
                   1397:     printf(" DIRC = %s \n",dirc);
1.205     brouard  1398:   } else {                             /* strip directory from path */
1.126     brouard  1399:     ss++;                              /* after this, the filename */
                   1400:     l2 = strlen( ss );                 /* length of filename */
                   1401:     if ( l2 == 0 ) return( GLOCK_ERROR_NOPATH );
                   1402:     strcpy( name, ss );                /* save file name */
                   1403:     strncpy( dirc, path, l1 - l2 );    /* now the directory */
1.186     brouard  1404:     dirc[l1-l2] = '\0';                        /* add zero */
1.126     brouard  1405:     printf(" DIRC2 = %s \n",dirc);
                   1406:   }
                   1407:   /* We add a separator at the end of dirc if not exists */
                   1408:   l1 = strlen( dirc );                 /* length of directory */
                   1409:   if( dirc[l1-1] != DIRSEPARATOR ){
                   1410:     dirc[l1] =  DIRSEPARATOR;
                   1411:     dirc[l1+1] = 0; 
                   1412:     printf(" DIRC3 = %s \n",dirc);
                   1413:   }
                   1414:   ss = strrchr( name, '.' );           /* find last / */
                   1415:   if (ss >0){
                   1416:     ss++;
                   1417:     strcpy(ext,ss);                    /* save extension */
                   1418:     l1= strlen( name);
                   1419:     l2= strlen(ss)+1;
                   1420:     strncpy( finame, name, l1-l2);
                   1421:     finame[l1-l2]= 0;
                   1422:   }
                   1423: 
                   1424:   return( 0 );                         /* we're done */
                   1425: }
                   1426: 
                   1427: 
                   1428: /******************************************/
                   1429: 
                   1430: void replace_back_to_slash(char *s, char*t)
                   1431: {
                   1432:   int i;
                   1433:   int lg=0;
                   1434:   i=0;
                   1435:   lg=strlen(t);
                   1436:   for(i=0; i<= lg; i++) {
                   1437:     (s[i] = t[i]);
                   1438:     if (t[i]== '\\') s[i]='/';
                   1439:   }
                   1440: }
                   1441: 
1.132     brouard  1442: char *trimbb(char *out, char *in)
1.137     brouard  1443: { /* Trim multiple blanks in line but keeps first blanks if line starts with blanks */
1.132     brouard  1444:   char *s;
                   1445:   s=out;
                   1446:   while (*in != '\0'){
1.137     brouard  1447:     while( *in == ' ' && *(in+1) == ' '){ /* && *(in+1) != '\0'){*/
1.132     brouard  1448:       in++;
                   1449:     }
                   1450:     *out++ = *in++;
                   1451:   }
                   1452:   *out='\0';
                   1453:   return s;
                   1454: }
                   1455: 
1.187     brouard  1456: /* char *substrchaine(char *out, char *in, char *chain) */
                   1457: /* { */
                   1458: /*   /\* Substract chain 'chain' from 'in', return and output 'out' *\/ */
                   1459: /*   char *s, *t; */
                   1460: /*   t=in;s=out; */
                   1461: /*   while ((*in != *chain) && (*in != '\0')){ */
                   1462: /*     *out++ = *in++; */
                   1463: /*   } */
                   1464: 
                   1465: /*   /\* *in matches *chain *\/ */
                   1466: /*   while ((*in++ == *chain++) && (*in != '\0')){ */
                   1467: /*     printf("*in = %c, *out= %c *chain= %c \n", *in, *out, *chain);  */
                   1468: /*   } */
                   1469: /*   in--; chain--; */
                   1470: /*   while ( (*in != '\0')){ */
                   1471: /*     printf("Bef *in = %c, *out= %c *chain= %c \n", *in, *out, *chain);  */
                   1472: /*     *out++ = *in++; */
                   1473: /*     printf("Aft *in = %c, *out= %c *chain= %c \n", *in, *out, *chain);  */
                   1474: /*   } */
                   1475: /*   *out='\0'; */
                   1476: /*   out=s; */
                   1477: /*   return out; */
                   1478: /* } */
                   1479: char *substrchaine(char *out, char *in, char *chain)
                   1480: {
                   1481:   /* Substract chain 'chain' from 'in', return and output 'out' */
                   1482:   /* in="V1+V1*age+age*age+V2", chain="age*age" */
                   1483: 
                   1484:   char *strloc;
                   1485: 
                   1486:   strcpy (out, in); 
                   1487:   strloc = strstr(out, chain); /* strloc points to out at age*age+V2 */
                   1488:   printf("Bef strloc=%s chain=%s out=%s \n", strloc, chain, out);
                   1489:   if(strloc != NULL){ 
                   1490:     /* will affect out */ /* strloc+strlenc(chain)=+V2 */ /* Will also work in Unicode */
                   1491:     memmove(strloc,strloc+strlen(chain), strlen(strloc+strlen(chain))+1);
                   1492:     /* strcpy (strloc, strloc +strlen(chain));*/
                   1493:   }
                   1494:   printf("Aft strloc=%s chain=%s in=%s out=%s \n", strloc, chain, in, out);
                   1495:   return out;
                   1496: }
                   1497: 
                   1498: 
1.145     brouard  1499: char *cutl(char *blocc, char *alocc, char *in, char occ)
                   1500: {
1.187     brouard  1501:   /* cuts string in into blocc and alocc where blocc ends before FIRST occurence of char 'occ' 
1.145     brouard  1502:      and alocc starts after first occurence of char 'occ' : ex cutv(blocc,alocc,"abcdef2ghi2j",'2')
1.187     brouard  1503:      gives blocc="abcdef" and alocc="ghi2j".
1.145     brouard  1504:      If occ is not found blocc is null and alocc is equal to in. Returns blocc
                   1505:   */
1.160     brouard  1506:   char *s, *t;
1.145     brouard  1507:   t=in;s=in;
                   1508:   while ((*in != occ) && (*in != '\0')){
                   1509:     *alocc++ = *in++;
                   1510:   }
                   1511:   if( *in == occ){
                   1512:     *(alocc)='\0';
                   1513:     s=++in;
                   1514:   }
                   1515:  
                   1516:   if (s == t) {/* occ not found */
                   1517:     *(alocc-(in-s))='\0';
                   1518:     in=s;
                   1519:   }
                   1520:   while ( *in != '\0'){
                   1521:     *blocc++ = *in++;
                   1522:   }
                   1523: 
                   1524:   *blocc='\0';
                   1525:   return t;
                   1526: }
1.137     brouard  1527: char *cutv(char *blocc, char *alocc, char *in, char occ)
                   1528: {
1.187     brouard  1529:   /* cuts string in into blocc and alocc where blocc ends before LAST occurence of char 'occ' 
1.137     brouard  1530:      and alocc starts after last occurence of char 'occ' : ex cutv(blocc,alocc,"abcdef2ghi2j",'2')
                   1531:      gives blocc="abcdef2ghi" and alocc="j".
                   1532:      If occ is not found blocc is null and alocc is equal to in. Returns alocc
                   1533:   */
                   1534:   char *s, *t;
                   1535:   t=in;s=in;
                   1536:   while (*in != '\0'){
                   1537:     while( *in == occ){
                   1538:       *blocc++ = *in++;
                   1539:       s=in;
                   1540:     }
                   1541:     *blocc++ = *in++;
                   1542:   }
                   1543:   if (s == t) /* occ not found */
                   1544:     *(blocc-(in-s))='\0';
                   1545:   else
                   1546:     *(blocc-(in-s)-1)='\0';
                   1547:   in=s;
                   1548:   while ( *in != '\0'){
                   1549:     *alocc++ = *in++;
                   1550:   }
                   1551: 
                   1552:   *alocc='\0';
                   1553:   return s;
                   1554: }
                   1555: 
1.126     brouard  1556: int nbocc(char *s, char occ)
                   1557: {
                   1558:   int i,j=0;
                   1559:   int lg=20;
                   1560:   i=0;
                   1561:   lg=strlen(s);
                   1562:   for(i=0; i<= lg; i++) {
1.234     brouard  1563:     if  (s[i] == occ ) j++;
1.126     brouard  1564:   }
                   1565:   return j;
                   1566: }
                   1567: 
1.137     brouard  1568: /* void cutv(char *u,char *v, char*t, char occ) */
                   1569: /* { */
                   1570: /*   /\* cuts string t into u and v where u ends before last occurence of char 'occ'  */
                   1571: /*      and v starts after last occurence of char 'occ' : ex cutv(u,v,"abcdef2ghi2j",'2') */
                   1572: /*      gives u="abcdef2ghi" and v="j" *\/ */
                   1573: /*   int i,lg,j,p=0; */
                   1574: /*   i=0; */
                   1575: /*   lg=strlen(t); */
                   1576: /*   for(j=0; j<=lg-1; j++) { */
                   1577: /*     if((t[j]!= occ) && (t[j+1]== occ)) p=j+1; */
                   1578: /*   } */
1.126     brouard  1579: 
1.137     brouard  1580: /*   for(j=0; j<p; j++) { */
                   1581: /*     (u[j] = t[j]); */
                   1582: /*   } */
                   1583: /*      u[p]='\0'; */
1.126     brouard  1584: 
1.137     brouard  1585: /*    for(j=0; j<= lg; j++) { */
                   1586: /*     if (j>=(p+1))(v[j-p-1] = t[j]); */
                   1587: /*   } */
                   1588: /* } */
1.126     brouard  1589: 
1.160     brouard  1590: #ifdef _WIN32
                   1591: char * strsep(char **pp, const char *delim)
                   1592: {
                   1593:   char *p, *q;
                   1594:          
                   1595:   if ((p = *pp) == NULL)
                   1596:     return 0;
                   1597:   if ((q = strpbrk (p, delim)) != NULL)
                   1598:   {
                   1599:     *pp = q + 1;
                   1600:     *q = '\0';
                   1601:   }
                   1602:   else
                   1603:     *pp = 0;
                   1604:   return p;
                   1605: }
                   1606: #endif
                   1607: 
1.126     brouard  1608: /********************** nrerror ********************/
                   1609: 
                   1610: void nrerror(char error_text[])
                   1611: {
                   1612:   fprintf(stderr,"ERREUR ...\n");
                   1613:   fprintf(stderr,"%s\n",error_text);
                   1614:   exit(EXIT_FAILURE);
                   1615: }
                   1616: /*********************** vector *******************/
                   1617: double *vector(int nl, int nh)
                   1618: {
                   1619:   double *v;
                   1620:   v=(double *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(double)));
                   1621:   if (!v) nrerror("allocation failure in vector");
                   1622:   return v-nl+NR_END;
                   1623: }
                   1624: 
                   1625: /************************ free vector ******************/
                   1626: void free_vector(double*v, int nl, int nh)
                   1627: {
                   1628:   free((FREE_ARG)(v+nl-NR_END));
                   1629: }
                   1630: 
                   1631: /************************ivector *******************************/
                   1632: int *ivector(long nl,long nh)
                   1633: {
                   1634:   int *v;
                   1635:   v=(int *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(int)));
                   1636:   if (!v) nrerror("allocation failure in ivector");
                   1637:   return v-nl+NR_END;
                   1638: }
                   1639: 
                   1640: /******************free ivector **************************/
                   1641: void free_ivector(int *v, long nl, long nh)
                   1642: {
                   1643:   free((FREE_ARG)(v+nl-NR_END));
                   1644: }
                   1645: 
                   1646: /************************lvector *******************************/
                   1647: long *lvector(long nl,long nh)
                   1648: {
                   1649:   long *v;
                   1650:   v=(long *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(long)));
                   1651:   if (!v) nrerror("allocation failure in ivector");
                   1652:   return v-nl+NR_END;
                   1653: }
                   1654: 
                   1655: /******************free lvector **************************/
                   1656: void free_lvector(long *v, long nl, long nh)
                   1657: {
                   1658:   free((FREE_ARG)(v+nl-NR_END));
                   1659: }
                   1660: 
                   1661: /******************* imatrix *******************************/
                   1662: int **imatrix(long nrl, long nrh, long ncl, long nch) 
                   1663:      /* allocate a int matrix with subscript range m[nrl..nrh][ncl..nch] */ 
                   1664: { 
                   1665:   long i, nrow=nrh-nrl+1,ncol=nch-ncl+1; 
                   1666:   int **m; 
                   1667:   
                   1668:   /* allocate pointers to rows */ 
                   1669:   m=(int **) malloc((size_t)((nrow+NR_END)*sizeof(int*))); 
                   1670:   if (!m) nrerror("allocation failure 1 in matrix()"); 
                   1671:   m += NR_END; 
                   1672:   m -= nrl; 
                   1673:   
                   1674:   
                   1675:   /* allocate rows and set pointers to them */ 
                   1676:   m[nrl]=(int *) malloc((size_t)((nrow*ncol+NR_END)*sizeof(int))); 
                   1677:   if (!m[nrl]) nrerror("allocation failure 2 in matrix()"); 
                   1678:   m[nrl] += NR_END; 
                   1679:   m[nrl] -= ncl; 
                   1680:   
                   1681:   for(i=nrl+1;i<=nrh;i++) m[i]=m[i-1]+ncol; 
                   1682:   
                   1683:   /* return pointer to array of pointers to rows */ 
                   1684:   return m; 
                   1685: } 
                   1686: 
                   1687: /****************** free_imatrix *************************/
                   1688: void free_imatrix(m,nrl,nrh,ncl,nch)
                   1689:       int **m;
                   1690:       long nch,ncl,nrh,nrl; 
                   1691:      /* free an int matrix allocated by imatrix() */ 
                   1692: { 
                   1693:   free((FREE_ARG) (m[nrl]+ncl-NR_END)); 
                   1694:   free((FREE_ARG) (m+nrl-NR_END)); 
                   1695: } 
                   1696: 
                   1697: /******************* matrix *******************************/
                   1698: double **matrix(long nrl, long nrh, long ncl, long nch)
                   1699: {
                   1700:   long i, nrow=nrh-nrl+1, ncol=nch-ncl+1;
                   1701:   double **m;
                   1702: 
                   1703:   m=(double **) malloc((size_t)((nrow+NR_END)*sizeof(double*)));
                   1704:   if (!m) nrerror("allocation failure 1 in matrix()");
                   1705:   m += NR_END;
                   1706:   m -= nrl;
                   1707: 
                   1708:   m[nrl]=(double *) malloc((size_t)((nrow*ncol+NR_END)*sizeof(double)));
                   1709:   if (!m[nrl]) nrerror("allocation failure 2 in matrix()");
                   1710:   m[nrl] += NR_END;
                   1711:   m[nrl] -= ncl;
                   1712: 
                   1713:   for (i=nrl+1; i<=nrh; i++) m[i]=m[i-1]+ncol;
                   1714:   return m;
1.145     brouard  1715:   /* print *(*(m+1)+70) or print m[1][70]; print m+1 or print &(m[1]) or &(m[1][0])
                   1716: m[i] = address of ith row of the table. &(m[i]) is its value which is another adress
                   1717: that of m[i][0]. In order to get the value p m[i][0] but it is unitialized.
1.126     brouard  1718:    */
                   1719: }
                   1720: 
                   1721: /*************************free matrix ************************/
                   1722: void free_matrix(double **m, long nrl, long nrh, long ncl, long nch)
                   1723: {
                   1724:   free((FREE_ARG)(m[nrl]+ncl-NR_END));
                   1725:   free((FREE_ARG)(m+nrl-NR_END));
                   1726: }
                   1727: 
                   1728: /******************* ma3x *******************************/
                   1729: double ***ma3x(long nrl, long nrh, long ncl, long nch, long nll, long nlh)
                   1730: {
                   1731:   long i, j, nrow=nrh-nrl+1, ncol=nch-ncl+1, nlay=nlh-nll+1;
                   1732:   double ***m;
                   1733: 
                   1734:   m=(double ***) malloc((size_t)((nrow+NR_END)*sizeof(double*)));
                   1735:   if (!m) nrerror("allocation failure 1 in matrix()");
                   1736:   m += NR_END;
                   1737:   m -= nrl;
                   1738: 
                   1739:   m[nrl]=(double **) malloc((size_t)((nrow*ncol+NR_END)*sizeof(double)));
                   1740:   if (!m[nrl]) nrerror("allocation failure 2 in matrix()");
                   1741:   m[nrl] += NR_END;
                   1742:   m[nrl] -= ncl;
                   1743: 
                   1744:   for (i=nrl+1; i<=nrh; i++) m[i]=m[i-1]+ncol;
                   1745: 
                   1746:   m[nrl][ncl]=(double *) malloc((size_t)((nrow*ncol*nlay+NR_END)*sizeof(double)));
                   1747:   if (!m[nrl][ncl]) nrerror("allocation failure 3 in matrix()");
                   1748:   m[nrl][ncl] += NR_END;
                   1749:   m[nrl][ncl] -= nll;
                   1750:   for (j=ncl+1; j<=nch; j++) 
                   1751:     m[nrl][j]=m[nrl][j-1]+nlay;
                   1752:   
                   1753:   for (i=nrl+1; i<=nrh; i++) {
                   1754:     m[i][ncl]=m[i-1l][ncl]+ncol*nlay;
                   1755:     for (j=ncl+1; j<=nch; j++) 
                   1756:       m[i][j]=m[i][j-1]+nlay;
                   1757:   }
                   1758:   return m; 
                   1759:   /*  gdb: p *(m+1) <=> p m[1] and p (m+1) <=> p (m+1) <=> p &(m[1])
                   1760:            &(m[i][j][k]) <=> *((*(m+i) + j)+k)
                   1761:   */
                   1762: }
                   1763: 
                   1764: /*************************free ma3x ************************/
                   1765: void free_ma3x(double ***m, long nrl, long nrh, long ncl, long nch,long nll, long nlh)
                   1766: {
                   1767:   free((FREE_ARG)(m[nrl][ncl]+ nll-NR_END));
                   1768:   free((FREE_ARG)(m[nrl]+ncl-NR_END));
                   1769:   free((FREE_ARG)(m+nrl-NR_END));
                   1770: }
                   1771: 
                   1772: /*************** function subdirf ***********/
                   1773: char *subdirf(char fileres[])
                   1774: {
                   1775:   /* Caution optionfilefiname is hidden */
                   1776:   strcpy(tmpout,optionfilefiname);
                   1777:   strcat(tmpout,"/"); /* Add to the right */
                   1778:   strcat(tmpout,fileres);
                   1779:   return tmpout;
                   1780: }
                   1781: 
                   1782: /*************** function subdirf2 ***********/
                   1783: char *subdirf2(char fileres[], char *preop)
                   1784: {
                   1785:   
                   1786:   /* Caution optionfilefiname is hidden */
                   1787:   strcpy(tmpout,optionfilefiname);
                   1788:   strcat(tmpout,"/");
                   1789:   strcat(tmpout,preop);
                   1790:   strcat(tmpout,fileres);
                   1791:   return tmpout;
                   1792: }
                   1793: 
                   1794: /*************** function subdirf3 ***********/
                   1795: char *subdirf3(char fileres[], char *preop, char *preop2)
                   1796: {
                   1797:   
                   1798:   /* Caution optionfilefiname is hidden */
                   1799:   strcpy(tmpout,optionfilefiname);
                   1800:   strcat(tmpout,"/");
                   1801:   strcat(tmpout,preop);
                   1802:   strcat(tmpout,preop2);
                   1803:   strcat(tmpout,fileres);
                   1804:   return tmpout;
                   1805: }
1.213     brouard  1806:  
                   1807: /*************** function subdirfext ***********/
                   1808: char *subdirfext(char fileres[], char *preop, char *postop)
                   1809: {
                   1810:   
                   1811:   strcpy(tmpout,preop);
                   1812:   strcat(tmpout,fileres);
                   1813:   strcat(tmpout,postop);
                   1814:   return tmpout;
                   1815: }
1.126     brouard  1816: 
1.213     brouard  1817: /*************** function subdirfext3 ***********/
                   1818: char *subdirfext3(char fileres[], char *preop, char *postop)
                   1819: {
                   1820:   
                   1821:   /* Caution optionfilefiname is hidden */
                   1822:   strcpy(tmpout,optionfilefiname);
                   1823:   strcat(tmpout,"/");
                   1824:   strcat(tmpout,preop);
                   1825:   strcat(tmpout,fileres);
                   1826:   strcat(tmpout,postop);
                   1827:   return tmpout;
                   1828: }
                   1829:  
1.162     brouard  1830: char *asc_diff_time(long time_sec, char ascdiff[])
                   1831: {
                   1832:   long sec_left, days, hours, minutes;
                   1833:   days = (time_sec) / (60*60*24);
                   1834:   sec_left = (time_sec) % (60*60*24);
                   1835:   hours = (sec_left) / (60*60) ;
                   1836:   sec_left = (sec_left) %(60*60);
                   1837:   minutes = (sec_left) /60;
                   1838:   sec_left = (sec_left) % (60);
                   1839:   sprintf(ascdiff,"%ld day(s) %ld hour(s) %ld minute(s) %ld second(s)",days, hours, minutes, sec_left);  
                   1840:   return ascdiff;
                   1841: }
                   1842: 
1.126     brouard  1843: /***************** f1dim *************************/
                   1844: extern int ncom; 
                   1845: extern double *pcom,*xicom;
                   1846: extern double (*nrfunc)(double []); 
                   1847:  
                   1848: double f1dim(double x) 
                   1849: { 
                   1850:   int j; 
                   1851:   double f;
                   1852:   double *xt; 
                   1853:  
                   1854:   xt=vector(1,ncom); 
                   1855:   for (j=1;j<=ncom;j++) xt[j]=pcom[j]+x*xicom[j]; 
                   1856:   f=(*nrfunc)(xt); 
                   1857:   free_vector(xt,1,ncom); 
                   1858:   return f; 
                   1859: } 
                   1860: 
                   1861: /*****************brent *************************/
                   1862: double brent(double ax, double bx, double cx, double (*f)(double), double tol,         double *xmin) 
1.187     brouard  1863: {
                   1864:   /* Given a function f, and given a bracketing triplet of abscissas ax, bx, cx (such that bx is
                   1865:    * between ax and cx, and f(bx) is less than both f(ax) and f(cx) ), this routine isolates
                   1866:    * the minimum to a fractional precision of about tol using Brent’s method. The abscissa of
                   1867:    * the minimum is returned as xmin, and the minimum function value is returned as brent , the
                   1868:    * returned function value. 
                   1869:   */
1.126     brouard  1870:   int iter; 
                   1871:   double a,b,d,etemp;
1.159     brouard  1872:   double fu=0,fv,fw,fx;
1.164     brouard  1873:   double ftemp=0.;
1.126     brouard  1874:   double p,q,r,tol1,tol2,u,v,w,x,xm; 
                   1875:   double e=0.0; 
                   1876:  
                   1877:   a=(ax < cx ? ax : cx); 
                   1878:   b=(ax > cx ? ax : cx); 
                   1879:   x=w=v=bx; 
                   1880:   fw=fv=fx=(*f)(x); 
                   1881:   for (iter=1;iter<=ITMAX;iter++) { 
                   1882:     xm=0.5*(a+b); 
                   1883:     tol2=2.0*(tol1=tol*fabs(x)+ZEPS); 
                   1884:     /*         if (2.0*fabs(fp-(*fret)) <= ftol*(fabs(fp)+fabs(*fret)))*/
                   1885:     printf(".");fflush(stdout);
                   1886:     fprintf(ficlog,".");fflush(ficlog);
1.162     brouard  1887: #ifdef DEBUGBRENT
1.126     brouard  1888:     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);
                   1889:     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);
                   1890:     /*         if ((fabs(x-xm) <= (tol2-0.5*(b-a)))||(2.0*fabs(fu-ftemp) <= ftol*1.e-2*(fabs(fu)+fabs(ftemp)))) { */
                   1891: #endif
                   1892:     if (fabs(x-xm) <= (tol2-0.5*(b-a))){ 
                   1893:       *xmin=x; 
                   1894:       return fx; 
                   1895:     } 
                   1896:     ftemp=fu;
                   1897:     if (fabs(e) > tol1) { 
                   1898:       r=(x-w)*(fx-fv); 
                   1899:       q=(x-v)*(fx-fw); 
                   1900:       p=(x-v)*q-(x-w)*r; 
                   1901:       q=2.0*(q-r); 
                   1902:       if (q > 0.0) p = -p; 
                   1903:       q=fabs(q); 
                   1904:       etemp=e; 
                   1905:       e=d; 
                   1906:       if (fabs(p) >= fabs(0.5*q*etemp) || p <= q*(a-x) || p >= q*(b-x)) 
1.224     brouard  1907:                                d=CGOLD*(e=(x >= xm ? a-x : b-x)); 
1.126     brouard  1908:       else { 
1.224     brouard  1909:                                d=p/q; 
                   1910:                                u=x+d; 
                   1911:                                if (u-a < tol2 || b-u < tol2) 
                   1912:                                        d=SIGN(tol1,xm-x); 
1.126     brouard  1913:       } 
                   1914:     } else { 
                   1915:       d=CGOLD*(e=(x >= xm ? a-x : b-x)); 
                   1916:     } 
                   1917:     u=(fabs(d) >= tol1 ? x+d : x+SIGN(tol1,d)); 
                   1918:     fu=(*f)(u); 
                   1919:     if (fu <= fx) { 
                   1920:       if (u >= x) a=x; else b=x; 
                   1921:       SHFT(v,w,x,u) 
1.183     brouard  1922:       SHFT(fv,fw,fx,fu) 
                   1923:     } else { 
                   1924:       if (u < x) a=u; else b=u; 
                   1925:       if (fu <= fw || w == x) { 
1.224     brouard  1926:                                v=w; 
                   1927:                                w=u; 
                   1928:                                fv=fw; 
                   1929:                                fw=fu; 
1.183     brouard  1930:       } else if (fu <= fv || v == x || v == w) { 
1.224     brouard  1931:                                v=u; 
                   1932:                                fv=fu; 
1.183     brouard  1933:       } 
                   1934:     } 
1.126     brouard  1935:   } 
                   1936:   nrerror("Too many iterations in brent"); 
                   1937:   *xmin=x; 
                   1938:   return fx; 
                   1939: } 
                   1940: 
                   1941: /****************** mnbrak ***********************/
                   1942: 
                   1943: void mnbrak(double *ax, double *bx, double *cx, double *fa, double *fb, double *fc, 
                   1944:            double (*func)(double)) 
1.183     brouard  1945: { /* Given a function func , and given distinct initial points ax and bx , this routine searches in
                   1946: the downhill direction (defined by the function as evaluated at the initial points) and returns
                   1947: new points ax , bx , cx that bracket a minimum of the function. Also returned are the function
                   1948: values at the three points, fa, fb , and fc such that fa > fb and fb < fc.
                   1949:    */
1.126     brouard  1950:   double ulim,u,r,q, dum;
                   1951:   double fu; 
1.187     brouard  1952: 
                   1953:   double scale=10.;
                   1954:   int iterscale=0;
                   1955: 
                   1956:   *fa=(*func)(*ax); /*  xta[j]=pcom[j]+(*ax)*xicom[j]; fa=f(xta[j])*/
                   1957:   *fb=(*func)(*bx); /*  xtb[j]=pcom[j]+(*bx)*xicom[j]; fb=f(xtb[j]) */
                   1958: 
                   1959: 
                   1960:   /* while(*fb != *fb){ /\* *ax should be ok, reducing distance to *ax *\/ */
                   1961:   /*   printf("Warning mnbrak *fb = %lf, *bx=%lf *ax=%lf *fa==%lf iter=%d\n",*fb, *bx, *ax, *fa, iterscale++); */
                   1962:   /*   *bx = *ax - (*ax - *bx)/scale; */
                   1963:   /*   *fb=(*func)(*bx);  /\*  xtb[j]=pcom[j]+(*bx)*xicom[j]; fb=f(xtb[j]) *\/ */
                   1964:   /* } */
                   1965: 
1.126     brouard  1966:   if (*fb > *fa) { 
                   1967:     SHFT(dum,*ax,*bx,dum) 
1.183     brouard  1968:     SHFT(dum,*fb,*fa,dum) 
                   1969:   } 
1.126     brouard  1970:   *cx=(*bx)+GOLD*(*bx-*ax); 
                   1971:   *fc=(*func)(*cx); 
1.183     brouard  1972: #ifdef DEBUG
1.224     brouard  1973:   printf("mnbrak0 a=%lf *fa=%lf, b=%lf *fb=%lf, c=%lf *fc=%lf\n",*ax,*fa,*bx,*fb,*cx, *fc);
                   1974:   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  1975: #endif
1.224     brouard  1976:   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  1977:     r=(*bx-*ax)*(*fb-*fc); 
1.224     brouard  1978:     q=(*bx-*cx)*(*fb-*fa); /* What if fa=inf */
1.126     brouard  1979:     u=(*bx)-((*bx-*cx)*q-(*bx-*ax)*r)/ 
1.183     brouard  1980:       (2.0*SIGN(FMAX(fabs(q-r),TINY),q-r)); /* Minimum abscissa of a parabolic estimated from (a,fa), (b,fb) and (c,fc). */
                   1981:     ulim=(*bx)+GLIMIT*(*cx-*bx); /* Maximum abscissa where function should be evaluated */
                   1982:     if ((*bx-u)*(u-*cx) > 0.0) { /* if u_p is between b and c */
1.126     brouard  1983:       fu=(*func)(u); 
1.163     brouard  1984: #ifdef DEBUG
                   1985:       /* f(x)=A(x-u)**2+f(u) */
                   1986:       double A, fparabu; 
                   1987:       A= (*fb - *fa)/(*bx-*ax)/(*bx+*ax-2*u);
                   1988:       fparabu= *fa - A*(*ax-u)*(*ax-u);
1.224     brouard  1989:       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);
                   1990:       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  1991:       /* And thus,it can be that fu > *fc even if fparabu < *fc */
                   1992:       /* mnbrak (*ax=7.666299858533, *fa=299039.693133272231), (*bx=8.595447774979, *fb=298976.598289369489),
                   1993:         (*cx=10.098840694817, *fc=298946.631474258087),  (*u=9.852501168332, fu=298948.773013752128, fparabu=298945.434711494134) */
                   1994:       /* In that case, there is no bracket in the output! Routine is wrong with many consequences.*/
1.163     brouard  1995: #endif 
1.184     brouard  1996: #ifdef MNBRAKORIGINAL
1.183     brouard  1997: #else
1.191     brouard  1998: /*       if (fu > *fc) { */
                   1999: /* #ifdef DEBUG */
                   2000: /*       printf("mnbrak4  fu > fc \n"); */
                   2001: /*       fprintf(ficlog, "mnbrak4 fu > fc\n"); */
                   2002: /* #endif */
                   2003: /*     /\* 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 *\\/  *\/ */
                   2004: /*     /\* SHFT(*fa,*fc,fu,*fc) /\\* (b, u, c) is a bracket while test fb > fc will be fu > fc  will exit *\\/ *\/ */
                   2005: /*     dum=u; /\* Shifting c and u *\/ */
                   2006: /*     u = *cx; */
                   2007: /*     *cx = dum; */
                   2008: /*     dum = fu; */
                   2009: /*     fu = *fc; */
                   2010: /*     *fc =dum; */
                   2011: /*       } else { /\* end *\/ */
                   2012: /* #ifdef DEBUG */
                   2013: /*       printf("mnbrak3  fu < fc \n"); */
                   2014: /*       fprintf(ficlog, "mnbrak3 fu < fc\n"); */
                   2015: /* #endif */
                   2016: /*     dum=u; /\* Shifting c and u *\/ */
                   2017: /*     u = *cx; */
                   2018: /*     *cx = dum; */
                   2019: /*     dum = fu; */
                   2020: /*     fu = *fc; */
                   2021: /*     *fc =dum; */
                   2022: /*       } */
1.224     brouard  2023: #ifdef DEBUGMNBRAK
                   2024:                 double A, fparabu; 
                   2025:      A= (*fb - *fa)/(*bx-*ax)/(*bx+*ax-2*u);
                   2026:      fparabu= *fa - A*(*ax-u)*(*ax-u);
                   2027:      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);
                   2028:      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  2029: #endif
1.191     brouard  2030:       dum=u; /* Shifting c and u */
                   2031:       u = *cx;
                   2032:       *cx = dum;
                   2033:       dum = fu;
                   2034:       fu = *fc;
                   2035:       *fc =dum;
1.183     brouard  2036: #endif
1.162     brouard  2037:     } else if ((*cx-u)*(u-ulim) > 0.0) { /* u is after c but before ulim */
1.183     brouard  2038: #ifdef DEBUG
1.224     brouard  2039:       printf("\nmnbrak2  u=%lf after c=%lf but before ulim\n",u,*cx);
                   2040:       fprintf(ficlog,"\nmnbrak2  u=%lf after c=%lf but before ulim\n",u,*cx);
1.183     brouard  2041: #endif
1.126     brouard  2042:       fu=(*func)(u); 
                   2043:       if (fu < *fc) { 
1.183     brouard  2044: #ifdef DEBUG
1.224     brouard  2045:                                printf("\nmnbrak2  u=%lf after c=%lf but before ulim=%lf AND fu=%lf < %lf=fc\n",u,*cx,ulim,fu, *fc);
                   2046:                          fprintf(ficlog,"\nmnbrak2  u=%lf after c=%lf but before ulim=%lf AND fu=%lf < %lf=fc\n",u,*cx,ulim,fu, *fc);
                   2047: #endif
                   2048:                          SHFT(*bx,*cx,u,*cx+GOLD*(*cx-*bx)) 
                   2049:                                SHFT(*fb,*fc,fu,(*func)(u)) 
                   2050: #ifdef DEBUG
                   2051:                                        printf("\nmnbrak2 shift GOLD c=%lf",*cx+GOLD*(*cx-*bx));
1.183     brouard  2052: #endif
                   2053:       } 
1.162     brouard  2054:     } else if ((u-ulim)*(ulim-*cx) >= 0.0) { /* u outside ulim (verifying that ulim is beyond c) */
1.183     brouard  2055: #ifdef DEBUG
1.224     brouard  2056:       printf("\nmnbrak2  u=%lf outside ulim=%lf (verifying that ulim is beyond c=%lf)\n",u,ulim,*cx);
                   2057:       fprintf(ficlog,"\nmnbrak2  u=%lf outside ulim=%lf (verifying that ulim is beyond c=%lf)\n",u,ulim,*cx);
1.183     brouard  2058: #endif
1.126     brouard  2059:       u=ulim; 
                   2060:       fu=(*func)(u); 
1.183     brouard  2061:     } else { /* u could be left to b (if r > q parabola has a maximum) */
                   2062: #ifdef DEBUG
1.224     brouard  2063:       printf("\nmnbrak2  u=%lf could be left to b=%lf (if r=%lf > q=%lf parabola has a maximum)\n",u,*bx,r,q);
                   2064:       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  2065: #endif
1.126     brouard  2066:       u=(*cx)+GOLD*(*cx-*bx); 
                   2067:       fu=(*func)(u); 
1.224     brouard  2068: #ifdef DEBUG
                   2069:       printf("\nmnbrak2 new u=%lf fu=%lf shifted gold left from c=%lf and b=%lf \n",u,fu,*cx,*bx);
                   2070:       fprintf(ficlog,"\nmnbrak2 new u=%lf fu=%lf shifted gold left from c=%lf and b=%lf \n",u,fu,*cx,*bx);
                   2071: #endif
1.183     brouard  2072:     } /* end tests */
1.126     brouard  2073:     SHFT(*ax,*bx,*cx,u) 
1.183     brouard  2074:     SHFT(*fa,*fb,*fc,fu) 
                   2075: #ifdef DEBUG
1.224     brouard  2076:       printf("\nmnbrak2 shift (*ax=%.12f, *fa=%.12lf), (*bx=%.12f, *fb=%.12lf), (*cx=%.12f, *fc=%.12lf)\n",*ax,*fa,*bx,*fb,*cx,*fc);
                   2077:       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  2078: #endif
                   2079:   } /* 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  2080: } 
                   2081: 
                   2082: /*************** linmin ************************/
1.162     brouard  2083: /* Given an n -dimensional point p[1..n] and an n -dimensional direction xi[1..n] , moves and
                   2084: resets p to where the function func(p) takes on a minimum along the direction xi from p ,
                   2085: and replaces xi by the actual vector displacement that p was moved. Also returns as fret
                   2086: the value of func at the returned location p . This is actually all accomplished by calling the
                   2087: routines mnbrak and brent .*/
1.126     brouard  2088: int ncom; 
                   2089: double *pcom,*xicom;
                   2090: double (*nrfunc)(double []); 
                   2091:  
1.224     brouard  2092: #ifdef LINMINORIGINAL
1.126     brouard  2093: void linmin(double p[], double xi[], int n, double *fret,double (*func)(double [])) 
1.224     brouard  2094: #else
                   2095: void linmin(double p[], double xi[], int n, double *fret,double (*func)(double []), int *flat) 
                   2096: #endif
1.126     brouard  2097: { 
                   2098:   double brent(double ax, double bx, double cx, 
                   2099:               double (*f)(double), double tol, double *xmin); 
                   2100:   double f1dim(double x); 
                   2101:   void mnbrak(double *ax, double *bx, double *cx, double *fa, double *fb, 
                   2102:              double *fc, double (*func)(double)); 
                   2103:   int j; 
                   2104:   double xx,xmin,bx,ax; 
                   2105:   double fx,fb,fa;
1.187     brouard  2106: 
1.203     brouard  2107: #ifdef LINMINORIGINAL
                   2108: #else
                   2109:   double scale=10., axs, xxs; /* Scale added for infinity */
                   2110: #endif
                   2111:   
1.126     brouard  2112:   ncom=n; 
                   2113:   pcom=vector(1,n); 
                   2114:   xicom=vector(1,n); 
                   2115:   nrfunc=func; 
                   2116:   for (j=1;j<=n;j++) { 
                   2117:     pcom[j]=p[j]; 
1.202     brouard  2118:     xicom[j]=xi[j]; /* Former scale xi[j] of currrent direction i */
1.126     brouard  2119:   } 
1.187     brouard  2120: 
1.203     brouard  2121: #ifdef LINMINORIGINAL
                   2122:   xx=1.;
                   2123: #else
                   2124:   axs=0.0;
                   2125:   xxs=1.;
                   2126:   do{
                   2127:     xx= xxs;
                   2128: #endif
1.187     brouard  2129:     ax=0.;
                   2130:     mnbrak(&ax,&xx,&bx,&fa,&fx,&fb,f1dim);  /* Outputs: xtx[j]=pcom[j]+(*xx)*xicom[j]; fx=f(xtx[j]) */
                   2131:     /* brackets with inputs ax=0 and xx=1, but points, pcom=p, and directions values, xicom=xi, are sent via f1dim(x) */
                   2132:     /* 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))   */
                   2133:     /* Outputs: fa=f(p(j)) and fx=f(p(j) + xxs * xi(j) ) and f(bx)= f(p(j)+ bx* xi(j)) */
                   2134:     /* Given input ax=axs and xx=xxs, xx might be too far from ax to get a finite f(xx) */
                   2135:     /* Searches on line, outputs (ax, xx, bx) such that fx < min(fa and fb) */
                   2136:     /* 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  2137: #ifdef LINMINORIGINAL
                   2138: #else
                   2139:     if (fx != fx){
1.224     brouard  2140:                        xxs=xxs/scale; /* Trying a smaller xx, closer to initial ax=0 */
                   2141:                        printf("|");
                   2142:                        fprintf(ficlog,"|");
1.203     brouard  2143: #ifdef DEBUGLINMIN
1.224     brouard  2144:                        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  2145: #endif
                   2146:     }
1.224     brouard  2147:   }while(fx != fx && xxs > 1.e-5);
1.203     brouard  2148: #endif
                   2149:   
1.191     brouard  2150: #ifdef DEBUGLINMIN
                   2151:   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  2152:   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  2153: #endif
1.224     brouard  2154: #ifdef LINMINORIGINAL
                   2155: #else
                   2156:        if(fb == fx){ /* Flat function in the direction */
                   2157:                xmin=xx;
                   2158:     *flat=1;
                   2159:        }else{
                   2160:     *flat=0;
                   2161: #endif
                   2162:                /*Flat mnbrak2 shift (*ax=0.000000000000, *fa=51626.272983130431), (*bx=-1.618034000000, *fb=51590.149499362531), (*cx=-4.236068025156, *fc=51590.149499362531) */
1.187     brouard  2163:   *fret=brent(ax,xx,bx,f1dim,TOL,&xmin); /* Giving a bracketting triplet (ax, xx, bx), find a minimum, xmin, according to f1dim, *fret(xmin),*/
                   2164:   /* fa = f(p[j] + ax * xi[j]), fx = f(p[j] + xx * xi[j]), fb = f(p[j] + bx * xi[j]) */
                   2165:   /* fmin = f(p[j] + xmin * xi[j]) */
                   2166:   /* P+lambda n in that direction (lambdamin), with TOL between abscisses */
                   2167:   /* f1dim(xmin): for (j=1;j<=ncom;j++) xt[j]=pcom[j]+xmin*xicom[j]; */
1.126     brouard  2168: #ifdef DEBUG
1.224     brouard  2169:   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);
                   2170:   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);
                   2171: #endif
                   2172: #ifdef LINMINORIGINAL
                   2173: #else
                   2174:                        }
1.126     brouard  2175: #endif
1.191     brouard  2176: #ifdef DEBUGLINMIN
                   2177:   printf("linmin end ");
1.202     brouard  2178:   fprintf(ficlog,"linmin end ");
1.191     brouard  2179: #endif
1.126     brouard  2180:   for (j=1;j<=n;j++) { 
1.203     brouard  2181: #ifdef LINMINORIGINAL
                   2182:     xi[j] *= xmin; 
                   2183: #else
                   2184: #ifdef DEBUGLINMIN
                   2185:     if(xxs <1.0)
                   2186:       printf(" before xi[%d]=%12.8f", j,xi[j]);
                   2187: #endif
                   2188:     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) */
                   2189: #ifdef DEBUGLINMIN
                   2190:     if(xxs <1.0)
                   2191:       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 );
                   2192: #endif
                   2193: #endif
1.187     brouard  2194:     p[j] += xi[j]; /* Parameters values are updated accordingly */
1.126     brouard  2195:   } 
1.191     brouard  2196: #ifdef DEBUGLINMIN
1.203     brouard  2197:   printf("\n");
1.191     brouard  2198:   printf("Comparing last *frec(xmin=%12.8f)=%12.8f from Brent and frec(0.)=%12.8f \n", xmin, *fret, (*func)(p));
1.202     brouard  2199:   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  2200:   for (j=1;j<=n;j++) { 
1.202     brouard  2201:     printf(" xi[%d]= %14.10f p[%d]= %12.7f",j,xi[j],j,p[j]);
                   2202:     fprintf(ficlog," xi[%d]= %14.10f p[%d]= %12.7f",j,xi[j],j,p[j]);
                   2203:     if(j % ncovmodel == 0){
1.191     brouard  2204:       printf("\n");
1.202     brouard  2205:       fprintf(ficlog,"\n");
                   2206:     }
1.191     brouard  2207:   }
1.203     brouard  2208: #else
1.191     brouard  2209: #endif
1.126     brouard  2210:   free_vector(xicom,1,n); 
                   2211:   free_vector(pcom,1,n); 
                   2212: } 
                   2213: 
                   2214: 
                   2215: /*************** powell ************************/
1.162     brouard  2216: /*
                   2217: Minimization of a function func of n variables. Input consists of an initial starting point
                   2218: p[1..n] ; an initial matrix xi[1..n][1..n] , whose columns contain the initial set of di-
                   2219: rections (usually the n unit vectors); and ftol , the fractional tolerance in the function value
                   2220: such that failure to decrease by more than this amount on one iteration signals doneness. On
                   2221: output, p is set to the best point found, xi is the then-current direction set, fret is the returned
                   2222: function value at p , and iter is the number of iterations taken. The routine linmin is used.
                   2223:  */
1.224     brouard  2224: #ifdef LINMINORIGINAL
                   2225: #else
                   2226:        int *flatdir; /* Function is vanishing in that direction */
1.225     brouard  2227:        int flat=0, flatd=0; /* Function is vanishing in that direction */
1.224     brouard  2228: #endif
1.126     brouard  2229: void powell(double p[], double **xi, int n, double ftol, int *iter, double *fret, 
                   2230:            double (*func)(double [])) 
                   2231: { 
1.224     brouard  2232: #ifdef LINMINORIGINAL
                   2233:  void linmin(double p[], double xi[], int n, double *fret, 
1.126     brouard  2234:              double (*func)(double [])); 
1.224     brouard  2235: #else 
1.241     brouard  2236:  void linmin(double p[], double xi[], int n, double *fret,
                   2237:             double (*func)(double []),int *flat); 
1.224     brouard  2238: #endif
1.239     brouard  2239:  int i,ibig,j,jk,k; 
1.126     brouard  2240:   double del,t,*pt,*ptt,*xit;
1.181     brouard  2241:   double directest;
1.126     brouard  2242:   double fp,fptt;
                   2243:   double *xits;
                   2244:   int niterf, itmp;
1.224     brouard  2245: #ifdef LINMINORIGINAL
                   2246: #else
                   2247: 
                   2248:   flatdir=ivector(1,n); 
                   2249:   for (j=1;j<=n;j++) flatdir[j]=0; 
                   2250: #endif
1.126     brouard  2251: 
                   2252:   pt=vector(1,n); 
                   2253:   ptt=vector(1,n); 
                   2254:   xit=vector(1,n); 
                   2255:   xits=vector(1,n); 
                   2256:   *fret=(*func)(p); 
                   2257:   for (j=1;j<=n;j++) pt[j]=p[j]; 
1.202     brouard  2258:   rcurr_time = time(NULL);  
1.126     brouard  2259:   for (*iter=1;;++(*iter)) { 
1.187     brouard  2260:     fp=(*fret); /* From former iteration or initial value */
1.126     brouard  2261:     ibig=0; 
                   2262:     del=0.0; 
1.157     brouard  2263:     rlast_time=rcurr_time;
                   2264:     /* (void) gettimeofday(&curr_time,&tzp); */
                   2265:     rcurr_time = time(NULL);  
                   2266:     curr_time = *localtime(&rcurr_time);
                   2267:     printf("\nPowell iter=%d -2*LL=%.12f %ld sec. %ld sec.",*iter,*fret, rcurr_time-rlast_time, rcurr_time-rstart_time);fflush(stdout);
                   2268:     fprintf(ficlog,"\nPowell iter=%d -2*LL=%.12f %ld sec. %ld sec.",*iter,*fret,rcurr_time-rlast_time, rcurr_time-rstart_time); fflush(ficlog);
                   2269: /*     fprintf(ficrespow,"%d %.12f %ld",*iter,*fret,curr_time.tm_sec-start_time.tm_sec); */
1.192     brouard  2270:     for (i=1;i<=n;i++) {
1.126     brouard  2271:       fprintf(ficrespow," %.12lf", p[i]);
                   2272:     }
1.239     brouard  2273:     fprintf(ficrespow,"\n");fflush(ficrespow);
                   2274:     printf("\n#model=  1      +     age ");
                   2275:     fprintf(ficlog,"\n#model=  1      +     age ");
                   2276:     if(nagesqr==1){
1.241     brouard  2277:        printf("  + age*age  ");
                   2278:        fprintf(ficlog,"  + age*age  ");
1.239     brouard  2279:     }
                   2280:     for(j=1;j <=ncovmodel-2;j++){
                   2281:       if(Typevar[j]==0) {
                   2282:        printf("  +      V%d  ",Tvar[j]);
                   2283:        fprintf(ficlog,"  +      V%d  ",Tvar[j]);
                   2284:       }else if(Typevar[j]==1) {
                   2285:        printf("  +    V%d*age ",Tvar[j]);
                   2286:        fprintf(ficlog,"  +    V%d*age ",Tvar[j]);
                   2287:       }else if(Typevar[j]==2) {
                   2288:        printf("  +    V%d*V%d ",Tvard[Tposprod[j]][1],Tvard[Tposprod[j]][2]);
                   2289:        fprintf(ficlog,"  +    V%d*V%d ",Tvard[Tposprod[j]][1],Tvard[Tposprod[j]][2]);
                   2290:       }
                   2291:     }
1.126     brouard  2292:     printf("\n");
1.239     brouard  2293: /*     printf("12   47.0114589    0.0154322   33.2424412    0.3279905    2.3731903  */
                   2294: /* 13  -21.5392400    0.1118147    1.2680506    1.2973408   -1.0663662  */
1.126     brouard  2295:     fprintf(ficlog,"\n");
1.239     brouard  2296:     for(i=1,jk=1; i <=nlstate; i++){
                   2297:       for(k=1; k <=(nlstate+ndeath); k++){
                   2298:        if (k != i) {
                   2299:          printf("%d%d ",i,k);
                   2300:          fprintf(ficlog,"%d%d ",i,k);
                   2301:          for(j=1; j <=ncovmodel; j++){
                   2302:            printf("%12.7f ",p[jk]);
                   2303:            fprintf(ficlog,"%12.7f ",p[jk]);
                   2304:            jk++; 
                   2305:          }
                   2306:          printf("\n");
                   2307:          fprintf(ficlog,"\n");
                   2308:        }
                   2309:       }
                   2310:     }
1.241     brouard  2311:     if(*iter <=3 && *iter >1){
1.157     brouard  2312:       tml = *localtime(&rcurr_time);
                   2313:       strcpy(strcurr,asctime(&tml));
                   2314:       rforecast_time=rcurr_time; 
1.126     brouard  2315:       itmp = strlen(strcurr);
                   2316:       if(strcurr[itmp-1]=='\n')  /* Windows outputs with a new line */
1.241     brouard  2317:        strcurr[itmp-1]='\0';
1.162     brouard  2318:       printf("\nConsidering the time needed for the last iteration #%d: %ld seconds,\n",*iter,rcurr_time-rlast_time);
1.157     brouard  2319:       fprintf(ficlog,"\nConsidering the time needed for this last iteration #%d: %ld seconds,\n",*iter,rcurr_time-rlast_time);
1.126     brouard  2320:       for(niterf=10;niterf<=30;niterf+=10){
1.241     brouard  2321:        rforecast_time=rcurr_time+(niterf-*iter)*(rcurr_time-rlast_time);
                   2322:        forecast_time = *localtime(&rforecast_time);
                   2323:        strcpy(strfor,asctime(&forecast_time));
                   2324:        itmp = strlen(strfor);
                   2325:        if(strfor[itmp-1]=='\n')
                   2326:          strfor[itmp-1]='\0';
                   2327:        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);
                   2328:        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  2329:       }
                   2330:     }
1.187     brouard  2331:     for (i=1;i<=n;i++) { /* For each direction i */
                   2332:       for (j=1;j<=n;j++) xit[j]=xi[j][i]; /* Directions stored from previous iteration with previous scales */
1.126     brouard  2333:       fptt=(*fret); 
                   2334: #ifdef DEBUG
1.203     brouard  2335:       printf("fret=%lf, %lf, %lf \n", *fret, *fret, *fret);
                   2336:       fprintf(ficlog, "fret=%lf, %lf, %lf \n", *fret, *fret, *fret);
1.126     brouard  2337: #endif
1.203     brouard  2338:       printf("%d",i);fflush(stdout); /* print direction (parameter) i */
1.126     brouard  2339:       fprintf(ficlog,"%d",i);fflush(ficlog);
1.224     brouard  2340: #ifdef LINMINORIGINAL
1.188     brouard  2341:       linmin(p,xit,n,fret,func); /* Point p[n]. xit[n] has been loaded for direction i as input.*/
1.224     brouard  2342: #else
                   2343:       linmin(p,xit,n,fret,func,&flat); /* Point p[n]. xit[n] has been loaded for direction i as input.*/
                   2344:                        flatdir[i]=flat; /* Function is vanishing in that direction i */
                   2345: #endif
                   2346:                        /* Outputs are fret(new point p) p is updated and xit rescaled */
1.188     brouard  2347:       if (fabs(fptt-(*fret)) > del) { /* We are keeping the max gain on each of the n directions */
1.224     brouard  2348:                                /* because that direction will be replaced unless the gain del is small */
                   2349:                                /* in comparison with the 'probable' gain, mu^2, with the last average direction. */
                   2350:                                /* Unless the n directions are conjugate some gain in the determinant may be obtained */
                   2351:                                /* with the new direction. */
                   2352:                                del=fabs(fptt-(*fret)); 
                   2353:                                ibig=i; 
1.126     brouard  2354:       } 
                   2355: #ifdef DEBUG
                   2356:       printf("%d %.12e",i,(*fret));
                   2357:       fprintf(ficlog,"%d %.12e",i,(*fret));
                   2358:       for (j=1;j<=n;j++) {
1.224     brouard  2359:                                xits[j]=FMAX(fabs(p[j]-pt[j]),1.e-5);
                   2360:                                printf(" x(%d)=%.12e",j,xit[j]);
                   2361:                                fprintf(ficlog," x(%d)=%.12e",j,xit[j]);
1.126     brouard  2362:       }
                   2363:       for(j=1;j<=n;j++) {
1.225     brouard  2364:                                printf(" p(%d)=%.12e",j,p[j]);
                   2365:                                fprintf(ficlog," p(%d)=%.12e",j,p[j]);
1.126     brouard  2366:       }
                   2367:       printf("\n");
                   2368:       fprintf(ficlog,"\n");
                   2369: #endif
1.187     brouard  2370:     } /* end loop on each direction i */
                   2371:     /* Convergence test will use last linmin estimation (fret) and compare former iteration (fp) */ 
1.188     brouard  2372:     /* But p and xit have been updated at the end of linmin, *fret corresponds to new p, xit  */
1.187     brouard  2373:     /* New value of last point Pn is not computed, P(n-1) */
1.224     brouard  2374:       for(j=1;j<=n;j++) {
1.225     brouard  2375:                                if(flatdir[j] >0){
                   2376:                                        printf(" p(%d)=%lf flat=%d ",j,p[j],flatdir[j]);
                   2377:                                        fprintf(ficlog," p(%d)=%lf flat=%d ",j,p[j],flatdir[j]);
                   2378:                                }
                   2379:                                /* printf("\n"); */
                   2380:                                /* fprintf(ficlog,"\n"); */
                   2381:                        }
1.243     brouard  2382:     /* if (2.0*fabs(fp-(*fret)) <= ftol*(fabs(fp)+fabs(*fret))) { /\* Did we reach enough precision? *\/ */
                   2383:     if (2.0*fabs(fp-(*fret)) <= ftol) { /* Did we reach enough precision? */
1.188     brouard  2384:       /* We could compare with a chi^2. chisquare(0.95,ddl=1)=3.84 */
                   2385:       /* By adding age*age in a model, the new -2LL should be lower and the difference follows a */
                   2386:       /* a chisquare statistics with 1 degree. To be significant at the 95% level, it should have */
                   2387:       /* decreased of more than 3.84  */
                   2388:       /* By adding age*age and V1*age the gain (-2LL) should be more than 5.99 (ddl=2) */
                   2389:       /* By using V1+V2+V3, the gain should be  7.82, compared with basic 1+age. */
                   2390:       /* By adding 10 parameters more the gain should be 18.31 */
1.224     brouard  2391:                        
1.188     brouard  2392:       /* Starting the program with initial values given by a former maximization will simply change */
                   2393:       /* the scales of the directions and the directions, because the are reset to canonical directions */
                   2394:       /* Thus the first calls to linmin will give new points and better maximizations until fp-(*fret) is */
                   2395:       /* under the tolerance value. If the tolerance is very small 1.e-9, it could last long.  */
1.126     brouard  2396: #ifdef DEBUG
                   2397:       int k[2],l;
                   2398:       k[0]=1;
                   2399:       k[1]=-1;
                   2400:       printf("Max: %.12e",(*func)(p));
                   2401:       fprintf(ficlog,"Max: %.12e",(*func)(p));
                   2402:       for (j=1;j<=n;j++) {
                   2403:        printf(" %.12e",p[j]);
                   2404:        fprintf(ficlog," %.12e",p[j]);
                   2405:       }
                   2406:       printf("\n");
                   2407:       fprintf(ficlog,"\n");
                   2408:       for(l=0;l<=1;l++) {
                   2409:        for (j=1;j<=n;j++) {
                   2410:          ptt[j]=p[j]+(p[j]-pt[j])*k[l];
                   2411:          printf("l=%d j=%d ptt=%.12e, xits=%.12e, p=%.12e, xit=%.12e", l,j,ptt[j],xits[j],p[j],xit[j]);
                   2412:          fprintf(ficlog,"l=%d j=%d ptt=%.12e, xits=%.12e, p=%.12e, xit=%.12e", l,j,ptt[j],xits[j],p[j],xit[j]);
                   2413:        }
                   2414:        printf("func(ptt)=%.12e, deriv=%.12e\n",(*func)(ptt),(ptt[j]-p[j])/((*func)(ptt)-(*func)(p)));
                   2415:        fprintf(ficlog,"func(ptt)=%.12e, deriv=%.12e\n",(*func)(ptt),(ptt[j]-p[j])/((*func)(ptt)-(*func)(p)));
                   2416:       }
                   2417: #endif
                   2418: 
1.224     brouard  2419: #ifdef LINMINORIGINAL
                   2420: #else
                   2421:       free_ivector(flatdir,1,n); 
                   2422: #endif
1.126     brouard  2423:       free_vector(xit,1,n); 
                   2424:       free_vector(xits,1,n); 
                   2425:       free_vector(ptt,1,n); 
                   2426:       free_vector(pt,1,n); 
                   2427:       return; 
1.192     brouard  2428:     } /* enough precision */ 
1.240     brouard  2429:     if (*iter == ITMAX*n) nrerror("powell exceeding maximum iterations."); 
1.181     brouard  2430:     for (j=1;j<=n;j++) { /* Computes the extrapolated point P_0 + 2 (P_n-P_0) */
1.126     brouard  2431:       ptt[j]=2.0*p[j]-pt[j]; 
                   2432:       xit[j]=p[j]-pt[j]; 
                   2433:       pt[j]=p[j]; 
                   2434:     } 
1.181     brouard  2435:     fptt=(*func)(ptt); /* f_3 */
1.224     brouard  2436: #ifdef NODIRECTIONCHANGEDUNTILNITER  /* No change in drections until some iterations are done */
                   2437:                if (*iter <=4) {
1.225     brouard  2438: #else
                   2439: #endif
1.224     brouard  2440: #ifdef POWELLNOF3INFF1TEST    /* skips test F3 <F1 */
1.192     brouard  2441: #else
1.161     brouard  2442:     if (fptt < fp) { /* If extrapolated point is better, decide if we keep that new direction or not */
1.192     brouard  2443: #endif
1.162     brouard  2444:       /* (x1 f1=fp), (x2 f2=*fret), (x3 f3=fptt), (xm fm) */
1.161     brouard  2445:       /* From x1 (P0) distance of x2 is at h and x3 is 2h */
1.162     brouard  2446:       /* Let f"(x2) be the 2nd derivative equal everywhere.  */
                   2447:       /* Then the parabolic through (x1,f1), (x2,f2) and (x3,f3) */
                   2448:       /* will reach at f3 = fm + h^2/2 f"m  ; f" = (f1 -2f2 +f3 ) / h**2 */
1.224     brouard  2449:       /* Conditional for using this new direction is that mu^2 = (f1-2f2+f3)^2 /2 < del or directest <0 */
                   2450:       /* also  lamda^2=(f1-f2)^2/mu² is a parasite solution of powell */
                   2451:       /* For powell, inclusion of this average direction is only if t(del)<0 or del inbetween mu^2 and lambda^2 */
1.161     brouard  2452:       /* t=2.0*(fp-2.0*(*fret)+fptt)*SQR(fp-(*fret)-del)-del*SQR(fp-fptt); */
1.224     brouard  2453:       /*  Even if f3 <f1, directest can be negative and t >0 */
                   2454:       /* mu² and del² are equal when f3=f1 */
                   2455:                        /* f3 < f1 : mu² < del <= lambda^2 both test are equivalent */
                   2456:                        /* f3 < f1 : mu² < lambda^2 < del then directtest is negative and powell t is positive */
                   2457:                        /* f3 > f1 : lambda² < mu^2 < del then t is negative and directest >0  */
                   2458:                        /* f3 > f1 : lambda² < del < mu^2 then t is positive and directest >0  */
1.183     brouard  2459: #ifdef NRCORIGINAL
                   2460:       t=2.0*(fp-2.0*(*fret)+fptt)*SQR(fp-(*fret)-del)- del*SQR(fp-fptt); /* Original Numerical Recipes in C*/
                   2461: #else
                   2462:       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  2463:       t= t- del*SQR(fp-fptt);
1.183     brouard  2464: #endif
1.202     brouard  2465:       directest = fp-2.0*(*fret)+fptt - 2.0 * del; /* If delta was big enough we change it for a new direction */
1.161     brouard  2466: #ifdef DEBUG
1.181     brouard  2467:       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);
                   2468:       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  2469:       printf("t3= %.12lf, t4= %.12lf, t3*= %.12lf, t4*= %.12lf\n",SQR(fp-(*fret)-del),SQR(fp-fptt),
                   2470:             (fp-(*fret)-del)*(fp-(*fret)-del),(fp-fptt)*(fp-fptt));
                   2471:       fprintf(ficlog,"t3= %.12lf, t4= %.12lf, t3*= %.12lf, t4*= %.12lf\n",SQR(fp-(*fret)-del),SQR(fp-fptt),
                   2472:             (fp-(*fret)-del)*(fp-(*fret)-del),(fp-fptt)*(fp-fptt));
                   2473:       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);
                   2474:       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);
                   2475: #endif
1.183     brouard  2476: #ifdef POWELLORIGINAL
                   2477:       if (t < 0.0) { /* Then we use it for new direction */
                   2478: #else
1.182     brouard  2479:       if (directest*t < 0.0) { /* Contradiction between both tests */
1.224     brouard  2480:                                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  2481:         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  2482:         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  2483:         fprintf(ficlog,"f1-2f2+f3= %.12lf, f1-f2-del= %.12lf, f1-f3= %.12lf\n",fp-2.0*(*fret)+fptt, fp -(*fret) -del, fp-fptt);
                   2484:       } 
1.181     brouard  2485:       if (directest < 0.0) { /* Then we use it for new direction */
                   2486: #endif
1.191     brouard  2487: #ifdef DEBUGLINMIN
1.234     brouard  2488:        printf("Before linmin in direction P%d-P0\n",n);
                   2489:        for (j=1;j<=n;j++) {
                   2490:          printf(" Before xit[%d]= %12.7f p[%d]= %12.7f",j,xit[j],j,p[j]);
                   2491:          fprintf(ficlog," Before xit[%d]= %12.7f p[%d]= %12.7f",j,xit[j],j,p[j]);
                   2492:          if(j % ncovmodel == 0){
                   2493:            printf("\n");
                   2494:            fprintf(ficlog,"\n");
                   2495:          }
                   2496:        }
1.224     brouard  2497: #endif
                   2498: #ifdef LINMINORIGINAL
1.234     brouard  2499:        linmin(p,xit,n,fret,func); /* computes minimum on the extrapolated direction: changes p and rescales xit.*/
1.224     brouard  2500: #else
1.234     brouard  2501:        linmin(p,xit,n,fret,func,&flat); /* computes minimum on the extrapolated direction: changes p and rescales xit.*/
                   2502:        flatdir[i]=flat; /* Function is vanishing in that direction i */
1.191     brouard  2503: #endif
1.234     brouard  2504:        
1.191     brouard  2505: #ifdef DEBUGLINMIN
1.234     brouard  2506:        for (j=1;j<=n;j++) { 
                   2507:          printf("After xit[%d]= %12.7f p[%d]= %12.7f",j,xit[j],j,p[j]);
                   2508:          fprintf(ficlog,"After xit[%d]= %12.7f p[%d]= %12.7f",j,xit[j],j,p[j]);
                   2509:          if(j % ncovmodel == 0){
                   2510:            printf("\n");
                   2511:            fprintf(ficlog,"\n");
                   2512:          }
                   2513:        }
1.224     brouard  2514: #endif
1.234     brouard  2515:        for (j=1;j<=n;j++) { 
                   2516:          xi[j][ibig]=xi[j][n]; /* Replace direction with biggest decrease by last direction n */
                   2517:          xi[j][n]=xit[j];      /* and this nth direction by the by the average p_0 p_n */
                   2518:        }
1.224     brouard  2519: #ifdef LINMINORIGINAL
                   2520: #else
1.234     brouard  2521:        for (j=1, flatd=0;j<=n;j++) {
                   2522:          if(flatdir[j]>0)
                   2523:            flatd++;
                   2524:        }
                   2525:        if(flatd >0){
1.255     brouard  2526:          printf("%d flat directions: ",flatd);
                   2527:          fprintf(ficlog,"%d flat directions :",flatd);
1.234     brouard  2528:          for (j=1;j<=n;j++) { 
                   2529:            if(flatdir[j]>0){
                   2530:              printf("%d ",j);
                   2531:              fprintf(ficlog,"%d ",j);
                   2532:            }
                   2533:          }
                   2534:          printf("\n");
                   2535:          fprintf(ficlog,"\n");
                   2536:        }
1.191     brouard  2537: #endif
1.234     brouard  2538:        printf("Gaining to use new average direction of P0 P%d instead of biggest increase direction %d :\n",n,ibig);
                   2539:        fprintf(ficlog,"Gaining to use new average direction of P0 P%d instead of biggest increase direction %d :\n",n,ibig);
                   2540:        
1.126     brouard  2541: #ifdef DEBUG
1.234     brouard  2542:        printf("Direction changed  last moved %d in place of ibig=%d, new last is the average:\n",n,ibig);
                   2543:        fprintf(ficlog,"Direction changed  last moved %d in place of ibig=%d, new last is the average:\n",n,ibig);
                   2544:        for(j=1;j<=n;j++){
                   2545:          printf(" %lf",xit[j]);
                   2546:          fprintf(ficlog," %lf",xit[j]);
                   2547:        }
                   2548:        printf("\n");
                   2549:        fprintf(ficlog,"\n");
1.126     brouard  2550: #endif
1.192     brouard  2551:       } /* end of t or directest negative */
1.224     brouard  2552: #ifdef POWELLNOF3INFF1TEST
1.192     brouard  2553: #else
1.234     brouard  2554:       } /* end if (fptt < fp)  */
1.192     brouard  2555: #endif
1.225     brouard  2556: #ifdef NODIRECTIONCHANGEDUNTILNITER  /* No change in drections until some iterations are done */
1.234     brouard  2557:     } /*NODIRECTIONCHANGEDUNTILNITER  No change in drections until some iterations are done */
1.225     brouard  2558: #else
1.224     brouard  2559: #endif
1.234     brouard  2560:                } /* loop iteration */ 
1.126     brouard  2561: } 
1.234     brouard  2562:   
1.126     brouard  2563: /**** Prevalence limit (stable or period prevalence)  ****************/
1.234     brouard  2564:   
1.235     brouard  2565:   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  2566:   {
1.279     brouard  2567:     /**< Computes the prevalence limit in each live state at age x and for covariate combination ij 
                   2568:      *   (and selected quantitative values in nres)
                   2569:      *  by left multiplying the unit
                   2570:      *  matrix by transitions matrix until convergence is reached with precision ftolpl 
                   2571:      * Wx= Wx-1 Px-1= Wx-2 Px-2 Px-1  = Wx-n Px-n ... Px-2 Px-1 I
                   2572:      * Wx is row vector: population in state 1, population in state 2, population dead
                   2573:      * or prevalence in state 1, prevalence in state 2, 0
                   2574:      * newm is the matrix after multiplications, its rows are identical at a factor.
                   2575:      * Inputs are the parameter, age, a tolerance for the prevalence limit ftolpl.
                   2576:      * Output is prlim.
                   2577:      * Initial matrix pimij 
                   2578:      */
1.206     brouard  2579:   /* {0.85204250825084937, 0.13044499163996345, 0.017512500109187184, */
                   2580:   /* 0.090851990222114765, 0.88271245433047185, 0.026435555447413338, */
                   2581:   /*  0,                   0                  , 1} */
                   2582:   /*
                   2583:    * and after some iteration: */
                   2584:   /* {0.45504275246439968, 0.42731458730878791, 0.11764266022681241, */
                   2585:   /*  0.45201005341706885, 0.42865420071559901, 0.11933574586733192, */
                   2586:   /*  0,                   0                  , 1} */
                   2587:   /* And prevalence by suppressing the deaths are close to identical rows in prlim: */
                   2588:   /* {0.51571254859325999, 0.4842874514067399, */
                   2589:   /*  0.51326036147820708, 0.48673963852179264} */
                   2590:   /* If we start from prlim again, prlim tends to a constant matrix */
1.234     brouard  2591:     
1.126     brouard  2592:   int i, ii,j,k;
1.209     brouard  2593:   double *min, *max, *meandiff, maxmax,sumnew=0.;
1.145     brouard  2594:   /* double **matprod2(); */ /* test */
1.218     brouard  2595:   double **out, cov[NCOVMAX+1], **pmij(); /* **pmmij is a global variable feeded with oldms etc */
1.126     brouard  2596:   double **newm;
1.209     brouard  2597:   double agefin, delaymax=200. ; /* 100 Max number of years to converge */
1.203     brouard  2598:   int ncvloop=0;
1.288     brouard  2599:   int first=0;
1.169     brouard  2600:   
1.209     brouard  2601:   min=vector(1,nlstate);
                   2602:   max=vector(1,nlstate);
                   2603:   meandiff=vector(1,nlstate);
                   2604: 
1.218     brouard  2605:        /* Starting with matrix unity */
1.126     brouard  2606:   for (ii=1;ii<=nlstate+ndeath;ii++)
                   2607:     for (j=1;j<=nlstate+ndeath;j++){
                   2608:       oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   2609:     }
1.169     brouard  2610:   
                   2611:   cov[1]=1.;
                   2612:   
                   2613:   /* Even if hstepm = 1, at least one multiplication by the unit matrix */
1.202     brouard  2614:   /* Start at agefin= age, computes the matrix of passage and loops decreasing agefin until convergence is reached */
1.126     brouard  2615:   for(agefin=age-stepm/YEARM; agefin>=age-delaymax; agefin=agefin-stepm/YEARM){
1.202     brouard  2616:     ncvloop++;
1.126     brouard  2617:     newm=savm;
                   2618:     /* Covariates have to be included here again */
1.138     brouard  2619:     cov[2]=agefin;
1.187     brouard  2620:     if(nagesqr==1)
                   2621:       cov[3]= agefin*agefin;;
1.234     brouard  2622:     for (k=1; k<=nsd;k++) { /* For single dummy covariates only */
                   2623:                        /* Here comes the value of the covariate 'ij' after renumbering k with single dummy covariates */
                   2624:       cov[2+nagesqr+TvarsDind[k]]=nbcode[TvarsD[k]][codtabm(ij,k)];
1.235     brouard  2625:       /* 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  2626:     }
                   2627:     for (k=1; k<=nsq;k++) { /* For single varying covariates only */
                   2628:                        /* Here comes the value of quantitative after renumbering k with single quantitative covariates */
1.235     brouard  2629:       cov[2+nagesqr+TvarsQind[k]]=Tqresult[nres][k]; 
                   2630:       /* 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  2631:     }
1.237     brouard  2632:     for (k=1; k<=cptcovage;k++){  /* For product with age */
1.234     brouard  2633:       if(Dummy[Tvar[Tage[k]]]){
                   2634:        cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,k)]*cov[2];
                   2635:       } else{
1.235     brouard  2636:        cov[2+nagesqr+Tage[k]]=Tqresult[nres][k]; 
1.234     brouard  2637:       }
1.235     brouard  2638:       /* 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  2639:     }
1.237     brouard  2640:     for (k=1; k<=cptcovprod;k++){ /* For product without age */
1.235     brouard  2641:       /* 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  2642:       if(Dummy[Tvard[k][1]==0]){
                   2643:        if(Dummy[Tvard[k][2]==0]){
                   2644:          cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)] * nbcode[Tvard[k][2]][codtabm(ij,k)];
                   2645:        }else{
                   2646:          cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)] * Tqresult[nres][k];
                   2647:        }
                   2648:       }else{
                   2649:        if(Dummy[Tvard[k][2]==0]){
                   2650:          cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][2]][codtabm(ij,k)] * Tqinvresult[nres][Tvard[k][1]];
                   2651:        }else{
                   2652:          cov[2+nagesqr+Tprod[k]]=Tqinvresult[nres][Tvard[k][1]]*  Tqinvresult[nres][Tvard[k][2]];
                   2653:        }
                   2654:       }
1.234     brouard  2655:     }
1.138     brouard  2656:     /*printf("ij=%d cptcovprod=%d tvar=%d ", ij, cptcovprod, Tvar[1]);*/
                   2657:     /*printf("ij=%d cov[3]=%lf cov[4]=%lf \n",ij, cov[3],cov[4]);*/
                   2658:     /*printf("ij=%d cov[3]=%lf \n",ij, cov[3]);*/
1.145     brouard  2659:     /* savm=pmij(pmmij,cov,ncovmodel,x,nlstate); */
                   2660:     /* out=matprod2(newm, pmij(pmmij,cov,ncovmodel,x,nlstate),1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm); /\* Bug Valgrind *\/ */
1.218     brouard  2661:                /* age and covariate values of ij are in 'cov' */
1.142     brouard  2662:     out=matprod2(newm, pmij(pmmij,cov,ncovmodel,x,nlstate),1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm); /* Bug Valgrind */
1.138     brouard  2663:     
1.126     brouard  2664:     savm=oldm;
                   2665:     oldm=newm;
1.209     brouard  2666: 
                   2667:     for(j=1; j<=nlstate; j++){
                   2668:       max[j]=0.;
                   2669:       min[j]=1.;
                   2670:     }
                   2671:     for(i=1;i<=nlstate;i++){
                   2672:       sumnew=0;
                   2673:       for(k=1; k<=ndeath; k++) sumnew+=newm[i][nlstate+k];
                   2674:       for(j=1; j<=nlstate; j++){ 
                   2675:        prlim[i][j]= newm[i][j]/(1-sumnew);
                   2676:        max[j]=FMAX(max[j],prlim[i][j]);
                   2677:        min[j]=FMIN(min[j],prlim[i][j]);
                   2678:       }
                   2679:     }
                   2680: 
1.126     brouard  2681:     maxmax=0.;
1.209     brouard  2682:     for(j=1; j<=nlstate; j++){
                   2683:       meandiff[j]=(max[j]-min[j])/(max[j]+min[j])*2.; /* mean difference for each column */
                   2684:       maxmax=FMAX(maxmax,meandiff[j]);
                   2685:       /* 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  2686:     } /* j loop */
1.203     brouard  2687:     *ncvyear= (int)age- (int)agefin;
1.208     brouard  2688:     /* 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  2689:     if(maxmax < ftolpl){
1.209     brouard  2690:       /* printf("maxmax=%lf ncvloop=%ld, age=%d, agefin=%d ncvyear=%d \n", maxmax, ncvloop, (int)age, (int)agefin, *ncvyear); */
                   2691:       free_vector(min,1,nlstate);
                   2692:       free_vector(max,1,nlstate);
                   2693:       free_vector(meandiff,1,nlstate);
1.126     brouard  2694:       return prlim;
                   2695:     }
1.288     brouard  2696:   } /* agefin loop */
1.208     brouard  2697:     /* After some age loop it doesn't converge */
1.288     brouard  2698:   if(!first){
                   2699:     first=1;
                   2700:     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);
                   2701:   }
                   2702:   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);
                   2703: 
1.209     brouard  2704:   /* 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); */
                   2705:   free_vector(min,1,nlstate);
                   2706:   free_vector(max,1,nlstate);
                   2707:   free_vector(meandiff,1,nlstate);
1.208     brouard  2708:   
1.169     brouard  2709:   return prlim; /* should not reach here */
1.126     brouard  2710: }
                   2711: 
1.217     brouard  2712: 
                   2713:  /**** Back Prevalence limit (stable or period prevalence)  ****************/
                   2714: 
1.218     brouard  2715:  /* 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) */
                   2716:  /* 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  2717:   double **bprevalim(double **bprlim, double ***prevacurrent, int nlstate, double x[], double age, double ftolpl, int *ncvyear, int ij, int nres)
1.217     brouard  2718: {
1.264     brouard  2719:   /* 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  2720:      matrix by transitions matrix until convergence is reached with precision ftolpl */
                   2721:   /* Wx= Wx-1 Px-1= Wx-2 Px-2 Px-1  = Wx-n Px-n ... Px-2 Px-1 I */
                   2722:   /* Wx is row vector: population in state 1, population in state 2, population dead */
                   2723:   /* or prevalence in state 1, prevalence in state 2, 0 */
                   2724:   /* newm is the matrix after multiplications, its rows are identical at a factor */
                   2725:   /* Initial matrix pimij */
                   2726:   /* {0.85204250825084937, 0.13044499163996345, 0.017512500109187184, */
                   2727:   /* 0.090851990222114765, 0.88271245433047185, 0.026435555447413338, */
                   2728:   /*  0,                   0                  , 1} */
                   2729:   /*
                   2730:    * and after some iteration: */
                   2731:   /* {0.45504275246439968, 0.42731458730878791, 0.11764266022681241, */
                   2732:   /*  0.45201005341706885, 0.42865420071559901, 0.11933574586733192, */
                   2733:   /*  0,                   0                  , 1} */
                   2734:   /* And prevalence by suppressing the deaths are close to identical rows in prlim: */
                   2735:   /* {0.51571254859325999, 0.4842874514067399, */
                   2736:   /*  0.51326036147820708, 0.48673963852179264} */
                   2737:   /* If we start from prlim again, prlim tends to a constant matrix */
                   2738: 
                   2739:   int i, ii,j,k;
1.247     brouard  2740:   int first=0;
1.217     brouard  2741:   double *min, *max, *meandiff, maxmax,sumnew=0.;
                   2742:   /* double **matprod2(); */ /* test */
                   2743:   double **out, cov[NCOVMAX+1], **bmij();
                   2744:   double **newm;
1.218     brouard  2745:   double        **dnewm, **doldm, **dsavm;  /* for use */
                   2746:   double        **oldm, **savm;  /* for use */
                   2747: 
1.217     brouard  2748:   double agefin, delaymax=200. ; /* 100 Max number of years to converge */
                   2749:   int ncvloop=0;
                   2750:   
                   2751:   min=vector(1,nlstate);
                   2752:   max=vector(1,nlstate);
                   2753:   meandiff=vector(1,nlstate);
                   2754: 
1.266     brouard  2755:   dnewm=ddnewms; doldm=ddoldms; dsavm=ddsavms;
                   2756:   oldm=oldms; savm=savms;
                   2757:   
                   2758:   /* Starting with matrix unity */
                   2759:   for (ii=1;ii<=nlstate+ndeath;ii++)
                   2760:     for (j=1;j<=nlstate+ndeath;j++){
1.217     brouard  2761:       oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   2762:     }
                   2763:   
                   2764:   cov[1]=1.;
                   2765:   
                   2766:   /* Even if hstepm = 1, at least one multiplication by the unit matrix */
                   2767:   /* Start at agefin= age, computes the matrix of passage and loops decreasing agefin until convergence is reached */
1.218     brouard  2768:   /* for(agefin=age+stepm/YEARM; agefin<=age+delaymax; agefin=agefin+stepm/YEARM){ /\* A changer en age *\/ */
1.288     brouard  2769:   /* for(agefin=age; agefin<AGESUP; agefin=agefin+stepm/YEARM){ /\* A changer en age *\/ */
                   2770:   for(agefin=age; agefin<FMIN(AGESUP,age+delaymax); agefin=agefin+stepm/YEARM){ /* A changer en age */
1.217     brouard  2771:     ncvloop++;
1.218     brouard  2772:     newm=savm; /* oldm should be kept from previous iteration or unity at start */
                   2773:                /* newm points to the allocated table savm passed by the function it can be written, savm could be reallocated */
1.217     brouard  2774:     /* Covariates have to be included here again */
                   2775:     cov[2]=agefin;
                   2776:     if(nagesqr==1)
                   2777:       cov[3]= agefin*agefin;;
1.242     brouard  2778:     for (k=1; k<=nsd;k++) { /* For single dummy covariates only */
                   2779:                        /* Here comes the value of the covariate 'ij' after renumbering k with single dummy covariates */
                   2780:       cov[2+nagesqr+TvarsDind[k]]=nbcode[TvarsD[k]][codtabm(ij,k)];
1.264     brouard  2781:       /* 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  2782:     }
                   2783:     /* for (k=1; k<=cptcovn;k++) { */
                   2784:     /*   /\* cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,Tvar[k])]; *\/ */
                   2785:     /*   cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,k)]; */
                   2786:     /*   /\* 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])]); *\/ */
                   2787:     /* } */
                   2788:     for (k=1; k<=nsq;k++) { /* For single varying covariates only */
                   2789:                        /* Here comes the value of quantitative after renumbering k with single quantitative covariates */
                   2790:       cov[2+nagesqr+TvarsQind[k]]=Tqresult[nres][k]; 
                   2791:       /* 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]); */
                   2792:     }
                   2793:     /* for (k=1; k<=cptcovage;k++) cov[2+nagesqr+Tage[k]]=nbcode[Tvar[k]][codtabm(ij,k)]*cov[2]; */
                   2794:     /* for (k=1; k<=cptcovprod;k++) /\* Useless *\/ */
                   2795:     /*   /\* cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,Tvard[k][1])] * nbcode[Tvard[k][2]][codtabm(ij,Tvard[k][2])]; *\/ */
                   2796:     /*   cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)] * nbcode[Tvard[k][2]][codtabm(ij,k)]; */
                   2797:     for (k=1; k<=cptcovage;k++){  /* For product with age */
                   2798:       if(Dummy[Tvar[Tage[k]]]){
                   2799:        cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,k)]*cov[2];
                   2800:       } else{
                   2801:        cov[2+nagesqr+Tage[k]]=Tqresult[nres][k]; 
                   2802:       }
                   2803:       /* 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]); */
                   2804:     }
                   2805:     for (k=1; k<=cptcovprod;k++){ /* For product without age */
                   2806:       /* 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]); */
                   2807:       if(Dummy[Tvard[k][1]==0]){
                   2808:        if(Dummy[Tvard[k][2]==0]){
                   2809:          cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)] * nbcode[Tvard[k][2]][codtabm(ij,k)];
                   2810:        }else{
                   2811:          cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)] * Tqresult[nres][k];
                   2812:        }
                   2813:       }else{
                   2814:        if(Dummy[Tvard[k][2]==0]){
                   2815:          cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][2]][codtabm(ij,k)] * Tqinvresult[nres][Tvard[k][1]];
                   2816:        }else{
                   2817:          cov[2+nagesqr+Tprod[k]]=Tqinvresult[nres][Tvard[k][1]]*  Tqinvresult[nres][Tvard[k][2]];
                   2818:        }
                   2819:       }
1.217     brouard  2820:     }
                   2821:     
                   2822:     /*printf("ij=%d cptcovprod=%d tvar=%d ", ij, cptcovprod, Tvar[1]);*/
                   2823:     /*printf("ij=%d cov[3]=%lf cov[4]=%lf \n",ij, cov[3],cov[4]);*/
                   2824:     /*printf("ij=%d cov[3]=%lf \n",ij, cov[3]);*/
                   2825:     /* savm=pmij(pmmij,cov,ncovmodel,x,nlstate); */
                   2826:     /* out=matprod2(newm, pmij(pmmij,cov,ncovmodel,x,nlstate),1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm); /\* Bug Valgrind *\/ */
1.218     brouard  2827:                /* ij should be linked to the correct index of cov */
                   2828:                /* age and covariate values ij are in 'cov', but we need to pass
                   2829:                 * ij for the observed prevalence at age and status and covariate
                   2830:                 * number:  prevacurrent[(int)agefin][ii][ij]
                   2831:                 */
                   2832:     /* 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 *\/ */
                   2833:     /* 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 *\/ */
                   2834:     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  2835:     /* if((int)age == 86 || (int)age == 87){ */
1.266     brouard  2836:     /*   printf(" Backward prevalim age=%d agefin=%d \n", (int) age, (int) agefin); */
                   2837:     /*   for(i=1; i<=nlstate+ndeath; i++) { */
                   2838:     /*         printf("%d newm= ",i); */
                   2839:     /*         for(j=1;j<=nlstate+ndeath;j++) { */
                   2840:     /*           printf("%f ",newm[i][j]); */
                   2841:     /*         } */
                   2842:     /*         printf("oldm * "); */
                   2843:     /*         for(j=1;j<=nlstate+ndeath;j++) { */
                   2844:     /*           printf("%f ",oldm[i][j]); */
                   2845:     /*         } */
1.268     brouard  2846:     /*         printf(" bmmij "); */
1.266     brouard  2847:     /*         for(j=1;j<=nlstate+ndeath;j++) { */
                   2848:     /*           printf("%f ",pmmij[i][j]); */
                   2849:     /*         } */
                   2850:     /*         printf("\n"); */
                   2851:     /*   } */
                   2852:     /* } */
1.217     brouard  2853:     savm=oldm;
                   2854:     oldm=newm;
1.266     brouard  2855: 
1.217     brouard  2856:     for(j=1; j<=nlstate; j++){
                   2857:       max[j]=0.;
                   2858:       min[j]=1.;
                   2859:     }
                   2860:     for(j=1; j<=nlstate; j++){ 
                   2861:       for(i=1;i<=nlstate;i++){
1.234     brouard  2862:        /* bprlim[i][j]= newm[i][j]/(1-sumnew); */
                   2863:        bprlim[i][j]= newm[i][j];
                   2864:        max[i]=FMAX(max[i],bprlim[i][j]); /* Max in line */
                   2865:        min[i]=FMIN(min[i],bprlim[i][j]);
1.217     brouard  2866:       }
                   2867:     }
1.218     brouard  2868:                
1.217     brouard  2869:     maxmax=0.;
                   2870:     for(i=1; i<=nlstate; i++){
                   2871:       meandiff[i]=(max[i]-min[i])/(max[i]+min[i])*2.; /* mean difference for each column */
                   2872:       maxmax=FMAX(maxmax,meandiff[i]);
                   2873:       /* 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  2874:     } /* i loop */
1.217     brouard  2875:     *ncvyear= -( (int)age- (int)agefin);
1.268     brouard  2876:     /* printf("Back maxmax=%lf ncvloop=%d, age=%d, agefin=%d ncvyear=%d \n", maxmax, ncvloop, (int)age, (int)agefin, *ncvyear); */
1.217     brouard  2877:     if(maxmax < ftolpl){
1.220     brouard  2878:       /* printf("OK Back maxmax=%lf ncvloop=%d, age=%d, agefin=%d ncvyear=%d \n", maxmax, ncvloop, (int)age, (int)agefin, *ncvyear); */
1.217     brouard  2879:       free_vector(min,1,nlstate);
                   2880:       free_vector(max,1,nlstate);
                   2881:       free_vector(meandiff,1,nlstate);
                   2882:       return bprlim;
                   2883:     }
1.288     brouard  2884:   } /* agefin loop */
1.217     brouard  2885:     /* After some age loop it doesn't converge */
1.288     brouard  2886:   if(!first){
1.247     brouard  2887:     first=1;
                   2888:     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\
                   2889: 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);
                   2890:   }
                   2891:   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  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:   /* 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); */
                   2894:   free_vector(min,1,nlstate);
                   2895:   free_vector(max,1,nlstate);
                   2896:   free_vector(meandiff,1,nlstate);
                   2897:   
                   2898:   return bprlim; /* should not reach here */
                   2899: }
                   2900: 
1.126     brouard  2901: /*************** transition probabilities ***************/ 
                   2902: 
                   2903: double **pmij(double **ps, double *cov, int ncovmodel, double *x, int nlstate )
                   2904: {
1.138     brouard  2905:   /* According to parameters values stored in x and the covariate's values stored in cov,
1.266     brouard  2906:      computes the probability to be observed in state j (after stepm years) being in state i by appying the
1.138     brouard  2907:      model to the ncovmodel covariates (including constant and age).
                   2908:      lnpijopii=ln(pij/pii)= aij+bij*age+cij*v1+dij*v2+... = sum_nc=1^ncovmodel xij(nc)*cov[nc]
                   2909:      and, according on how parameters are entered, the position of the coefficient xij(nc) of the
                   2910:      ncth covariate in the global vector x is given by the formula:
                   2911:      j<i nc+((i-1)*(nlstate+ndeath-1)+j-1)*ncovmodel
                   2912:      j>=i nc + ((i-1)*(nlstate+ndeath-1)+(j-2))*ncovmodel
                   2913:      Computes ln(pij/pii) (lnpijopii), deduces pij/pii by exponentiation,
                   2914:      sums on j different of i to get 1-pii/pii, deduces pii, and then all pij.
1.266     brouard  2915:      Outputs ps[i][j] or probability to be observed in j being in i according to
1.138     brouard  2916:      the values of the covariates cov[nc] and corresponding parameter values x[nc+shiftij]
1.266     brouard  2917:      Sum on j ps[i][j] should equal to 1.
1.138     brouard  2918:   */
                   2919:   double s1, lnpijopii;
1.126     brouard  2920:   /*double t34;*/
1.164     brouard  2921:   int i,j, nc, ii, jj;
1.126     brouard  2922: 
1.223     brouard  2923:   for(i=1; i<= nlstate; i++){
                   2924:     for(j=1; j<i;j++){
                   2925:       for (nc=1, lnpijopii=0.;nc <=ncovmodel; nc++){
                   2926:        /*lnpijopii += param[i][j][nc]*cov[nc];*/
                   2927:        lnpijopii += x[nc+((i-1)*(nlstate+ndeath-1)+j-1)*ncovmodel]*cov[nc];
                   2928:        /*       printf("Int j<i s1=%.17e, lnpijopii=%.17e\n",s1,lnpijopii); */
                   2929:       }
                   2930:       ps[i][j]=lnpijopii; /* In fact ln(pij/pii) */
                   2931:       /*       printf("s1=%.17e, lnpijopii=%.17e\n",s1,lnpijopii); */
                   2932:     }
                   2933:     for(j=i+1; j<=nlstate+ndeath;j++){
                   2934:       for (nc=1, lnpijopii=0.;nc <=ncovmodel; nc++){
                   2935:        /*lnpijopii += x[(i-1)*nlstate*ncovmodel+(j-2)*ncovmodel+nc+(i-1)*(ndeath-1)*ncovmodel]*cov[nc];*/
                   2936:        lnpijopii += x[nc + ((i-1)*(nlstate+ndeath-1)+(j-2))*ncovmodel]*cov[nc];
                   2937:        /*        printf("Int j>i s1=%.17e, lnpijopii=%.17e %lx %lx\n",s1,lnpijopii,s1,lnpijopii); */
                   2938:       }
                   2939:       ps[i][j]=lnpijopii; /* In fact ln(pij/pii) */
                   2940:     }
                   2941:   }
1.218     brouard  2942:   
1.223     brouard  2943:   for(i=1; i<= nlstate; i++){
                   2944:     s1=0;
                   2945:     for(j=1; j<i; j++){
                   2946:       s1+=exp(ps[i][j]); /* In fact sums pij/pii */
                   2947:       /*printf("debug1 %d %d ps=%lf exp(ps)=%lf s1+=%lf\n",i,j,ps[i][j],exp(ps[i][j]),s1); */
                   2948:     }
                   2949:     for(j=i+1; j<=nlstate+ndeath; j++){
                   2950:       s1+=exp(ps[i][j]); /* In fact sums pij/pii */
                   2951:       /*printf("debug2 %d %d ps=%lf exp(ps)=%lf s1+=%lf\n",i,j,ps[i][j],exp(ps[i][j]),s1); */
                   2952:     }
                   2953:     /* s1= sum_{j<>i} pij/pii=(1-pii)/pii and thus pii is known from s1 */
                   2954:     ps[i][i]=1./(s1+1.);
                   2955:     /* Computing other pijs */
                   2956:     for(j=1; j<i; j++)
                   2957:       ps[i][j]= exp(ps[i][j])*ps[i][i];
                   2958:     for(j=i+1; j<=nlstate+ndeath; j++)
                   2959:       ps[i][j]= exp(ps[i][j])*ps[i][i];
                   2960:     /* ps[i][nlstate+1]=1.-s1- ps[i][i];*/ /* Sum should be 1 */
                   2961:   } /* end i */
1.218     brouard  2962:   
1.223     brouard  2963:   for(ii=nlstate+1; ii<= nlstate+ndeath; ii++){
                   2964:     for(jj=1; jj<= nlstate+ndeath; jj++){
                   2965:       ps[ii][jj]=0;
                   2966:       ps[ii][ii]=1;
                   2967:     }
                   2968:   }
1.293   ! brouard  2969:   /* Added for backcast */ /* Transposed matrix too */
        !          2970:   for(jj=1; jj<= nlstate+ndeath; jj++){
        !          2971:     s1=0.;
        !          2972:     for(ii=1; ii<= nlstate+ndeath; ii++){
        !          2973:       s1+=ps[ii][jj];
        !          2974:     }
        !          2975:     for(ii=1; ii<= nlstate; ii++){
        !          2976:       ps[ii][jj]=ps[ii][jj]/s1;
        !          2977:     }
        !          2978:   }
        !          2979:   /* Transposition */
        !          2980:   for(jj=1; jj<= nlstate+ndeath; jj++){
        !          2981:     for(ii=jj; ii<= nlstate+ndeath; ii++){
        !          2982:       s1=ps[ii][jj];
        !          2983:       ps[ii][jj]=ps[jj][ii];
        !          2984:       ps[jj][ii]=s1;
        !          2985:     }
        !          2986:   }
1.223     brouard  2987:   /* for(ii=1; ii<= nlstate+ndeath; ii++){ */
                   2988:   /*   for(jj=1; jj<= nlstate+ndeath; jj++){ */
                   2989:   /*   printf(" pmij  ps[%d][%d]=%lf ",ii,jj,ps[ii][jj]); */
                   2990:   /*   } */
                   2991:   /*   printf("\n "); */
                   2992:   /* } */
                   2993:   /* printf("\n ");printf("%lf ",cov[2]);*/
                   2994:   /*
                   2995:     for(i=1; i<= npar; i++) printf("%f ",x[i]);
1.218     brouard  2996:                goto end;*/
1.266     brouard  2997:   return ps; /* Pointer is unchanged since its call */
1.126     brouard  2998: }
                   2999: 
1.218     brouard  3000: /*************** backward transition probabilities ***************/ 
                   3001: 
                   3002:  /* 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 ) */
                   3003: /* double **bmij(double **ps, double *cov, int ncovmodel, double *x, int nlstate,  double ***prevacurrent, double ***dnewm, double **doldm, double **dsavm, int ij ) */
                   3004:  double **bmij(double **ps, double *cov, int ncovmodel, double *x, int nlstate,  double ***prevacurrent, int ij )
                   3005: {
1.266     brouard  3006:   /* Computes the backward probability at age agefin and covariate combination ij. In fact cov is already filled and x too.
                   3007:    * 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  3008:    */
1.218     brouard  3009:   int i, ii, j,k;
1.222     brouard  3010:   
                   3011:   double **out, **pmij();
                   3012:   double sumnew=0.;
1.218     brouard  3013:   double agefin;
1.292     brouard  3014:   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  3015:   double **dnewm, **dsavm, **doldm;
                   3016:   double **bbmij;
                   3017:   
1.218     brouard  3018:   doldm=ddoldms; /* global pointers */
1.222     brouard  3019:   dnewm=ddnewms;
                   3020:   dsavm=ddsavms;
                   3021:   
                   3022:   agefin=cov[2];
1.268     brouard  3023:   /* Bx = Diag(w_x) P_x Diag(Sum_i w^i_x p^ij_x */
1.222     brouard  3024:   /* bmij *//* age is cov[2], ij is included in cov, but we need for
1.266     brouard  3025:      the observed prevalence (with this covariate ij) at beginning of transition */
                   3026:   /* dsavm=pmij(pmmij,cov,ncovmodel,x,nlstate); */
1.268     brouard  3027: 
                   3028:   /* P_x */
1.266     brouard  3029:   pmmij=pmij(pmmij,cov,ncovmodel,x,nlstate); /*This is forward probability from agefin to agefin + stepm */
1.268     brouard  3030:   /* outputs pmmij which is a stochastic matrix in row */
                   3031: 
                   3032:   /* Diag(w_x) */
1.292     brouard  3033:   /* Rescaling the cross-sectional prevalence: Problem with prevacurrent which can be zero */
1.268     brouard  3034:   sumnew=0.;
1.269     brouard  3035:   /*for (ii=1;ii<=nlstate+ndeath;ii++){*/
1.268     brouard  3036:   for (ii=1;ii<=nlstate;ii++){ /* Only on live states */
1.269     brouard  3037:     /* printf(" agefin=%d, ii=%d, ij=%d, prev=%f\n",(int)agefin,ii, ij, prevacurrent[(int)agefin][ii][ij]);  */
1.268     brouard  3038:     sumnew+=prevacurrent[(int)agefin][ii][ij];
                   3039:   }
                   3040:   if(sumnew >0.01){  /* At least some value in the prevalence */
                   3041:     for (ii=1;ii<=nlstate+ndeath;ii++){
                   3042:       for (j=1;j<=nlstate+ndeath;j++)
1.269     brouard  3043:        doldm[ii][j]=(ii==j ? prevacurrent[(int)agefin][ii][ij]/sumnew : 0.0);
1.268     brouard  3044:     }
                   3045:   }else{
                   3046:     for (ii=1;ii<=nlstate+ndeath;ii++){
                   3047:       for (j=1;j<=nlstate+ndeath;j++)
                   3048:       doldm[ii][j]=(ii==j ? 1./nlstate : 0.0);
                   3049:     }
                   3050:     /* if(sumnew <0.9){ */
                   3051:     /*   printf("Problem internal bmij B: sum on i wi <0.9: j=%d, sum_i wi=%lf,agefin=%d\n",j,sumnew, (int)agefin); */
                   3052:     /* } */
                   3053:   }
                   3054:   k3=0.0;  /* We put the last diagonal to 0 */
                   3055:   for (ii=nlstate+1;ii<=nlstate+ndeath;ii++){
                   3056:       doldm[ii][ii]= k3;
                   3057:   }
                   3058:   /* End doldm, At the end doldm is diag[(w_i)] */
                   3059:   
1.292     brouard  3060:   /* Left product of this diag matrix by pmmij=Px (dnewm=dsavm*doldm): diag[(w_i)*Px */
                   3061:   bbmij=matprod2(dnewm, doldm,1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, pmmij); /* was a Bug Valgrind */
1.268     brouard  3062: 
1.292     brouard  3063:   /* Diag(Sum_i w^i_x p^ij_x, should be the prevalence at age x+stepm */
1.268     brouard  3064:   /* 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  3065:   for (j=1;j<=nlstate+ndeath;j++){
1.268     brouard  3066:     sumnew=0.;
1.222     brouard  3067:     for (ii=1;ii<=nlstate;ii++){
1.266     brouard  3068:       /* sumnew+=dsavm[ii][j]*prevacurrent[(int)agefin][ii][ij]; */
1.268     brouard  3069:       sumnew+=pmmij[ii][j]*doldm[ii][ii]; /* Yes prevalence at beginning of transition */
1.222     brouard  3070:     } /* sumnew is (N11+N21)/N..= N.1/N.. = sum on i of w_i pij */
1.268     brouard  3071:     for (ii=1;ii<=nlstate+ndeath;ii++){
1.222     brouard  3072:        /* if(agefin >= agemaxpar && agefin <= agemaxpar+stepm/YEARM){ */
1.268     brouard  3073:        /*      dsavm[ii][j]=(ii==j ? 1./sumnew : 0.0); */
1.222     brouard  3074:        /* }else if(agefin >= agemaxpar+stepm/YEARM){ */
1.268     brouard  3075:        /*      dsavm[ii][j]=(ii==j ? 1./sumnew : 0.0); */
1.222     brouard  3076:        /* }else */
1.268     brouard  3077:       dsavm[ii][j]=(ii==j ? 1./sumnew : 0.0);
                   3078:     } /*End ii */
                   3079:   } /* 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 */
                   3080: 
1.292     brouard  3081:   ps=matprod2(ps, dnewm,1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, dsavm); /* was a Bug Valgrind */
1.268     brouard  3082:   /* ps is now diag[w_i] * Px * diag [1/(w_1p1i+w_2 p2i)] */
1.222     brouard  3083:   /* end bmij */
1.266     brouard  3084:   return ps; /*pointer is unchanged */
1.218     brouard  3085: }
1.217     brouard  3086: /*************** transition probabilities ***************/ 
                   3087: 
1.218     brouard  3088: double **bpmij(double **ps, double *cov, int ncovmodel, double *x, int nlstate )
1.217     brouard  3089: {
                   3090:   /* According to parameters values stored in x and the covariate's values stored in cov,
                   3091:      computes the probability to be observed in state j being in state i by appying the
                   3092:      model to the ncovmodel covariates (including constant and age).
                   3093:      lnpijopii=ln(pij/pii)= aij+bij*age+cij*v1+dij*v2+... = sum_nc=1^ncovmodel xij(nc)*cov[nc]
                   3094:      and, according on how parameters are entered, the position of the coefficient xij(nc) of the
                   3095:      ncth covariate in the global vector x is given by the formula:
                   3096:      j<i nc+((i-1)*(nlstate+ndeath-1)+j-1)*ncovmodel
                   3097:      j>=i nc + ((i-1)*(nlstate+ndeath-1)+(j-2))*ncovmodel
                   3098:      Computes ln(pij/pii) (lnpijopii), deduces pij/pii by exponentiation,
                   3099:      sums on j different of i to get 1-pii/pii, deduces pii, and then all pij.
                   3100:      Outputs ps[i][j] the probability to be observed in j being in j according to
                   3101:      the values of the covariates cov[nc] and corresponding parameter values x[nc+shiftij]
                   3102:   */
                   3103:   double s1, lnpijopii;
                   3104:   /*double t34;*/
                   3105:   int i,j, nc, ii, jj;
                   3106: 
1.234     brouard  3107:   for(i=1; i<= nlstate; i++){
                   3108:     for(j=1; j<i;j++){
                   3109:       for (nc=1, lnpijopii=0.;nc <=ncovmodel; nc++){
                   3110:        /*lnpijopii += param[i][j][nc]*cov[nc];*/
                   3111:        lnpijopii += x[nc+((i-1)*(nlstate+ndeath-1)+j-1)*ncovmodel]*cov[nc];
                   3112:        /*       printf("Int j<i s1=%.17e, lnpijopii=%.17e\n",s1,lnpijopii); */
                   3113:       }
                   3114:       ps[i][j]=lnpijopii; /* In fact ln(pij/pii) */
                   3115:       /*       printf("s1=%.17e, lnpijopii=%.17e\n",s1,lnpijopii); */
                   3116:     }
                   3117:     for(j=i+1; j<=nlstate+ndeath;j++){
                   3118:       for (nc=1, lnpijopii=0.;nc <=ncovmodel; nc++){
                   3119:        /*lnpijopii += x[(i-1)*nlstate*ncovmodel+(j-2)*ncovmodel+nc+(i-1)*(ndeath-1)*ncovmodel]*cov[nc];*/
                   3120:        lnpijopii += x[nc + ((i-1)*(nlstate+ndeath-1)+(j-2))*ncovmodel]*cov[nc];
                   3121:        /*        printf("Int j>i s1=%.17e, lnpijopii=%.17e %lx %lx\n",s1,lnpijopii,s1,lnpijopii); */
                   3122:       }
                   3123:       ps[i][j]=lnpijopii; /* In fact ln(pij/pii) */
                   3124:     }
                   3125:   }
                   3126:   
                   3127:   for(i=1; i<= nlstate; i++){
                   3128:     s1=0;
                   3129:     for(j=1; j<i; j++){
                   3130:       s1+=exp(ps[i][j]); /* In fact sums pij/pii */
                   3131:       /*printf("debug1 %d %d ps=%lf exp(ps)=%lf s1+=%lf\n",i,j,ps[i][j],exp(ps[i][j]),s1); */
                   3132:     }
                   3133:     for(j=i+1; j<=nlstate+ndeath; j++){
                   3134:       s1+=exp(ps[i][j]); /* In fact sums pij/pii */
                   3135:       /*printf("debug2 %d %d ps=%lf exp(ps)=%lf s1+=%lf\n",i,j,ps[i][j],exp(ps[i][j]),s1); */
                   3136:     }
                   3137:     /* s1= sum_{j<>i} pij/pii=(1-pii)/pii and thus pii is known from s1 */
                   3138:     ps[i][i]=1./(s1+1.);
                   3139:     /* Computing other pijs */
                   3140:     for(j=1; j<i; j++)
                   3141:       ps[i][j]= exp(ps[i][j])*ps[i][i];
                   3142:     for(j=i+1; j<=nlstate+ndeath; j++)
                   3143:       ps[i][j]= exp(ps[i][j])*ps[i][i];
                   3144:     /* ps[i][nlstate+1]=1.-s1- ps[i][i];*/ /* Sum should be 1 */
                   3145:   } /* end i */
                   3146:   
                   3147:   for(ii=nlstate+1; ii<= nlstate+ndeath; ii++){
                   3148:     for(jj=1; jj<= nlstate+ndeath; jj++){
                   3149:       ps[ii][jj]=0;
                   3150:       ps[ii][ii]=1;
                   3151:     }
                   3152:   }
                   3153:   /* Added for backcast */ /* Transposed matrix too */
                   3154:   for(jj=1; jj<= nlstate+ndeath; jj++){
                   3155:     s1=0.;
                   3156:     for(ii=1; ii<= nlstate+ndeath; ii++){
                   3157:       s1+=ps[ii][jj];
                   3158:     }
                   3159:     for(ii=1; ii<= nlstate; ii++){
                   3160:       ps[ii][jj]=ps[ii][jj]/s1;
                   3161:     }
                   3162:   }
                   3163:   /* Transposition */
                   3164:   for(jj=1; jj<= nlstate+ndeath; jj++){
                   3165:     for(ii=jj; ii<= nlstate+ndeath; ii++){
                   3166:       s1=ps[ii][jj];
                   3167:       ps[ii][jj]=ps[jj][ii];
                   3168:       ps[jj][ii]=s1;
                   3169:     }
                   3170:   }
                   3171:   /* for(ii=1; ii<= nlstate+ndeath; ii++){ */
                   3172:   /*   for(jj=1; jj<= nlstate+ndeath; jj++){ */
                   3173:   /*   printf(" pmij  ps[%d][%d]=%lf ",ii,jj,ps[ii][jj]); */
                   3174:   /*   } */
                   3175:   /*   printf("\n "); */
                   3176:   /* } */
                   3177:   /* printf("\n ");printf("%lf ",cov[2]);*/
                   3178:   /*
                   3179:     for(i=1; i<= npar; i++) printf("%f ",x[i]);
                   3180:     goto end;*/
                   3181:   return ps;
1.217     brouard  3182: }
                   3183: 
                   3184: 
1.126     brouard  3185: /**************** Product of 2 matrices ******************/
                   3186: 
1.145     brouard  3187: double **matprod2(double **out, double **in,int nrl, int nrh, int ncl, int nch, int ncolol, int ncoloh, double **b)
1.126     brouard  3188: {
                   3189:   /* Computes the matrix product of in(1,nrh-nrl+1)(1,nch-ncl+1) times
                   3190:      b(1,nch-ncl+1)(1,ncoloh-ncolol+1) into out(...) */
                   3191:   /* in, b, out are matrice of pointers which should have been initialized 
                   3192:      before: only the contents of out is modified. The function returns
                   3193:      a pointer to pointers identical to out */
1.145     brouard  3194:   int i, j, k;
1.126     brouard  3195:   for(i=nrl; i<= nrh; i++)
1.145     brouard  3196:     for(k=ncolol; k<=ncoloh; k++){
                   3197:       out[i][k]=0.;
                   3198:       for(j=ncl; j<=nch; j++)
                   3199:        out[i][k] +=in[i][j]*b[j][k];
                   3200:     }
1.126     brouard  3201:   return out;
                   3202: }
                   3203: 
                   3204: 
                   3205: /************* Higher Matrix Product ***************/
                   3206: 
1.235     brouard  3207: 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  3208: {
1.218     brouard  3209:   /* Computes the transition matrix starting at age 'age' and combination of covariate values corresponding to ij over 
1.126     brouard  3210:      'nhstepm*hstepm*stepm' months (i.e. until
                   3211:      age (in years)  age+nhstepm*hstepm*stepm/12) by multiplying 
                   3212:      nhstepm*hstepm matrices. 
                   3213:      Output is stored in matrix po[i][j][h] for h every 'hstepm' step 
                   3214:      (typically every 2 years instead of every month which is too big 
                   3215:      for the memory).
                   3216:      Model is determined by parameters x and covariates have to be 
                   3217:      included manually here. 
                   3218: 
                   3219:      */
                   3220: 
                   3221:   int i, j, d, h, k;
1.131     brouard  3222:   double **out, cov[NCOVMAX+1];
1.126     brouard  3223:   double **newm;
1.187     brouard  3224:   double agexact;
1.214     brouard  3225:   double agebegin, ageend;
1.126     brouard  3226: 
                   3227:   /* Hstepm could be zero and should return the unit matrix */
                   3228:   for (i=1;i<=nlstate+ndeath;i++)
                   3229:     for (j=1;j<=nlstate+ndeath;j++){
                   3230:       oldm[i][j]=(i==j ? 1.0 : 0.0);
                   3231:       po[i][j][0]=(i==j ? 1.0 : 0.0);
                   3232:     }
                   3233:   /* Even if hstepm = 1, at least one multiplication by the unit matrix */
                   3234:   for(h=1; h <=nhstepm; h++){
                   3235:     for(d=1; d <=hstepm; d++){
                   3236:       newm=savm;
                   3237:       /* Covariates have to be included here again */
                   3238:       cov[1]=1.;
1.214     brouard  3239:       agexact=age+((h-1)*hstepm + (d-1))*stepm/YEARM; /* age just before transition */
1.187     brouard  3240:       cov[2]=agexact;
                   3241:       if(nagesqr==1)
1.227     brouard  3242:        cov[3]= agexact*agexact;
1.235     brouard  3243:       for (k=1; k<=nsd;k++) { /* For single dummy covariates only */
                   3244:                        /* Here comes the value of the covariate 'ij' after renumbering k with single dummy covariates */
                   3245:        cov[2+nagesqr+TvarsDind[k]]=nbcode[TvarsD[k]][codtabm(ij,k)];
                   3246:        /* 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)); */
                   3247:       }
                   3248:       for (k=1; k<=nsq;k++) { /* For single varying covariates only */
                   3249:        /* Here comes the value of quantitative after renumbering k with single quantitative covariates */
                   3250:        cov[2+nagesqr+TvarsQind[k]]=Tqresult[nres][k]; 
                   3251:        /* 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]); */
                   3252:       }
                   3253:       for (k=1; k<=cptcovage;k++){
                   3254:        if(Dummy[Tvar[Tage[k]]]){
                   3255:          cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,k)]*cov[2];
                   3256:        } else{
                   3257:          cov[2+nagesqr+Tage[k]]=Tqresult[nres][k]; 
                   3258:        }
                   3259:        /* 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]); */
                   3260:       }
                   3261:       for (k=1; k<=cptcovprod;k++){ /*  */
                   3262:        /* 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]); */
                   3263:        cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)] * nbcode[Tvard[k][2]][codtabm(ij,k)];
                   3264:       }
                   3265:       /* for (k=1; k<=cptcovn;k++)  */
                   3266:       /*       cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,k)]; */
                   3267:       /* for (k=1; k<=cptcovage;k++) /\* Should start at cptcovn+1 *\/ */
                   3268:       /*       cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,k)]*cov[2]; */
                   3269:       /* for (k=1; k<=cptcovprod;k++) /\* Useless because included in cptcovn *\/ */
                   3270:       /*       cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)]*nbcode[Tvard[k][2]][codtabm(ij,k)]; */
1.227     brouard  3271:       
                   3272:       
1.126     brouard  3273:       /*printf("hxi cptcov=%d cptcode=%d\n",cptcov,cptcode);*/
                   3274:       /*printf("h=%d d=%d age=%f cov=%f\n",h,d,age,cov[2]);*/
1.218     brouard  3275:                        /* right multiplication of oldm by the current matrix */
1.126     brouard  3276:       out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, 
                   3277:                   pmij(pmmij,cov,ncovmodel,x,nlstate));
1.217     brouard  3278:       /* if((int)age == 70){ */
                   3279:       /*       printf(" Forward hpxij age=%d agexact=%f d=%d nhstepm=%d hstepm=%d\n", (int) age, agexact, d, nhstepm, hstepm); */
                   3280:       /*       for(i=1; i<=nlstate+ndeath; i++) { */
                   3281:       /*         printf("%d pmmij ",i); */
                   3282:       /*         for(j=1;j<=nlstate+ndeath;j++) { */
                   3283:       /*           printf("%f ",pmmij[i][j]); */
                   3284:       /*         } */
                   3285:       /*         printf(" oldm "); */
                   3286:       /*         for(j=1;j<=nlstate+ndeath;j++) { */
                   3287:       /*           printf("%f ",oldm[i][j]); */
                   3288:       /*         } */
                   3289:       /*         printf("\n"); */
                   3290:       /*       } */
                   3291:       /* } */
1.126     brouard  3292:       savm=oldm;
                   3293:       oldm=newm;
                   3294:     }
                   3295:     for(i=1; i<=nlstate+ndeath; i++)
                   3296:       for(j=1;j<=nlstate+ndeath;j++) {
1.267     brouard  3297:        po[i][j][h]=newm[i][j];
                   3298:        /*if(h==nhstepm) printf("po[%d][%d][%d]=%f ",i,j,h,po[i][j][h]);*/
1.126     brouard  3299:       }
1.128     brouard  3300:     /*printf("h=%d ",h);*/
1.126     brouard  3301:   } /* end h */
1.267     brouard  3302:   /*     printf("\n H=%d \n",h); */
1.126     brouard  3303:   return po;
                   3304: }
                   3305: 
1.217     brouard  3306: /************* Higher Back Matrix Product ***************/
1.218     brouard  3307: /* 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  3308: 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  3309: {
1.266     brouard  3310:   /* For a combination of dummy covariate ij, computes the transition matrix starting at age 'age' over
1.217     brouard  3311:      'nhstepm*hstepm*stepm' months (i.e. until
1.218     brouard  3312:      age (in years)  age+nhstepm*hstepm*stepm/12) by multiplying
                   3313:      nhstepm*hstepm matrices.
                   3314:      Output is stored in matrix po[i][j][h] for h every 'hstepm' step
                   3315:      (typically every 2 years instead of every month which is too big
1.217     brouard  3316:      for the memory).
1.218     brouard  3317:      Model is determined by parameters x and covariates have to be
1.266     brouard  3318:      included manually here. Then we use a call to bmij(x and cov)
                   3319:      The addresss of po (p3mat allocated to the dimension of nhstepm) should be stored for output
1.222     brouard  3320:   */
1.217     brouard  3321: 
                   3322:   int i, j, d, h, k;
1.266     brouard  3323:   double **out, cov[NCOVMAX+1], **bmij();
                   3324:   double **newm, ***newmm;
1.217     brouard  3325:   double agexact;
                   3326:   double agebegin, ageend;
1.222     brouard  3327:   double **oldm, **savm;
1.217     brouard  3328: 
1.266     brouard  3329:   newmm=po; /* To be saved */
                   3330:   oldm=oldms;savm=savms; /* Global pointers */
1.217     brouard  3331:   /* Hstepm could be zero and should return the unit matrix */
                   3332:   for (i=1;i<=nlstate+ndeath;i++)
                   3333:     for (j=1;j<=nlstate+ndeath;j++){
                   3334:       oldm[i][j]=(i==j ? 1.0 : 0.0);
                   3335:       po[i][j][0]=(i==j ? 1.0 : 0.0);
                   3336:     }
                   3337:   /* Even if hstepm = 1, at least one multiplication by the unit matrix */
                   3338:   for(h=1; h <=nhstepm; h++){
                   3339:     for(d=1; d <=hstepm; d++){
                   3340:       newm=savm;
                   3341:       /* Covariates have to be included here again */
                   3342:       cov[1]=1.;
1.271     brouard  3343:       agexact=age-( (h-1)*hstepm + (d)  )*stepm/YEARM; /* age just before transition, d or d-1? */
1.217     brouard  3344:       /* agexact=age+((h-1)*hstepm + (d-1))*stepm/YEARM; /\* age just before transition *\/ */
                   3345:       cov[2]=agexact;
                   3346:       if(nagesqr==1)
1.222     brouard  3347:        cov[3]= agexact*agexact;
1.266     brouard  3348:       for (k=1; k<=cptcovn;k++){
                   3349:       /*       cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,k)]; */
                   3350:       /* /\* cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,Tvar[k])]; *\/ */
                   3351:        cov[2+nagesqr+TvarsDind[k]]=nbcode[TvarsD[k]][codtabm(ij,k)];
                   3352:         /* 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)); */
                   3353:       }
1.267     brouard  3354:       for (k=1; k<=nsq;k++) { /* For single varying covariates only */
                   3355:        /* Here comes the value of quantitative after renumbering k with single quantitative covariates */
                   3356:        cov[2+nagesqr+TvarsQind[k]]=Tqresult[nres][k]; 
                   3357:        /* 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]); */
                   3358:       }
                   3359:       for (k=1; k<=cptcovage;k++){ /* Should start at cptcovn+1 */
                   3360:        if(Dummy[Tvar[Tage[k]]]){
                   3361:          cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,k)]*cov[2];
                   3362:        } else{
                   3363:          cov[2+nagesqr+Tage[k]]=Tqresult[nres][k]; 
                   3364:        }
                   3365:        /* 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]); */
                   3366:       }
                   3367:       for (k=1; k<=cptcovprod;k++){ /* Useless because included in cptcovn */
1.222     brouard  3368:        cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)]*nbcode[Tvard[k][2]][codtabm(ij,k)];
1.267     brouard  3369:       }                        
1.217     brouard  3370:       /*printf("hxi cptcov=%d cptcode=%d\n",cptcov,cptcode);*/
                   3371:       /*printf("h=%d d=%d age=%f cov=%f\n",h,d,age,cov[2]);*/
1.267     brouard  3372: 
1.218     brouard  3373:       /* Careful transposed matrix */
1.266     brouard  3374:       /* age is in cov[2], prevacurrent at beginning of transition. */
1.218     brouard  3375:       /* out=matprod2(newm, bmij(pmmij,cov,ncovmodel,x,nlstate,prevacurrent, dnewm, doldm, dsavm,ij),\ */
1.222     brouard  3376:       /*                                                1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm); */
1.218     brouard  3377:       out=matprod2(newm, bmij(pmmij,cov,ncovmodel,x,nlstate,prevacurrent,ij),\
1.222     brouard  3378:                   1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm);
1.217     brouard  3379:       /* if((int)age == 70){ */
                   3380:       /*       printf(" Backward hbxij age=%d agexact=%f d=%d nhstepm=%d hstepm=%d\n", (int) age, agexact, d, nhstepm, hstepm); */
                   3381:       /*       for(i=1; i<=nlstate+ndeath; i++) { */
                   3382:       /*         printf("%d pmmij ",i); */
                   3383:       /*         for(j=1;j<=nlstate+ndeath;j++) { */
                   3384:       /*           printf("%f ",pmmij[i][j]); */
                   3385:       /*         } */
                   3386:       /*         printf(" oldm "); */
                   3387:       /*         for(j=1;j<=nlstate+ndeath;j++) { */
                   3388:       /*           printf("%f ",oldm[i][j]); */
                   3389:       /*         } */
                   3390:       /*         printf("\n"); */
                   3391:       /*       } */
                   3392:       /* } */
                   3393:       savm=oldm;
                   3394:       oldm=newm;
                   3395:     }
                   3396:     for(i=1; i<=nlstate+ndeath; i++)
                   3397:       for(j=1;j<=nlstate+ndeath;j++) {
1.222     brouard  3398:        po[i][j][h]=newm[i][j];
1.268     brouard  3399:        /* if(h==nhstepm) */
                   3400:        /*   printf("po[%d][%d][%d]=%f ",i,j,h,po[i][j][h]); */
1.217     brouard  3401:       }
1.268     brouard  3402:     /* printf("h=%d %.1f ",h, agexact); */
1.217     brouard  3403:   } /* end h */
1.268     brouard  3404:   /* printf("\n H=%d nhs=%d \n",h, nhstepm); */
1.217     brouard  3405:   return po;
                   3406: }
                   3407: 
                   3408: 
1.162     brouard  3409: #ifdef NLOPT
                   3410:   double  myfunc(unsigned n, const double *p1, double *grad, void *pd){
                   3411:   double fret;
                   3412:   double *xt;
                   3413:   int j;
                   3414:   myfunc_data *d2 = (myfunc_data *) pd;
                   3415: /* xt = (p1-1); */
                   3416:   xt=vector(1,n); 
                   3417:   for (j=1;j<=n;j++)   xt[j]=p1[j-1]; /* xt[1]=p1[0] */
                   3418: 
                   3419:   fret=(d2->function)(xt); /*  p xt[1]@8 is fine */
                   3420:   /* fret=(*func)(xt); /\*  p xt[1]@8 is fine *\/ */
                   3421:   printf("Function = %.12lf ",fret);
                   3422:   for (j=1;j<=n;j++) printf(" %d %.8lf", j, xt[j]); 
                   3423:   printf("\n");
                   3424:  free_vector(xt,1,n);
                   3425:   return fret;
                   3426: }
                   3427: #endif
1.126     brouard  3428: 
                   3429: /*************** log-likelihood *************/
                   3430: double func( double *x)
                   3431: {
1.226     brouard  3432:   int i, ii, j, k, mi, d, kk;
                   3433:   int ioffset=0;
                   3434:   double l, ll[NLSTATEMAX+1], cov[NCOVMAX+1];
                   3435:   double **out;
                   3436:   double lli; /* Individual log likelihood */
                   3437:   int s1, s2;
1.228     brouard  3438:   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  3439:   double bbh, survp;
                   3440:   long ipmx;
                   3441:   double agexact;
                   3442:   /*extern weight */
                   3443:   /* We are differentiating ll according to initial status */
                   3444:   /*  for (i=1;i<=npar;i++) printf("%f ", x[i]);*/
                   3445:   /*for(i=1;i<imx;i++) 
                   3446:     printf(" %d\n",s[4][i]);
                   3447:   */
1.162     brouard  3448: 
1.226     brouard  3449:   ++countcallfunc;
1.162     brouard  3450: 
1.226     brouard  3451:   cov[1]=1.;
1.126     brouard  3452: 
1.226     brouard  3453:   for(k=1; k<=nlstate; k++) ll[k]=0.;
1.224     brouard  3454:   ioffset=0;
1.226     brouard  3455:   if(mle==1){
                   3456:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
                   3457:       /* Computes the values of the ncovmodel covariates of the model
                   3458:         depending if the covariates are fixed or varying (age dependent) and stores them in cov[]
                   3459:         Then computes with function pmij which return a matrix p[i][j] giving the elementary probability
                   3460:         to be observed in j being in i according to the model.
                   3461:       */
1.243     brouard  3462:       ioffset=2+nagesqr ;
1.233     brouard  3463:    /* Fixed */
1.234     brouard  3464:       for (k=1; k<=ncovf;k++){ /* Simple and product fixed covariates without age* products */
                   3465:        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)*/
                   3466:       }
1.226     brouard  3467:       /* In model V2+V1*V4+age*V3+V3*V2 Tvar[1] is V2, Tvar[2=V1*V4] 
                   3468:         is 6, Tvar[3=age*V3] should not be computed because of age Tvar[4=V3*V2] 
                   3469:         has been calculated etc */
                   3470:       /* For an individual i, wav[i] gives the number of effective waves */
                   3471:       /* We compute the contribution to Likelihood of each effective transition
                   3472:         mw[mi][i] is real wave of the mi th effectve wave */
                   3473:       /* Then statuses are computed at each begin and end of an effective wave s1=s[ mw[mi][i] ][i];
                   3474:         s2=s[mw[mi+1][i]][i];
                   3475:         And the iv th varying covariate is the cotvar[mw[mi+1][i]][iv][i]
                   3476:         But if the variable is not in the model TTvar[iv] is the real variable effective in the model:
                   3477:         meaning that decodemodel should be used cotvar[mw[mi+1][i]][TTvar[iv]][i]
                   3478:       */
                   3479:       for(mi=1; mi<= wav[i]-1; mi++){
1.234     brouard  3480:        for(k=1; k <= ncovv ; k++){ /* Varying  covariates (single and product but no age )*/
1.242     brouard  3481:          /* cov[ioffset+TvarVind[k]]=cotvar[mw[mi][i]][Tvar[TvarVind[k]]][i]; */
                   3482:          cov[ioffset+TvarVind[k]]=cotvar[mw[mi][i]][Tvar[TvarVind[k]]-ncovcol-nqv][i];
1.234     brouard  3483:        }
                   3484:        for (ii=1;ii<=nlstate+ndeath;ii++)
                   3485:          for (j=1;j<=nlstate+ndeath;j++){
                   3486:            oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   3487:            savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   3488:          }
                   3489:        for(d=0; d<dh[mi][i]; d++){
                   3490:          newm=savm;
                   3491:          agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
                   3492:          cov[2]=agexact;
                   3493:          if(nagesqr==1)
                   3494:            cov[3]= agexact*agexact;  /* Should be changed here */
                   3495:          for (kk=1; kk<=cptcovage;kk++) {
1.242     brouard  3496:          if(!FixedV[Tvar[Tage[kk]]])
1.234     brouard  3497:            cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact; /* Tage[kk] gives the data-covariate associated with age */
1.242     brouard  3498:          else
                   3499:            cov[Tage[kk]+2+nagesqr]=cotvar[mw[mi][i]][Tvar[Tage[kk]]-ncovcol-nqv][i]*agexact;
1.234     brouard  3500:          }
                   3501:          out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   3502:                       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   3503:          savm=oldm;
                   3504:          oldm=newm;
                   3505:        } /* end mult */
                   3506:        
                   3507:        /*lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]);*/ /* Original formula */
                   3508:        /* But now since version 0.9 we anticipate for bias at large stepm.
                   3509:         * If stepm is larger than one month (smallest stepm) and if the exact delay 
                   3510:         * (in months) between two waves is not a multiple of stepm, we rounded to 
                   3511:         * the nearest (and in case of equal distance, to the lowest) interval but now
                   3512:         * we keep into memory the bias bh[mi][i] and also the previous matrix product
                   3513:         * (i.e to dh[mi][i]-1) saved in 'savm'. Then we inter(extra)polate the
                   3514:         * probability in order to take into account the bias as a fraction of the way
1.231     brouard  3515:                                 * from savm to out if bh is negative or even beyond if bh is positive. bh varies
                   3516:                                 * -stepm/2 to stepm/2 .
                   3517:                                 * For stepm=1 the results are the same as for previous versions of Imach.
                   3518:                                 * For stepm > 1 the results are less biased than in previous versions. 
                   3519:                                 */
1.234     brouard  3520:        s1=s[mw[mi][i]][i];
                   3521:        s2=s[mw[mi+1][i]][i];
                   3522:        bbh=(double)bh[mi][i]/(double)stepm; 
                   3523:        /* bias bh is positive if real duration
                   3524:         * is higher than the multiple of stepm and negative otherwise.
                   3525:         */
                   3526:        /* lli= (savm[s1][s2]>1.e-8 ?(1.+bbh)*log(out[s1][s2])- bbh*log(savm[s1][s2]):log((1.+bbh)*out[s1][s2]));*/
                   3527:        if( s2 > nlstate){ 
                   3528:          /* i.e. if s2 is a death state and if the date of death is known 
                   3529:             then the contribution to the likelihood is the probability to 
                   3530:             die between last step unit time and current  step unit time, 
                   3531:             which is also equal to probability to die before dh 
                   3532:             minus probability to die before dh-stepm . 
                   3533:             In version up to 0.92 likelihood was computed
                   3534:             as if date of death was unknown. Death was treated as any other
                   3535:             health state: the date of the interview describes the actual state
                   3536:             and not the date of a change in health state. The former idea was
                   3537:             to consider that at each interview the state was recorded
                   3538:             (healthy, disable or death) and IMaCh was corrected; but when we
                   3539:             introduced the exact date of death then we should have modified
                   3540:             the contribution of an exact death to the likelihood. This new
                   3541:             contribution is smaller and very dependent of the step unit
                   3542:             stepm. It is no more the probability to die between last interview
                   3543:             and month of death but the probability to survive from last
                   3544:             interview up to one month before death multiplied by the
                   3545:             probability to die within a month. Thanks to Chris
                   3546:             Jackson for correcting this bug.  Former versions increased
                   3547:             mortality artificially. The bad side is that we add another loop
                   3548:             which slows down the processing. The difference can be up to 10%
                   3549:             lower mortality.
                   3550:          */
                   3551:          /* If, at the beginning of the maximization mostly, the
                   3552:             cumulative probability or probability to be dead is
                   3553:             constant (ie = 1) over time d, the difference is equal to
                   3554:             0.  out[s1][3] = savm[s1][3]: probability, being at state
                   3555:             s1 at precedent wave, to be dead a month before current
                   3556:             wave is equal to probability, being at state s1 at
                   3557:             precedent wave, to be dead at mont of the current
                   3558:             wave. Then the observed probability (that this person died)
                   3559:             is null according to current estimated parameter. In fact,
                   3560:             it should be very low but not zero otherwise the log go to
                   3561:             infinity.
                   3562:          */
1.183     brouard  3563: /* #ifdef INFINITYORIGINAL */
                   3564: /*         lli=log(out[s1][s2] - savm[s1][s2]); */
                   3565: /* #else */
                   3566: /*       if ((out[s1][s2] - savm[s1][s2]) < mytinydouble)  */
                   3567: /*         lli=log(mytinydouble); */
                   3568: /*       else */
                   3569: /*         lli=log(out[s1][s2] - savm[s1][s2]); */
                   3570: /* #endif */
1.226     brouard  3571:          lli=log(out[s1][s2] - savm[s1][s2]);
1.216     brouard  3572:          
1.226     brouard  3573:        } else if  ( s2==-1 ) { /* alive */
                   3574:          for (j=1,survp=0. ; j<=nlstate; j++) 
                   3575:            survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
                   3576:          /*survp += out[s1][j]; */
                   3577:          lli= log(survp);
                   3578:        }
                   3579:        else if  (s2==-4) { 
                   3580:          for (j=3,survp=0. ; j<=nlstate; j++)  
                   3581:            survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
                   3582:          lli= log(survp); 
                   3583:        } 
                   3584:        else if  (s2==-5) { 
                   3585:          for (j=1,survp=0. ; j<=2; j++)  
                   3586:            survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
                   3587:          lli= log(survp); 
                   3588:        } 
                   3589:        else{
                   3590:          lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */
                   3591:          /*  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 */
                   3592:        } 
                   3593:        /*lli=(1.+bbh)*log(out[s1][s2])- bbh*log(savm[s1][s2]);*/
                   3594:        /*if(lli ==000.0)*/
                   3595:        /*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); */
                   3596:        ipmx +=1;
                   3597:        sw += weight[i];
                   3598:        ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
                   3599:        /* if (lli < log(mytinydouble)){ */
                   3600:        /*   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); */
                   3601:        /*   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]); */
                   3602:        /* } */
                   3603:       } /* end of wave */
                   3604:     } /* end of individual */
                   3605:   }  else if(mle==2){
                   3606:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
                   3607:       for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i];
                   3608:       for(mi=1; mi<= wav[i]-1; mi++){
                   3609:        for (ii=1;ii<=nlstate+ndeath;ii++)
                   3610:          for (j=1;j<=nlstate+ndeath;j++){
                   3611:            oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   3612:            savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   3613:          }
                   3614:        for(d=0; d<=dh[mi][i]; d++){
                   3615:          newm=savm;
                   3616:          agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
                   3617:          cov[2]=agexact;
                   3618:          if(nagesqr==1)
                   3619:            cov[3]= agexact*agexact;
                   3620:          for (kk=1; kk<=cptcovage;kk++) {
                   3621:            cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact;
                   3622:          }
                   3623:          out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   3624:                       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   3625:          savm=oldm;
                   3626:          oldm=newm;
                   3627:        } /* end mult */
                   3628:       
                   3629:        s1=s[mw[mi][i]][i];
                   3630:        s2=s[mw[mi+1][i]][i];
                   3631:        bbh=(double)bh[mi][i]/(double)stepm; 
                   3632:        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 */
                   3633:        ipmx +=1;
                   3634:        sw += weight[i];
                   3635:        ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
                   3636:       } /* end of wave */
                   3637:     } /* end of individual */
                   3638:   }  else if(mle==3){  /* exponential inter-extrapolation */
                   3639:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
                   3640:       for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i];
                   3641:       for(mi=1; mi<= wav[i]-1; mi++){
                   3642:        for (ii=1;ii<=nlstate+ndeath;ii++)
                   3643:          for (j=1;j<=nlstate+ndeath;j++){
                   3644:            oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   3645:            savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   3646:          }
                   3647:        for(d=0; d<dh[mi][i]; d++){
                   3648:          newm=savm;
                   3649:          agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
                   3650:          cov[2]=agexact;
                   3651:          if(nagesqr==1)
                   3652:            cov[3]= agexact*agexact;
                   3653:          for (kk=1; kk<=cptcovage;kk++) {
                   3654:            cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact;
                   3655:          }
                   3656:          out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   3657:                       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   3658:          savm=oldm;
                   3659:          oldm=newm;
                   3660:        } /* end mult */
                   3661:       
                   3662:        s1=s[mw[mi][i]][i];
                   3663:        s2=s[mw[mi+1][i]][i];
                   3664:        bbh=(double)bh[mi][i]/(double)stepm; 
                   3665:        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 */
                   3666:        ipmx +=1;
                   3667:        sw += weight[i];
                   3668:        ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
                   3669:       } /* end of wave */
                   3670:     } /* end of individual */
                   3671:   }else if (mle==4){  /* ml=4 no inter-extrapolation */
                   3672:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
                   3673:       for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i];
                   3674:       for(mi=1; mi<= wav[i]-1; mi++){
                   3675:        for (ii=1;ii<=nlstate+ndeath;ii++)
                   3676:          for (j=1;j<=nlstate+ndeath;j++){
                   3677:            oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   3678:            savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   3679:          }
                   3680:        for(d=0; d<dh[mi][i]; d++){
                   3681:          newm=savm;
                   3682:          agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
                   3683:          cov[2]=agexact;
                   3684:          if(nagesqr==1)
                   3685:            cov[3]= agexact*agexact;
                   3686:          for (kk=1; kk<=cptcovage;kk++) {
                   3687:            cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact;
                   3688:          }
1.126     brouard  3689:        
1.226     brouard  3690:          out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   3691:                       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   3692:          savm=oldm;
                   3693:          oldm=newm;
                   3694:        } /* end mult */
                   3695:       
                   3696:        s1=s[mw[mi][i]][i];
                   3697:        s2=s[mw[mi+1][i]][i];
                   3698:        if( s2 > nlstate){ 
                   3699:          lli=log(out[s1][s2] - savm[s1][s2]);
                   3700:        } else if  ( s2==-1 ) { /* alive */
                   3701:          for (j=1,survp=0. ; j<=nlstate; j++) 
                   3702:            survp += out[s1][j];
                   3703:          lli= log(survp);
                   3704:        }else{
                   3705:          lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]); /* Original formula */
                   3706:        }
                   3707:        ipmx +=1;
                   3708:        sw += weight[i];
                   3709:        ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
1.126     brouard  3710: /*     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  3711:       } /* end of wave */
                   3712:     } /* end of individual */
                   3713:   }else{  /* ml=5 no inter-extrapolation no jackson =0.8a */
                   3714:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
                   3715:       for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i];
                   3716:       for(mi=1; mi<= wav[i]-1; mi++){
                   3717:        for (ii=1;ii<=nlstate+ndeath;ii++)
                   3718:          for (j=1;j<=nlstate+ndeath;j++){
                   3719:            oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   3720:            savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   3721:          }
                   3722:        for(d=0; d<dh[mi][i]; d++){
                   3723:          newm=savm;
                   3724:          agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
                   3725:          cov[2]=agexact;
                   3726:          if(nagesqr==1)
                   3727:            cov[3]= agexact*agexact;
                   3728:          for (kk=1; kk<=cptcovage;kk++) {
                   3729:            cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact;
                   3730:          }
1.126     brouard  3731:        
1.226     brouard  3732:          out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   3733:                       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   3734:          savm=oldm;
                   3735:          oldm=newm;
                   3736:        } /* end mult */
                   3737:       
                   3738:        s1=s[mw[mi][i]][i];
                   3739:        s2=s[mw[mi+1][i]][i];
                   3740:        lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]); /* Original formula */
                   3741:        ipmx +=1;
                   3742:        sw += weight[i];
                   3743:        ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
                   3744:        /*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]);*/
                   3745:       } /* end of wave */
                   3746:     } /* end of individual */
                   3747:   } /* End of if */
                   3748:   for(k=1,l=0.; k<=nlstate; k++) l += ll[k];
                   3749:   /* printf("l1=%f l2=%f ",ll[1],ll[2]); */
                   3750:   l= l*ipmx/sw; /* To get the same order of magnitude as if weight=1 for every body */
                   3751:   return -l;
1.126     brouard  3752: }
                   3753: 
                   3754: /*************** log-likelihood *************/
                   3755: double funcone( double *x)
                   3756: {
1.228     brouard  3757:   /* Same as func but slower because of a lot of printf and if */
1.126     brouard  3758:   int i, ii, j, k, mi, d, kk;
1.228     brouard  3759:   int ioffset=0;
1.131     brouard  3760:   double l, ll[NLSTATEMAX+1], cov[NCOVMAX+1];
1.126     brouard  3761:   double **out;
                   3762:   double lli; /* Individual log likelihood */
                   3763:   double llt;
                   3764:   int s1, s2;
1.228     brouard  3765:   int iv=0, iqv=0, itv=0, iqtv=0 ; /* Index of varying covariate, fixed quantitative cov, time varying covariate, quantitative time varying covariate */
                   3766: 
1.126     brouard  3767:   double bbh, survp;
1.187     brouard  3768:   double agexact;
1.214     brouard  3769:   double agebegin, ageend;
1.126     brouard  3770:   /*extern weight */
                   3771:   /* We are differentiating ll according to initial status */
                   3772:   /*  for (i=1;i<=npar;i++) printf("%f ", x[i]);*/
                   3773:   /*for(i=1;i<imx;i++) 
                   3774:     printf(" %d\n",s[4][i]);
                   3775:   */
                   3776:   cov[1]=1.;
                   3777: 
                   3778:   for(k=1; k<=nlstate; k++) ll[k]=0.;
1.224     brouard  3779:   ioffset=0;
                   3780:   for (i=1,ipmx=0, sw=0.; i<=imx; i++){
1.243     brouard  3781:     /* ioffset=2+nagesqr+cptcovage; */
                   3782:     ioffset=2+nagesqr;
1.232     brouard  3783:     /* Fixed */
1.224     brouard  3784:     /* for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i]; */
1.232     brouard  3785:     /* for (k=1; k<=ncoveff;k++){ /\* Simple and product fixed Dummy covariates without age* products *\/ */
                   3786:     for (k=1; k<=ncovf;k++){ /* Simple and product fixed covariates without age* products */
                   3787:       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)*/
                   3788: /*    cov[ioffset+TvarFind[1]]=covar[Tvar[TvarFind[1]]][i];  */
                   3789: /*    cov[2+6]=covar[Tvar[6]][i];  */
                   3790: /*    cov[2+6]=covar[2][i]; V2  */
                   3791: /*    cov[TvarFind[2]]=covar[Tvar[TvarFind[2]]][i];  */
                   3792: /*    cov[2+7]=covar[Tvar[7]][i];  */
                   3793: /*    cov[2+7]=covar[7][i]; V7=V1*V2  */
                   3794: /*    cov[TvarFind[3]]=covar[Tvar[TvarFind[3]]][i];  */
                   3795: /*    cov[2+9]=covar[Tvar[9]][i];  */
                   3796: /*    cov[2+9]=covar[1][i]; V1  */
1.225     brouard  3797:     }
1.232     brouard  3798:     /* for (k=1; k<=nqfveff;k++){ /\* Simple and product fixed Quantitative covariates without age* products *\/ */
                   3799:     /*   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?)*\/ */
                   3800:     /* } */
1.231     brouard  3801:     /* for(iqv=1; iqv <= nqfveff; iqv++){ /\* Quantitative fixed covariates *\/ */
                   3802:     /*   cov[++ioffset]=coqvar[Tvar[iqv]][i]; /\* Only V2 k=6 and V1*V2 7 *\/ */
                   3803:     /* } */
1.225     brouard  3804:     
1.233     brouard  3805: 
                   3806:     for(mi=1; mi<= wav[i]-1; mi++){  /* Varying with waves */
1.232     brouard  3807:     /* Wave varying (but not age varying) */
                   3808:       for(k=1; k <= ncovv ; k++){ /* Varying  covariates (single and product but no age )*/
1.242     brouard  3809:        /* cov[ioffset+TvarVind[k]]=cotvar[mw[mi][i]][Tvar[TvarVind[k]]][i]; */
                   3810:        cov[ioffset+TvarVind[k]]=cotvar[mw[mi][i]][Tvar[TvarVind[k]]-ncovcol-nqv][i];
                   3811:       }
1.232     brouard  3812:       /* for(itv=1; itv <= ntveff; itv++){ /\* Varying dummy covariates (single??)*\/ */
1.242     brouard  3813:       /* iv= Tvar[Tmodelind[ioffset-2-nagesqr-cptcovage+itv]]-ncovcol-nqv; /\* Counting the # varying covariate from 1 to ntveff *\/ */
                   3814:       /* cov[ioffset+iv]=cotvar[mw[mi][i]][iv][i]; */
                   3815:       /* k=ioffset-2-nagesqr-cptcovage+itv; /\* position in simple model *\/ */
                   3816:       /* cov[ioffset+itv]=cotvar[mw[mi][i]][TmodelInvind[itv]][i]; */
                   3817:       /* 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  3818:       /* for(iqtv=1; iqtv <= nqtveff; iqtv++){ /\* Varying quantitatives covariates *\/ */
1.242     brouard  3819:       /*       iv=TmodelInvQind[iqtv]; /\* Counting the # varying covariate from 1 to ntveff *\/ */
                   3820:       /*       /\* 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]); *\/ */
                   3821:       /*       cov[ioffset+ntveff+iqtv]=cotqvar[mw[mi][i]][TmodelInvQind[iqtv]][i]; */
1.232     brouard  3822:       /* } */
1.126     brouard  3823:       for (ii=1;ii<=nlstate+ndeath;ii++)
1.242     brouard  3824:        for (j=1;j<=nlstate+ndeath;j++){
                   3825:          oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   3826:          savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   3827:        }
1.214     brouard  3828:       
                   3829:       agebegin=agev[mw[mi][i]][i]; /* Age at beginning of effective wave */
                   3830:       ageend=agev[mw[mi][i]][i] + (dh[mi][i])*stepm/YEARM; /* Age at end of effective wave and at the end of transition */
                   3831:       for(d=0; d<dh[mi][i]; d++){  /* Delay between two effective waves */
1.247     brouard  3832:       /* for(d=0; d<=0; d++){  /\* Delay between two effective waves Only one matrix to speed up*\/ */
1.242     brouard  3833:        /*dh[m][i] or dh[mw[mi][i]][i] is the delay between two effective waves m=mw[mi][i]
                   3834:          and mw[mi+1][i]. dh depends on stepm.*/
                   3835:        newm=savm;
1.247     brouard  3836:        agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;  /* Here d is needed */
1.242     brouard  3837:        cov[2]=agexact;
                   3838:        if(nagesqr==1)
                   3839:          cov[3]= agexact*agexact;
                   3840:        for (kk=1; kk<=cptcovage;kk++) {
                   3841:          if(!FixedV[Tvar[Tage[kk]]])
                   3842:            cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact;
                   3843:          else
                   3844:            cov[Tage[kk]+2+nagesqr]=cotvar[mw[mi][i]][Tvar[Tage[kk]]-ncovcol-nqv][i]*agexact;
                   3845:        }
                   3846:        /* printf("i=%d,mi=%d,d=%d,mw[mi][i]=%d\n",i, mi,d,mw[mi][i]); */
                   3847:        /* savm=pmij(pmmij,cov,ncovmodel,x,nlstate); */
                   3848:        out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   3849:                     1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   3850:        /* out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath, */
                   3851:        /*           1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate)); */
                   3852:        savm=oldm;
                   3853:        oldm=newm;
1.126     brouard  3854:       } /* end mult */
                   3855:       
                   3856:       s1=s[mw[mi][i]][i];
                   3857:       s2=s[mw[mi+1][i]][i];
1.217     brouard  3858:       /* if(s2==-1){ */
1.268     brouard  3859:       /*       printf(" ERROR s1=%d, s2=%d i=%d \n", s1, s2, i); */
1.217     brouard  3860:       /*       /\* exit(1); *\/ */
                   3861:       /* } */
1.126     brouard  3862:       bbh=(double)bh[mi][i]/(double)stepm; 
                   3863:       /* bias is positive if real duration
                   3864:        * is higher than the multiple of stepm and negative otherwise.
                   3865:        */
                   3866:       if( s2 > nlstate && (mle <5) ){  /* Jackson */
1.242     brouard  3867:        lli=log(out[s1][s2] - savm[s1][s2]);
1.216     brouard  3868:       } else if  ( s2==-1 ) { /* alive */
1.242     brouard  3869:        for (j=1,survp=0. ; j<=nlstate; j++) 
                   3870:          survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
                   3871:        lli= log(survp);
1.126     brouard  3872:       }else if (mle==1){
1.242     brouard  3873:        lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */
1.126     brouard  3874:       } else if(mle==2){
1.242     brouard  3875:        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  3876:       } else if(mle==3){  /* exponential inter-extrapolation */
1.242     brouard  3877:        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  3878:       } else if (mle==4){  /* mle=4 no inter-extrapolation */
1.242     brouard  3879:        lli=log(out[s1][s2]); /* Original formula */
1.136     brouard  3880:       } else{  /* mle=0 back to 1 */
1.242     brouard  3881:        lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */
                   3882:        /*lli=log(out[s1][s2]); */ /* Original formula */
1.126     brouard  3883:       } /* End of if */
                   3884:       ipmx +=1;
                   3885:       sw += weight[i];
                   3886:       ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
1.132     brouard  3887:       /*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  3888:       if(globpr){
1.246     brouard  3889:        fprintf(ficresilk,"%09ld %6.1f %6.1f %6d %2d %2d %2d %2d %3d %15.6f %8.4f %8.3f\
1.126     brouard  3890:  %11.6f %11.6f %11.6f ", \
1.242     brouard  3891:                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  3892:                2*weight[i]*lli,(s2==-1? -1: out[s1][s2]),(s2==-1? -1: savm[s1][s2]));
1.242     brouard  3893:        for(k=1,llt=0.,l=0.; k<=nlstate; k++){
                   3894:          llt +=ll[k]*gipmx/gsw;
                   3895:          fprintf(ficresilk," %10.6f",-ll[k]*gipmx/gsw);
                   3896:        }
                   3897:        fprintf(ficresilk," %10.6f\n", -llt);
1.126     brouard  3898:       }
1.232     brouard  3899:        } /* end of wave */
                   3900: } /* end of individual */
                   3901: for(k=1,l=0.; k<=nlstate; k++) l += ll[k];
                   3902: /* printf("l1=%f l2=%f ",ll[1],ll[2]); */
                   3903: l= l*ipmx/sw; /* To get the same order of magnitude as if weight=1 for every body */
                   3904: if(globpr==0){ /* First time we count the contributions and weights */
                   3905:        gipmx=ipmx;
                   3906:        gsw=sw;
                   3907: }
                   3908: return -l;
1.126     brouard  3909: }
                   3910: 
                   3911: 
                   3912: /*************** function likelione ***********/
1.292     brouard  3913: void likelione(FILE *ficres,double p[], int npar, int nlstate, int *globpri, long *ipmx, double *sw, double *fretone, double (*func)(double []))
1.126     brouard  3914: {
                   3915:   /* This routine should help understanding what is done with 
                   3916:      the selection of individuals/waves and
                   3917:      to check the exact contribution to the likelihood.
                   3918:      Plotting could be done.
                   3919:    */
                   3920:   int k;
                   3921: 
                   3922:   if(*globpri !=0){ /* Just counts and sums, no printings */
1.201     brouard  3923:     strcpy(fileresilk,"ILK_"); 
1.202     brouard  3924:     strcat(fileresilk,fileresu);
1.126     brouard  3925:     if((ficresilk=fopen(fileresilk,"w"))==NULL) {
                   3926:       printf("Problem with resultfile: %s\n", fileresilk);
                   3927:       fprintf(ficlog,"Problem with resultfile: %s\n", fileresilk);
                   3928:     }
1.214     brouard  3929:     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");
                   3930:     fprintf(ficresilk, "#num_i ageb agend i s1 s2 mi mw dh likeli weight %%weight 2wlli out sav ");
1.126     brouard  3931:     /*         i,s1,s2,mi,mw[mi][i],dh[mi][i],exp(lli),weight[i],2*weight[i]*lli,out[s1][s2],savm[s1][s2]); */
                   3932:     for(k=1; k<=nlstate; k++) 
                   3933:       fprintf(ficresilk," -2*gipw/gsw*weight*ll[%d]++",k);
                   3934:     fprintf(ficresilk," -2*gipw/gsw*weight*ll(total)\n");
                   3935:   }
                   3936: 
1.292     brouard  3937:   *fretone=(*func)(p);
1.126     brouard  3938:   if(*globpri !=0){
                   3939:     fclose(ficresilk);
1.205     brouard  3940:     if (mle ==0)
                   3941:       fprintf(fichtm,"\n<br>File of contributions to the likelihood computed with initial parameters and mle = %d.",mle);
                   3942:     else if(mle >=1)
                   3943:       fprintf(fichtm,"\n<br>File of contributions to the likelihood computed with optimized parameters mle = %d.",mle);
                   3944:     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  3945:     fprintf(fichtm,"\n<br>Equation of the model: <b>model=1+age+%s</b><br>\n",model); 
1.208     brouard  3946:       
                   3947:     for (k=1; k<= nlstate ; k++) {
1.211     brouard  3948:       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  3949: <img src=\"%s-p%dj.png\">",k,k,subdirf2(optionfilefiname,"ILK_"),k,subdirf2(optionfilefiname,"ILK_"),k,subdirf2(optionfilefiname,"ILK_"),k);
                   3950:     }
1.207     brouard  3951:     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  3952: <img src=\"%s-ori.png\">",subdirf2(optionfilefiname,"ILK_"),subdirf2(optionfilefiname,"ILK_"),subdirf2(optionfilefiname,"ILK_"));
1.207     brouard  3953:     fprintf(fichtm,"<br>- and by state of destination <a href=\"%s-dest.png\">%s-dest.png</a><br> \
1.204     brouard  3954: <img src=\"%s-dest.png\">",subdirf2(optionfilefiname,"ILK_"),subdirf2(optionfilefiname,"ILK_"),subdirf2(optionfilefiname,"ILK_"));
1.207     brouard  3955:     fflush(fichtm);
1.205     brouard  3956:   }
1.126     brouard  3957:   return;
                   3958: }
                   3959: 
                   3960: 
                   3961: /*********** Maximum Likelihood Estimation ***************/
                   3962: 
                   3963: void mlikeli(FILE *ficres,double p[], int npar, int ncovmodel, int nlstate, double ftol, double (*func)(double []))
                   3964: {
1.165     brouard  3965:   int i,j, iter=0;
1.126     brouard  3966:   double **xi;
                   3967:   double fret;
                   3968:   double fretone; /* Only one call to likelihood */
                   3969:   /*  char filerespow[FILENAMELENGTH];*/
1.162     brouard  3970: 
                   3971: #ifdef NLOPT
                   3972:   int creturn;
                   3973:   nlopt_opt opt;
                   3974:   /* double lb[9] = { -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL }; /\* lower bounds *\/ */
                   3975:   double *lb;
                   3976:   double minf; /* the minimum objective value, upon return */
                   3977:   double * p1; /* Shifted parameters from 0 instead of 1 */
                   3978:   myfunc_data dinst, *d = &dinst;
                   3979: #endif
                   3980: 
                   3981: 
1.126     brouard  3982:   xi=matrix(1,npar,1,npar);
                   3983:   for (i=1;i<=npar;i++)
                   3984:     for (j=1;j<=npar;j++)
                   3985:       xi[i][j]=(i==j ? 1.0 : 0.0);
                   3986:   printf("Powell\n");  fprintf(ficlog,"Powell\n");
1.201     brouard  3987:   strcpy(filerespow,"POW_"); 
1.126     brouard  3988:   strcat(filerespow,fileres);
                   3989:   if((ficrespow=fopen(filerespow,"w"))==NULL) {
                   3990:     printf("Problem with resultfile: %s\n", filerespow);
                   3991:     fprintf(ficlog,"Problem with resultfile: %s\n", filerespow);
                   3992:   }
                   3993:   fprintf(ficrespow,"# Powell\n# iter -2*LL");
                   3994:   for (i=1;i<=nlstate;i++)
                   3995:     for(j=1;j<=nlstate+ndeath;j++)
                   3996:       if(j!=i)fprintf(ficrespow," p%1d%1d",i,j);
                   3997:   fprintf(ficrespow,"\n");
1.162     brouard  3998: #ifdef POWELL
1.126     brouard  3999:   powell(p,xi,npar,ftol,&iter,&fret,func);
1.162     brouard  4000: #endif
1.126     brouard  4001: 
1.162     brouard  4002: #ifdef NLOPT
                   4003: #ifdef NEWUOA
                   4004:   opt = nlopt_create(NLOPT_LN_NEWUOA,npar);
                   4005: #else
                   4006:   opt = nlopt_create(NLOPT_LN_BOBYQA,npar);
                   4007: #endif
                   4008:   lb=vector(0,npar-1);
                   4009:   for (i=0;i<npar;i++) lb[i]= -HUGE_VAL;
                   4010:   nlopt_set_lower_bounds(opt, lb);
                   4011:   nlopt_set_initial_step1(opt, 0.1);
                   4012:   
                   4013:   p1= (p+1); /*  p *(p+1)@8 and p *(p1)@8 are equal p1[0]=p[1] */
                   4014:   d->function = func;
                   4015:   printf(" Func %.12lf \n",myfunc(npar,p1,NULL,d));
                   4016:   nlopt_set_min_objective(opt, myfunc, d);
                   4017:   nlopt_set_xtol_rel(opt, ftol);
                   4018:   if ((creturn=nlopt_optimize(opt, p1, &minf)) < 0) {
                   4019:     printf("nlopt failed! %d\n",creturn); 
                   4020:   }
                   4021:   else {
                   4022:     printf("found minimum after %d evaluations (NLOPT=%d)\n", countcallfunc ,NLOPT);
                   4023:     printf("found minimum at f(%g,%g) = %0.10g\n", p[0], p[1], minf);
                   4024:     iter=1; /* not equal */
                   4025:   }
                   4026:   nlopt_destroy(opt);
                   4027: #endif
1.126     brouard  4028:   free_matrix(xi,1,npar,1,npar);
                   4029:   fclose(ficrespow);
1.203     brouard  4030:   printf("\n#Number of iterations & function calls = %d & %d, -2 Log likelihood = %.12f\n",iter, countcallfunc,func(p));
                   4031:   fprintf(ficlog,"\n#Number of iterations & function calls = %d & %d, -2 Log likelihood = %.12f\n",iter, countcallfunc,func(p));
1.180     brouard  4032:   fprintf(ficres,"#Number of iterations & function calls = %d & %d, -2 Log likelihood = %.12f\n",iter, countcallfunc,func(p));
1.126     brouard  4033: 
                   4034: }
                   4035: 
                   4036: /**** Computes Hessian and covariance matrix ***/
1.203     brouard  4037: void hesscov(double **matcov, double **hess, double p[], int npar, double delti[], double ftolhess, double (*func)(double []))
1.126     brouard  4038: {
                   4039:   double  **a,**y,*x,pd;
1.203     brouard  4040:   /* double **hess; */
1.164     brouard  4041:   int i, j;
1.126     brouard  4042:   int *indx;
                   4043: 
                   4044:   double hessii(double p[], double delta, int theta, double delti[],double (*func)(double []),int npar);
1.203     brouard  4045:   double hessij(double p[], double **hess, double delti[], int i, int j,double (*func)(double []),int npar);
1.126     brouard  4046:   void lubksb(double **a, int npar, int *indx, double b[]) ;
                   4047:   void ludcmp(double **a, int npar, int *indx, double *d) ;
                   4048:   double gompertz(double p[]);
1.203     brouard  4049:   /* hess=matrix(1,npar,1,npar); */
1.126     brouard  4050: 
                   4051:   printf("\nCalculation of the hessian matrix. Wait...\n");
                   4052:   fprintf(ficlog,"\nCalculation of the hessian matrix. Wait...\n");
                   4053:   for (i=1;i<=npar;i++){
1.203     brouard  4054:     printf("%d-",i);fflush(stdout);
                   4055:     fprintf(ficlog,"%d-",i);fflush(ficlog);
1.126     brouard  4056:    
                   4057:      hess[i][i]=hessii(p,ftolhess,i,delti,func,npar);
                   4058:     
                   4059:     /*  printf(" %f ",p[i]);
                   4060:        printf(" %lf %lf %lf",hess[i][i],ftolhess,delti[i]);*/
                   4061:   }
                   4062:   
                   4063:   for (i=1;i<=npar;i++) {
                   4064:     for (j=1;j<=npar;j++)  {
                   4065:       if (j>i) { 
1.203     brouard  4066:        printf(".%d-%d",i,j);fflush(stdout);
                   4067:        fprintf(ficlog,".%d-%d",i,j);fflush(ficlog);
                   4068:        hess[i][j]=hessij(p,hess, delti,i,j,func,npar);
1.126     brouard  4069:        
                   4070:        hess[j][i]=hess[i][j];    
                   4071:        /*printf(" %lf ",hess[i][j]);*/
                   4072:       }
                   4073:     }
                   4074:   }
                   4075:   printf("\n");
                   4076:   fprintf(ficlog,"\n");
                   4077: 
                   4078:   printf("\nInverting the hessian to get the covariance matrix. Wait...\n");
                   4079:   fprintf(ficlog,"\nInverting the hessian to get the covariance matrix. Wait...\n");
                   4080:   
                   4081:   a=matrix(1,npar,1,npar);
                   4082:   y=matrix(1,npar,1,npar);
                   4083:   x=vector(1,npar);
                   4084:   indx=ivector(1,npar);
                   4085:   for (i=1;i<=npar;i++)
                   4086:     for (j=1;j<=npar;j++) a[i][j]=hess[i][j];
                   4087:   ludcmp(a,npar,indx,&pd);
                   4088: 
                   4089:   for (j=1;j<=npar;j++) {
                   4090:     for (i=1;i<=npar;i++) x[i]=0;
                   4091:     x[j]=1;
                   4092:     lubksb(a,npar,indx,x);
                   4093:     for (i=1;i<=npar;i++){ 
                   4094:       matcov[i][j]=x[i];
                   4095:     }
                   4096:   }
                   4097: 
                   4098:   printf("\n#Hessian matrix#\n");
                   4099:   fprintf(ficlog,"\n#Hessian matrix#\n");
                   4100:   for (i=1;i<=npar;i++) { 
                   4101:     for (j=1;j<=npar;j++) { 
1.203     brouard  4102:       printf("%.6e ",hess[i][j]);
                   4103:       fprintf(ficlog,"%.6e ",hess[i][j]);
1.126     brouard  4104:     }
                   4105:     printf("\n");
                   4106:     fprintf(ficlog,"\n");
                   4107:   }
                   4108: 
1.203     brouard  4109:   /* printf("\n#Covariance matrix#\n"); */
                   4110:   /* fprintf(ficlog,"\n#Covariance matrix#\n"); */
                   4111:   /* for (i=1;i<=npar;i++) {  */
                   4112:   /*   for (j=1;j<=npar;j++) {  */
                   4113:   /*     printf("%.6e ",matcov[i][j]); */
                   4114:   /*     fprintf(ficlog,"%.6e ",matcov[i][j]); */
                   4115:   /*   } */
                   4116:   /*   printf("\n"); */
                   4117:   /*   fprintf(ficlog,"\n"); */
                   4118:   /* } */
                   4119: 
1.126     brouard  4120:   /* Recompute Inverse */
1.203     brouard  4121:   /* for (i=1;i<=npar;i++) */
                   4122:   /*   for (j=1;j<=npar;j++) a[i][j]=matcov[i][j]; */
                   4123:   /* ludcmp(a,npar,indx,&pd); */
                   4124: 
                   4125:   /*  printf("\n#Hessian matrix recomputed#\n"); */
                   4126: 
                   4127:   /* for (j=1;j<=npar;j++) { */
                   4128:   /*   for (i=1;i<=npar;i++) x[i]=0; */
                   4129:   /*   x[j]=1; */
                   4130:   /*   lubksb(a,npar,indx,x); */
                   4131:   /*   for (i=1;i<=npar;i++){  */
                   4132:   /*     y[i][j]=x[i]; */
                   4133:   /*     printf("%.3e ",y[i][j]); */
                   4134:   /*     fprintf(ficlog,"%.3e ",y[i][j]); */
                   4135:   /*   } */
                   4136:   /*   printf("\n"); */
                   4137:   /*   fprintf(ficlog,"\n"); */
                   4138:   /* } */
                   4139: 
                   4140:   /* Verifying the inverse matrix */
                   4141: #ifdef DEBUGHESS
                   4142:   y=matprod2(y,hess,1,npar,1,npar,1,npar,matcov);
1.126     brouard  4143: 
1.203     brouard  4144:    printf("\n#Verification: multiplying the matrix of covariance by the Hessian matrix, should be unity:#\n");
                   4145:    fprintf(ficlog,"\n#Verification: multiplying the matrix of covariance by the Hessian matrix. Should be unity:#\n");
1.126     brouard  4146: 
                   4147:   for (j=1;j<=npar;j++) {
                   4148:     for (i=1;i<=npar;i++){ 
1.203     brouard  4149:       printf("%.2f ",y[i][j]);
                   4150:       fprintf(ficlog,"%.2f ",y[i][j]);
1.126     brouard  4151:     }
                   4152:     printf("\n");
                   4153:     fprintf(ficlog,"\n");
                   4154:   }
1.203     brouard  4155: #endif
1.126     brouard  4156: 
                   4157:   free_matrix(a,1,npar,1,npar);
                   4158:   free_matrix(y,1,npar,1,npar);
                   4159:   free_vector(x,1,npar);
                   4160:   free_ivector(indx,1,npar);
1.203     brouard  4161:   /* free_matrix(hess,1,npar,1,npar); */
1.126     brouard  4162: 
                   4163: 
                   4164: }
                   4165: 
                   4166: /*************** hessian matrix ****************/
                   4167: double hessii(double x[], double delta, int theta, double delti[], double (*func)(double []), int npar)
1.203     brouard  4168: { /* Around values of x, computes the function func and returns the scales delti and hessian */
1.126     brouard  4169:   int i;
                   4170:   int l=1, lmax=20;
1.203     brouard  4171:   double k1,k2, res, fx;
1.132     brouard  4172:   double p2[MAXPARM+1]; /* identical to x */
1.126     brouard  4173:   double delt=0.0001, delts, nkhi=10.,nkhif=1., khi=1.e-4;
                   4174:   int k=0,kmax=10;
                   4175:   double l1;
                   4176: 
                   4177:   fx=func(x);
                   4178:   for (i=1;i<=npar;i++) p2[i]=x[i];
1.145     brouard  4179:   for(l=0 ; l <=lmax; l++){  /* Enlarging the zone around the Maximum */
1.126     brouard  4180:     l1=pow(10,l);
                   4181:     delts=delt;
                   4182:     for(k=1 ; k <kmax; k=k+1){
                   4183:       delt = delta*(l1*k);
                   4184:       p2[theta]=x[theta] +delt;
1.145     brouard  4185:       k1=func(p2)-fx;   /* Might be negative if too close to the theoretical maximum */
1.126     brouard  4186:       p2[theta]=x[theta]-delt;
                   4187:       k2=func(p2)-fx;
                   4188:       /*res= (k1-2.0*fx+k2)/delt/delt; */
1.203     brouard  4189:       res= (k1+k2)/delt/delt/2.; /* Divided by 2 because L and not 2*L */
1.126     brouard  4190:       
1.203     brouard  4191: #ifdef DEBUGHESSII
1.126     brouard  4192:       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);
                   4193:       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);
                   4194: #endif
                   4195:       /*if(fabs(k1-2.0*fx+k2) <1.e-13){ */
                   4196:       if((k1 <khi/nkhi/2.) || (k2 <khi/nkhi/2.)){
                   4197:        k=kmax;
                   4198:       }
                   4199:       else if((k1 >khi/nkhif) || (k2 >khi/nkhif)){ /* Keeps lastvalue before 3.84/2 KHI2 5% 1d.f. */
1.164     brouard  4200:        k=kmax; l=lmax*10;
1.126     brouard  4201:       }
                   4202:       else if((k1 >khi/nkhi) || (k2 >khi/nkhi)){ 
                   4203:        delts=delt;
                   4204:       }
1.203     brouard  4205:     } /* End loop k */
1.126     brouard  4206:   }
                   4207:   delti[theta]=delts;
                   4208:   return res; 
                   4209:   
                   4210: }
                   4211: 
1.203     brouard  4212: double hessij( double x[], double **hess, double delti[], int thetai,int thetaj,double (*func)(double []),int npar)
1.126     brouard  4213: {
                   4214:   int i;
1.164     brouard  4215:   int l=1, lmax=20;
1.126     brouard  4216:   double k1,k2,k3,k4,res,fx;
1.132     brouard  4217:   double p2[MAXPARM+1];
1.203     brouard  4218:   int k, kmax=1;
                   4219:   double v1, v2, cv12, lc1, lc2;
1.208     brouard  4220: 
                   4221:   int firstime=0;
1.203     brouard  4222:   
1.126     brouard  4223:   fx=func(x);
1.203     brouard  4224:   for (k=1; k<=kmax; k=k+10) {
1.126     brouard  4225:     for (i=1;i<=npar;i++) p2[i]=x[i];
1.203     brouard  4226:     p2[thetai]=x[thetai]+delti[thetai]*k;
                   4227:     p2[thetaj]=x[thetaj]+delti[thetaj]*k;
1.126     brouard  4228:     k1=func(p2)-fx;
                   4229:   
1.203     brouard  4230:     p2[thetai]=x[thetai]+delti[thetai]*k;
                   4231:     p2[thetaj]=x[thetaj]-delti[thetaj]*k;
1.126     brouard  4232:     k2=func(p2)-fx;
                   4233:   
1.203     brouard  4234:     p2[thetai]=x[thetai]-delti[thetai]*k;
                   4235:     p2[thetaj]=x[thetaj]+delti[thetaj]*k;
1.126     brouard  4236:     k3=func(p2)-fx;
                   4237:   
1.203     brouard  4238:     p2[thetai]=x[thetai]-delti[thetai]*k;
                   4239:     p2[thetaj]=x[thetaj]-delti[thetaj]*k;
1.126     brouard  4240:     k4=func(p2)-fx;
1.203     brouard  4241:     res=(k1-k2-k3+k4)/4.0/delti[thetai]/k/delti[thetaj]/k/2.; /* Because of L not 2*L */
                   4242:     if(k1*k2*k3*k4 <0.){
1.208     brouard  4243:       firstime=1;
1.203     brouard  4244:       kmax=kmax+10;
1.208     brouard  4245:     }
                   4246:     if(kmax >=10 || firstime ==1){
1.246     brouard  4247:       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);
                   4248:       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  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:     }
                   4252: #ifdef DEBUGHESSIJ
                   4253:     v1=hess[thetai][thetai];
                   4254:     v2=hess[thetaj][thetaj];
                   4255:     cv12=res;
                   4256:     /* Computing eigen value of Hessian matrix */
                   4257:     lc1=((v1+v2)+sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
                   4258:     lc2=((v1+v2)-sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
                   4259:     if ((lc2 <0) || (lc1 <0) ){
                   4260:       printf("Warning: sub Hessian matrix '%d%d' does not have positive eigen values \n",thetai,thetaj);
                   4261:       fprintf(ficlog, "Warning: sub Hessian matrix '%d%d' does not have positive eigen values \n",thetai,thetaj);
                   4262:       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);
                   4263:       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);
                   4264:     }
1.126     brouard  4265: #endif
                   4266:   }
                   4267:   return res;
                   4268: }
                   4269: 
1.203     brouard  4270:     /* Not done yet: Was supposed to fix if not exactly at the maximum */
                   4271: /* double hessij( double x[], double delti[], int thetai,int thetaj,double (*func)(double []),int npar) */
                   4272: /* { */
                   4273: /*   int i; */
                   4274: /*   int l=1, lmax=20; */
                   4275: /*   double k1,k2,k3,k4,res,fx; */
                   4276: /*   double p2[MAXPARM+1]; */
                   4277: /*   double delt=0.0001, delts, nkhi=10.,nkhif=1., khi=1.e-4; */
                   4278: /*   int k=0,kmax=10; */
                   4279: /*   double l1; */
                   4280:   
                   4281: /*   fx=func(x); */
                   4282: /*   for(l=0 ; l <=lmax; l++){  /\* Enlarging the zone around the Maximum *\/ */
                   4283: /*     l1=pow(10,l); */
                   4284: /*     delts=delt; */
                   4285: /*     for(k=1 ; k <kmax; k=k+1){ */
                   4286: /*       delt = delti*(l1*k); */
                   4287: /*       for (i=1;i<=npar;i++) p2[i]=x[i]; */
                   4288: /*       p2[thetai]=x[thetai]+delti[thetai]/k; */
                   4289: /*       p2[thetaj]=x[thetaj]+delti[thetaj]/k; */
                   4290: /*       k1=func(p2)-fx; */
                   4291:       
                   4292: /*       p2[thetai]=x[thetai]+delti[thetai]/k; */
                   4293: /*       p2[thetaj]=x[thetaj]-delti[thetaj]/k; */
                   4294: /*       k2=func(p2)-fx; */
                   4295:       
                   4296: /*       p2[thetai]=x[thetai]-delti[thetai]/k; */
                   4297: /*       p2[thetaj]=x[thetaj]+delti[thetaj]/k; */
                   4298: /*       k3=func(p2)-fx; */
                   4299:       
                   4300: /*       p2[thetai]=x[thetai]-delti[thetai]/k; */
                   4301: /*       p2[thetaj]=x[thetaj]-delti[thetaj]/k; */
                   4302: /*       k4=func(p2)-fx; */
                   4303: /*       res=(k1-k2-k3+k4)/4.0/delti[thetai]*k/delti[thetaj]*k/2.; /\* Because of L not 2*L *\/ */
                   4304: /* #ifdef DEBUGHESSIJ */
                   4305: /*       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); */
                   4306: /*       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); */
                   4307: /* #endif */
                   4308: /*       if((k1 <khi/nkhi/2.) || (k2 <khi/nkhi/2.)|| (k4 <khi/nkhi/2.)|| (k4 <khi/nkhi/2.)){ */
                   4309: /*     k=kmax; */
                   4310: /*       } */
                   4311: /*       else if((k1 >khi/nkhif) || (k2 >khi/nkhif) || (k4 >khi/nkhif) || (k4 >khi/nkhif)){ /\* Keeps lastvalue before 3.84/2 KHI2 5% 1d.f. *\/ */
                   4312: /*     k=kmax; l=lmax*10; */
                   4313: /*       } */
                   4314: /*       else if((k1 >khi/nkhi) || (k2 >khi/nkhi)){  */
                   4315: /*     delts=delt; */
                   4316: /*       } */
                   4317: /*     } /\* End loop k *\/ */
                   4318: /*   } */
                   4319: /*   delti[theta]=delts; */
                   4320: /*   return res;  */
                   4321: /* } */
                   4322: 
                   4323: 
1.126     brouard  4324: /************** Inverse of matrix **************/
                   4325: void ludcmp(double **a, int n, int *indx, double *d) 
                   4326: { 
                   4327:   int i,imax,j,k; 
                   4328:   double big,dum,sum,temp; 
                   4329:   double *vv; 
                   4330:  
                   4331:   vv=vector(1,n); 
                   4332:   *d=1.0; 
                   4333:   for (i=1;i<=n;i++) { 
                   4334:     big=0.0; 
                   4335:     for (j=1;j<=n;j++) 
                   4336:       if ((temp=fabs(a[i][j])) > big) big=temp; 
1.256     brouard  4337:     if (big == 0.0){
                   4338:       printf(" Singular Hessian matrix at row %d:\n",i);
                   4339:       for (j=1;j<=n;j++) {
                   4340:        printf(" a[%d][%d]=%f,",i,j,a[i][j]);
                   4341:        fprintf(ficlog," a[%d][%d]=%f,",i,j,a[i][j]);
                   4342:       }
                   4343:       fflush(ficlog);
                   4344:       fclose(ficlog);
                   4345:       nrerror("Singular matrix in routine ludcmp"); 
                   4346:     }
1.126     brouard  4347:     vv[i]=1.0/big; 
                   4348:   } 
                   4349:   for (j=1;j<=n;j++) { 
                   4350:     for (i=1;i<j;i++) { 
                   4351:       sum=a[i][j]; 
                   4352:       for (k=1;k<i;k++) sum -= a[i][k]*a[k][j]; 
                   4353:       a[i][j]=sum; 
                   4354:     } 
                   4355:     big=0.0; 
                   4356:     for (i=j;i<=n;i++) { 
                   4357:       sum=a[i][j]; 
                   4358:       for (k=1;k<j;k++) 
                   4359:        sum -= a[i][k]*a[k][j]; 
                   4360:       a[i][j]=sum; 
                   4361:       if ( (dum=vv[i]*fabs(sum)) >= big) { 
                   4362:        big=dum; 
                   4363:        imax=i; 
                   4364:       } 
                   4365:     } 
                   4366:     if (j != imax) { 
                   4367:       for (k=1;k<=n;k++) { 
                   4368:        dum=a[imax][k]; 
                   4369:        a[imax][k]=a[j][k]; 
                   4370:        a[j][k]=dum; 
                   4371:       } 
                   4372:       *d = -(*d); 
                   4373:       vv[imax]=vv[j]; 
                   4374:     } 
                   4375:     indx[j]=imax; 
                   4376:     if (a[j][j] == 0.0) a[j][j]=TINY; 
                   4377:     if (j != n) { 
                   4378:       dum=1.0/(a[j][j]); 
                   4379:       for (i=j+1;i<=n;i++) a[i][j] *= dum; 
                   4380:     } 
                   4381:   } 
                   4382:   free_vector(vv,1,n);  /* Doesn't work */
                   4383: ;
                   4384: } 
                   4385: 
                   4386: void lubksb(double **a, int n, int *indx, double b[]) 
                   4387: { 
                   4388:   int i,ii=0,ip,j; 
                   4389:   double sum; 
                   4390:  
                   4391:   for (i=1;i<=n;i++) { 
                   4392:     ip=indx[i]; 
                   4393:     sum=b[ip]; 
                   4394:     b[ip]=b[i]; 
                   4395:     if (ii) 
                   4396:       for (j=ii;j<=i-1;j++) sum -= a[i][j]*b[j]; 
                   4397:     else if (sum) ii=i; 
                   4398:     b[i]=sum; 
                   4399:   } 
                   4400:   for (i=n;i>=1;i--) { 
                   4401:     sum=b[i]; 
                   4402:     for (j=i+1;j<=n;j++) sum -= a[i][j]*b[j]; 
                   4403:     b[i]=sum/a[i][i]; 
                   4404:   } 
                   4405: } 
                   4406: 
                   4407: void pstamp(FILE *fichier)
                   4408: {
1.196     brouard  4409:   fprintf(fichier,"# %s.%s\n#IMaCh version %s, %s\n#%s\n# %s", optionfilefiname,optionfilext,version,copyright, fullversion, strstart);
1.126     brouard  4410: }
                   4411: 
1.253     brouard  4412: 
                   4413: 
1.126     brouard  4414: /************ Frequencies ********************/
1.251     brouard  4415: void  freqsummary(char fileres[], double p[], double pstart[], int iagemin, int iagemax, int **s, double **agev, int nlstate, int imx, \
1.226     brouard  4416:                  int *Tvaraff, int *invalidvarcomb, int **nbcode, int *ncodemax,double **mint,double **anint, char strstart[], \
                   4417:                  int firstpass,  int lastpass, int stepm, int weightopt, char model[])
1.250     brouard  4418: {  /* Some frequencies as well as proposing some starting values */
1.226     brouard  4419:   
1.265     brouard  4420:   int i, m, jk, j1, bool, z1,j, nj, nl, k, iv, jj=0, s1=1, s2=1;
1.226     brouard  4421:   int iind=0, iage=0;
                   4422:   int mi; /* Effective wave */
                   4423:   int first;
                   4424:   double ***freq; /* Frequencies */
1.268     brouard  4425:   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 */
                   4426:   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  4427:   double *meanq, *stdq, *idq;
1.226     brouard  4428:   double **meanqt;
                   4429:   double *pp, **prop, *posprop, *pospropt;
                   4430:   double pos=0., posproptt=0., pospropta=0., k2, dateintsum=0,k2cpt=0;
                   4431:   char fileresp[FILENAMELENGTH], fileresphtm[FILENAMELENGTH], fileresphtmfr[FILENAMELENGTH];
                   4432:   double agebegin, ageend;
                   4433:     
                   4434:   pp=vector(1,nlstate);
1.251     brouard  4435:   prop=matrix(1,nlstate,iagemin-AGEMARGE,iagemax+4+AGEMARGE); 
1.226     brouard  4436:   posprop=vector(1,nlstate); /* Counting the number of transition starting from a live state per age */ 
                   4437:   pospropt=vector(1,nlstate); /* Counting the number of transition starting from a live state */ 
                   4438:   /* prop=matrix(1,nlstate,iagemin,iagemax+3); */
                   4439:   meanq=vector(1,nqfveff); /* Number of Quantitative Fixed Variables Effective */
1.284     brouard  4440:   stdq=vector(1,nqfveff); /* Number of Quantitative Fixed Variables Effective */
1.283     brouard  4441:   idq=vector(1,nqfveff); /* Number of Quantitative Fixed Variables Effective */
1.226     brouard  4442:   meanqt=matrix(1,lastpass,1,nqtveff);
                   4443:   strcpy(fileresp,"P_");
                   4444:   strcat(fileresp,fileresu);
                   4445:   /*strcat(fileresphtm,fileresu);*/
                   4446:   if((ficresp=fopen(fileresp,"w"))==NULL) {
                   4447:     printf("Problem with prevalence resultfile: %s\n", fileresp);
                   4448:     fprintf(ficlog,"Problem with prevalence resultfile: %s\n", fileresp);
                   4449:     exit(0);
                   4450:   }
1.240     brouard  4451:   
1.226     brouard  4452:   strcpy(fileresphtm,subdirfext(optionfilefiname,"PHTM_",".htm"));
                   4453:   if((ficresphtm=fopen(fileresphtm,"w"))==NULL) {
                   4454:     printf("Problem with prevalence HTM resultfile '%s' with errno='%s'\n",fileresphtm,strerror(errno));
                   4455:     fprintf(ficlog,"Problem with prevalence HTM resultfile '%s' with errno='%s'\n",fileresphtm,strerror(errno));
                   4456:     fflush(ficlog);
                   4457:     exit(70); 
                   4458:   }
                   4459:   else{
                   4460:     fprintf(ficresphtm,"<html><head>\n<title>IMaCh PHTM_ %s</title></head>\n <body><font size=\"2\">%s <br> %s</font> \
1.240     brouard  4461: <hr size=\"2\" color=\"#EC5E5E\"> \n                                   \
1.214     brouard  4462: Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=1+age+%s<br>\n",\
1.226     brouard  4463:            fileresphtm,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model);
                   4464:   }
1.237     brouard  4465:   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  4466:   
1.226     brouard  4467:   strcpy(fileresphtmfr,subdirfext(optionfilefiname,"PHTMFR_",".htm"));
                   4468:   if((ficresphtmfr=fopen(fileresphtmfr,"w"))==NULL) {
                   4469:     printf("Problem with frequency table HTM resultfile '%s' with errno='%s'\n",fileresphtmfr,strerror(errno));
                   4470:     fprintf(ficlog,"Problem with frequency table HTM resultfile '%s' with errno='%s'\n",fileresphtmfr,strerror(errno));
                   4471:     fflush(ficlog);
                   4472:     exit(70); 
1.240     brouard  4473:   } else{
1.226     brouard  4474:     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  4475: <hr size=\"2\" color=\"#EC5E5E\"> \n                                   \
1.214     brouard  4476: Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=1+age+%s<br>\n",\
1.226     brouard  4477:            fileresphtmfr,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model);
                   4478:   }
1.240     brouard  4479:   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);
                   4480:   
1.253     brouard  4481:   y= vector(iagemin-AGEMARGE,iagemax+4+AGEMARGE);
                   4482:   x= vector(iagemin-AGEMARGE,iagemax+4+AGEMARGE);
1.251     brouard  4483:   freq= ma3x(-5,nlstate+ndeath,-5,nlstate+ndeath,iagemin-AGEMARGE,iagemax+4+AGEMARGE);
1.226     brouard  4484:   j1=0;
1.126     brouard  4485:   
1.227     brouard  4486:   /* j=ncoveff;  /\* Only fixed dummy covariates *\/ */
                   4487:   j=cptcoveff;  /* Only dummy covariates of the model */
1.226     brouard  4488:   if (cptcovn<1) {j=1;ncodemax[1]=1;}
1.240     brouard  4489:   
                   4490:   
1.226     brouard  4491:   /* Detects if a combination j1 is empty: for a multinomial variable like 3 education levels:
                   4492:      reference=low_education V1=0,V2=0
                   4493:      med_educ                V1=1 V2=0, 
                   4494:      high_educ               V1=0 V2=1
                   4495:      Then V1=1 and V2=1 is a noisy combination that we want to exclude for the list 2**cptcoveff 
                   4496:   */
1.249     brouard  4497:   dateintsum=0;
                   4498:   k2cpt=0;
                   4499: 
1.253     brouard  4500:   if(cptcoveff == 0 )
1.265     brouard  4501:     nl=1;  /* Constant and age model only */
1.253     brouard  4502:   else
                   4503:     nl=2;
1.265     brouard  4504: 
                   4505:   /* if a constant only model, one pass to compute frequency tables and to write it on ficresp */
                   4506:   /* Loop on nj=1 or 2 if dummy covariates j!=0
                   4507:    *   Loop on j1(1 to 2**cptcoveff) covariate combination
                   4508:    *     freq[s1][s2][iage] =0.
                   4509:    *     Loop on iind
                   4510:    *       ++freq[s1][s2][iage] weighted
                   4511:    *     end iind
                   4512:    *     if covariate and j!0
                   4513:    *       headers Variable on one line
                   4514:    *     endif cov j!=0
                   4515:    *     header of frequency table by age
                   4516:    *     Loop on age
                   4517:    *       pp[s1]+=freq[s1][s2][iage] weighted
                   4518:    *       pos+=freq[s1][s2][iage] weighted
                   4519:    *       Loop on s1 initial state
                   4520:    *         fprintf(ficresp
                   4521:    *       end s1
                   4522:    *     end age
                   4523:    *     if j!=0 computes starting values
                   4524:    *     end compute starting values
                   4525:    *   end j1
                   4526:    * end nl 
                   4527:    */
1.253     brouard  4528:   for (nj = 1; nj <= nl; nj++){   /* nj= 1 constant model, nl number of loops. */
                   4529:     if(nj==1)
                   4530:       j=0;  /* First pass for the constant */
1.265     brouard  4531:     else{
1.253     brouard  4532:       j=cptcoveff; /* Other passes for the covariate values */
1.265     brouard  4533:     }
1.251     brouard  4534:     first=1;
1.265     brouard  4535:     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  4536:       posproptt=0.;
                   4537:       /*printf("cptcoveff=%d Tvaraff=%d", cptcoveff,Tvaraff[1]);
                   4538:        scanf("%d", i);*/
                   4539:       for (i=-5; i<=nlstate+ndeath; i++)  
1.265     brouard  4540:        for (s2=-5; s2<=nlstate+ndeath; s2++)  
1.251     brouard  4541:          for(m=iagemin; m <= iagemax+3; m++)
1.265     brouard  4542:            freq[i][s2][m]=0;
1.251     brouard  4543:       
                   4544:       for (i=1; i<=nlstate; i++)  {
1.240     brouard  4545:        for(m=iagemin; m <= iagemax+3; m++)
1.251     brouard  4546:          prop[i][m]=0;
                   4547:        posprop[i]=0;
                   4548:        pospropt[i]=0;
                   4549:       }
1.283     brouard  4550:       for (z1=1; z1<= nqfveff; z1++) { /* zeroing for each combination j1 as well as for the total */
1.284     brouard  4551:         idq[z1]=0.;
                   4552:         meanq[z1]=0.;
                   4553:         stdq[z1]=0.;
1.283     brouard  4554:       }
                   4555:       /* for (z1=1; z1<= nqtveff; z1++) { */
1.251     brouard  4556:       /*   for(m=1;m<=lastpass;m++){ */
1.283     brouard  4557:       /*         meanqt[m][z1]=0.; */
                   4558:       /*       } */
                   4559:       /* }       */
1.251     brouard  4560:       /* dateintsum=0; */
                   4561:       /* k2cpt=0; */
                   4562:       
1.265     brouard  4563:       /* For that combination of covariates j1 (V4=1 V3=0 for example), we count and print the frequencies in one pass */
1.251     brouard  4564:       for (iind=1; iind<=imx; iind++) { /* For each individual iind */
                   4565:        bool=1;
                   4566:        if(j !=0){
                   4567:          if(anyvaryingduminmodel==0){ /* If All fixed covariates */
                   4568:            if (cptcoveff >0) { /* Filter is here: Must be looked at for model=V1+V2+V3+V4 */
                   4569:              for (z1=1; z1<=cptcoveff; z1++) { /* loops on covariates in the model */
                   4570:                /* if(Tvaraff[z1] ==-20){ */
                   4571:                /*       /\* sumnew+=cotvar[mw[mi][iind]][z1][iind]; *\/ */
                   4572:                /* }else  if(Tvaraff[z1] ==-10){ */
                   4573:                /*       /\* sumnew+=coqvar[z1][iind]; *\/ */
                   4574:                /* }else  */
                   4575:                if (covar[Tvaraff[z1]][iind]!= nbcode[Tvaraff[z1]][codtabm(j1,z1)]){ /* for combination j1 of covariates */
1.265     brouard  4576:                  /* Tests if the value of the covariate z1 for this individual iind responded to combination j1 (V4=1 V3=0) */
1.251     brouard  4577:                  bool=0; /* bool should be equal to 1 to be selected, one covariate value failed */
                   4578:                  /* 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", 
                   4579:                     bool,i,z1, z1, Tvaraff[z1],i,covar[Tvaraff[z1]][i],j1,z1,codtabm(j1,z1),
                   4580:                     j1,z1,nbcode[Tvaraff[z1]][codtabm(j1,z1)],j1);*/
                   4581:                  /* For j1=7 in V1+V2+V3+V4 = 0 1 1 0 and codtabm(7,3)=1 and nbcde[3][?]=1*/
                   4582:                } /* Onlyf fixed */
                   4583:              } /* end z1 */
                   4584:            } /* cptcovn > 0 */
                   4585:          } /* end any */
                   4586:        }/* end j==0 */
1.265     brouard  4587:        if (bool==1){ /* We selected an individual iind satisfying combination j1 (V4=1 V3=0) or all fixed covariates */
1.251     brouard  4588:          /* for(m=firstpass; m<=lastpass; m++){ */
1.284     brouard  4589:          for(mi=1; mi<wav[iind];mi++){ /* For each wave */
1.251     brouard  4590:            m=mw[mi][iind];
                   4591:            if(j!=0){
                   4592:              if(anyvaryingduminmodel==1){ /* Some are varying covariates */
                   4593:                for (z1=1; z1<=cptcoveff; z1++) {
                   4594:                  if( Fixed[Tmodelind[z1]]==1){
                   4595:                    iv= Tvar[Tmodelind[z1]]-ncovcol-nqv;
                   4596:                    if (cotvar[m][iv][iind]!= nbcode[Tvaraff[z1]][codtabm(j1,z1)]) /* iv=1 to ntv, right modality. If covariate's 
                   4597:                                                                                      value is -1, we don't select. It differs from the 
                   4598:                                                                                      constant and age model which counts them. */
                   4599:                      bool=0; /* not selected */
                   4600:                  }else if( Fixed[Tmodelind[z1]]== 0) { /* fixed */
                   4601:                    if (covar[Tvaraff[z1]][iind]!= nbcode[Tvaraff[z1]][codtabm(j1,z1)]) {
                   4602:                      bool=0;
                   4603:                    }
                   4604:                  }
                   4605:                }
                   4606:              }/* Some are varying covariates, we tried to speed up if all fixed covariates in the model, avoiding waves loop  */
                   4607:            } /* end j==0 */
                   4608:            /* bool =0 we keep that guy which corresponds to the combination of dummy values */
1.284     brouard  4609:            if(bool==1){ /*Selected */
1.251     brouard  4610:              /* dh[m][iind] or dh[mw[mi][iind]][iind] is the delay between two effective (mi) waves m=mw[mi][iind]
                   4611:                 and mw[mi+1][iind]. dh depends on stepm. */
                   4612:              agebegin=agev[m][iind]; /* Age at beginning of wave before transition*/
                   4613:              ageend=agev[m][iind]+(dh[m][iind])*stepm/YEARM; /* Age at end of wave and transition */
                   4614:              if(m >=firstpass && m <=lastpass){
                   4615:                k2=anint[m][iind]+(mint[m][iind]/12.);
                   4616:                /*if ((k2>=dateprev1) && (k2<=dateprev2)) {*/
                   4617:                if(agev[m][iind]==0) agev[m][iind]=iagemax+1;  /* All ages equal to 0 are in iagemax+1 */
                   4618:                if(agev[m][iind]==1) agev[m][iind]=iagemax+2;  /* All ages equal to 1 are in iagemax+2 */
                   4619:                if (s[m][iind]>0 && s[m][iind]<=nlstate)  /* If status at wave m is known and a live state */
                   4620:                  prop[s[m][iind]][(int)agev[m][iind]] += weight[iind];  /* At age of beginning of transition, where status is known */
                   4621:                if (m<lastpass) {
                   4622:                  /* if(s[m][iind]==4 && s[m+1][iind]==4) */
                   4623:                  /*   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]); */
                   4624:                  if(s[m][iind]==-1)
                   4625:                    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.));
                   4626:                  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  4627:                  for (z1=1; z1<= nqfveff; z1++) { /* Quantitative variables, calculating mean */
                   4628:                    idq[z1]=idq[z1]+weight[iind];
                   4629:                    meanq[z1]+=covar[ncovcol+z1][iind]*weight[iind];  /* Computes mean of quantitative with selected filter */
                   4630:                    stdq[z1]+=covar[ncovcol+z1][iind]*covar[ncovcol+z1][iind]*weight[iind]*weight[iind]; /* *weight[iind];*/  /* Computes mean of quantitative with selected filter */
                   4631:                  }
1.251     brouard  4632:                  /* if((int)agev[m][iind] == 55) */
                   4633:                  /*   printf("j=%d, j1=%d Age %d, iind=%d, num=%09ld m=%d\n",j,j1,(int)agev[m][iind],iind, num[iind],m); */
                   4634:                  /* freq[s[m][iind]][s[m+1][iind]][(int)((agebegin+ageend)/2.)] += weight[iind]; */
                   4635:                  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  4636:                }
1.251     brouard  4637:              } /* end if between passes */  
                   4638:              if ((agev[m][iind]>1) && (agev[m][iind]< (iagemax+3)) && (anint[m][iind]!=9999) && (mint[m][iind]!=99) && (j==0)) {
                   4639:                dateintsum=dateintsum+k2; /* on all covariates ?*/
                   4640:                k2cpt++;
                   4641:                /* printf("iind=%ld dateintmean = %lf dateintsum=%lf k2cpt=%lf k2=%lf\n",iind, dateintsum/k2cpt, dateintsum,k2cpt, k2); */
1.234     brouard  4642:              }
1.251     brouard  4643:            }else{
                   4644:              bool=1;
                   4645:            }/* end bool 2 */
                   4646:          } /* end m */
1.284     brouard  4647:          /* for (z1=1; z1<= nqfveff; z1++) { /\* Quantitative variables, calculating mean *\/ */
                   4648:          /*   idq[z1]=idq[z1]+weight[iind]; */
                   4649:          /*   meanq[z1]+=covar[ncovcol+z1][iind]*weight[iind];  /\* Computes mean of quantitative with selected filter *\/ */
                   4650:          /*   stdq[z1]+=covar[ncovcol+z1][iind]*covar[ncovcol+z1][iind]*weight[iind]*weight[iind]; /\* *weight[iind];*\/  /\* Computes mean of quantitative with selected filter *\/ */
                   4651:          /* } */
1.251     brouard  4652:        } /* end bool */
                   4653:       } /* end iind = 1 to imx */
                   4654:       /* prop[s][age] is feeded for any initial and valid live state as well as
                   4655:         freq[s1][s2][age] at single age of beginning the transition, for a combination j1 */
                   4656:       
                   4657:       
                   4658:       /*      fprintf(ficresp, "#Count between %.lf/%.lf/%.lf and %.lf/%.lf/%.lf\n",jprev1, mprev1,anprev1,jprev2, mprev2,anprev2);*/
1.265     brouard  4659:       if(cptcoveff==0 && nj==1) /* no covariate and first pass */
                   4660:         pstamp(ficresp);
1.251     brouard  4661:       if  (cptcoveff>0 && j!=0){
1.265     brouard  4662:         pstamp(ficresp);
1.251     brouard  4663:        printf( "\n#********** Variable "); 
                   4664:        fprintf(ficresp, "\n#********** Variable "); 
                   4665:        fprintf(ficresphtm, "\n<br/><br/><h3>********** Variable "); 
                   4666:        fprintf(ficresphtmfr, "\n<br/><br/><h3>********** Variable "); 
                   4667:        fprintf(ficlog, "\n#********** Variable "); 
                   4668:        for (z1=1; z1<=cptcoveff; z1++){
                   4669:          if(!FixedV[Tvaraff[z1]]){
                   4670:            printf( "V%d(fixed)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
                   4671:            fprintf(ficresp, "V%d(fixed)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
                   4672:            fprintf(ficresphtm, "V%d(fixed)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
                   4673:            fprintf(ficresphtmfr, "V%d(fixed)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
                   4674:            fprintf(ficlog, "V%d(fixed)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
1.250     brouard  4675:          }else{
1.251     brouard  4676:            printf( "V%d(varying)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
                   4677:            fprintf(ficresp, "V%d(varying)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
                   4678:            fprintf(ficresphtm, "V%d(varying)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
                   4679:            fprintf(ficresphtmfr, "V%d(varying)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
                   4680:            fprintf(ficlog, "V%d(varying)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
                   4681:          }
                   4682:        }
                   4683:        printf( "**********\n#");
                   4684:        fprintf(ficresp, "**********\n#");
                   4685:        fprintf(ficresphtm, "**********</h3>\n");
                   4686:        fprintf(ficresphtmfr, "**********</h3>\n");
                   4687:        fprintf(ficlog, "**********\n");
                   4688:       }
1.284     brouard  4689:       /*
                   4690:        Printing means of quantitative variables if any
                   4691:       */
                   4692:       for (z1=1; z1<= nqfveff; z1++) {
1.285     brouard  4693:        fprintf(ficlog,"Mean of fixed quantitative variable V%d on %.0f individuals sum=%f", ncovcol+z1, idq[z1], meanq[z1]);
1.284     brouard  4694:        fprintf(ficlog,", mean=%.3g\n",meanq[z1]/idq[z1]);
                   4695:        if(weightopt==1){
                   4696:          printf(" Weighted mean and standard deviation of");
                   4697:          fprintf(ficlog," Weighted mean and standard deviation of");
                   4698:          fprintf(ficresphtmfr," Weighted mean and standard deviation of");
                   4699:        }
1.285     brouard  4700:        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]));
                   4701:        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]));
                   4702:        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  4703:       }
                   4704:       /* for (z1=1; z1<= nqtveff; z1++) { */
                   4705:       /*       for(m=1;m<=lastpass;m++){ */
                   4706:       /*         fprintf(ficresphtmfr,"V quantitative id %d, pass id=%d, mean=%f<p>\n", z1, m, meanqt[m][z1]); */
                   4707:       /*   } */
                   4708:       /* } */
1.283     brouard  4709: 
1.251     brouard  4710:       fprintf(ficresphtm,"<table style=\"text-align:center; border: 1px solid\">");
1.265     brouard  4711:       if((cptcoveff==0 && nj==1)|| nj==2 ) /* no covariate and first pass */
                   4712:         fprintf(ficresp, " Age");
                   4713:       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  4714:       for(i=1; i<=nlstate;i++) {
1.265     brouard  4715:        if((cptcoveff==0 && nj==1)|| nj==2 ) fprintf(ficresp," Prev(%d)  N(%d)  N  ",i,i);
1.251     brouard  4716:        fprintf(ficresphtm, "<th>Age</th><th>Prev(%d)</th><th>N(%d)</th><th>N</th>",i,i);
                   4717:       }
1.265     brouard  4718:       if((cptcoveff==0 && nj==1)|| nj==2 ) fprintf(ficresp, "\n");
1.251     brouard  4719:       fprintf(ficresphtm, "\n");
                   4720:       
                   4721:       /* Header of frequency table by age */
                   4722:       fprintf(ficresphtmfr,"<table style=\"text-align:center; border: 1px solid\">");
                   4723:       fprintf(ficresphtmfr,"<th>Age</th> ");
1.265     brouard  4724:       for(s2=-1; s2 <=nlstate+ndeath; s2++){
1.251     brouard  4725:        for(m=-1; m <=nlstate+ndeath; m++){
1.265     brouard  4726:          if(s2!=0 && m!=0)
                   4727:            fprintf(ficresphtmfr,"<th>%d%d</th> ",s2,m);
1.240     brouard  4728:        }
1.226     brouard  4729:       }
1.251     brouard  4730:       fprintf(ficresphtmfr, "\n");
                   4731:     
                   4732:       /* For each age */
                   4733:       for(iage=iagemin; iage <= iagemax+3; iage++){
                   4734:        fprintf(ficresphtm,"<tr>");
                   4735:        if(iage==iagemax+1){
                   4736:          fprintf(ficlog,"1");
                   4737:          fprintf(ficresphtmfr,"<tr><th>0</th> ");
                   4738:        }else if(iage==iagemax+2){
                   4739:          fprintf(ficlog,"0");
                   4740:          fprintf(ficresphtmfr,"<tr><th>Unknown</th> ");
                   4741:        }else if(iage==iagemax+3){
                   4742:          fprintf(ficlog,"Total");
                   4743:          fprintf(ficresphtmfr,"<tr><th>Total</th> ");
                   4744:        }else{
1.240     brouard  4745:          if(first==1){
1.251     brouard  4746:            first=0;
                   4747:            printf("See log file for details...\n");
                   4748:          }
                   4749:          fprintf(ficresphtmfr,"<tr><th>%d</th> ",iage);
                   4750:          fprintf(ficlog,"Age %d", iage);
                   4751:        }
1.265     brouard  4752:        for(s1=1; s1 <=nlstate ; s1++){
                   4753:          for(m=-1, pp[s1]=0; m <=nlstate+ndeath ; m++)
                   4754:            pp[s1] += freq[s1][m][iage]; 
1.251     brouard  4755:        }
1.265     brouard  4756:        for(s1=1; s1 <=nlstate ; s1++){
1.251     brouard  4757:          for(m=-1, pos=0; m <=0 ; m++)
1.265     brouard  4758:            pos += freq[s1][m][iage];
                   4759:          if(pp[s1]>=1.e-10){
1.251     brouard  4760:            if(first==1){
1.265     brouard  4761:              printf(" %d.=%.0f loss[%d]=%.1f%%",s1,pp[s1],s1,100*pos/pp[s1]);
1.251     brouard  4762:            }
1.265     brouard  4763:            fprintf(ficlog," %d.=%.0f loss[%d]=%.1f%%",s1,pp[s1],s1,100*pos/pp[s1]);
1.251     brouard  4764:          }else{
                   4765:            if(first==1)
1.265     brouard  4766:              printf(" %d.=%.0f loss[%d]=NaNQ%%",s1,pp[s1],s1);
                   4767:            fprintf(ficlog," %d.=%.0f loss[%d]=NaNQ%%",s1,pp[s1],s1);
1.240     brouard  4768:          }
                   4769:        }
                   4770:       
1.265     brouard  4771:        for(s1=1; s1 <=nlstate ; s1++){ 
                   4772:          /* posprop[s1]=0; */
                   4773:          for(m=0, pp[s1]=0; m <=nlstate+ndeath; m++)/* Summing on all ages */
                   4774:            pp[s1] += freq[s1][m][iage];
                   4775:        }       /* pp[s1] is the total number of transitions starting from state s1 and any ending status until this age */
                   4776:       
                   4777:        for(s1=1,pos=0, pospropta=0.; s1 <=nlstate ; s1++){
                   4778:          pos += pp[s1]; /* pos is the total number of transitions until this age */
                   4779:          posprop[s1] += prop[s1][iage]; /* prop is the number of transitions from a live state
                   4780:                                            from s1 at age iage prop[s[m][iind]][(int)agev[m][iind]] += weight[iind] */
                   4781:          pospropta += prop[s1][iage]; /* prop is the number of transitions from a live state
                   4782:                                          from s1 at age iage prop[s[m][iind]][(int)agev[m][iind]] += weight[iind] */
                   4783:        }
                   4784:        
                   4785:        /* Writing ficresp */
                   4786:        if(cptcoveff==0 && nj==1){ /* no covariate and first pass */
                   4787:           if( iage <= iagemax){
                   4788:            fprintf(ficresp," %d",iage);
                   4789:           }
                   4790:         }else if( nj==2){
                   4791:           if( iage <= iagemax){
                   4792:            fprintf(ficresp," %d",iage);
                   4793:             for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresp, " %d %d",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
                   4794:           }
1.240     brouard  4795:        }
1.265     brouard  4796:        for(s1=1; s1 <=nlstate ; s1++){
1.240     brouard  4797:          if(pos>=1.e-5){
1.251     brouard  4798:            if(first==1)
1.265     brouard  4799:              printf(" %d.=%.0f prev[%d]=%.1f%%",s1,pp[s1],s1,100*pp[s1]/pos);
                   4800:            fprintf(ficlog," %d.=%.0f prev[%d]=%.1f%%",s1,pp[s1],s1,100*pp[s1]/pos);
1.251     brouard  4801:          }else{
                   4802:            if(first==1)
1.265     brouard  4803:              printf(" %d.=%.0f prev[%d]=NaNQ%%",s1,pp[s1],s1);
                   4804:            fprintf(ficlog," %d.=%.0f prev[%d]=NaNQ%%",s1,pp[s1],s1);
1.251     brouard  4805:          }
                   4806:          if( iage <= iagemax){
                   4807:            if(pos>=1.e-5){
1.265     brouard  4808:              if(cptcoveff==0 && nj==1){ /* no covariate and first pass */
                   4809:                fprintf(ficresp," %.5f %.0f %.0f",prop[s1][iage]/pospropta, prop[s1][iage],pospropta);
                   4810:               }else if( nj==2){
                   4811:                fprintf(ficresp," %.5f %.0f %.0f",prop[s1][iage]/pospropta, prop[s1][iage],pospropta);
                   4812:               }
                   4813:              fprintf(ficresphtm,"<th>%d</th><td>%.5f</td><td>%.0f</td><td>%.0f</td>",iage,prop[s1][iage]/pospropta, prop[s1][iage],pospropta);
                   4814:              /*probs[iage][s1][j1]= pp[s1]/pos;*/
                   4815:              /*printf("\niage=%d s1=%d j1=%d %.5f %.0f %.0f %f",iage,s1,j1,pp[s1]/pos, pp[s1],pos,probs[iage][s1][j1]);*/
                   4816:            } else{
                   4817:              if((cptcoveff==0 && nj==1)|| nj==2 ) fprintf(ficresp," NaNq %.0f %.0f",prop[s1][iage],pospropta);
                   4818:              fprintf(ficresphtm,"<th>%d</th><td>NaNq</td><td>%.0f</td><td>%.0f</td>",iage, prop[s1][iage],pospropta);
1.251     brouard  4819:            }
1.240     brouard  4820:          }
1.265     brouard  4821:          pospropt[s1] +=posprop[s1];
                   4822:        } /* end loop s1 */
1.251     brouard  4823:        /* pospropt=0.; */
1.265     brouard  4824:        for(s1=-1; s1 <=nlstate+ndeath; s1++){
1.251     brouard  4825:          for(m=-1; m <=nlstate+ndeath; m++){
1.265     brouard  4826:            if(freq[s1][m][iage] !=0 ) { /* minimizing output */
1.251     brouard  4827:              if(first==1){
1.265     brouard  4828:                printf(" %d%d=%.0f",s1,m,freq[s1][m][iage]);
1.251     brouard  4829:              }
1.265     brouard  4830:              /* printf(" %d%d=%.0f",s1,m,freq[s1][m][iage]); */
                   4831:              fprintf(ficlog," %d%d=%.0f",s1,m,freq[s1][m][iage]);
1.251     brouard  4832:            }
1.265     brouard  4833:            if(s1!=0 && m!=0)
                   4834:              fprintf(ficresphtmfr,"<td>%.0f</td> ",freq[s1][m][iage]);
1.240     brouard  4835:          }
1.265     brouard  4836:        } /* end loop s1 */
1.251     brouard  4837:        posproptt=0.; 
1.265     brouard  4838:        for(s1=1; s1 <=nlstate; s1++){
                   4839:          posproptt += pospropt[s1];
1.251     brouard  4840:        }
                   4841:        fprintf(ficresphtmfr,"</tr>\n ");
1.265     brouard  4842:        fprintf(ficresphtm,"</tr>\n");
                   4843:        if((cptcoveff==0 && nj==1)|| nj==2 ) {
                   4844:          if(iage <= iagemax)
                   4845:            fprintf(ficresp,"\n");
1.240     brouard  4846:        }
1.251     brouard  4847:        if(first==1)
                   4848:          printf("Others in log...\n");
                   4849:        fprintf(ficlog,"\n");
                   4850:       } /* end loop age iage */
1.265     brouard  4851:       
1.251     brouard  4852:       fprintf(ficresphtm,"<tr><th>Tot</th>");
1.265     brouard  4853:       for(s1=1; s1 <=nlstate ; s1++){
1.251     brouard  4854:        if(posproptt < 1.e-5){
1.265     brouard  4855:          fprintf(ficresphtm,"<td>Nanq</td><td>%.0f</td><td>%.0f</td>",pospropt[s1],posproptt); 
1.251     brouard  4856:        }else{
1.265     brouard  4857:          fprintf(ficresphtm,"<td>%.5f</td><td>%.0f</td><td>%.0f</td>",pospropt[s1]/posproptt,pospropt[s1],posproptt);  
1.240     brouard  4858:        }
1.226     brouard  4859:       }
1.251     brouard  4860:       fprintf(ficresphtm,"</tr>\n");
                   4861:       fprintf(ficresphtm,"</table>\n");
                   4862:       fprintf(ficresphtmfr,"</table>\n");
1.226     brouard  4863:       if(posproptt < 1.e-5){
1.251     brouard  4864:        fprintf(ficresphtm,"\n <p><b> This combination (%d) is not valid and no result will be produced</b></p>",j1);
                   4865:        fprintf(ficresphtmfr,"\n <p><b> This combination (%d) is not valid and no result will be produced</b></p>",j1);
1.260     brouard  4866:        fprintf(ficlog,"#  This combination (%d) is not valid and no result will be produced\n",j1);
                   4867:        printf("#  This combination (%d) is not valid and no result will be produced\n",j1);
1.251     brouard  4868:        invalidvarcomb[j1]=1;
1.226     brouard  4869:       }else{
1.251     brouard  4870:        fprintf(ficresphtm,"\n <p> This combination (%d) is valid and result will be produced.</p>",j1);
                   4871:        invalidvarcomb[j1]=0;
1.226     brouard  4872:       }
1.251     brouard  4873:       fprintf(ficresphtmfr,"</table>\n");
                   4874:       fprintf(ficlog,"\n");
                   4875:       if(j!=0){
                   4876:        printf("#Freqsummary: Starting values for combination j1=%d:\n", j1);
1.265     brouard  4877:        for(i=1,s1=1; i <=nlstate; i++){
1.251     brouard  4878:          for(k=1; k <=(nlstate+ndeath); k++){
                   4879:            if (k != i) {
1.265     brouard  4880:              for(jj=1; jj <=ncovmodel; jj++){ /* For counting s1 */
1.253     brouard  4881:                if(jj==1){  /* Constant case (in fact cste + age) */
1.251     brouard  4882:                  if(j1==1){ /* All dummy covariates to zero */
                   4883:                    freq[i][k][iagemax+4]=freq[i][k][iagemax+3]; /* Stores case 0 0 0 */
                   4884:                    freq[i][i][iagemax+4]=freq[i][i][iagemax+3]; /* Stores case 0 0 0 */
1.252     brouard  4885:                    printf("%d%d ",i,k);
                   4886:                    fprintf(ficlog,"%d%d ",i,k);
1.265     brouard  4887:                    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]));
                   4888:                    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]));
                   4889:                    pstart[s1]= log(freq[i][k][iagemax+3]/freq[i][i][iagemax+3]);
1.251     brouard  4890:                  }
1.253     brouard  4891:                }else if((j1==1) && (jj==2 || nagesqr==1)){ /* age or age*age parameter without covariate V4*age (to be done later) */
                   4892:                  for(iage=iagemin; iage <= iagemax+3; iage++){
                   4893:                    x[iage]= (double)iage;
                   4894:                    y[iage]= log(freq[i][k][iage]/freq[i][i][iage]);
1.265     brouard  4895:                    /* 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  4896:                  }
1.268     brouard  4897:                  /* Some are not finite, but linreg will ignore these ages */
                   4898:                  no=0;
1.253     brouard  4899:                  linreg(iagemin,iagemax,&no,x,y,&a,&b,&r, &sa, &sb ); /* y= a+b*x with standard errors */
1.265     brouard  4900:                  pstart[s1]=b;
                   4901:                  pstart[s1-1]=a;
1.252     brouard  4902:                }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 */ 
                   4903:                  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]);
                   4904:                  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  4905:                  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  4906:                  printf("%d%d ",i,k);
                   4907:                  fprintf(ficlog,"%d%d ",i,k);
1.265     brouard  4908:                  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  4909:                }else{ /* Other cases, like quantitative fixed or varying covariates */
                   4910:                  ;
                   4911:                }
                   4912:                /* printf("%12.7f )", param[i][jj][k]); */
                   4913:                /* fprintf(ficlog,"%12.7f )", param[i][jj][k]); */
1.265     brouard  4914:                s1++; 
1.251     brouard  4915:              } /* end jj */
                   4916:            } /* end k!= i */
                   4917:          } /* end k */
1.265     brouard  4918:        } /* end i, s1 */
1.251     brouard  4919:       } /* end j !=0 */
                   4920:     } /* end selected combination of covariate j1 */
                   4921:     if(j==0){ /* We can estimate starting values from the occurences in each case */
                   4922:       printf("#Freqsummary: Starting values for the constants:\n");
                   4923:       fprintf(ficlog,"\n");
1.265     brouard  4924:       for(i=1,s1=1; i <=nlstate; i++){
1.251     brouard  4925:        for(k=1; k <=(nlstate+ndeath); k++){
                   4926:          if (k != i) {
                   4927:            printf("%d%d ",i,k);
                   4928:            fprintf(ficlog,"%d%d ",i,k);
                   4929:            for(jj=1; jj <=ncovmodel; jj++){
1.265     brouard  4930:              pstart[s1]=p[s1]; /* Setting pstart to p values by default */
1.253     brouard  4931:              if(jj==1){ /* Age has to be done */
1.265     brouard  4932:                pstart[s1]= log(freq[i][k][iagemax+3]/freq[i][i][iagemax+3]);
                   4933:                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]));
                   4934:                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  4935:              }
                   4936:              /* printf("%12.7f )", param[i][jj][k]); */
                   4937:              /* fprintf(ficlog,"%12.7f )", param[i][jj][k]); */
1.265     brouard  4938:              s1++; 
1.250     brouard  4939:            }
1.251     brouard  4940:            printf("\n");
                   4941:            fprintf(ficlog,"\n");
1.250     brouard  4942:          }
                   4943:        }
1.284     brouard  4944:       } /* end of state i */
1.251     brouard  4945:       printf("#Freqsummary\n");
                   4946:       fprintf(ficlog,"\n");
1.265     brouard  4947:       for(s1=-1; s1 <=nlstate+ndeath; s1++){
                   4948:        for(s2=-1; s2 <=nlstate+ndeath; s2++){
                   4949:          /* param[i]|j][k]= freq[s1][s2][iagemax+3] */
                   4950:          printf(" %d%d=%.0f",s1,s2,freq[s1][s2][iagemax+3]);
                   4951:          fprintf(ficlog," %d%d=%.0f",s1,s2,freq[s1][s2][iagemax+3]);
                   4952:          /* if(freq[s1][s2][iage] !=0 ) { /\* minimizing output *\/ */
                   4953:          /*   printf(" %d%d=%.0f",s1,s2,freq[s1][s2][iagemax+3]); */
                   4954:          /*   fprintf(ficlog," %d%d=%.0f",s1,s2,freq[s1][s2][iagemax+3]); */
1.251     brouard  4955:          /* } */
                   4956:        }
1.265     brouard  4957:       } /* end loop s1 */
1.251     brouard  4958:       
                   4959:       printf("\n");
                   4960:       fprintf(ficlog,"\n");
                   4961:     } /* end j=0 */
1.249     brouard  4962:   } /* end j */
1.252     brouard  4963: 
1.253     brouard  4964:   if(mle == -2){  /* We want to use these values as starting values */
1.252     brouard  4965:     for(i=1, jk=1; i <=nlstate; i++){
                   4966:       for(j=1; j <=nlstate+ndeath; j++){
                   4967:        if(j!=i){
                   4968:          /*ca[0]= k+'a'-1;ca[1]='\0';*/
                   4969:          printf("%1d%1d",i,j);
                   4970:          fprintf(ficparo,"%1d%1d",i,j);
                   4971:          for(k=1; k<=ncovmodel;k++){
                   4972:            /*    printf(" %lf",param[i][j][k]); */
                   4973:            /*    fprintf(ficparo," %lf",param[i][j][k]); */
                   4974:            p[jk]=pstart[jk];
                   4975:            printf(" %f ",pstart[jk]);
                   4976:            fprintf(ficparo," %f ",pstart[jk]);
                   4977:            jk++;
                   4978:          }
                   4979:          printf("\n");
                   4980:          fprintf(ficparo,"\n");
                   4981:        }
                   4982:       }
                   4983:     }
                   4984:   } /* end mle=-2 */
1.226     brouard  4985:   dateintmean=dateintsum/k2cpt; 
1.240     brouard  4986:   
1.226     brouard  4987:   fclose(ficresp);
                   4988:   fclose(ficresphtm);
                   4989:   fclose(ficresphtmfr);
1.283     brouard  4990:   free_vector(idq,1,nqfveff);
1.226     brouard  4991:   free_vector(meanq,1,nqfveff);
1.284     brouard  4992:   free_vector(stdq,1,nqfveff);
1.226     brouard  4993:   free_matrix(meanqt,1,lastpass,1,nqtveff);
1.253     brouard  4994:   free_vector(x, iagemin-AGEMARGE, iagemax+4+AGEMARGE);
                   4995:   free_vector(y, iagemin-AGEMARGE, iagemax+4+AGEMARGE);
1.251     brouard  4996:   free_ma3x(freq,-5,nlstate+ndeath,-5,nlstate+ndeath, iagemin-AGEMARGE, iagemax+4+AGEMARGE);
1.226     brouard  4997:   free_vector(pospropt,1,nlstate);
                   4998:   free_vector(posprop,1,nlstate);
1.251     brouard  4999:   free_matrix(prop,1,nlstate,iagemin-AGEMARGE, iagemax+4+AGEMARGE);
1.226     brouard  5000:   free_vector(pp,1,nlstate);
                   5001:   /* End of freqsummary */
                   5002: }
1.126     brouard  5003: 
1.268     brouard  5004: /* Simple linear regression */
                   5005: int linreg(int ifi, int ila, int *no, const double x[], const double y[], double* a, double* b, double* r, double* sa, double * sb) {
                   5006: 
                   5007:   /* y=a+bx regression */
                   5008:   double   sumx = 0.0;                        /* sum of x                      */
                   5009:   double   sumx2 = 0.0;                       /* sum of x**2                   */
                   5010:   double   sumxy = 0.0;                       /* sum of x * y                  */
                   5011:   double   sumy = 0.0;                        /* sum of y                      */
                   5012:   double   sumy2 = 0.0;                       /* sum of y**2                   */
                   5013:   double   sume2 = 0.0;                       /* sum of square or residuals */
                   5014:   double yhat;
                   5015:   
                   5016:   double denom=0;
                   5017:   int i;
                   5018:   int ne=*no;
                   5019:   
                   5020:   for ( i=ifi, ne=0;i<=ila;i++) {
                   5021:     if(!isfinite(x[i]) || !isfinite(y[i])){
                   5022:       /* printf(" x[%d]=%f, y[%d]=%f\n",i,x[i],i,y[i]); */
                   5023:       continue;
                   5024:     }
                   5025:     ne=ne+1;
                   5026:     sumx  += x[i];       
                   5027:     sumx2 += x[i]*x[i];  
                   5028:     sumxy += x[i] * y[i];
                   5029:     sumy  += y[i];      
                   5030:     sumy2 += y[i]*y[i]; 
                   5031:     denom = (ne * sumx2 - sumx*sumx);
                   5032:     /* 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); */
                   5033:   } 
                   5034:   
                   5035:   denom = (ne * sumx2 - sumx*sumx);
                   5036:   if (denom == 0) {
                   5037:     // vertical, slope m is infinity
                   5038:     *b = INFINITY;
                   5039:     *a = 0;
                   5040:     if (r) *r = 0;
                   5041:     return 1;
                   5042:   }
                   5043:   
                   5044:   *b = (ne * sumxy  -  sumx * sumy) / denom;
                   5045:   *a = (sumy * sumx2  -  sumx * sumxy) / denom;
                   5046:   if (r!=NULL) {
                   5047:     *r = (sumxy - sumx * sumy / ne) /          /* compute correlation coeff     */
                   5048:       sqrt((sumx2 - sumx*sumx/ne) *
                   5049:           (sumy2 - sumy*sumy/ne));
                   5050:   }
                   5051:   *no=ne;
                   5052:   for ( i=ifi, ne=0;i<=ila;i++) {
                   5053:     if(!isfinite(x[i]) || !isfinite(y[i])){
                   5054:       /* printf(" x[%d]=%f, y[%d]=%f\n",i,x[i],i,y[i]); */
                   5055:       continue;
                   5056:     }
                   5057:     ne=ne+1;
                   5058:     yhat = y[i] - *a -*b* x[i];
                   5059:     sume2  += yhat * yhat ;       
                   5060:     
                   5061:     denom = (ne * sumx2 - sumx*sumx);
                   5062:     /* 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); */
                   5063:   } 
                   5064:   *sb = sqrt(sume2/(double)(ne-2)/(sumx2 - sumx * sumx /(double)ne));
                   5065:   *sa= *sb * sqrt(sumx2/ne);
                   5066:   
                   5067:   return 0; 
                   5068: }
                   5069: 
1.126     brouard  5070: /************ Prevalence ********************/
1.227     brouard  5071: 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)
                   5072: {  
                   5073:   /* Compute observed prevalence between dateprev1 and dateprev2 by counting the number of people
                   5074:      in each health status at the date of interview (if between dateprev1 and dateprev2).
                   5075:      We still use firstpass and lastpass as another selection.
                   5076:   */
1.126     brouard  5077:  
1.227     brouard  5078:   int i, m, jk, j1, bool, z1,j, iv;
                   5079:   int mi; /* Effective wave */
                   5080:   int iage;
                   5081:   double agebegin, ageend;
                   5082: 
                   5083:   double **prop;
                   5084:   double posprop; 
                   5085:   double  y2; /* in fractional years */
                   5086:   int iagemin, iagemax;
                   5087:   int first; /** to stop verbosity which is redirected to log file */
                   5088: 
                   5089:   iagemin= (int) agemin;
                   5090:   iagemax= (int) agemax;
                   5091:   /*pp=vector(1,nlstate);*/
1.251     brouard  5092:   prop=matrix(1,nlstate,iagemin-AGEMARGE,iagemax+4+AGEMARGE); 
1.227     brouard  5093:   /*  freq=ma3x(-1,nlstate+ndeath,-1,nlstate+ndeath,iagemin,iagemax+3);*/
                   5094:   j1=0;
1.222     brouard  5095:   
1.227     brouard  5096:   /*j=cptcoveff;*/
                   5097:   if (cptcovn<1) {j=1;ncodemax[1]=1;}
1.222     brouard  5098:   
1.288     brouard  5099:   first=0;
1.227     brouard  5100:   for(j1=1; j1<= (int) pow(2,cptcoveff);j1++){ /* For each combination of covariate */
                   5101:     for (i=1; i<=nlstate; i++)  
1.251     brouard  5102:       for(iage=iagemin-AGEMARGE; iage <= iagemax+4+AGEMARGE; iage++)
1.227     brouard  5103:        prop[i][iage]=0.0;
                   5104:     printf("Prevalence combination of varying and fixed dummies %d\n",j1);
                   5105:     /* fprintf(ficlog," V%d=%d ",Tvaraff[j1],nbcode[Tvaraff[j1]][codtabm(k,j1)]); */
                   5106:     fprintf(ficlog,"Prevalence combination of varying and fixed dummies %d\n",j1);
                   5107:     
                   5108:     for (i=1; i<=imx; i++) { /* Each individual */
                   5109:       bool=1;
                   5110:       /* for(m=firstpass; m<=lastpass; m++){/\* Other selection (we can limit to certain interviews*\/ */
                   5111:       for(mi=1; mi<wav[i];mi++){ /* For this wave too look where individual can be counted V4=0 V3=0 */
                   5112:        m=mw[mi][i];
                   5113:        /* Tmodelind[z1]=k is the position of the varying covariate in the model, but which # within 1 to ntv? */
                   5114:        /* Tvar[Tmodelind[z1]] is the n of Vn; n-ncovcol-nqv is the first time varying covariate or iv */
                   5115:        for (z1=1; z1<=cptcoveff; z1++){
                   5116:          if( Fixed[Tmodelind[z1]]==1){
                   5117:            iv= Tvar[Tmodelind[z1]]-ncovcol-nqv;
                   5118:            if (cotvar[m][iv][i]!= nbcode[Tvaraff[z1]][codtabm(j1,z1)]) /* iv=1 to ntv, right modality */
                   5119:              bool=0;
                   5120:          }else if( Fixed[Tmodelind[z1]]== 0)  /* fixed */
                   5121:            if (covar[Tvaraff[z1]][i]!= nbcode[Tvaraff[z1]][codtabm(j1,z1)]) {
                   5122:              bool=0;
                   5123:            }
                   5124:        }
                   5125:        if(bool==1){ /* Otherwise we skip that wave/person */
                   5126:          agebegin=agev[m][i]; /* Age at beginning of wave before transition*/
                   5127:          /* ageend=agev[m][i]+(dh[m][i])*stepm/YEARM; /\* Age at end of wave and transition *\/ */
                   5128:          if(m >=firstpass && m <=lastpass){
                   5129:            y2=anint[m][i]+(mint[m][i]/12.); /* Fractional date in year */
                   5130:            if ((y2>=dateprev1) && (y2<=dateprev2)) { /* Here is the main selection (fractional years) */
                   5131:              if(agev[m][i]==0) agev[m][i]=iagemax+1;
                   5132:              if(agev[m][i]==1) agev[m][i]=iagemax+2;
1.251     brouard  5133:              if((int)agev[m][i] <iagemin-AGEMARGE || (int)agev[m][i] >iagemax+4+AGEMARGE){
1.227     brouard  5134:                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); 
                   5135:                exit(1);
                   5136:              }
                   5137:              if (s[m][i]>0 && s[m][i]<=nlstate) { 
                   5138:                /*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]]);*/
                   5139:                prop[s[m][i]][(int)agev[m][i]] += weight[i];/* At age of beginning of transition, where status is known */
                   5140:                prop[s[m][i]][iagemax+3] += weight[i]; 
                   5141:              } /* end valid statuses */ 
                   5142:            } /* end selection of dates */
                   5143:          } /* end selection of waves */
                   5144:        } /* end bool */
                   5145:       } /* end wave */
                   5146:     } /* end individual */
                   5147:     for(i=iagemin; i <= iagemax+3; i++){  
                   5148:       for(jk=1,posprop=0; jk <=nlstate ; jk++) { 
                   5149:        posprop += prop[jk][i]; 
                   5150:       } 
                   5151:       
                   5152:       for(jk=1; jk <=nlstate ; jk++){      
                   5153:        if( i <=  iagemax){ 
                   5154:          if(posprop>=1.e-5){ 
                   5155:            probs[i][jk][j1]= prop[jk][i]/posprop;
                   5156:          } else{
1.288     brouard  5157:            if(!first){
                   5158:              first=1;
1.266     brouard  5159:              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]);
                   5160:            }else{
1.288     brouard  5161:              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  5162:            }
                   5163:          }
                   5164:        } 
                   5165:       }/* end jk */ 
                   5166:     }/* end i */ 
1.222     brouard  5167:      /*} *//* end i1 */
1.227     brouard  5168:   } /* end j1 */
1.222     brouard  5169:   
1.227     brouard  5170:   /*  free_ma3x(freq,-1,nlstate+ndeath,-1,nlstate+ndeath, iagemin, iagemax+3);*/
                   5171:   /*free_vector(pp,1,nlstate);*/
1.251     brouard  5172:   free_matrix(prop,1,nlstate, iagemin-AGEMARGE,iagemax+4+AGEMARGE);
1.227     brouard  5173: }  /* End of prevalence */
1.126     brouard  5174: 
                   5175: /************* Waves Concatenation ***************/
                   5176: 
                   5177: 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)
                   5178: {
                   5179:   /* Concatenates waves: wav[i] is the number of effective (useful waves) of individual i.
                   5180:      Death is a valid wave (if date is known).
                   5181:      mw[mi][i] is the mi (mi=1 to wav[i])  effective wave of individual i
                   5182:      dh[m][i] or dh[mw[mi][i]][i] is the delay between two effective waves m=mw[mi][i]
                   5183:      and mw[mi+1][i]. dh depends on stepm.
1.227     brouard  5184:   */
1.126     brouard  5185: 
1.224     brouard  5186:   int i=0, mi=0, m=0, mli=0;
1.126     brouard  5187:   /* int j, k=0,jk, ju, jl,jmin=1e+5, jmax=-1;
                   5188:      double sum=0., jmean=0.;*/
1.224     brouard  5189:   int first=0, firstwo=0, firsthree=0, firstfour=0, firstfiv=0;
1.126     brouard  5190:   int j, k=0,jk, ju, jl;
                   5191:   double sum=0.;
                   5192:   first=0;
1.214     brouard  5193:   firstwo=0;
1.217     brouard  5194:   firsthree=0;
1.218     brouard  5195:   firstfour=0;
1.164     brouard  5196:   jmin=100000;
1.126     brouard  5197:   jmax=-1;
                   5198:   jmean=0.;
1.224     brouard  5199: 
                   5200: /* Treating live states */
1.214     brouard  5201:   for(i=1; i<=imx; i++){  /* For simple cases and if state is death */
1.224     brouard  5202:     mi=0;  /* First valid wave */
1.227     brouard  5203:     mli=0; /* Last valid wave */
1.126     brouard  5204:     m=firstpass;
1.214     brouard  5205:     while(s[m][i] <= nlstate){  /* a live state */
1.227     brouard  5206:       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 */
                   5207:        mli=m-1;/* mw[++mi][i]=m-1; */
                   5208:       }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 */
                   5209:        mw[++mi][i]=m;
                   5210:        mli=m;
1.224     brouard  5211:       } /* else might be a useless wave  -1 and mi is not incremented and mw[mi] not updated */
                   5212:       if(m < lastpass){ /* m < lastpass, standard case */
1.227     brouard  5213:        m++; /* mi gives the "effective" current wave, m the current wave, go to next wave by incrementing m */
1.216     brouard  5214:       }
1.227     brouard  5215:       else{ /* m >= lastpass, eventual special issue with warning */
1.224     brouard  5216: #ifdef UNKNOWNSTATUSNOTCONTRIBUTING
1.227     brouard  5217:        break;
1.224     brouard  5218: #else
1.227     brouard  5219:        if(s[m][i]==-1 && (int) andc[i] == 9999 && (int)anint[m][i] != 9999){
                   5220:          if(firsthree == 0){
1.262     brouard  5221:            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  5222:            firsthree=1;
                   5223:          }
1.262     brouard  5224:          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  5225:          mw[++mi][i]=m;
                   5226:          mli=m;
                   5227:        }
                   5228:        if(s[m][i]==-2){ /* Vital status is really unknown */
                   5229:          nbwarn++;
                   5230:          if((int)anint[m][i] == 9999){  /*  Has the vital status really been verified? */
                   5231:            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);
                   5232:            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);
                   5233:          }
                   5234:          break;
                   5235:        }
                   5236:        break;
1.224     brouard  5237: #endif
1.227     brouard  5238:       }/* End m >= lastpass */
1.126     brouard  5239:     }/* end while */
1.224     brouard  5240: 
1.227     brouard  5241:     /* 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  5242:     /* After last pass */
1.224     brouard  5243: /* Treating death states */
1.214     brouard  5244:     if (s[m][i] > nlstate){  /* In a death state */
1.227     brouard  5245:       /* if( mint[m][i]==mdc[m][i] && anint[m][i]==andc[m][i]){ /\* same date of death and date of interview *\/ */
                   5246:       /* } */
1.126     brouard  5247:       mi++;    /* Death is another wave */
                   5248:       /* if(mi==0)  never been interviewed correctly before death */
1.227     brouard  5249:       /* Only death is a correct wave */
1.126     brouard  5250:       mw[mi][i]=m;
1.257     brouard  5251:     } /* else not in a death state */
1.224     brouard  5252: #ifndef DISPATCHINGKNOWNDEATHAFTERLASTWAVE
1.257     brouard  5253:     else if ((int) andc[i] != 9999) {  /* Date of death is known */
1.218     brouard  5254:       if ((int)anint[m][i]!= 9999) { /* date of last interview is known */
1.227     brouard  5255:        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 */
                   5256:          nbwarn++;
                   5257:          if(firstfiv==0){
                   5258:            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 );
                   5259:            firstfiv=1;
                   5260:          }else{
                   5261:            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 );
                   5262:          }
                   5263:        }else{ /* Death occured afer last wave potential bias */
                   5264:          nberr++;
                   5265:          if(firstwo==0){
1.257     brouard  5266:            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  5267:            firstwo=1;
                   5268:          }
1.257     brouard  5269:          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  5270:        }
1.257     brouard  5271:       }else{ /* if date of interview is unknown */
1.227     brouard  5272:        /* death is known but not confirmed by death status at any wave */
                   5273:        if(firstfour==0){
                   5274:          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 );
                   5275:          firstfour=1;
                   5276:        }
                   5277:        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  5278:       }
1.224     brouard  5279:     } /* end if date of death is known */
                   5280: #endif
                   5281:     wav[i]=mi; /* mi should be the last effective wave (or mli) */
                   5282:     /* wav[i]=mw[mi][i]; */
1.126     brouard  5283:     if(mi==0){
                   5284:       nbwarn++;
                   5285:       if(first==0){
1.227     brouard  5286:        printf("Warning! No valid information for individual %ld line=%d (skipped) and may be others, see log file\n",num[i],i);
                   5287:        first=1;
1.126     brouard  5288:       }
                   5289:       if(first==1){
1.227     brouard  5290:        fprintf(ficlog,"Warning! No valid information for individual %ld line=%d (skipped)\n",num[i],i);
1.126     brouard  5291:       }
                   5292:     } /* end mi==0 */
                   5293:   } /* End individuals */
1.214     brouard  5294:   /* wav and mw are no more changed */
1.223     brouard  5295:        
1.214     brouard  5296:   
1.126     brouard  5297:   for(i=1; i<=imx; i++){
                   5298:     for(mi=1; mi<wav[i];mi++){
                   5299:       if (stepm <=0)
1.227     brouard  5300:        dh[mi][i]=1;
1.126     brouard  5301:       else{
1.260     brouard  5302:        if (s[mw[mi+1][i]][i] > nlstate) { /* A death, but what if date is unknown? */
1.227     brouard  5303:          if (agedc[i] < 2*AGESUP) {
                   5304:            j= rint(agedc[i]*12-agev[mw[mi][i]][i]*12); 
                   5305:            if(j==0) j=1;  /* Survives at least one month after exam */
                   5306:            else if(j<0){
                   5307:              nberr++;
                   5308:              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]);
                   5309:              j=1; /* Temporary Dangerous patch */
                   5310:              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);
                   5311:              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]);
                   5312:              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);
                   5313:            }
                   5314:            k=k+1;
                   5315:            if (j >= jmax){
                   5316:              jmax=j;
                   5317:              ijmax=i;
                   5318:            }
                   5319:            if (j <= jmin){
                   5320:              jmin=j;
                   5321:              ijmin=i;
                   5322:            }
                   5323:            sum=sum+j;
                   5324:            /*if (j<0) printf("j=%d num=%d \n",j,i);*/
                   5325:            /*    printf("%d %d %d %d\n", s[mw[mi][i]][i] ,s[mw[mi+1][i]][i],j,i);*/
                   5326:          }
                   5327:        }
                   5328:        else{
                   5329:          j= rint( (agev[mw[mi+1][i]][i]*12 - agev[mw[mi][i]][i]*12));
1.126     brouard  5330: /*       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  5331:                                        
1.227     brouard  5332:          k=k+1;
                   5333:          if (j >= jmax) {
                   5334:            jmax=j;
                   5335:            ijmax=i;
                   5336:          }
                   5337:          else if (j <= jmin){
                   5338:            jmin=j;
                   5339:            ijmin=i;
                   5340:          }
                   5341:          /*        if (j<10) printf("j=%d jmin=%d num=%d ",j,jmin,i); */
                   5342:          /*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]);*/
                   5343:          if(j<0){
                   5344:            nberr++;
                   5345:            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]);
                   5346:            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]);
                   5347:          }
                   5348:          sum=sum+j;
                   5349:        }
                   5350:        jk= j/stepm;
                   5351:        jl= j -jk*stepm;
                   5352:        ju= j -(jk+1)*stepm;
                   5353:        if(mle <=1){ /* only if we use a the linear-interpoloation pseudo-likelihood */
                   5354:          if(jl==0){
                   5355:            dh[mi][i]=jk;
                   5356:            bh[mi][i]=0;
                   5357:          }else{ /* We want a negative bias in order to only have interpolation ie
                   5358:                  * to avoid the price of an extra matrix product in likelihood */
                   5359:            dh[mi][i]=jk+1;
                   5360:            bh[mi][i]=ju;
                   5361:          }
                   5362:        }else{
                   5363:          if(jl <= -ju){
                   5364:            dh[mi][i]=jk;
                   5365:            bh[mi][i]=jl;       /* bias is positive if real duration
                   5366:                                 * is higher than the multiple of stepm and negative otherwise.
                   5367:                                 */
                   5368:          }
                   5369:          else{
                   5370:            dh[mi][i]=jk+1;
                   5371:            bh[mi][i]=ju;
                   5372:          }
                   5373:          if(dh[mi][i]==0){
                   5374:            dh[mi][i]=1; /* At least one step */
                   5375:            bh[mi][i]=ju; /* At least one step */
                   5376:            /*  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);*/
                   5377:          }
                   5378:        } /* end if mle */
1.126     brouard  5379:       }
                   5380:     } /* end wave */
                   5381:   }
                   5382:   jmean=sum/k;
                   5383:   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  5384:   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  5385: }
1.126     brouard  5386: 
                   5387: /*********** Tricode ****************************/
1.220     brouard  5388:  void tricode(int *cptcov, int *Tvar, int **nbcode, int imx, int *Ndum)
1.242     brouard  5389:  {
                   5390:    /**< Uses cptcovn+2*cptcovprod as the number of covariates */
                   5391:    /*    Tvar[i]=atoi(stre);  find 'n' in Vn and stores in Tvar. If model=V2+V1 Tvar[1]=2 and Tvar[2]=1 
                   5392:     * Boring subroutine which should only output nbcode[Tvar[j]][k]
                   5393:     * Tvar[5] in V2+V1+V3*age+V2*V4 is 4 (V4) even it is a time varying or quantitative variable
                   5394:     * nbcode[Tvar[5]][1]= nbcode[4][1]=0, nbcode[4][2]=1 (usually);
                   5395:     */
1.130     brouard  5396: 
1.242     brouard  5397:    int ij=1, k=0, j=0, i=0, maxncov=NCOVMAX;
                   5398:    int modmaxcovj=0; /* Modality max of covariates j */
                   5399:    int cptcode=0; /* Modality max of covariates j */
                   5400:    int modmincovj=0; /* Modality min of covariates j */
1.145     brouard  5401: 
                   5402: 
1.242     brouard  5403:    /* cptcoveff=0;  */
                   5404:    /* *cptcov=0; */
1.126     brouard  5405:  
1.242     brouard  5406:    for (k=1; k <= maxncov; k++) ncodemax[k]=0; /* Horrible constant again replaced by NCOVMAX */
1.285     brouard  5407:    for (k=1; k <= maxncov; k++)
                   5408:      for(j=1; j<=2; j++)
                   5409:        nbcode[k][j]=0; /* Valgrind */
1.126     brouard  5410: 
1.242     brouard  5411:    /* Loop on covariates without age and products and no quantitative variable */
                   5412:    for (k=1; k<=cptcovt; k++) { /* From model V1 + V2*age + V3 + V3*V4 keeps V1 + V3 = 2 only */
                   5413:      for (j=-1; (j < maxncov); j++) Ndum[j]=0;
                   5414:      if(Dummy[k]==0 && Typevar[k] !=1){ /* Dummy covariate and not age product */ 
                   5415:        switch(Fixed[k]) {
                   5416:        case 0: /* Testing on fixed dummy covariate, simple or product of fixed */
                   5417:         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*/
                   5418:           ij=(int)(covar[Tvar[k]][i]);
                   5419:           /* ij=0 or 1 or -1. Value of the covariate Tvar[j] for individual i
                   5420:            * If product of Vn*Vm, still boolean *:
                   5421:            * If it was coded 1, 2, 3, 4 should be splitted into 3 boolean variables
                   5422:            * 1 => 0 0 0, 2 => 0 0 1, 3 => 0 1 1, 4=1 0 0   */
                   5423:           /* Finds for covariate j, n=Tvar[j] of Vn . ij is the
                   5424:              modality of the nth covariate of individual i. */
                   5425:           if (ij > modmaxcovj)
                   5426:             modmaxcovj=ij; 
                   5427:           else if (ij < modmincovj) 
                   5428:             modmincovj=ij; 
1.287     brouard  5429:           if (ij <0 || ij >1 ){
                   5430:             printf("Information, IMaCh doesn't treat covariate with missing values (-1), individual %d will be skipped.\n",i);
                   5431:             fprintf(ficlog,"Information, currently IMaCh doesn't treat covariate with missing values (-1), individual %d will be skipped.\n",i);
                   5432:           }
                   5433:           if ((ij < -1) || (ij > NCOVMAX)){
1.242     brouard  5434:             printf( "Error: minimal is less than -1 or maximal is bigger than %d. Exiting. \n", NCOVMAX );
                   5435:             exit(1);
                   5436:           }else
                   5437:             Ndum[ij]++; /*counts and stores the occurence of this modality 0, 1, -1*/
                   5438:           /*  If coded 1, 2, 3 , counts the number of 1 Ndum[1], number of 2, Ndum[2], etc */
                   5439:           /*printf("i=%d ij=%d Ndum[ij]=%d imx=%d",i,ij,Ndum[ij],imx);*/
                   5440:           /* getting the maximum value of the modality of the covariate
                   5441:              (should be 0 or 1 now) Tvar[j]. If V=sex and male is coded 0 and
                   5442:              female ies 1, then modmaxcovj=1.
                   5443:           */
                   5444:         } /* end for loop on individuals i */
                   5445:         printf(" Minimal and maximal values of %d th (fixed) covariate V%d: min=%d max=%d \n", k, Tvar[k], modmincovj, modmaxcovj);
                   5446:         fprintf(ficlog," Minimal and maximal values of %d th (fixed) covariate V%d: min=%d max=%d \n", k, Tvar[k], modmincovj, modmaxcovj);
                   5447:         cptcode=modmaxcovj;
                   5448:         /* Ndum[0] = frequency of 0 for model-covariate j, Ndum[1] frequency of 1 etc. */
                   5449:         /*for (i=0; i<=cptcode; i++) {*/
                   5450:         for (j=modmincovj;  j<=modmaxcovj; j++) { /* j=-1 ? 0 and 1*//* For each value j of the modality of model-cov k */
                   5451:           printf("Frequencies of (fixed) covariate %d ie V%d with value %d: %d\n", k, Tvar[k], j, Ndum[j]);
                   5452:           fprintf(ficlog, "Frequencies of (fixed) covariate %d ie V%d with value %d: %d\n", k, Tvar[k], j, Ndum[j]);
                   5453:           if( Ndum[j] != 0 ){ /* Counts if nobody answered modality j ie empty modality, we skip it and reorder */
                   5454:             if( j != -1){
                   5455:               ncodemax[k]++;  /* ncodemax[k]= Number of modalities of the k th
                   5456:                                  covariate for which somebody answered excluding 
                   5457:                                  undefined. Usually 2: 0 and 1. */
                   5458:             }
                   5459:             ncodemaxwundef[k]++; /* ncodemax[j]= Number of modalities of the k th
                   5460:                                     covariate for which somebody answered including 
                   5461:                                     undefined. Usually 3: -1, 0 and 1. */
                   5462:           }    /* In fact  ncodemax[k]=2 (dichotom. variables only) but it could be more for
                   5463:                 * historical reasons: 3 if coded 1, 2, 3 and 4 and Ndum[2]=0 */
                   5464:         } /* Ndum[-1] number of undefined modalities */
1.231     brouard  5465:                        
1.242     brouard  5466:         /* j is a covariate, n=Tvar[j] of Vn; Fills nbcode */
                   5467:         /* For covariate j, modalities could be 1, 2, 3, 4, 5, 6, 7. */
                   5468:         /* If Ndum[1]=0, Ndum[2]=0, Ndum[3]= 635, Ndum[4]=0, Ndum[5]=0, Ndum[6]=27, Ndum[7]=125; */
                   5469:         /* modmincovj=3; modmaxcovj = 7; */
                   5470:         /* There are only 3 modalities non empty 3, 6, 7 (or 2 if 27 is too few) : ncodemax[j]=3; */
                   5471:         /* which will be coded 0, 1, 2 which in binary on 2=3-1 digits are 0=00 1=01, 2=10; */
                   5472:         /*              defining two dummy variables: variables V1_1 and V1_2.*/
                   5473:         /* nbcode[Tvar[j]][ij]=k; */
                   5474:         /* nbcode[Tvar[j]][1]=0; */
                   5475:         /* nbcode[Tvar[j]][2]=1; */
                   5476:         /* nbcode[Tvar[j]][3]=2; */
                   5477:         /* To be continued (not working yet). */
                   5478:         ij=0; /* ij is similar to i but can jump over null modalities */
1.287     brouard  5479: 
                   5480:         /* 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*/
                   5481:         /* Skipping the case of missing values by reducing nbcode to 0 and 1 and not -1, 0, 1 */
                   5482:         /* model=V1+V2+V3, if V2=-1, 0 or 1, then nbcode[2][1]=0 and nbcode[2][2]=1 instead of
                   5483:          * nbcode[2][1]=-1, nbcode[2][2]=0 and nbcode[2][3]=1 */
                   5484:         /*, could be restored in the future */
                   5485:         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  5486:           if (Ndum[i] == 0) { /* If nobody responded to this modality k */
                   5487:             break;
                   5488:           }
                   5489:           ij++;
1.287     brouard  5490:           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  5491:           cptcode = ij; /* New max modality for covar j */
                   5492:         } /* end of loop on modality i=-1 to 1 or more */
                   5493:         break;
                   5494:        case 1: /* Testing on varying covariate, could be simple and
                   5495:                * should look at waves or product of fixed *
                   5496:                * varying. No time to test -1, assuming 0 and 1 only */
                   5497:         ij=0;
                   5498:         for(i=0; i<=1;i++){
                   5499:           nbcode[Tvar[k]][++ij]=i;
                   5500:         }
                   5501:         break;
                   5502:        default:
                   5503:         break;
                   5504:        } /* end switch */
                   5505:      } /* end dummy test */
1.287     brouard  5506:    } /* 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  5507:   
                   5508:    for (k=-1; k< maxncov; k++) Ndum[k]=0; 
                   5509:    /* Look at fixed dummy (single or product) covariates to check empty modalities */
                   5510:    for (i=1; i<=ncovmodel-2-nagesqr; i++) { /* -2, cste and age and eventually age*age */ 
                   5511:      /* Listing of all covariables in statement model to see if some covariates appear twice. For example, V1 appears twice in V1+V1*V2.*/ 
                   5512:      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 */ 
                   5513:      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 */
                   5514:      /* V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1,  {2, 1, 1, 1, 2, 1, 1, 0, 0} */
                   5515:    } /* V4+V3+V5, Ndum[1]@5={0, 0, 1, 1, 1} */
                   5516:   
                   5517:    ij=0;
                   5518:    /* for (i=0; i<=  maxncov-1; i++) { /\* modmaxcovj is unknown here. Only Ndum[2(V2),3(age*V3), 5(V3*V2) 6(V1*V4) *\/ */
                   5519:    for (k=1; k<=  cptcovt; k++) { /* modmaxcovj is unknown here. Only Ndum[2(V2),3(age*V3), 5(V3*V2) 6(V1*V4) */
                   5520:      /*printf("Ndum[%d]=%d\n",i, Ndum[i]);*/
                   5521:      /* if((Ndum[i]!=0) && (i<=ncovcol)){  /\* Tvar[i] <= ncovmodel ? *\/ */
                   5522:      if(Ndum[Tvar[k]]!=0 && Dummy[k] == 0 && Typevar[k]==0){  /* Only Dummy and non empty in the model */
                   5523:        /* If product not in single variable we don't print results */
                   5524:        /*printf("diff Ndum[%d]=%d\n",i, Ndum[i]);*/
                   5525:        ++ij;/* V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1, */
                   5526:        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*/
                   5527:        Tmodelind[ij]=k; /* Tmodelind: index in model of dummies Tmodelind[1]=2 V4: pos=2; V3: pos=3, V1=9 {2, 3, 9, ?, ?,} */
                   5528:        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 */
                   5529:        if(Fixed[k]!=0)
                   5530:         anyvaryingduminmodel=1;
                   5531:        /* }else if((Ndum[i]!=0) && (i<=ncovcol+nqv)){ */
                   5532:        /*   Tvaraff[++ij]=-10; /\* Dont'n know how to treat quantitative variables yet *\/ */
                   5533:        /* }else if((Ndum[i]!=0) && (i<=ncovcol+nqv+ntv)){ */
                   5534:        /*   Tvaraff[++ij]=i; /\*For printing (unclear) *\/ */
                   5535:        /* }else if((Ndum[i]!=0) && (i<=ncovcol+nqv+ntv+nqtv)){ */
                   5536:        /*   Tvaraff[++ij]=-20; /\* Dont'n know how to treat quantitative variables yet *\/ */
                   5537:      } 
                   5538:    } /* Tvaraff[1]@5 {3, 4, -20, 0, 0} Very strange */
                   5539:    /* ij--; */
                   5540:    /* cptcoveff=ij; /\*Number of total covariates*\/ */
                   5541:    *cptcov=ij; /*Number of total real effective covariates: effective
                   5542:                * because they can be excluded from the model and real
                   5543:                * if in the model but excluded because missing values, but how to get k from ij?*/
                   5544:    for(j=ij+1; j<= cptcovt; j++){
                   5545:      Tvaraff[j]=0;
                   5546:      Tmodelind[j]=0;
                   5547:    }
                   5548:    for(j=ntveff+1; j<= cptcovt; j++){
                   5549:      TmodelInvind[j]=0;
                   5550:    }
                   5551:    /* To be sorted */
                   5552:    ;
                   5553:  }
1.126     brouard  5554: 
1.145     brouard  5555: 
1.126     brouard  5556: /*********** Health Expectancies ****************/
                   5557: 
1.235     brouard  5558:  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  5559: 
                   5560: {
                   5561:   /* Health expectancies, no variances */
1.164     brouard  5562:   int i, j, nhstepm, hstepm, h, nstepm;
1.126     brouard  5563:   int nhstepma, nstepma; /* Decreasing with age */
                   5564:   double age, agelim, hf;
                   5565:   double ***p3mat;
                   5566:   double eip;
                   5567: 
1.238     brouard  5568:   /* pstamp(ficreseij); */
1.126     brouard  5569:   fprintf(ficreseij,"# (a) Life expectancies by health status at initial age and (b) health expectancies by health status at initial age\n");
                   5570:   fprintf(ficreseij,"# Age");
                   5571:   for(i=1; i<=nlstate;i++){
                   5572:     for(j=1; j<=nlstate;j++){
                   5573:       fprintf(ficreseij," e%1d%1d ",i,j);
                   5574:     }
                   5575:     fprintf(ficreseij," e%1d. ",i);
                   5576:   }
                   5577:   fprintf(ficreseij,"\n");
                   5578: 
                   5579:   
                   5580:   if(estepm < stepm){
                   5581:     printf ("Problem %d lower than %d\n",estepm, stepm);
                   5582:   }
                   5583:   else  hstepm=estepm;   
                   5584:   /* We compute the life expectancy from trapezoids spaced every estepm months
                   5585:    * This is mainly to measure the difference between two models: for example
                   5586:    * if stepm=24 months pijx are given only every 2 years and by summing them
                   5587:    * we are calculating an estimate of the Life Expectancy assuming a linear 
                   5588:    * progression in between and thus overestimating or underestimating according
                   5589:    * to the curvature of the survival function. If, for the same date, we 
                   5590:    * estimate the model with stepm=1 month, we can keep estepm to 24 months
                   5591:    * to compare the new estimate of Life expectancy with the same linear 
                   5592:    * hypothesis. A more precise result, taking into account a more precise
                   5593:    * curvature will be obtained if estepm is as small as stepm. */
                   5594: 
                   5595:   /* For example we decided to compute the life expectancy with the smallest unit */
                   5596:   /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm. 
                   5597:      nhstepm is the number of hstepm from age to agelim 
                   5598:      nstepm is the number of stepm from age to agelin. 
1.270     brouard  5599:      Look at hpijx to understand the reason which relies in memory size consideration
1.126     brouard  5600:      and note for a fixed period like estepm months */
                   5601:   /* We decided (b) to get a life expectancy respecting the most precise curvature of the
                   5602:      survival function given by stepm (the optimization length). Unfortunately it
                   5603:      means that if the survival funtion is printed only each two years of age and if
                   5604:      you sum them up and add 1 year (area under the trapezoids) you won't get the same 
                   5605:      results. So we changed our mind and took the option of the best precision.
                   5606:   */
                   5607:   hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */ 
                   5608: 
                   5609:   agelim=AGESUP;
                   5610:   /* If stepm=6 months */
                   5611:     /* Computed by stepm unit matrices, product of hstepm matrices, stored
                   5612:        in an array of nhstepm length: nhstepm=10, hstepm=4, stepm=6 months */
                   5613:     
                   5614: /* nhstepm age range expressed in number of stepm */
                   5615:   nstepm=(int) rint((agelim-bage)*YEARM/stepm); /* Biggest nstepm */
                   5616:   /* Typically if 20 years nstepm = 20*12/6=40 stepm */ 
                   5617:   /* if (stepm >= YEARM) hstepm=1;*/
                   5618:   nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
                   5619:   p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   5620: 
                   5621:   for (age=bage; age<=fage; age ++){ 
                   5622:     nstepma=(int) rint((agelim-bage)*YEARM/stepm); /* Biggest nstepm */
                   5623:     /* Typically if 20 years nstepm = 20*12/6=40 stepm */ 
                   5624:     /* if (stepm >= YEARM) hstepm=1;*/
                   5625:     nhstepma = nstepma/hstepm;/* Expressed in hstepm, typically nhstepma=40/4=10 */
                   5626: 
                   5627:     /* If stepm=6 months */
                   5628:     /* Computed by stepm unit matrices, product of hstepma matrices, stored
                   5629:        in an array of nhstepma length: nhstepma=10, hstepm=4, stepm=6 months */
                   5630:     
1.235     brouard  5631:     hpxij(p3mat,nhstepma,age,hstepm,x,nlstate,stepm,oldm, savm, cij, nres);  
1.126     brouard  5632:     
                   5633:     hf=hstepm*stepm/YEARM;  /* Duration of hstepm expressed in year unit. */
                   5634:     
                   5635:     printf("%d|",(int)age);fflush(stdout);
                   5636:     fprintf(ficlog,"%d|",(int)age);fflush(ficlog);
                   5637:     
                   5638:     /* Computing expectancies */
                   5639:     for(i=1; i<=nlstate;i++)
                   5640:       for(j=1; j<=nlstate;j++)
                   5641:        for (h=0, eij[i][j][(int)age]=0; h<=nhstepm-1; h++){
                   5642:          eij[i][j][(int)age] += (p3mat[i][j][h]+p3mat[i][j][h+1])/2.0*hf;
                   5643:          
                   5644:          /* 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]);*/
                   5645: 
                   5646:        }
                   5647: 
                   5648:     fprintf(ficreseij,"%3.0f",age );
                   5649:     for(i=1; i<=nlstate;i++){
                   5650:       eip=0;
                   5651:       for(j=1; j<=nlstate;j++){
                   5652:        eip +=eij[i][j][(int)age];
                   5653:        fprintf(ficreseij,"%9.4f", eij[i][j][(int)age] );
                   5654:       }
                   5655:       fprintf(ficreseij,"%9.4f", eip );
                   5656:     }
                   5657:     fprintf(ficreseij,"\n");
                   5658:     
                   5659:   }
                   5660:   free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   5661:   printf("\n");
                   5662:   fprintf(ficlog,"\n");
                   5663:   
                   5664: }
                   5665: 
1.235     brouard  5666:  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  5667: 
                   5668: {
                   5669:   /* Covariances of health expectancies eij and of total life expectancies according
1.222     brouard  5670:      to initial status i, ei. .
1.126     brouard  5671:   */
                   5672:   int i, j, nhstepm, hstepm, h, nstepm, k, cptj, cptj2, i2, j2, ij, ji;
                   5673:   int nhstepma, nstepma; /* Decreasing with age */
                   5674:   double age, agelim, hf;
                   5675:   double ***p3matp, ***p3matm, ***varhe;
                   5676:   double **dnewm,**doldm;
                   5677:   double *xp, *xm;
                   5678:   double **gp, **gm;
                   5679:   double ***gradg, ***trgradg;
                   5680:   int theta;
                   5681: 
                   5682:   double eip, vip;
                   5683: 
                   5684:   varhe=ma3x(1,nlstate*nlstate,1,nlstate*nlstate,(int) bage, (int) fage);
                   5685:   xp=vector(1,npar);
                   5686:   xm=vector(1,npar);
                   5687:   dnewm=matrix(1,nlstate*nlstate,1,npar);
                   5688:   doldm=matrix(1,nlstate*nlstate,1,nlstate*nlstate);
                   5689:   
                   5690:   pstamp(ficresstdeij);
                   5691:   fprintf(ficresstdeij,"# Health expectancies with standard errors\n");
                   5692:   fprintf(ficresstdeij,"# Age");
                   5693:   for(i=1; i<=nlstate;i++){
                   5694:     for(j=1; j<=nlstate;j++)
                   5695:       fprintf(ficresstdeij," e%1d%1d (SE)",i,j);
                   5696:     fprintf(ficresstdeij," e%1d. ",i);
                   5697:   }
                   5698:   fprintf(ficresstdeij,"\n");
                   5699: 
                   5700:   pstamp(ficrescveij);
                   5701:   fprintf(ficrescveij,"# Subdiagonal matrix of covariances of health expectancies by age: cov(eij,ekl)\n");
                   5702:   fprintf(ficrescveij,"# Age");
                   5703:   for(i=1; i<=nlstate;i++)
                   5704:     for(j=1; j<=nlstate;j++){
                   5705:       cptj= (j-1)*nlstate+i;
                   5706:       for(i2=1; i2<=nlstate;i2++)
                   5707:        for(j2=1; j2<=nlstate;j2++){
                   5708:          cptj2= (j2-1)*nlstate+i2;
                   5709:          if(cptj2 <= cptj)
                   5710:            fprintf(ficrescveij,"  %1d%1d,%1d%1d",i,j,i2,j2);
                   5711:        }
                   5712:     }
                   5713:   fprintf(ficrescveij,"\n");
                   5714:   
                   5715:   if(estepm < stepm){
                   5716:     printf ("Problem %d lower than %d\n",estepm, stepm);
                   5717:   }
                   5718:   else  hstepm=estepm;   
                   5719:   /* We compute the life expectancy from trapezoids spaced every estepm months
                   5720:    * This is mainly to measure the difference between two models: for example
                   5721:    * if stepm=24 months pijx are given only every 2 years and by summing them
                   5722:    * we are calculating an estimate of the Life Expectancy assuming a linear 
                   5723:    * progression in between and thus overestimating or underestimating according
                   5724:    * to the curvature of the survival function. If, for the same date, we 
                   5725:    * estimate the model with stepm=1 month, we can keep estepm to 24 months
                   5726:    * to compare the new estimate of Life expectancy with the same linear 
                   5727:    * hypothesis. A more precise result, taking into account a more precise
                   5728:    * curvature will be obtained if estepm is as small as stepm. */
                   5729: 
                   5730:   /* For example we decided to compute the life expectancy with the smallest unit */
                   5731:   /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm. 
                   5732:      nhstepm is the number of hstepm from age to agelim 
                   5733:      nstepm is the number of stepm from age to agelin. 
                   5734:      Look at hpijx to understand the reason of that which relies in memory size
                   5735:      and note for a fixed period like estepm months */
                   5736:   /* We decided (b) to get a life expectancy respecting the most precise curvature of the
                   5737:      survival function given by stepm (the optimization length). Unfortunately it
                   5738:      means that if the survival funtion is printed only each two years of age and if
                   5739:      you sum them up and add 1 year (area under the trapezoids) you won't get the same 
                   5740:      results. So we changed our mind and took the option of the best precision.
                   5741:   */
                   5742:   hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */ 
                   5743: 
                   5744:   /* If stepm=6 months */
                   5745:   /* nhstepm age range expressed in number of stepm */
                   5746:   agelim=AGESUP;
                   5747:   nstepm=(int) rint((agelim-bage)*YEARM/stepm); 
                   5748:   /* Typically if 20 years nstepm = 20*12/6=40 stepm */ 
                   5749:   /* if (stepm >= YEARM) hstepm=1;*/
                   5750:   nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
                   5751:   
                   5752:   p3matp=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   5753:   p3matm=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   5754:   gradg=ma3x(0,nhstepm,1,npar,1,nlstate*nlstate);
                   5755:   trgradg =ma3x(0,nhstepm,1,nlstate*nlstate,1,npar);
                   5756:   gp=matrix(0,nhstepm,1,nlstate*nlstate);
                   5757:   gm=matrix(0,nhstepm,1,nlstate*nlstate);
                   5758: 
                   5759:   for (age=bage; age<=fage; age ++){ 
                   5760:     nstepma=(int) rint((agelim-bage)*YEARM/stepm); /* Biggest nstepm */
                   5761:     /* Typically if 20 years nstepm = 20*12/6=40 stepm */ 
                   5762:     /* if (stepm >= YEARM) hstepm=1;*/
                   5763:     nhstepma = nstepma/hstepm;/* Expressed in hstepm, typically nhstepma=40/4=10 */
1.218     brouard  5764:                
1.126     brouard  5765:     /* If stepm=6 months */
                   5766:     /* Computed by stepm unit matrices, product of hstepma matrices, stored
                   5767:        in an array of nhstepma length: nhstepma=10, hstepm=4, stepm=6 months */
                   5768:     
                   5769:     hf=hstepm*stepm/YEARM;  /* Duration of hstepm expressed in year unit. */
1.218     brouard  5770:                
1.126     brouard  5771:     /* Computing  Variances of health expectancies */
                   5772:     /* Gradient is computed with plus gp and minus gm. Code is duplicated in order to
                   5773:        decrease memory allocation */
                   5774:     for(theta=1; theta <=npar; theta++){
                   5775:       for(i=1; i<=npar; i++){ 
1.222     brouard  5776:        xp[i] = x[i] + (i==theta ?delti[theta]:0);
                   5777:        xm[i] = x[i] - (i==theta ?delti[theta]:0);
1.126     brouard  5778:       }
1.235     brouard  5779:       hpxij(p3matp,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, cij, nres);  
                   5780:       hpxij(p3matm,nhstepm,age,hstepm,xm,nlstate,stepm,oldm,savm, cij, nres);  
1.218     brouard  5781:                        
1.126     brouard  5782:       for(j=1; j<= nlstate; j++){
1.222     brouard  5783:        for(i=1; i<=nlstate; i++){
                   5784:          for(h=0; h<=nhstepm-1; h++){
                   5785:            gp[h][(j-1)*nlstate + i] = (p3matp[i][j][h]+p3matp[i][j][h+1])/2.;
                   5786:            gm[h][(j-1)*nlstate + i] = (p3matm[i][j][h]+p3matm[i][j][h+1])/2.;
                   5787:          }
                   5788:        }
1.126     brouard  5789:       }
1.218     brouard  5790:                        
1.126     brouard  5791:       for(ij=1; ij<= nlstate*nlstate; ij++)
1.222     brouard  5792:        for(h=0; h<=nhstepm-1; h++){
                   5793:          gradg[h][theta][ij]= (gp[h][ij]-gm[h][ij])/2./delti[theta];
                   5794:        }
1.126     brouard  5795:     }/* End theta */
                   5796:     
                   5797:     
                   5798:     for(h=0; h<=nhstepm-1; h++)
                   5799:       for(j=1; j<=nlstate*nlstate;j++)
1.222     brouard  5800:        for(theta=1; theta <=npar; theta++)
                   5801:          trgradg[h][j][theta]=gradg[h][theta][j];
1.126     brouard  5802:     
1.218     brouard  5803:                
1.222     brouard  5804:     for(ij=1;ij<=nlstate*nlstate;ij++)
1.126     brouard  5805:       for(ji=1;ji<=nlstate*nlstate;ji++)
1.222     brouard  5806:        varhe[ij][ji][(int)age] =0.;
1.218     brouard  5807:                
1.222     brouard  5808:     printf("%d|",(int)age);fflush(stdout);
                   5809:     fprintf(ficlog,"%d|",(int)age);fflush(ficlog);
                   5810:     for(h=0;h<=nhstepm-1;h++){
1.126     brouard  5811:       for(k=0;k<=nhstepm-1;k++){
1.222     brouard  5812:        matprod2(dnewm,trgradg[h],1,nlstate*nlstate,1,npar,1,npar,matcov);
                   5813:        matprod2(doldm,dnewm,1,nlstate*nlstate,1,npar,1,nlstate*nlstate,gradg[k]);
                   5814:        for(ij=1;ij<=nlstate*nlstate;ij++)
                   5815:          for(ji=1;ji<=nlstate*nlstate;ji++)
                   5816:            varhe[ij][ji][(int)age] += doldm[ij][ji]*hf*hf;
1.126     brouard  5817:       }
                   5818:     }
1.218     brouard  5819:                
1.126     brouard  5820:     /* Computing expectancies */
1.235     brouard  5821:     hpxij(p3matm,nhstepm,age,hstepm,x,nlstate,stepm,oldm, savm, cij,nres);  
1.126     brouard  5822:     for(i=1; i<=nlstate;i++)
                   5823:       for(j=1; j<=nlstate;j++)
1.222     brouard  5824:        for (h=0, eij[i][j][(int)age]=0; h<=nhstepm-1; h++){
                   5825:          eij[i][j][(int)age] += (p3matm[i][j][h]+p3matm[i][j][h+1])/2.0*hf;
1.218     brouard  5826:                                        
1.222     brouard  5827:          /* 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  5828:                                        
1.222     brouard  5829:        }
1.269     brouard  5830: 
                   5831:     /* Standard deviation of expectancies ij */                
1.126     brouard  5832:     fprintf(ficresstdeij,"%3.0f",age );
                   5833:     for(i=1; i<=nlstate;i++){
                   5834:       eip=0.;
                   5835:       vip=0.;
                   5836:       for(j=1; j<=nlstate;j++){
1.222     brouard  5837:        eip += eij[i][j][(int)age];
                   5838:        for(k=1; k<=nlstate;k++) /* Sum on j and k of cov(eij,eik) */
                   5839:          vip += varhe[(j-1)*nlstate+i][(k-1)*nlstate+i][(int)age];
                   5840:        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  5841:       }
                   5842:       fprintf(ficresstdeij," %9.4f (%.4f)", eip, sqrt(vip));
                   5843:     }
                   5844:     fprintf(ficresstdeij,"\n");
1.218     brouard  5845:                
1.269     brouard  5846:     /* Variance of expectancies ij */          
1.126     brouard  5847:     fprintf(ficrescveij,"%3.0f",age );
                   5848:     for(i=1; i<=nlstate;i++)
                   5849:       for(j=1; j<=nlstate;j++){
1.222     brouard  5850:        cptj= (j-1)*nlstate+i;
                   5851:        for(i2=1; i2<=nlstate;i2++)
                   5852:          for(j2=1; j2<=nlstate;j2++){
                   5853:            cptj2= (j2-1)*nlstate+i2;
                   5854:            if(cptj2 <= cptj)
                   5855:              fprintf(ficrescveij," %.4f", varhe[cptj][cptj2][(int)age]);
                   5856:          }
1.126     brouard  5857:       }
                   5858:     fprintf(ficrescveij,"\n");
1.218     brouard  5859:                
1.126     brouard  5860:   }
                   5861:   free_matrix(gm,0,nhstepm,1,nlstate*nlstate);
                   5862:   free_matrix(gp,0,nhstepm,1,nlstate*nlstate);
                   5863:   free_ma3x(gradg,0,nhstepm,1,npar,1,nlstate*nlstate);
                   5864:   free_ma3x(trgradg,0,nhstepm,1,nlstate*nlstate,1,npar);
                   5865:   free_ma3x(p3matm,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   5866:   free_ma3x(p3matp,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   5867:   printf("\n");
                   5868:   fprintf(ficlog,"\n");
1.218     brouard  5869:        
1.126     brouard  5870:   free_vector(xm,1,npar);
                   5871:   free_vector(xp,1,npar);
                   5872:   free_matrix(dnewm,1,nlstate*nlstate,1,npar);
                   5873:   free_matrix(doldm,1,nlstate*nlstate,1,nlstate*nlstate);
                   5874:   free_ma3x(varhe,1,nlstate*nlstate,1,nlstate*nlstate,(int) bage, (int)fage);
                   5875: }
1.218     brouard  5876:  
1.126     brouard  5877: /************ Variance ******************/
1.235     brouard  5878:  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  5879:  {
1.279     brouard  5880:    /** Variance of health expectancies 
                   5881:     *  double **prevalim(double **prlim, int nlstate, double *xp, double age, double **oldm, double ** savm,double ftolpl);
                   5882:     * double **newm;
                   5883:     * int movingaverage(double ***probs, double bage,double fage, double ***mobaverage, int mobilav) 
                   5884:     */
1.218     brouard  5885:   
                   5886:    /* int movingaverage(); */
                   5887:    double **dnewm,**doldm;
                   5888:    double **dnewmp,**doldmp;
                   5889:    int i, j, nhstepm, hstepm, h, nstepm ;
1.288     brouard  5890:    int first=0;
1.218     brouard  5891:    int k;
                   5892:    double *xp;
1.279     brouard  5893:    double **gp, **gm;  /**< for var eij */
                   5894:    double ***gradg, ***trgradg; /**< for var eij */
                   5895:    double **gradgp, **trgradgp; /**< for var p point j */
                   5896:    double *gpp, *gmp; /**< for var p point j */
                   5897:    double **varppt; /**< for var p point j nlstate to nlstate+ndeath */
1.218     brouard  5898:    double ***p3mat;
                   5899:    double age,agelim, hf;
                   5900:    /* double ***mobaverage; */
                   5901:    int theta;
                   5902:    char digit[4];
                   5903:    char digitp[25];
                   5904: 
                   5905:    char fileresprobmorprev[FILENAMELENGTH];
                   5906: 
                   5907:    if(popbased==1){
                   5908:      if(mobilav!=0)
                   5909:        strcpy(digitp,"-POPULBASED-MOBILAV_");
                   5910:      else strcpy(digitp,"-POPULBASED-NOMOBIL_");
                   5911:    }
                   5912:    else 
                   5913:      strcpy(digitp,"-STABLBASED_");
1.126     brouard  5914: 
1.218     brouard  5915:    /* if (mobilav!=0) { */
                   5916:    /*   mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX); */
                   5917:    /*   if (movingaverage(probs, bage, fage, mobaverage,mobilav)!=0){ */
                   5918:    /*     fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav); */
                   5919:    /*     printf(" Error in movingaverage mobilav=%d\n",mobilav); */
                   5920:    /*   } */
                   5921:    /* } */
                   5922: 
                   5923:    strcpy(fileresprobmorprev,"PRMORPREV-"); 
                   5924:    sprintf(digit,"%-d",ij);
                   5925:    /*printf("DIGIT=%s, ij=%d ijr=%-d|\n",digit, ij,ij);*/
                   5926:    strcat(fileresprobmorprev,digit); /* Tvar to be done */
                   5927:    strcat(fileresprobmorprev,digitp); /* Popbased or not, mobilav or not */
                   5928:    strcat(fileresprobmorprev,fileresu);
                   5929:    if((ficresprobmorprev=fopen(fileresprobmorprev,"w"))==NULL) {
                   5930:      printf("Problem with resultfile: %s\n", fileresprobmorprev);
                   5931:      fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobmorprev);
                   5932:    }
                   5933:    printf("Computing total mortality p.j=w1*p1j+w2*p2j+..: result on file '%s' \n",fileresprobmorprev);
                   5934:    fprintf(ficlog,"Computing total mortality p.j=w1*p1j+w2*p2j+..: result on file '%s' \n",fileresprobmorprev);
                   5935:    pstamp(ficresprobmorprev);
                   5936:    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  5937:    fprintf(ficresprobmorprev,"# Selected quantitative variables and dummies");
                   5938:    for (j=1; j<= nsq; j++){ /* For each selected (single) quantitative value */
                   5939:      fprintf(ficresprobmorprev," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]);
                   5940:    }
                   5941:    for(j=1;j<=cptcoveff;j++) 
                   5942:      fprintf(ficresprobmorprev,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(ij,j)]);
                   5943:    fprintf(ficresprobmorprev,"\n");
                   5944: 
1.218     brouard  5945:    fprintf(ficresprobmorprev,"# Age cov=%-d",ij);
                   5946:    for(j=nlstate+1; j<=(nlstate+ndeath);j++){
                   5947:      fprintf(ficresprobmorprev," p.%-d SE",j);
                   5948:      for(i=1; i<=nlstate;i++)
                   5949:        fprintf(ficresprobmorprev," w%1d p%-d%-d",i,i,j);
                   5950:    }  
                   5951:    fprintf(ficresprobmorprev,"\n");
                   5952:   
                   5953:    fprintf(ficgp,"\n# Routine varevsij");
                   5954:    fprintf(ficgp,"\nunset title \n");
                   5955:    /* fprintf(fichtm, "#Local time at start: %s", strstart);*/
                   5956:    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");
                   5957:    fprintf(fichtm,"\n<br>%s  <br>\n",digitp);
1.279     brouard  5958: 
1.218     brouard  5959:    varppt = matrix(nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
                   5960:    pstamp(ficresvij);
                   5961:    fprintf(ficresvij,"# Variance and covariance of health expectancies e.j \n#  (weighted average of eij where weights are ");
                   5962:    if(popbased==1)
                   5963:      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);
                   5964:    else
                   5965:      fprintf(ficresvij,"the age specific period (stable) prevalences in each health state \n");
                   5966:    fprintf(ficresvij,"# Age");
                   5967:    for(i=1; i<=nlstate;i++)
                   5968:      for(j=1; j<=nlstate;j++)
                   5969:        fprintf(ficresvij," Cov(e.%1d, e.%1d)",i,j);
                   5970:    fprintf(ficresvij,"\n");
                   5971: 
                   5972:    xp=vector(1,npar);
                   5973:    dnewm=matrix(1,nlstate,1,npar);
                   5974:    doldm=matrix(1,nlstate,1,nlstate);
                   5975:    dnewmp= matrix(nlstate+1,nlstate+ndeath,1,npar);
                   5976:    doldmp= matrix(nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
                   5977: 
                   5978:    gradgp=matrix(1,npar,nlstate+1,nlstate+ndeath);
                   5979:    gpp=vector(nlstate+1,nlstate+ndeath);
                   5980:    gmp=vector(nlstate+1,nlstate+ndeath);
                   5981:    trgradgp =matrix(nlstate+1,nlstate+ndeath,1,npar); /* mu or p point j*/
1.126     brouard  5982:   
1.218     brouard  5983:    if(estepm < stepm){
                   5984:      printf ("Problem %d lower than %d\n",estepm, stepm);
                   5985:    }
                   5986:    else  hstepm=estepm;   
                   5987:    /* For example we decided to compute the life expectancy with the smallest unit */
                   5988:    /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm. 
                   5989:       nhstepm is the number of hstepm from age to agelim 
                   5990:       nstepm is the number of stepm from age to agelim. 
                   5991:       Look at function hpijx to understand why because of memory size limitations, 
                   5992:       we decided (b) to get a life expectancy respecting the most precise curvature of the
                   5993:       survival function given by stepm (the optimization length). Unfortunately it
                   5994:       means that if the survival funtion is printed every two years of age and if
                   5995:       you sum them up and add 1 year (area under the trapezoids) you won't get the same 
                   5996:       results. So we changed our mind and took the option of the best precision.
                   5997:    */
                   5998:    hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */ 
                   5999:    agelim = AGESUP;
                   6000:    for (age=bage; age<=fage; age ++){ /* If stepm=6 months */
                   6001:      nstepm=(int) rint((agelim-age)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */ 
                   6002:      nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
                   6003:      p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   6004:      gradg=ma3x(0,nhstepm,1,npar,1,nlstate);
                   6005:      gp=matrix(0,nhstepm,1,nlstate);
                   6006:      gm=matrix(0,nhstepm,1,nlstate);
                   6007:                
                   6008:                
                   6009:      for(theta=1; theta <=npar; theta++){
                   6010:        for(i=1; i<=npar; i++){ /* Computes gradient x + delta*/
                   6011:         xp[i] = x[i] + (i==theta ?delti[theta]:0);
                   6012:        }
1.279     brouard  6013:        /**< Computes the prevalence limit with parameter theta shifted of delta up to ftolpl precision and 
                   6014:        * returns into prlim .
1.288     brouard  6015:        */
1.242     brouard  6016:        prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp,ij, nres);
1.279     brouard  6017: 
                   6018:        /* If popbased = 1 we use crossection prevalences. Previous step is useless but prlim is created */
1.218     brouard  6019:        if (popbased==1) {
                   6020:         if(mobilav ==0){
                   6021:           for(i=1; i<=nlstate;i++)
                   6022:             prlim[i][i]=probs[(int)age][i][ij];
                   6023:         }else{ /* mobilav */ 
                   6024:           for(i=1; i<=nlstate;i++)
                   6025:             prlim[i][i]=mobaverage[(int)age][i][ij];
                   6026:         }
                   6027:        }
1.279     brouard  6028:        /**< Computes the shifted transition matrix \f$ {}{h}_p^{ij}_x\f$ at horizon h.
                   6029:        */                      
                   6030:        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  6031:        /**< 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  6032:        * at horizon h in state j including mortality.
                   6033:        */
1.218     brouard  6034:        for(j=1; j<= nlstate; j++){
                   6035:         for(h=0; h<=nhstepm; h++){
                   6036:           for(i=1, gp[h][j]=0.;i<=nlstate;i++)
                   6037:             gp[h][j] += prlim[i][i]*p3mat[i][j][h];
                   6038:         }
                   6039:        }
1.279     brouard  6040:        /* Next for computing shifted+ probability of death (h=1 means
1.218     brouard  6041:          computed over hstepm matrices product = hstepm*stepm months) 
1.279     brouard  6042:          as a weighted average of prlim(i) * p(i,j) p.3=w1*p13 + w2*p23 .
1.218     brouard  6043:        */
                   6044:        for(j=nlstate+1;j<=nlstate+ndeath;j++){
                   6045:         for(i=1,gpp[j]=0.; i<= nlstate; i++)
                   6046:           gpp[j] += prlim[i][i]*p3mat[i][j][1];
1.279     brouard  6047:        }
                   6048:        
                   6049:        /* Again with minus shift */
1.218     brouard  6050:                        
                   6051:        for(i=1; i<=npar; i++) /* Computes gradient x - delta */
                   6052:         xp[i] = x[i] - (i==theta ?delti[theta]:0);
1.288     brouard  6053: 
1.242     brouard  6054:        prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp, ij, nres);
1.218     brouard  6055:                        
                   6056:        if (popbased==1) {
                   6057:         if(mobilav ==0){
                   6058:           for(i=1; i<=nlstate;i++)
                   6059:             prlim[i][i]=probs[(int)age][i][ij];
                   6060:         }else{ /* mobilav */ 
                   6061:           for(i=1; i<=nlstate;i++)
                   6062:             prlim[i][i]=mobaverage[(int)age][i][ij];
                   6063:         }
                   6064:        }
                   6065:                        
1.235     brouard  6066:        hpxij(p3mat,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, ij,nres);  
1.218     brouard  6067:                        
                   6068:        for(j=1; j<= nlstate; j++){  /* Sum of wi * eij = e.j */
                   6069:         for(h=0; h<=nhstepm; h++){
                   6070:           for(i=1, gm[h][j]=0.;i<=nlstate;i++)
                   6071:             gm[h][j] += prlim[i][i]*p3mat[i][j][h];
                   6072:         }
                   6073:        }
                   6074:        /* This for computing probability of death (h=1 means
                   6075:          computed over hstepm matrices product = hstepm*stepm months) 
                   6076:          as a weighted average of prlim.
                   6077:        */
                   6078:        for(j=nlstate+1;j<=nlstate+ndeath;j++){
                   6079:         for(i=1,gmp[j]=0.; i<= nlstate; i++)
                   6080:           gmp[j] += prlim[i][i]*p3mat[i][j][1];
                   6081:        }    
1.279     brouard  6082:        /* end shifting computations */
                   6083: 
                   6084:        /**< Computing gradient matrix at horizon h 
                   6085:        */
1.218     brouard  6086:        for(j=1; j<= nlstate; j++) /* vareij */
                   6087:         for(h=0; h<=nhstepm; h++){
                   6088:           gradg[h][theta][j]= (gp[h][j]-gm[h][j])/2./delti[theta];
                   6089:         }
1.279     brouard  6090:        /**< Gradient of overall mortality p.3 (or p.j) 
                   6091:        */
                   6092:        for(j=nlstate+1; j<= nlstate+ndeath; j++){ /* var mu mortality from j */
1.218     brouard  6093:         gradgp[theta][j]= (gpp[j]-gmp[j])/2./delti[theta];
                   6094:        }
                   6095:                        
                   6096:      } /* End theta */
1.279     brouard  6097:      
                   6098:      /* We got the gradient matrix for each theta and state j */               
1.218     brouard  6099:      trgradg =ma3x(0,nhstepm,1,nlstate,1,npar); /* veij */
                   6100:                
                   6101:      for(h=0; h<=nhstepm; h++) /* veij */
                   6102:        for(j=1; j<=nlstate;j++)
                   6103:         for(theta=1; theta <=npar; theta++)
                   6104:           trgradg[h][j][theta]=gradg[h][theta][j];
                   6105:                
                   6106:      for(j=nlstate+1; j<=nlstate+ndeath;j++) /* mu */
                   6107:        for(theta=1; theta <=npar; theta++)
                   6108:         trgradgp[j][theta]=gradgp[theta][j];
1.279     brouard  6109:      /**< as well as its transposed matrix 
                   6110:       */               
1.218     brouard  6111:                
                   6112:      hf=hstepm*stepm/YEARM;  /* Duration of hstepm expressed in year unit. */
                   6113:      for(i=1;i<=nlstate;i++)
                   6114:        for(j=1;j<=nlstate;j++)
                   6115:         vareij[i][j][(int)age] =0.;
1.279     brouard  6116: 
                   6117:      /* Computing trgradg by matcov by gradg at age and summing over h
                   6118:       * and k (nhstepm) formula 15 of article
                   6119:       * Lievre-Brouard-Heathcote
                   6120:       */
                   6121:      
1.218     brouard  6122:      for(h=0;h<=nhstepm;h++){
                   6123:        for(k=0;k<=nhstepm;k++){
                   6124:         matprod2(dnewm,trgradg[h],1,nlstate,1,npar,1,npar,matcov);
                   6125:         matprod2(doldm,dnewm,1,nlstate,1,npar,1,nlstate,gradg[k]);
                   6126:         for(i=1;i<=nlstate;i++)
                   6127:           for(j=1;j<=nlstate;j++)
                   6128:             vareij[i][j][(int)age] += doldm[i][j]*hf*hf;
                   6129:        }
                   6130:      }
                   6131:                
1.279     brouard  6132:      /* pptj is p.3 or p.j = trgradgp by cov by gradgp, variance of
                   6133:       * p.j overall mortality formula 49 but computed directly because
                   6134:       * we compute the grad (wix pijx) instead of grad (pijx),even if
                   6135:       * wix is independent of theta.
                   6136:       */
1.218     brouard  6137:      matprod2(dnewmp,trgradgp,nlstate+1,nlstate+ndeath,1,npar,1,npar,matcov);
                   6138:      matprod2(doldmp,dnewmp,nlstate+1,nlstate+ndeath,1,npar,nlstate+1,nlstate+ndeath,gradgp);
                   6139:      for(j=nlstate+1;j<=nlstate+ndeath;j++)
                   6140:        for(i=nlstate+1;i<=nlstate+ndeath;i++)
                   6141:         varppt[j][i]=doldmp[j][i];
                   6142:      /* end ppptj */
                   6143:      /*  x centered again */
                   6144:                
1.242     brouard  6145:      prevalim(prlim,nlstate,x,age,oldm,savm,ftolpl,ncvyearp,ij, nres);
1.218     brouard  6146:                
                   6147:      if (popbased==1) {
                   6148:        if(mobilav ==0){
                   6149:         for(i=1; i<=nlstate;i++)
                   6150:           prlim[i][i]=probs[(int)age][i][ij];
                   6151:        }else{ /* mobilav */ 
                   6152:         for(i=1; i<=nlstate;i++)
                   6153:           prlim[i][i]=mobaverage[(int)age][i][ij];
                   6154:        }
                   6155:      }
                   6156:                
                   6157:      /* This for computing probability of death (h=1 means
                   6158:        computed over hstepm (estepm) matrices product = hstepm*stepm months) 
                   6159:        as a weighted average of prlim.
                   6160:      */
1.235     brouard  6161:      hpxij(p3mat,nhstepm,age,hstepm,x,nlstate,stepm,oldm,savm, ij, nres);  
1.218     brouard  6162:      for(j=nlstate+1;j<=nlstate+ndeath;j++){
                   6163:        for(i=1,gmp[j]=0.;i<= nlstate; i++) 
                   6164:         gmp[j] += prlim[i][i]*p3mat[i][j][1]; 
                   6165:      }    
                   6166:      /* end probability of death */
                   6167:                
                   6168:      fprintf(ficresprobmorprev,"%3d %d ",(int) age, ij);
                   6169:      for(j=nlstate+1; j<=(nlstate+ndeath);j++){
                   6170:        fprintf(ficresprobmorprev," %11.3e %11.3e",gmp[j], sqrt(varppt[j][j]));
                   6171:        for(i=1; i<=nlstate;i++){
                   6172:         fprintf(ficresprobmorprev," %11.3e %11.3e ",prlim[i][i],p3mat[i][j][1]);
                   6173:        }
                   6174:      } 
                   6175:      fprintf(ficresprobmorprev,"\n");
                   6176:                
                   6177:      fprintf(ficresvij,"%.0f ",age );
                   6178:      for(i=1; i<=nlstate;i++)
                   6179:        for(j=1; j<=nlstate;j++){
                   6180:         fprintf(ficresvij," %.4f", vareij[i][j][(int)age]);
                   6181:        }
                   6182:      fprintf(ficresvij,"\n");
                   6183:      free_matrix(gp,0,nhstepm,1,nlstate);
                   6184:      free_matrix(gm,0,nhstepm,1,nlstate);
                   6185:      free_ma3x(gradg,0,nhstepm,1,npar,1,nlstate);
                   6186:      free_ma3x(trgradg,0,nhstepm,1,nlstate,1,npar);
                   6187:      free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   6188:    } /* End age */
                   6189:    free_vector(gpp,nlstate+1,nlstate+ndeath);
                   6190:    free_vector(gmp,nlstate+1,nlstate+ndeath);
                   6191:    free_matrix(gradgp,1,npar,nlstate+1,nlstate+ndeath);
                   6192:    free_matrix(trgradgp,nlstate+1,nlstate+ndeath,1,npar); /* mu or p point j*/
                   6193:    /* fprintf(ficgp,"\nunset parametric;unset label; set ter png small size 320, 240"); */
                   6194:    fprintf(ficgp,"\nunset parametric;unset label; set ter svg size 640, 480");
                   6195:    /* for(j=nlstate+1; j<= nlstate+ndeath; j++){ *//* Only the first actually */
                   6196:    fprintf(ficgp,"\n set log y; unset log x;set xlabel \"Age\"; set ylabel \"Force of mortality (year-1)\";");
                   6197:    fprintf(ficgp,"\nset out \"%s%s.svg\";",subdirf3(optionfilefiname,"VARMUPTJGR-",digitp),digit);
                   6198:    /*   fprintf(ficgp,"\n plot \"%s\"  u 1:($3*%6.3f) not w l 1 ",fileresprobmorprev,YEARM/estepm); */
                   6199:    /*   fprintf(ficgp,"\n replot \"%s\"  u 1:(($3+1.96*$4)*%6.3f) t \"95\%% interval\" w l 2 ",fileresprobmorprev,YEARM/estepm); */
                   6200:    /*   fprintf(ficgp,"\n replot \"%s\"  u 1:(($3-1.96*$4)*%6.3f) not w l 2 ",fileresprobmorprev,YEARM/estepm); */
                   6201:    fprintf(ficgp,"\n plot \"%s\"  u 1:($3) not w l lt 1 ",subdirf(fileresprobmorprev));
                   6202:    fprintf(ficgp,"\n replot \"%s\"  u 1:(($3+1.96*$4)) t \"95%% interval\" w l lt 2 ",subdirf(fileresprobmorprev));
                   6203:    fprintf(ficgp,"\n replot \"%s\"  u 1:(($3-1.96*$4)) not w l lt 2 ",subdirf(fileresprobmorprev));
                   6204:    fprintf(fichtm,"\n<br> File (multiple files are possible if covariates are present): <A href=\"%s\">%s</a>\n",subdirf(fileresprobmorprev),subdirf(fileresprobmorprev));
                   6205:    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);
                   6206:    /*  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  6207:     */
1.218     brouard  6208:    /*   fprintf(ficgp,"\nset out \"varmuptjgr%s%s%s.svg\";replot;",digitp,optionfilefiname,digit); */
                   6209:    fprintf(ficgp,"\nset out;\nset out \"%s%s.svg\";replot;set out;\n",subdirf3(optionfilefiname,"VARMUPTJGR-",digitp),digit);
1.126     brouard  6210: 
1.218     brouard  6211:    free_vector(xp,1,npar);
                   6212:    free_matrix(doldm,1,nlstate,1,nlstate);
                   6213:    free_matrix(dnewm,1,nlstate,1,npar);
                   6214:    free_matrix(doldmp,nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
                   6215:    free_matrix(dnewmp,nlstate+1,nlstate+ndeath,1,npar);
                   6216:    free_matrix(varppt,nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
                   6217:    /* if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX); */
                   6218:    fclose(ficresprobmorprev);
                   6219:    fflush(ficgp);
                   6220:    fflush(fichtm); 
                   6221:  }  /* end varevsij */
1.126     brouard  6222: 
                   6223: /************ Variance of prevlim ******************/
1.269     brouard  6224:  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  6225: {
1.205     brouard  6226:   /* Variance of prevalence limit  for each state ij using current parameters x[] and estimates of neighbourhood give by delti*/
1.126     brouard  6227:   /*  double **prevalim(double **prlim, int nlstate, double *xp, double age, double **oldm, double **savm,double ftolpl);*/
1.164     brouard  6228: 
1.268     brouard  6229:   double **dnewmpar,**doldm;
1.126     brouard  6230:   int i, j, nhstepm, hstepm;
                   6231:   double *xp;
                   6232:   double *gp, *gm;
                   6233:   double **gradg, **trgradg;
1.208     brouard  6234:   double **mgm, **mgp;
1.126     brouard  6235:   double age,agelim;
                   6236:   int theta;
                   6237:   
                   6238:   pstamp(ficresvpl);
1.288     brouard  6239:   fprintf(ficresvpl,"# Standard deviation of period (forward stable) prevalences \n");
1.241     brouard  6240:   fprintf(ficresvpl,"# Age ");
                   6241:   if(nresult >=1)
                   6242:     fprintf(ficresvpl," Result# ");
1.126     brouard  6243:   for(i=1; i<=nlstate;i++)
                   6244:       fprintf(ficresvpl," %1d-%1d",i,i);
                   6245:   fprintf(ficresvpl,"\n");
                   6246: 
                   6247:   xp=vector(1,npar);
1.268     brouard  6248:   dnewmpar=matrix(1,nlstate,1,npar);
1.126     brouard  6249:   doldm=matrix(1,nlstate,1,nlstate);
                   6250:   
                   6251:   hstepm=1*YEARM; /* Every year of age */
                   6252:   hstepm=hstepm/stepm; /* Typically in stepm units, if j= 2 years, = 2/6 months = 4 */ 
                   6253:   agelim = AGESUP;
                   6254:   for (age=bage; age<=fage; age ++){ /* If stepm=6 months */
                   6255:     nhstepm=(int) rint((agelim-age)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */ 
                   6256:     if (stepm >= YEARM) hstepm=1;
                   6257:     nhstepm = nhstepm/hstepm; /* Typically 40/4=10 */
                   6258:     gradg=matrix(1,npar,1,nlstate);
1.208     brouard  6259:     mgp=matrix(1,npar,1,nlstate);
                   6260:     mgm=matrix(1,npar,1,nlstate);
1.126     brouard  6261:     gp=vector(1,nlstate);
                   6262:     gm=vector(1,nlstate);
                   6263: 
                   6264:     for(theta=1; theta <=npar; theta++){
                   6265:       for(i=1; i<=npar; i++){ /* Computes gradient */
                   6266:        xp[i] = x[i] + (i==theta ?delti[theta]:0);
                   6267:       }
1.288     brouard  6268:       /* if((int)age==79 ||(int)age== 80 ||(int)age== 81 ) */
                   6269:       /*       prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp,ij,nres); */
                   6270:       /* else */
                   6271:       prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp,ij,nres);
1.208     brouard  6272:       for(i=1;i<=nlstate;i++){
1.126     brouard  6273:        gp[i] = prlim[i][i];
1.208     brouard  6274:        mgp[theta][i] = prlim[i][i];
                   6275:       }
1.126     brouard  6276:       for(i=1; i<=npar; i++) /* Computes gradient */
                   6277:        xp[i] = x[i] - (i==theta ?delti[theta]:0);
1.288     brouard  6278:       /* if((int)age==79 ||(int)age== 80 ||(int)age== 81 ) */
                   6279:       /*       prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp,ij,nres); */
                   6280:       /* else */
                   6281:       prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp,ij,nres);
1.208     brouard  6282:       for(i=1;i<=nlstate;i++){
1.126     brouard  6283:        gm[i] = prlim[i][i];
1.208     brouard  6284:        mgm[theta][i] = prlim[i][i];
                   6285:       }
1.126     brouard  6286:       for(i=1;i<=nlstate;i++)
                   6287:        gradg[theta][i]= (gp[i]-gm[i])/2./delti[theta];
1.209     brouard  6288:       /* gradg[theta][2]= -gradg[theta][1]; */ /* For testing if nlstate=2 */
1.126     brouard  6289:     } /* End theta */
                   6290: 
                   6291:     trgradg =matrix(1,nlstate,1,npar);
                   6292: 
                   6293:     for(j=1; j<=nlstate;j++)
                   6294:       for(theta=1; theta <=npar; theta++)
                   6295:        trgradg[j][theta]=gradg[theta][j];
1.209     brouard  6296:     /* if((int)age==79 ||(int)age== 80 ||(int)age== 81 ){ */
                   6297:     /*   printf("\nmgm mgp %d ",(int)age); */
                   6298:     /*   for(j=1; j<=nlstate;j++){ */
                   6299:     /*         printf(" %d ",j); */
                   6300:     /*         for(theta=1; theta <=npar; theta++) */
                   6301:     /*           printf(" %d %lf %lf",theta,mgm[theta][j],mgp[theta][j]); */
                   6302:     /*         printf("\n "); */
                   6303:     /*   } */
                   6304:     /* } */
                   6305:     /* if((int)age==79 ||(int)age== 80 ||(int)age== 81 ){ */
                   6306:     /*   printf("\n gradg %d ",(int)age); */
                   6307:     /*   for(j=1; j<=nlstate;j++){ */
                   6308:     /*         printf("%d ",j); */
                   6309:     /*         for(theta=1; theta <=npar; theta++) */
                   6310:     /*           printf("%d %lf ",theta,gradg[theta][j]); */
                   6311:     /*         printf("\n "); */
                   6312:     /*   } */
                   6313:     /* } */
1.126     brouard  6314: 
                   6315:     for(i=1;i<=nlstate;i++)
                   6316:       varpl[i][(int)age] =0.;
1.209     brouard  6317:     if((int)age==79 ||(int)age== 80  ||(int)age== 81){
1.268     brouard  6318:     matprod2(dnewmpar,trgradg,1,nlstate,1,npar,1,npar,matcov);
                   6319:     matprod2(doldm,dnewmpar,1,nlstate,1,npar,1,nlstate,gradg);
1.205     brouard  6320:     }else{
1.268     brouard  6321:     matprod2(dnewmpar,trgradg,1,nlstate,1,npar,1,npar,matcov);
                   6322:     matprod2(doldm,dnewmpar,1,nlstate,1,npar,1,nlstate,gradg);
1.205     brouard  6323:     }
1.126     brouard  6324:     for(i=1;i<=nlstate;i++)
                   6325:       varpl[i][(int)age] = doldm[i][i]; /* Covariances are useless */
                   6326: 
                   6327:     fprintf(ficresvpl,"%.0f ",age );
1.241     brouard  6328:     if(nresult >=1)
                   6329:       fprintf(ficresvpl,"%d ",nres );
1.288     brouard  6330:     for(i=1; i<=nlstate;i++){
1.126     brouard  6331:       fprintf(ficresvpl," %.5f (%.5f)",prlim[i][i],sqrt(varpl[i][(int)age]));
1.288     brouard  6332:       /* for(j=1;j<=nlstate;j++) */
                   6333:       /*       fprintf(ficresvpl," %d %.5f ",j,prlim[j][i]); */
                   6334:     }
1.126     brouard  6335:     fprintf(ficresvpl,"\n");
                   6336:     free_vector(gp,1,nlstate);
                   6337:     free_vector(gm,1,nlstate);
1.208     brouard  6338:     free_matrix(mgm,1,npar,1,nlstate);
                   6339:     free_matrix(mgp,1,npar,1,nlstate);
1.126     brouard  6340:     free_matrix(gradg,1,npar,1,nlstate);
                   6341:     free_matrix(trgradg,1,nlstate,1,npar);
                   6342:   } /* End age */
                   6343: 
                   6344:   free_vector(xp,1,npar);
                   6345:   free_matrix(doldm,1,nlstate,1,npar);
1.268     brouard  6346:   free_matrix(dnewmpar,1,nlstate,1,nlstate);
                   6347: 
                   6348: }
                   6349: 
                   6350: 
                   6351: /************ Variance of backprevalence limit ******************/
1.269     brouard  6352:  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  6353: {
                   6354:   /* Variance of backward prevalence limit  for each state ij using current parameters x[] and estimates of neighbourhood give by delti*/
                   6355:   /*  double **prevalim(double **prlim, int nlstate, double *xp, double age, double **oldm, double **savm,double ftolpl);*/
                   6356: 
                   6357:   double **dnewmpar,**doldm;
                   6358:   int i, j, nhstepm, hstepm;
                   6359:   double *xp;
                   6360:   double *gp, *gm;
                   6361:   double **gradg, **trgradg;
                   6362:   double **mgm, **mgp;
                   6363:   double age,agelim;
                   6364:   int theta;
                   6365:   
                   6366:   pstamp(ficresvbl);
                   6367:   fprintf(ficresvbl,"# Standard deviation of back (stable) prevalences \n");
                   6368:   fprintf(ficresvbl,"# Age ");
                   6369:   if(nresult >=1)
                   6370:     fprintf(ficresvbl," Result# ");
                   6371:   for(i=1; i<=nlstate;i++)
                   6372:       fprintf(ficresvbl," %1d-%1d",i,i);
                   6373:   fprintf(ficresvbl,"\n");
                   6374: 
                   6375:   xp=vector(1,npar);
                   6376:   dnewmpar=matrix(1,nlstate,1,npar);
                   6377:   doldm=matrix(1,nlstate,1,nlstate);
                   6378:   
                   6379:   hstepm=1*YEARM; /* Every year of age */
                   6380:   hstepm=hstepm/stepm; /* Typically in stepm units, if j= 2 years, = 2/6 months = 4 */ 
                   6381:   agelim = AGEINF;
                   6382:   for (age=fage; age>=bage; age --){ /* If stepm=6 months */
                   6383:     nhstepm=(int) rint((age-agelim)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */ 
                   6384:     if (stepm >= YEARM) hstepm=1;
                   6385:     nhstepm = nhstepm/hstepm; /* Typically 40/4=10 */
                   6386:     gradg=matrix(1,npar,1,nlstate);
                   6387:     mgp=matrix(1,npar,1,nlstate);
                   6388:     mgm=matrix(1,npar,1,nlstate);
                   6389:     gp=vector(1,nlstate);
                   6390:     gm=vector(1,nlstate);
                   6391: 
                   6392:     for(theta=1; theta <=npar; theta++){
                   6393:       for(i=1; i<=npar; i++){ /* Computes gradient */
                   6394:        xp[i] = x[i] + (i==theta ?delti[theta]:0);
                   6395:       }
                   6396:       if(mobilavproj > 0 )
                   6397:        bprevalim(bprlim, mobaverage,nlstate,xp,age,ftolpl,ncvyearp,ij,nres);
                   6398:       else
                   6399:        bprevalim(bprlim, mobaverage,nlstate,xp,age,ftolpl,ncvyearp,ij,nres);
                   6400:       for(i=1;i<=nlstate;i++){
                   6401:        gp[i] = bprlim[i][i];
                   6402:        mgp[theta][i] = bprlim[i][i];
                   6403:       }
                   6404:      for(i=1; i<=npar; i++) /* Computes gradient */
                   6405:        xp[i] = x[i] - (i==theta ?delti[theta]:0);
                   6406:        if(mobilavproj > 0 )
                   6407:        bprevalim(bprlim, mobaverage,nlstate,xp,age,ftolpl,ncvyearp,ij,nres);
                   6408:        else
                   6409:        bprevalim(bprlim, mobaverage,nlstate,xp,age,ftolpl,ncvyearp,ij,nres);
                   6410:       for(i=1;i<=nlstate;i++){
                   6411:        gm[i] = bprlim[i][i];
                   6412:        mgm[theta][i] = bprlim[i][i];
                   6413:       }
                   6414:       for(i=1;i<=nlstate;i++)
                   6415:        gradg[theta][i]= (gp[i]-gm[i])/2./delti[theta];
                   6416:       /* gradg[theta][2]= -gradg[theta][1]; */ /* For testing if nlstate=2 */
                   6417:     } /* End theta */
                   6418: 
                   6419:     trgradg =matrix(1,nlstate,1,npar);
                   6420: 
                   6421:     for(j=1; j<=nlstate;j++)
                   6422:       for(theta=1; theta <=npar; theta++)
                   6423:        trgradg[j][theta]=gradg[theta][j];
                   6424:     /* if((int)age==79 ||(int)age== 80 ||(int)age== 81 ){ */
                   6425:     /*   printf("\nmgm mgp %d ",(int)age); */
                   6426:     /*   for(j=1; j<=nlstate;j++){ */
                   6427:     /*         printf(" %d ",j); */
                   6428:     /*         for(theta=1; theta <=npar; theta++) */
                   6429:     /*           printf(" %d %lf %lf",theta,mgm[theta][j],mgp[theta][j]); */
                   6430:     /*         printf("\n "); */
                   6431:     /*   } */
                   6432:     /* } */
                   6433:     /* if((int)age==79 ||(int)age== 80 ||(int)age== 81 ){ */
                   6434:     /*   printf("\n gradg %d ",(int)age); */
                   6435:     /*   for(j=1; j<=nlstate;j++){ */
                   6436:     /*         printf("%d ",j); */
                   6437:     /*         for(theta=1; theta <=npar; theta++) */
                   6438:     /*           printf("%d %lf ",theta,gradg[theta][j]); */
                   6439:     /*         printf("\n "); */
                   6440:     /*   } */
                   6441:     /* } */
                   6442: 
                   6443:     for(i=1;i<=nlstate;i++)
                   6444:       varbpl[i][(int)age] =0.;
                   6445:     if((int)age==79 ||(int)age== 80  ||(int)age== 81){
                   6446:     matprod2(dnewmpar,trgradg,1,nlstate,1,npar,1,npar,matcov);
                   6447:     matprod2(doldm,dnewmpar,1,nlstate,1,npar,1,nlstate,gradg);
                   6448:     }else{
                   6449:     matprod2(dnewmpar,trgradg,1,nlstate,1,npar,1,npar,matcov);
                   6450:     matprod2(doldm,dnewmpar,1,nlstate,1,npar,1,nlstate,gradg);
                   6451:     }
                   6452:     for(i=1;i<=nlstate;i++)
                   6453:       varbpl[i][(int)age] = doldm[i][i]; /* Covariances are useless */
                   6454: 
                   6455:     fprintf(ficresvbl,"%.0f ",age );
                   6456:     if(nresult >=1)
                   6457:       fprintf(ficresvbl,"%d ",nres );
                   6458:     for(i=1; i<=nlstate;i++)
                   6459:       fprintf(ficresvbl," %.5f (%.5f)",bprlim[i][i],sqrt(varbpl[i][(int)age]));
                   6460:     fprintf(ficresvbl,"\n");
                   6461:     free_vector(gp,1,nlstate);
                   6462:     free_vector(gm,1,nlstate);
                   6463:     free_matrix(mgm,1,npar,1,nlstate);
                   6464:     free_matrix(mgp,1,npar,1,nlstate);
                   6465:     free_matrix(gradg,1,npar,1,nlstate);
                   6466:     free_matrix(trgradg,1,nlstate,1,npar);
                   6467:   } /* End age */
                   6468: 
                   6469:   free_vector(xp,1,npar);
                   6470:   free_matrix(doldm,1,nlstate,1,npar);
                   6471:   free_matrix(dnewmpar,1,nlstate,1,nlstate);
1.126     brouard  6472: 
                   6473: }
                   6474: 
                   6475: /************ Variance of one-step probabilities  ******************/
                   6476: 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  6477:  {
                   6478:    int i, j=0,  k1, l1, tj;
                   6479:    int k2, l2, j1,  z1;
                   6480:    int k=0, l;
                   6481:    int first=1, first1, first2;
                   6482:    double cv12, mu1, mu2, lc1, lc2, v12, v21, v11, v22,v1,v2, c12, tnalp;
                   6483:    double **dnewm,**doldm;
                   6484:    double *xp;
                   6485:    double *gp, *gm;
                   6486:    double **gradg, **trgradg;
                   6487:    double **mu;
                   6488:    double age, cov[NCOVMAX+1];
                   6489:    double std=2.0; /* Number of standard deviation wide of confidence ellipsoids */
                   6490:    int theta;
                   6491:    char fileresprob[FILENAMELENGTH];
                   6492:    char fileresprobcov[FILENAMELENGTH];
                   6493:    char fileresprobcor[FILENAMELENGTH];
                   6494:    double ***varpij;
                   6495: 
                   6496:    strcpy(fileresprob,"PROB_"); 
                   6497:    strcat(fileresprob,fileres);
                   6498:    if((ficresprob=fopen(fileresprob,"w"))==NULL) {
                   6499:      printf("Problem with resultfile: %s\n", fileresprob);
                   6500:      fprintf(ficlog,"Problem with resultfile: %s\n", fileresprob);
                   6501:    }
                   6502:    strcpy(fileresprobcov,"PROBCOV_"); 
                   6503:    strcat(fileresprobcov,fileresu);
                   6504:    if((ficresprobcov=fopen(fileresprobcov,"w"))==NULL) {
                   6505:      printf("Problem with resultfile: %s\n", fileresprobcov);
                   6506:      fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobcov);
                   6507:    }
                   6508:    strcpy(fileresprobcor,"PROBCOR_"); 
                   6509:    strcat(fileresprobcor,fileresu);
                   6510:    if((ficresprobcor=fopen(fileresprobcor,"w"))==NULL) {
                   6511:      printf("Problem with resultfile: %s\n", fileresprobcor);
                   6512:      fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobcor);
                   6513:    }
                   6514:    printf("Computing standard deviation of one-step probabilities: result on file '%s' \n",fileresprob);
                   6515:    fprintf(ficlog,"Computing standard deviation of one-step probabilities: result on file '%s' \n",fileresprob);
                   6516:    printf("Computing matrix of variance covariance of one-step probabilities: result on file '%s' \n",fileresprobcov);
                   6517:    fprintf(ficlog,"Computing matrix of variance covariance of one-step probabilities: result on file '%s' \n",fileresprobcov);
                   6518:    printf("and correlation matrix of one-step probabilities: result on file '%s' \n",fileresprobcor);
                   6519:    fprintf(ficlog,"and correlation matrix of one-step probabilities: result on file '%s' \n",fileresprobcor);
                   6520:    pstamp(ficresprob);
                   6521:    fprintf(ficresprob,"#One-step probabilities and stand. devi in ()\n");
                   6522:    fprintf(ficresprob,"# Age");
                   6523:    pstamp(ficresprobcov);
                   6524:    fprintf(ficresprobcov,"#One-step probabilities and covariance matrix\n");
                   6525:    fprintf(ficresprobcov,"# Age");
                   6526:    pstamp(ficresprobcor);
                   6527:    fprintf(ficresprobcor,"#One-step probabilities and correlation matrix\n");
                   6528:    fprintf(ficresprobcor,"# Age");
1.126     brouard  6529: 
                   6530: 
1.222     brouard  6531:    for(i=1; i<=nlstate;i++)
                   6532:      for(j=1; j<=(nlstate+ndeath);j++){
                   6533:        fprintf(ficresprob," p%1d-%1d (SE)",i,j);
                   6534:        fprintf(ficresprobcov," p%1d-%1d ",i,j);
                   6535:        fprintf(ficresprobcor," p%1d-%1d ",i,j);
                   6536:      }  
                   6537:    /* fprintf(ficresprob,"\n");
                   6538:       fprintf(ficresprobcov,"\n");
                   6539:       fprintf(ficresprobcor,"\n");
                   6540:    */
                   6541:    xp=vector(1,npar);
                   6542:    dnewm=matrix(1,(nlstate)*(nlstate+ndeath),1,npar);
                   6543:    doldm=matrix(1,(nlstate)*(nlstate+ndeath),1,(nlstate)*(nlstate+ndeath));
                   6544:    mu=matrix(1,(nlstate)*(nlstate+ndeath), (int) bage, (int)fage);
                   6545:    varpij=ma3x(1,nlstate*(nlstate+ndeath),1,nlstate*(nlstate+ndeath),(int) bage, (int) fage);
                   6546:    first=1;
                   6547:    fprintf(ficgp,"\n# Routine varprob");
                   6548:    fprintf(fichtm,"\n<li><h4> Computing and drawing one step probabilities with their confidence intervals</h4></li>\n");
                   6549:    fprintf(fichtm,"\n");
                   6550: 
1.288     brouard  6551:    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  6552:    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);
                   6553:    fprintf(fichtmcov,"\nEllipsoids of confidence centered on point (p<inf>ij</inf>, p<inf>kl</inf>) are estimated \
1.126     brouard  6554: and drawn. It helps understanding how is the covariance between two incidences.\
                   6555:  They are expressed in year<sup>-1</sup> in order to be less dependent of stepm.<br>\n");
1.222     brouard  6556:    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  6557: It can be understood this way: if pij and pkl where uncorrelated the (2x2) matrix of covariance \
                   6558: would have been (1/(var pij), 0 , 0, 1/(var pkl)), and the confidence interval would be 2 \
                   6559: standard deviations wide on each axis. <br>\
                   6560:  Now, if both incidences are correlated (usual case) we diagonalised the inverse of the covariance matrix\
                   6561:  and made the appropriate rotation to look at the uncorrelated principal directions.<br>\
                   6562: To be simple, these graphs help to understand the significativity of each parameter in relation to a second other one.<br> \n");
                   6563: 
1.222     brouard  6564:    cov[1]=1;
                   6565:    /* tj=cptcoveff; */
1.225     brouard  6566:    tj = (int) pow(2,cptcoveff);
1.222     brouard  6567:    if (cptcovn<1) {tj=1;ncodemax[1]=1;}
                   6568:    j1=0;
1.224     brouard  6569:    for(j1=1; j1<=tj;j1++){  /* For each valid combination of covariates or only once*/
1.222     brouard  6570:      if  (cptcovn>0) {
                   6571:        fprintf(ficresprob, "\n#********** Variable "); 
1.225     brouard  6572:        for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresprob, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
1.222     brouard  6573:        fprintf(ficresprob, "**********\n#\n");
                   6574:        fprintf(ficresprobcov, "\n#********** Variable "); 
1.225     brouard  6575:        for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresprobcov, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
1.222     brouard  6576:        fprintf(ficresprobcov, "**********\n#\n");
1.220     brouard  6577:                        
1.222     brouard  6578:        fprintf(ficgp, "\n#********** Variable "); 
1.225     brouard  6579:        for (z1=1; z1<=cptcoveff; z1++) fprintf(ficgp, " V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
1.222     brouard  6580:        fprintf(ficgp, "**********\n#\n");
1.220     brouard  6581:                        
                   6582:                        
1.222     brouard  6583:        fprintf(fichtmcov, "\n<hr  size=\"2\" color=\"#EC5E5E\">********** Variable "); 
1.225     brouard  6584:        for (z1=1; z1<=cptcoveff; z1++) fprintf(fichtm, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
1.222     brouard  6585:        fprintf(fichtmcov, "**********\n<hr size=\"2\" color=\"#EC5E5E\">");
1.220     brouard  6586:                        
1.222     brouard  6587:        fprintf(ficresprobcor, "\n#********** Variable ");    
1.225     brouard  6588:        for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresprobcor, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
1.222     brouard  6589:        fprintf(ficresprobcor, "**********\n#");    
                   6590:        if(invalidvarcomb[j1]){
                   6591:         fprintf(ficgp,"\n#Combination (%d) ignored because no cases \n",j1); 
                   6592:         fprintf(fichtmcov,"\n<h3>Combination (%d) ignored because no cases </h3>\n",j1); 
                   6593:         continue;
                   6594:        }
                   6595:      }
                   6596:      gradg=matrix(1,npar,1,(nlstate)*(nlstate+ndeath));
                   6597:      trgradg=matrix(1,(nlstate)*(nlstate+ndeath),1,npar);
                   6598:      gp=vector(1,(nlstate)*(nlstate+ndeath));
                   6599:      gm=vector(1,(nlstate)*(nlstate+ndeath));
                   6600:      for (age=bage; age<=fage; age ++){ 
                   6601:        cov[2]=age;
                   6602:        if(nagesqr==1)
                   6603:         cov[3]= age*age;
                   6604:        for (k=1; k<=cptcovn;k++) {
                   6605:         cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(j1,k)];
                   6606:         /*cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(j1,Tvar[k])];*//* j1 1 2 3 4
                   6607:                                                                    * 1  1 1 1 1
                   6608:                                                                    * 2  2 1 1 1
                   6609:                                                                    * 3  1 2 1 1
                   6610:                                                                    */
                   6611:         /* nbcode[1][1]=0 nbcode[1][2]=1;*/
                   6612:        }
                   6613:        /* for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2]; */
                   6614:        for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,k)]*cov[2];
                   6615:        for (k=1; k<=cptcovprod;k++)
                   6616:         cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)]*nbcode[Tvard[k][2]][codtabm(ij,k)];
1.220     brouard  6617:                        
                   6618:                        
1.222     brouard  6619:        for(theta=1; theta <=npar; theta++){
                   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);
1.220     brouard  6624:                                
1.222     brouard  6625:         k=0;
                   6626:         for(i=1; i<= (nlstate); i++){
                   6627:           for(j=1; j<=(nlstate+ndeath);j++){
                   6628:             k=k+1;
                   6629:             gp[k]=pmmij[i][j];
                   6630:           }
                   6631:         }
1.220     brouard  6632:                                
1.222     brouard  6633:         for(i=1; i<=npar; i++)
                   6634:           xp[i] = x[i] - (i==theta ?delti[theta]:(double)0);
1.220     brouard  6635:                                
1.222     brouard  6636:         pmij(pmmij,cov,ncovmodel,xp,nlstate);
                   6637:         k=0;
                   6638:         for(i=1; i<=(nlstate); i++){
                   6639:           for(j=1; j<=(nlstate+ndeath);j++){
                   6640:             k=k+1;
                   6641:             gm[k]=pmmij[i][j];
                   6642:           }
                   6643:         }
1.220     brouard  6644:                                
1.222     brouard  6645:         for(i=1; i<= (nlstate)*(nlstate+ndeath); i++) 
                   6646:           gradg[theta][i]=(gp[i]-gm[i])/(double)2./delti[theta];  
                   6647:        }
1.126     brouard  6648: 
1.222     brouard  6649:        for(j=1; j<=(nlstate)*(nlstate+ndeath);j++)
                   6650:         for(theta=1; theta <=npar; theta++)
                   6651:           trgradg[j][theta]=gradg[theta][j];
1.220     brouard  6652:                        
1.222     brouard  6653:        matprod2(dnewm,trgradg,1,(nlstate)*(nlstate+ndeath),1,npar,1,npar,matcov); 
                   6654:        matprod2(doldm,dnewm,1,(nlstate)*(nlstate+ndeath),1,npar,1,(nlstate)*(nlstate+ndeath),gradg);
1.220     brouard  6655:                        
1.222     brouard  6656:        pmij(pmmij,cov,ncovmodel,x,nlstate);
1.220     brouard  6657:                        
1.222     brouard  6658:        k=0;
                   6659:        for(i=1; i<=(nlstate); i++){
                   6660:         for(j=1; j<=(nlstate+ndeath);j++){
                   6661:           k=k+1;
                   6662:           mu[k][(int) age]=pmmij[i][j];
                   6663:         }
                   6664:        }
                   6665:        for(i=1;i<=(nlstate)*(nlstate+ndeath);i++)
                   6666:         for(j=1;j<=(nlstate)*(nlstate+ndeath);j++)
                   6667:           varpij[i][j][(int)age] = doldm[i][j];
1.220     brouard  6668:                        
1.222     brouard  6669:        /*printf("\n%d ",(int)age);
                   6670:         for (i=1; i<=(nlstate)*(nlstate+ndeath);i++){
                   6671:         printf("%e [%e ;%e] ",gm[i],gm[i]-2*sqrt(doldm[i][i]),gm[i]+2*sqrt(doldm[i][i]));
                   6672:         fprintf(ficlog,"%e [%e ;%e] ",gm[i],gm[i]-2*sqrt(doldm[i][i]),gm[i]+2*sqrt(doldm[i][i]));
                   6673:         }*/
1.220     brouard  6674:                        
1.222     brouard  6675:        fprintf(ficresprob,"\n%d ",(int)age);
                   6676:        fprintf(ficresprobcov,"\n%d ",(int)age);
                   6677:        fprintf(ficresprobcor,"\n%d ",(int)age);
1.220     brouard  6678:                        
1.222     brouard  6679:        for (i=1; i<=(nlstate)*(nlstate+ndeath);i++)
                   6680:         fprintf(ficresprob,"%11.3e (%11.3e) ",mu[i][(int) age],sqrt(varpij[i][i][(int)age]));
                   6681:        for (i=1; i<=(nlstate)*(nlstate+ndeath);i++){
                   6682:         fprintf(ficresprobcov,"%11.3e ",mu[i][(int) age]);
                   6683:         fprintf(ficresprobcor,"%11.3e ",mu[i][(int) age]);
                   6684:        }
                   6685:        i=0;
                   6686:        for (k=1; k<=(nlstate);k++){
                   6687:         for (l=1; l<=(nlstate+ndeath);l++){ 
                   6688:           i++;
                   6689:           fprintf(ficresprobcov,"\n%d %d-%d",(int)age,k,l);
                   6690:           fprintf(ficresprobcor,"\n%d %d-%d",(int)age,k,l);
                   6691:           for (j=1; j<=i;j++){
                   6692:             /* printf(" k=%d l=%d i=%d j=%d\n",k,l,i,j);fflush(stdout); */
                   6693:             fprintf(ficresprobcov," %11.3e",varpij[i][j][(int)age]);
                   6694:             fprintf(ficresprobcor," %11.3e",varpij[i][j][(int) age]/sqrt(varpij[i][i][(int) age])/sqrt(varpij[j][j][(int)age]));
                   6695:           }
                   6696:         }
                   6697:        }/* end of loop for state */
                   6698:      } /* end of loop for age */
                   6699:      free_vector(gp,1,(nlstate+ndeath)*(nlstate+ndeath));
                   6700:      free_vector(gm,1,(nlstate+ndeath)*(nlstate+ndeath));
                   6701:      free_matrix(trgradg,1,(nlstate+ndeath)*(nlstate+ndeath),1,npar);
                   6702:      free_matrix(gradg,1,(nlstate+ndeath)*(nlstate+ndeath),1,npar);
                   6703:     
                   6704:      /* Confidence intervalle of pij  */
                   6705:      /*
                   6706:        fprintf(ficgp,"\nunset parametric;unset label");
                   6707:        fprintf(ficgp,"\nset log y;unset log x; set xlabel \"Age\";set ylabel \"probability (year-1)\"");
                   6708:        fprintf(ficgp,"\nset ter png small\nset size 0.65,0.65");
                   6709:        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);
                   6710:        fprintf(fichtm,"\n<br><img src=\"pijgr%s.png\"> ",optionfilefiname);
                   6711:        fprintf(ficgp,"\nset out \"pijgr%s.png\"",optionfilefiname);
                   6712:        fprintf(ficgp,"\nplot \"%s\" every :::%d::%d u 1:2 \"\%%lf",k1,k2,xfilevarprob);
                   6713:      */
                   6714:                
                   6715:      /* Drawing ellipsoids of confidence of two variables p(k1-l1,k2-l2)*/
                   6716:      first1=1;first2=2;
                   6717:      for (k2=1; k2<=(nlstate);k2++){
                   6718:        for (l2=1; l2<=(nlstate+ndeath);l2++){ 
                   6719:         if(l2==k2) continue;
                   6720:         j=(k2-1)*(nlstate+ndeath)+l2;
                   6721:         for (k1=1; k1<=(nlstate);k1++){
                   6722:           for (l1=1; l1<=(nlstate+ndeath);l1++){ 
                   6723:             if(l1==k1) continue;
                   6724:             i=(k1-1)*(nlstate+ndeath)+l1;
                   6725:             if(i<=j) continue;
                   6726:             for (age=bage; age<=fage; age ++){ 
                   6727:               if ((int)age %5==0){
                   6728:                 v1=varpij[i][i][(int)age]/stepm*YEARM/stepm*YEARM;
                   6729:                 v2=varpij[j][j][(int)age]/stepm*YEARM/stepm*YEARM;
                   6730:                 cv12=varpij[i][j][(int)age]/stepm*YEARM/stepm*YEARM;
                   6731:                 mu1=mu[i][(int) age]/stepm*YEARM ;
                   6732:                 mu2=mu[j][(int) age]/stepm*YEARM;
                   6733:                 c12=cv12/sqrt(v1*v2);
                   6734:                 /* Computing eigen value of matrix of covariance */
                   6735:                 lc1=((v1+v2)+sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
                   6736:                 lc2=((v1+v2)-sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
                   6737:                 if ((lc2 <0) || (lc1 <0) ){
                   6738:                   if(first2==1){
                   6739:                     first1=0;
                   6740:                     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);
                   6741:                   }
                   6742:                   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);
                   6743:                   /* lc1=fabs(lc1); */ /* If we want to have them positive */
                   6744:                   /* lc2=fabs(lc2); */
                   6745:                 }
1.220     brouard  6746:                                                                
1.222     brouard  6747:                 /* Eigen vectors */
1.280     brouard  6748:                 if(1+(v1-lc1)*(v1-lc1)/cv12/cv12 <1.e-5){
                   6749:                   printf(" Error sqrt of a negative number: %lf\n",1+(v1-lc1)*(v1-lc1)/cv12/cv12);
                   6750:                   fprintf(ficlog," Error sqrt of a negative number: %lf\n",1+(v1-lc1)*(v1-lc1)/cv12/cv12);
                   6751:                   v11=(1./sqrt(fabs(1+(v1-lc1)*(v1-lc1)/cv12/cv12)));
                   6752:                 }else
                   6753:                   v11=(1./sqrt(1+(v1-lc1)*(v1-lc1)/cv12/cv12));
1.222     brouard  6754:                 /*v21=sqrt(1.-v11*v11); *//* error */
                   6755:                 v21=(lc1-v1)/cv12*v11;
                   6756:                 v12=-v21;
                   6757:                 v22=v11;
                   6758:                 tnalp=v21/v11;
                   6759:                 if(first1==1){
                   6760:                   first1=0;
                   6761:                   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);
                   6762:                 }
                   6763:                 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);
                   6764:                 /*printf(fignu*/
                   6765:                 /* mu1+ v11*lc1*cost + v12*lc2*sin(t) */
                   6766:                 /* mu2+ v21*lc1*cost + v22*lc2*sin(t) */
                   6767:                 if(first==1){
                   6768:                   first=0;
                   6769:                   fprintf(ficgp,"\n# Ellipsoids of confidence\n#\n");
                   6770:                   fprintf(ficgp,"\nset parametric;unset label");
                   6771:                   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);
                   6772:                   fprintf(ficgp,"\nset ter svg size 640, 480");
1.266     brouard  6773:                   fprintf(fichtmcov,"\n<p><br>Ellipsoids of confidence cov(p%1d%1d,p%1d%1d) expressed in year<sup>-1</sup>\
1.220     brouard  6774:  :<a href=\"%s_%d%1d%1d-%1d%1d.svg\">                                                                                                                                          \
1.201     brouard  6775: %s_%d%1d%1d-%1d%1d.svg</A>, ",k1,l1,k2,l2,\
1.222     brouard  6776:                           subdirf2(optionfilefiname,"VARPIJGR_"), j1,k1,l1,k2,l2,      \
                   6777:                           subdirf2(optionfilefiname,"VARPIJGR_"), j1,k1,l1,k2,l2);
                   6778:                   fprintf(fichtmcov,"\n<br><img src=\"%s_%d%1d%1d-%1d%1d.svg\"> ",subdirf2(optionfilefiname,"VARPIJGR_"), j1,k1,l1,k2,l2);
                   6779:                   fprintf(fichtmcov,"\n<br> Correlation at age %d (%.3f),",(int) age, c12);
                   6780:                   fprintf(ficgp,"\nset out \"%s_%d%1d%1d-%1d%1d.svg\"",subdirf2(optionfilefiname,"VARPIJGR_"), j1,k1,l1,k2,l2);
                   6781:                   fprintf(ficgp,"\nset label \"%d\" at %11.3e,%11.3e center",(int) age, mu1,mu2);
                   6782:                   fprintf(ficgp,"\n# Age %d, p%1d%1d - p%1d%1d",(int) age, k1,l1,k2,l2);
                   6783:                   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  6784:                           mu1,std,v11,sqrt(fabs(lc1)),v12,sqrt(fabs(lc2)), \
                   6785:                           mu2,std,v21,sqrt(fabs(lc1)),v22,sqrt(fabs(lc2))); /* For gnuplot only */
1.222     brouard  6786:                 }else{
                   6787:                   first=0;
                   6788:                   fprintf(fichtmcov," %d (%.3f),",(int) age, c12);
                   6789:                   fprintf(ficgp,"\n# Age %d, p%1d%1d - p%1d%1d",(int) age, k1,l1,k2,l2);
                   6790:                   fprintf(ficgp,"\nset label \"%d\" at %11.3e,%11.3e center",(int) age, mu1,mu2);
                   6791:                   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  6792:                           mu1,std,v11,sqrt(lc1),v12,sqrt(fabs(lc2)),   \
                   6793:                           mu2,std,v21,sqrt(lc1),v22,sqrt(fabs(lc2)));
1.222     brouard  6794:                 }/* if first */
                   6795:               } /* age mod 5 */
                   6796:             } /* end loop age */
                   6797:             fprintf(ficgp,"\nset out;\nset out \"%s_%d%1d%1d-%1d%1d.svg\";replot;set out;",subdirf2(optionfilefiname,"VARPIJGR_"), j1,k1,l1,k2,l2);
                   6798:             first=1;
                   6799:           } /*l12 */
                   6800:         } /* k12 */
                   6801:        } /*l1 */
                   6802:      }/* k1 */
                   6803:    }  /* loop on combination of covariates j1 */
                   6804:    free_ma3x(varpij,1,nlstate,1,nlstate+ndeath,(int) bage, (int)fage);
                   6805:    free_matrix(mu,1,(nlstate+ndeath)*(nlstate+ndeath),(int) bage, (int)fage);
                   6806:    free_matrix(doldm,1,(nlstate)*(nlstate+ndeath),1,(nlstate)*(nlstate+ndeath));
                   6807:    free_matrix(dnewm,1,(nlstate)*(nlstate+ndeath),1,npar);
                   6808:    free_vector(xp,1,npar);
                   6809:    fclose(ficresprob);
                   6810:    fclose(ficresprobcov);
                   6811:    fclose(ficresprobcor);
                   6812:    fflush(ficgp);
                   6813:    fflush(fichtmcov);
                   6814:  }
1.126     brouard  6815: 
                   6816: 
                   6817: /******************* Printing html file ***********/
1.201     brouard  6818: void printinghtml(char fileresu[], char title[], char datafile[], int firstpass, \
1.126     brouard  6819:                  int lastpass, int stepm, int weightopt, char model[],\
                   6820:                  int imx,int jmin, int jmax, double jmeanint,char rfileres[],\
1.258     brouard  6821:                  int popforecast, int mobilav, int prevfcast, int mobilavproj, int backcast, int estepm , \
1.273     brouard  6822:                  double jprev1, double mprev1,double anprev1, double dateprev1, double dateproj1, double dateback1, \
                   6823:                  double jprev2, double mprev2,double anprev2, double dateprev2, double dateproj2, double dateback2){
1.237     brouard  6824:   int jj1, k1, i1, cpt, k4, nres;
1.126     brouard  6825: 
                   6826:    fprintf(fichtm,"<ul><li><a href='#firstorder'>Result files (first order: no variance)</a>\n \
                   6827:    <li><a href='#secondorder'>Result files (second order (variance)</a>\n \
                   6828: </ul>");
1.237     brouard  6829:    fprintf(fichtm,"<ul><li> model=1+age+%s\n \
                   6830: </ul>", model);
1.214     brouard  6831:    fprintf(fichtm,"<ul><li><h4><a name='firstorder'>Result files (first order: no variance)</a></h4>\n");
                   6832:    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",
                   6833:           jprev1, mprev1,anprev1,jprev2, mprev2,anprev2,subdirfext3(optionfilefiname,"PHTMFR_",".htm"),subdirfext3(optionfilefiname,"PHTMFR_",".htm"));
                   6834:    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  6835:           jprev1, mprev1,anprev1,jprev2, mprev2,anprev2,subdirfext3(optionfilefiname,"PHTM_",".htm"),subdirfext3(optionfilefiname,"PHTM_",".htm"));
                   6836:    fprintf(fichtm,",  <a href=\"%s\">%s</a> (text file) <br>\n",subdirf2(fileresu,"P_"),subdirf2(fileresu,"P_"));
1.126     brouard  6837:    fprintf(fichtm,"\
                   6838:  - Estimated transition probabilities over %d (stepm) months: <a href=\"%s\">%s</a><br>\n ",
1.201     brouard  6839:           stepm,subdirf2(fileresu,"PIJ_"),subdirf2(fileresu,"PIJ_"));
1.126     brouard  6840:    fprintf(fichtm,"\
1.217     brouard  6841:  - Estimated back transition probabilities over %d (stepm) months: <a href=\"%s\">%s</a><br>\n ",
                   6842:           stepm,subdirf2(fileresu,"PIJB_"),subdirf2(fileresu,"PIJB_"));
                   6843:    fprintf(fichtm,"\
1.288     brouard  6844:  - Period (forward) prevalence in each health state: <a href=\"%s\">%s</a> <br>\n",
1.201     brouard  6845:           subdirf2(fileresu,"PL_"),subdirf2(fileresu,"PL_"));
1.126     brouard  6846:    fprintf(fichtm,"\
1.288     brouard  6847:  - Backward prevalence in each health state: <a href=\"%s\">%s</a> <br>\n",
1.217     brouard  6848:           subdirf2(fileresu,"PLB_"),subdirf2(fileresu,"PLB_"));
                   6849:    fprintf(fichtm,"\
1.211     brouard  6850:  - (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  6851:    <a href=\"%s\">%s</a> <br>\n",
1.201     brouard  6852:           estepm,subdirf2(fileresu,"E_"),subdirf2(fileresu,"E_"));
1.211     brouard  6853:    if(prevfcast==1){
                   6854:      fprintf(fichtm,"\
                   6855:  - Prevalence projections by age and states:                           \
1.201     brouard  6856:    <a href=\"%s\">%s</a> <br>\n</li>", subdirf2(fileresu,"F_"),subdirf2(fileresu,"F_"));
1.211     brouard  6857:    }
1.126     brouard  6858: 
                   6859: 
1.225     brouard  6860:    m=pow(2,cptcoveff);
1.222     brouard  6861:    if (cptcovn < 1) {m=1;ncodemax[1]=1;}
1.126     brouard  6862: 
1.264     brouard  6863:    fprintf(fichtm," \n<ul><li><b>Graphs</b></li><p>");
                   6864: 
                   6865:    jj1=0;
                   6866: 
                   6867:    fprintf(fichtm," \n<ul>");
                   6868:    for(nres=1; nres <= nresult; nres++) /* For each resultline */
                   6869:    for(k1=1; k1<=m;k1++){ /* For each combination of covariate */
                   6870:      if(m != 1 && TKresult[nres]!= k1)
                   6871:        continue;
                   6872:      jj1++;
                   6873:      if (cptcovn > 0) {
                   6874:        fprintf(fichtm,"\n<li><a  size=\"1\" color=\"#EC5E5E\" href=\"#rescov");
                   6875:        for (cpt=1; cpt<=cptcoveff;cpt++){ 
                   6876:         fprintf(fichtm,"_V%d=%d_",Tvresult[nres][cpt],(int)Tresult[nres][cpt]);
                   6877:        }
                   6878:        for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
                   6879:         fprintf(fichtm,"_V%d=%f_",Tvqresult[nres][k4],Tqresult[nres][k4]);
                   6880:        }
                   6881:        fprintf(fichtm,"\">");
                   6882:        
                   6883:        /* if(nqfveff+nqtveff 0) */ /* Test to be done */
                   6884:        fprintf(fichtm,"************ Results for covariates");
                   6885:        for (cpt=1; cpt<=cptcoveff;cpt++){ 
                   6886:         fprintf(fichtm," V%d=%d ",Tvresult[nres][cpt],(int)Tresult[nres][cpt]);
                   6887:        }
                   6888:        for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
                   6889:         fprintf(fichtm," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
                   6890:        }
                   6891:        if(invalidvarcomb[k1]){
                   6892:         fprintf(fichtm," Warning Combination (%d) ignored because no cases ",k1); 
                   6893:         continue;
                   6894:        }
                   6895:        fprintf(fichtm,"</a></li>");
                   6896:      } /* cptcovn >0 */
                   6897:    }
                   6898:      fprintf(fichtm," \n</ul>");
                   6899: 
1.222     brouard  6900:    jj1=0;
1.237     brouard  6901: 
                   6902:    for(nres=1; nres <= nresult; nres++) /* For each resultline */
1.241     brouard  6903:    for(k1=1; k1<=m;k1++){ /* For each combination of covariate */
1.253     brouard  6904:      if(m != 1 && TKresult[nres]!= k1)
1.237     brouard  6905:        continue;
1.220     brouard  6906: 
1.222     brouard  6907:      /* for(i1=1; i1<=ncodemax[k1];i1++){ */
                   6908:      jj1++;
                   6909:      if (cptcovn > 0) {
1.264     brouard  6910:        fprintf(fichtm,"\n<p><a name=\"rescov");
                   6911:        for (cpt=1; cpt<=cptcoveff;cpt++){ 
                   6912:         fprintf(fichtm,"_V%d=%d_",Tvresult[nres][cpt],(int)Tresult[nres][cpt]);
                   6913:        }
                   6914:        for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
                   6915:         fprintf(fichtm,"_V%d=%f_",Tvqresult[nres][k4],Tqresult[nres][k4]);
                   6916:        }
                   6917:        fprintf(fichtm,"\"</a>");
                   6918:  
1.222     brouard  6919:        fprintf(fichtm,"<hr  size=\"2\" color=\"#EC5E5E\">************ Results for covariates");
1.225     brouard  6920:        for (cpt=1; cpt<=cptcoveff;cpt++){ 
1.237     brouard  6921:         fprintf(fichtm," V%d=%d ",Tvresult[nres][cpt],(int)Tresult[nres][cpt]);
                   6922:         printf(" V%d=%d ",Tvresult[nres][cpt],Tresult[nres][cpt]);fflush(stdout);
                   6923:         /* fprintf(fichtm," V%d=%d ",Tvaraff[cpt],nbcode[Tvaraff[cpt]][codtabm(jj1,cpt)]); */
                   6924:         /* printf(" V%d=%d ",Tvaraff[cpt],nbcode[Tvaraff[cpt]][codtabm(jj1,cpt)]);fflush(stdout); */
1.222     brouard  6925:        }
1.237     brouard  6926:        for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
                   6927:        fprintf(fichtm," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
                   6928:        printf(" V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);fflush(stdout);
                   6929:       }
                   6930:        
1.230     brouard  6931:        /* if(nqfveff+nqtveff 0) */ /* Test to be done */
1.222     brouard  6932:        fprintf(fichtm," ************\n<hr size=\"2\" color=\"#EC5E5E\">");
                   6933:        if(invalidvarcomb[k1]){
                   6934:         fprintf(fichtm,"\n<h3>Combination (%d) ignored because no cases </h3>\n",k1); 
                   6935:         printf("\nCombination (%d) ignored because no cases \n",k1); 
                   6936:         continue;
                   6937:        }
                   6938:      }
                   6939:      /* aij, bij */
1.259     brouard  6940:      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  6941: <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  6942:      /* Pij */
1.241     brouard  6943:      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> \
                   6944: <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  6945:      /* Quasi-incidences */
                   6946:      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  6947:  before but expressed in per year i.e. quasi incidences if stepm is small and probabilities too, \
1.211     brouard  6948:  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  6949: 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> \
                   6950: <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  6951:      /* Survival functions (period) in state j */
                   6952:      for(cpt=1; cpt<=nlstate;cpt++){
1.292     brouard  6953:        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  6954: <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  6955:      }
                   6956:      /* State specific survival functions (period) */
                   6957:      for(cpt=1; cpt<=nlstate;cpt++){
1.292     brouard  6958:        fprintf(fichtm,"<br>\n- Survival functions in state %d and in any other live state (total).\
                   6959:  And probability to be observed in various states (up to %d) being in state %d at different ages.      \
1.283     brouard  6960:  <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  6961:      }
1.288     brouard  6962:      /* Period (forward stable) prevalence in each health state */
1.222     brouard  6963:      for(cpt=1; cpt<=nlstate;cpt++){
1.264     brouard  6964:        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> \
                   6965: <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  6966:      }
                   6967:      if(backcast==1){
1.288     brouard  6968:        /* Backward prevalence in each health state */
1.222     brouard  6969:        for(cpt=1; cpt<=nlstate;cpt++){
1.264     brouard  6970:         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  6971: <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  6972:        }
1.217     brouard  6973:      }
1.222     brouard  6974:      if(prevfcast==1){
1.288     brouard  6975:        /* Projection of prevalence up to period (forward stable) prevalence in each health state */
1.222     brouard  6976:        for(cpt=1; cpt<=nlstate;cpt++){
1.288     brouard  6977:         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  6978: <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  6979:        }
                   6980:      }
1.268     brouard  6981:      if(backcast==1){
                   6982:       /* Back projection of prevalence up to stable (mixed) back-prevalence in each health state */
                   6983:        for(cpt=1; cpt<=nlstate;cpt++){
1.273     brouard  6984:         fprintf(fichtm,"<br>\n- Back projection of cross-sectional prevalence (estimated with cases observed from %.1f to %.1f and mobil_average=%d), \
                   6985:  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 \
                   6986:  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) \
                   6987: with weights corresponding to observed prevalence at different ages. <a href=\"%s_%d-%d-%d.svg\">%s_%d-%d-%d.svg</a><br> \
                   6988:  <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  6989:        }
                   6990:      }
1.220     brouard  6991:         
1.222     brouard  6992:      for(cpt=1; cpt<=nlstate;cpt++) {
1.241     brouard  6993:        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> \
                   6994: <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  6995:      }
                   6996:      /* } /\* end i1 *\/ */
                   6997:    }/* End k1 */
                   6998:    fprintf(fichtm,"</ul>");
1.126     brouard  6999: 
1.222     brouard  7000:    fprintf(fichtm,"\
1.126     brouard  7001: \n<br><li><h4> <a name='secondorder'>Result files (second order: variances)</a></h4>\n\
1.193     brouard  7002:  - Parameter file with estimated parameters and covariance matrix: <a href=\"%s\">%s</a> <br> \
1.203     brouard  7003:  - 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  7004: But because parameters are usually highly correlated (a higher incidence of disability \
                   7005: and a higher incidence of recovery can give very close observed transition) it might \
                   7006: be very useful to look not only at linear confidence intervals estimated from the \
                   7007: variances but at the covariance matrix. And instead of looking at the estimated coefficients \
                   7008: (parameters) of the logistic regression, it might be more meaningful to visualize the \
                   7009: covariance matrix of the one-step probabilities. \
                   7010: See page 'Matrix of variance-covariance of one-step probabilities' below. \n", rfileres,rfileres);
1.126     brouard  7011: 
1.222     brouard  7012:    fprintf(fichtm," - Standard deviation of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
                   7013:           subdirf2(fileresu,"PROB_"),subdirf2(fileresu,"PROB_"));
                   7014:    fprintf(fichtm,"\
1.126     brouard  7015:  - Variance-covariance of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
1.222     brouard  7016:           subdirf2(fileresu,"PROBCOV_"),subdirf2(fileresu,"PROBCOV_"));
1.126     brouard  7017: 
1.222     brouard  7018:    fprintf(fichtm,"\
1.126     brouard  7019:  - Correlation matrix of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
1.222     brouard  7020:           subdirf2(fileresu,"PROBCOR_"),subdirf2(fileresu,"PROBCOR_"));
                   7021:    fprintf(fichtm,"\
1.126     brouard  7022:  - 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): \
                   7023:    <a href=\"%s\">%s</a> <br>\n</li>",
1.201     brouard  7024:           estepm,subdirf2(fileresu,"CVE_"),subdirf2(fileresu,"CVE_"));
1.222     brouard  7025:    fprintf(fichtm,"\
1.126     brouard  7026:  - (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): \
                   7027:    <a href=\"%s\">%s</a> <br>\n</li>",
1.201     brouard  7028:           estepm,subdirf2(fileresu,"STDE_"),subdirf2(fileresu,"STDE_"));
1.222     brouard  7029:    fprintf(fichtm,"\
1.288     brouard  7030:  - 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  7031:           estepm, subdirf2(fileresu,"V_"),subdirf2(fileresu,"V_"));
                   7032:    fprintf(fichtm,"\
1.128     brouard  7033:  - 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  7034:           estepm, subdirf2(fileresu,"T_"),subdirf2(fileresu,"T_"));
                   7035:    fprintf(fichtm,"\
1.288     brouard  7036:  - Standard deviation of forward (period) prevalences: <a href=\"%s\">%s</a> <br>\n",\
1.222     brouard  7037:           subdirf2(fileresu,"VPL_"),subdirf2(fileresu,"VPL_"));
1.126     brouard  7038: 
                   7039: /*  if(popforecast==1) fprintf(fichtm,"\n */
                   7040: /*  - Prevalences forecasting: <a href=\"f%s\">f%s</a> <br>\n */
                   7041: /*  - Population forecasting (if popforecast=1): <a href=\"pop%s\">pop%s</a> <br>\n */
                   7042: /*     <br>",fileres,fileres,fileres,fileres); */
                   7043: /*  else  */
                   7044: /*    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  7045:    fflush(fichtm);
                   7046:    fprintf(fichtm," <ul><li><b>Graphs</b></li><p>");
1.126     brouard  7047: 
1.225     brouard  7048:    m=pow(2,cptcoveff);
1.222     brouard  7049:    if (cptcovn < 1) {m=1;ncodemax[1]=1;}
1.126     brouard  7050: 
1.222     brouard  7051:    jj1=0;
1.237     brouard  7052: 
1.241     brouard  7053:    for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.222     brouard  7054:    for(k1=1; k1<=m;k1++){
1.253     brouard  7055:      if(m != 1 && TKresult[nres]!= k1)
1.237     brouard  7056:        continue;
1.222     brouard  7057:      /* for(i1=1; i1<=ncodemax[k1];i1++){ */
                   7058:      jj1++;
1.126     brouard  7059:      if (cptcovn > 0) {
                   7060:        fprintf(fichtm,"<hr  size=\"2\" color=\"#EC5E5E\">************ Results for covariates");
1.225     brouard  7061:        for (cpt=1; cpt<=cptcoveff;cpt++)  /**< cptcoveff number of variables */
1.237     brouard  7062:         fprintf(fichtm," V%d=%d ",Tvresult[nres][cpt],Tresult[nres][cpt]);
                   7063:         /* fprintf(fichtm," V%d=%d ",Tvaraff[cpt],nbcode[Tvaraff[cpt]][codtabm(jj1,cpt)]); */
                   7064:        for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
                   7065:        fprintf(fichtm," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
                   7066:       }
                   7067: 
1.126     brouard  7068:        fprintf(fichtm," ************\n<hr size=\"2\" color=\"#EC5E5E\">");
1.220     brouard  7069: 
1.222     brouard  7070:        if(invalidvarcomb[k1]){
                   7071:         fprintf(fichtm,"\n<h4>Combination (%d) ignored because no cases </h4>\n",k1); 
                   7072:         continue;
                   7073:        }
1.126     brouard  7074:      }
                   7075:      for(cpt=1; cpt<=nlstate;cpt++) {
1.258     brouard  7076:        fprintf(fichtm,"\n<br>- Observed (cross-sectional with mov_average=%d) and period (incidence based) \
1.241     brouard  7077: 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  7078: <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  7079:      }
                   7080:      fprintf(fichtm,"\n<br>- Total life expectancy by age and \
1.128     brouard  7081: health expectancies in states (1) and (2). If popbased=1 the smooth (due to the model) \
                   7082: true period expectancies (those weighted with period prevalences are also\
                   7083:  drawn in addition to the population based expectancies computed using\
1.241     brouard  7084:  observed and cahotic prevalences:  <a href=\"%s_%d-%d.svg\">%s_%d-%d.svg</a>\n<br>\
                   7085: <img src=\"%s_%d-%d.svg\">",subdirf2(optionfilefiname,"E_"),k1,nres,subdirf2(optionfilefiname,"E_"),k1,nres,subdirf2(optionfilefiname,"E_"),k1,nres);
1.222     brouard  7086:      /* } /\* end i1 *\/ */
                   7087:    }/* End k1 */
1.241     brouard  7088:   }/* End nres */
1.222     brouard  7089:    fprintf(fichtm,"</ul>");
                   7090:    fflush(fichtm);
1.126     brouard  7091: }
                   7092: 
                   7093: /******************* Gnuplot file **************/
1.270     brouard  7094: 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  7095: 
                   7096:   char dirfileres[132],optfileres[132];
1.264     brouard  7097:   char gplotcondition[132], gplotlabel[132];
1.237     brouard  7098:   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  7099:   int lv=0, vlv=0, kl=0;
1.130     brouard  7100:   int ng=0;
1.201     brouard  7101:   int vpopbased;
1.223     brouard  7102:   int ioffset; /* variable offset for columns */
1.270     brouard  7103:   int iyearc=1; /* variable column for year of projection  */
                   7104:   int iagec=1; /* variable column for age of projection  */
1.235     brouard  7105:   int nres=0; /* Index of resultline */
1.266     brouard  7106:   int istart=1; /* For starting graphs in projections */
1.219     brouard  7107: 
1.126     brouard  7108: /*   if((ficgp=fopen(optionfilegnuplot,"a"))==NULL) { */
                   7109: /*     printf("Problem with file %s",optionfilegnuplot); */
                   7110: /*     fprintf(ficlog,"Problem with file %s",optionfilegnuplot); */
                   7111: /*   } */
                   7112: 
                   7113:   /*#ifdef windows */
                   7114:   fprintf(ficgp,"cd \"%s\" \n",pathc);
1.223     brouard  7115:   /*#endif */
1.225     brouard  7116:   m=pow(2,cptcoveff);
1.126     brouard  7117: 
1.274     brouard  7118:   /* diagram of the model */
                   7119:   fprintf(ficgp,"\n#Diagram of the model \n");
                   7120:   fprintf(ficgp,"\ndelta=0.03;delta2=0.07;unset arrow;\n");
                   7121:   fprintf(ficgp,"yoff=(%d > 2? 0:1);\n",nlstate);
                   7122:   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);
                   7123: 
                   7124:   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);
                   7125:   fprintf(ficgp,"\n#show arrow\nunset label\n");
                   7126:   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);
                   7127:   fprintf(ficgp,"\nset label %d+1 sprintf(\"State %%d\",%d+1) center at 0.,0.  font \"helvetica, 16\" tc rgbcolor \"red\"\n",nlstate,nlstate);
                   7128:   fprintf(ficgp,"\n#show label\nunset border;unset xtics; unset ytics;\n");
                   7129:   fprintf(ficgp,"\n\nset ter svg size 640, 480;set out \"%s_.svg\" \n",subdirf2(optionfilefiname,"D_"));
                   7130:   fprintf(ficgp,"unset log y; plot [-1.2:1.2][yoff-1.2:1.2] 1/0 not; set out;reset;\n");
                   7131: 
1.202     brouard  7132:   /* Contribution to likelihood */
                   7133:   /* Plot the probability implied in the likelihood */
1.223     brouard  7134:   fprintf(ficgp,"\n# Contributions to the Likelihood, mle >=1. For mle=4 no interpolation, pure matrix products.\n#\n");
                   7135:   fprintf(ficgp,"\n set log y; unset log x;set xlabel \"Age\"; set ylabel \"Likelihood (-2Log(L))\";");
                   7136:   /* fprintf(ficgp,"\nset ter svg size 640, 480"); */ /* Too big for svg */
                   7137:   fprintf(ficgp,"\nset ter pngcairo size 640, 480");
1.204     brouard  7138: /* nice for mle=4 plot by number of matrix products.
1.202     brouard  7139:    replot  "rrtest1/toto.txt" u 2:($4 == 1 && $5==2 ? $9 : 1/0):5 t "p12" with point lc 1 */
                   7140: /* replot exp(p1+p2*x)/(1+exp(p1+p2*x)+exp(p3+p4*x)+exp(p5+p6*x)) t "p12(x)"  */
1.223     brouard  7141:   /* fprintf(ficgp,"\nset out \"%s.svg\";",subdirf2(optionfilefiname,"ILK_")); */
                   7142:   fprintf(ficgp,"\nset out \"%s-dest.png\";",subdirf2(optionfilefiname,"ILK_"));
                   7143:   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));
                   7144:   fprintf(ficgp,"\nset out \"%s-ori.png\";",subdirf2(optionfilefiname,"ILK_"));
                   7145:   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));
                   7146:   for (i=1; i<= nlstate ; i ++) {
                   7147:     fprintf(ficgp,"\nset out \"%s-p%dj.png\";set ylabel \"Probability for each individual/wave\";",subdirf2(optionfilefiname,"ILK_"),i);
                   7148:     fprintf(ficgp,"unset log;\n# plot weighted, mean weight should have point size of 0.5\n plot  \"%s\"",subdirf(fileresilk));
                   7149:     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);
                   7150:     for (j=2; j<= nlstate+ndeath ; j ++) {
                   7151:       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);
                   7152:     }
                   7153:     fprintf(ficgp,";\nset out; unset ylabel;\n"); 
                   7154:   }
                   7155:   /* 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 */               
                   7156:   /* fprintf(ficgp,"\nset log y;plot  \"%s\" u 2:(-$11):3 t \"All sample, all transitions\" with dots lc variable",subdirf(fileresilk)); */
                   7157:   /* fprintf(ficgp,"\nreplot  \"%s\" u 2:($3 <= 3 ? -$11 : 1/0):3 t \"First 3 individuals\" with line lc variable", subdirf(fileresilk)); */
                   7158:   fprintf(ficgp,"\nset out;unset log\n");
                   7159:   /* fprintf(ficgp,"\nset out \"%s.svg\"; replot; set out; # bug gnuplot",subdirf2(optionfilefiname,"ILK_")); */
1.202     brouard  7160: 
1.126     brouard  7161:   strcpy(dirfileres,optionfilefiname);
                   7162:   strcpy(optfileres,"vpl");
1.223     brouard  7163:   /* 1eme*/
1.238     brouard  7164:   for (cpt=1; cpt<= nlstate ; cpt ++){ /* For each live state */
                   7165:     for (k1=1; k1<= m ; k1 ++){ /* For each valid combination of covariate */
1.236     brouard  7166:       for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.238     brouard  7167:        /* plot [100000000000000000000:-100000000000000000000] "mysbiaspar/vplrmysbiaspar.txt to check */
1.253     brouard  7168:        if(m != 1 && TKresult[nres]!= k1)
1.238     brouard  7169:          continue;
                   7170:        /* We are interested in selected combination by the resultline */
1.246     brouard  7171:        /* printf("\n# 1st: Period (stable) prevalence with CI: 'VPL_' files and live state =%d ", cpt); */
1.288     brouard  7172:        fprintf(ficgp,"\n# 1st: Forward (stable period) prevalence with CI: 'VPL_' files  and live state =%d ", cpt);
1.264     brouard  7173:        strcpy(gplotlabel,"(");
1.238     brouard  7174:        for (k=1; k<=cptcoveff; k++){    /* For each covariate k get corresponding value lv for combination k1 */
                   7175:          lv= decodtabm(k1,k,cptcoveff); /* Should be the value of the covariate corresponding to k1 combination */
                   7176:          /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   7177:          /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   7178:          /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
                   7179:          vlv= nbcode[Tvaraff[k]][lv]; /* vlv is the value of the covariate lv, 0 or 1 */
                   7180:          /* For each combination of covariate k1 (V1=1, V3=0), we printed the current covariate k and its value vlv */
1.246     brouard  7181:          /* printf(" V%d=%d ",Tvaraff[k],vlv); */
1.238     brouard  7182:          fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv);
1.264     brouard  7183:          sprintf(gplotlabel+strlen(gplotlabel)," V%d=%d ",Tvaraff[k],vlv);
1.238     brouard  7184:        }
                   7185:        for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
1.246     brouard  7186:          /* printf(" V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]); */
1.238     brouard  7187:          fprintf(ficgp," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
1.264     brouard  7188:          sprintf(gplotlabel+strlen(gplotlabel)," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
                   7189:        }
                   7190:        strcpy(gplotlabel+strlen(gplotlabel),")");
1.246     brouard  7191:        /* printf("\n#\n"); */
1.238     brouard  7192:        fprintf(ficgp,"\n#\n");
                   7193:        if(invalidvarcomb[k1]){
1.260     brouard  7194:           /*k1=k1-1;*/ /* To be checked */
1.238     brouard  7195:          fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   7196:          continue;
                   7197:        }
1.235     brouard  7198:       
1.241     brouard  7199:        fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" \n",subdirf2(optionfilefiname,"V_"),cpt,k1,nres);
                   7200:        fprintf(ficgp,"\n#set out \"V_%s_%d-%d-%d.svg\" \n",optionfilefiname,cpt,k1,nres);
1.276     brouard  7201:        /* fprintf(ficgp,"set label \"Alive state %d %s\" at graph 0.98,0.5 center rotate font \"Helvetica,12\"\n",cpt,gplotlabel); */
                   7202:        fprintf(ficgp,"set title \"Alive state %d %s\" font \"Helvetica,12\"\n",cpt,gplotlabel);
1.260     brouard  7203:        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);
                   7204:        /* 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); */
                   7205:       /* k1-1 error should be nres-1*/
1.238     brouard  7206:        for (i=1; i<= nlstate ; i ++) {
                   7207:          if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
                   7208:          else        fprintf(ficgp," %%*lf (%%*lf)");
                   7209:        }
1.288     brouard  7210:        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  7211:        for (i=1; i<= nlstate ; i ++) {
                   7212:          if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
                   7213:          else fprintf(ficgp," %%*lf (%%*lf)");
                   7214:        } 
1.260     brouard  7215:        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  7216:        for (i=1; i<= nlstate ; i ++) {
                   7217:          if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
                   7218:          else fprintf(ficgp," %%*lf (%%*lf)");
                   7219:        }  
1.265     brouard  7220:        /* 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)); */
                   7221:        
                   7222:        fprintf(ficgp,"\" t\"\" w l lt 1,\"%s\" u 1:((",subdirf2(fileresu,"P_"));
                   7223:         if(cptcoveff ==0){
1.271     brouard  7224:          fprintf(ficgp,"$%d)) t 'Observed prevalence in state %d' with line lt 3",      2+3*(cpt-1),  cpt );
1.265     brouard  7225:        }else{
                   7226:          kl=0;
                   7227:          for (k=1; k<=cptcoveff; k++){    /* For each combination of covariate  */
                   7228:            lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate value corresponding to k1 combination and kth covariate */
                   7229:            /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   7230:            /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   7231:            /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
                   7232:            vlv= nbcode[Tvaraff[k]][lv];
                   7233:            kl++;
                   7234:            /* 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 *\/ */
                   7235:            /*6+(cpt-1)*(nlstate+1)+1+(i-1)+(nlstate+1)*nlstate; 6+(1-1)*(2+1)+1+(1-1) +(2+1)*2=13 */ 
                   7236:            /*6+1+(i-1)+(nlstate+1)*nlstate; 6+1+(1-1) +(2+1)*2=13 */ 
                   7237:            /* ''  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*/
                   7238:            if(k==cptcoveff){
                   7239:              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], \
                   7240:                      2+cptcoveff*2+3*(cpt-1),  cpt );  /* 4 or 6 ?*/
                   7241:            }else{
                   7242:              fprintf(ficgp,"$%d==%d && $%d==%d && ",kl+1, Tvaraff[k],kl+1+1,nbcode[Tvaraff[k]][lv]);
                   7243:              kl++;
                   7244:            }
                   7245:          } /* end covariate */
                   7246:        } /* end if no covariate */
                   7247: 
1.238     brouard  7248:        if(backcast==1){ /* We need to get the corresponding values of the covariates involved in this combination k1 */
                   7249:          /* 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  7250:          fprintf(ficgp,",\"%s\" u 1:((",subdirf2(fileresu,"PLB_")); /* Age is in 1, nres in 2 to be fixed */
1.238     brouard  7251:          if(cptcoveff ==0){
1.245     brouard  7252:            fprintf(ficgp,"$%d)) t 'Backward prevalence in state %d' with line lt 3",    2+(cpt-1),  cpt );
1.238     brouard  7253:          }else{
                   7254:            kl=0;
                   7255:            for (k=1; k<=cptcoveff; k++){    /* For each combination of covariate  */
                   7256:              lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate value corresponding to k1 combination and kth covariate */
                   7257:              /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   7258:              /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   7259:              /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
                   7260:              vlv= nbcode[Tvaraff[k]][lv];
1.223     brouard  7261:              kl++;
1.238     brouard  7262:              /* 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 *\/ */
                   7263:              /*6+(cpt-1)*(nlstate+1)+1+(i-1)+(nlstate+1)*nlstate; 6+(1-1)*(2+1)+1+(1-1) +(2+1)*2=13 */ 
                   7264:              /*6+1+(i-1)+(nlstate+1)*nlstate; 6+1+(1-1) +(2+1)*2=13 */ 
                   7265:              /* ''  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*/
                   7266:              if(k==cptcoveff){
1.245     brouard  7267:                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  7268:                        2+cptcoveff*2+(cpt-1),  cpt );  /* 4 or 6 ?*/
1.238     brouard  7269:              }else{
                   7270:                fprintf(ficgp,"$%d==%d && $%d==%d && ",kl+1, Tvaraff[k],kl+1+1,nbcode[Tvaraff[k]][lv]);
                   7271:                kl++;
                   7272:              }
                   7273:            } /* end covariate */
                   7274:          } /* end if no covariate */
1.268     brouard  7275:          if(backcast == 1){
                   7276:            fprintf(ficgp,", \"%s\" every :::%d::%d u 1:($2==%d ? $3:1/0) \"%%lf %%lf",subdirf2(fileresu,"VBL_"),nres-1,nres-1,nres);
                   7277:            /* k1-1 error should be nres-1*/
                   7278:            for (i=1; i<= nlstate ; i ++) {
                   7279:              if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
                   7280:              else        fprintf(ficgp," %%*lf (%%*lf)");
                   7281:            }
1.271     brouard  7282:            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  7283:            for (i=1; i<= nlstate ; i ++) {
                   7284:              if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
                   7285:              else fprintf(ficgp," %%*lf (%%*lf)");
                   7286:            } 
1.276     brouard  7287:            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  7288:            for (i=1; i<= nlstate ; i ++) {
                   7289:              if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
                   7290:              else fprintf(ficgp," %%*lf (%%*lf)");
                   7291:            } 
1.274     brouard  7292:            fprintf(ficgp,"\" t\"\" w l lt 4");
1.268     brouard  7293:          } /* end if backprojcast */
1.238     brouard  7294:        } /* end if backcast */
1.276     brouard  7295:        /* fprintf(ficgp,"\nset out ;unset label;\n"); */
                   7296:        fprintf(ficgp,"\nset out ;unset title;\n");
1.238     brouard  7297:       } /* nres */
1.201     brouard  7298:     } /* k1 */
                   7299:   } /* cpt */
1.235     brouard  7300: 
                   7301:   
1.126     brouard  7302:   /*2 eme*/
1.238     brouard  7303:   for (k1=1; k1<= m ; k1 ++){  
                   7304:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.253     brouard  7305:       if(m != 1 && TKresult[nres]!= k1)
1.238     brouard  7306:        continue;
                   7307:       fprintf(ficgp,"\n# 2nd: Total life expectancy with CI: 't' files ");
1.264     brouard  7308:       strcpy(gplotlabel,"(");
1.238     brouard  7309:       for (k=1; k<=cptcoveff; k++){    /* For each covariate and each value */
1.225     brouard  7310:        lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate number corresponding to k1 combination */
1.223     brouard  7311:        /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   7312:        /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   7313:        /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
                   7314:        vlv= nbcode[Tvaraff[k]][lv];
                   7315:        fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv);
1.264     brouard  7316:        sprintf(gplotlabel+strlen(gplotlabel)," V%d=%d ",Tvaraff[k],vlv);
1.211     brouard  7317:       }
1.237     brouard  7318:       /* for(k=1; k <= ncovds; k++){ */
1.236     brouard  7319:       for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
1.238     brouard  7320:        printf(" V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
1.236     brouard  7321:        fprintf(ficgp," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
1.264     brouard  7322:        sprintf(gplotlabel+strlen(gplotlabel)," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
1.238     brouard  7323:       }
1.264     brouard  7324:       strcpy(gplotlabel+strlen(gplotlabel),")");
1.211     brouard  7325:       fprintf(ficgp,"\n#\n");
1.223     brouard  7326:       if(invalidvarcomb[k1]){
                   7327:        fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   7328:        continue;
                   7329:       }
1.219     brouard  7330:                        
1.241     brouard  7331:       fprintf(ficgp,"\nset out \"%s_%d-%d.svg\" \n",subdirf2(optionfilefiname,"E_"),k1,nres);
1.238     brouard  7332:       for(vpopbased=0; vpopbased <= popbased; vpopbased++){ /* Done for vpopbased=0 and vpopbased=1 if popbased==1*/
1.264     brouard  7333:        fprintf(ficgp,"\nset label \"popbased %d %s\" at graph 0.98,0.5 center rotate font \"Helvetica,12\"\n",vpopbased,gplotlabel);
                   7334:        if(vpopbased==0){
1.238     brouard  7335:          fprintf(ficgp,"set ylabel \"Years\" \nset ter svg size 640, 480\nplot [%.f:%.f] ",ageminpar,fage);
1.264     brouard  7336:        }else
1.238     brouard  7337:          fprintf(ficgp,"\nreplot ");
                   7338:        for (i=1; i<= nlstate+1 ; i ++) {
                   7339:          k=2*i;
1.261     brouard  7340:          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  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== 1) fprintf(ficgp,"\" t\"TLE\" w l lt %d, \\\n",i);
                   7346:          else fprintf(ficgp,"\" t\"LE in state (%d)\" w l lt %d, \\\n",i-1,i+1);
1.261     brouard  7347:          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  7348:          for (j=1; j<= nlstate+1 ; j ++) {
                   7349:            if (j==i) fprintf(ficgp," %%lf (%%lf)");
                   7350:            else fprintf(ficgp," %%*lf (%%*lf)");
                   7351:          }   
                   7352:          fprintf(ficgp,"\" t\"\" w l lt 0,");
1.261     brouard  7353:          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  7354:          for (j=1; j<= nlstate+1 ; j ++) {
                   7355:            if (j==i) fprintf(ficgp," %%lf (%%lf)");
                   7356:            else fprintf(ficgp," %%*lf (%%*lf)");
                   7357:          }   
                   7358:          if (i== (nlstate+1)) fprintf(ficgp,"\" t\"\" w l lt 0");
                   7359:          else fprintf(ficgp,"\" t\"\" w l lt 0,\\\n");
                   7360:        } /* state */
                   7361:       } /* vpopbased */
1.264     brouard  7362:       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  7363:     } /* end nres */
                   7364:   } /* k1 end 2 eme*/
                   7365:        
                   7366:        
                   7367:   /*3eme*/
                   7368:   for (k1=1; k1<= m ; k1 ++){
                   7369:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.253     brouard  7370:       if(m != 1 && TKresult[nres]!= k1)
1.238     brouard  7371:        continue;
                   7372: 
                   7373:       for (cpt=1; cpt<= nlstate ; cpt ++) {
1.261     brouard  7374:        fprintf(ficgp,"\n\n# 3d: Life expectancy with EXP_ files:  combination=%d state=%d",k1, cpt);
1.264     brouard  7375:        strcpy(gplotlabel,"(");
1.238     brouard  7376:        for (k=1; k<=cptcoveff; k++){    /* For each covariate and each value */
                   7377:          lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate number corresponding to k1 combination */
                   7378:          /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   7379:          /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   7380:          /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
                   7381:          vlv= nbcode[Tvaraff[k]][lv];
                   7382:          fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv);
1.264     brouard  7383:          sprintf(gplotlabel+strlen(gplotlabel)," V%d=%d ",Tvaraff[k],vlv);
1.238     brouard  7384:        }
                   7385:        for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
                   7386:          fprintf(ficgp," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
1.264     brouard  7387:          sprintf(gplotlabel+strlen(gplotlabel)," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
1.238     brouard  7388:        }       
1.264     brouard  7389:        strcpy(gplotlabel+strlen(gplotlabel),")");
1.238     brouard  7390:        fprintf(ficgp,"\n#\n");
                   7391:        if(invalidvarcomb[k1]){
                   7392:          fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   7393:          continue;
                   7394:        }
                   7395:                        
                   7396:        /*       k=2+nlstate*(2*cpt-2); */
                   7397:        k=2+(nlstate+1)*(cpt-1);
1.241     brouard  7398:        fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" \n",subdirf2(optionfilefiname,"EXP_"),cpt,k1,nres);
1.264     brouard  7399:        fprintf(ficgp,"set label \"%s\" at graph 0.98,0.5 center rotate font \"Helvetica,12\"\n",gplotlabel);
1.238     brouard  7400:        fprintf(ficgp,"set ter svg size 640, 480\n\
1.261     brouard  7401: 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  7402:        /*fprintf(ficgp,",\"e%s\" every :::%d::%d u 1:($%d-2*$%d) \"\%%lf ",fileres,k1-1,k1-1,k,k+1);
                   7403:          for (i=1; i<= nlstate*2 ; i ++) fprintf(ficgp,"\%%lf (\%%lf) ");
                   7404:          fprintf(ficgp,"\" t \"e%d1\" w l",cpt);
                   7405:          fprintf(ficgp,",\"e%s\" every :::%d::%d u 1:($%d+2*$%d) \"\%%lf ",fileres,k1-1,k1-1,k,k+1);
                   7406:          for (i=1; i<= nlstate*2 ; i ++) fprintf(ficgp,"\%%lf (\%%lf) ");
                   7407:          fprintf(ficgp,"\" t \"e%d1\" w l",cpt);
1.219     brouard  7408:                                
1.238     brouard  7409:        */
                   7410:        for (i=1; i< nlstate ; i ++) {
1.261     brouard  7411:          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  7412:          /*    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  7413:                                
1.238     brouard  7414:        } 
1.261     brouard  7415:        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  7416:       }
1.264     brouard  7417:       fprintf(ficgp,"\nunset label;\n");
1.238     brouard  7418:     } /* end nres */
                   7419:   } /* end kl 3eme */
1.126     brouard  7420:   
1.223     brouard  7421:   /* 4eme */
1.201     brouard  7422:   /* Survival functions (period) from state i in state j by initial state i */
1.238     brouard  7423:   for (k1=1; k1<=m; k1++){    /* For each covariate and each value */
                   7424:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.253     brouard  7425:       if(m != 1 && TKresult[nres]!= k1)
1.223     brouard  7426:        continue;
1.238     brouard  7427:       for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each life state cpt*/
1.264     brouard  7428:        strcpy(gplotlabel,"(");
1.238     brouard  7429:        fprintf(ficgp,"\n#\n#\n# Survival functions in state j : 'LIJ_' files, cov=%d state=%d",k1, cpt);
                   7430:        for (k=1; k<=cptcoveff; k++){    /* For each covariate and each value */
                   7431:          lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate number corresponding to k1 combination */
                   7432:          /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   7433:          /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   7434:          /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
                   7435:          vlv= nbcode[Tvaraff[k]][lv];
                   7436:          fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv);
1.264     brouard  7437:          sprintf(gplotlabel+strlen(gplotlabel)," V%d=%d ",Tvaraff[k],vlv);
1.238     brouard  7438:        }
                   7439:        for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
                   7440:          fprintf(ficgp," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
1.264     brouard  7441:          sprintf(gplotlabel+strlen(gplotlabel)," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
1.238     brouard  7442:        }       
1.264     brouard  7443:        strcpy(gplotlabel+strlen(gplotlabel),")");
1.238     brouard  7444:        fprintf(ficgp,"\n#\n");
                   7445:        if(invalidvarcomb[k1]){
                   7446:          fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   7447:          continue;
1.223     brouard  7448:        }
1.238     brouard  7449:       
1.241     brouard  7450:        fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" \n",subdirf2(optionfilefiname,"LIJ_"),cpt,k1,nres);
1.264     brouard  7451:        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  7452:        fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Probability to be alive\" \n\
                   7453: set ter svg size 640, 480\nunset log y\nplot [%.f:%.f]  ", ageminpar, agemaxpar);
                   7454:        k=3;
                   7455:        for (i=1; i<= nlstate ; i ++){
                   7456:          if(i==1){
                   7457:            fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"PIJ_"));
                   7458:          }else{
                   7459:            fprintf(ficgp,", '' ");
                   7460:          }
                   7461:          l=(nlstate+ndeath)*(i-1)+1;
                   7462:          fprintf(ficgp," u ($1==%d ? ($3):1/0):($%d/($%d",k1,k+l+(cpt-1),k+l);
                   7463:          for (j=2; j<= nlstate+ndeath ; j ++)
                   7464:            fprintf(ficgp,"+$%d",k+l+j-1);
                   7465:          fprintf(ficgp,")) t \"l(%d,%d)\" w l",i,cpt);
                   7466:        } /* nlstate */
1.264     brouard  7467:        fprintf(ficgp,"\nset out; unset label;\n");
1.238     brouard  7468:       } /* end cpt state*/ 
                   7469:     } /* end nres */
                   7470:   } /* end covariate k1 */  
                   7471: 
1.220     brouard  7472: /* 5eme */
1.201     brouard  7473:   /* Survival functions (period) from state i in state j by final state j */
1.238     brouard  7474:   for (k1=1; k1<= m ; k1++){ /* For each covariate combination if any */
                   7475:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.253     brouard  7476:       if(m != 1 && TKresult[nres]!= k1)
1.227     brouard  7477:        continue;
1.238     brouard  7478:       for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each inital state  */
1.264     brouard  7479:        strcpy(gplotlabel,"(");
1.238     brouard  7480:        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);
                   7481:        for (k=1; k<=cptcoveff; k++){    /* For each covariate and each value */
                   7482:          lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate number corresponding to k1 combination */
                   7483:          /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   7484:          /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   7485:          /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
                   7486:          vlv= nbcode[Tvaraff[k]][lv];
                   7487:          fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv);
1.264     brouard  7488:          sprintf(gplotlabel+strlen(gplotlabel)," V%d=%d ",Tvaraff[k],vlv);
1.238     brouard  7489:        }
                   7490:        for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
                   7491:          fprintf(ficgp," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
1.264     brouard  7492:          sprintf(gplotlabel+strlen(gplotlabel)," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
1.238     brouard  7493:        }       
1.264     brouard  7494:        strcpy(gplotlabel+strlen(gplotlabel),")");
1.238     brouard  7495:        fprintf(ficgp,"\n#\n");
                   7496:        if(invalidvarcomb[k1]){
                   7497:          fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   7498:          continue;
                   7499:        }
1.227     brouard  7500:       
1.241     brouard  7501:        fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" \n",subdirf2(optionfilefiname,"LIJT_"),cpt,k1,nres);
1.264     brouard  7502:        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  7503:        fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Probability to be alive\" \n\
                   7504: set ter svg size 640, 480\nunset log y\nplot [%.f:%.f]  ", ageminpar, agemaxpar);
                   7505:        k=3;
                   7506:        for (j=1; j<= nlstate ; j ++){ /* Lived in state j */
                   7507:          if(j==1)
                   7508:            fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"PIJ_"));
                   7509:          else
                   7510:            fprintf(ficgp,", '' ");
                   7511:          l=(nlstate+ndeath)*(cpt-1) +j;
                   7512:          fprintf(ficgp," u (($1==%d && (floor($2)%%5 == 0)) ? ($3):1/0):($%d",k1,k+l);
                   7513:          /* for (i=2; i<= nlstate+ndeath ; i ++) */
                   7514:          /*   fprintf(ficgp,"+$%d",k+l+i-1); */
                   7515:          fprintf(ficgp,") t \"l(%d,%d)\" w l",cpt,j);
                   7516:        } /* nlstate */
                   7517:        fprintf(ficgp,", '' ");
                   7518:        fprintf(ficgp," u (($1==%d && (floor($2)%%5 == 0)) ? ($3):1/0):(",k1);
                   7519:        for (j=1; j<= nlstate ; j ++){ /* Lived in state j */
                   7520:          l=(nlstate+ndeath)*(cpt-1) +j;
                   7521:          if(j < nlstate)
                   7522:            fprintf(ficgp,"$%d +",k+l);
                   7523:          else
                   7524:            fprintf(ficgp,"$%d) t\"l(%d,.)\" w l",k+l,cpt);
                   7525:        }
1.264     brouard  7526:        fprintf(ficgp,"\nset out; unset label;\n");
1.238     brouard  7527:       } /* end cpt state*/ 
                   7528:     } /* end covariate */  
                   7529:   } /* end nres */
1.227     brouard  7530:   
1.220     brouard  7531: /* 6eme */
1.202     brouard  7532:   /* CV preval stable (period) for each covariate */
1.237     brouard  7533:   for (k1=1; k1<= m ; k1 ++) /* For each covariate combination if any */
                   7534:   for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.253     brouard  7535:     if(m != 1 && TKresult[nres]!= k1)
1.237     brouard  7536:       continue;
1.255     brouard  7537:     for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each life state of arrival */
1.264     brouard  7538:       strcpy(gplotlabel,"(");      
1.288     brouard  7539:       fprintf(ficgp,"\n#\n#\n#CV preval stable (forward): 'pij' files, covariatecombination#=%d state=%d",k1, cpt);
1.225     brouard  7540:       for (k=1; k<=cptcoveff; k++){    /* For each covariate and each value */
1.227     brouard  7541:        lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate number corresponding to k1 combination */
                   7542:        /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   7543:        /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   7544:        /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
                   7545:        vlv= nbcode[Tvaraff[k]][lv];
                   7546:        fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv);
1.264     brouard  7547:        sprintf(gplotlabel+strlen(gplotlabel)," V%d=%d ",Tvaraff[k],vlv);
1.211     brouard  7548:       }
1.237     brouard  7549:       for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
                   7550:        fprintf(ficgp," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
1.264     brouard  7551:        sprintf(gplotlabel+strlen(gplotlabel)," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
1.237     brouard  7552:       }        
1.264     brouard  7553:       strcpy(gplotlabel+strlen(gplotlabel),")");
1.211     brouard  7554:       fprintf(ficgp,"\n#\n");
1.223     brouard  7555:       if(invalidvarcomb[k1]){
1.227     brouard  7556:        fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   7557:        continue;
1.223     brouard  7558:       }
1.227     brouard  7559:       
1.241     brouard  7560:       fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" \n",subdirf2(optionfilefiname,"P_"),cpt,k1,nres);
1.264     brouard  7561:       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  7562:       fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Probability\" \n\
1.238     brouard  7563: set ter svg size 640, 480\nunset log y\nplot [%.f:%.f]  ", ageminpar, agemaxpar);
1.211     brouard  7564:       k=3; /* Offset */
1.255     brouard  7565:       for (i=1; i<= nlstate ; i ++){ /* State of origin */
1.227     brouard  7566:        if(i==1)
                   7567:          fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"PIJ_"));
                   7568:        else
                   7569:          fprintf(ficgp,", '' ");
1.255     brouard  7570:        l=(nlstate+ndeath)*(i-1)+1; /* 1, 1+ nlstate+ndeath, 1+2*(nlstate+ndeath) */
1.227     brouard  7571:        fprintf(ficgp," u ($1==%d ? ($3):1/0):($%d/($%d",k1,k+l+(cpt-1),k+l);
                   7572:        for (j=2; j<= nlstate ; j ++)
                   7573:          fprintf(ficgp,"+$%d",k+l+j-1);
                   7574:        fprintf(ficgp,")) t \"prev(%d,%d)\" w l",i,cpt);
1.153     brouard  7575:       } /* nlstate */
1.264     brouard  7576:       fprintf(ficgp,"\nset out; unset label;\n");
1.153     brouard  7577:     } /* end cpt state*/ 
                   7578:   } /* end covariate */  
1.227     brouard  7579:   
                   7580:   
1.220     brouard  7581: /* 7eme */
1.218     brouard  7582:   if(backcast == 1){
1.288     brouard  7583:     /* CV backward prevalence  for each covariate */
1.237     brouard  7584:     for (k1=1; k1<= m ; k1 ++) /* For each covariate combination if any */
                   7585:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.253     brouard  7586:       if(m != 1 && TKresult[nres]!= k1)
1.237     brouard  7587:        continue;
1.268     brouard  7588:       for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each life origin state */
1.264     brouard  7589:        strcpy(gplotlabel,"(");      
1.288     brouard  7590:        fprintf(ficgp,"\n#\n#\n#CV Backward stable prevalence: 'pijb' files, covariatecombination#=%d state=%d",k1, cpt);
1.227     brouard  7591:        for (k=1; k<=cptcoveff; k++){    /* For each covariate and each value */
                   7592:          lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate number corresponding to k1 combination */
                   7593:          /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   7594:          /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
1.223     brouard  7595:          /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
1.227     brouard  7596:          vlv= nbcode[Tvaraff[k]][lv];
                   7597:          fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv);
1.264     brouard  7598:          sprintf(gplotlabel+strlen(gplotlabel)," V%d=%d ",Tvaraff[k],vlv);
1.227     brouard  7599:        }
1.237     brouard  7600:        for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
                   7601:          fprintf(ficgp," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
1.264     brouard  7602:          sprintf(gplotlabel+strlen(gplotlabel)," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
1.237     brouard  7603:        }       
1.264     brouard  7604:        strcpy(gplotlabel+strlen(gplotlabel),")");
1.227     brouard  7605:        fprintf(ficgp,"\n#\n");
                   7606:        if(invalidvarcomb[k1]){
                   7607:          fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   7608:          continue;
                   7609:        }
                   7610:        
1.241     brouard  7611:        fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" \n",subdirf2(optionfilefiname,"PB_"),cpt,k1,nres);
1.268     brouard  7612:        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  7613:        fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Probability\" \n\
1.238     brouard  7614: set ter svg size 640, 480\nunset log y\nplot [%.f:%.f]  ", ageminpar, agemaxpar);
1.227     brouard  7615:        k=3; /* Offset */
1.268     brouard  7616:        for (i=1; i<= nlstate ; i ++){ /* State of arrival */
1.227     brouard  7617:          if(i==1)
                   7618:            fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"PIJB_"));
                   7619:          else
                   7620:            fprintf(ficgp,", '' ");
                   7621:          /* l=(nlstate+ndeath)*(i-1)+1; */
1.255     brouard  7622:          l=(nlstate+ndeath)*(cpt-1)+1; /* fixed for i; cpt=1 1, cpt=2 1+ nlstate+ndeath, 1+2*(nlstate+ndeath) */
1.227     brouard  7623:          /* fprintf(ficgp," u ($1==%d ? ($3):1/0):($%d/($%d",k1,k+l+(cpt-1),k+l); /\* a vérifier *\/ */
                   7624:          /* 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  7625:          fprintf(ficgp," u ($1==%d ? ($3):1/0):($%d",k1,k+l+i-1); /* To be verified */
1.227     brouard  7626:          /* for (j=2; j<= nlstate ; j ++) */
                   7627:          /*    fprintf(ficgp,"+$%d",k+l+j-1); */
                   7628:          /*    /\* fprintf(ficgp,"+$%d",k+l+j-1); *\/ */
1.268     brouard  7629:          fprintf(ficgp,") t \"bprev(%d,%d)\" w l",cpt,i);
1.227     brouard  7630:        } /* nlstate */
1.264     brouard  7631:        fprintf(ficgp,"\nset out; unset label;\n");
1.218     brouard  7632:       } /* end cpt state*/ 
                   7633:     } /* end covariate */  
                   7634:   } /* End if backcast */
                   7635:   
1.223     brouard  7636:   /* 8eme */
1.218     brouard  7637:   if(prevfcast==1){
1.288     brouard  7638:     /* Projection from cross-sectional to forward stable (period) prevalence for each covariate */
1.218     brouard  7639:     
1.237     brouard  7640:     for (k1=1; k1<= m ; k1 ++) /* For each covariate combination if any */
                   7641:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.253     brouard  7642:       if(m != 1 && TKresult[nres]!= k1)
1.237     brouard  7643:        continue;
1.211     brouard  7644:       for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each life state */
1.264     brouard  7645:        strcpy(gplotlabel,"(");      
1.288     brouard  7646:        fprintf(ficgp,"\n#\n#\n#Projection of prevalence to forward stable prevalence (period): 'PROJ_' files, covariatecombination#=%d state=%d",k1, cpt);
1.227     brouard  7647:        for (k=1; k<=cptcoveff; k++){    /* For each correspondig covariate value  */
                   7648:          lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate value corresponding to k1 combination and kth covariate */
                   7649:          /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   7650:          /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   7651:          /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
                   7652:          vlv= nbcode[Tvaraff[k]][lv];
                   7653:          fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv);
1.264     brouard  7654:          sprintf(gplotlabel+strlen(gplotlabel)," V%d=%d ",Tvaraff[k],vlv);
1.227     brouard  7655:        }
1.237     brouard  7656:        for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
                   7657:          fprintf(ficgp," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
1.264     brouard  7658:          sprintf(gplotlabel+strlen(gplotlabel)," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
1.237     brouard  7659:        }       
1.264     brouard  7660:        strcpy(gplotlabel+strlen(gplotlabel),")");
1.227     brouard  7661:        fprintf(ficgp,"\n#\n");
                   7662:        if(invalidvarcomb[k1]){
                   7663:          fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   7664:          continue;
                   7665:        }
                   7666:        
                   7667:        fprintf(ficgp,"# hpijx=probability over h years, hp.jx is weighted by observed prev\n ");
1.241     brouard  7668:        fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" \n",subdirf2(optionfilefiname,"PROJ_"),cpt,k1,nres);
1.264     brouard  7669:        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  7670:        fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Prevalence\" \n\
1.238     brouard  7671: set ter svg size 640, 480\nunset log y\nplot [%.f:%.f]  ", ageminpar, agemaxpar);
1.266     brouard  7672: 
                   7673:        /* for (i=1; i<= nlstate+1 ; i ++){  /\* nlstate +1 p11 p21 p.1 *\/ */
                   7674:        istart=nlstate+1; /* Could be one if by state, but nlstate+1 is w.i projection only */
                   7675:        /*istart=1;*/ /* Could be one if by state, but nlstate+1 is w.i projection only */
                   7676:        for (i=istart; i<= nlstate+1 ; i ++){  /* nlstate +1 p11 p21 p.1 */
1.227     brouard  7677:          /*#  V1  = 1  V2 =  0 yearproj age p11 p21 p.1 p12 p22 p.2 p13 p23 p.3*/
                   7678:          /*#   1    2   3    4    5      6  7   8   9   10   11 12  13   14  15 */   
                   7679:          /*# yearproj age p11 p21 p.1 p12 p22 p.2 p13 p23 p.3*/
                   7680:          /*#   1       2   3    4    5      6  7   8   9   10   11 12  13   14  15 */   
1.266     brouard  7681:          if(i==istart){
1.227     brouard  7682:            fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"F_"));
                   7683:          }else{
                   7684:            fprintf(ficgp,",\\\n '' ");
                   7685:          }
                   7686:          if(cptcoveff ==0){ /* No covariate */
                   7687:            ioffset=2; /* Age is in 2 */
                   7688:            /*# yearproj age p11 p21 p31 p.1 p12 p22 p32 p.2 p13 p23 p33 p.3 p14 p24 p34 p.4*/
                   7689:            /*#   1       2   3   4   5  6    7  8   9   10  11  12  13  14  15  16  17  18 */
                   7690:            /*# V1  = 1 yearproj age p11 p21 p31 p.1 p12 p22 p32 p.2 p13 p23 p33 p.3 p14 p24 p34 p.4*/
                   7691:            /*#  1    2        3   4   5  6    7  8   9   10  11  12  13  14  15  16  17  18 */
                   7692:            fprintf(ficgp," u %d:(", ioffset); 
1.266     brouard  7693:            if(i==nlstate+1){
1.270     brouard  7694:              fprintf(ficgp," $%d/(1.-$%d)):1 t 'pw.%d' with line lc variable ",        \
1.266     brouard  7695:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1),  ioffset+1+(i-1)+(nlstate+1)*nlstate,cpt );
                   7696:              fprintf(ficgp,",\\\n '' ");
                   7697:              fprintf(ficgp," u %d:(",ioffset); 
1.270     brouard  7698:              fprintf(ficgp," (($1-$2) == %d ) ? $%d/(1.-$%d) : 1/0):1 with labels center not ", \
1.266     brouard  7699:                     offyear,                           \
1.268     brouard  7700:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1),  ioffset+1+(i-1)+(nlstate+1)*nlstate );
1.266     brouard  7701:            }else
1.227     brouard  7702:              fprintf(ficgp," $%d/(1.-$%d)) t 'p%d%d' with line ",      \
                   7703:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1),  ioffset+1+(i-1)+(nlstate+1)*nlstate,i,cpt );
                   7704:          }else{ /* more than 2 covariates */
1.270     brouard  7705:            ioffset=2*cptcoveff+2; /* Age is in 4 or 6 or etc.*/
                   7706:            /*#  V1  = 1  V2 =  0 yearproj age p11 p21 p.1 p12 p22 p.2 p13 p23 p.3*/
                   7707:            /*#   1    2   3    4    5      6  7   8   9   10   11 12  13   14  15 */
                   7708:            iyearc=ioffset-1;
                   7709:            iagec=ioffset;
1.227     brouard  7710:            fprintf(ficgp," u %d:(",ioffset); 
                   7711:            kl=0;
                   7712:            strcpy(gplotcondition,"(");
                   7713:            for (k=1; k<=cptcoveff; k++){    /* For each covariate writing the chain of conditions */
                   7714:              lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate value corresponding to combination k1 and covariate k */
                   7715:              /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   7716:              /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   7717:              /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
                   7718:              vlv= nbcode[Tvaraff[k]][lv]; /* Value of the modality of Tvaraff[k] */
                   7719:              kl++;
                   7720:              sprintf(gplotcondition+strlen(gplotcondition),"$%d==%d && $%d==%d " ,kl,Tvaraff[k], kl+1, nbcode[Tvaraff[k]][lv]);
                   7721:              kl++;
                   7722:              if(k <cptcoveff && cptcoveff>1)
                   7723:                sprintf(gplotcondition+strlen(gplotcondition)," && ");
                   7724:            }
                   7725:            strcpy(gplotcondition+strlen(gplotcondition),")");
                   7726:            /* 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 *\/ */
                   7727:            /*6+(cpt-1)*(nlstate+1)+1+(i-1)+(nlstate+1)*nlstate; 6+(1-1)*(2+1)+1+(1-1) +(2+1)*2=13 */ 
                   7728:            /*6+1+(i-1)+(nlstate+1)*nlstate; 6+1+(1-1) +(2+1)*2=13 */ 
                   7729:            /* ''  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*/
                   7730:            if(i==nlstate+1){
1.270     brouard  7731:              fprintf(ficgp,"%s ? $%d/(1.-$%d) : 1/0):%d t 'p.%d' with line lc variable", gplotcondition, \
                   7732:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1),  ioffset+1+(i-1)+(nlstate+1)*nlstate,iyearc, cpt );
1.266     brouard  7733:              fprintf(ficgp,",\\\n '' ");
1.270     brouard  7734:              fprintf(ficgp," u %d:(",iagec); 
                   7735:              fprintf(ficgp,"%s && (($%d-$%d) == %d ) ? $%d/(1.-$%d) : 1/0):%d with labels center not ", gplotcondition, \
                   7736:                      iyearc, iagec, offyear,                           \
                   7737:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1),  ioffset+1+(i-1)+(nlstate+1)*nlstate, iyearc );
1.266     brouard  7738: /*  '' 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  7739:            }else{
                   7740:              fprintf(ficgp,"%s ? $%d/(1.-$%d) : 1/0) t 'p%d%d' with line ", gplotcondition, \
                   7741:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1), ioffset +1+(i-1)+(nlstate+1)*nlstate,i,cpt );
                   7742:            }
                   7743:          } /* end if covariate */
                   7744:        } /* nlstate */
1.264     brouard  7745:        fprintf(ficgp,"\nset out; unset label;\n");
1.223     brouard  7746:       } /* end cpt state*/
                   7747:     } /* end covariate */
                   7748:   } /* End if prevfcast */
1.227     brouard  7749:   
1.268     brouard  7750:   if(backcast==1){
                   7751:     /* Back projection from cross-sectional to stable (mixed) for each covariate */
                   7752:     
                   7753:     for (k1=1; k1<= m ; k1 ++) /* For each covariate combination if any */
                   7754:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
                   7755:       if(m != 1 && TKresult[nres]!= k1)
                   7756:        continue;
                   7757:       for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each life state */
                   7758:        strcpy(gplotlabel,"(");      
                   7759:        fprintf(ficgp,"\n#\n#\n#Back projection of prevalence to stable (mixed) back prevalence: 'BPROJ_' files, covariatecombination#=%d originstate=%d",k1, cpt);
                   7760:        for (k=1; k<=cptcoveff; k++){    /* For each correspondig covariate value  */
                   7761:          lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate value corresponding to k1 combination and kth covariate */
                   7762:          /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   7763:          /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   7764:          /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
                   7765:          vlv= nbcode[Tvaraff[k]][lv];
                   7766:          fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv);
                   7767:          sprintf(gplotlabel+strlen(gplotlabel)," V%d=%d ",Tvaraff[k],vlv);
                   7768:        }
                   7769:        for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
                   7770:          fprintf(ficgp," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
                   7771:          sprintf(gplotlabel+strlen(gplotlabel)," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
                   7772:        }       
                   7773:        strcpy(gplotlabel+strlen(gplotlabel),")");
                   7774:        fprintf(ficgp,"\n#\n");
                   7775:        if(invalidvarcomb[k1]){
                   7776:          fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   7777:          continue;
                   7778:        }
                   7779:        
                   7780:        fprintf(ficgp,"# hbijx=backprobability over h years, hb.jx is weighted by observed prev at destination state\n ");
                   7781:        fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" \n",subdirf2(optionfilefiname,"PROJB_"),cpt,k1,nres);
                   7782:        fprintf(ficgp,"set label \"Origin alive state %d %s\" at graph 0.98,0.5 center rotate font \"Helvetica,12\"\n",cpt,gplotlabel);
                   7783:        fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Prevalence\" \n\
                   7784: set ter svg size 640, 480\nunset log y\nplot [%.f:%.f]  ", ageminpar, agemaxpar);
                   7785: 
                   7786:        /* for (i=1; i<= nlstate+1 ; i ++){  /\* nlstate +1 p11 p21 p.1 *\/ */
                   7787:        istart=nlstate+1; /* Could be one if by state, but nlstate+1 is w.i projection only */
                   7788:        /*istart=1;*/ /* Could be one if by state, but nlstate+1 is w.i projection only */
                   7789:        for (i=istart; i<= nlstate+1 ; i ++){  /* nlstate +1 p11 p21 p.1 */
                   7790:          /*#  V1  = 1  V2 =  0 yearproj age p11 p21 p.1 p12 p22 p.2 p13 p23 p.3*/
                   7791:          /*#   1    2   3    4    5      6  7   8   9   10   11 12  13   14  15 */   
                   7792:          /*# yearproj age p11 p21 p.1 p12 p22 p.2 p13 p23 p.3*/
                   7793:          /*#   1       2   3    4    5      6  7   8   9   10   11 12  13   14  15 */   
                   7794:          if(i==istart){
                   7795:            fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"FB_"));
                   7796:          }else{
                   7797:            fprintf(ficgp,",\\\n '' ");
                   7798:          }
                   7799:          if(cptcoveff ==0){ /* No covariate */
                   7800:            ioffset=2; /* Age is in 2 */
                   7801:            /*# yearproj age p11 p21 p31 p.1 p12 p22 p32 p.2 p13 p23 p33 p.3 p14 p24 p34 p.4*/
                   7802:            /*#   1       2   3   4   5  6    7  8   9   10  11  12  13  14  15  16  17  18 */
                   7803:            /*# V1  = 1 yearproj age p11 p21 p31 p.1 p12 p22 p32 p.2 p13 p23 p33 p.3 p14 p24 p34 p.4*/
                   7804:            /*#  1    2        3   4   5  6    7  8   9   10  11  12  13  14  15  16  17  18 */
                   7805:            fprintf(ficgp," u %d:(", ioffset); 
                   7806:            if(i==nlstate+1){
1.270     brouard  7807:              fprintf(ficgp," $%d/(1.-$%d)):1 t 'bw%d' with line lc variable ", \
1.268     brouard  7808:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1),  ioffset+1+(i-1)+(nlstate+1)*nlstate,cpt );
                   7809:              fprintf(ficgp,",\\\n '' ");
                   7810:              fprintf(ficgp," u %d:(",ioffset); 
1.270     brouard  7811:              fprintf(ficgp," (($1-$2) == %d ) ? $%d : 1/0):1 with labels center not ", \
1.268     brouard  7812:                     offbyear,                          \
                   7813:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1) );
                   7814:            }else
                   7815:              fprintf(ficgp," $%d/(1.-$%d)) t 'b%d%d' with line ",      \
                   7816:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1),  ioffset+1+(i-1)+(nlstate+1)*nlstate,cpt,i );
                   7817:          }else{ /* more than 2 covariates */
1.270     brouard  7818:            ioffset=2*cptcoveff+2; /* Age is in 4 or 6 or etc.*/
                   7819:            /*#  V1  = 1  V2 =  0 yearproj age p11 p21 p.1 p12 p22 p.2 p13 p23 p.3*/
                   7820:            /*#   1    2   3    4    5      6  7   8   9   10   11 12  13   14  15 */
                   7821:            iyearc=ioffset-1;
                   7822:            iagec=ioffset;
1.268     brouard  7823:            fprintf(ficgp," u %d:(",ioffset); 
                   7824:            kl=0;
                   7825:            strcpy(gplotcondition,"(");
                   7826:            for (k=1; k<=cptcoveff; k++){    /* For each covariate writing the chain of conditions */
                   7827:              lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate value corresponding to combination k1 and covariate k */
                   7828:              /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   7829:              /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   7830:              /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
                   7831:              vlv= nbcode[Tvaraff[k]][lv]; /* Value of the modality of Tvaraff[k] */
                   7832:              kl++;
                   7833:              sprintf(gplotcondition+strlen(gplotcondition),"$%d==%d && $%d==%d " ,kl,Tvaraff[k], kl+1, nbcode[Tvaraff[k]][lv]);
                   7834:              kl++;
                   7835:              if(k <cptcoveff && cptcoveff>1)
                   7836:                sprintf(gplotcondition+strlen(gplotcondition)," && ");
                   7837:            }
                   7838:            strcpy(gplotcondition+strlen(gplotcondition),")");
                   7839:            /* 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 *\/ */
                   7840:            /*6+(cpt-1)*(nlstate+1)+1+(i-1)+(nlstate+1)*nlstate; 6+(1-1)*(2+1)+1+(1-1) +(2+1)*2=13 */ 
                   7841:            /*6+1+(i-1)+(nlstate+1)*nlstate; 6+1+(1-1) +(2+1)*2=13 */ 
                   7842:            /* ''  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*/
                   7843:            if(i==nlstate+1){
1.270     brouard  7844:              fprintf(ficgp,"%s ? $%d : 1/0):%d t 'bw%d' with line lc variable", gplotcondition, \
                   7845:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1),iyearc,cpt );
1.268     brouard  7846:              fprintf(ficgp,",\\\n '' ");
1.270     brouard  7847:              fprintf(ficgp," u %d:(",iagec); 
1.268     brouard  7848:              /* fprintf(ficgp,"%s && (($5-$6) == %d ) ? $%d/(1.-$%d) : 1/0):5 with labels center not ", gplotcondition, \ */
1.270     brouard  7849:              fprintf(ficgp,"%s && (($%d-$%d) == %d ) ? $%d : 1/0):%d with labels center not ", gplotcondition, \
                   7850:                      iyearc,iagec,offbyear,                            \
                   7851:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1), iyearc );
1.268     brouard  7852: /*  '' u 6:(($1==1 && $2==0  && $3==2 && $4==0) && (($5-$6) == 1947) ? $10/(1.-$22) : 1/0):5 with labels center boxed not*/
                   7853:            }else{
                   7854:              /* fprintf(ficgp,"%s ? $%d/(1.-$%d) : 1/0) t 'p%d%d' with line ", gplotcondition, \ */
                   7855:              fprintf(ficgp,"%s ? $%d : 1/0) t 'b%d%d' with line ", gplotcondition, \
                   7856:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1), cpt,i );
                   7857:            }
                   7858:          } /* end if covariate */
                   7859:        } /* nlstate */
                   7860:        fprintf(ficgp,"\nset out; unset label;\n");
                   7861:       } /* end cpt state*/
                   7862:     } /* end covariate */
                   7863:   } /* End if backcast */
                   7864:   
1.227     brouard  7865:   
1.238     brouard  7866:   /* 9eme writing MLE parameters */
                   7867:   fprintf(ficgp,"\n##############\n#9eme MLE estimated parameters\n#############\n");
1.126     brouard  7868:   for(i=1,jk=1; i <=nlstate; i++){
1.187     brouard  7869:     fprintf(ficgp,"# initial state %d\n",i);
1.126     brouard  7870:     for(k=1; k <=(nlstate+ndeath); k++){
                   7871:       if (k != i) {
1.227     brouard  7872:        fprintf(ficgp,"#   current state %d\n",k);
                   7873:        for(j=1; j <=ncovmodel; j++){
                   7874:          fprintf(ficgp,"p%d=%f; ",jk,p[jk]);
                   7875:          jk++; 
                   7876:        }
                   7877:        fprintf(ficgp,"\n");
1.126     brouard  7878:       }
                   7879:     }
1.223     brouard  7880:   }
1.187     brouard  7881:   fprintf(ficgp,"##############\n#\n");
1.227     brouard  7882:   
1.145     brouard  7883:   /*goto avoid;*/
1.238     brouard  7884:   /* 10eme Graphics of probabilities or incidences using written MLE parameters */
                   7885:   fprintf(ficgp,"\n##############\n#10eme Graphics of probabilities or incidences\n#############\n");
1.187     brouard  7886:   fprintf(ficgp,"# logi(p12/p11)=a12+b12*age+c12age*age+d12*V1+e12*V1*age\n");
                   7887:   fprintf(ficgp,"# logi(p12/p11)=p1 +p2*age +p3*age*age+ p4*V1+ p5*V1*age\n");
                   7888:   fprintf(ficgp,"# logi(p13/p11)=a13+b13*age+c13age*age+d13*V1+e13*V1*age\n");
                   7889:   fprintf(ficgp,"# logi(p13/p11)=p6 +p7*age +p8*age*age+ p9*V1+ p10*V1*age\n");
                   7890:   fprintf(ficgp,"# p12+p13+p14+p11=1=p11(1+exp(a12+b12*age+c12age*age+d12*V1+e12*V1*age)\n");
                   7891:   fprintf(ficgp,"#                      +exp(a13+b13*age+c13age*age+d13*V1+e13*V1*age)+...)\n");
                   7892:   fprintf(ficgp,"# p11=1/(1+exp(a12+b12*age+c12age*age+d12*V1+e12*V1*age)\n");
                   7893:   fprintf(ficgp,"#                      +exp(a13+b13*age+c13age*age+d13*V1+e13*V1*age)+...)\n");
                   7894:   fprintf(ficgp,"# p12=exp(a12+b12*age+c12age*age+d12*V1+e12*V1*age)/\n");
                   7895:   fprintf(ficgp,"#     (1+exp(a12+b12*age+c12age*age+d12*V1+e12*V1*age)\n");
                   7896:   fprintf(ficgp,"#       +exp(a13+b13*age+c13age*age+d13*V1+e13*V1*age))\n");
                   7897:   fprintf(ficgp,"#       +exp(a14+b14*age+c14age*age+d14*V1+e14*V1*age)+...)\n");
                   7898:   fprintf(ficgp,"#\n");
1.223     brouard  7899:   for(ng=1; ng<=3;ng++){ /* Number of graphics: first is logit, 2nd is probabilities, third is incidences per year*/
1.238     brouard  7900:     fprintf(ficgp,"#Number of graphics: first is logit, 2nd is probabilities, third is incidences per year\n");
1.237     brouard  7901:     fprintf(ficgp,"#model=%s \n",model);
1.238     brouard  7902:     fprintf(ficgp,"# Type of graphic ng=%d\n",ng);
1.264     brouard  7903:     fprintf(ficgp,"#   k1=1 to 2^%d=%d\n",cptcoveff,m);/* to be checked */
                   7904:     for(k1=1; k1 <=m; k1++)  /* For each combination of covariate */
1.237     brouard  7905:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.264     brouard  7906:       if(m != 1 && TKresult[nres]!= k1)
1.237     brouard  7907:        continue;
1.264     brouard  7908:       fprintf(ficgp,"\n\n# Combination of dummy  k1=%d which is ",k1);
                   7909:       strcpy(gplotlabel,"(");
1.276     brouard  7910:       /*sprintf(gplotlabel+strlen(gplotlabel)," Dummy combination %d ",k1);*/
1.264     brouard  7911:       for (k=1; k<=cptcoveff; k++){    /* For each correspondig covariate value  */
                   7912:        lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate value corresponding to k1 combination and kth covariate */
                   7913:        /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   7914:        /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   7915:        /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
                   7916:        vlv= nbcode[Tvaraff[k]][lv];
                   7917:        fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv);
                   7918:        sprintf(gplotlabel+strlen(gplotlabel)," V%d=%d ",Tvaraff[k],vlv);
                   7919:       }
1.237     brouard  7920:       for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
                   7921:        fprintf(ficgp," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
1.264     brouard  7922:        sprintf(gplotlabel+strlen(gplotlabel)," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
1.237     brouard  7923:       }        
1.264     brouard  7924:       strcpy(gplotlabel+strlen(gplotlabel),")");
1.237     brouard  7925:       fprintf(ficgp,"\n#\n");
1.264     brouard  7926:       fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" ",subdirf2(optionfilefiname,"PE_"),k1,ng,nres);
1.276     brouard  7927:       fprintf(ficgp,"\nset key outside ");
                   7928:       /* fprintf(ficgp,"\nset label \"%s\" at graph 1.2,0.5 center rotate font \"Helvetica,12\"\n",gplotlabel); */
                   7929:       fprintf(ficgp,"\nset title \"%s\" font \"Helvetica,12\"\n",gplotlabel);
1.223     brouard  7930:       fprintf(ficgp,"\nset ter svg size 640, 480 ");
                   7931:       if (ng==1){
                   7932:        fprintf(ficgp,"\nset ylabel \"Value of the logit of the model\"\n"); /* exp(a12+b12*x) could be nice */
                   7933:        fprintf(ficgp,"\nunset log y");
                   7934:       }else if (ng==2){
                   7935:        fprintf(ficgp,"\nset ylabel \"Probability\"\n");
                   7936:        fprintf(ficgp,"\nset log y");
                   7937:       }else if (ng==3){
                   7938:        fprintf(ficgp,"\nset ylabel \"Quasi-incidence per year\"\n");
                   7939:        fprintf(ficgp,"\nset log y");
                   7940:       }else
                   7941:        fprintf(ficgp,"\nunset title ");
                   7942:       fprintf(ficgp,"\nplot  [%.f:%.f] ",ageminpar,agemaxpar);
                   7943:       i=1;
                   7944:       for(k2=1; k2<=nlstate; k2++) {
                   7945:        k3=i;
                   7946:        for(k=1; k<=(nlstate+ndeath); k++) {
                   7947:          if (k != k2){
                   7948:            switch( ng) {
                   7949:            case 1:
                   7950:              if(nagesqr==0)
                   7951:                fprintf(ficgp," p%d+p%d*x",i,i+1);
                   7952:              else /* nagesqr =1 */
                   7953:                fprintf(ficgp," p%d+p%d*x+p%d*x*x",i,i+1,i+1+nagesqr);
                   7954:              break;
                   7955:            case 2: /* ng=2 */
                   7956:              if(nagesqr==0)
                   7957:                fprintf(ficgp," exp(p%d+p%d*x",i,i+1);
                   7958:              else /* nagesqr =1 */
                   7959:                fprintf(ficgp," exp(p%d+p%d*x+p%d*x*x",i,i+1,i+1+nagesqr);
                   7960:              break;
                   7961:            case 3:
                   7962:              if(nagesqr==0)
                   7963:                fprintf(ficgp," %f*exp(p%d+p%d*x",YEARM/stepm,i,i+1);
                   7964:              else /* nagesqr =1 */
                   7965:                fprintf(ficgp," %f*exp(p%d+p%d*x+p%d*x*x",YEARM/stepm,i,i+1,i+1+nagesqr);
                   7966:              break;
                   7967:            }
                   7968:            ij=1;/* To be checked else nbcode[0][0] wrong */
1.237     brouard  7969:            ijp=1; /* product no age */
                   7970:            /* for(j=3; j <=ncovmodel-nagesqr; j++) { */
                   7971:            for(j=1; j <=cptcovt; j++) { /* For each covariate of the simplified model */
1.223     brouard  7972:              /* printf("Tage[%d]=%d, j=%d\n", ij, Tage[ij], j); */
1.268     brouard  7973:              if(cptcovage >0){ /* V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1, 2 V5 and V1 */
                   7974:                if(j==Tage[ij]) { /* Product by age  To be looked at!!*/
                   7975:                  if(ij <=cptcovage) { /* V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1, 2 V5 and V1 */
                   7976:                    if(DummyV[j]==0){
                   7977:                      fprintf(ficgp,"+p%d*%d*x",i+j+2+nagesqr-1,Tinvresult[nres][Tvar[j]]);;
                   7978:                    }else{ /* quantitative */
                   7979:                      fprintf(ficgp,"+p%d*%f*x",i+j+2+nagesqr-1,Tqinvresult[nres][Tvar[j]]); /* Tqinvresult in decoderesult */
                   7980:                      /* fprintf(ficgp,"+p%d*%d*x",i+j+nagesqr-1,nbcode[Tvar[j-2]][codtabm(k1,Tvar[j-2])]); */
                   7981:                    }
                   7982:                    ij++;
1.237     brouard  7983:                  }
1.268     brouard  7984:                } 
                   7985:              }else if(cptcovprod >0){
                   7986:                if(j==Tprod[ijp]) { /* */ 
                   7987:                  /* printf("Tprod[%d]=%d, j=%d\n", ij, Tprod[ijp], j); */
                   7988:                  if(ijp <=cptcovprod) { /* Product */
                   7989:                    if(DummyV[Tvard[ijp][1]]==0){/* Vn is dummy */
                   7990:                      if(DummyV[Tvard[ijp][2]]==0){/* Vn and Vm are dummy */
                   7991:                        /* 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)]); */
                   7992:                        fprintf(ficgp,"+p%d*%d*%d",i+j+2+nagesqr-1,Tinvresult[nres][Tvard[ijp][1]],Tinvresult[nres][Tvard[ijp][2]]);
                   7993:                      }else{ /* Vn is dummy and Vm is quanti */
                   7994:                        /* fprintf(ficgp,"+p%d*%d*%f",i+j+2+nagesqr-1,nbcode[Tvard[ijp][1]][codtabm(k1,j)],Tqinvresult[nres][Tvard[ijp][2]]); */
                   7995:                        fprintf(ficgp,"+p%d*%d*%f",i+j+2+nagesqr-1,Tinvresult[nres][Tvard[ijp][1]],Tqinvresult[nres][Tvard[ijp][2]]);
                   7996:                      }
                   7997:                    }else{ /* Vn*Vm Vn is quanti */
                   7998:                      if(DummyV[Tvard[ijp][2]]==0){
                   7999:                        fprintf(ficgp,"+p%d*%d*%f",i+j+2+nagesqr-1,Tinvresult[nres][Tvard[ijp][2]],Tqinvresult[nres][Tvard[ijp][1]]);
                   8000:                      }else{ /* Both quanti */
                   8001:                        fprintf(ficgp,"+p%d*%f*%f",i+j+2+nagesqr-1,Tqinvresult[nres][Tvard[ijp][1]],Tqinvresult[nres][Tvard[ijp][2]]);
                   8002:                      }
1.237     brouard  8003:                    }
1.268     brouard  8004:                    ijp++;
1.237     brouard  8005:                  }
1.268     brouard  8006:                } /* end Tprod */
1.237     brouard  8007:              } else{  /* simple covariate */
1.264     brouard  8008:                /* fprintf(ficgp,"+p%d*%d",i+j+2+nagesqr-1,nbcode[Tvar[j]][codtabm(k1,j)]); /\* Valgrind bug nbcode *\/ */
1.237     brouard  8009:                if(Dummy[j]==0){
                   8010:                  fprintf(ficgp,"+p%d*%d",i+j+2+nagesqr-1,Tinvresult[nres][Tvar[j]]); /*  */
                   8011:                }else{ /* quantitative */
                   8012:                  fprintf(ficgp,"+p%d*%f",i+j+2+nagesqr-1,Tqinvresult[nres][Tvar[j]]); /* */
1.264     brouard  8013:                  /* fprintf(ficgp,"+p%d*%d*x",i+j+nagesqr-1,nbcode[Tvar[j-2]][codtabm(k1,Tvar[j-2])]); */
1.223     brouard  8014:                }
1.237     brouard  8015:              } /* end simple */
                   8016:            } /* end j */
1.223     brouard  8017:          }else{
                   8018:            i=i-ncovmodel;
                   8019:            if(ng !=1 ) /* For logit formula of log p11 is more difficult to get */
                   8020:              fprintf(ficgp," (1.");
                   8021:          }
1.227     brouard  8022:          
1.223     brouard  8023:          if(ng != 1){
                   8024:            fprintf(ficgp,")/(1");
1.227     brouard  8025:            
1.264     brouard  8026:            for(cpt=1; cpt <=nlstate; cpt++){ 
1.223     brouard  8027:              if(nagesqr==0)
1.264     brouard  8028:                fprintf(ficgp,"+exp(p%d+p%d*x",k3+(cpt-1)*ncovmodel,k3+(cpt-1)*ncovmodel+1);
1.223     brouard  8029:              else /* nagesqr =1 */
1.264     brouard  8030:                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  8031:               
1.223     brouard  8032:              ij=1;
                   8033:              for(j=3; j <=ncovmodel-nagesqr; j++){
1.268     brouard  8034:                 if(cptcovage >0){ 
                   8035:                   if((j-2)==Tage[ij]) { /* Bug valgrind */
                   8036:                     if(ij <=cptcovage) { /* Bug valgrind */
                   8037:                       fprintf(ficgp,"+p%d*%d*x",k3+(cpt-1)*ncovmodel+1+j-2+nagesqr,nbcode[Tvar[j-2]][codtabm(k1,j-2)]);
                   8038:                       /* fprintf(ficgp,"+p%d*%d*x",k3+(cpt-1)*ncovmodel+1+j-2+nagesqr,nbcode[Tvar[j-2]][codtabm(k1,Tvar[j-2])]); */
                   8039:                       ij++;
                   8040:                     }
                   8041:                   }
                   8042:                 }else
                   8043:                   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  8044:              }
                   8045:              fprintf(ficgp,")");
                   8046:            }
                   8047:            fprintf(ficgp,")");
                   8048:            if(ng ==2)
1.276     brouard  8049:              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  8050:            else /* ng= 3 */
1.276     brouard  8051:              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  8052:          }else{ /* end ng <> 1 */
                   8053:            if( k !=k2) /* logit p11 is hard to draw */
1.276     brouard  8054:              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  8055:          }
                   8056:          if ((k+k2)!= (nlstate*2+ndeath) && ng != 1)
                   8057:            fprintf(ficgp,",");
                   8058:          if (ng == 1 && k!=k2 && (k+k2)!= (nlstate*2+ndeath))
                   8059:            fprintf(ficgp,",");
                   8060:          i=i+ncovmodel;
                   8061:        } /* end k */
                   8062:       } /* end k2 */
1.276     brouard  8063:       /* fprintf(ficgp,"\n set out; unset label;set key default;\n"); */
                   8064:       fprintf(ficgp,"\n set out; unset title;set key default;\n");
1.264     brouard  8065:     } /* end k1 */
1.223     brouard  8066:   } /* end ng */
                   8067:   /* avoid: */
                   8068:   fflush(ficgp); 
1.126     brouard  8069: }  /* end gnuplot */
                   8070: 
                   8071: 
                   8072: /*************** Moving average **************/
1.219     brouard  8073: /* int movingaverage(double ***probs, double bage, double fage, double ***mobaverage, int mobilav, double bageout, double fageout){ */
1.222     brouard  8074:  int movingaverage(double ***probs, double bage, double fage, double ***mobaverage, int mobilav){
1.218     brouard  8075:    
1.222     brouard  8076:    int i, cpt, cptcod;
                   8077:    int modcovmax =1;
                   8078:    int mobilavrange, mob;
                   8079:    int iage=0;
1.288     brouard  8080:    int firstA1=0, firstA2=0;
1.222     brouard  8081: 
1.266     brouard  8082:    double sum=0., sumr=0.;
1.222     brouard  8083:    double age;
1.266     brouard  8084:    double *sumnewp, *sumnewm, *sumnewmr;
                   8085:    double *agemingood, *agemaxgood; 
                   8086:    double *agemingoodr, *agemaxgoodr; 
1.222     brouard  8087:   
                   8088:   
1.278     brouard  8089:    /* modcovmax=2*cptcoveff;  Max number of modalities. We suppose  */
                   8090:    /*             a covariate has 2 modalities, should be equal to ncovcombmax   */
1.222     brouard  8091: 
                   8092:    sumnewp = vector(1,ncovcombmax);
                   8093:    sumnewm = vector(1,ncovcombmax);
1.266     brouard  8094:    sumnewmr = vector(1,ncovcombmax);
1.222     brouard  8095:    agemingood = vector(1,ncovcombmax); 
1.266     brouard  8096:    agemingoodr = vector(1,ncovcombmax);        
1.222     brouard  8097:    agemaxgood = vector(1,ncovcombmax);
1.266     brouard  8098:    agemaxgoodr = vector(1,ncovcombmax);
1.222     brouard  8099: 
                   8100:    for (cptcod=1;cptcod<=ncovcombmax;cptcod++){
1.266     brouard  8101:      sumnewm[cptcod]=0.; sumnewmr[cptcod]=0.;
1.222     brouard  8102:      sumnewp[cptcod]=0.;
1.266     brouard  8103:      agemingood[cptcod]=0, agemingoodr[cptcod]=0;
                   8104:      agemaxgood[cptcod]=0, agemaxgoodr[cptcod]=0;
1.222     brouard  8105:    }
                   8106:    if (cptcovn<1) ncovcombmax=1; /* At least 1 pass */
                   8107:   
1.266     brouard  8108:    if(mobilav==-1 || mobilav==1||mobilav ==3 ||mobilav==5 ||mobilav== 7){
                   8109:      if(mobilav==1 || mobilav==-1) mobilavrange=5; /* default */
1.222     brouard  8110:      else mobilavrange=mobilav;
                   8111:      for (age=bage; age<=fage; age++)
                   8112:        for (i=1; i<=nlstate;i++)
                   8113:         for (cptcod=1;cptcod<=ncovcombmax;cptcod++)
                   8114:           mobaverage[(int)age][i][cptcod]=probs[(int)age][i][cptcod];
                   8115:      /* We keep the original values on the extreme ages bage, fage and for 
                   8116:        fage+1 and bage-1 we use a 3 terms moving average; for fage+2 bage+2
                   8117:        we use a 5 terms etc. until the borders are no more concerned. 
                   8118:      */ 
                   8119:      for (mob=3;mob <=mobilavrange;mob=mob+2){
                   8120:        for (age=bage+(mob-1)/2; age<=fage-(mob-1)/2; age++){
1.266     brouard  8121:         for (cptcod=1;cptcod<=ncovcombmax;cptcod++){
                   8122:           sumnewm[cptcod]=0.;
                   8123:           for (i=1; i<=nlstate;i++){
1.222     brouard  8124:             mobaverage[(int)age][i][cptcod] =probs[(int)age][i][cptcod];
                   8125:             for (cpt=1;cpt<=(mob-1)/2;cpt++){
                   8126:               mobaverage[(int)age][i][cptcod] +=probs[(int)age-cpt][i][cptcod];
                   8127:               mobaverage[(int)age][i][cptcod] +=probs[(int)age+cpt][i][cptcod];
                   8128:             }
                   8129:             mobaverage[(int)age][i][cptcod]=mobaverage[(int)age][i][cptcod]/mob;
1.266     brouard  8130:             sumnewm[cptcod]+=mobaverage[(int)age][i][cptcod];
                   8131:           } /* end i */
                   8132:           if(sumnewm[cptcod] >1.e-3) mobaverage[(int)age][i][cptcod]=mobaverage[(int)age][i][cptcod]/sumnewm[cptcod]; /* Rescaling to sum one */
                   8133:         } /* end cptcod */
1.222     brouard  8134:        }/* end age */
                   8135:      }/* end mob */
1.266     brouard  8136:    }else{
                   8137:      printf("Error internal in movingaverage, mobilav=%d.\n",mobilav);
1.222     brouard  8138:      return -1;
1.266     brouard  8139:    }
                   8140: 
                   8141:    for (cptcod=1;cptcod<=ncovcombmax;cptcod++){ /* for each combination */
1.222     brouard  8142:      /* for (age=bage+(mob-1)/2; age<=fage-(mob-1)/2; age++){ */
                   8143:      if(invalidvarcomb[cptcod]){
                   8144:        printf("\nCombination (%d) ignored because no cases \n",cptcod); 
                   8145:        continue;
                   8146:      }
1.219     brouard  8147: 
1.266     brouard  8148:      for (age=fage-(mob-1)/2; age>=bage+(mob-1)/2; age--){ /*looking for the youngest and oldest good age */
                   8149:        sumnewm[cptcod]=0.;
                   8150:        sumnewmr[cptcod]=0.;
                   8151:        for (i=1; i<=nlstate;i++){
                   8152:         sumnewm[cptcod]+=mobaverage[(int)age][i][cptcod];
                   8153:         sumnewmr[cptcod]+=probs[(int)age][i][cptcod];
                   8154:        }
                   8155:        if(fabs(sumnewmr[cptcod] - 1.) <= 1.e-3) { /* good without smoothing */
                   8156:         agemingoodr[cptcod]=age;
                   8157:        }
                   8158:        if(fabs(sumnewm[cptcod] - 1.) <= 1.e-3) { /* good */
                   8159:           agemingood[cptcod]=age;
                   8160:        }
                   8161:      } /* age */
                   8162:      for (age=bage+(mob-1)/2; age<=fage-(mob-1)/2; age++){ /*looking for the youngest and oldest good age */
1.222     brouard  8163:        sumnewm[cptcod]=0.;
1.266     brouard  8164:        sumnewmr[cptcod]=0.;
1.222     brouard  8165:        for (i=1; i<=nlstate;i++){
                   8166:         sumnewm[cptcod]+=mobaverage[(int)age][i][cptcod];
1.266     brouard  8167:         sumnewmr[cptcod]+=probs[(int)age][i][cptcod];
                   8168:        }
                   8169:        if(fabs(sumnewmr[cptcod] - 1.) <= 1.e-3) { /* good without smoothing */
                   8170:         agemaxgoodr[cptcod]=age;
1.222     brouard  8171:        }
                   8172:        if(fabs(sumnewm[cptcod] - 1.) <= 1.e-3) { /* good */
1.266     brouard  8173:         agemaxgood[cptcod]=age;
                   8174:        }
                   8175:      } /* age */
                   8176:      /* Thus we have agemingood and agemaxgood as well as goodr for raw (preobs) */
                   8177:      /* but they will change */
1.288     brouard  8178:      firstA1=0;firstA2=0;
1.266     brouard  8179:      for (age=fage-(mob-1)/2; age>=bage; age--){/* From oldest to youngest, filling up to the youngest */
                   8180:        sumnewm[cptcod]=0.;
                   8181:        sumnewmr[cptcod]=0.;
                   8182:        for (i=1; i<=nlstate;i++){
                   8183:         sumnewm[cptcod]+=mobaverage[(int)age][i][cptcod];
                   8184:         sumnewmr[cptcod]+=probs[(int)age][i][cptcod];
                   8185:        }
                   8186:        if(mobilav==-1){ /* Forcing raw ages if good else agemingood */
                   8187:         if(fabs(sumnewmr[cptcod] - 1.) <= 1.e-3) { /* good without smoothing */
                   8188:           agemaxgoodr[cptcod]=age;  /* age min */
                   8189:           for (i=1; i<=nlstate;i++)
                   8190:             mobaverage[(int)age][i][cptcod]=probs[(int)age][i][cptcod];
                   8191:         }else{ /* bad we change the value with the values of good ages */
                   8192:           for (i=1; i<=nlstate;i++){
                   8193:             mobaverage[(int)age][i][cptcod]=mobaverage[(int)agemaxgoodr[cptcod]][i][cptcod];
                   8194:           } /* i */
                   8195:         } /* end bad */
                   8196:        }else{
                   8197:         if(fabs(sumnewm[cptcod] - 1.) <= 1.e-3) { /* good */
                   8198:           agemaxgood[cptcod]=age;
                   8199:         }else{ /* bad we change the value with the values of good ages */
                   8200:           for (i=1; i<=nlstate;i++){
                   8201:             mobaverage[(int)age][i][cptcod]=mobaverage[(int)agemaxgood[cptcod]][i][cptcod];
                   8202:           } /* i */
                   8203:         } /* end bad */
                   8204:        }/* end else */
                   8205:        sum=0.;sumr=0.;
                   8206:        for (i=1; i<=nlstate;i++){
                   8207:         sum+=mobaverage[(int)age][i][cptcod];
                   8208:         sumr+=probs[(int)age][i][cptcod];
                   8209:        }
                   8210:        if(fabs(sum - 1.) > 1.e-3) { /* bad */
1.288     brouard  8211:         if(!firstA1){
                   8212:           firstA1=1;
                   8213:           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);
                   8214:         }
                   8215:         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  8216:        } /* end bad */
                   8217:        /* else{ /\* We found some ages summing to one, we will smooth the oldest *\/ */
                   8218:        if(fabs(sumr - 1.) > 1.e-3) { /* bad */
1.288     brouard  8219:         if(!firstA2){
                   8220:           firstA2=1;
                   8221:           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);
                   8222:         }
                   8223:         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  8224:        } /* end bad */
                   8225:      }/* age */
1.266     brouard  8226: 
                   8227:      for (age=bage+(mob-1)/2; age<=fage; age++){/* From youngest, finding the oldest wrong */
1.222     brouard  8228:        sumnewm[cptcod]=0.;
1.266     brouard  8229:        sumnewmr[cptcod]=0.;
1.222     brouard  8230:        for (i=1; i<=nlstate;i++){
                   8231:         sumnewm[cptcod]+=mobaverage[(int)age][i][cptcod];
1.266     brouard  8232:         sumnewmr[cptcod]+=probs[(int)age][i][cptcod];
                   8233:        } 
                   8234:        if(mobilav==-1){ /* Forcing raw ages if good else agemingood */
                   8235:         if(fabs(sumnewmr[cptcod] - 1.) <= 1.e-3) { /* good */
                   8236:           agemingoodr[cptcod]=age;
                   8237:           for (i=1; i<=nlstate;i++)
                   8238:             mobaverage[(int)age][i][cptcod]=probs[(int)age][i][cptcod];
                   8239:         }else{ /* bad we change the value with the values of good ages */
                   8240:           for (i=1; i<=nlstate;i++){
                   8241:             mobaverage[(int)age][i][cptcod]=mobaverage[(int)agemingoodr[cptcod]][i][cptcod];
                   8242:           } /* i */
                   8243:         } /* end bad */
                   8244:        }else{
                   8245:         if(fabs(sumnewm[cptcod] - 1.) <= 1.e-3) { /* good */
                   8246:           agemingood[cptcod]=age;
                   8247:         }else{ /* bad */
                   8248:           for (i=1; i<=nlstate;i++){
                   8249:             mobaverage[(int)age][i][cptcod]=mobaverage[(int)agemingood[cptcod]][i][cptcod];
                   8250:           } /* i */
                   8251:         } /* end bad */
                   8252:        }/* end else */
                   8253:        sum=0.;sumr=0.;
                   8254:        for (i=1; i<=nlstate;i++){
                   8255:         sum+=mobaverage[(int)age][i][cptcod];
                   8256:         sumr+=mobaverage[(int)age][i][cptcod];
1.222     brouard  8257:        }
1.266     brouard  8258:        if(fabs(sum - 1.) > 1.e-3) { /* bad */
1.268     brouard  8259:         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  8260:        } /* end bad */
                   8261:        /* else{ /\* We found some ages summing to one, we will smooth the oldest *\/ */
                   8262:        if(fabs(sumr - 1.) > 1.e-3) { /* bad */
1.268     brouard  8263:         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  8264:        } /* end bad */
                   8265:      }/* age */
1.266     brouard  8266: 
1.222     brouard  8267:                
                   8268:      for (age=bage; age<=fage; age++){
1.235     brouard  8269:        /* printf("%d %d ", cptcod, (int)age); */
1.222     brouard  8270:        sumnewp[cptcod]=0.;
                   8271:        sumnewm[cptcod]=0.;
                   8272:        for (i=1; i<=nlstate;i++){
                   8273:         sumnewp[cptcod]+=probs[(int)age][i][cptcod];
                   8274:         sumnewm[cptcod]+=mobaverage[(int)age][i][cptcod];
                   8275:         /* printf("%.4f %.4f ",probs[(int)age][i][cptcod], mobaverage[(int)age][i][cptcod]); */
                   8276:        }
                   8277:        /* printf("%.4f %.4f \n",sumnewp[cptcod], sumnewm[cptcod]); */
                   8278:      }
                   8279:      /* printf("\n"); */
                   8280:      /* } */
1.266     brouard  8281: 
1.222     brouard  8282:      /* brutal averaging */
1.266     brouard  8283:      /* for (i=1; i<=nlstate;i++){ */
                   8284:      /*   for (age=1; age<=bage; age++){ */
                   8285:      /*         mobaverage[(int)age][i][cptcod]=mobaverage[(int)agemingood[cptcod]][i][cptcod]; */
                   8286:      /*         /\* printf("age=%d i=%d cptcod=%d mobaverage=%.4f \n",(int)age,i, cptcod, mobaverage[(int)age][i][cptcod]); *\/ */
                   8287:      /*   }     */
                   8288:      /*   for (age=fage; age<=AGESUP; age++){ */
                   8289:      /*         mobaverage[(int)age][i][cptcod]=mobaverage[(int)agemaxgood[cptcod]][i][cptcod]; */
                   8290:      /*         /\* printf("age=%d i=%d cptcod=%d mobaverage=%.4f \n",(int)age,i, cptcod, mobaverage[(int)age][i][cptcod]); *\/ */
                   8291:      /*   } */
                   8292:      /* } /\* end i status *\/ */
                   8293:      /* for (i=nlstate+1; i<=nlstate+ndeath;i++){ */
                   8294:      /*   for (age=1; age<=AGESUP; age++){ */
                   8295:      /*         /\*printf("i=%d, age=%d, cptcod=%d\n",i, (int)age, cptcod);*\/ */
                   8296:      /*         mobaverage[(int)age][i][cptcod]=0.; */
                   8297:      /*   } */
                   8298:      /* } */
1.222     brouard  8299:    }/* end cptcod */
1.266     brouard  8300:    free_vector(agemaxgoodr,1, ncovcombmax);
                   8301:    free_vector(agemaxgood,1, ncovcombmax);
                   8302:    free_vector(agemingood,1, ncovcombmax);
                   8303:    free_vector(agemingoodr,1, ncovcombmax);
                   8304:    free_vector(sumnewmr,1, ncovcombmax);
1.222     brouard  8305:    free_vector(sumnewm,1, ncovcombmax);
                   8306:    free_vector(sumnewp,1, ncovcombmax);
                   8307:    return 0;
                   8308:  }/* End movingaverage */
1.218     brouard  8309:  
1.126     brouard  8310: 
                   8311: /************** Forecasting ******************/
1.269     brouard  8312:  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  8313:   /* proj1, year, month, day of starting projection 
                   8314:      agemin, agemax range of age
                   8315:      dateprev1 dateprev2 range of dates during which prevalence is computed
                   8316:      anproj2 year of en of projection (same day and month as proj1).
                   8317:   */
1.267     brouard  8318:   int yearp, stepsize, hstepm, nhstepm, j, k, cptcod, i, h, i1, k4, nres=0;
1.126     brouard  8319:   double agec; /* generic age */
                   8320:   double agelim, ppij, yp,yp1,yp2,jprojmean,mprojmean,anprojmean;
                   8321:   double *popeffectif,*popcount;
                   8322:   double ***p3mat;
1.218     brouard  8323:   /* double ***mobaverage; */
1.126     brouard  8324:   char fileresf[FILENAMELENGTH];
                   8325: 
                   8326:   agelim=AGESUP;
1.211     brouard  8327:   /* Compute observed prevalence between dateprev1 and dateprev2 by counting the number of people
                   8328:      in each health status at the date of interview (if between dateprev1 and dateprev2).
                   8329:      We still use firstpass and lastpass as another selection.
                   8330:   */
1.214     brouard  8331:   /* freqsummary(fileres, agemin, agemax, s, agev, nlstate, imx,Tvaraff,nbcode, ncodemax,mint,anint,strstart,\ */
                   8332:   /*         firstpass, lastpass,  stepm,  weightopt, model); */
1.126     brouard  8333:  
1.201     brouard  8334:   strcpy(fileresf,"F_"); 
                   8335:   strcat(fileresf,fileresu);
1.126     brouard  8336:   if((ficresf=fopen(fileresf,"w"))==NULL) {
                   8337:     printf("Problem with forecast resultfile: %s\n", fileresf);
                   8338:     fprintf(ficlog,"Problem with forecast resultfile: %s\n", fileresf);
                   8339:   }
1.235     brouard  8340:   printf("\nComputing forecasting: result on file '%s', please wait... \n", fileresf);
                   8341:   fprintf(ficlog,"\nComputing forecasting: result on file '%s', please wait... \n", fileresf);
1.126     brouard  8342: 
1.225     brouard  8343:   if (cptcoveff==0) ncodemax[cptcoveff]=1;
1.126     brouard  8344: 
                   8345: 
                   8346:   stepsize=(int) (stepm+YEARM-1)/YEARM;
                   8347:   if (stepm<=12) stepsize=1;
                   8348:   if(estepm < stepm){
                   8349:     printf ("Problem %d lower than %d\n",estepm, stepm);
                   8350:   }
1.270     brouard  8351:   else{
                   8352:     hstepm=estepm;   
                   8353:   }
                   8354:   if(estepm > stepm){ /* Yes every two year */
                   8355:     stepsize=2;
                   8356:   }
1.126     brouard  8357: 
                   8358:   hstepm=hstepm/stepm; 
                   8359:   yp1=modf(dateintmean,&yp);/* extracts integral of datemean in yp  and
                   8360:                                fractional in yp1 */
                   8361:   anprojmean=yp;
                   8362:   yp2=modf((yp1*12),&yp);
                   8363:   mprojmean=yp;
                   8364:   yp1=modf((yp2*30.5),&yp);
                   8365:   jprojmean=yp;
                   8366:   if(jprojmean==0) jprojmean=1;
                   8367:   if(mprojmean==0) jprojmean=1;
                   8368: 
1.227     brouard  8369:   i1=pow(2,cptcoveff);
1.126     brouard  8370:   if (cptcovn < 1){i1=1;}
                   8371:   
                   8372:   fprintf(ficresf,"# Mean day of interviews %.lf/%.lf/%.lf (%.2f) between %.2f and %.2f \n",jprojmean,mprojmean,anprojmean,dateintmean,dateprev1,dateprev2); 
                   8373:   
                   8374:   fprintf(ficresf,"#****** Routine prevforecast **\n");
1.227     brouard  8375:   
1.126     brouard  8376: /*           if (h==(int)(YEARM*yearp)){ */
1.235     brouard  8377:   for(nres=1; nres <= nresult; nres++) /* For each resultline */
                   8378:   for(k=1; k<=i1;k++){
1.253     brouard  8379:     if(i1 != 1 && TKresult[nres]!= k)
1.235     brouard  8380:       continue;
1.227     brouard  8381:     if(invalidvarcomb[k]){
                   8382:       printf("\nCombination (%d) projection ignored because no cases \n",k); 
                   8383:       continue;
                   8384:     }
                   8385:     fprintf(ficresf,"\n#****** hpijx=probability over h years, hp.jx is weighted by observed prev \n#");
                   8386:     for(j=1;j<=cptcoveff;j++) {
                   8387:       fprintf(ficresf," V%d (=) %d",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   8388:     }
1.235     brouard  8389:     for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
1.238     brouard  8390:       fprintf(ficresf," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
1.235     brouard  8391:     }
1.227     brouard  8392:     fprintf(ficresf," yearproj age");
                   8393:     for(j=1; j<=nlstate+ndeath;j++){ 
                   8394:       for(i=1; i<=nlstate;i++)               
                   8395:        fprintf(ficresf," p%d%d",i,j);
                   8396:       fprintf(ficresf," wp.%d",j);
                   8397:     }
                   8398:     for (yearp=0; yearp<=(anproj2-anproj1);yearp +=stepsize) {
                   8399:       fprintf(ficresf,"\n");
                   8400:       fprintf(ficresf,"\n# Forecasting at date %.lf/%.lf/%.lf ",jproj1,mproj1,anproj1+yearp);   
1.270     brouard  8401:       /* for (agec=fage; agec>=(ageminpar-1); agec--){  */
                   8402:       for (agec=fage; agec>=(bage); agec--){ 
1.227     brouard  8403:        nhstepm=(int) rint((agelim-agec)*YEARM/stepm); 
                   8404:        nhstepm = nhstepm/hstepm; 
                   8405:        p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   8406:        oldm=oldms;savm=savms;
1.268     brouard  8407:        /* We compute pii at age agec over nhstepm);*/
1.235     brouard  8408:        hpxij(p3mat,nhstepm,agec,hstepm,p,nlstate,stepm,oldm,savm, k,nres);
1.268     brouard  8409:        /* Then we print p3mat for h corresponding to the right agec+h*stepms=yearp */
1.227     brouard  8410:        for (h=0; h<=nhstepm; h++){
                   8411:          if (h*hstepm/YEARM*stepm ==yearp) {
1.268     brouard  8412:            break;
                   8413:          }
                   8414:        }
                   8415:        fprintf(ficresf,"\n");
                   8416:        for(j=1;j<=cptcoveff;j++) 
                   8417:          fprintf(ficresf,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   8418:        fprintf(ficresf,"%.f %.f ",anproj1+yearp,agec+h*hstepm/YEARM*stepm);
                   8419:        
                   8420:        for(j=1; j<=nlstate+ndeath;j++) {
                   8421:          ppij=0.;
                   8422:          for(i=1; i<=nlstate;i++) {
1.278     brouard  8423:            if (mobilav>=1)
                   8424:             ppij=ppij+p3mat[i][j][h]*prev[(int)agec][i][k];
                   8425:            else { /* even if mobilav==-1 we use mobaverage, probs may not sums to 1 */
                   8426:                ppij=ppij+p3mat[i][j][h]*probs[(int)(agec)][i][k];
                   8427:            }
1.268     brouard  8428:            fprintf(ficresf," %.3f", p3mat[i][j][h]);
                   8429:          } /* end i */
                   8430:          fprintf(ficresf," %.3f", ppij);
                   8431:        }/* end j */
1.227     brouard  8432:        free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   8433:       } /* end agec */
1.266     brouard  8434:       /* diffyear=(int) anproj1+yearp-ageminpar-1; */
                   8435:       /*printf("Prevforecast %d+%d-%d=diffyear=%d\n",(int) anproj1, (int)yearp,(int)ageminpar,(int) anproj1-(int)ageminpar);*/
1.227     brouard  8436:     } /* end yearp */
                   8437:   } /* end  k */
1.219     brouard  8438:        
1.126     brouard  8439:   fclose(ficresf);
1.215     brouard  8440:   printf("End of Computing forecasting \n");
                   8441:   fprintf(ficlog,"End of Computing forecasting\n");
                   8442: 
1.126     brouard  8443: }
                   8444: 
1.269     brouard  8445: /************** Back Forecasting ******************/
                   8446:  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  8447:   /* back1, year, month, day of starting backection
                   8448:      agemin, agemax range of age
                   8449:      dateprev1 dateprev2 range of dates during which prevalence is computed
1.269     brouard  8450:      anback2 year of end of backprojection (same day and month as back1).
                   8451:      prevacurrent and prev are prevalences.
1.267     brouard  8452:   */
                   8453:   int yearp, stepsize, hstepm, nhstepm, j, k, cptcod, i, h, i1, k4, nres=0;
                   8454:   double agec; /* generic age */
1.268     brouard  8455:   double agelim, ppij, ppi, yp,yp1,yp2,jprojmean,mprojmean,anprojmean;
1.267     brouard  8456:   double *popeffectif,*popcount;
                   8457:   double ***p3mat;
                   8458:   /* double ***mobaverage; */
                   8459:   char fileresfb[FILENAMELENGTH];
                   8460:  
1.268     brouard  8461:   agelim=AGEINF;
1.267     brouard  8462:   /* Compute observed prevalence between dateprev1 and dateprev2 by counting the number of people
                   8463:      in each health status at the date of interview (if between dateprev1 and dateprev2).
                   8464:      We still use firstpass and lastpass as another selection.
                   8465:   */
                   8466:   /* freqsummary(fileres, agemin, agemax, s, agev, nlstate, imx,Tvaraff,nbcode, ncodemax,mint,anint,strstart,\ */
                   8467:   /*         firstpass, lastpass,  stepm,  weightopt, model); */
                   8468: 
                   8469:   /*Do we need to compute prevalence again?*/
                   8470: 
                   8471:   /* prevalence(probs, ageminpar, agemax, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass); */
                   8472:   
                   8473:   strcpy(fileresfb,"FB_");
                   8474:   strcat(fileresfb,fileresu);
                   8475:   if((ficresfb=fopen(fileresfb,"w"))==NULL) {
                   8476:     printf("Problem with back forecast resultfile: %s\n", fileresfb);
                   8477:     fprintf(ficlog,"Problem with back forecast resultfile: %s\n", fileresfb);
                   8478:   }
                   8479:   printf("\nComputing back forecasting: result on file '%s', please wait... \n", fileresfb);
                   8480:   fprintf(ficlog,"\nComputing back forecasting: result on file '%s', please wait... \n", fileresfb);
                   8481:   
                   8482:   if (cptcoveff==0) ncodemax[cptcoveff]=1;
                   8483:   
                   8484:    
                   8485:   stepsize=(int) (stepm+YEARM-1)/YEARM;
                   8486:   if (stepm<=12) stepsize=1;
                   8487:   if(estepm < stepm){
                   8488:     printf ("Problem %d lower than %d\n",estepm, stepm);
                   8489:   }
1.270     brouard  8490:   else{
                   8491:     hstepm=estepm;   
                   8492:   }
                   8493:   if(estepm >= stepm){ /* Yes every two year */
                   8494:     stepsize=2;
                   8495:   }
1.267     brouard  8496:   
                   8497:   hstepm=hstepm/stepm;
                   8498:   yp1=modf(dateintmean,&yp);/* extracts integral of datemean in yp  and
                   8499:                                fractional in yp1 */
                   8500:   anprojmean=yp;
                   8501:   yp2=modf((yp1*12),&yp);
                   8502:   mprojmean=yp;
                   8503:   yp1=modf((yp2*30.5),&yp);
                   8504:   jprojmean=yp;
                   8505:   if(jprojmean==0) jprojmean=1;
                   8506:   if(mprojmean==0) jprojmean=1;
                   8507:   
                   8508:   i1=pow(2,cptcoveff);
                   8509:   if (cptcovn < 1){i1=1;}
                   8510:   
                   8511:   fprintf(ficresfb,"# Mean day of interviews %.lf/%.lf/%.lf (%.2f) between %.2f and %.2f \n",jprojmean,mprojmean,anprojmean,dateintmean,dateprev1,dateprev2);
1.268     brouard  8512:   printf("# Mean day of interviews %.lf/%.lf/%.lf (%.2f) between %.2f and %.2f \n",jprojmean,mprojmean,anprojmean,dateintmean,dateprev1,dateprev2);
1.267     brouard  8513:   
                   8514:   fprintf(ficresfb,"#****** Routine prevbackforecast **\n");
                   8515:   
                   8516:   for(nres=1; nres <= nresult; nres++) /* For each resultline */
                   8517:   for(k=1; k<=i1;k++){
                   8518:     if(i1 != 1 && TKresult[nres]!= k)
                   8519:       continue;
                   8520:     if(invalidvarcomb[k]){
                   8521:       printf("\nCombination (%d) projection ignored because no cases \n",k); 
                   8522:       continue;
                   8523:     }
1.268     brouard  8524:     fprintf(ficresfb,"\n#****** hbijx=probability over h years, hb.jx is weighted by observed prev \n#");
1.267     brouard  8525:     for(j=1;j<=cptcoveff;j++) {
                   8526:       fprintf(ficresfb," V%d (=) %d",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   8527:     }
                   8528:     for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
                   8529:       fprintf(ficresf," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
                   8530:     }
                   8531:     fprintf(ficresfb," yearbproj age");
                   8532:     for(j=1; j<=nlstate+ndeath;j++){
                   8533:       for(i=1; i<=nlstate;i++)
1.268     brouard  8534:        fprintf(ficresfb," b%d%d",i,j);
                   8535:       fprintf(ficresfb," b.%d",j);
1.267     brouard  8536:     }
                   8537:     for (yearp=0; yearp>=(anback2-anback1);yearp -=stepsize) {
                   8538:       /* for (yearp=0; yearp<=(anproj2-anproj1);yearp +=stepsize) {  */
                   8539:       fprintf(ficresfb,"\n");
                   8540:       fprintf(ficresfb,"\n# Back Forecasting at date %.lf/%.lf/%.lf ",jback1,mback1,anback1+yearp);
1.273     brouard  8541:       /* printf("\n# Back Forecasting at date %.lf/%.lf/%.lf ",jback1,mback1,anback1+yearp); */
1.270     brouard  8542:       /* for (agec=bage; agec<=agemax-1; agec++){  /\* testing *\/ */
                   8543:       for (agec=bage; agec<=fage; agec++){  /* testing */
1.268     brouard  8544:        /* We compute bij at age agec over nhstepm, nhstepm decreases when agec increases because of agemax;*/
1.271     brouard  8545:        nhstepm=(int) (agec-agelim) *YEARM/stepm;/*     nhstepm=(int) rint((agec-agelim)*YEARM/stepm);*/
1.267     brouard  8546:        nhstepm = nhstepm/hstepm;
                   8547:        p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   8548:        oldm=oldms;savm=savms;
1.268     brouard  8549:        /* computes hbxij at age agec over 1 to nhstepm */
1.271     brouard  8550:        /* printf("####prevbackforecast debug  agec=%.2f nhstepm=%d\n",agec, nhstepm);fflush(stdout); */
1.267     brouard  8551:        hbxij(p3mat,nhstepm,agec,hstepm,p,prevacurrent,nlstate,stepm, k, nres);
1.268     brouard  8552:        /* hpxij(p3mat,nhstepm,agec,hstepm,p,             nlstate,stepm,oldm,savm, k,nres); */
                   8553:        /* Then we print p3mat for h corresponding to the right agec+h*stepms=yearp */
                   8554:        /* printf(" agec=%.2f\n",agec);fflush(stdout); */
1.267     brouard  8555:        for (h=0; h<=nhstepm; h++){
1.268     brouard  8556:          if (h*hstepm/YEARM*stepm ==-yearp) {
                   8557:            break;
                   8558:          }
                   8559:        }
                   8560:        fprintf(ficresfb,"\n");
                   8561:        for(j=1;j<=cptcoveff;j++)
                   8562:          fprintf(ficresfb,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   8563:        fprintf(ficresfb,"%.f %.f ",anback1+yearp,agec-h*hstepm/YEARM*stepm);
                   8564:        for(i=1; i<=nlstate+ndeath;i++) {
                   8565:          ppij=0.;ppi=0.;
                   8566:          for(j=1; j<=nlstate;j++) {
                   8567:            /* if (mobilav==1) */
1.269     brouard  8568:            ppij=ppij+p3mat[i][j][h]*prevacurrent[(int)agec][j][k];
                   8569:            ppi=ppi+prevacurrent[(int)agec][j][k];
                   8570:            /* ppij=ppij+p3mat[i][j][h]*mobaverage[(int)agec][j][k]; */
                   8571:            /* ppi=ppi+mobaverage[(int)agec][j][k]; */
1.267     brouard  8572:              /* else { */
                   8573:              /*        ppij=ppij+p3mat[i][j][h]*probs[(int)(agec)][i][k]; */
                   8574:              /* } */
1.268     brouard  8575:            fprintf(ficresfb," %.3f", p3mat[i][j][h]);
                   8576:          } /* end j */
                   8577:          if(ppi <0.99){
                   8578:            printf("Error in prevbackforecast, prevalence doesn't sum to 1 for state %d: %3f\n",i, ppi);
                   8579:            fprintf(ficlog,"Error in prevbackforecast, prevalence doesn't sum to 1 for state %d: %3f\n",i, ppi);
                   8580:          }
                   8581:          fprintf(ficresfb," %.3f", ppij);
                   8582:        }/* end j */
1.267     brouard  8583:        free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   8584:       } /* end agec */
                   8585:     } /* end yearp */
                   8586:   } /* end k */
1.217     brouard  8587:   
1.267     brouard  8588:   /* if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX); */
1.217     brouard  8589:   
1.267     brouard  8590:   fclose(ficresfb);
                   8591:   printf("End of Computing Back forecasting \n");
                   8592:   fprintf(ficlog,"End of Computing Back forecasting\n");
1.218     brouard  8593:        
1.267     brouard  8594: }
1.217     brouard  8595: 
1.269     brouard  8596: /* Variance of prevalence limit: varprlim */
                   8597:  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  8598:     /*------- Variance of forward period (stable) prevalence------*/   
1.269     brouard  8599:  
                   8600:    char fileresvpl[FILENAMELENGTH];  
                   8601:    FILE *ficresvpl;
                   8602:    double **oldm, **savm;
                   8603:    double **varpl; /* Variances of prevalence limits by age */   
                   8604:    int i1, k, nres, j ;
                   8605:    
                   8606:     strcpy(fileresvpl,"VPL_");
                   8607:     strcat(fileresvpl,fileresu);
                   8608:     if((ficresvpl=fopen(fileresvpl,"w"))==NULL) {
1.288     brouard  8609:       printf("Problem with variance of forward period (stable) prevalence  resultfile: %s\n", fileresvpl);
1.269     brouard  8610:       exit(0);
                   8611:     }
1.288     brouard  8612:     printf("Computing Variance-covariance of forward period (stable) prevalence: file '%s' ...", fileresvpl);fflush(stdout);
                   8613:     fprintf(ficlog, "Computing Variance-covariance of forward period (stable) prevalence: file '%s' ...", fileresvpl);fflush(ficlog);
1.269     brouard  8614:     
                   8615:     /*for(cptcov=1,k=0;cptcov<=i1;cptcov++){
                   8616:       for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*/
                   8617:     
                   8618:     i1=pow(2,cptcoveff);
                   8619:     if (cptcovn < 1){i1=1;}
                   8620: 
                   8621:     for(nres=1; nres <= nresult; nres++) /* For each resultline */
                   8622:     for(k=1; k<=i1;k++){
                   8623:       if(i1 != 1 && TKresult[nres]!= k)
                   8624:        continue;
                   8625:       fprintf(ficresvpl,"\n#****** ");
                   8626:       printf("\n#****** ");
                   8627:       fprintf(ficlog,"\n#****** ");
                   8628:       for(j=1;j<=cptcoveff;j++) {
                   8629:        fprintf(ficresvpl,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   8630:        fprintf(ficlog,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   8631:        printf("V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   8632:       }
                   8633:       for (j=1; j<= nsq; j++){ /* For each selected (single) quantitative value */
                   8634:        printf(" V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]);
                   8635:        fprintf(ficresvpl," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]);
                   8636:        fprintf(ficlog," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]);
                   8637:       }        
                   8638:       fprintf(ficresvpl,"******\n");
                   8639:       printf("******\n");
                   8640:       fprintf(ficlog,"******\n");
                   8641:       
                   8642:       varpl=matrix(1,nlstate,(int) bage, (int) fage);
                   8643:       oldm=oldms;savm=savms;
                   8644:       varprevlim(fileresvpl, ficresvpl, varpl, matcov, p, delti, nlstate, stepm, (int) bage, (int) fage, oldm, savm, prlim, ftolpl, ncvyearp, k, strstart, nres);
                   8645:       free_matrix(varpl,1,nlstate,(int) bage, (int)fage);
                   8646:       /*}*/
                   8647:     }
                   8648:     
                   8649:     fclose(ficresvpl);
1.288     brouard  8650:     printf("done variance-covariance of forward period prevalence\n");fflush(stdout);
                   8651:     fprintf(ficlog,"done variance-covariance of forward period prevalence\n");fflush(ficlog);
1.269     brouard  8652: 
                   8653:  }
                   8654: /* Variance of back prevalence: varbprlim */
                   8655:  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){
                   8656:       /*------- Variance of back (stable) prevalence------*/
                   8657: 
                   8658:    char fileresvbl[FILENAMELENGTH];  
                   8659:    FILE  *ficresvbl;
                   8660: 
                   8661:    double **oldm, **savm;
                   8662:    double **varbpl; /* Variances of back prevalence limits by age */   
                   8663:    int i1, k, nres, j ;
                   8664: 
                   8665:    strcpy(fileresvbl,"VBL_");
                   8666:    strcat(fileresvbl,fileresu);
                   8667:    if((ficresvbl=fopen(fileresvbl,"w"))==NULL) {
                   8668:      printf("Problem with variance of back (stable) prevalence  resultfile: %s\n", fileresvbl);
                   8669:      exit(0);
                   8670:    }
                   8671:    printf("Computing Variance-covariance of back (stable) prevalence: file '%s' ...", fileresvbl);fflush(stdout);
                   8672:    fprintf(ficlog, "Computing Variance-covariance of back (stable) prevalence: file '%s' ...", fileresvbl);fflush(ficlog);
                   8673:    
                   8674:    
                   8675:    i1=pow(2,cptcoveff);
                   8676:    if (cptcovn < 1){i1=1;}
                   8677:    
                   8678:    for(nres=1; nres <= nresult; nres++) /* For each resultline */
                   8679:      for(k=1; k<=i1;k++){
                   8680:        if(i1 != 1 && TKresult[nres]!= k)
                   8681:         continue;
                   8682:        fprintf(ficresvbl,"\n#****** ");
                   8683:        printf("\n#****** ");
                   8684:        fprintf(ficlog,"\n#****** ");
                   8685:        for(j=1;j<=cptcoveff;j++) {
                   8686:         fprintf(ficresvbl,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   8687:         fprintf(ficlog,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   8688:         printf("V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   8689:        }
                   8690:        for (j=1; j<= nsq; j++){ /* For each selected (single) quantitative value */
                   8691:         printf(" V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]);
                   8692:         fprintf(ficresvbl," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]);
                   8693:         fprintf(ficlog," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]);
                   8694:        }
                   8695:        fprintf(ficresvbl,"******\n");
                   8696:        printf("******\n");
                   8697:        fprintf(ficlog,"******\n");
                   8698:        
                   8699:        varbpl=matrix(1,nlstate,(int) bage, (int) fage);
                   8700:        oldm=oldms;savm=savms;
                   8701:        
                   8702:        varbrevlim(fileresvbl, ficresvbl, varbpl, matcov, p, delti, nlstate, stepm, (int) bage, (int) fage, oldm, savm, bprlim, ftolpl, mobilavproj, ncvyearp, k, strstart, nres);
                   8703:        free_matrix(varbpl,1,nlstate,(int) bage, (int)fage);
                   8704:        /*}*/
                   8705:      }
                   8706:    
                   8707:    fclose(ficresvbl);
                   8708:    printf("done variance-covariance of back prevalence\n");fflush(stdout);
                   8709:    fprintf(ficlog,"done variance-covariance of back prevalence\n");fflush(ficlog);
                   8710: 
                   8711:  } /* End of varbprlim */
                   8712: 
1.126     brouard  8713: /************** Forecasting *****not tested NB*************/
1.227     brouard  8714: /* 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  8715:   
1.227     brouard  8716: /*   int cpt, stepsize, hstepm, nhstepm, j,k,c, cptcod, i,h; */
                   8717: /*   int *popage; */
                   8718: /*   double calagedatem, agelim, kk1, kk2; */
                   8719: /*   double *popeffectif,*popcount; */
                   8720: /*   double ***p3mat,***tabpop,***tabpopprev; */
                   8721: /*   /\* double ***mobaverage; *\/ */
                   8722: /*   char filerespop[FILENAMELENGTH]; */
1.126     brouard  8723: 
1.227     brouard  8724: /*   tabpop= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX); */
                   8725: /*   tabpopprev= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX); */
                   8726: /*   agelim=AGESUP; */
                   8727: /*   calagedatem=(anpyram+mpyram/12.+jpyram/365.-dateintmean)*YEARM; */
1.126     brouard  8728:   
1.227     brouard  8729: /*   prevalence(probs, ageminpar, agemax, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass); */
1.126     brouard  8730:   
                   8731:   
1.227     brouard  8732: /*   strcpy(filerespop,"POP_");  */
                   8733: /*   strcat(filerespop,fileresu); */
                   8734: /*   if((ficrespop=fopen(filerespop,"w"))==NULL) { */
                   8735: /*     printf("Problem with forecast resultfile: %s\n", filerespop); */
                   8736: /*     fprintf(ficlog,"Problem with forecast resultfile: %s\n", filerespop); */
                   8737: /*   } */
                   8738: /*   printf("Computing forecasting: result on file '%s' \n", filerespop); */
                   8739: /*   fprintf(ficlog,"Computing forecasting: result on file '%s' \n", filerespop); */
1.126     brouard  8740: 
1.227     brouard  8741: /*   if (cptcoveff==0) ncodemax[cptcoveff]=1; */
1.126     brouard  8742: 
1.227     brouard  8743: /*   /\* if (mobilav!=0) { *\/ */
                   8744: /*   /\*   mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX); *\/ */
                   8745: /*   /\*   if (movingaverage(probs, ageminpar, fage, mobaverage,mobilav)!=0){ *\/ */
                   8746: /*   /\*     fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav); *\/ */
                   8747: /*   /\*     printf(" Error in movingaverage mobilav=%d\n",mobilav); *\/ */
                   8748: /*   /\*   } *\/ */
                   8749: /*   /\* } *\/ */
1.126     brouard  8750: 
1.227     brouard  8751: /*   stepsize=(int) (stepm+YEARM-1)/YEARM; */
                   8752: /*   if (stepm<=12) stepsize=1; */
1.126     brouard  8753:   
1.227     brouard  8754: /*   agelim=AGESUP; */
1.126     brouard  8755:   
1.227     brouard  8756: /*   hstepm=1; */
                   8757: /*   hstepm=hstepm/stepm;  */
1.218     brouard  8758:        
1.227     brouard  8759: /*   if (popforecast==1) { */
                   8760: /*     if((ficpop=fopen(popfile,"r"))==NULL) { */
                   8761: /*       printf("Problem with population file : %s\n",popfile);exit(0); */
                   8762: /*       fprintf(ficlog,"Problem with population file : %s\n",popfile);exit(0); */
                   8763: /*     }  */
                   8764: /*     popage=ivector(0,AGESUP); */
                   8765: /*     popeffectif=vector(0,AGESUP); */
                   8766: /*     popcount=vector(0,AGESUP); */
1.126     brouard  8767:     
1.227     brouard  8768: /*     i=1;    */
                   8769: /*     while ((c=fscanf(ficpop,"%d %lf\n",&popage[i],&popcount[i])) != EOF) i=i+1; */
1.218     brouard  8770:     
1.227     brouard  8771: /*     imx=i; */
                   8772: /*     for (i=1; i<imx;i++) popeffectif[popage[i]]=popcount[i]; */
                   8773: /*   } */
1.218     brouard  8774:   
1.227     brouard  8775: /*   for(cptcov=1,k=0;cptcov<=i2;cptcov++){ */
                   8776: /*     for(cptcod=1;cptcod<=ncodemax[cptcoveff];cptcod++){ */
                   8777: /*       k=k+1; */
                   8778: /*       fprintf(ficrespop,"\n#******"); */
                   8779: /*       for(j=1;j<=cptcoveff;j++) { */
                   8780: /*     fprintf(ficrespop," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]); */
                   8781: /*       } */
                   8782: /*       fprintf(ficrespop,"******\n"); */
                   8783: /*       fprintf(ficrespop,"# Age"); */
                   8784: /*       for(j=1; j<=nlstate+ndeath;j++) fprintf(ficrespop," P.%d",j); */
                   8785: /*       if (popforecast==1)  fprintf(ficrespop," [Population]"); */
1.126     brouard  8786:       
1.227     brouard  8787: /*       for (cpt=0; cpt<=0;cpt++) {  */
                   8788: /*     fprintf(ficrespop,"\n\n# Forecasting at date %.lf/%.lf/%.lf ",jpyram,mpyram,anpyram+cpt);    */
1.126     brouard  8789:        
1.227     brouard  8790: /*     for (agedeb=(fage-((int)calagedatem %12/12.)); agedeb>=(ageminpar-((int)calagedatem %12)/12.); agedeb--){  */
                   8791: /*       nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm);  */
                   8792: /*       nhstepm = nhstepm/hstepm;  */
1.126     brouard  8793:          
1.227     brouard  8794: /*       p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm); */
                   8795: /*       oldm=oldms;savm=savms; */
                   8796: /*       hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);   */
1.218     brouard  8797:          
1.227     brouard  8798: /*       for (h=0; h<=nhstepm; h++){ */
                   8799: /*         if (h==(int) (calagedatem+YEARM*cpt)) { */
                   8800: /*           fprintf(ficrespop,"\n %3.f ",agedeb+h*hstepm/YEARM*stepm); */
                   8801: /*         }  */
                   8802: /*         for(j=1; j<=nlstate+ndeath;j++) { */
                   8803: /*           kk1=0.;kk2=0; */
                   8804: /*           for(i=1; i<=nlstate;i++) {               */
                   8805: /*             if (mobilav==1)  */
                   8806: /*               kk1=kk1+p3mat[i][j][h]*mobaverage[(int)agedeb+1][i][cptcod]; */
                   8807: /*             else { */
                   8808: /*               kk1=kk1+p3mat[i][j][h]*probs[(int)(agedeb+1)][i][cptcod]; */
                   8809: /*             } */
                   8810: /*           } */
                   8811: /*           if (h==(int)(calagedatem+12*cpt)){ */
                   8812: /*             tabpop[(int)(agedeb)][j][cptcod]=kk1; */
                   8813: /*             /\*fprintf(ficrespop," %.3f", kk1); */
                   8814: /*               if (popforecast==1) fprintf(ficrespop," [%.f]", kk1*popeffectif[(int)agedeb+1]);*\/ */
                   8815: /*           } */
                   8816: /*         } */
                   8817: /*         for(i=1; i<=nlstate;i++){ */
                   8818: /*           kk1=0.; */
                   8819: /*           for(j=1; j<=nlstate;j++){ */
                   8820: /*             kk1= kk1+tabpop[(int)(agedeb)][j][cptcod];  */
                   8821: /*           } */
                   8822: /*           tabpopprev[(int)(agedeb)][i][cptcod]=tabpop[(int)(agedeb)][i][cptcod]/kk1*popeffectif[(int)(agedeb+(calagedatem+12*cpt)*hstepm/YEARM*stepm-1)]; */
                   8823: /*         } */
1.218     brouard  8824:            
1.227     brouard  8825: /*         if (h==(int)(calagedatem+12*cpt)) */
                   8826: /*           for(j=1; j<=nlstate;j++)  */
                   8827: /*             fprintf(ficrespop," %15.2f",tabpopprev[(int)(agedeb+1)][j][cptcod]); */
                   8828: /*       } */
                   8829: /*       free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm); */
                   8830: /*     } */
                   8831: /*       } */
1.218     brouard  8832:       
1.227     brouard  8833: /*       /\******\/ */
1.218     brouard  8834:       
1.227     brouard  8835: /*       for (cpt=1; cpt<=(anpyram1-anpyram);cpt++) {  */
                   8836: /*     fprintf(ficrespop,"\n\n# Forecasting at date %.lf/%.lf/%.lf ",jpyram,mpyram,anpyram+cpt);    */
                   8837: /*     for (agedeb=(fage-((int)calagedatem %12/12.)); agedeb>=(ageminpar-((int)calagedatem %12)/12.); agedeb--){  */
                   8838: /*       nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm);  */
                   8839: /*       nhstepm = nhstepm/hstepm;  */
1.126     brouard  8840:          
1.227     brouard  8841: /*       p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm); */
                   8842: /*       oldm=oldms;savm=savms; */
                   8843: /*       hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);   */
                   8844: /*       for (h=0; h<=nhstepm; h++){ */
                   8845: /*         if (h==(int) (calagedatem+YEARM*cpt)) { */
                   8846: /*           fprintf(ficresf,"\n %3.f ",agedeb+h*hstepm/YEARM*stepm); */
                   8847: /*         }  */
                   8848: /*         for(j=1; j<=nlstate+ndeath;j++) { */
                   8849: /*           kk1=0.;kk2=0; */
                   8850: /*           for(i=1; i<=nlstate;i++) {               */
                   8851: /*             kk1=kk1+p3mat[i][j][h]*tabpopprev[(int)agedeb+1][i][cptcod];     */
                   8852: /*           } */
                   8853: /*           if (h==(int)(calagedatem+12*cpt)) fprintf(ficresf," %15.2f", kk1);         */
                   8854: /*         } */
                   8855: /*       } */
                   8856: /*       free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm); */
                   8857: /*     } */
                   8858: /*       } */
                   8859: /*     }  */
                   8860: /*   } */
1.218     brouard  8861:   
1.227     brouard  8862: /*   /\* if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX); *\/ */
1.218     brouard  8863:   
1.227     brouard  8864: /*   if (popforecast==1) { */
                   8865: /*     free_ivector(popage,0,AGESUP); */
                   8866: /*     free_vector(popeffectif,0,AGESUP); */
                   8867: /*     free_vector(popcount,0,AGESUP); */
                   8868: /*   } */
                   8869: /*   free_ma3x(tabpop,1, AGESUP,1,NCOVMAX, 1,NCOVMAX); */
                   8870: /*   free_ma3x(tabpopprev,1, AGESUP,1,NCOVMAX, 1,NCOVMAX); */
                   8871: /*   fclose(ficrespop); */
                   8872: /* } /\* End of popforecast *\/ */
1.218     brouard  8873:  
1.126     brouard  8874: int fileappend(FILE *fichier, char *optionfich)
                   8875: {
                   8876:   if((fichier=fopen(optionfich,"a"))==NULL) {
                   8877:     printf("Problem with file: %s\n", optionfich);
                   8878:     fprintf(ficlog,"Problem with file: %s\n", optionfich);
                   8879:     return (0);
                   8880:   }
                   8881:   fflush(fichier);
                   8882:   return (1);
                   8883: }
                   8884: 
                   8885: 
                   8886: /**************** function prwizard **********************/
                   8887: void prwizard(int ncovmodel, int nlstate, int ndeath,  char model[], FILE *ficparo)
                   8888: {
                   8889: 
                   8890:   /* Wizard to print covariance matrix template */
                   8891: 
1.164     brouard  8892:   char ca[32], cb[32];
                   8893:   int i,j, k, li, lj, lk, ll, jj, npar, itimes;
1.126     brouard  8894:   int numlinepar;
                   8895: 
                   8896:   printf("# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
                   8897:   fprintf(ficparo,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
                   8898:   for(i=1; i <=nlstate; i++){
                   8899:     jj=0;
                   8900:     for(j=1; j <=nlstate+ndeath; j++){
                   8901:       if(j==i) continue;
                   8902:       jj++;
                   8903:       /*ca[0]= k+'a'-1;ca[1]='\0';*/
                   8904:       printf("%1d%1d",i,j);
                   8905:       fprintf(ficparo,"%1d%1d",i,j);
                   8906:       for(k=1; k<=ncovmodel;k++){
                   8907:        /*        printf(" %lf",param[i][j][k]); */
                   8908:        /*        fprintf(ficparo," %lf",param[i][j][k]); */
                   8909:        printf(" 0.");
                   8910:        fprintf(ficparo," 0.");
                   8911:       }
                   8912:       printf("\n");
                   8913:       fprintf(ficparo,"\n");
                   8914:     }
                   8915:   }
                   8916:   printf("# Scales (for hessian or gradient estimation)\n");
                   8917:   fprintf(ficparo,"# Scales (for hessian or gradient estimation)\n");
                   8918:   npar= (nlstate+ndeath-1)*nlstate*ncovmodel; /* Number of parameters*/ 
                   8919:   for(i=1; i <=nlstate; i++){
                   8920:     jj=0;
                   8921:     for(j=1; j <=nlstate+ndeath; j++){
                   8922:       if(j==i) continue;
                   8923:       jj++;
                   8924:       fprintf(ficparo,"%1d%1d",i,j);
                   8925:       printf("%1d%1d",i,j);
                   8926:       fflush(stdout);
                   8927:       for(k=1; k<=ncovmodel;k++){
                   8928:        /*      printf(" %le",delti3[i][j][k]); */
                   8929:        /*      fprintf(ficparo," %le",delti3[i][j][k]); */
                   8930:        printf(" 0.");
                   8931:        fprintf(ficparo," 0.");
                   8932:       }
                   8933:       numlinepar++;
                   8934:       printf("\n");
                   8935:       fprintf(ficparo,"\n");
                   8936:     }
                   8937:   }
                   8938:   printf("# Covariance matrix\n");
                   8939: /* # 121 Var(a12)\n\ */
                   8940: /* # 122 Cov(b12,a12) Var(b12)\n\ */
                   8941: /* # 131 Cov(a13,a12) Cov(a13,b12, Var(a13)\n\ */
                   8942: /* # 132 Cov(b13,a12) Cov(b13,b12, Cov(b13,a13) Var(b13)\n\ */
                   8943: /* # 212 Cov(a21,a12) Cov(a21,b12, Cov(a21,a13) Cov(a21,b13) Var(a21)\n\ */
                   8944: /* # 212 Cov(b21,a12) Cov(b21,b12, Cov(b21,a13) Cov(b21,b13) Cov(b21,a21) Var(b21)\n\ */
                   8945: /* # 232 Cov(a23,a12) Cov(a23,b12, Cov(a23,a13) Cov(a23,b13) Cov(a23,a21) Cov(a23,b21) Var(a23)\n\ */
                   8946: /* # 232 Cov(b23,a12) Cov(b23,b12) ... Var (b23)\n" */
                   8947:   fflush(stdout);
                   8948:   fprintf(ficparo,"# Covariance matrix\n");
                   8949:   /* # 121 Var(a12)\n\ */
                   8950:   /* # 122 Cov(b12,a12) Var(b12)\n\ */
                   8951:   /* #   ...\n\ */
                   8952:   /* # 232 Cov(b23,a12)  Cov(b23,b12) ... Var (b23)\n" */
                   8953:   
                   8954:   for(itimes=1;itimes<=2;itimes++){
                   8955:     jj=0;
                   8956:     for(i=1; i <=nlstate; i++){
                   8957:       for(j=1; j <=nlstate+ndeath; j++){
                   8958:        if(j==i) continue;
                   8959:        for(k=1; k<=ncovmodel;k++){
                   8960:          jj++;
                   8961:          ca[0]= k+'a'-1;ca[1]='\0';
                   8962:          if(itimes==1){
                   8963:            printf("#%1d%1d%d",i,j,k);
                   8964:            fprintf(ficparo,"#%1d%1d%d",i,j,k);
                   8965:          }else{
                   8966:            printf("%1d%1d%d",i,j,k);
                   8967:            fprintf(ficparo,"%1d%1d%d",i,j,k);
                   8968:            /*  printf(" %.5le",matcov[i][j]); */
                   8969:          }
                   8970:          ll=0;
                   8971:          for(li=1;li <=nlstate; li++){
                   8972:            for(lj=1;lj <=nlstate+ndeath; lj++){
                   8973:              if(lj==li) continue;
                   8974:              for(lk=1;lk<=ncovmodel;lk++){
                   8975:                ll++;
                   8976:                if(ll<=jj){
                   8977:                  cb[0]= lk +'a'-1;cb[1]='\0';
                   8978:                  if(ll<jj){
                   8979:                    if(itimes==1){
                   8980:                      printf(" Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
                   8981:                      fprintf(ficparo," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
                   8982:                    }else{
                   8983:                      printf(" 0.");
                   8984:                      fprintf(ficparo," 0.");
                   8985:                    }
                   8986:                  }else{
                   8987:                    if(itimes==1){
                   8988:                      printf(" Var(%s%1d%1d)",ca,i,j);
                   8989:                      fprintf(ficparo," Var(%s%1d%1d)",ca,i,j);
                   8990:                    }else{
                   8991:                      printf(" 0.");
                   8992:                      fprintf(ficparo," 0.");
                   8993:                    }
                   8994:                  }
                   8995:                }
                   8996:              } /* end lk */
                   8997:            } /* end lj */
                   8998:          } /* end li */
                   8999:          printf("\n");
                   9000:          fprintf(ficparo,"\n");
                   9001:          numlinepar++;
                   9002:        } /* end k*/
                   9003:       } /*end j */
                   9004:     } /* end i */
                   9005:   } /* end itimes */
                   9006: 
                   9007: } /* end of prwizard */
                   9008: /******************* Gompertz Likelihood ******************************/
                   9009: double gompertz(double x[])
                   9010: { 
                   9011:   double A,B,L=0.0,sump=0.,num=0.;
                   9012:   int i,n=0; /* n is the size of the sample */
                   9013: 
1.220     brouard  9014:   for (i=1;i<=imx ; i++) {
1.126     brouard  9015:     sump=sump+weight[i];
                   9016:     /*    sump=sump+1;*/
                   9017:     num=num+1;
                   9018:   }
                   9019:  
                   9020:  
                   9021:   /* for (i=0; i<=imx; i++) 
                   9022:      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]);*/
                   9023: 
                   9024:   for (i=1;i<=imx ; i++)
                   9025:     {
                   9026:       if (cens[i] == 1 && wav[i]>1)
                   9027:        A=-x[1]/(x[2])*(exp(x[2]*(agecens[i]-agegomp))-exp(x[2]*(ageexmed[i]-agegomp)));
                   9028:       
                   9029:       if (cens[i] == 0 && wav[i]>1)
                   9030:        A=-x[1]/(x[2])*(exp(x[2]*(agedc[i]-agegomp))-exp(x[2]*(ageexmed[i]-agegomp)))
                   9031:             +log(x[1]/YEARM)+x[2]*(agedc[i]-agegomp)+log(YEARM);  
                   9032:       
                   9033:       /*if (wav[i] > 1 && agecens[i] > 15) {*/ /* ??? */
                   9034:       if (wav[i] > 1 ) { /* ??? */
                   9035:        L=L+A*weight[i];
                   9036:        /*      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]);*/
                   9037:       }
                   9038:     }
                   9039: 
                   9040:  /*printf("x1=%2.9f x2=%2.9f x3=%2.9f L=%f\n",x[1],x[2],x[3],L);*/
                   9041:  
                   9042:   return -2*L*num/sump;
                   9043: }
                   9044: 
1.136     brouard  9045: #ifdef GSL
                   9046: /******************* Gompertz_f Likelihood ******************************/
                   9047: double gompertz_f(const gsl_vector *v, void *params)
                   9048: { 
                   9049:   double A,B,LL=0.0,sump=0.,num=0.;
                   9050:   double *x= (double *) v->data;
                   9051:   int i,n=0; /* n is the size of the sample */
                   9052: 
                   9053:   for (i=0;i<=imx-1 ; i++) {
                   9054:     sump=sump+weight[i];
                   9055:     /*    sump=sump+1;*/
                   9056:     num=num+1;
                   9057:   }
                   9058:  
                   9059:  
                   9060:   /* for (i=0; i<=imx; i++) 
                   9061:      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]);*/
                   9062:   printf("x[0]=%lf x[1]=%lf\n",x[0],x[1]);
                   9063:   for (i=1;i<=imx ; i++)
                   9064:     {
                   9065:       if (cens[i] == 1 && wav[i]>1)
                   9066:        A=-x[0]/(x[1])*(exp(x[1]*(agecens[i]-agegomp))-exp(x[1]*(ageexmed[i]-agegomp)));
                   9067:       
                   9068:       if (cens[i] == 0 && wav[i]>1)
                   9069:        A=-x[0]/(x[1])*(exp(x[1]*(agedc[i]-agegomp))-exp(x[1]*(ageexmed[i]-agegomp)))
                   9070:             +log(x[0]/YEARM)+x[1]*(agedc[i]-agegomp)+log(YEARM);  
                   9071:       
                   9072:       /*if (wav[i] > 1 && agecens[i] > 15) {*/ /* ??? */
                   9073:       if (wav[i] > 1 ) { /* ??? */
                   9074:        LL=LL+A*weight[i];
                   9075:        /*      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]);*/
                   9076:       }
                   9077:     }
                   9078: 
                   9079:  /*printf("x1=%2.9f x2=%2.9f x3=%2.9f L=%f\n",x[1],x[2],x[3],L);*/
                   9080:   printf("x[0]=%lf x[1]=%lf -2*LL*num/sump=%lf\n",x[0],x[1],-2*LL*num/sump);
                   9081:  
                   9082:   return -2*LL*num/sump;
                   9083: }
                   9084: #endif
                   9085: 
1.126     brouard  9086: /******************* Printing html file ***********/
1.201     brouard  9087: void printinghtmlmort(char fileresu[], char title[], char datafile[], int firstpass, \
1.126     brouard  9088:                  int lastpass, int stepm, int weightopt, char model[],\
                   9089:                  int imx,  double p[],double **matcov,double agemortsup){
                   9090:   int i,k;
                   9091: 
                   9092:   fprintf(fichtm,"<ul><li><h4>Result files </h4>\n Force of mortality. Parameters of the Gompertz fit (with confidence interval in brackets):<br>");
                   9093:   fprintf(fichtm,"  mu(age) =%lf*exp(%lf*(age-%d)) per year<br><br>",p[1],p[2],agegomp);
                   9094:   for (i=1;i<=2;i++) 
                   9095:     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  9096:   fprintf(fichtm,"<br><br><img src=\"graphmort.svg\">");
1.126     brouard  9097:   fprintf(fichtm,"</ul>");
                   9098: 
                   9099: fprintf(fichtm,"<ul><li><h4>Life table</h4>\n <br>");
                   9100: 
                   9101:  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>");
                   9102: 
                   9103:  for (k=agegomp;k<(agemortsup-2);k++) 
                   9104:    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]);
                   9105: 
                   9106:  
                   9107:   fflush(fichtm);
                   9108: }
                   9109: 
                   9110: /******************* Gnuplot file **************/
1.201     brouard  9111: void printinggnuplotmort(char fileresu[], char optionfilefiname[], double ageminpar, double agemaxpar, double fage , char pathc[], double p[]){
1.126     brouard  9112: 
                   9113:   char dirfileres[132],optfileres[132];
1.164     brouard  9114: 
1.126     brouard  9115:   int ng;
                   9116: 
                   9117: 
                   9118:   /*#ifdef windows */
                   9119:   fprintf(ficgp,"cd \"%s\" \n",pathc);
                   9120:     /*#endif */
                   9121: 
                   9122: 
                   9123:   strcpy(dirfileres,optionfilefiname);
                   9124:   strcpy(optfileres,"vpl");
1.199     brouard  9125:   fprintf(ficgp,"set out \"graphmort.svg\"\n "); 
1.126     brouard  9126:   fprintf(ficgp,"set xlabel \"Age\"\n set ylabel \"Force of mortality (per year)\" \n "); 
1.199     brouard  9127:   fprintf(ficgp, "set ter svg size 640, 480\n set log y\n"); 
1.145     brouard  9128:   /* fprintf(ficgp, "set size 0.65,0.65\n"); */
1.126     brouard  9129:   fprintf(ficgp,"plot [%d:100] %lf*exp(%lf*(x-%d))",agegomp,p[1],p[2],agegomp);
                   9130: 
                   9131: } 
                   9132: 
1.136     brouard  9133: int readdata(char datafile[], int firstobs, int lastobs, int *imax)
                   9134: {
1.126     brouard  9135: 
1.136     brouard  9136:   /*-------- data file ----------*/
                   9137:   FILE *fic;
                   9138:   char dummy[]="                         ";
1.240     brouard  9139:   int i=0, j=0, n=0, iv=0, v;
1.223     brouard  9140:   int lstra;
1.136     brouard  9141:   int linei, month, year,iout;
                   9142:   char line[MAXLINE], linetmp[MAXLINE];
1.164     brouard  9143:   char stra[MAXLINE], strb[MAXLINE];
1.136     brouard  9144:   char *stratrunc;
1.223     brouard  9145: 
1.240     brouard  9146:   DummyV=ivector(1,NCOVMAX); /* 1 to 3 */
                   9147:   FixedV=ivector(1,NCOVMAX); /* 1 to 3 */
1.126     brouard  9148: 
1.240     brouard  9149:   for(v=1; v <=ncovcol;v++){
                   9150:     DummyV[v]=0;
                   9151:     FixedV[v]=0;
                   9152:   }
                   9153:   for(v=ncovcol+1; v <=ncovcol+nqv;v++){
                   9154:     DummyV[v]=1;
                   9155:     FixedV[v]=0;
                   9156:   }
                   9157:   for(v=ncovcol+nqv+1; v <=ncovcol+nqv+ntv;v++){
                   9158:     DummyV[v]=0;
                   9159:     FixedV[v]=1;
                   9160:   }
                   9161:   for(v=ncovcol+nqv+ntv+1; v <=ncovcol+nqv+ntv+nqtv;v++){
                   9162:     DummyV[v]=1;
                   9163:     FixedV[v]=1;
                   9164:   }
                   9165:   for(v=1; v <=ncovcol+nqv+ntv+nqtv;v++){
                   9166:     printf("Covariate type in the data: V%d, DummyV(V%d)=%d, FixedV(V%d)=%d\n",v,v,DummyV[v],v,FixedV[v]);
                   9167:     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]);
                   9168:   }
1.126     brouard  9169: 
1.136     brouard  9170:   if((fic=fopen(datafile,"r"))==NULL)    {
1.218     brouard  9171:     printf("Problem while opening datafile: %s with errno='%s'\n", datafile,strerror(errno));fflush(stdout);
                   9172:     fprintf(ficlog,"Problem while opening datafile: %s with errno='%s'\n", datafile,strerror(errno));fflush(ficlog);return 1;
1.136     brouard  9173:   }
1.126     brouard  9174: 
1.136     brouard  9175:   i=1;
                   9176:   linei=0;
                   9177:   while ((fgets(line, MAXLINE, fic) != NULL) &&((i >= firstobs) && (i <=lastobs))) {
                   9178:     linei=linei+1;
                   9179:     for(j=strlen(line); j>=0;j--){  /* Untabifies line */
                   9180:       if(line[j] == '\t')
                   9181:        line[j] = ' ';
                   9182:     }
                   9183:     for(j=strlen(line)-1; (line[j]==' ')||(line[j]==10)||(line[j]==13);j--){
                   9184:       ;
                   9185:     };
                   9186:     line[j+1]=0;  /* Trims blanks at end of line */
                   9187:     if(line[0]=='#'){
                   9188:       fprintf(ficlog,"Comment line\n%s\n",line);
                   9189:       printf("Comment line\n%s\n",line);
                   9190:       continue;
                   9191:     }
                   9192:     trimbb(linetmp,line); /* Trims multiple blanks in line */
1.164     brouard  9193:     strcpy(line, linetmp);
1.223     brouard  9194:     
                   9195:     /* Loops on waves */
                   9196:     for (j=maxwav;j>=1;j--){
                   9197:       for (iv=nqtv;iv>=1;iv--){  /* Loop  on time varying quantitative variables */
1.238     brouard  9198:        cutv(stra, strb, line, ' '); 
                   9199:        if(strb[0]=='.') { /* Missing value */
                   9200:          lval=-1;
                   9201:          cotqvar[j][iv][i]=-1; /* 0.0/0.0 */
                   9202:          cotvar[j][ntv+iv][i]=-1; /* For performance reasons */
                   9203:          if(isalpha(strb[1])) { /* .m or .d Really Missing value */
                   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. If missing, you should remove this individual or impute a value.  Exiting.\n", strb, linei,i,line,iv, nqtv, j);
                   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. If missing, you should remove this individual or impute a value.  Exiting.\n", strb, linei,i,line,iv, nqtv, j);fflush(ficlog);
                   9206:            return 1;
                   9207:          }
                   9208:        }else{
                   9209:          errno=0;
                   9210:          /* what_kind_of_number(strb); */
                   9211:          dval=strtod(strb,&endptr); 
                   9212:          /* if( strb[0]=='\0' || (*endptr != '\0')){ */
                   9213:          /* if(strb != endptr && *endptr == '\0') */
                   9214:          /*    dval=dlval; */
                   9215:          /* if (errno == ERANGE && (lval == LONG_MAX || lval == LONG_MIN)) */
                   9216:          if( strb[0]=='\0' || (*endptr != '\0')){
                   9217:            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);
                   9218:            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);
                   9219:            return 1;
                   9220:          }
                   9221:          cotqvar[j][iv][i]=dval; 
                   9222:          cotvar[j][ntv+iv][i]=dval; 
                   9223:        }
                   9224:        strcpy(line,stra);
1.223     brouard  9225:       }/* end loop ntqv */
1.225     brouard  9226:       
1.223     brouard  9227:       for (iv=ntv;iv>=1;iv--){  /* Loop  on time varying dummies */
1.238     brouard  9228:        cutv(stra, strb, line, ' '); 
                   9229:        if(strb[0]=='.') { /* Missing value */
                   9230:          lval=-1;
                   9231:        }else{
                   9232:          errno=0;
                   9233:          lval=strtol(strb,&endptr,10); 
                   9234:          /*    if (errno == ERANGE && (lval == LONG_MAX || lval == LONG_MIN))*/
                   9235:          if( strb[0]=='\0' || (*endptr != '\0')){
                   9236:            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);
                   9237:            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);
                   9238:            return 1;
                   9239:          }
                   9240:        }
                   9241:        if(lval <-1 || lval >1){
                   9242:          printf("Error reading data around '%ld' at line number %d for individual %d, '%s'\n \
1.223     brouard  9243:  Should be a value of %d(nth) covariate (0 should be the value for the reference and 1\n \
                   9244:  for the alternative. IMaCh does not build design variables automatically, do it yourself.\n \
1.238     brouard  9245:  For example, for multinomial values like 1, 2 and 3,\n                        \
                   9246:  build V1=0 V2=0 for the reference value (1),\n                                \
                   9247:         V1=1 V2=0 for (2) \n                                           \
1.223     brouard  9248:  and V1=0 V2=1 for (3). V1=1 V2=1 should not exist and the corresponding\n \
1.238     brouard  9249:  output of IMaCh is often meaningless.\n                               \
1.223     brouard  9250:  Exiting.\n",lval,linei, i,line,j);
1.238     brouard  9251:          fprintf(ficlog,"Error reading data around '%ld' at line number %d for individual %d, '%s'\n \
1.223     brouard  9252:  Should be a value of %d(nth) covariate (0 should be the value for the reference and 1\n \
                   9253:  for the alternative. IMaCh does not build design variables automatically, do it yourself.\n \
1.238     brouard  9254:  For example, for multinomial values like 1, 2 and 3,\n                        \
                   9255:  build V1=0 V2=0 for the reference value (1),\n                                \
                   9256:         V1=1 V2=0 for (2) \n                                           \
1.223     brouard  9257:  and V1=0 V2=1 for (3). V1=1 V2=1 should not exist and the corresponding\n \
1.238     brouard  9258:  output of IMaCh is often meaningless.\n                               \
1.223     brouard  9259:  Exiting.\n",lval,linei, i,line,j);fflush(ficlog);
1.238     brouard  9260:          return 1;
                   9261:        }
                   9262:        cotvar[j][iv][i]=(double)(lval);
                   9263:        strcpy(line,stra);
1.223     brouard  9264:       }/* end loop ntv */
1.225     brouard  9265:       
1.223     brouard  9266:       /* Statuses  at wave */
1.137     brouard  9267:       cutv(stra, strb, line, ' '); 
1.223     brouard  9268:       if(strb[0]=='.') { /* Missing value */
1.238     brouard  9269:        lval=-1;
1.136     brouard  9270:       }else{
1.238     brouard  9271:        errno=0;
                   9272:        lval=strtol(strb,&endptr,10); 
                   9273:        /*      if (errno == ERANGE && (lval == LONG_MAX || lval == LONG_MIN))*/
                   9274:        if( strb[0]=='\0' || (*endptr != '\0')){
                   9275:          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);
                   9276:          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);
                   9277:          return 1;
                   9278:        }
1.136     brouard  9279:       }
1.225     brouard  9280:       
1.136     brouard  9281:       s[j][i]=lval;
1.225     brouard  9282:       
1.223     brouard  9283:       /* Date of Interview */
1.136     brouard  9284:       strcpy(line,stra);
                   9285:       cutv(stra, strb,line,' ');
1.169     brouard  9286:       if( (iout=sscanf(strb,"%d/%d",&month, &year)) != 0){
1.136     brouard  9287:       }
1.169     brouard  9288:       else  if( (iout=sscanf(strb,"%s.",dummy)) != 0){
1.225     brouard  9289:        month=99;
                   9290:        year=9999;
1.136     brouard  9291:       }else{
1.225     brouard  9292:        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);
                   9293:        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);
                   9294:        return 1;
1.136     brouard  9295:       }
                   9296:       anint[j][i]= (double) year; 
                   9297:       mint[j][i]= (double)month; 
                   9298:       strcpy(line,stra);
1.223     brouard  9299:     } /* End loop on waves */
1.225     brouard  9300:     
1.223     brouard  9301:     /* Date of death */
1.136     brouard  9302:     cutv(stra, strb,line,' '); 
1.169     brouard  9303:     if( (iout=sscanf(strb,"%d/%d",&month, &year)) != 0){
1.136     brouard  9304:     }
1.169     brouard  9305:     else  if( (iout=sscanf(strb,"%s.",dummy)) != 0){
1.136     brouard  9306:       month=99;
                   9307:       year=9999;
                   9308:     }else{
1.141     brouard  9309:       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  9310:       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);
                   9311:       return 1;
1.136     brouard  9312:     }
                   9313:     andc[i]=(double) year; 
                   9314:     moisdc[i]=(double) month; 
                   9315:     strcpy(line,stra);
                   9316:     
1.223     brouard  9317:     /* Date of birth */
1.136     brouard  9318:     cutv(stra, strb,line,' '); 
1.169     brouard  9319:     if( (iout=sscanf(strb,"%d/%d",&month, &year)) != 0){
1.136     brouard  9320:     }
1.169     brouard  9321:     else  if( (iout=sscanf(strb,"%s.", dummy)) != 0){
1.136     brouard  9322:       month=99;
                   9323:       year=9999;
                   9324:     }else{
1.141     brouard  9325:       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);
                   9326:       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  9327:       return 1;
1.136     brouard  9328:     }
                   9329:     if (year==9999) {
1.141     brouard  9330:       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);
                   9331:       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  9332:       return 1;
                   9333:       
1.136     brouard  9334:     }
                   9335:     annais[i]=(double)(year);
                   9336:     moisnais[i]=(double)(month); 
                   9337:     strcpy(line,stra);
1.225     brouard  9338:     
1.223     brouard  9339:     /* Sample weight */
1.136     brouard  9340:     cutv(stra, strb,line,' '); 
                   9341:     errno=0;
                   9342:     dval=strtod(strb,&endptr); 
                   9343:     if( strb[0]=='\0' || (*endptr != '\0')){
1.141     brouard  9344:       printf("Error reading data around '%f' at line number %d, \"%s\" for individual %d\nShould be a weight.  Exiting.\n",dval, i,line,linei);
                   9345:       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  9346:       fflush(ficlog);
                   9347:       return 1;
                   9348:     }
                   9349:     weight[i]=dval; 
                   9350:     strcpy(line,stra);
1.225     brouard  9351:     
1.223     brouard  9352:     for (iv=nqv;iv>=1;iv--){  /* Loop  on fixed quantitative variables */
                   9353:       cutv(stra, strb, line, ' '); 
                   9354:       if(strb[0]=='.') { /* Missing value */
1.225     brouard  9355:        lval=-1;
1.223     brouard  9356:       }else{
1.225     brouard  9357:        errno=0;
                   9358:        /* what_kind_of_number(strb); */
                   9359:        dval=strtod(strb,&endptr);
                   9360:        /* if(strb != endptr && *endptr == '\0') */
                   9361:        /*   dval=dlval; */
                   9362:        /* if (errno == ERANGE && (lval == LONG_MAX || lval == LONG_MIN)) */
                   9363:        if( strb[0]=='\0' || (*endptr != '\0')){
                   9364:          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);
                   9365:          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);
                   9366:          return 1;
                   9367:        }
                   9368:        coqvar[iv][i]=dval; 
1.226     brouard  9369:        covar[ncovcol+iv][i]=dval; /* including qvar in standard covar for performance reasons */ 
1.223     brouard  9370:       }
                   9371:       strcpy(line,stra);
                   9372:     }/* end loop nqv */
1.136     brouard  9373:     
1.223     brouard  9374:     /* Covariate values */
1.136     brouard  9375:     for (j=ncovcol;j>=1;j--){
                   9376:       cutv(stra, strb,line,' '); 
1.223     brouard  9377:       if(strb[0]=='.') { /* Missing covariate value */
1.225     brouard  9378:        lval=-1;
1.136     brouard  9379:       }else{
1.225     brouard  9380:        errno=0;
                   9381:        lval=strtol(strb,&endptr,10); 
                   9382:        if( strb[0]=='\0' || (*endptr != '\0')){
                   9383:          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);
                   9384:          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);
                   9385:          return 1;
                   9386:        }
1.136     brouard  9387:       }
                   9388:       if(lval <-1 || lval >1){
1.225     brouard  9389:        printf("Error reading data around '%ld' at line number %d for individual %d, '%s'\n \
1.136     brouard  9390:  Should be a value of %d(nth) covariate (0 should be the value for the reference and 1\n \
                   9391:  for the alternative. IMaCh does not build design variables automatically, do it yourself.\n \
1.225     brouard  9392:  For example, for multinomial values like 1, 2 and 3,\n                        \
                   9393:  build V1=0 V2=0 for the reference value (1),\n                                \
                   9394:         V1=1 V2=0 for (2) \n                                           \
1.136     brouard  9395:  and V1=0 V2=1 for (3). V1=1 V2=1 should not exist and the corresponding\n \
1.225     brouard  9396:  output of IMaCh is often meaningless.\n                               \
1.136     brouard  9397:  Exiting.\n",lval,linei, i,line,j);
1.225     brouard  9398:        fprintf(ficlog,"Error reading data around '%ld' at line number %d for individual %d, '%s'\n \
1.136     brouard  9399:  Should be a value of %d(nth) covariate (0 should be the value for the reference and 1\n \
                   9400:  for the alternative. IMaCh does not build design variables automatically, do it yourself.\n \
1.225     brouard  9401:  For example, for multinomial values like 1, 2 and 3,\n                        \
                   9402:  build V1=0 V2=0 for the reference value (1),\n                                \
                   9403:         V1=1 V2=0 for (2) \n                                           \
1.136     brouard  9404:  and V1=0 V2=1 for (3). V1=1 V2=1 should not exist and the corresponding\n \
1.225     brouard  9405:  output of IMaCh is often meaningless.\n                               \
1.136     brouard  9406:  Exiting.\n",lval,linei, i,line,j);fflush(ficlog);
1.225     brouard  9407:        return 1;
1.136     brouard  9408:       }
                   9409:       covar[j][i]=(double)(lval);
                   9410:       strcpy(line,stra);
                   9411:     }  
                   9412:     lstra=strlen(stra);
1.225     brouard  9413:     
1.136     brouard  9414:     if(lstra > 9){ /* More than 2**32 or max of what printf can write with %ld */
                   9415:       stratrunc = &(stra[lstra-9]);
                   9416:       num[i]=atol(stratrunc);
                   9417:     }
                   9418:     else
                   9419:       num[i]=atol(stra);
                   9420:     /*if((s[2][i]==2) && (s[3][i]==-1)&&(s[4][i]==9)){
                   9421:       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;}*/
                   9422:     
                   9423:     i=i+1;
                   9424:   } /* End loop reading  data */
1.225     brouard  9425:   
1.136     brouard  9426:   *imax=i-1; /* Number of individuals */
                   9427:   fclose(fic);
1.225     brouard  9428:   
1.136     brouard  9429:   return (0);
1.164     brouard  9430:   /* endread: */
1.225     brouard  9431:   printf("Exiting readdata: ");
                   9432:   fclose(fic);
                   9433:   return (1);
1.223     brouard  9434: }
1.126     brouard  9435: 
1.234     brouard  9436: void removefirstspace(char **stri){/*, char stro[]) {*/
1.230     brouard  9437:   char *p1 = *stri, *p2 = *stri;
1.235     brouard  9438:   while (*p2 == ' ')
1.234     brouard  9439:     p2++; 
                   9440:   /* while ((*p1++ = *p2++) !=0) */
                   9441:   /*   ; */
                   9442:   /* do */
                   9443:   /*   while (*p2 == ' ') */
                   9444:   /*     p2++; */
                   9445:   /* while (*p1++ == *p2++); */
                   9446:   *stri=p2; 
1.145     brouard  9447: }
                   9448: 
1.235     brouard  9449: int decoderesult ( char resultline[], int nres)
1.230     brouard  9450: /**< This routine decode one result line and returns the combination # of dummy covariates only **/
                   9451: {
1.235     brouard  9452:   int j=0, k=0, k1=0, k2=0, k3=0, k4=0, match=0, k2q=0, k3q=0, k4q=0;
1.230     brouard  9453:   char resultsav[MAXLINE];
1.234     brouard  9454:   int resultmodel[MAXLINE];
                   9455:   int modelresult[MAXLINE];
1.230     brouard  9456:   char stra[80], strb[80], strc[80], strd[80],stre[80];
                   9457: 
1.234     brouard  9458:   removefirstspace(&resultline);
1.233     brouard  9459:   printf("decoderesult:%s\n",resultline);
1.230     brouard  9460: 
                   9461:   if (strstr(resultline,"v") !=0){
                   9462:     printf("Error. 'v' must be in upper case 'V' result: %s ",resultline);
                   9463:     fprintf(ficlog,"Error. 'v' must be in upper case result: %s ",resultline);fflush(ficlog);
                   9464:     return 1;
                   9465:   }
                   9466:   trimbb(resultsav, resultline);
                   9467:   if (strlen(resultsav) >1){
                   9468:     j=nbocc(resultsav,'='); /**< j=Number of covariate values'=' */
                   9469:   }
1.253     brouard  9470:   if(j == 0){ /* Resultline but no = */
                   9471:     TKresult[nres]=0; /* Combination for the nresult and the model */
                   9472:     return (0);
                   9473:   }
                   9474:     
1.234     brouard  9475:   if( j != cptcovs ){ /* Be careful if a variable is in a product but not single */
                   9476:     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);
                   9477:     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);
                   9478:   }
                   9479:   for(k=1; k<=j;k++){ /* Loop on any covariate of the result line */
                   9480:     if(nbocc(resultsav,'=') >1){
                   9481:        cutl(stra,strb,resultsav,' '); /* keeps in strb after the first ' ' 
                   9482:                                      resultsav= V4=1 V5=25.1 V3=0 strb=V3=0 stra= V4=1 V5=25.1 */
                   9483:        cutl(strc,strd,strb,'=');  /* strb:V4=1 strc=1 strd=V4 */
                   9484:     }else
                   9485:       cutl(strc,strd,resultsav,'=');
1.230     brouard  9486:     Tvalsel[k]=atof(strc); /* 1 */
1.234     brouard  9487:     
1.230     brouard  9488:     cutl(strc,stre,strd,'V'); /* strd='V4' strc=4 stre='V' */;
                   9489:     Tvarsel[k]=atoi(strc);
                   9490:     /* Typevarsel[k]=1;  /\* 1 for age product *\/ */
                   9491:     /* cptcovsel++;     */
                   9492:     if (nbocc(stra,'=') >0)
                   9493:       strcpy(resultsav,stra); /* and analyzes it */
                   9494:   }
1.235     brouard  9495:   /* Checking for missing or useless values in comparison of current model needs */
1.236     brouard  9496:   for(k1=1; k1<= cptcovt ;k1++){ /* model line V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
                   9497:     if(Typevar[k1]==0){ /* Single covariate in model */
1.234     brouard  9498:       match=0;
1.236     brouard  9499:       for(k2=1; k2 <=j;k2++){/* result line V4=1 V5=24.1 V3=1  V2=8 V1=0 */
1.237     brouard  9500:        if(Tvar[k1]==Tvarsel[k2]) {/* Tvar[1]=5 == Tvarsel[2]=5   */
1.236     brouard  9501:          modelresult[k2]=k1;/* modelresult[2]=1 modelresult[1]=2  modelresult[3]=3  modelresult[6]=4 modelresult[9]=5 */
1.234     brouard  9502:          match=1;
                   9503:          break;
                   9504:        }
                   9505:       }
                   9506:       if(match == 0){
                   9507:        printf("Error in result line: %d value missing; result: %s, model=%s\n",k1, resultline, model);
                   9508:       }
                   9509:     }
                   9510:   }
1.235     brouard  9511:   /* Checking for missing or useless values in comparison of current model needs */
                   9512:   for(k2=1; k2 <=j;k2++){ /* result line V4=1 V5=24.1 V3=1  V2=8 V1=0 */
1.234     brouard  9513:     match=0;
1.235     brouard  9514:     for(k1=1; k1<= cptcovt ;k1++){ /* model line V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
                   9515:       if(Typevar[k1]==0){ /* Single */
1.237     brouard  9516:        if(Tvar[k1]==Tvarsel[k2]) { /* Tvar[2]=4 == Tvarsel[1]=4   */
1.235     brouard  9517:          resultmodel[k1]=k2;  /* resultmodel[2]=1 resultmodel[1]=2  resultmodel[3]=3  resultmodel[6]=4 resultmodel[9]=5 */
1.234     brouard  9518:          ++match;
                   9519:        }
                   9520:       }
                   9521:     }
                   9522:     if(match == 0){
                   9523:       printf("Error in result line: %d value missing; result: %s, model=%s\n",k1, resultline, model);
                   9524:     }else if(match > 1){
                   9525:       printf("Error in result line: %d doubled; result: %s, model=%s\n",k2, resultline, model);
                   9526:     }
                   9527:   }
1.235     brouard  9528:       
1.234     brouard  9529:   /* We need to deduce which combination number is chosen and save quantitative values */
1.235     brouard  9530:   /* model line V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
                   9531:   /* result line V4=1 V5=25.1 V3=0  V2=8 V1=1 */
                   9532:   /* should give a combination of dummy V4=1, V3=0, V1=1 => V4*2**(0) + V3*2**(1) + V1*2**(2) = 5 + (1offset) = 6*/
                   9533:   /* result line V4=1 V5=24.1 V3=1  V2=8 V1=0 */
                   9534:   /* should give a combination of dummy V4=1, V3=1, V1=0 => V4*2**(0) + V3*2**(1) + V1*2**(2) = 3 + (1offset) = 4*/
                   9535:   /*    1 0 0 0 */
                   9536:   /*    2 1 0 0 */
                   9537:   /*    3 0 1 0 */ 
                   9538:   /*    4 1 1 0 */ /* V4=1, V3=1, V1=0 */
                   9539:   /*    5 0 0 1 */
                   9540:   /*    6 1 0 1 */ /* V4=1, V3=0, V1=1 */
                   9541:   /*    7 0 1 1 */
                   9542:   /*    8 1 1 1 */
1.237     brouard  9543:   /* V(Tvresult)=Tresult V4=1 V3=0 V1=1 Tresult[nres=1][2]=0 */
                   9544:   /* V(Tvqresult)=Tqresult V5=25.1 V2=8 Tqresult[nres=1][1]=25.1 */
                   9545:   /* V5*age V5 known which value for nres?  */
                   9546:   /* Tqinvresult[2]=8 Tqinvresult[1]=25.1  */
1.235     brouard  9547:   for(k1=1, k=0, k4=0, k4q=0; k1 <=cptcovt;k1++){ /* model line */
                   9548:     if( Dummy[k1]==0 && Typevar[k1]==0 ){ /* Single dummy */
1.237     brouard  9549:       k3= resultmodel[k1]; /* resultmodel[2(V4)] = 1=k3 */
1.235     brouard  9550:       k2=(int)Tvarsel[k3]; /*  Tvarsel[resultmodel[2]]= Tvarsel[1] = 4=k2 */
                   9551:       k+=Tvalsel[k3]*pow(2,k4);  /*  Tvalsel[1]=1  */
1.237     brouard  9552:       Tresult[nres][k4+1]=Tvalsel[k3];/* Tresult[nres][1]=1(V4=1)  Tresult[nres][2]=0(V3=0) */
                   9553:       Tvresult[nres][k4+1]=(int)Tvarsel[k3];/* Tvresult[nres][1]=4 Tvresult[nres][3]=1 */
                   9554:       Tinvresult[nres][(int)Tvarsel[k3]]=Tvalsel[k3]; /* Tinvresult[nres][4]=1 */
1.235     brouard  9555:       printf("Decoderesult Dummy k=%d, V(k2=V%d)= Tvalsel[%d]=%d, 2**(%d)\n",k, k2, k3, (int)Tvalsel[k3], k4);
                   9556:       k4++;;
                   9557:     }  else if( Dummy[k1]==1 && Typevar[k1]==0 ){ /* Single quantitative */
                   9558:       k3q= resultmodel[k1]; /* resultmodel[2] = 1=k3 */
                   9559:       k2q=(int)Tvarsel[k3q]; /*  Tvarsel[resultmodel[2]]= Tvarsel[1] = 4=k2 */
1.237     brouard  9560:       Tqresult[nres][k4q+1]=Tvalsel[k3q]; /* Tqresult[nres][1]=25.1 */
                   9561:       Tvqresult[nres][k4q+1]=(int)Tvarsel[k3q]; /* Tvqresult[nres][1]=5 */
                   9562:       Tqinvresult[nres][(int)Tvarsel[k3q]]=Tvalsel[k3q]; /* Tqinvresult[nres][5]=25.1 */
1.235     brouard  9563:       printf("Decoderesult Quantitative nres=%d, V(k2q=V%d)= Tvalsel[%d]=%d, Tvarsel[%d]=%f\n",nres, k2q, k3q, Tvarsel[k3q], k3q, Tvalsel[k3q]);
                   9564:       k4q++;;
                   9565:     }
                   9566:   }
1.234     brouard  9567:   
1.235     brouard  9568:   TKresult[nres]=++k; /* Combination for the nresult and the model */
1.230     brouard  9569:   return (0);
                   9570: }
1.235     brouard  9571: 
1.230     brouard  9572: int decodemodel( char model[], int lastobs)
                   9573:  /**< This routine decodes the model and returns:
1.224     brouard  9574:        * Model  V1+V2+V3+V8+V7*V8+V5*V6+V8*age+V3*age+age*age
                   9575:        * - nagesqr = 1 if age*age in the model, otherwise 0.
                   9576:        * - cptcovt total number of covariates of the model nbocc(+)+1 = 8 excepting constant and age and age*age
                   9577:        * - cptcovn or number of covariates k of the models excluding age*products =6 and age*age
                   9578:        * - cptcovage number of covariates with age*products =2
                   9579:        * - cptcovs number of simple covariates
                   9580:        * - 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
                   9581:        *     which is a new column after the 9 (ncovcol) variables. 
                   9582:        * - if k is a product Vn*Vm covar[k][i] is filled with correct values for each individual
                   9583:        * - Tprod[l] gives the kth covariates of the product Vn*Vm l=1 to cptcovprod-cptcovage
                   9584:        *    Tprod[1]@2 {5, 6}: position of first product V7*V8 is 5, and second V5*V6 is 6.
                   9585:        * - Tvard[k]  p Tvard[1][1]@4 {7, 8, 5, 6} for V7*V8 and V5*V6 .
                   9586:        */
1.136     brouard  9587: {
1.238     brouard  9588:   int i, j, k, ks, v;
1.227     brouard  9589:   int  j1, k1, k2, k3, k4;
1.136     brouard  9590:   char modelsav[80];
1.145     brouard  9591:   char stra[80], strb[80], strc[80], strd[80],stre[80];
1.187     brouard  9592:   char *strpt;
1.136     brouard  9593: 
1.145     brouard  9594:   /*removespace(model);*/
1.136     brouard  9595:   if (strlen(model) >1){ /* If there is at least 1 covariate */
1.145     brouard  9596:     j=0, j1=0, k1=0, k2=-1, ks=0, cptcovn=0;
1.137     brouard  9597:     if (strstr(model,"AGE") !=0){
1.192     brouard  9598:       printf("Error. AGE must be in lower case 'age' model=1+age+%s. ",model);
                   9599:       fprintf(ficlog,"Error. AGE must be in lower case model=1+age+%s. ",model);fflush(ficlog);
1.136     brouard  9600:       return 1;
                   9601:     }
1.141     brouard  9602:     if (strstr(model,"v") !=0){
                   9603:       printf("Error. 'v' must be in upper case 'V' model=%s ",model);
                   9604:       fprintf(ficlog,"Error. 'v' must be in upper case model=%s ",model);fflush(ficlog);
                   9605:       return 1;
                   9606:     }
1.187     brouard  9607:     strcpy(modelsav,model); 
                   9608:     if ((strpt=strstr(model,"age*age")) !=0){
                   9609:       printf(" strpt=%s, model=%s\n",strpt, model);
                   9610:       if(strpt != model){
1.234     brouard  9611:        printf("Error in model: 'model=%s'; 'age*age' should in first place before other covariates\n \
1.192     brouard  9612:  'model=1+age+age*age+V1.' or 'model=1+age+age*age+V1+V1*age.', please swap as well as \n \
1.187     brouard  9613:  corresponding column of parameters.\n",model);
1.234     brouard  9614:        fprintf(ficlog,"Error in model: 'model=%s'; 'age*age' should in first place before other covariates\n \
1.192     brouard  9615:  'model=1+age+age*age+V1.' or 'model=1+age+age*age+V1+V1*age.', please swap as well as \n \
1.187     brouard  9616:  corresponding column of parameters.\n",model); fflush(ficlog);
1.234     brouard  9617:        return 1;
1.225     brouard  9618:       }
1.187     brouard  9619:       nagesqr=1;
                   9620:       if (strstr(model,"+age*age") !=0)
1.234     brouard  9621:        substrchaine(modelsav, model, "+age*age");
1.187     brouard  9622:       else if (strstr(model,"age*age+") !=0)
1.234     brouard  9623:        substrchaine(modelsav, model, "age*age+");
1.187     brouard  9624:       else 
1.234     brouard  9625:        substrchaine(modelsav, model, "age*age");
1.187     brouard  9626:     }else
                   9627:       nagesqr=0;
                   9628:     if (strlen(modelsav) >1){
                   9629:       j=nbocc(modelsav,'+'); /**< j=Number of '+' */
                   9630:       j1=nbocc(modelsav,'*'); /**< j1=Number of '*' */
1.224     brouard  9631:       cptcovs=j+1-j1; /**<  Number of simple covariates V1+V1*age+V3 +V3*V4+age*age=> V1 + V3 =5-3=2  */
1.187     brouard  9632:       cptcovt= j+1; /* Number of total covariates in the model, not including
1.225     brouard  9633:                     * cst, age and age*age 
                   9634:                     * V1+V1*age+ V3 + V3*V4+age*age=> 3+1=4*/
                   9635:       /* including age products which are counted in cptcovage.
                   9636:        * but the covariates which are products must be treated 
                   9637:        * separately: ncovn=4- 2=2 (V1+V3). */
1.187     brouard  9638:       cptcovprod=j1; /**< Number of products  V1*V2 +v3*age = 2 */
                   9639:       cptcovprodnoage=0; /**< Number of covariate products without age: V3*V4 =1  */
1.225     brouard  9640:       
                   9641:       
1.187     brouard  9642:       /*   Design
                   9643:        *  V1   V2   V3   V4  V5  V6  V7  V8  V9 Weight
                   9644:        *  <          ncovcol=8                >
                   9645:        * Model V2 + V1 + V3*age + V3 + V5*V6 + V7*V8 + V8*age + V8
                   9646:        *   k=  1    2      3       4     5       6      7        8
                   9647:        *  cptcovn number of covariates (not including constant and age ) = # of + plus 1 = 7+1=8
                   9648:        *  covar[k,i], value of kth covariate if not including age for individual i:
1.224     brouard  9649:        *       covar[1][i]= (V1), covar[4][i]=(V4), covar[8][i]=(V8)
                   9650:        *  Tvar[k] # of the kth covariate:  Tvar[1]=2  Tvar[2]=1 Tvar[4]=3 Tvar[8]=8
1.187     brouard  9651:        *       if multiplied by age: V3*age Tvar[3=V3*age]=3 (V3) Tvar[7]=8 and 
                   9652:        *  Tage[++cptcovage]=k
                   9653:        *       if products, new covar are created after ncovcol with k1
                   9654:        *  Tvar[k]=ncovcol+k1; # of the kth covariate product:  Tvar[5]=ncovcol+1=10  Tvar[6]=ncovcol+1=11
                   9655:        *  Tprod[k1]=k; Tprod[1]=5 Tprod[2]= 6; gives the position of the k1th product
                   9656:        *  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
                   9657:        *  Tvar[cptcovn+k2]=Tvard[k1][1];Tvar[cptcovn+k2+1]=Tvard[k1][2];
                   9658:        *  Tvar[8+1]=5;Tvar[8+2]=6;Tvar[8+3]=7;Tvar[8+4]=8 inverted
                   9659:        *  V1   V2   V3   V4  V5  V6  V7  V8  V9  V10  V11
                   9660:        *  <          ncovcol=8                >
                   9661:        *       Model V2 + V1 + V3*age + V3 + V5*V6 + V7*V8 + V8*age + V8    d1   d1   d2  d2
                   9662:        *          k=  1    2      3       4     5       6      7        8    9   10   11  12
                   9663:        *     Tvar[k]= 2    1      3       3    10      11      8        8    5    6    7   8
                   9664:        * p Tvar[1]@12={2,   1,     3,      3,   11,     10,     8,       8,   7,   8,   5,  6}
                   9665:        * p Tprod[1]@2={                         6, 5}
                   9666:        *p Tvard[1][1]@4= {7, 8, 5, 6}
                   9667:        * covar[k][i]= V2   V1      ?      V3    V5*V6?   V7*V8?  ?       V8   
                   9668:        *  cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];
                   9669:        *How to reorganize?
                   9670:        * Model V1 + V2 + V3 + V8 + V5*V6 + V7*V8 + V3*age + V8*age
                   9671:        * Tvars {2,   1,     3,      3,   11,     10,     8,       8,   7,   8,   5,  6}
                   9672:        *       {2,   1,     4,      8,    5,      6,     3,       7}
                   9673:        * Struct []
                   9674:        */
1.225     brouard  9675:       
1.187     brouard  9676:       /* This loop fills the array Tvar from the string 'model'.*/
                   9677:       /* j is the number of + signs in the model V1+V2+V3 j=2 i=3 to 1 */
                   9678:       /*   modelsav=V2+V1+V4+age*V3 strb=age*V3 stra=V2+V1+V4  */
                   9679:       /*       k=4 (age*V3) Tvar[k=4]= 3 (from V3) Tage[cptcovage=1]=4 */
                   9680:       /*       k=3 V4 Tvar[k=3]= 4 (from V4) */
                   9681:       /*       k=2 V1 Tvar[k=2]= 1 (from V1) */
                   9682:       /*       k=1 Tvar[1]=2 (from V2) */
                   9683:       /*       k=5 Tvar[5] */
                   9684:       /* for (k=1; k<=cptcovn;k++) { */
1.198     brouard  9685:       /*       cov[2+k]=nbcode[Tvar[k]][codtabm(ij,Tvar[k])]; */
1.187     brouard  9686:       /*       } */
1.198     brouard  9687:       /* for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,Tvar[Tage[k])]]*cov[2]; */
1.187     brouard  9688:       /*
                   9689:        * Treating invertedly V2+V1+V3*age+V2*V4 is as if written V2*V4 +V3*age + V1 + V2 */
1.227     brouard  9690:       for(k=cptcovt; k>=1;k--){ /**< Number of covariates not including constant and age, neither age*age*/
                   9691:         Tvar[k]=0; Tprod[k]=0; Tposprod[k]=0;
                   9692:       }
1.187     brouard  9693:       cptcovage=0;
                   9694:       for(k=1; k<=cptcovt;k++){ /* Loop on total covariates of the model */
1.234     brouard  9695:        cutl(stra,strb,modelsav,'+'); /* keeps in strb after the first '+' 
1.225     brouard  9696:                                         modelsav==V2+V1+V4+V3*age strb=V3*age stra=V2+V1+V4 */ 
1.234     brouard  9697:        if (nbocc(modelsav,'+')==0) strcpy(strb,modelsav); /* and analyzes it */
                   9698:        /*      printf("i=%d a=%s b=%s sav=%s\n",i, stra,strb,modelsav);*/
                   9699:        /*scanf("%d",i);*/
                   9700:        if (strchr(strb,'*')) {  /**< Model includes a product V2+V1+V4+V3*age strb=V3*age */
                   9701:          cutl(strc,strd,strb,'*'); /**< strd*strc  Vm*Vn: strb=V3*age(input) strc=age strd=V3 ; V3*V2 strc=V2, strd=V3 */
                   9702:          if (strcmp(strc,"age")==0) { /**< Model includes age: Vn*age */
                   9703:            /* covar is not filled and then is empty */
                   9704:            cptcovprod--;
                   9705:            cutl(stre,strb,strd,'V'); /* strd=V3(input): stre="3" */
                   9706:            Tvar[k]=atoi(stre);  /* V2+V1+V4+V3*age Tvar[4]=3 ; V1+V2*age Tvar[2]=2; V1+V1*age Tvar[2]=1 */
                   9707:            Typevar[k]=1;  /* 1 for age product */
                   9708:            cptcovage++; /* Sums the number of covariates which include age as a product */
                   9709:            Tage[cptcovage]=k;  /* Tvar[4]=3, Tage[1] = 4 or V1+V1*age Tvar[2]=1, Tage[1]=2 */
                   9710:            /*printf("stre=%s ", stre);*/
                   9711:          } else if (strcmp(strd,"age")==0) { /* or age*Vn */
                   9712:            cptcovprod--;
                   9713:            cutl(stre,strb,strc,'V');
                   9714:            Tvar[k]=atoi(stre);
                   9715:            Typevar[k]=1;  /* 1 for age product */
                   9716:            cptcovage++;
                   9717:            Tage[cptcovage]=k;
                   9718:          } else {  /* Age is not in the model product V2+V1+V1*V4+V3*age+V3*V2  strb=V3*V2*/
                   9719:            /* loops on k1=1 (V3*V2) and k1=2 V4*V3 */
                   9720:            cptcovn++;
                   9721:            cptcovprodnoage++;k1++;
                   9722:            cutl(stre,strb,strc,'V'); /* strc= Vn, stre is n; strb=V3*V2 stre=3 strc=*/
                   9723:            Tvar[k]=ncovcol+nqv+ntv+nqtv+k1; /* For model-covariate k tells which data-covariate to use but
                   9724:                                                because this model-covariate is a construction we invent a new column
                   9725:                                                which is after existing variables ncovcol+nqv+ntv+nqtv + k1
                   9726:                                                If already ncovcol=4 and model=V2+V1+V1*V4+age*V3+V3*V2
                   9727:                                                Tvar[3=V1*V4]=4+1 Tvar[5=V3*V2]=4 + 2= 6, etc */
                   9728:            Typevar[k]=2;  /* 2 for double fixed dummy covariates */
                   9729:            cutl(strc,strb,strd,'V'); /* strd was Vm, strc is m */
                   9730:            Tprod[k1]=k;  /* Tprod[1]=3(=V1*V4) for V2+V1+V1*V4+age*V3+V3*V2  */
                   9731:            Tposprod[k]=k1; /* Tpsprod[3]=1, Tposprod[2]=5 */
                   9732:            Tvard[k1][1] =atoi(strc); /* m 1 for V1*/
                   9733:            Tvard[k1][2] =atoi(stre); /* n 4 for V4*/
                   9734:            k2=k2+2;  /* k2 is initialize to -1, We want to store the n and m in Vn*Vm at the end of Tvar */
                   9735:            /* Tvar[cptcovt+k2]=Tvard[k1][1]; /\* Tvar[(cptcovt=4+k2=1)=5]= 1 (V1) *\/ */
                   9736:            /* Tvar[cptcovt+k2+1]=Tvard[k1][2];  /\* Tvar[(cptcovt=4+(k2=1)+1)=6]= 4 (V4) *\/ */
1.225     brouard  9737:             /*ncovcol=4 and model=V2+V1+V1*V4+age*V3+V3*V2, Tvar[3]=5, Tvar[4]=6, cptcovt=5 */
1.234     brouard  9738:            /*                     1  2   3      4     5 | Tvar[5+1)=1, Tvar[7]=2   */
                   9739:            for (i=1; i<=lastobs;i++){
                   9740:              /* Computes the new covariate which is a product of
                   9741:                 covar[n][i]* covar[m][i] and stores it at ncovol+k1 May not be defined */
                   9742:              covar[ncovcol+k1][i]=covar[atoi(stre)][i]*covar[atoi(strc)][i];
                   9743:            }
                   9744:          } /* End age is not in the model */
                   9745:        } /* End if model includes a product */
                   9746:        else { /* no more sum */
                   9747:          /*printf("d=%s c=%s b=%s\n", strd,strc,strb);*/
                   9748:          /*  scanf("%d",i);*/
                   9749:          cutl(strd,strc,strb,'V');
                   9750:          ks++; /**< Number of simple covariates dummy or quantitative, fixe or varying */
                   9751:          cptcovn++; /** V4+V3+V5: V4 and V3 timevarying dummy covariates, V5 timevarying quantitative */
                   9752:          Tvar[k]=atoi(strd);
                   9753:          Typevar[k]=0;  /* 0 for simple covariates */
                   9754:        }
                   9755:        strcpy(modelsav,stra);  /* modelsav=V2+V1+V4 stra=V2+V1+V4 */ 
1.223     brouard  9756:                                /*printf("a=%s b=%s sav=%s\n", stra,strb,modelsav);
1.225     brouard  9757:                                  scanf("%d",i);*/
1.187     brouard  9758:       } /* end of loop + on total covariates */
                   9759:     } /* end if strlen(modelsave == 0) age*age might exist */
                   9760:   } /* end if strlen(model == 0) */
1.136     brouard  9761:   
                   9762:   /*The number n of Vn is stored in Tvar. cptcovage =number of age covariate. Tage gives the position of age. cptcovprod= number of products.
                   9763:     If model=V1+V1*age then Tvar[1]=1 Tvar[2]=1 cptcovage=1 Tage[1]=2 cptcovprod=0*/
1.225     brouard  9764:   
1.136     brouard  9765:   /* printf("tvar1=%d tvar2=%d tvar3=%d cptcovage=%d Tage=%d",Tvar[1],Tvar[2],Tvar[3],cptcovage,Tage[1]);
1.225     brouard  9766:      printf("cptcovprod=%d ", cptcovprod);
                   9767:      fprintf(ficlog,"cptcovprod=%d ", cptcovprod);
                   9768:      scanf("%d ",i);*/
                   9769: 
                   9770: 
1.230     brouard  9771: /* Until here, decodemodel knows only the grammar (simple, product, age*) of the model but not what kind
                   9772:    of variable (dummy vs quantitative, fixed vs time varying) is behind. But we know the # of each. */
1.226     brouard  9773: /* ncovcol= 1, nqv=1 | ntv=2, nqtv= 1  = 5 possible variables data: 2 fixed 3, varying
                   9774:    model=        V5 + V4 +V3 + V4*V3 + V5*age + V2 + V1*V2 + V1*age + V5*age, V1 is not used saving its place
                   9775:    k =           1    2   3     4       5       6      7      8        9
                   9776:    Tvar[k]=      5    4   3 1+1+2+1+1=6 5       2      7      1        5
                   9777:    Typevar[k]=   0    0   0     2       1       0      2      1        1
1.227     brouard  9778:    Fixed[k]      1    1   1     1       3       0    0 or 2   2        3
                   9779:    Dummy[k]      1    0   0     0       3       1      1      2        3
                   9780:          Tmodelind[combination of covar]=k;
1.225     brouard  9781: */  
                   9782: /* Dispatching between quantitative and time varying covariates */
1.226     brouard  9783:   /* If Tvar[k] >ncovcol it is a product */
1.225     brouard  9784:   /* 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  9785:        /* Computing effective variables, ie used by the model, that is from the cptcovt variables */
1.227     brouard  9786:   printf("Model=%s\n\
                   9787: Typevar: 0 for simple covariate (dummy, quantitative, fixed or varying), 1 for age product, 2 for  product \n\
                   9788: Fixed[k] 0=fixed (product or simple), 1 varying, 2 fixed with age product, 3 varying with age product \n\
                   9789: 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);
                   9790:   fprintf(ficlog,"Model=%s\n\
                   9791: Typevar: 0 for simple covariate (dummy, quantitative, fixed or varying), 1 for age product, 2 for  product \n\
                   9792: Fixed[k] 0=fixed (product or simple), 1 varying, 2 fixed with age product, 3 varying with age product \n\
                   9793: 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  9794:   for(k=-1;k<=cptcovt; k++){ Fixed[k]=0; Dummy[k]=0;}
1.234     brouard  9795:   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 */
                   9796:     if (Tvar[k] <=ncovcol && Typevar[k]==0 ){ /* Simple fixed dummy (<=ncovcol) covariates */
1.227     brouard  9797:       Fixed[k]= 0;
                   9798:       Dummy[k]= 0;
1.225     brouard  9799:       ncoveff++;
1.232     brouard  9800:       ncovf++;
1.234     brouard  9801:       nsd++;
                   9802:       modell[k].maintype= FTYPE;
                   9803:       TvarsD[nsd]=Tvar[k];
                   9804:       TvarsDind[nsd]=k;
                   9805:       TvarF[ncovf]=Tvar[k];
                   9806:       TvarFind[ncovf]=k;
                   9807:       TvarFD[ncoveff]=Tvar[k]; /* TvarFD[1]=V1 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
                   9808:       TvarFDind[ncoveff]=k; /* TvarFDind[1]=9 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
                   9809:     }else if( Tvar[k] <=ncovcol &&  Typevar[k]==2){ /* Product of fixed dummy (<=ncovcol) covariates */
                   9810:       Fixed[k]= 0;
                   9811:       Dummy[k]= 0;
                   9812:       ncoveff++;
                   9813:       ncovf++;
                   9814:       modell[k].maintype= FTYPE;
                   9815:       TvarF[ncovf]=Tvar[k];
                   9816:       TvarFind[ncovf]=k;
1.230     brouard  9817:       TvarFD[ncoveff]=Tvar[k]; /* TvarFD[1]=V1 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
1.231     brouard  9818:       TvarFDind[ncoveff]=k; /* TvarFDind[1]=9 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
1.240     brouard  9819:     }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  9820:       Fixed[k]= 0;
                   9821:       Dummy[k]= 1;
1.230     brouard  9822:       nqfveff++;
1.234     brouard  9823:       modell[k].maintype= FTYPE;
                   9824:       modell[k].subtype= FQ;
                   9825:       nsq++;
                   9826:       TvarsQ[nsq]=Tvar[k];
                   9827:       TvarsQind[nsq]=k;
1.232     brouard  9828:       ncovf++;
1.234     brouard  9829:       TvarF[ncovf]=Tvar[k];
                   9830:       TvarFind[ncovf]=k;
1.231     brouard  9831:       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  9832:       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  9833:     }else if( Tvar[k] <=ncovcol+nqv+ntv && Typevar[k]==0){/* Only simple time varying dummy variables */
1.227     brouard  9834:       Fixed[k]= 1;
                   9835:       Dummy[k]= 0;
1.225     brouard  9836:       ntveff++; /* Only simple time varying dummy variable */
1.234     brouard  9837:       modell[k].maintype= VTYPE;
                   9838:       modell[k].subtype= VD;
                   9839:       nsd++;
                   9840:       TvarsD[nsd]=Tvar[k];
                   9841:       TvarsDind[nsd]=k;
                   9842:       ncovv++; /* Only simple time varying variables */
                   9843:       TvarV[ncovv]=Tvar[k];
1.242     brouard  9844:       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  9845:       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 */
                   9846:       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  9847:       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);
                   9848:       printf("Quasi TmodelInvind[%d]=%d\n",k,Tvar[k]- ncovcol-nqv);
1.231     brouard  9849:     }else if( Tvar[k] <=ncovcol+nqv+ntv+nqtv  && Typevar[k]==0){ /* Only simple time varying quantitative variable V5*/
1.234     brouard  9850:       Fixed[k]= 1;
                   9851:       Dummy[k]= 1;
                   9852:       nqtveff++;
                   9853:       modell[k].maintype= VTYPE;
                   9854:       modell[k].subtype= VQ;
                   9855:       ncovv++; /* Only simple time varying variables */
                   9856:       nsq++;
                   9857:       TvarsQ[nsq]=Tvar[k];
                   9858:       TvarsQind[nsq]=k;
                   9859:       TvarV[ncovv]=Tvar[k];
1.242     brouard  9860:       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  9861:       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 */
                   9862:       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  9863:       TmodelInvQind[nqtveff]=Tvar[k]- ncovcol-nqv-ntv;/* Only simple time varying quantitative variable */
                   9864:       /* Tmodeliqind[k]=nqtveff;/\* Only simple time varying quantitative variable *\/ */
                   9865:       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  9866:       printf("Quasi TmodelInvQind[%d]=%d\n",k,Tvar[k]- ncovcol-nqv-ntv);
1.227     brouard  9867:     }else if (Typevar[k] == 1) {  /* product with age */
1.234     brouard  9868:       ncova++;
                   9869:       TvarA[ncova]=Tvar[k];
                   9870:       TvarAind[ncova]=k;
1.231     brouard  9871:       if (Tvar[k] <=ncovcol ){ /* Product age with fixed dummy covariatee */
1.240     brouard  9872:        Fixed[k]= 2;
                   9873:        Dummy[k]= 2;
                   9874:        modell[k].maintype= ATYPE;
                   9875:        modell[k].subtype= APFD;
                   9876:        /* ncoveff++; */
1.227     brouard  9877:       }else if( Tvar[k] <=ncovcol+nqv) { /* Remind that product Vn*Vm are added in k*/
1.240     brouard  9878:        Fixed[k]= 2;
                   9879:        Dummy[k]= 3;
                   9880:        modell[k].maintype= ATYPE;
                   9881:        modell[k].subtype= APFQ;                /*      Product age * fixed quantitative */
                   9882:        /* nqfveff++;  /\* Only simple fixed quantitative variable *\/ */
1.227     brouard  9883:       }else if( Tvar[k] <=ncovcol+nqv+ntv ){
1.240     brouard  9884:        Fixed[k]= 3;
                   9885:        Dummy[k]= 2;
                   9886:        modell[k].maintype= ATYPE;
                   9887:        modell[k].subtype= APVD;                /*      Product age * varying dummy */
                   9888:        /* ntveff++; /\* Only simple time varying dummy variable *\/ */
1.227     brouard  9889:       }else if( Tvar[k] <=ncovcol+nqv+ntv+nqtv){
1.240     brouard  9890:        Fixed[k]= 3;
                   9891:        Dummy[k]= 3;
                   9892:        modell[k].maintype= ATYPE;
                   9893:        modell[k].subtype= APVQ;                /*      Product age * varying quantitative */
                   9894:        /* nqtveff++;/\* Only simple time varying quantitative variable *\/ */
1.227     brouard  9895:       }
                   9896:     }else if (Typevar[k] == 2) {  /* product without age */
                   9897:       k1=Tposprod[k];
                   9898:       if(Tvard[k1][1] <=ncovcol){
1.240     brouard  9899:        if(Tvard[k1][2] <=ncovcol){
                   9900:          Fixed[k]= 1;
                   9901:          Dummy[k]= 0;
                   9902:          modell[k].maintype= FTYPE;
                   9903:          modell[k].subtype= FPDD;              /*      Product fixed dummy * fixed dummy */
                   9904:          ncovf++; /* Fixed variables without age */
                   9905:          TvarF[ncovf]=Tvar[k];
                   9906:          TvarFind[ncovf]=k;
                   9907:        }else if(Tvard[k1][2] <=ncovcol+nqv){
                   9908:          Fixed[k]= 0;  /* or 2 ?*/
                   9909:          Dummy[k]= 1;
                   9910:          modell[k].maintype= FTYPE;
                   9911:          modell[k].subtype= FPDQ;              /*      Product fixed dummy * fixed quantitative */
                   9912:          ncovf++; /* Varying variables without age */
                   9913:          TvarF[ncovf]=Tvar[k];
                   9914:          TvarFind[ncovf]=k;
                   9915:        }else if(Tvard[k1][2] <=ncovcol+nqv+ntv){
                   9916:          Fixed[k]= 1;
                   9917:          Dummy[k]= 0;
                   9918:          modell[k].maintype= VTYPE;
                   9919:          modell[k].subtype= VPDD;              /*      Product fixed dummy * varying dummy */
                   9920:          ncovv++; /* Varying variables without age */
                   9921:          TvarV[ncovv]=Tvar[k];
                   9922:          TvarVind[ncovv]=k;
                   9923:        }else if(Tvard[k1][2] <=ncovcol+nqv+ntv+nqtv){
                   9924:          Fixed[k]= 1;
                   9925:          Dummy[k]= 1;
                   9926:          modell[k].maintype= VTYPE;
                   9927:          modell[k].subtype= VPDQ;              /*      Product fixed dummy * varying quantitative */
                   9928:          ncovv++; /* Varying variables without age */
                   9929:          TvarV[ncovv]=Tvar[k];
                   9930:          TvarVind[ncovv]=k;
                   9931:        }
1.227     brouard  9932:       }else if(Tvard[k1][1] <=ncovcol+nqv){
1.240     brouard  9933:        if(Tvard[k1][2] <=ncovcol){
                   9934:          Fixed[k]= 0;  /* or 2 ?*/
                   9935:          Dummy[k]= 1;
                   9936:          modell[k].maintype= FTYPE;
                   9937:          modell[k].subtype= FPDQ;              /*      Product fixed quantitative * fixed dummy */
                   9938:          ncovf++; /* Fixed variables without age */
                   9939:          TvarF[ncovf]=Tvar[k];
                   9940:          TvarFind[ncovf]=k;
                   9941:        }else if(Tvard[k1][2] <=ncovcol+nqv+ntv){
                   9942:          Fixed[k]= 1;
                   9943:          Dummy[k]= 1;
                   9944:          modell[k].maintype= VTYPE;
                   9945:          modell[k].subtype= VPDQ;              /*      Product fixed quantitative * varying dummy */
                   9946:          ncovv++; /* Varying variables without age */
                   9947:          TvarV[ncovv]=Tvar[k];
                   9948:          TvarVind[ncovv]=k;
                   9949:        }else if(Tvard[k1][2] <=ncovcol+nqv+ntv+nqtv){
                   9950:          Fixed[k]= 1;
                   9951:          Dummy[k]= 1;
                   9952:          modell[k].maintype= VTYPE;
                   9953:          modell[k].subtype= VPQQ;              /*      Product fixed quantitative * varying quantitative */
                   9954:          ncovv++; /* Varying variables without age */
                   9955:          TvarV[ncovv]=Tvar[k];
                   9956:          TvarVind[ncovv]=k;
                   9957:          ncovv++; /* Varying variables without age */
                   9958:          TvarV[ncovv]=Tvar[k];
                   9959:          TvarVind[ncovv]=k;
                   9960:        }
1.227     brouard  9961:       }else if(Tvard[k1][1] <=ncovcol+nqv+ntv){
1.240     brouard  9962:        if(Tvard[k1][2] <=ncovcol){
                   9963:          Fixed[k]= 1;
                   9964:          Dummy[k]= 1;
                   9965:          modell[k].maintype= VTYPE;
                   9966:          modell[k].subtype= VPDD;              /*      Product time varying dummy * fixed dummy */
                   9967:          ncovv++; /* Varying variables without age */
                   9968:          TvarV[ncovv]=Tvar[k];
                   9969:          TvarVind[ncovv]=k;
                   9970:        }else if(Tvard[k1][2] <=ncovcol+nqv){
                   9971:          Fixed[k]= 1;
                   9972:          Dummy[k]= 1;
                   9973:          modell[k].maintype= VTYPE;
                   9974:          modell[k].subtype= VPDQ;              /*      Product time varying dummy * fixed quantitative */
                   9975:          ncovv++; /* Varying variables without age */
                   9976:          TvarV[ncovv]=Tvar[k];
                   9977:          TvarVind[ncovv]=k;
                   9978:        }else if(Tvard[k1][2] <=ncovcol+nqv+ntv){
                   9979:          Fixed[k]= 1;
                   9980:          Dummy[k]= 0;
                   9981:          modell[k].maintype= VTYPE;
                   9982:          modell[k].subtype= VPDD;              /*      Product time varying dummy * time varying dummy */
                   9983:          ncovv++; /* Varying variables without age */
                   9984:          TvarV[ncovv]=Tvar[k];
                   9985:          TvarVind[ncovv]=k;
                   9986:        }else if(Tvard[k1][2] <=ncovcol+nqv+ntv+nqtv){
                   9987:          Fixed[k]= 1;
                   9988:          Dummy[k]= 1;
                   9989:          modell[k].maintype= VTYPE;
                   9990:          modell[k].subtype= VPDQ;              /*      Product time varying dummy * time varying quantitative */
                   9991:          ncovv++; /* Varying variables without age */
                   9992:          TvarV[ncovv]=Tvar[k];
                   9993:          TvarVind[ncovv]=k;
                   9994:        }
1.227     brouard  9995:       }else if(Tvard[k1][1] <=ncovcol+nqv+ntv+nqtv){
1.240     brouard  9996:        if(Tvard[k1][2] <=ncovcol){
                   9997:          Fixed[k]= 1;
                   9998:          Dummy[k]= 1;
                   9999:          modell[k].maintype= VTYPE;
                   10000:          modell[k].subtype= VPDQ;              /*      Product time varying quantitative * fixed dummy */
                   10001:          ncovv++; /* Varying variables without age */
                   10002:          TvarV[ncovv]=Tvar[k];
                   10003:          TvarVind[ncovv]=k;
                   10004:        }else if(Tvard[k1][2] <=ncovcol+nqv){
                   10005:          Fixed[k]= 1;
                   10006:          Dummy[k]= 1;
                   10007:          modell[k].maintype= VTYPE;
                   10008:          modell[k].subtype= VPQQ;              /*      Product time varying quantitative * fixed quantitative */
                   10009:          ncovv++; /* Varying variables without age */
                   10010:          TvarV[ncovv]=Tvar[k];
                   10011:          TvarVind[ncovv]=k;
                   10012:        }else if(Tvard[k1][2] <=ncovcol+nqv+ntv){
                   10013:          Fixed[k]= 1;
                   10014:          Dummy[k]= 1;
                   10015:          modell[k].maintype= VTYPE;
                   10016:          modell[k].subtype= VPDQ;              /*      Product time varying quantitative * time varying dummy */
                   10017:          ncovv++; /* Varying variables without age */
                   10018:          TvarV[ncovv]=Tvar[k];
                   10019:          TvarVind[ncovv]=k;
                   10020:        }else if(Tvard[k1][2] <=ncovcol+nqv+ntv+nqtv){
                   10021:          Fixed[k]= 1;
                   10022:          Dummy[k]= 1;
                   10023:          modell[k].maintype= VTYPE;
                   10024:          modell[k].subtype= VPQQ;              /*      Product time varying quantitative * time varying quantitative */
                   10025:          ncovv++; /* Varying variables without age */
                   10026:          TvarV[ncovv]=Tvar[k];
                   10027:          TvarVind[ncovv]=k;
                   10028:        }
1.227     brouard  10029:       }else{
1.240     brouard  10030:        printf("Error unknown type of covariate: Tvard[%d][1]=%d,Tvard[%d][2]=%d\n",k1,Tvard[k1][1],k1,Tvard[k1][2]);
                   10031:        fprintf(ficlog,"Error unknown type of covariate: Tvard[%d][1]=%d,Tvard[%d][2]=%d\n",k1,Tvard[k1][1],k1,Tvard[k1][2]);
                   10032:       } /*end k1*/
1.225     brouard  10033:     }else{
1.226     brouard  10034:       printf("Error, current version can't treat for performance reasons, Tvar[%d]=%d, Typevar[%d]=%d\n", k, Tvar[k], k, Typevar[k]);
                   10035:       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  10036:     }
1.227     brouard  10037:     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  10038:     printf("           modell[%d].maintype=%d, modell[%d].subtype=%d\n",k,modell[k].maintype,k,modell[k].subtype);
1.227     brouard  10039:     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]);
                   10040:   }
                   10041:   /* Searching for doublons in the model */
                   10042:   for(k1=1; k1<= cptcovt;k1++){
                   10043:     for(k2=1; k2 <k1;k2++){
1.285     brouard  10044:       /* if((Typevar[k1]==Typevar[k2]) && (Fixed[Tvar[k1]]==Fixed[Tvar[k2]]) && (Dummy[Tvar[k1]]==Dummy[Tvar[k2]] )){ */
                   10045:       if((Typevar[k1]==Typevar[k2]) && (Fixed[k1]==Fixed[k2]) && (Dummy[k1]==Dummy[k2] )){
1.234     brouard  10046:        if((Typevar[k1] == 0 || Typevar[k1] == 1)){ /* Simple or age product */
                   10047:          if(Tvar[k1]==Tvar[k2]){
1.285     brouard  10048:            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]);
                   10049:            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  10050:            return(1);
                   10051:          }
                   10052:        }else if (Typevar[k1] ==2){
                   10053:          k3=Tposprod[k1];
                   10054:          k4=Tposprod[k2];
                   10055:          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])) ){
                   10056:            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]]);
                   10057:            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);
                   10058:            return(1);
                   10059:          }
                   10060:        }
1.227     brouard  10061:       }
                   10062:     }
1.225     brouard  10063:   }
                   10064:   printf("ncoveff=%d, nqfveff=%d, ntveff=%d, nqtveff=%d, cptcovn=%d\n",ncoveff,nqfveff,ntveff,nqtveff,cptcovn);
                   10065:   fprintf(ficlog,"ncoveff=%d, nqfveff=%d, ntveff=%d, nqtveff=%d, cptcovn=%d\n",ncoveff,nqfveff,ntveff,nqtveff,cptcovn);
1.234     brouard  10066:   printf("ncovf=%d, ncovv=%d, ncova=%d, nsd=%d, nsq=%d\n",ncovf,ncovv,ncova,nsd,nsq);
                   10067:   fprintf(ficlog,"ncovf=%d, ncovv=%d, ncova=%d, nsd=%d, nsq=%d\n",ncovf,ncovv,ncova,nsd, nsq);
1.137     brouard  10068:   return (0); /* with covar[new additional covariate if product] and Tage if age */ 
1.164     brouard  10069:   /*endread:*/
1.225     brouard  10070:   printf("Exiting decodemodel: ");
                   10071:   return (1);
1.136     brouard  10072: }
                   10073: 
1.169     brouard  10074: int calandcheckages(int imx, int maxwav, double *agemin, double *agemax, int *nberr, int *nbwarn )
1.248     brouard  10075: {/* Check ages at death */
1.136     brouard  10076:   int i, m;
1.218     brouard  10077:   int firstone=0;
                   10078:   
1.136     brouard  10079:   for (i=1; i<=imx; i++) {
                   10080:     for(m=2; (m<= maxwav); m++) {
                   10081:       if (((int)mint[m][i]== 99) && (s[m][i] <= nlstate)){
                   10082:        anint[m][i]=9999;
1.216     brouard  10083:        if (s[m][i] != -2) /* Keeping initial status of unknown vital status */
                   10084:          s[m][i]=-1;
1.136     brouard  10085:       }
                   10086:       if((int)moisdc[i]==99 && (int)andc[i]==9999 && s[m][i]>nlstate){
1.260     brouard  10087:        *nberr = *nberr + 1;
1.218     brouard  10088:        if(firstone == 0){
                   10089:          firstone=1;
1.260     brouard  10090:        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  10091:        }
1.262     brouard  10092:        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  10093:        s[m][i]=-1;  /* Droping the death status */
1.136     brouard  10094:       }
                   10095:       if((int)moisdc[i]==99 && (int)andc[i]!=9999 && s[m][i]>nlstate){
1.169     brouard  10096:        (*nberr)++;
1.259     brouard  10097:        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  10098:        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  10099:        s[m][i]=-2; /* We prefer to skip it (and to skip it in version 0.8a1 too */
1.136     brouard  10100:       }
                   10101:     }
                   10102:   }
                   10103: 
                   10104:   for (i=1; i<=imx; i++)  {
                   10105:     agedc[i]=(moisdc[i]/12.+andc[i])-(moisnais[i]/12.+annais[i]);
                   10106:     for(m=firstpass; (m<= lastpass); m++){
1.214     brouard  10107:       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  10108:        if (s[m][i] >= nlstate+1) {
1.169     brouard  10109:          if(agedc[i]>0){
                   10110:            if((int)moisdc[i]!=99 && (int)andc[i]!=9999){
1.136     brouard  10111:              agev[m][i]=agedc[i];
1.214     brouard  10112:              /*if(moisdc[i]==99 && andc[i]==9999) s[m][i]=-1;*/
1.169     brouard  10113:            }else {
1.136     brouard  10114:              if ((int)andc[i]!=9999){
                   10115:                nbwarn++;
                   10116:                printf("Warning negative age at death: %ld line:%d\n",num[i],i);
                   10117:                fprintf(ficlog,"Warning negative age at death: %ld line:%d\n",num[i],i);
                   10118:                agev[m][i]=-1;
                   10119:              }
                   10120:            }
1.169     brouard  10121:          } /* agedc > 0 */
1.214     brouard  10122:        } /* end if */
1.136     brouard  10123:        else if(s[m][i] !=9){ /* Standard case, age in fractional
                   10124:                                 years but with the precision of a month */
                   10125:          agev[m][i]=(mint[m][i]/12.+1./24.+anint[m][i])-(moisnais[i]/12.+1./24.+annais[i]);
                   10126:          if((int)mint[m][i]==99 || (int)anint[m][i]==9999)
                   10127:            agev[m][i]=1;
                   10128:          else if(agev[m][i] < *agemin){ 
                   10129:            *agemin=agev[m][i];
                   10130:            printf(" Min anint[%d][%d]=%.2f annais[%d]=%.2f, agemin=%.2f\n",m,i,anint[m][i], i,annais[i], *agemin);
                   10131:          }
                   10132:          else if(agev[m][i] >*agemax){
                   10133:            *agemax=agev[m][i];
1.156     brouard  10134:            /* printf(" Max anint[%d][%d]=%.0f annais[%d]=%.0f, agemax=%.2f\n",m,i,anint[m][i], i,annais[i], *agemax);*/
1.136     brouard  10135:          }
                   10136:          /*agev[m][i]=anint[m][i]-annais[i];*/
                   10137:          /*     agev[m][i] = age[i]+2*m;*/
1.214     brouard  10138:        } /* en if 9*/
1.136     brouard  10139:        else { /* =9 */
1.214     brouard  10140:          /* printf("Debug num[%d]=%ld s[%d][%d]=%d\n",i,num[i], m,i, s[m][i]); */
1.136     brouard  10141:          agev[m][i]=1;
                   10142:          s[m][i]=-1;
                   10143:        }
                   10144:       }
1.214     brouard  10145:       else if(s[m][i]==0) /*= 0 Unknown */
1.136     brouard  10146:        agev[m][i]=1;
1.214     brouard  10147:       else{
                   10148:        printf("Warning, num[%d]=%ld, s[%d][%d]=%d\n", i, num[i], m, i,s[m][i]); 
                   10149:        fprintf(ficlog, "Warning, num[%d]=%ld, s[%d][%d]=%d\n", i, num[i], m, i,s[m][i]); 
                   10150:        agev[m][i]=0;
                   10151:       }
                   10152:     } /* End for lastpass */
                   10153:   }
1.136     brouard  10154:     
                   10155:   for (i=1; i<=imx; i++)  {
                   10156:     for(m=firstpass; (m<=lastpass); m++){
                   10157:       if (s[m][i] > (nlstate+ndeath)) {
1.169     brouard  10158:        (*nberr)++;
1.136     brouard  10159:        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);     
                   10160:        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);     
                   10161:        return 1;
                   10162:       }
                   10163:     }
                   10164:   }
                   10165: 
                   10166:   /*for (i=1; i<=imx; i++){
                   10167:   for (m=firstpass; (m<lastpass); m++){
                   10168:      printf("%ld %d %.lf %d %d\n", num[i],(covar[1][i]),agev[m][i],s[m][i],s[m+1][i]);
                   10169: }
                   10170: 
                   10171: }*/
                   10172: 
                   10173: 
1.139     brouard  10174:   printf("Total number of individuals= %d, Agemin = %.2f, Agemax= %.2f\n\n", imx, *agemin, *agemax);
                   10175:   fprintf(ficlog,"Total number of individuals= %d, Agemin = %.2f, Agemax= %.2f\n\n", imx, *agemin, *agemax); 
1.136     brouard  10176: 
                   10177:   return (0);
1.164     brouard  10178:  /* endread:*/
1.136     brouard  10179:     printf("Exiting calandcheckages: ");
                   10180:     return (1);
                   10181: }
                   10182: 
1.172     brouard  10183: #if defined(_MSC_VER)
                   10184: /*printf("Visual C++ compiler: %s \n;", _MSC_FULL_VER);*/
                   10185: /*fprintf(ficlog, "Visual C++ compiler: %s \n;", _MSC_FULL_VER);*/
                   10186: //#include "stdafx.h"
                   10187: //#include <stdio.h>
                   10188: //#include <tchar.h>
                   10189: //#include <windows.h>
                   10190: //#include <iostream>
                   10191: typedef BOOL(WINAPI *LPFN_ISWOW64PROCESS) (HANDLE, PBOOL);
                   10192: 
                   10193: LPFN_ISWOW64PROCESS fnIsWow64Process;
                   10194: 
                   10195: BOOL IsWow64()
                   10196: {
                   10197:        BOOL bIsWow64 = FALSE;
                   10198: 
                   10199:        //typedef BOOL (APIENTRY *LPFN_ISWOW64PROCESS)
                   10200:        //  (HANDLE, PBOOL);
                   10201: 
                   10202:        //LPFN_ISWOW64PROCESS fnIsWow64Process;
                   10203: 
                   10204:        HMODULE module = GetModuleHandle(_T("kernel32"));
                   10205:        const char funcName[] = "IsWow64Process";
                   10206:        fnIsWow64Process = (LPFN_ISWOW64PROCESS)
                   10207:                GetProcAddress(module, funcName);
                   10208: 
                   10209:        if (NULL != fnIsWow64Process)
                   10210:        {
                   10211:                if (!fnIsWow64Process(GetCurrentProcess(),
                   10212:                        &bIsWow64))
                   10213:                        //throw std::exception("Unknown error");
                   10214:                        printf("Unknown error\n");
                   10215:        }
                   10216:        return bIsWow64 != FALSE;
                   10217: }
                   10218: #endif
1.177     brouard  10219: 
1.191     brouard  10220: void syscompilerinfo(int logged)
1.292     brouard  10221: {
                   10222: #include <stdint.h>
                   10223: 
                   10224:   /* #include "syscompilerinfo.h"*/
1.185     brouard  10225:    /* command line Intel compiler 32bit windows, XP compatible:*/
                   10226:    /* /GS /W3 /Gy
                   10227:       /Zc:wchar_t /Zi /O2 /Fd"Release\vc120.pdb" /D "WIN32" /D "NDEBUG" /D
                   10228:       "_CONSOLE" /D "_LIB" /D "_USING_V110_SDK71_" /D "_UNICODE" /D
                   10229:       "UNICODE" /Qipo /Zc:forScope /Gd /Oi /MT /Fa"Release\" /EHsc /nologo
1.186     brouard  10230:       /Fo"Release\" /Qprof-dir "Release\" /Fp"Release\IMaCh.pch"
                   10231:    */ 
                   10232:    /* 64 bits */
1.185     brouard  10233:    /*
                   10234:      /GS /W3 /Gy
                   10235:      /Zc:wchar_t /Zi /O2 /Fd"x64\Release\vc120.pdb" /D "WIN32" /D "NDEBUG"
                   10236:      /D "_CONSOLE" /D "_LIB" /D "_UNICODE" /D "UNICODE" /Qipo /Zc:forScope
                   10237:      /Oi /MD /Fa"x64\Release\" /EHsc /nologo /Fo"x64\Release\" /Qprof-dir
                   10238:      "x64\Release\" /Fp"x64\Release\IMaCh.pch" */
                   10239:    /* Optimization are useless and O3 is slower than O2 */
                   10240:    /*
                   10241:      /GS /W3 /Gy /Zc:wchar_t /Zi /O3 /Fd"x64\Release\vc120.pdb" /D "WIN32" 
                   10242:      /D "NDEBUG" /D "_CONSOLE" /D "_LIB" /D "_UNICODE" /D "UNICODE" /Qipo 
                   10243:      /Zc:forScope /Oi /MD /Fa"x64\Release\" /EHsc /nologo /Qparallel 
                   10244:      /Fo"x64\Release\" /Qprof-dir "x64\Release\" /Fp"x64\Release\IMaCh.pch" 
                   10245:    */
1.186     brouard  10246:    /* Link is */ /* /OUT:"visual studio
1.185     brouard  10247:       2013\Projects\IMaCh\Release\IMaCh.exe" /MANIFEST /NXCOMPAT
                   10248:       /PDB:"visual studio
                   10249:       2013\Projects\IMaCh\Release\IMaCh.pdb" /DYNAMICBASE
                   10250:       "kernel32.lib" "user32.lib" "gdi32.lib" "winspool.lib"
                   10251:       "comdlg32.lib" "advapi32.lib" "shell32.lib" "ole32.lib"
                   10252:       "oleaut32.lib" "uuid.lib" "odbc32.lib" "odbccp32.lib"
                   10253:       /MACHINE:X86 /OPT:REF /SAFESEH /INCREMENTAL:NO
                   10254:       /SUBSYSTEM:CONSOLE",5.01" /MANIFESTUAC:"level='asInvoker'
                   10255:       uiAccess='false'"
                   10256:       /ManifestFile:"Release\IMaCh.exe.intermediate.manifest" /OPT:ICF
                   10257:       /NOLOGO /TLBID:1
                   10258:    */
1.292     brouard  10259: 
                   10260: 
1.177     brouard  10261: #if defined __INTEL_COMPILER
1.178     brouard  10262: #if defined(__GNUC__)
                   10263:        struct utsname sysInfo;  /* For Intel on Linux and OS/X */
                   10264: #endif
1.177     brouard  10265: #elif defined(__GNUC__) 
1.179     brouard  10266: #ifndef  __APPLE__
1.174     brouard  10267: #include <gnu/libc-version.h>  /* Only on gnu */
1.179     brouard  10268: #endif
1.177     brouard  10269:    struct utsname sysInfo;
1.178     brouard  10270:    int cross = CROSS;
                   10271:    if (cross){
                   10272:           printf("Cross-");
1.191     brouard  10273:           if(logged) fprintf(ficlog, "Cross-");
1.178     brouard  10274:    }
1.174     brouard  10275: #endif
                   10276: 
1.191     brouard  10277:    printf("Compiled with:");if(logged)fprintf(ficlog,"Compiled with:");
1.169     brouard  10278: #if defined(__clang__)
1.191     brouard  10279:    printf(" Clang/LLVM");if(logged)fprintf(ficlog," Clang/LLVM");      /* Clang/LLVM. ---------------------------------------------- */
1.169     brouard  10280: #endif
                   10281: #if defined(__ICC) || defined(__INTEL_COMPILER)
1.191     brouard  10282:    printf(" Intel ICC/ICPC");if(logged)fprintf(ficlog," Intel ICC/ICPC");/* Intel ICC/ICPC. ------------------------------------------ */
1.169     brouard  10283: #endif
                   10284: #if defined(__GNUC__) || defined(__GNUG__)
1.191     brouard  10285:    printf(" GNU GCC/G++");if(logged)fprintf(ficlog," GNU GCC/G++");/* GNU GCC/G++. --------------------------------------------- */
1.169     brouard  10286: #endif
                   10287: #if defined(__HP_cc) || defined(__HP_aCC)
1.191     brouard  10288:    printf(" Hewlett-Packard C/aC++");if(logged)fprintf(fcilog," Hewlett-Packard C/aC++"); /* Hewlett-Packard C/aC++. ---------------------------------- */
1.169     brouard  10289: #endif
                   10290: #if defined(__IBMC__) || defined(__IBMCPP__)
1.191     brouard  10291:    printf(" IBM XL C/C++"); if(logged) fprintf(ficlog," IBM XL C/C++");/* IBM XL C/C++. -------------------------------------------- */
1.169     brouard  10292: #endif
                   10293: #if defined(_MSC_VER)
1.191     brouard  10294:    printf(" Microsoft Visual Studio");if(logged)fprintf(ficlog," Microsoft Visual Studio");/* Microsoft Visual Studio. --------------------------------- */
1.169     brouard  10295: #endif
                   10296: #if defined(__PGI)
1.191     brouard  10297:    printf(" Portland Group PGCC/PGCPP");if(logged) fprintf(ficlog," Portland Group PGCC/PGCPP");/* Portland Group PGCC/PGCPP. ------------------------------- */
1.169     brouard  10298: #endif
                   10299: #if defined(__SUNPRO_C) || defined(__SUNPRO_CC)
1.191     brouard  10300:    printf(" Oracle Solaris Studio");if(logged)fprintf(ficlog," Oracle Solaris Studio\n");/* Oracle Solaris Studio. ----------------------------------- */
1.167     brouard  10301: #endif
1.191     brouard  10302:    printf(" for "); if (logged) fprintf(ficlog, " for ");
1.169     brouard  10303:    
1.167     brouard  10304: // http://stackoverflow.com/questions/4605842/how-to-identify-platform-compiler-from-preprocessor-macros
                   10305: #ifdef _WIN32 // note the underscore: without it, it's not msdn official!
                   10306:     // Windows (x64 and x86)
1.191     brouard  10307:    printf("Windows (x64 and x86) ");if(logged) fprintf(ficlog,"Windows (x64 and x86) ");
1.167     brouard  10308: #elif __unix__ // all unices, not all compilers
                   10309:     // Unix
1.191     brouard  10310:    printf("Unix ");if(logged) fprintf(ficlog,"Unix ");
1.167     brouard  10311: #elif __linux__
                   10312:     // linux
1.191     brouard  10313:    printf("linux ");if(logged) fprintf(ficlog,"linux ");
1.167     brouard  10314: #elif __APPLE__
1.174     brouard  10315:     // Mac OS, not sure if this is covered by __posix__ and/or __unix__ though..
1.191     brouard  10316:    printf("Mac OS ");if(logged) fprintf(ficlog,"Mac OS ");
1.167     brouard  10317: #endif
                   10318: 
                   10319: /*  __MINGW32__          */
                   10320: /*  __CYGWIN__  */
                   10321: /* __MINGW64__  */
                   10322: // http://msdn.microsoft.com/en-us/library/b0084kay.aspx
                   10323: /* _MSC_VER  //the Visual C++ compiler is 17.00.51106.1, the _MSC_VER macro evaluates to 1700. Type cl /?  */
                   10324: /* _MSC_FULL_VER //the Visual C++ compiler is 15.00.20706.01, the _MSC_FULL_VER macro evaluates to 150020706 */
                   10325: /* _WIN64  // Defined for applications for Win64. */
                   10326: /* _M_X64 // Defined for compilations that target x64 processors. */
                   10327: /* _DEBUG // Defined when you compile with /LDd, /MDd, and /MTd. */
1.171     brouard  10328: 
1.167     brouard  10329: #if UINTPTR_MAX == 0xffffffff
1.191     brouard  10330:    printf(" 32-bit"); if(logged) fprintf(ficlog," 32-bit");/* 32-bit */
1.167     brouard  10331: #elif UINTPTR_MAX == 0xffffffffffffffff
1.191     brouard  10332:    printf(" 64-bit"); if(logged) fprintf(ficlog," 64-bit");/* 64-bit */
1.167     brouard  10333: #else
1.191     brouard  10334:    printf(" wtf-bit"); if(logged) fprintf(ficlog," wtf-bit");/* wtf */
1.167     brouard  10335: #endif
                   10336: 
1.169     brouard  10337: #if defined(__GNUC__)
                   10338: # if defined(__GNUC_PATCHLEVEL__)
                   10339: #  define __GNUC_VERSION__ (__GNUC__ * 10000 \
                   10340:                             + __GNUC_MINOR__ * 100 \
                   10341:                             + __GNUC_PATCHLEVEL__)
                   10342: # else
                   10343: #  define __GNUC_VERSION__ (__GNUC__ * 10000 \
                   10344:                             + __GNUC_MINOR__ * 100)
                   10345: # endif
1.174     brouard  10346:    printf(" using GNU C version %d.\n", __GNUC_VERSION__);
1.191     brouard  10347:    if(logged) fprintf(ficlog, " using GNU C version %d.\n", __GNUC_VERSION__);
1.176     brouard  10348: 
                   10349:    if (uname(&sysInfo) != -1) {
                   10350:      printf("Running on: %s %s %s %s %s\n",sysInfo.sysname, sysInfo.nodename, sysInfo.release, sysInfo.version, sysInfo.machine);
1.191     brouard  10351:         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  10352:    }
                   10353:    else
                   10354:       perror("uname() error");
1.179     brouard  10355:    //#ifndef __INTEL_COMPILER 
                   10356: #if !defined (__INTEL_COMPILER) && !defined(__APPLE__)
1.174     brouard  10357:    printf("GNU libc version: %s\n", gnu_get_libc_version()); 
1.191     brouard  10358:    if(logged) fprintf(ficlog,"GNU libc version: %s\n", gnu_get_libc_version());
1.177     brouard  10359: #endif
1.169     brouard  10360: #endif
1.172     brouard  10361: 
1.286     brouard  10362:    //   void main ()
1.172     brouard  10363:    //   {
1.169     brouard  10364: #if defined(_MSC_VER)
1.174     brouard  10365:    if (IsWow64()){
1.191     brouard  10366:           printf("\nThe program (probably compiled for 32bit) is running under WOW64 (64bit) emulation.\n");
                   10367:           if (logged) fprintf(ficlog, "\nThe program (probably compiled for 32bit) is running under WOW64 (64bit) emulation.\n");
1.174     brouard  10368:    }
                   10369:    else{
1.191     brouard  10370:           printf("\nThe program is not running under WOW64 (i.e probably on a 64bit Windows).\n");
                   10371:           if (logged) fprintf(ficlog, "\nThe programm is not running under WOW64 (i.e probably on a 64bit Windows).\n");
1.174     brouard  10372:    }
1.172     brouard  10373:    //     printf("\nPress Enter to continue...");
                   10374:    //     getchar();
                   10375:    //   }
                   10376: 
1.169     brouard  10377: #endif
                   10378:    
1.167     brouard  10379: 
1.219     brouard  10380: }
1.136     brouard  10381: 
1.219     brouard  10382: int prevalence_limit(double *p, double **prlim, double ageminpar, double agemaxpar, double ftolpl, int *ncvyearp){
1.288     brouard  10383:   /*--------------- Prevalence limit  (forward period or forward stable prevalence) --------------*/
1.235     brouard  10384:   int i, j, k, i1, k4=0, nres=0 ;
1.202     brouard  10385:   /* double ftolpl = 1.e-10; */
1.180     brouard  10386:   double age, agebase, agelim;
1.203     brouard  10387:   double tot;
1.180     brouard  10388: 
1.202     brouard  10389:   strcpy(filerespl,"PL_");
                   10390:   strcat(filerespl,fileresu);
                   10391:   if((ficrespl=fopen(filerespl,"w"))==NULL) {
1.288     brouard  10392:     printf("Problem with forward period (stable) prevalence resultfile: %s\n", filerespl);return 1;
                   10393:     fprintf(ficlog,"Problem with forward period (stable) prevalence resultfile: %s\n", filerespl);return 1;
1.202     brouard  10394:   }
1.288     brouard  10395:   printf("\nComputing forward period (stable) prevalence: result on file '%s' \n", filerespl);
                   10396:   fprintf(ficlog,"\nComputing forward period (stable) prevalence: result on file '%s' \n", filerespl);
1.202     brouard  10397:   pstamp(ficrespl);
1.288     brouard  10398:   fprintf(ficrespl,"# Forward period (stable) prevalence. Precision given by ftolpl=%g \n", ftolpl);
1.202     brouard  10399:   fprintf(ficrespl,"#Age ");
                   10400:   for(i=1; i<=nlstate;i++) fprintf(ficrespl,"%d-%d ",i,i);
                   10401:   fprintf(ficrespl,"\n");
1.180     brouard  10402:   
1.219     brouard  10403:   /* prlim=matrix(1,nlstate,1,nlstate);*/ /* back in main */
1.180     brouard  10404: 
1.219     brouard  10405:   agebase=ageminpar;
                   10406:   agelim=agemaxpar;
1.180     brouard  10407: 
1.227     brouard  10408:   /* i1=pow(2,ncoveff); */
1.234     brouard  10409:   i1=pow(2,cptcoveff); /* Number of combination of dummy covariates */
1.219     brouard  10410:   if (cptcovn < 1){i1=1;}
1.180     brouard  10411: 
1.238     brouard  10412:   for(k=1; k<=i1;k++){ /* For each combination k of dummy covariates in the model */
                   10413:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.253     brouard  10414:       if(i1 != 1 && TKresult[nres]!= k)
1.238     brouard  10415:        continue;
1.235     brouard  10416: 
1.238     brouard  10417:       /* for(cptcov=1,k=0;cptcov<=i1;cptcov++){ */
                   10418:       /* for(cptcov=1,k=0;cptcov<=1;cptcov++){ */
                   10419:       //for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){
                   10420:       /* k=k+1; */
                   10421:       /* to clean */
                   10422:       //printf("cptcov=%d cptcod=%d codtab=%d\n",cptcov, cptcod,codtabm(cptcod,cptcov));
                   10423:       fprintf(ficrespl,"#******");
                   10424:       printf("#******");
                   10425:       fprintf(ficlog,"#******");
                   10426:       for(j=1;j<=cptcoveff ;j++) {/* all covariates */
                   10427:        fprintf(ficrespl," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]); /* Here problem for varying dummy*/
                   10428:        printf(" V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   10429:        fprintf(ficlog," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   10430:       }
                   10431:       for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
                   10432:        printf(" V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
                   10433:        fprintf(ficrespl," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
                   10434:        fprintf(ficlog," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
                   10435:       }
                   10436:       fprintf(ficrespl,"******\n");
                   10437:       printf("******\n");
                   10438:       fprintf(ficlog,"******\n");
                   10439:       if(invalidvarcomb[k]){
                   10440:        printf("\nCombination (%d) ignored because no case \n",k); 
                   10441:        fprintf(ficrespl,"#Combination (%d) ignored because no case \n",k); 
                   10442:        fprintf(ficlog,"\nCombination (%d) ignored because no case \n",k); 
                   10443:        continue;
                   10444:       }
1.219     brouard  10445: 
1.238     brouard  10446:       fprintf(ficrespl,"#Age ");
                   10447:       for(j=1;j<=cptcoveff;j++) {
                   10448:        fprintf(ficrespl,"V%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   10449:       }
                   10450:       for(i=1; i<=nlstate;i++) fprintf(ficrespl,"  %d-%d   ",i,i);
                   10451:       fprintf(ficrespl,"Total Years_to_converge\n");
1.227     brouard  10452:     
1.238     brouard  10453:       for (age=agebase; age<=agelim; age++){
                   10454:        /* for (age=agebase; age<=agebase; age++){ */
                   10455:        prevalim(prlim, nlstate, p, age, oldm, savm, ftolpl, ncvyearp, k, nres);
                   10456:        fprintf(ficrespl,"%.0f ",age );
                   10457:        for(j=1;j<=cptcoveff;j++)
                   10458:          fprintf(ficrespl,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   10459:        tot=0.;
                   10460:        for(i=1; i<=nlstate;i++){
                   10461:          tot +=  prlim[i][i];
                   10462:          fprintf(ficrespl," %.5f", prlim[i][i]);
                   10463:        }
                   10464:        fprintf(ficrespl," %.3f %d\n", tot, *ncvyearp);
                   10465:       } /* Age */
                   10466:       /* was end of cptcod */
                   10467:     } /* cptcov */
                   10468:   } /* nres */
1.219     brouard  10469:   return 0;
1.180     brouard  10470: }
                   10471: 
1.218     brouard  10472: 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  10473:        /*--------------- Back Prevalence limit  (backward stable prevalence) --------------*/
1.218     brouard  10474:        
                   10475:        /* Computes the back prevalence limit  for any combination      of covariate values 
                   10476:    * at any age between ageminpar and agemaxpar
                   10477:         */
1.235     brouard  10478:   int i, j, k, i1, nres=0 ;
1.217     brouard  10479:   /* double ftolpl = 1.e-10; */
                   10480:   double age, agebase, agelim;
                   10481:   double tot;
1.218     brouard  10482:   /* double ***mobaverage; */
                   10483:   /* double     **dnewm, **doldm, **dsavm;  /\* for use *\/ */
1.217     brouard  10484: 
                   10485:   strcpy(fileresplb,"PLB_");
                   10486:   strcat(fileresplb,fileresu);
                   10487:   if((ficresplb=fopen(fileresplb,"w"))==NULL) {
1.288     brouard  10488:     printf("Problem with backward prevalence resultfile: %s\n", fileresplb);return 1;
                   10489:     fprintf(ficlog,"Problem with backward prevalence resultfile: %s\n", fileresplb);return 1;
1.217     brouard  10490:   }
1.288     brouard  10491:   printf("Computing backward prevalence: result on file '%s' \n", fileresplb);
                   10492:   fprintf(ficlog,"Computing backward prevalence: result on file '%s' \n", fileresplb);
1.217     brouard  10493:   pstamp(ficresplb);
1.288     brouard  10494:   fprintf(ficresplb,"# Backward prevalence. Precision given by ftolpl=%g \n", ftolpl);
1.217     brouard  10495:   fprintf(ficresplb,"#Age ");
                   10496:   for(i=1; i<=nlstate;i++) fprintf(ficresplb,"%d-%d ",i,i);
                   10497:   fprintf(ficresplb,"\n");
                   10498:   
1.218     brouard  10499:   
                   10500:   /* prlim=matrix(1,nlstate,1,nlstate);*/ /* back in main */
                   10501:   
                   10502:   agebase=ageminpar;
                   10503:   agelim=agemaxpar;
                   10504:   
                   10505:   
1.227     brouard  10506:   i1=pow(2,cptcoveff);
1.218     brouard  10507:   if (cptcovn < 1){i1=1;}
1.227     brouard  10508:   
1.238     brouard  10509:   for(nres=1; nres <= nresult; nres++){ /* For each resultline */
                   10510:     for(k=1; k<=i1;k++){ /* For any combination of dummy covariates, fixed and varying */
1.253     brouard  10511:      if(i1 != 1 && TKresult[nres]!= k)
1.238     brouard  10512:        continue;
                   10513:       //printf("cptcov=%d cptcod=%d codtab=%d\n",cptcov, cptcod,codtabm(cptcod,cptcov));
                   10514:       fprintf(ficresplb,"#******");
                   10515:       printf("#******");
                   10516:       fprintf(ficlog,"#******");
                   10517:       for(j=1;j<=cptcoveff ;j++) {/* all covariates */
                   10518:        fprintf(ficresplb," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   10519:        printf(" V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   10520:        fprintf(ficlog," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   10521:       }
                   10522:       for (j=1; j<= nsq; j++){ /* For each selected (single) quantitative value */
                   10523:        printf(" V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]);
                   10524:        fprintf(ficresplb," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]);
                   10525:        fprintf(ficlog," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]);
                   10526:       }
                   10527:       fprintf(ficresplb,"******\n");
                   10528:       printf("******\n");
                   10529:       fprintf(ficlog,"******\n");
                   10530:       if(invalidvarcomb[k]){
                   10531:        printf("\nCombination (%d) ignored because no cases \n",k); 
                   10532:        fprintf(ficresplb,"#Combination (%d) ignored because no cases \n",k); 
                   10533:        fprintf(ficlog,"\nCombination (%d) ignored because no cases \n",k); 
                   10534:        continue;
                   10535:       }
1.218     brouard  10536:     
1.238     brouard  10537:       fprintf(ficresplb,"#Age ");
                   10538:       for(j=1;j<=cptcoveff;j++) {
                   10539:        fprintf(ficresplb,"V%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   10540:       }
                   10541:       for(i=1; i<=nlstate;i++) fprintf(ficresplb,"  %d-%d   ",i,i);
                   10542:       fprintf(ficresplb,"Total Years_to_converge\n");
1.218     brouard  10543:     
                   10544:     
1.238     brouard  10545:       for (age=agebase; age<=agelim; age++){
                   10546:        /* for (age=agebase; age<=agebase; age++){ */
                   10547:        if(mobilavproj > 0){
                   10548:          /* bprevalim(bprlim, mobaverage, nlstate, p, age, ageminpar, agemaxpar, oldm, savm, doldm, dsavm, ftolpl, ncvyearp, k); */
                   10549:          /* bprevalim(bprlim, mobaverage, nlstate, p, age, oldm, savm, dnewm, doldm, dsavm, ftolpl, ncvyearp, k); */
1.242     brouard  10550:          bprevalim(bprlim, mobaverage, nlstate, p, age, ftolpl, ncvyearp, k, nres);
1.238     brouard  10551:        }else if (mobilavproj == 0){
                   10552:          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);
                   10553:          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);
                   10554:          exit(1);
                   10555:        }else{
                   10556:          /* bprevalim(bprlim, probs, nlstate, p, age, oldm, savm, dnewm, doldm, dsavm, ftolpl, ncvyearp, k); */
1.242     brouard  10557:          bprevalim(bprlim, probs, nlstate, p, age, ftolpl, ncvyearp, k,nres);
1.266     brouard  10558:          /* printf("TOTOT\n"); */
                   10559:           /* exit(1); */
1.238     brouard  10560:        }
                   10561:        fprintf(ficresplb,"%.0f ",age );
                   10562:        for(j=1;j<=cptcoveff;j++)
                   10563:          fprintf(ficresplb,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   10564:        tot=0.;
                   10565:        for(i=1; i<=nlstate;i++){
                   10566:          tot +=  bprlim[i][i];
                   10567:          fprintf(ficresplb," %.5f", bprlim[i][i]);
                   10568:        }
                   10569:        fprintf(ficresplb," %.3f %d\n", tot, *ncvyearp);
                   10570:       } /* Age */
                   10571:       /* was end of cptcod */
1.255     brouard  10572:       /*fprintf(ficresplb,"\n");*/ /* Seems to be necessary for gnuplot only if two result lines and no covariate. */
1.238     brouard  10573:     } /* end of any combination */
                   10574:   } /* end of nres */  
1.218     brouard  10575:   /* hBijx(p, bage, fage); */
                   10576:   /* fclose(ficrespijb); */
                   10577:   
                   10578:   return 0;
1.217     brouard  10579: }
1.218     brouard  10580:  
1.180     brouard  10581: int hPijx(double *p, int bage, int fage){
                   10582:     /*------------- h Pij x at various ages ------------*/
                   10583: 
                   10584:   int stepsize;
                   10585:   int agelim;
                   10586:   int hstepm;
                   10587:   int nhstepm;
1.235     brouard  10588:   int h, i, i1, j, k, k4, nres=0;
1.180     brouard  10589: 
                   10590:   double agedeb;
                   10591:   double ***p3mat;
                   10592: 
1.201     brouard  10593:     strcpy(filerespij,"PIJ_");  strcat(filerespij,fileresu);
1.180     brouard  10594:     if((ficrespij=fopen(filerespij,"w"))==NULL) {
                   10595:       printf("Problem with Pij resultfile: %s\n", filerespij); return 1;
                   10596:       fprintf(ficlog,"Problem with Pij resultfile: %s\n", filerespij); return 1;
                   10597:     }
                   10598:     printf("Computing pij: result on file '%s' \n", filerespij);
                   10599:     fprintf(ficlog,"Computing pij: result on file '%s' \n", filerespij);
                   10600:   
                   10601:     stepsize=(int) (stepm+YEARM-1)/YEARM;
                   10602:     /*if (stepm<=24) stepsize=2;*/
                   10603: 
                   10604:     agelim=AGESUP;
                   10605:     hstepm=stepsize*YEARM; /* Every year of age */
                   10606:     hstepm=hstepm/stepm; /* Typically 2 years, = 2/6 months = 4 */ 
1.218     brouard  10607:                
1.180     brouard  10608:     /* hstepm=1;   aff par mois*/
                   10609:     pstamp(ficrespij);
                   10610:     fprintf(ficrespij,"#****** h Pij x Probability to be in state j at age x+h being in i at x ");
1.227     brouard  10611:     i1= pow(2,cptcoveff);
1.218     brouard  10612:                /* for(cptcov=1,k=0;cptcov<=i1;cptcov++){ */
                   10613:                /*    /\*for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*\/ */
                   10614:                /*      k=k+1;  */
1.235     brouard  10615:     for(nres=1; nres <= nresult; nres++) /* For each resultline */
                   10616:     for(k=1; k<=i1;k++){
1.253     brouard  10617:       if(i1 != 1 && TKresult[nres]!= k)
1.235     brouard  10618:        continue;
1.183     brouard  10619:       fprintf(ficrespij,"\n#****** ");
1.227     brouard  10620:       for(j=1;j<=cptcoveff;j++) 
1.198     brouard  10621:        fprintf(ficrespij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
1.235     brouard  10622:       for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
                   10623:        printf(" V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
                   10624:        fprintf(ficrespij," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
                   10625:       }
1.183     brouard  10626:       fprintf(ficrespij,"******\n");
                   10627:       
                   10628:       for (agedeb=fage; agedeb>=bage; agedeb--){ /* If stepm=6 months */
                   10629:        nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */ 
                   10630:        nhstepm = nhstepm/hstepm; /* Typically 40/4=10 */
                   10631:        
                   10632:        /*        nhstepm=nhstepm*YEARM; aff par mois*/
1.180     brouard  10633:        
1.183     brouard  10634:        p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   10635:        oldm=oldms;savm=savms;
1.235     brouard  10636:        hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k, nres);  
1.183     brouard  10637:        fprintf(ficrespij,"# Cov Agex agex+h hpijx with i,j=");
                   10638:        for(i=1; i<=nlstate;i++)
                   10639:          for(j=1; j<=nlstate+ndeath;j++)
                   10640:            fprintf(ficrespij," %1d-%1d",i,j);
                   10641:        fprintf(ficrespij,"\n");
                   10642:        for (h=0; h<=nhstepm; h++){
                   10643:          /*agedebphstep = agedeb + h*hstepm/YEARM*stepm;*/
                   10644:          fprintf(ficrespij,"%d %3.f %3.f",k, agedeb, agedeb + h*hstepm/YEARM*stepm );
1.180     brouard  10645:          for(i=1; i<=nlstate;i++)
                   10646:            for(j=1; j<=nlstate+ndeath;j++)
1.183     brouard  10647:              fprintf(ficrespij," %.5f", p3mat[i][j][h]);
1.180     brouard  10648:          fprintf(ficrespij,"\n");
                   10649:        }
1.183     brouard  10650:        free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   10651:        fprintf(ficrespij,"\n");
                   10652:       }
1.180     brouard  10653:       /*}*/
                   10654:     }
1.218     brouard  10655:     return 0;
1.180     brouard  10656: }
1.218     brouard  10657:  
                   10658:  int hBijx(double *p, int bage, int fage, double ***prevacurrent){
1.217     brouard  10659:     /*------------- h Bij x at various ages ------------*/
                   10660: 
                   10661:   int stepsize;
1.218     brouard  10662:   /* int agelim; */
                   10663:        int ageminl;
1.217     brouard  10664:   int hstepm;
                   10665:   int nhstepm;
1.238     brouard  10666:   int h, i, i1, j, k, nres;
1.218     brouard  10667:        
1.217     brouard  10668:   double agedeb;
                   10669:   double ***p3mat;
1.218     brouard  10670:        
                   10671:   strcpy(filerespijb,"PIJB_");  strcat(filerespijb,fileresu);
                   10672:   if((ficrespijb=fopen(filerespijb,"w"))==NULL) {
                   10673:     printf("Problem with Pij back resultfile: %s\n", filerespijb); return 1;
                   10674:     fprintf(ficlog,"Problem with Pij back resultfile: %s\n", filerespijb); return 1;
                   10675:   }
                   10676:   printf("Computing pij back: result on file '%s' \n", filerespijb);
                   10677:   fprintf(ficlog,"Computing pij back: result on file '%s' \n", filerespijb);
                   10678:   
                   10679:   stepsize=(int) (stepm+YEARM-1)/YEARM;
                   10680:   /*if (stepm<=24) stepsize=2;*/
1.217     brouard  10681:   
1.218     brouard  10682:   /* agelim=AGESUP; */
1.289     brouard  10683:   ageminl=AGEINF; /* was 30 */
1.218     brouard  10684:   hstepm=stepsize*YEARM; /* Every year of age */
                   10685:   hstepm=hstepm/stepm; /* Typically 2 years, = 2/6 months = 4 */
                   10686:   
                   10687:   /* hstepm=1;   aff par mois*/
                   10688:   pstamp(ficrespijb);
1.255     brouard  10689:   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  10690:   i1= pow(2,cptcoveff);
1.218     brouard  10691:   /* for(cptcov=1,k=0;cptcov<=i1;cptcov++){ */
                   10692:   /*    /\*for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*\/ */
                   10693:   /*   k=k+1;  */
1.238     brouard  10694:   for(nres=1; nres <= nresult; nres++){ /* For each resultline */
                   10695:     for(k=1; k<=i1;k++){ /* For any combination of dummy covariates, fixed and varying */
1.253     brouard  10696:       if(i1 != 1 && TKresult[nres]!= k)
1.238     brouard  10697:        continue;
                   10698:       fprintf(ficrespijb,"\n#****** ");
                   10699:       for(j=1;j<=cptcoveff;j++)
                   10700:        fprintf(ficrespijb,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   10701:       for (j=1; j<= nsq; j++){ /* For each selected (single) quantitative value */
                   10702:        fprintf(ficrespijb," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]);
                   10703:       }
                   10704:       fprintf(ficrespijb,"******\n");
1.264     brouard  10705:       if(invalidvarcomb[k]){  /* Is it necessary here? */
1.238     brouard  10706:        fprintf(ficrespijb,"\n#Combination (%d) ignored because no cases \n",k); 
                   10707:        continue;
                   10708:       }
                   10709:       
                   10710:       /* for (agedeb=fage; agedeb>=bage; agedeb--){ /\* If stepm=6 months *\/ */
                   10711:       for (agedeb=bage; agedeb<=fage; agedeb++){ /* If stepm=6 months and estepm=24 (2 years) */
                   10712:        /* nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm); /\* Typically 20 years = 20*12/6=40 *\/ */
                   10713:        nhstepm=(int) rint((agedeb-ageminl)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */
                   10714:        nhstepm = nhstepm/hstepm; /* Typically 40/4=10, because estepm=24 stepm=6 => hstepm=24/6=4 */
                   10715:        
                   10716:        /*        nhstepm=nhstepm*YEARM; aff par mois*/
                   10717:        
1.266     brouard  10718:        p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm); /* We can't have it at an upper level because of nhstepm */
                   10719:        /* and memory limitations if stepm is small */
                   10720: 
1.238     brouard  10721:        /* oldm=oldms;savm=savms; */
                   10722:        /* hbxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);   */
1.267     brouard  10723:        hbxij(p3mat,nhstepm,agedeb,hstepm,p,prevacurrent,nlstate,stepm, k, nres);
1.238     brouard  10724:        /* hbxij(p3mat,nhstepm,agedeb,hstepm,p,prevacurrent,nlstate,stepm,oldm,savm, dnewm, doldm, dsavm, k); */
1.255     brouard  10725:        fprintf(ficrespijb,"# Cov Agex agex-h hbijx with i,j=");
1.217     brouard  10726:        for(i=1; i<=nlstate;i++)
                   10727:          for(j=1; j<=nlstate+ndeath;j++)
1.238     brouard  10728:            fprintf(ficrespijb," %1d-%1d",i,j);
1.217     brouard  10729:        fprintf(ficrespijb,"\n");
1.238     brouard  10730:        for (h=0; h<=nhstepm; h++){
                   10731:          /*agedebphstep = agedeb + h*hstepm/YEARM*stepm;*/
                   10732:          fprintf(ficrespijb,"%d %3.f %3.f",k, agedeb, agedeb - h*hstepm/YEARM*stepm );
                   10733:          /* fprintf(ficrespijb,"%d %3.f %3.f",k, agedeb, agedeb + h*hstepm/YEARM*stepm ); */
                   10734:          for(i=1; i<=nlstate;i++)
                   10735:            for(j=1; j<=nlstate+ndeath;j++)
                   10736:              fprintf(ficrespijb," %.5f", p3mat[i][j][h]);
                   10737:          fprintf(ficrespijb,"\n");
                   10738:        }
                   10739:        free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   10740:        fprintf(ficrespijb,"\n");
                   10741:       } /* end age deb */
                   10742:     } /* end combination */
                   10743:   } /* end nres */
1.218     brouard  10744:   return 0;
                   10745:  } /*  hBijx */
1.217     brouard  10746: 
1.180     brouard  10747: 
1.136     brouard  10748: /***********************************************/
                   10749: /**************** Main Program *****************/
                   10750: /***********************************************/
                   10751: 
                   10752: int main(int argc, char *argv[])
                   10753: {
                   10754: #ifdef GSL
                   10755:   const gsl_multimin_fminimizer_type *T;
                   10756:   size_t iteri = 0, it;
                   10757:   int rval = GSL_CONTINUE;
                   10758:   int status = GSL_SUCCESS;
                   10759:   double ssval;
                   10760: #endif
                   10761:   int movingaverage(double ***probs, double bage,double fage, double ***mobaverage, int mobilav);
1.290     brouard  10762:   int i,j, k, iter=0,m,size=100, cptcod; /* Suppressing because nobs */
                   10763:   /* int i,j, k, n=MAXN,iter=0,m,size=100, cptcod; */
1.209     brouard  10764:   int ncvyear=0; /* Number of years needed for the period prevalence to converge */
1.164     brouard  10765:   int jj, ll, li, lj, lk;
1.136     brouard  10766:   int numlinepar=0; /* Current linenumber of parameter file */
1.197     brouard  10767:   int num_filled;
1.136     brouard  10768:   int itimes;
                   10769:   int NDIM=2;
                   10770:   int vpopbased=0;
1.235     brouard  10771:   int nres=0;
1.258     brouard  10772:   int endishere=0;
1.277     brouard  10773:   int noffset=0;
1.274     brouard  10774:   int ncurrv=0; /* Temporary variable */
                   10775:   
1.164     brouard  10776:   char ca[32], cb[32];
1.136     brouard  10777:   /*  FILE *fichtm; *//* Html File */
                   10778:   /* FILE *ficgp;*/ /*Gnuplot File */
                   10779:   struct stat info;
1.191     brouard  10780:   double agedeb=0.;
1.194     brouard  10781: 
                   10782:   double ageminpar=AGEOVERFLOW,agemin=AGEOVERFLOW, agemaxpar=-AGEOVERFLOW, agemax=-AGEOVERFLOW;
1.219     brouard  10783:   double ageminout=-AGEOVERFLOW,agemaxout=AGEOVERFLOW; /* Smaller Age range redefined after movingaverage */
1.136     brouard  10784: 
1.165     brouard  10785:   double fret;
1.191     brouard  10786:   double dum=0.; /* Dummy variable */
1.136     brouard  10787:   double ***p3mat;
1.218     brouard  10788:   /* double ***mobaverage; */
1.164     brouard  10789: 
                   10790:   char line[MAXLINE];
1.197     brouard  10791:   char path[MAXLINE],pathc[MAXLINE],pathcd[MAXLINE],pathtot[MAXLINE];
                   10792: 
1.234     brouard  10793:   char  modeltemp[MAXLINE];
1.230     brouard  10794:   char resultline[MAXLINE];
                   10795:   
1.136     brouard  10796:   char pathr[MAXLINE], pathimach[MAXLINE]; 
1.164     brouard  10797:   char *tok, *val; /* pathtot */
1.290     brouard  10798:   int firstobs=1, lastobs=10; /* nobs = lastobs-firstobs declared globally ;*/
1.195     brouard  10799:   int c,  h , cpt, c2;
1.191     brouard  10800:   int jl=0;
                   10801:   int i1, j1, jk, stepsize=0;
1.194     brouard  10802:   int count=0;
                   10803: 
1.164     brouard  10804:   int *tab; 
1.136     brouard  10805:   int mobilavproj=0 , prevfcast=0 ; /* moving average of prev, If prevfcast=1 prevalence projection */
1.293   ! brouard  10806:   int backcast=0; /* defined as global for mlikeli and mle*/
1.136     brouard  10807:   int mobilav=0,popforecast=0;
1.191     brouard  10808:   int hstepm=0, nhstepm=0;
1.136     brouard  10809:   int agemortsup;
                   10810:   float  sumlpop=0.;
                   10811:   double jprev1=1, mprev1=1,anprev1=2000,jprev2=1, mprev2=1,anprev2=2000;
                   10812:   double jpyram=1, mpyram=1,anpyram=2000,jpyram1=1, mpyram1=1,anpyram1=2000;
                   10813: 
1.191     brouard  10814:   double bage=0, fage=110., age, agelim=0., agebase=0.;
1.136     brouard  10815:   double ftolpl=FTOL;
                   10816:   double **prlim;
1.217     brouard  10817:   double **bprlim;
1.136     brouard  10818:   double ***param; /* Matrix of parameters */
1.251     brouard  10819:   double ***paramstart; /* Matrix of starting parameter values */
                   10820:   double  *p, *pstart; /* p=param[1][1] pstart is for starting values guessed by freqsummary */
1.136     brouard  10821:   double **matcov; /* Matrix of covariance */
1.203     brouard  10822:   double **hess; /* Hessian matrix */
1.136     brouard  10823:   double ***delti3; /* Scale */
                   10824:   double *delti; /* Scale */
                   10825:   double ***eij, ***vareij;
                   10826:   double **varpl; /* Variances of prevalence limits by age */
1.269     brouard  10827: 
1.136     brouard  10828:   double *epj, vepp;
1.164     brouard  10829: 
1.273     brouard  10830:   double dateprev1, dateprev2;
                   10831:   double jproj1=1,mproj1=1,anproj1=2000,jproj2=1,mproj2=1,anproj2=2000, dateproj1=0, dateproj2=0;
                   10832:   double jback1=1,mback1=1,anback1=2000,jback2=1,mback2=1,anback2=2000, dateback1=0, dateback2=0;
1.217     brouard  10833: 
1.136     brouard  10834:   double **ximort;
1.145     brouard  10835:   char *alph[]={"a","a","b","c","d","e"}, str[4]="1234";
1.136     brouard  10836:   int *dcwave;
                   10837: 
1.164     brouard  10838:   char z[1]="c";
1.136     brouard  10839: 
                   10840:   /*char  *strt;*/
                   10841:   char strtend[80];
1.126     brouard  10842: 
1.164     brouard  10843: 
1.126     brouard  10844: /*   setlocale (LC_ALL, ""); */
                   10845: /*   bindtextdomain (PACKAGE, LOCALEDIR); */
                   10846: /*   textdomain (PACKAGE); */
                   10847: /*   setlocale (LC_CTYPE, ""); */
                   10848: /*   setlocale (LC_MESSAGES, ""); */
                   10849: 
                   10850:   /*   gettimeofday(&start_time, (struct timezone*)0); */ /* at first time */
1.157     brouard  10851:   rstart_time = time(NULL);  
                   10852:   /*  (void) gettimeofday(&start_time,&tzp);*/
                   10853:   start_time = *localtime(&rstart_time);
1.126     brouard  10854:   curr_time=start_time;
1.157     brouard  10855:   /*tml = *localtime(&start_time.tm_sec);*/
                   10856:   /* strcpy(strstart,asctime(&tml)); */
                   10857:   strcpy(strstart,asctime(&start_time));
1.126     brouard  10858: 
                   10859: /*  printf("Localtime (at start)=%s",strstart); */
1.157     brouard  10860: /*  tp.tm_sec = tp.tm_sec +86400; */
                   10861: /*  tm = *localtime(&start_time.tm_sec); */
1.126     brouard  10862: /*   tmg.tm_year=tmg.tm_year +dsign*dyear; */
                   10863: /*   tmg.tm_mon=tmg.tm_mon +dsign*dmonth; */
                   10864: /*   tmg.tm_hour=tmg.tm_hour + 1; */
1.157     brouard  10865: /*   tp.tm_sec = mktime(&tmg); */
1.126     brouard  10866: /*   strt=asctime(&tmg); */
                   10867: /*   printf("Time(after) =%s",strstart);  */
                   10868: /*  (void) time (&time_value);
                   10869: *  printf("time=%d,t-=%d\n",time_value,time_value-86400);
                   10870: *  tm = *localtime(&time_value);
                   10871: *  strstart=asctime(&tm);
                   10872: *  printf("tim_value=%d,asctime=%s\n",time_value,strstart); 
                   10873: */
                   10874: 
                   10875:   nberr=0; /* Number of errors and warnings */
                   10876:   nbwarn=0;
1.184     brouard  10877: #ifdef WIN32
                   10878:   _getcwd(pathcd, size);
                   10879: #else
1.126     brouard  10880:   getcwd(pathcd, size);
1.184     brouard  10881: #endif
1.191     brouard  10882:   syscompilerinfo(0);
1.196     brouard  10883:   printf("\nIMaCh version %s, %s\n%s",version, copyright, fullversion);
1.126     brouard  10884:   if(argc <=1){
                   10885:     printf("\nEnter the parameter file name: ");
1.205     brouard  10886:     if(!fgets(pathr,FILENAMELENGTH,stdin)){
                   10887:       printf("ERROR Empty parameter file name\n");
                   10888:       goto end;
                   10889:     }
1.126     brouard  10890:     i=strlen(pathr);
                   10891:     if(pathr[i-1]=='\n')
                   10892:       pathr[i-1]='\0';
1.156     brouard  10893:     i=strlen(pathr);
1.205     brouard  10894:     if(i >= 1 && pathr[i-1]==' ') {/* This may happen when dragging on oS/X! */
1.156     brouard  10895:       pathr[i-1]='\0';
1.205     brouard  10896:     }
                   10897:     i=strlen(pathr);
                   10898:     if( i==0 ){
                   10899:       printf("ERROR Empty parameter file name\n");
                   10900:       goto end;
                   10901:     }
                   10902:     for (tok = pathr; tok != NULL; ){
1.126     brouard  10903:       printf("Pathr |%s|\n",pathr);
                   10904:       while ((val = strsep(&tok, "\"" )) != NULL && *val == '\0');
                   10905:       printf("val= |%s| pathr=%s\n",val,pathr);
                   10906:       strcpy (pathtot, val);
                   10907:       if(pathr[0] == '\0') break; /* Dirty */
                   10908:     }
                   10909:   }
1.281     brouard  10910:   else if (argc<=2){
                   10911:     strcpy(pathtot,argv[1]);
                   10912:   }
1.126     brouard  10913:   else{
                   10914:     strcpy(pathtot,argv[1]);
1.281     brouard  10915:     strcpy(z,argv[2]);
                   10916:     printf("\nargv[2]=%s z=%c\n",argv[2],z[0]);
1.126     brouard  10917:   }
                   10918:   /*if(getcwd(pathcd, MAXLINE)!= NULL)printf ("Error pathcd\n");*/
                   10919:   /*cygwin_split_path(pathtot,path,optionfile);
                   10920:     printf("pathtot=%s, path=%s, optionfile=%s\n",pathtot,path,optionfile);*/
                   10921:   /* cutv(path,optionfile,pathtot,'\\');*/
                   10922: 
                   10923:   /* Split argv[0], imach program to get pathimach */
                   10924:   printf("\nargv[0]=%s argv[1]=%s, \n",argv[0],argv[1]);
                   10925:   split(argv[0],pathimach,optionfile,optionfilext,optionfilefiname);
                   10926:   printf("\nargv[0]=%s pathimach=%s, \noptionfile=%s \noptionfilext=%s \noptionfilefiname=%s\n",argv[0],pathimach,optionfile,optionfilext,optionfilefiname);
                   10927:  /*   strcpy(pathimach,argv[0]); */
                   10928:   /* Split argv[1]=pathtot, parameter file name to get path, optionfile, extension and name */
                   10929:   split(pathtot,path,optionfile,optionfilext,optionfilefiname);
                   10930:   printf("\npathtot=%s,\npath=%s,\noptionfile=%s \noptionfilext=%s \noptionfilefiname=%s\n",pathtot,path,optionfile,optionfilext,optionfilefiname);
1.184     brouard  10931: #ifdef WIN32
                   10932:   _chdir(path); /* Can be a relative path */
                   10933:   if(_getcwd(pathcd,MAXLINE) > 0) /* So pathcd is the full path */
                   10934: #else
1.126     brouard  10935:   chdir(path); /* Can be a relative path */
1.184     brouard  10936:   if (getcwd(pathcd, MAXLINE) > 0) /* So pathcd is the full path */
                   10937: #endif
                   10938:   printf("Current directory %s!\n",pathcd);
1.126     brouard  10939:   strcpy(command,"mkdir ");
                   10940:   strcat(command,optionfilefiname);
                   10941:   if((outcmd=system(command)) != 0){
1.169     brouard  10942:     printf("Directory already exists (or can't create it) %s%s, err=%d\n",path,optionfilefiname,outcmd);
1.126     brouard  10943:     /* fprintf(ficlog,"Problem creating directory %s%s\n",path,optionfilefiname); */
                   10944:     /* fclose(ficlog); */
                   10945: /*     exit(1); */
                   10946:   }
                   10947: /*   if((imk=mkdir(optionfilefiname))<0){ */
                   10948: /*     perror("mkdir"); */
                   10949: /*   } */
                   10950: 
                   10951:   /*-------- arguments in the command line --------*/
                   10952: 
1.186     brouard  10953:   /* Main Log file */
1.126     brouard  10954:   strcat(filelog, optionfilefiname);
                   10955:   strcat(filelog,".log");    /* */
                   10956:   if((ficlog=fopen(filelog,"w"))==NULL)    {
                   10957:     printf("Problem with logfile %s\n",filelog);
                   10958:     goto end;
                   10959:   }
                   10960:   fprintf(ficlog,"Log filename:%s\n",filelog);
1.197     brouard  10961:   fprintf(ficlog,"Version %s %s",version,fullversion);
1.126     brouard  10962:   fprintf(ficlog,"\nEnter the parameter file name: \n");
                   10963:   fprintf(ficlog,"pathimach=%s\npathtot=%s\n\
                   10964:  path=%s \n\
                   10965:  optionfile=%s\n\
                   10966:  optionfilext=%s\n\
1.156     brouard  10967:  optionfilefiname='%s'\n",pathimach,pathtot,path,optionfile,optionfilext,optionfilefiname);
1.126     brouard  10968: 
1.197     brouard  10969:   syscompilerinfo(1);
1.167     brouard  10970: 
1.126     brouard  10971:   printf("Local time (at start):%s",strstart);
                   10972:   fprintf(ficlog,"Local time (at start): %s",strstart);
                   10973:   fflush(ficlog);
                   10974: /*   (void) gettimeofday(&curr_time,&tzp); */
1.157     brouard  10975: /*   printf("Elapsed time %d\n", asc_diff_time(curr_time.tm_sec-start_time.tm_sec,tmpout)); */
1.126     brouard  10976: 
                   10977:   /* */
                   10978:   strcpy(fileres,"r");
                   10979:   strcat(fileres, optionfilefiname);
1.201     brouard  10980:   strcat(fileresu, optionfilefiname); /* Without r in front */
1.126     brouard  10981:   strcat(fileres,".txt");    /* Other files have txt extension */
1.201     brouard  10982:   strcat(fileresu,".txt");    /* Other files have txt extension */
1.126     brouard  10983: 
1.186     brouard  10984:   /* Main ---------arguments file --------*/
1.126     brouard  10985: 
                   10986:   if((ficpar=fopen(optionfile,"r"))==NULL)    {
1.155     brouard  10987:     printf("Problem with optionfile '%s' with errno='%s'\n",optionfile,strerror(errno));
                   10988:     fprintf(ficlog,"Problem with optionfile '%s' with errno='%s'\n",optionfile,strerror(errno));
1.126     brouard  10989:     fflush(ficlog);
1.149     brouard  10990:     /* goto end; */
                   10991:     exit(70); 
1.126     brouard  10992:   }
                   10993: 
                   10994:   strcpy(filereso,"o");
1.201     brouard  10995:   strcat(filereso,fileresu);
1.126     brouard  10996:   if((ficparo=fopen(filereso,"w"))==NULL) { /* opened on subdirectory */
                   10997:     printf("Problem with Output resultfile: %s\n", filereso);
                   10998:     fprintf(ficlog,"Problem with Output resultfile: %s\n", filereso);
                   10999:     fflush(ficlog);
                   11000:     goto end;
                   11001:   }
1.278     brouard  11002:       /*-------- Rewriting parameter file ----------*/
                   11003:   strcpy(rfileres,"r");    /* "Rparameterfile */
                   11004:   strcat(rfileres,optionfilefiname);    /* Parameter file first name */
                   11005:   strcat(rfileres,".");    /* */
                   11006:   strcat(rfileres,optionfilext);    /* Other files have txt extension */
                   11007:   if((ficres =fopen(rfileres,"w"))==NULL) {
                   11008:     printf("Problem writing new parameter file: %s\n", rfileres);goto end;
                   11009:     fprintf(ficlog,"Problem writing new parameter file: %s\n", rfileres);goto end;
                   11010:     fflush(ficlog);
                   11011:     goto end;
                   11012:   }
                   11013:   fprintf(ficres,"#IMaCh %s\n",version);
1.126     brouard  11014: 
1.278     brouard  11015:                                      
1.126     brouard  11016:   /* Reads comments: lines beginning with '#' */
                   11017:   numlinepar=0;
1.277     brouard  11018:   /* Is it a BOM UTF-8 Windows file? */
                   11019:   /* First parameter line */
1.197     brouard  11020:   while(fgets(line, MAXLINE, ficpar)) {
1.277     brouard  11021:     noffset=0;
                   11022:     if( line[0] == (char)0xEF && line[1] == (char)0xBB) /* EF BB BF */
                   11023:     {
                   11024:       noffset=noffset+3;
                   11025:       printf("# File is an UTF8 Bom.\n"); // 0xBF
                   11026:     }
                   11027:     else if( line[0] == (char)0xFE && line[1] == (char)0xFF)
                   11028:     {
                   11029:       noffset=noffset+2;
                   11030:       printf("# File is an UTF16BE BOM file\n");
                   11031:     }
                   11032:     else if( line[0] == 0 && line[1] == 0)
                   11033:     {
                   11034:       if( line[2] == (char)0xFE && line[3] == (char)0xFF){
                   11035:        noffset=noffset+4;
                   11036:        printf("# File is an UTF16BE BOM file\n");
                   11037:       }
                   11038:     } else{
                   11039:       ;/*printf(" Not a BOM file\n");*/
                   11040:     }
                   11041:   
1.197     brouard  11042:     /* If line starts with a # it is a comment */
1.277     brouard  11043:     if (line[noffset] == '#') {
1.197     brouard  11044:       numlinepar++;
                   11045:       fputs(line,stdout);
                   11046:       fputs(line,ficparo);
1.278     brouard  11047:       fputs(line,ficres);
1.197     brouard  11048:       fputs(line,ficlog);
                   11049:       continue;
                   11050:     }else
                   11051:       break;
                   11052:   }
                   11053:   if((num_filled=sscanf(line,"title=%s datafile=%s lastobs=%d firstpass=%d lastpass=%d\n", \
                   11054:                        title, datafile, &lastobs, &firstpass,&lastpass)) !=EOF){
                   11055:     if (num_filled != 5) {
                   11056:       printf("Should be 5 parameters\n");
1.283     brouard  11057:       fprintf(ficlog,"Should be 5 parameters\n");
1.197     brouard  11058:     }
1.126     brouard  11059:     numlinepar++;
1.197     brouard  11060:     printf("title=%s datafile=%s lastobs=%d firstpass=%d lastpass=%d\n", title, datafile, lastobs, firstpass,lastpass);
1.283     brouard  11061:     fprintf(ficparo,"title=%s datafile=%s lastobs=%d firstpass=%d lastpass=%d\n", title, datafile, lastobs, firstpass,lastpass);
                   11062:     fprintf(ficres,"title=%s datafile=%s lastobs=%d firstpass=%d lastpass=%d\n", title, datafile, lastobs, firstpass,lastpass);
                   11063:     fprintf(ficlog,"title=%s datafile=%s lastobs=%d firstpass=%d lastpass=%d\n", title, datafile, lastobs, firstpass,lastpass);
1.197     brouard  11064:   }
                   11065:   /* Second parameter line */
                   11066:   while(fgets(line, MAXLINE, ficpar)) {
1.283     brouard  11067:     /* while(fscanf(ficpar,"%[^\n]", line)) { */
                   11068:     /* If line starts with a # it is a comment. Strangely fgets reads the EOL and fputs doesn't */
1.197     brouard  11069:     if (line[0] == '#') {
                   11070:       numlinepar++;
1.283     brouard  11071:       printf("%s",line);
                   11072:       fprintf(ficres,"%s",line);
                   11073:       fprintf(ficparo,"%s",line);
                   11074:       fprintf(ficlog,"%s",line);
1.197     brouard  11075:       continue;
                   11076:     }else
                   11077:       break;
                   11078:   }
1.223     brouard  11079:   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", \
                   11080:                        &ftol, &stepm, &ncovcol, &nqv, &ntv, &nqtv, &nlstate, &ndeath, &maxwav, &mle, &weightopt)) !=EOF){
                   11081:     if (num_filled != 11) {
                   11082:       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  11083:       printf("but line=%s\n",line);
1.283     brouard  11084:       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");
                   11085:       fprintf(ficlog,"but line=%s\n",line);
1.197     brouard  11086:     }
1.286     brouard  11087:     if( lastpass > maxwav){
                   11088:       printf("Error (lastpass = %d) > (maxwav = %d)\n",lastpass, maxwav);
                   11089:       fprintf(ficlog,"Error (lastpass = %d) > (maxwav = %d)\n",lastpass, maxwav);
                   11090:       fflush(ficlog);
                   11091:       goto end;
                   11092:     }
                   11093:       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  11094:     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  11095:     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  11096:     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  11097:   }
1.203     brouard  11098:   /* ftolpl=6*ftol*1.e5; /\* 6.e-3 make convergences in less than 80 loops for the prevalence limit *\/ */
1.209     brouard  11099:   /*ftolpl=6.e-4; *//* 6.e-3 make convergences in less than 80 loops for the prevalence limit */
1.197     brouard  11100:   /* Third parameter line */
                   11101:   while(fgets(line, MAXLINE, ficpar)) {
                   11102:     /* If line starts with a # it is a comment */
                   11103:     if (line[0] == '#') {
                   11104:       numlinepar++;
1.283     brouard  11105:       printf("%s",line);
                   11106:       fprintf(ficres,"%s",line);
                   11107:       fprintf(ficparo,"%s",line);
                   11108:       fprintf(ficlog,"%s",line);
1.197     brouard  11109:       continue;
                   11110:     }else
                   11111:       break;
                   11112:   }
1.201     brouard  11113:   if((num_filled=sscanf(line,"model=1+age%[^.\n]", model)) !=EOF){
1.279     brouard  11114:     if (num_filled != 1){
                   11115:       printf("ERROR %d: Model should be at minimum 'model=1+age' %s\n",num_filled, line);
                   11116:       fprintf(ficlog,"ERROR %d: Model should be at minimum 'model=1+age' %s\n",num_filled, line);
1.197     brouard  11117:       model[0]='\0';
                   11118:       goto end;
                   11119:     }
                   11120:     else{
                   11121:       if (model[0]=='+'){
                   11122:        for(i=1; i<=strlen(model);i++)
                   11123:          modeltemp[i-1]=model[i];
1.201     brouard  11124:        strcpy(model,modeltemp); 
1.197     brouard  11125:       }
                   11126:     }
1.199     brouard  11127:     /* printf(" model=1+age%s modeltemp= %s, model=%s\n",model, modeltemp, model);fflush(stdout); */
1.203     brouard  11128:     printf("model=1+age+%s\n",model);fflush(stdout);
1.283     brouard  11129:     fprintf(ficparo,"model=1+age+%s\n",model);fflush(stdout);
                   11130:     fprintf(ficres,"model=1+age+%s\n",model);fflush(stdout);
                   11131:     fprintf(ficlog,"model=1+age+%s\n",model);fflush(stdout);
1.197     brouard  11132:   }
                   11133:   /* 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); */
                   11134:   /* numlinepar=numlinepar+3; /\* In general *\/ */
                   11135:   /* 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  11136:   /* 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); */
                   11137:   /* 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  11138:   fflush(ficlog);
1.190     brouard  11139:   /* if(model[0]=='#'|| model[0]== '\0'){ */
                   11140:   if(model[0]=='#'){
1.279     brouard  11141:     printf("Error in 'model' line: model should start with 'model=1+age+' and end without space \n \
                   11142:  'model=1+age+' or 'model=1+age+V1.' or 'model=1+age+age*age+V1+V1*age' or \n \
                   11143:  'model=1+age+V1+V2' or 'model=1+age+V1+V2+V1*V2' etc. \n");           \
1.187     brouard  11144:     if(mle != -1){
1.279     brouard  11145:       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  11146:       exit(1);
                   11147:     }
                   11148:   }
1.126     brouard  11149:   while((c=getc(ficpar))=='#' && c!= EOF){
                   11150:     ungetc(c,ficpar);
                   11151:     fgets(line, MAXLINE, ficpar);
                   11152:     numlinepar++;
1.195     brouard  11153:     if(line[1]=='q'){ /* This #q will quit imach (the answer is q) */
                   11154:       z[0]=line[1];
                   11155:     }
                   11156:     /* printf("****line [1] = %c \n",line[1]); */
1.141     brouard  11157:     fputs(line, stdout);
                   11158:     //puts(line);
1.126     brouard  11159:     fputs(line,ficparo);
                   11160:     fputs(line,ficlog);
                   11161:   }
                   11162:   ungetc(c,ficpar);
                   11163: 
                   11164:    
1.290     brouard  11165:   covar=matrix(0,NCOVMAX,firstobs,lastobs);  /**< used in readdata */
                   11166:   if(nqv>=1)coqvar=matrix(1,nqv,firstobs,lastobs);  /**< Fixed quantitative covariate */
                   11167:   if(nqtv>=1)cotqvar=ma3x(1,maxwav,1,nqtv,firstobs,lastobs);  /**< Time varying quantitative covariate */
                   11168:   if(ntv+nqtv>=1)cotvar=ma3x(1,maxwav,1,ntv+nqtv,firstobs,lastobs);  /**< Time varying covariate (dummy and quantitative)*/
1.136     brouard  11169:   cptcovn=0; /*Number of covariates, i.e. number of '+' in model statement plus one, indepently of n in Vn*/
                   11170:   /* v1+v2+v3+v2*v4+v5*age makes cptcovn = 5
                   11171:      v1+v2*age+v2*v3 makes cptcovn = 3
                   11172:   */
                   11173:   if (strlen(model)>1) 
1.187     brouard  11174:     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  11175:   else
1.187     brouard  11176:     ncovmodel=2; /* Constant and age */
1.133     brouard  11177:   nforce= (nlstate+ndeath-1)*nlstate; /* Number of forces ij from state i to j */
                   11178:   npar= nforce*ncovmodel; /* Number of parameters like aij*/
1.131     brouard  11179:   if(npar >MAXPARM || nlstate >NLSTATEMAX || ndeath >NDEATHMAX || ncovmodel>NCOVMAX){
                   11180:     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);
                   11181:     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);
                   11182:     fflush(stdout);
                   11183:     fclose (ficlog);
                   11184:     goto end;
                   11185:   }
1.126     brouard  11186:   delti3= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
                   11187:   delti=delti3[1][1];
                   11188:   /*delti=vector(1,npar); *//* Scale of each paramater (output from hesscov)*/
                   11189:   if(mle==-1){ /* Print a wizard for help writing covariance matrix */
1.247     brouard  11190: /* We could also provide initial parameters values giving by simple logistic regression 
                   11191:  * only one way, that is without matrix product. We will have nlstate maximizations */
                   11192:       /* for(i=1;i<nlstate;i++){ */
                   11193:       /*       /\*reducing xi for 1 to npar to 1 to ncovmodel; *\/ */
                   11194:       /*    mlikeli(ficres,p, ncovmodel, ncovmodel, nlstate, ftol, funcnoprod); */
                   11195:       /* } */
1.126     brouard  11196:     prwizard(ncovmodel, nlstate, ndeath, model, ficparo);
1.191     brouard  11197:     printf(" You chose mle=-1, look at file %s for a template of covariance matrix \n",filereso);
                   11198:     fprintf(ficlog," You chose mle=-1, look at file %s for a template of covariance matrix \n",filereso);
1.126     brouard  11199:     free_ma3x(delti3,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel); 
                   11200:     fclose (ficparo);
                   11201:     fclose (ficlog);
                   11202:     goto end;
                   11203:     exit(0);
1.220     brouard  11204:   }  else if(mle==-5) { /* Main Wizard */
1.126     brouard  11205:     prwizard(ncovmodel, nlstate, ndeath, model, ficparo);
1.192     brouard  11206:     printf(" You chose mle=-3, look at file %s for a template of covariance matrix \n",filereso);
                   11207:     fprintf(ficlog," You chose mle=-3, look at file %s for a template of covariance matrix \n",filereso);
1.126     brouard  11208:     param= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
                   11209:     matcov=matrix(1,npar,1,npar);
1.203     brouard  11210:     hess=matrix(1,npar,1,npar);
1.220     brouard  11211:   }  else{ /* Begin of mle != -1 or -5 */
1.145     brouard  11212:     /* Read guessed parameters */
1.126     brouard  11213:     /* Reads comments: lines beginning with '#' */
                   11214:     while((c=getc(ficpar))=='#' && c!= EOF){
                   11215:       ungetc(c,ficpar);
                   11216:       fgets(line, MAXLINE, ficpar);
                   11217:       numlinepar++;
1.141     brouard  11218:       fputs(line,stdout);
1.126     brouard  11219:       fputs(line,ficparo);
                   11220:       fputs(line,ficlog);
                   11221:     }
                   11222:     ungetc(c,ficpar);
                   11223:     
                   11224:     param= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
1.251     brouard  11225:     paramstart= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
1.126     brouard  11226:     for(i=1; i <=nlstate; i++){
1.234     brouard  11227:       j=0;
1.126     brouard  11228:       for(jj=1; jj <=nlstate+ndeath; jj++){
1.234     brouard  11229:        if(jj==i) continue;
                   11230:        j++;
1.292     brouard  11231:        while((c=getc(ficpar))=='#' && c!= EOF){
                   11232:          ungetc(c,ficpar);
                   11233:          fgets(line, MAXLINE, ficpar);
                   11234:          numlinepar++;
                   11235:          fputs(line,stdout);
                   11236:          fputs(line,ficparo);
                   11237:          fputs(line,ficlog);
                   11238:        }
                   11239:        ungetc(c,ficpar);
1.234     brouard  11240:        fscanf(ficpar,"%1d%1d",&i1,&j1);
                   11241:        if ((i1 != i) || (j1 != jj)){
                   11242:          printf("Error in line parameters number %d, %1d%1d instead of %1d%1d \n \
1.126     brouard  11243: It might be a problem of design; if ncovcol and the model are correct\n \
                   11244: run imach with mle=-1 to get a correct template of the parameter file.\n",numlinepar, i,j, i1, j1);
1.234     brouard  11245:          exit(1);
                   11246:        }
                   11247:        fprintf(ficparo,"%1d%1d",i1,j1);
                   11248:        if(mle==1)
                   11249:          printf("%1d%1d",i,jj);
                   11250:        fprintf(ficlog,"%1d%1d",i,jj);
                   11251:        for(k=1; k<=ncovmodel;k++){
                   11252:          fscanf(ficpar," %lf",&param[i][j][k]);
                   11253:          if(mle==1){
                   11254:            printf(" %lf",param[i][j][k]);
                   11255:            fprintf(ficlog," %lf",param[i][j][k]);
                   11256:          }
                   11257:          else
                   11258:            fprintf(ficlog," %lf",param[i][j][k]);
                   11259:          fprintf(ficparo," %lf",param[i][j][k]);
                   11260:        }
                   11261:        fscanf(ficpar,"\n");
                   11262:        numlinepar++;
                   11263:        if(mle==1)
                   11264:          printf("\n");
                   11265:        fprintf(ficlog,"\n");
                   11266:        fprintf(ficparo,"\n");
1.126     brouard  11267:       }
                   11268:     }  
                   11269:     fflush(ficlog);
1.234     brouard  11270:     
1.251     brouard  11271:     /* Reads parameters values */
1.126     brouard  11272:     p=param[1][1];
1.251     brouard  11273:     pstart=paramstart[1][1];
1.126     brouard  11274:     
                   11275:     /* Reads comments: lines beginning with '#' */
                   11276:     while((c=getc(ficpar))=='#' && c!= EOF){
                   11277:       ungetc(c,ficpar);
                   11278:       fgets(line, MAXLINE, ficpar);
                   11279:       numlinepar++;
1.141     brouard  11280:       fputs(line,stdout);
1.126     brouard  11281:       fputs(line,ficparo);
                   11282:       fputs(line,ficlog);
                   11283:     }
                   11284:     ungetc(c,ficpar);
                   11285: 
                   11286:     for(i=1; i <=nlstate; i++){
                   11287:       for(j=1; j <=nlstate+ndeath-1; j++){
1.234     brouard  11288:        fscanf(ficpar,"%1d%1d",&i1,&j1);
                   11289:        if ( (i1-i) * (j1-j) != 0){
                   11290:          printf("Error in line parameters number %d, %1d%1d instead of %1d%1d \n",numlinepar, i,j, i1, j1);
                   11291:          exit(1);
                   11292:        }
                   11293:        printf("%1d%1d",i,j);
                   11294:        fprintf(ficparo,"%1d%1d",i1,j1);
                   11295:        fprintf(ficlog,"%1d%1d",i1,j1);
                   11296:        for(k=1; k<=ncovmodel;k++){
                   11297:          fscanf(ficpar,"%le",&delti3[i][j][k]);
                   11298:          printf(" %le",delti3[i][j][k]);
                   11299:          fprintf(ficparo," %le",delti3[i][j][k]);
                   11300:          fprintf(ficlog," %le",delti3[i][j][k]);
                   11301:        }
                   11302:        fscanf(ficpar,"\n");
                   11303:        numlinepar++;
                   11304:        printf("\n");
                   11305:        fprintf(ficparo,"\n");
                   11306:        fprintf(ficlog,"\n");
1.126     brouard  11307:       }
                   11308:     }
                   11309:     fflush(ficlog);
1.234     brouard  11310:     
1.145     brouard  11311:     /* Reads covariance matrix */
1.126     brouard  11312:     delti=delti3[1][1];
1.220     brouard  11313:                
                   11314:                
1.126     brouard  11315:     /* 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  11316:                
1.126     brouard  11317:     /* Reads comments: lines beginning with '#' */
                   11318:     while((c=getc(ficpar))=='#' && c!= EOF){
                   11319:       ungetc(c,ficpar);
                   11320:       fgets(line, MAXLINE, ficpar);
                   11321:       numlinepar++;
1.141     brouard  11322:       fputs(line,stdout);
1.126     brouard  11323:       fputs(line,ficparo);
                   11324:       fputs(line,ficlog);
                   11325:     }
                   11326:     ungetc(c,ficpar);
1.220     brouard  11327:                
1.126     brouard  11328:     matcov=matrix(1,npar,1,npar);
1.203     brouard  11329:     hess=matrix(1,npar,1,npar);
1.131     brouard  11330:     for(i=1; i <=npar; i++)
                   11331:       for(j=1; j <=npar; j++) matcov[i][j]=0.;
1.220     brouard  11332:                
1.194     brouard  11333:     /* Scans npar lines */
1.126     brouard  11334:     for(i=1; i <=npar; i++){
1.226     brouard  11335:       count=fscanf(ficpar,"%1d%1d%d",&i1,&j1,&jk);
1.194     brouard  11336:       if(count != 3){
1.226     brouard  11337:        printf("Error! Error in parameter file %s at line %d after line starting with %1d%1d%1d\n\
1.194     brouard  11338: This is probably because your covariance matrix doesn't \n  contain exactly %d lines corresponding to your model line '1+age+%s'.\n\
                   11339: Please run with mle=-1 to get a correct covariance matrix.\n",optionfile,numlinepar, i1,j1,jk, npar, model);
1.226     brouard  11340:        fprintf(ficlog,"Error! Error in parameter file %s at line %d after line starting with %1d%1d%1d\n\
1.194     brouard  11341: This is probably because your covariance matrix doesn't \n  contain exactly %d lines corresponding to your model line '1+age+%s'.\n\
                   11342: Please run with mle=-1 to get a correct covariance matrix.\n",optionfile,numlinepar, i1,j1,jk, npar, model);
1.226     brouard  11343:        exit(1);
1.220     brouard  11344:       }else{
1.226     brouard  11345:        if(mle==1)
                   11346:          printf("%1d%1d%d",i1,j1,jk);
                   11347:       }
                   11348:       fprintf(ficlog,"%1d%1d%d",i1,j1,jk);
                   11349:       fprintf(ficparo,"%1d%1d%d",i1,j1,jk);
1.126     brouard  11350:       for(j=1; j <=i; j++){
1.226     brouard  11351:        fscanf(ficpar," %le",&matcov[i][j]);
                   11352:        if(mle==1){
                   11353:          printf(" %.5le",matcov[i][j]);
                   11354:        }
                   11355:        fprintf(ficlog," %.5le",matcov[i][j]);
                   11356:        fprintf(ficparo," %.5le",matcov[i][j]);
1.126     brouard  11357:       }
                   11358:       fscanf(ficpar,"\n");
                   11359:       numlinepar++;
                   11360:       if(mle==1)
1.220     brouard  11361:                                printf("\n");
1.126     brouard  11362:       fprintf(ficlog,"\n");
                   11363:       fprintf(ficparo,"\n");
                   11364:     }
1.194     brouard  11365:     /* End of read covariance matrix npar lines */
1.126     brouard  11366:     for(i=1; i <=npar; i++)
                   11367:       for(j=i+1;j<=npar;j++)
1.226     brouard  11368:        matcov[i][j]=matcov[j][i];
1.126     brouard  11369:     
                   11370:     if(mle==1)
                   11371:       printf("\n");
                   11372:     fprintf(ficlog,"\n");
                   11373:     
                   11374:     fflush(ficlog);
                   11375:     
                   11376:   }    /* End of mle != -3 */
1.218     brouard  11377:   
1.186     brouard  11378:   /*  Main data
                   11379:    */
1.290     brouard  11380:   nobs=lastobs-firstobs+1; /* was = lastobs;*/
                   11381:   /* num=lvector(1,n); */
                   11382:   /* moisnais=vector(1,n); */
                   11383:   /* annais=vector(1,n); */
                   11384:   /* moisdc=vector(1,n); */
                   11385:   /* andc=vector(1,n); */
                   11386:   /* weight=vector(1,n); */
                   11387:   /* agedc=vector(1,n); */
                   11388:   /* cod=ivector(1,n); */
                   11389:   /* for(i=1;i<=n;i++){ */
                   11390:   num=lvector(firstobs,lastobs);
                   11391:   moisnais=vector(firstobs,lastobs);
                   11392:   annais=vector(firstobs,lastobs);
                   11393:   moisdc=vector(firstobs,lastobs);
                   11394:   andc=vector(firstobs,lastobs);
                   11395:   weight=vector(firstobs,lastobs);
                   11396:   agedc=vector(firstobs,lastobs);
                   11397:   cod=ivector(firstobs,lastobs);
                   11398:   for(i=firstobs;i<=lastobs;i++){
1.234     brouard  11399:     num[i]=0;
                   11400:     moisnais[i]=0;
                   11401:     annais[i]=0;
                   11402:     moisdc[i]=0;
                   11403:     andc[i]=0;
                   11404:     agedc[i]=0;
                   11405:     cod[i]=0;
                   11406:     weight[i]=1.0; /* Equal weights, 1 by default */
                   11407:   }
1.290     brouard  11408:   mint=matrix(1,maxwav,firstobs,lastobs);
                   11409:   anint=matrix(1,maxwav,firstobs,lastobs);
                   11410:   s=imatrix(1,maxwav+1,firstobs,lastobs); /* s[i][j] health state for wave i and individual j */ 
1.126     brouard  11411:   tab=ivector(1,NCOVMAX);
1.144     brouard  11412:   ncodemax=ivector(1,NCOVMAX); /* Number of code per covariate; if O and 1 only, 2**ncov; V1+V2+V3+V4=>16 */
1.192     brouard  11413:   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  11414: 
1.136     brouard  11415:   /* Reads data from file datafile */
                   11416:   if (readdata(datafile, firstobs, lastobs, &imx)==1)
                   11417:     goto end;
                   11418: 
                   11419:   /* Calculation of the number of parameters from char model */
1.234     brouard  11420:   /*    modelsav=V2+V1+V4+age*V3 strb=age*V3 stra=V2+V1+V4 
1.137     brouard  11421:        k=4 (age*V3) Tvar[k=4]= 3 (from V3) Tag[cptcovage=1]=4
                   11422:        k=3 V4 Tvar[k=3]= 4 (from V4)
                   11423:        k=2 V1 Tvar[k=2]= 1 (from V1)
                   11424:        k=1 Tvar[1]=2 (from V2)
1.234     brouard  11425:   */
                   11426:   
                   11427:   Tvar=ivector(1,NCOVMAX); /* Was 15 changed to NCOVMAX. */
                   11428:   TvarsDind=ivector(1,NCOVMAX); /*  */
                   11429:   TvarsD=ivector(1,NCOVMAX); /*  */
                   11430:   TvarsQind=ivector(1,NCOVMAX); /*  */
                   11431:   TvarsQ=ivector(1,NCOVMAX); /*  */
1.232     brouard  11432:   TvarF=ivector(1,NCOVMAX); /*  */
                   11433:   TvarFind=ivector(1,NCOVMAX); /*  */
                   11434:   TvarV=ivector(1,NCOVMAX); /*  */
                   11435:   TvarVind=ivector(1,NCOVMAX); /*  */
                   11436:   TvarA=ivector(1,NCOVMAX); /*  */
                   11437:   TvarAind=ivector(1,NCOVMAX); /*  */
1.231     brouard  11438:   TvarFD=ivector(1,NCOVMAX); /*  */
                   11439:   TvarFDind=ivector(1,NCOVMAX); /*  */
                   11440:   TvarFQ=ivector(1,NCOVMAX); /*  */
                   11441:   TvarFQind=ivector(1,NCOVMAX); /*  */
                   11442:   TvarVD=ivector(1,NCOVMAX); /*  */
                   11443:   TvarVDind=ivector(1,NCOVMAX); /*  */
                   11444:   TvarVQ=ivector(1,NCOVMAX); /*  */
                   11445:   TvarVQind=ivector(1,NCOVMAX); /*  */
                   11446: 
1.230     brouard  11447:   Tvalsel=vector(1,NCOVMAX); /*  */
1.233     brouard  11448:   Tvarsel=ivector(1,NCOVMAX); /*  */
1.226     brouard  11449:   Typevar=ivector(-1,NCOVMAX); /* -1 to 2 */
                   11450:   Fixed=ivector(-1,NCOVMAX); /* -1 to 3 */
                   11451:   Dummy=ivector(-1,NCOVMAX); /* -1 to 3 */
1.137     brouard  11452:   /*  V2+V1+V4+age*V3 is a model with 4 covariates (3 plus signs). 
                   11453:       For each model-covariate stores the data-covariate id. Tvar[1]=2, Tvar[2]=1, Tvar[3]=4, 
                   11454:       Tvar[4=age*V3] is 3 and 'age' is recorded in Tage.
                   11455:   */
                   11456:   /* For model-covariate k tells which data-covariate to use but
                   11457:     because this model-covariate is a construction we invent a new column
                   11458:     ncovcol + k1
                   11459:     If already ncovcol=4 and model=V2+V1+V1*V4+age*V3
                   11460:     Tvar[3=V1*V4]=4+1 etc */
1.227     brouard  11461:   Tprod=ivector(1,NCOVMAX); /* Gives the k position of the k1 product */
                   11462:   Tposprod=ivector(1,NCOVMAX); /* Gives the k1 product from the k position */
1.137     brouard  11463:   /* Tprod[k1=1]=3(=V1*V4) for V2+V1+V1*V4+age*V3
                   11464:      if  V2+V1+V1*V4+age*V3+V3*V2   TProd[k1=2]=5 (V3*V2)
1.227     brouard  11465:      Tposprod[k]=k1 , Tposprod[3]=1, Tposprod[5]=2 
1.137     brouard  11466:   */
1.145     brouard  11467:   Tvaraff=ivector(1,NCOVMAX); /* Unclear */
                   11468:   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  11469:                            * For V3*V2 (in V2+V1+V1*V4+age*V3+V3*V2), V3*V2 position is 2nd. 
                   11470:                            * Tvard[k1=2][1]=3 (V3) Tvard[k1=2][2]=2(V2) */
1.145     brouard  11471:   Tage=ivector(1,NCOVMAX); /* Gives the covariate id of covariates associated with age: V2 + V1 + age*V4 + V3*age
1.137     brouard  11472:                         4 covariates (3 plus signs)
                   11473:                         Tage[1=V3*age]= 4; Tage[2=age*V4] = 3
                   11474:                      */  
1.230     brouard  11475:   Tmodelind=ivector(1,NCOVMAX);/** gives the k model position of an
1.227     brouard  11476:                                * individual dummy, fixed or varying:
                   11477:                                * Tmodelind[Tvaraff[3]]=9,Tvaraff[1]@9={4,
                   11478:                                * 3, 1, 0, 0, 0, 0, 0, 0},
1.230     brouard  11479:                                * model=V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 , 
                   11480:                                * V1 df, V2 qf, V3 & V4 dv, V5 qv
                   11481:                                * Tmodelind[1]@9={9,0,3,2,}*/
                   11482:   TmodelInvind=ivector(1,NCOVMAX); /* TmodelInvind=Tvar[k]- ncovcol-nqv={5-2-1=2,*/
                   11483:   TmodelInvQind=ivector(1,NCOVMAX);/** gives the k model position of an
1.228     brouard  11484:                                * individual quantitative, fixed or varying:
                   11485:                                * Tmodelqind[1]=1,Tvaraff[1]@9={4,
                   11486:                                * 3, 1, 0, 0, 0, 0, 0, 0},
                   11487:                                * model=V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1*/
1.186     brouard  11488: /* Main decodemodel */
                   11489: 
1.187     brouard  11490: 
1.223     brouard  11491:   if(decodemodel(model, lastobs) == 1) /* In order to get Tvar[k] V4+V3+V5 p Tvar[1]@3  = {4, 3, 5}*/
1.136     brouard  11492:     goto end;
                   11493: 
1.137     brouard  11494:   if((double)(lastobs-imx)/(double)imx > 1.10){
                   11495:     nbwarn++;
                   11496:     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); 
                   11497:     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); 
                   11498:   }
1.136     brouard  11499:     /*  if(mle==1){*/
1.137     brouard  11500:   if (weightopt != 1) { /* Maximisation without weights. We can have weights different from 1 but want no weight*/
                   11501:     for(i=1;i<=imx;i++) weight[i]=1.0; /* changed to imx */
1.136     brouard  11502:   }
                   11503: 
                   11504:     /*-calculation of age at interview from date of interview and age at death -*/
                   11505:   agev=matrix(1,maxwav,1,imx);
                   11506: 
                   11507:   if(calandcheckages(imx, maxwav, &agemin, &agemax, &nberr, &nbwarn) == 1)
                   11508:     goto end;
                   11509: 
1.126     brouard  11510: 
1.136     brouard  11511:   agegomp=(int)agemin;
1.290     brouard  11512:   free_vector(moisnais,firstobs,lastobs);
                   11513:   free_vector(annais,firstobs,lastobs);
1.126     brouard  11514:   /* free_matrix(mint,1,maxwav,1,n);
                   11515:      free_matrix(anint,1,maxwav,1,n);*/
1.215     brouard  11516:   /* free_vector(moisdc,1,n); */
                   11517:   /* free_vector(andc,1,n); */
1.145     brouard  11518:   /* */
                   11519:   
1.126     brouard  11520:   wav=ivector(1,imx);
1.214     brouard  11521:   /* dh=imatrix(1,lastpass-firstpass+1,1,imx); */
                   11522:   /* bh=imatrix(1,lastpass-firstpass+1,1,imx); */
                   11523:   /* mw=imatrix(1,lastpass-firstpass+1,1,imx); */
                   11524:   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.*/
                   11525:   bh=imatrix(1,lastpass-firstpass+2,1,imx);
                   11526:   mw=imatrix(1,lastpass-firstpass+2,1,imx);
1.126     brouard  11527:    
                   11528:   /* Concatenates waves */
1.214     brouard  11529:   /* Concatenates waves: wav[i] is the number of effective (useful waves) of individual i.
                   11530:      Death is a valid wave (if date is known).
                   11531:      mw[mi][i] is the number of (mi=1 to wav[i]) effective wave out of mi of individual i
                   11532:      dh[m][i] or dh[mw[mi][i]][i] is the delay between two effective waves m=mw[mi][i]
                   11533:      and mw[mi+1][i]. dh depends on stepm.
                   11534:   */
                   11535: 
1.126     brouard  11536:   concatwav(wav, dh, bh, mw, s, agedc, agev,  firstpass, lastpass, imx, nlstate, stepm);
1.248     brouard  11537:   /* Concatenates waves */
1.145     brouard  11538:  
1.290     brouard  11539:   free_vector(moisdc,firstobs,lastobs);
                   11540:   free_vector(andc,firstobs,lastobs);
1.215     brouard  11541: 
1.126     brouard  11542:   /* Routine tricode is to calculate cptcoveff (real number of unique covariates) and to associate covariable number and modality */
                   11543:   nbcode=imatrix(0,NCOVMAX,0,NCOVMAX); 
                   11544:   ncodemax[1]=1;
1.145     brouard  11545:   Ndum =ivector(-1,NCOVMAX);  
1.225     brouard  11546:   cptcoveff=0;
1.220     brouard  11547:   if (ncovmodel-nagesqr > 2 ){ /* That is if covariate other than cst, age and age*age */
                   11548:     tricode(&cptcoveff,Tvar,nbcode,imx, Ndum); /**< Fills nbcode[Tvar[j]][l]; */
1.227     brouard  11549:   }
                   11550:   
                   11551:   ncovcombmax=pow(2,cptcoveff);
                   11552:   invalidvarcomb=ivector(1, ncovcombmax); 
                   11553:   for(i=1;i<ncovcombmax;i++)
                   11554:     invalidvarcomb[i]=0;
                   11555:   
1.211     brouard  11556:   /* Nbcode gives the value of the lth modality (currently 1 to 2) of jth covariate, in
1.186     brouard  11557:      V2+V1*age, there are 3 covariates Tvar[2]=1 (V1).*/
1.211     brouard  11558:   /* 1 to ncodemax[j] which is the maximum value of this jth covariate */
1.227     brouard  11559:   
1.200     brouard  11560:   /*  codtab=imatrix(1,100,1,10);*/ /* codtab[h,k]=( (h-1) - mod(k-1,2**(k-1) )/2**(k-1) */
1.198     brouard  11561:   /*printf(" codtab[1,1],codtab[100,10]=%d,%d\n", codtab[1][1],codtabm(100,10));*/
1.186     brouard  11562:   /* codtab gives the value 1 or 2 of the hth combination of k covariates (1 or 2).*/
1.211     brouard  11563:   /* nbcode[Tvaraff[j]][codtabm(h,j)]) : if there are only 2 modalities for a covariate j, 
                   11564:    * codtabm(h,j) gives its value classified at position h and nbcode gives how it is coded 
                   11565:    * (currently 0 or 1) in the data.
                   11566:    * In a loop on h=1 to 2**k, and a loop on j (=1 to k), we get the value of 
                   11567:    * corresponding modality (h,j).
                   11568:    */
                   11569: 
1.145     brouard  11570:   h=0;
                   11571:   /*if (cptcovn > 0) */
1.126     brouard  11572:   m=pow(2,cptcoveff);
                   11573:  
1.144     brouard  11574:          /**< codtab(h,k)  k   = codtab[h,k]=( (h-1) - mod(k-1,2**(k-1) )/2**(k-1) + 1
1.211     brouard  11575:           * For k=4 covariates, h goes from 1 to m=2**k
                   11576:           * codtabm(h,k)=  (1 & (h-1) >> (k-1)) + 1;
                   11577:            * #define codtabm(h,k)  (1 & (h-1) >> (k-1))+1
1.186     brouard  11578:           *     h\k   1     2     3     4
1.143     brouard  11579:           *______________________________  
                   11580:           *     1 i=1 1 i=1 1 i=1 1 i=1 1
                   11581:           *     2     2     1     1     1
                   11582:           *     3 i=2 1     2     1     1
                   11583:           *     4     2     2     1     1
                   11584:           *     5 i=3 1 i=2 1     2     1
                   11585:           *     6     2     1     2     1
                   11586:           *     7 i=4 1     2     2     1
                   11587:           *     8     2     2     2     1
1.197     brouard  11588:           *     9 i=5 1 i=3 1 i=2 1     2
                   11589:           *    10     2     1     1     2
                   11590:           *    11 i=6 1     2     1     2
                   11591:           *    12     2     2     1     2
                   11592:           *    13 i=7 1 i=4 1     2     2    
                   11593:           *    14     2     1     2     2
                   11594:           *    15 i=8 1     2     2     2
                   11595:           *    16     2     2     2     2
1.143     brouard  11596:           */
1.212     brouard  11597:   /* How to do the opposite? From combination h (=1 to 2**k) how to get the value on the covariates? */
1.211     brouard  11598:      /* from h=5 and m, we get then number of covariates k=log(m)/log(2)=4
                   11599:      * and the value of each covariate?
                   11600:      * V1=1, V2=1, V3=2, V4=1 ?
                   11601:      * h-1=4 and 4 is 0100 or reverse 0010, and +1 is 1121 ok.
                   11602:      * h=6, 6-1=5, 5 is 0101, 1010, 2121, V1=2nd, V2=1st, V3=2nd, V4=1st.
                   11603:      * In order to get the real value in the data, we use nbcode
                   11604:      * nbcode[Tvar[3][2nd]]=1 and nbcode[Tvar[4][1]]=0
                   11605:      * We are keeping this crazy system in order to be able (in the future?) 
                   11606:      * to have more than 2 values (0 or 1) for a covariate.
                   11607:      * #define codtabm(h,k)  (1 & (h-1) >> (k-1))+1
                   11608:      * h=6, k=2? h-1=5=0101, reverse 1010, +1=2121, k=2nd position: value is 1: codtabm(6,2)=1
                   11609:      *              bbbbbbbb
                   11610:      *              76543210     
                   11611:      *   h-1        00000101 (6-1=5)
1.219     brouard  11612:      *(h-1)>>(k-1)= 00000010 >> (2-1) = 1 right shift
1.211     brouard  11613:      *           &
                   11614:      *     1        00000001 (1)
1.219     brouard  11615:      *              00000000        = 1 & ((h-1) >> (k-1))
                   11616:      *          +1= 00000001 =1 
1.211     brouard  11617:      *
                   11618:      * h=14, k=3 => h'=h-1=13, k'=k-1=2
                   11619:      *          h'      1101 =2^3+2^2+0x2^1+2^0
                   11620:      *    >>k'            11
                   11621:      *          &   00000001
                   11622:      *            = 00000001
                   11623:      *      +1    = 00000010=2    =  codtabm(14,3)   
                   11624:      * Reverse h=6 and m=16?
                   11625:      * cptcoveff=log(16)/log(2)=4 covariate: 6-1=5=0101 reversed=1010 +1=2121 =>V1=2, V2=1, V3=2, V4=1.
                   11626:      * for (j=1 to cptcoveff) Vj=decodtabm(j,h,cptcoveff)
                   11627:      * decodtabm(h,j,cptcoveff)= (((h-1) >> (j-1)) & 1) +1 
                   11628:      * decodtabm(h,j,cptcoveff)= (h <= (1<<cptcoveff)?(((h-1) >> (j-1)) & 1) +1 : -1)
                   11629:      * V3=decodtabm(14,3,2**4)=2
                   11630:      *          h'=13   1101 =2^3+2^2+0x2^1+2^0
                   11631:      *(h-1) >> (j-1)    0011 =13 >> 2
                   11632:      *          &1 000000001
                   11633:      *           = 000000001
                   11634:      *         +1= 000000010 =2
                   11635:      *                  2211
                   11636:      *                  V1=1+1, V2=0+1, V3=1+1, V4=1+1
                   11637:      *                  V3=2
1.220     brouard  11638:                 * codtabm and decodtabm are identical
1.211     brouard  11639:      */
                   11640: 
1.145     brouard  11641: 
                   11642:  free_ivector(Ndum,-1,NCOVMAX);
                   11643: 
                   11644: 
1.126     brouard  11645:     
1.186     brouard  11646:   /* Initialisation of ----------- gnuplot -------------*/
1.126     brouard  11647:   strcpy(optionfilegnuplot,optionfilefiname);
                   11648:   if(mle==-3)
1.201     brouard  11649:     strcat(optionfilegnuplot,"-MORT_");
1.126     brouard  11650:   strcat(optionfilegnuplot,".gp");
                   11651: 
                   11652:   if((ficgp=fopen(optionfilegnuplot,"w"))==NULL) {
                   11653:     printf("Problem with file %s",optionfilegnuplot);
                   11654:   }
                   11655:   else{
1.204     brouard  11656:     fprintf(ficgp,"\n# IMaCh-%s\n", version); 
1.126     brouard  11657:     fprintf(ficgp,"# %s\n", optionfilegnuplot); 
1.141     brouard  11658:     //fprintf(ficgp,"set missing 'NaNq'\n");
                   11659:     fprintf(ficgp,"set datafile missing 'NaNq'\n");
1.126     brouard  11660:   }
                   11661:   /*  fclose(ficgp);*/
1.186     brouard  11662: 
                   11663: 
                   11664:   /* Initialisation of --------- index.htm --------*/
1.126     brouard  11665: 
                   11666:   strcpy(optionfilehtm,optionfilefiname); /* Main html file */
                   11667:   if(mle==-3)
1.201     brouard  11668:     strcat(optionfilehtm,"-MORT_");
1.126     brouard  11669:   strcat(optionfilehtm,".htm");
                   11670:   if((fichtm=fopen(optionfilehtm,"w"))==NULL)    {
1.131     brouard  11671:     printf("Problem with %s \n",optionfilehtm);
                   11672:     exit(0);
1.126     brouard  11673:   }
                   11674: 
                   11675:   strcpy(optionfilehtmcov,optionfilefiname); /* Only for matrix of covariance */
                   11676:   strcat(optionfilehtmcov,"-cov.htm");
                   11677:   if((fichtmcov=fopen(optionfilehtmcov,"w"))==NULL)    {
                   11678:     printf("Problem with %s \n",optionfilehtmcov), exit(0);
                   11679:   }
                   11680:   else{
                   11681:   fprintf(fichtmcov,"<html><head>\n<title>IMaCh Cov %s</title></head>\n <body><font size=\"2\">%s <br> %s</font> \
                   11682: <hr size=\"2\" color=\"#EC5E5E\"> \n\
1.204     brouard  11683: Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=1+age+%s<br>\n",\
1.126     brouard  11684:          optionfilehtmcov,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model);
                   11685:   }
                   11686: 
1.213     brouard  11687:   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  11688: <hr size=\"2\" color=\"#EC5E5E\"> \n\
                   11689: <font size=\"2\">IMaCh-%s <br> %s</font> \
1.126     brouard  11690: <hr size=\"2\" color=\"#EC5E5E\"> \n\
1.204     brouard  11691: Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=1+age+%s<br>\n\
1.126     brouard  11692: \n\
                   11693: <hr  size=\"2\" color=\"#EC5E5E\">\
                   11694:  <ul><li><h4>Parameter files</h4>\n\
                   11695:  - Parameter file: <a href=\"%s.%s\">%s.%s</a><br>\n\
                   11696:  - Copy of the parameter file: <a href=\"o%s\">o%s</a><br>\n\
                   11697:  - Log file of the run: <a href=\"%s\">%s</a><br>\n\
                   11698:  - Gnuplot file name: <a href=\"%s\">%s</a><br>\n\
                   11699:  - Date and time at start: %s</ul>\n",\
                   11700:          optionfilehtm,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model,\
                   11701:          optionfilefiname,optionfilext,optionfilefiname,optionfilext,\
                   11702:          fileres,fileres,\
                   11703:          filelog,filelog,optionfilegnuplot,optionfilegnuplot,strstart);
                   11704:   fflush(fichtm);
                   11705: 
                   11706:   strcpy(pathr,path);
                   11707:   strcat(pathr,optionfilefiname);
1.184     brouard  11708: #ifdef WIN32
                   11709:   _chdir(optionfilefiname); /* Move to directory named optionfile */
                   11710: #else
1.126     brouard  11711:   chdir(optionfilefiname); /* Move to directory named optionfile */
1.184     brouard  11712: #endif
                   11713:          
1.126     brouard  11714:   
1.220     brouard  11715:   /* Calculates basic frequencies. Computes observed prevalence at single age 
                   11716:                 and for any valid combination of covariates
1.126     brouard  11717:      and prints on file fileres'p'. */
1.251     brouard  11718:   freqsummary(fileres, p, pstart, agemin, agemax, s, agev, nlstate, imx, Tvaraff, invalidvarcomb, nbcode, ncodemax,mint,anint,strstart, \
1.227     brouard  11719:              firstpass, lastpass,  stepm,  weightopt, model);
1.126     brouard  11720: 
                   11721:   fprintf(fichtm,"\n");
1.286     brouard  11722:   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  11723:          ftol, stepm);
                   11724:   fprintf(fichtm,"\n<li>Number of fixed dummy covariates: ncovcol=%d ", ncovcol);
                   11725:   ncurrv=1;
                   11726:   for(i=ncurrv; i <=ncovcol; i++) fprintf(fichtm,"V%d ", i);
                   11727:   fprintf(fichtm,"\n<li> Number of fixed quantitative variables: nqv=%d ", nqv); 
                   11728:   ncurrv=i;
                   11729:   for(i=ncurrv; i <=ncurrv-1+nqv; i++) fprintf(fichtm,"V%d ", i);
1.290     brouard  11730:   fprintf(fichtm,"\n<li> Number of time varying (wave varying) dummy covariates: ntv=%d ", ntv);
1.274     brouard  11731:   ncurrv=i;
                   11732:   for(i=ncurrv; i <=ncurrv-1+ntv; i++) fprintf(fichtm,"V%d ", i);
1.290     brouard  11733:   fprintf(fichtm,"\n<li>Number of time varying  quantitative covariates: nqtv=%d ", nqtv);
1.274     brouard  11734:   ncurrv=i;
                   11735:   for(i=ncurrv; i <=ncurrv-1+nqtv; i++) fprintf(fichtm,"V%d ", i);
                   11736:   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", \
                   11737:           nlstate, ndeath, maxwav, mle, weightopt);
                   11738: 
                   11739:   fprintf(fichtm,"<h4> Diagram of states <a href=\"%s_.svg\">%s_.svg</a></h4> \n\
                   11740: <img src=\"%s_.svg\">", subdirf2(optionfilefiname,"D_"),subdirf2(optionfilefiname,"D_"),subdirf2(optionfilefiname,"D_"));
                   11741: 
                   11742:   
                   11743:   fprintf(fichtm,"\n<h4>Some descriptive statistics </h4>\n<br>Total number of observations=%d <br>\n\
1.126     brouard  11744: Youngest age at first (selected) pass %.2f, oldest age %.2f<br>\n\
                   11745: Interval (in months) between two waves: Min=%d Max=%d Mean=%.2lf<br>\n",\
1.274     brouard  11746:   imx,agemin,agemax,jmin,jmax,jmean);
1.126     brouard  11747:   pmmij= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
1.268     brouard  11748:   oldms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
                   11749:   newms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
                   11750:   savms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
                   11751:   oldm=oldms; newm=newms; savm=savms; /* Keeps fixed addresses to free */
1.218     brouard  11752: 
1.126     brouard  11753:   /* For Powell, parameters are in a vector p[] starting at p[1]
                   11754:      so we point p on param[1][1] so that p[1] maps on param[1][1][1] */
                   11755:   p=param[1][1]; /* *(*(*(param +1)+1)+0) */
                   11756: 
                   11757:   globpr=0; /* To get the number ipmx of contributions and the sum of weights*/
1.186     brouard  11758:   /* For mortality only */
1.126     brouard  11759:   if (mle==-3){
1.136     brouard  11760:     ximort=matrix(1,NDIM,1,NDIM); 
1.248     brouard  11761:     for(i=1;i<=NDIM;i++)
                   11762:       for(j=1;j<=NDIM;j++)
                   11763:        ximort[i][j]=0.;
1.186     brouard  11764:     /*     ximort=gsl_matrix_alloc(1,NDIM,1,NDIM); */
1.290     brouard  11765:     cens=ivector(firstobs,lastobs);
                   11766:     ageexmed=vector(firstobs,lastobs);
                   11767:     agecens=vector(firstobs,lastobs);
                   11768:     dcwave=ivector(firstobs,lastobs);
1.223     brouard  11769:                
1.126     brouard  11770:     for (i=1; i<=imx; i++){
                   11771:       dcwave[i]=-1;
                   11772:       for (m=firstpass; m<=lastpass; m++)
1.226     brouard  11773:        if (s[m][i]>nlstate) {
                   11774:          dcwave[i]=m;
                   11775:          /*    printf("i=%d j=%d s=%d dcwave=%d\n",i,j, s[j][i],dcwave[i]);*/
                   11776:          break;
                   11777:        }
1.126     brouard  11778:     }
1.226     brouard  11779:     
1.126     brouard  11780:     for (i=1; i<=imx; i++) {
                   11781:       if (wav[i]>0){
1.226     brouard  11782:        ageexmed[i]=agev[mw[1][i]][i];
                   11783:        j=wav[i];
                   11784:        agecens[i]=1.; 
                   11785:        
                   11786:        if (ageexmed[i]> 1 && wav[i] > 0){
                   11787:          agecens[i]=agev[mw[j][i]][i];
                   11788:          cens[i]= 1;
                   11789:        }else if (ageexmed[i]< 1) 
                   11790:          cens[i]= -1;
                   11791:        if (agedc[i]< AGESUP && agedc[i]>1 && dcwave[i]>firstpass && dcwave[i]<=lastpass)
                   11792:          cens[i]=0 ;
1.126     brouard  11793:       }
                   11794:       else cens[i]=-1;
                   11795:     }
                   11796:     
                   11797:     for (i=1;i<=NDIM;i++) {
                   11798:       for (j=1;j<=NDIM;j++)
1.226     brouard  11799:        ximort[i][j]=(i == j ? 1.0 : 0.0);
1.126     brouard  11800:     }
                   11801:     
1.145     brouard  11802:     /*p[1]=0.0268; p[NDIM]=0.083;*/
1.126     brouard  11803:     /*printf("%lf %lf", p[1], p[2]);*/
                   11804:     
                   11805:     
1.136     brouard  11806: #ifdef GSL
                   11807:     printf("GSL optimization\n");  fprintf(ficlog,"Powell\n");
1.162     brouard  11808: #else
1.126     brouard  11809:     printf("Powell\n");  fprintf(ficlog,"Powell\n");
1.136     brouard  11810: #endif
1.201     brouard  11811:     strcpy(filerespow,"POW-MORT_"); 
                   11812:     strcat(filerespow,fileresu);
1.126     brouard  11813:     if((ficrespow=fopen(filerespow,"w"))==NULL) {
                   11814:       printf("Problem with resultfile: %s\n", filerespow);
                   11815:       fprintf(ficlog,"Problem with resultfile: %s\n", filerespow);
                   11816:     }
1.136     brouard  11817: #ifdef GSL
                   11818:     fprintf(ficrespow,"# GSL optimization\n# iter -2*LL");
1.162     brouard  11819: #else
1.126     brouard  11820:     fprintf(ficrespow,"# Powell\n# iter -2*LL");
1.136     brouard  11821: #endif
1.126     brouard  11822:     /*  for (i=1;i<=nlstate;i++)
                   11823:        for(j=1;j<=nlstate+ndeath;j++)
                   11824:        if(j!=i)fprintf(ficrespow," p%1d%1d",i,j);
                   11825:     */
                   11826:     fprintf(ficrespow,"\n");
1.136     brouard  11827: #ifdef GSL
                   11828:     /* gsl starts here */ 
                   11829:     T = gsl_multimin_fminimizer_nmsimplex;
                   11830:     gsl_multimin_fminimizer *sfm = NULL;
                   11831:     gsl_vector *ss, *x;
                   11832:     gsl_multimin_function minex_func;
                   11833: 
                   11834:     /* Initial vertex size vector */
                   11835:     ss = gsl_vector_alloc (NDIM);
                   11836:     
                   11837:     if (ss == NULL){
                   11838:       GSL_ERROR_VAL ("failed to allocate space for ss", GSL_ENOMEM, 0);
                   11839:     }
                   11840:     /* Set all step sizes to 1 */
                   11841:     gsl_vector_set_all (ss, 0.001);
                   11842: 
                   11843:     /* Starting point */
1.126     brouard  11844:     
1.136     brouard  11845:     x = gsl_vector_alloc (NDIM);
                   11846:     
                   11847:     if (x == NULL){
                   11848:       gsl_vector_free(ss);
                   11849:       GSL_ERROR_VAL ("failed to allocate space for x", GSL_ENOMEM, 0);
                   11850:     }
                   11851:   
                   11852:     /* Initialize method and iterate */
                   11853:     /*     p[1]=0.0268; p[NDIM]=0.083; */
1.186     brouard  11854:     /*     gsl_vector_set(x, 0, 0.0268); */
                   11855:     /*     gsl_vector_set(x, 1, 0.083); */
1.136     brouard  11856:     gsl_vector_set(x, 0, p[1]);
                   11857:     gsl_vector_set(x, 1, p[2]);
                   11858: 
                   11859:     minex_func.f = &gompertz_f;
                   11860:     minex_func.n = NDIM;
                   11861:     minex_func.params = (void *)&p; /* ??? */
                   11862:     
                   11863:     sfm = gsl_multimin_fminimizer_alloc (T, NDIM);
                   11864:     gsl_multimin_fminimizer_set (sfm, &minex_func, x, ss);
                   11865:     
                   11866:     printf("Iterations beginning .....\n\n");
                   11867:     printf("Iter. #    Intercept       Slope     -Log Likelihood     Simplex size\n");
                   11868: 
                   11869:     iteri=0;
                   11870:     while (rval == GSL_CONTINUE){
                   11871:       iteri++;
                   11872:       status = gsl_multimin_fminimizer_iterate(sfm);
                   11873:       
                   11874:       if (status) printf("error: %s\n", gsl_strerror (status));
                   11875:       fflush(0);
                   11876:       
                   11877:       if (status) 
                   11878:         break;
                   11879:       
                   11880:       rval = gsl_multimin_test_size (gsl_multimin_fminimizer_size (sfm), 1e-6);
                   11881:       ssval = gsl_multimin_fminimizer_size (sfm);
                   11882:       
                   11883:       if (rval == GSL_SUCCESS)
                   11884:         printf ("converged to a local maximum at\n");
                   11885:       
                   11886:       printf("%5d ", iteri);
                   11887:       for (it = 0; it < NDIM; it++){
                   11888:        printf ("%10.5f ", gsl_vector_get (sfm->x, it));
                   11889:       }
                   11890:       printf("f() = %-10.5f ssize = %.7f\n", sfm->fval, ssval);
                   11891:     }
                   11892:     
                   11893:     printf("\n\n Please note: Program should be run many times with varying starting points to detemine global maximum\n\n");
                   11894:     
                   11895:     gsl_vector_free(x); /* initial values */
                   11896:     gsl_vector_free(ss); /* inital step size */
                   11897:     for (it=0; it<NDIM; it++){
                   11898:       p[it+1]=gsl_vector_get(sfm->x,it);
                   11899:       fprintf(ficrespow," %.12lf", p[it]);
                   11900:     }
                   11901:     gsl_multimin_fminimizer_free (sfm); /* p *(sfm.x.data) et p *(sfm.x.data+1)  */
                   11902: #endif
                   11903: #ifdef POWELL
                   11904:      powell(p,ximort,NDIM,ftol,&iter,&fret,gompertz);
                   11905: #endif  
1.126     brouard  11906:     fclose(ficrespow);
                   11907:     
1.203     brouard  11908:     hesscov(matcov, hess, p, NDIM, delti, 1e-4, gompertz); 
1.126     brouard  11909: 
                   11910:     for(i=1; i <=NDIM; i++)
                   11911:       for(j=i+1;j<=NDIM;j++)
1.220     brouard  11912:                                matcov[i][j]=matcov[j][i];
1.126     brouard  11913:     
                   11914:     printf("\nCovariance matrix\n ");
1.203     brouard  11915:     fprintf(ficlog,"\nCovariance matrix\n ");
1.126     brouard  11916:     for(i=1; i <=NDIM; i++) {
                   11917:       for(j=1;j<=NDIM;j++){ 
1.220     brouard  11918:                                printf("%f ",matcov[i][j]);
                   11919:                                fprintf(ficlog,"%f ",matcov[i][j]);
1.126     brouard  11920:       }
1.203     brouard  11921:       printf("\n ");  fprintf(ficlog,"\n ");
1.126     brouard  11922:     }
                   11923:     
                   11924:     printf("iter=%d MLE=%f Eq=%lf*exp(%lf*(age-%d))\n",iter,-gompertz(p),p[1],p[2],agegomp);
1.193     brouard  11925:     for (i=1;i<=NDIM;i++) {
1.126     brouard  11926:       printf("%f [%f ; %f]\n",p[i],p[i]-2*sqrt(matcov[i][i]),p[i]+2*sqrt(matcov[i][i]));
1.193     brouard  11927:       fprintf(ficlog,"%f [%f ; %f]\n",p[i],p[i]-2*sqrt(matcov[i][i]),p[i]+2*sqrt(matcov[i][i]));
                   11928:     }
1.126     brouard  11929:     lsurv=vector(1,AGESUP);
                   11930:     lpop=vector(1,AGESUP);
                   11931:     tpop=vector(1,AGESUP);
                   11932:     lsurv[agegomp]=100000;
                   11933:     
                   11934:     for (k=agegomp;k<=AGESUP;k++) {
                   11935:       agemortsup=k;
                   11936:       if (p[1]*exp(p[2]*(k-agegomp))>1) break;
                   11937:     }
                   11938:     
                   11939:     for (k=agegomp;k<agemortsup;k++)
                   11940:       lsurv[k+1]=lsurv[k]-lsurv[k]*(p[1]*exp(p[2]*(k-agegomp)));
                   11941:     
                   11942:     for (k=agegomp;k<agemortsup;k++){
                   11943:       lpop[k]=(lsurv[k]+lsurv[k+1])/2.;
                   11944:       sumlpop=sumlpop+lpop[k];
                   11945:     }
                   11946:     
                   11947:     tpop[agegomp]=sumlpop;
                   11948:     for (k=agegomp;k<(agemortsup-3);k++){
                   11949:       /*  tpop[k+1]=2;*/
                   11950:       tpop[k+1]=tpop[k]-lpop[k];
                   11951:     }
                   11952:     
                   11953:     
                   11954:     printf("\nAge   lx     qx    dx    Lx     Tx     e(x)\n");
                   11955:     for (k=agegomp;k<(agemortsup-2);k++) 
                   11956:       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]);
                   11957:     
                   11958:     
                   11959:     replace_back_to_slash(pathc,pathcd); /* Even gnuplot wants a / */
1.220     brouard  11960:                ageminpar=50;
                   11961:                agemaxpar=100;
1.194     brouard  11962:     if(ageminpar == AGEOVERFLOW ||agemaxpar == AGEOVERFLOW){
                   11963:        printf("Warning! Error in gnuplot file with ageminpar %f or agemaxpar %f overflow\n\
                   11964: This is probably because your parameter file doesn't \n  contain the exact number of lines (or columns) corresponding to your model line.\n\
                   11965: Please run with mle=-1 to get a correct covariance matrix.\n",ageminpar,agemaxpar);
                   11966:        fprintf(ficlog,"Warning! Error in gnuplot file with ageminpar %f or agemaxpar %f overflow\n\
                   11967: This is probably because your parameter file doesn't \n  contain the exact number of lines (or columns) corresponding to your model line.\n\
                   11968: Please run with mle=-1 to get a correct covariance matrix.\n",ageminpar,agemaxpar);
1.220     brouard  11969:     }else{
                   11970:                        printf("Warning! ageminpar %f and agemaxpar %f have been fixed because for simplification until it is fixed...\n\n",ageminpar,agemaxpar);
                   11971:                        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  11972:       printinggnuplotmort(fileresu, optionfilefiname,ageminpar,agemaxpar,fage, pathc,p);
1.220     brouard  11973:                }
1.201     brouard  11974:     printinghtmlmort(fileresu,title,datafile, firstpass, lastpass, \
1.126     brouard  11975:                     stepm, weightopt,\
                   11976:                     model,imx,p,matcov,agemortsup);
                   11977:     
                   11978:     free_vector(lsurv,1,AGESUP);
                   11979:     free_vector(lpop,1,AGESUP);
                   11980:     free_vector(tpop,1,AGESUP);
1.220     brouard  11981:     free_matrix(ximort,1,NDIM,1,NDIM);
1.290     brouard  11982:     free_ivector(dcwave,firstobs,lastobs);
                   11983:     free_vector(agecens,firstobs,lastobs);
                   11984:     free_vector(ageexmed,firstobs,lastobs);
                   11985:     free_ivector(cens,firstobs,lastobs);
1.220     brouard  11986: #ifdef GSL
1.136     brouard  11987: #endif
1.186     brouard  11988:   } /* Endof if mle==-3 mortality only */
1.205     brouard  11989:   /* Standard  */
                   11990:   else{ /* For mle !=- 3, could be 0 or 1 or 4 etc. */
                   11991:     globpr=0;/* Computes sum of likelihood for globpr=1 and funcone */
                   11992:     /* Computes likelihood for initial parameters, uses funcone to compute gpimx and gsw */
1.132     brouard  11993:     likelione(ficres, p, npar, nlstate, &globpr, &ipmx, &sw, &fretone, funcone); /* Prints the contributions to the likelihood */
1.126     brouard  11994:     printf("First Likeli=%12.6f ipmx=%ld sw=%12.6f",fretone,ipmx,sw);
                   11995:     for (k=1; k<=npar;k++)
                   11996:       printf(" %d %8.5f",k,p[k]);
                   11997:     printf("\n");
1.205     brouard  11998:     if(mle>=1){ /* Could be 1 or 2, Real Maximization */
                   11999:       /* mlikeli uses func not funcone */
1.247     brouard  12000:       /* for(i=1;i<nlstate;i++){ */
                   12001:       /*       /\*reducing xi for 1 to npar to 1 to ncovmodel; *\/ */
                   12002:       /*    mlikeli(ficres,p, ncovmodel, ncovmodel, nlstate, ftol, funcnoprod); */
                   12003:       /* } */
1.205     brouard  12004:       mlikeli(ficres,p, npar, ncovmodel, nlstate, ftol, func);
                   12005:     }
                   12006:     if(mle==0) {/* No optimization, will print the likelihoods for the datafile */
                   12007:       globpr=0;/* Computes sum of likelihood for globpr=1 and funcone */
                   12008:       /* Computes likelihood for initial parameters, uses funcone to compute gpimx and gsw */
                   12009:       likelione(ficres, p, npar, nlstate, &globpr, &ipmx, &sw, &fretone, funcone); /* Prints the contributions to the likelihood */
                   12010:     }
                   12011:     globpr=1; /* again, to print the individual contributions using computed gpimx and gsw */
1.126     brouard  12012:     likelione(ficres, p, npar, nlstate, &globpr, &ipmx, &sw, &fretone, funcone); /* Prints the contributions to the likelihood */
                   12013:     printf("Second Likeli=%12.6f ipmx=%ld sw=%12.6f",fretone,ipmx,sw);
                   12014:     for (k=1; k<=npar;k++)
                   12015:       printf(" %d %8.5f",k,p[k]);
                   12016:     printf("\n");
                   12017:     
                   12018:     /*--------- results files --------------*/
1.283     brouard  12019:     /* 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  12020:     
                   12021:     
                   12022:     fprintf(ficres,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
                   12023:     printf("# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
                   12024:     fprintf(ficlog,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
                   12025:     for(i=1,jk=1; i <=nlstate; i++){
                   12026:       for(k=1; k <=(nlstate+ndeath); k++){
1.225     brouard  12027:        if (k != i) {
                   12028:          printf("%d%d ",i,k);
                   12029:          fprintf(ficlog,"%d%d ",i,k);
                   12030:          fprintf(ficres,"%1d%1d ",i,k);
                   12031:          for(j=1; j <=ncovmodel; j++){
                   12032:            printf("%12.7f ",p[jk]);
                   12033:            fprintf(ficlog,"%12.7f ",p[jk]);
                   12034:            fprintf(ficres,"%12.7f ",p[jk]);
                   12035:            jk++; 
                   12036:          }
                   12037:          printf("\n");
                   12038:          fprintf(ficlog,"\n");
                   12039:          fprintf(ficres,"\n");
                   12040:        }
1.126     brouard  12041:       }
                   12042:     }
1.203     brouard  12043:     if(mle != 0){
                   12044:       /* Computing hessian and covariance matrix only at a peak of the Likelihood, that is after optimization */
1.126     brouard  12045:       ftolhess=ftol; /* Usually correct */
1.203     brouard  12046:       hesscov(matcov, hess, p, npar, delti, ftolhess, func);
                   12047:       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");
                   12048:       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");
                   12049:       for(i=1,jk=1; i <=nlstate; i++){
1.225     brouard  12050:        for(k=1; k <=(nlstate+ndeath); k++){
                   12051:          if (k != i) {
                   12052:            printf("%d%d ",i,k);
                   12053:            fprintf(ficlog,"%d%d ",i,k);
                   12054:            for(j=1; j <=ncovmodel; j++){
                   12055:              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]));
                   12056:              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]));
                   12057:              jk++; 
                   12058:            }
                   12059:            printf("\n");
                   12060:            fprintf(ficlog,"\n");
                   12061:          }
                   12062:        }
1.193     brouard  12063:       }
1.203     brouard  12064:     } /* end of hesscov and Wald tests */
1.225     brouard  12065:     
1.203     brouard  12066:     /*  */
1.126     brouard  12067:     fprintf(ficres,"# Scales (for hessian or gradient estimation)\n");
                   12068:     printf("# Scales (for hessian or gradient estimation)\n");
                   12069:     fprintf(ficlog,"# Scales (for hessian or gradient estimation)\n");
                   12070:     for(i=1,jk=1; i <=nlstate; i++){
                   12071:       for(j=1; j <=nlstate+ndeath; j++){
1.225     brouard  12072:        if (j!=i) {
                   12073:          fprintf(ficres,"%1d%1d",i,j);
                   12074:          printf("%1d%1d",i,j);
                   12075:          fprintf(ficlog,"%1d%1d",i,j);
                   12076:          for(k=1; k<=ncovmodel;k++){
                   12077:            printf(" %.5e",delti[jk]);
                   12078:            fprintf(ficlog," %.5e",delti[jk]);
                   12079:            fprintf(ficres," %.5e",delti[jk]);
                   12080:            jk++;
                   12081:          }
                   12082:          printf("\n");
                   12083:          fprintf(ficlog,"\n");
                   12084:          fprintf(ficres,"\n");
                   12085:        }
1.126     brouard  12086:       }
                   12087:     }
                   12088:     
                   12089:     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  12090:     if(mle >= 1) /* To big for the screen */
1.126     brouard  12091:       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");
                   12092:     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");
                   12093:     /* # 121 Var(a12)\n\ */
                   12094:     /* # 122 Cov(b12,a12) Var(b12)\n\ */
                   12095:     /* # 131 Cov(a13,a12) Cov(a13,b12, Var(a13)\n\ */
                   12096:     /* # 132 Cov(b13,a12) Cov(b13,b12, Cov(b13,a13) Var(b13)\n\ */
                   12097:     /* # 212 Cov(a21,a12) Cov(a21,b12, Cov(a21,a13) Cov(a21,b13) Var(a21)\n\ */
                   12098:     /* # 212 Cov(b21,a12) Cov(b21,b12, Cov(b21,a13) Cov(b21,b13) Cov(b21,a21) Var(b21)\n\ */
                   12099:     /* # 232 Cov(a23,a12) Cov(a23,b12, Cov(a23,a13) Cov(a23,b13) Cov(a23,a21) Cov(a23,b21) Var(a23)\n\ */
                   12100:     /* # 232 Cov(b23,a12) Cov(b23,b12) ... Var (b23)\n" */
                   12101:     
                   12102:     
                   12103:     /* Just to have a covariance matrix which will be more understandable
                   12104:        even is we still don't want to manage dictionary of variables
                   12105:     */
                   12106:     for(itimes=1;itimes<=2;itimes++){
                   12107:       jj=0;
                   12108:       for(i=1; i <=nlstate; i++){
1.225     brouard  12109:        for(j=1; j <=nlstate+ndeath; j++){
                   12110:          if(j==i) continue;
                   12111:          for(k=1; k<=ncovmodel;k++){
                   12112:            jj++;
                   12113:            ca[0]= k+'a'-1;ca[1]='\0';
                   12114:            if(itimes==1){
                   12115:              if(mle>=1)
                   12116:                printf("#%1d%1d%d",i,j,k);
                   12117:              fprintf(ficlog,"#%1d%1d%d",i,j,k);
                   12118:              fprintf(ficres,"#%1d%1d%d",i,j,k);
                   12119:            }else{
                   12120:              if(mle>=1)
                   12121:                printf("%1d%1d%d",i,j,k);
                   12122:              fprintf(ficlog,"%1d%1d%d",i,j,k);
                   12123:              fprintf(ficres,"%1d%1d%d",i,j,k);
                   12124:            }
                   12125:            ll=0;
                   12126:            for(li=1;li <=nlstate; li++){
                   12127:              for(lj=1;lj <=nlstate+ndeath; lj++){
                   12128:                if(lj==li) continue;
                   12129:                for(lk=1;lk<=ncovmodel;lk++){
                   12130:                  ll++;
                   12131:                  if(ll<=jj){
                   12132:                    cb[0]= lk +'a'-1;cb[1]='\0';
                   12133:                    if(ll<jj){
                   12134:                      if(itimes==1){
                   12135:                        if(mle>=1)
                   12136:                          printf(" Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
                   12137:                        fprintf(ficlog," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
                   12138:                        fprintf(ficres," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
                   12139:                      }else{
                   12140:                        if(mle>=1)
                   12141:                          printf(" %.5e",matcov[jj][ll]); 
                   12142:                        fprintf(ficlog," %.5e",matcov[jj][ll]); 
                   12143:                        fprintf(ficres," %.5e",matcov[jj][ll]); 
                   12144:                      }
                   12145:                    }else{
                   12146:                      if(itimes==1){
                   12147:                        if(mle>=1)
                   12148:                          printf(" Var(%s%1d%1d)",ca,i,j);
                   12149:                        fprintf(ficlog," Var(%s%1d%1d)",ca,i,j);
                   12150:                        fprintf(ficres," Var(%s%1d%1d)",ca,i,j);
                   12151:                      }else{
                   12152:                        if(mle>=1)
                   12153:                          printf(" %.7e",matcov[jj][ll]); 
                   12154:                        fprintf(ficlog," %.7e",matcov[jj][ll]); 
                   12155:                        fprintf(ficres," %.7e",matcov[jj][ll]); 
                   12156:                      }
                   12157:                    }
                   12158:                  }
                   12159:                } /* end lk */
                   12160:              } /* end lj */
                   12161:            } /* end li */
                   12162:            if(mle>=1)
                   12163:              printf("\n");
                   12164:            fprintf(ficlog,"\n");
                   12165:            fprintf(ficres,"\n");
                   12166:            numlinepar++;
                   12167:          } /* end k*/
                   12168:        } /*end j */
1.126     brouard  12169:       } /* end i */
                   12170:     } /* end itimes */
                   12171:     
                   12172:     fflush(ficlog);
                   12173:     fflush(ficres);
1.225     brouard  12174:     while(fgets(line, MAXLINE, ficpar)) {
                   12175:       /* If line starts with a # it is a comment */
                   12176:       if (line[0] == '#') {
                   12177:        numlinepar++;
                   12178:        fputs(line,stdout);
                   12179:        fputs(line,ficparo);
                   12180:        fputs(line,ficlog);
                   12181:        continue;
                   12182:       }else
                   12183:        break;
                   12184:     }
                   12185:     
1.209     brouard  12186:     /* while((c=getc(ficpar))=='#' && c!= EOF){ */
                   12187:     /*   ungetc(c,ficpar); */
                   12188:     /*   fgets(line, MAXLINE, ficpar); */
                   12189:     /*   fputs(line,stdout); */
                   12190:     /*   fputs(line,ficparo); */
                   12191:     /* } */
                   12192:     /* ungetc(c,ficpar); */
1.126     brouard  12193:     
                   12194:     estepm=0;
1.209     brouard  12195:     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  12196:       
                   12197:       if (num_filled != 6) {
                   12198:        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);
                   12199:        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);
                   12200:        goto end;
                   12201:       }
                   12202:       printf("agemin=%lf agemax=%lf bage=%lf fage=%lf estepm=%d ftolpl=%lf\n",ageminpar,agemaxpar, bage, fage, estepm, ftolpl);
                   12203:     }
                   12204:     /* ftolpl=6*ftol*1.e5; /\* 6.e-3 make convergences in less than 80 loops for the prevalence limit *\/ */
                   12205:     /*ftolpl=6.e-4;*/ /* 6.e-3 make convergences in less than 80 loops for the prevalence limit */
                   12206:     
1.209     brouard  12207:     /* fscanf(ficpar,"agemin=%lf agemax=%lf bage=%lf fage=%lf estepm=%d ftolpl=%\n",&ageminpar,&agemaxpar, &bage, &fage, &estepm); */
1.126     brouard  12208:     if (estepm==0 || estepm < stepm) estepm=stepm;
                   12209:     if (fage <= 2) {
                   12210:       bage = ageminpar;
                   12211:       fage = agemaxpar;
                   12212:     }
                   12213:     
                   12214:     fprintf(ficres,"# agemin agemax for life expectancy, bage fage (if mle==0 ie no data nor Max likelihood).\n");
1.211     brouard  12215:     fprintf(ficres,"agemin=%.0f agemax=%.0f bage=%.0f fage=%.0f estepm=%d ftolpl=%e\n",ageminpar,agemaxpar,bage,fage, estepm, ftolpl);
                   12216:     fprintf(ficparo,"agemin=%.0f agemax=%.0f bage=%.0f fage=%.0f estepm=%d, ftolpl=%e\n",ageminpar,agemaxpar,bage,fage, estepm, ftolpl);
1.220     brouard  12217:                
1.186     brouard  12218:     /* Other stuffs, more or less useful */    
1.254     brouard  12219:     while(fgets(line, MAXLINE, ficpar)) {
                   12220:       /* If line starts with a # it is a comment */
                   12221:       if (line[0] == '#') {
                   12222:        numlinepar++;
                   12223:        fputs(line,stdout);
                   12224:        fputs(line,ficparo);
                   12225:        fputs(line,ficlog);
                   12226:        continue;
                   12227:       }else
                   12228:        break;
                   12229:     }
                   12230: 
                   12231:     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){
                   12232:       
                   12233:       if (num_filled != 7) {
                   12234:        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);
                   12235:        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);
                   12236:        goto end;
                   12237:       }
                   12238:       printf("begin-prev-date=%.lf/%.lf/%.lf end-prev-date=%.lf/%.lf/%.lf mov_average=%d\n",jprev1, mprev1,anprev1,jprev2, mprev2,anprev2,mobilav);
                   12239:       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);
                   12240:       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);
                   12241:       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  12242:     }
1.254     brouard  12243: 
                   12244:     while(fgets(line, MAXLINE, ficpar)) {
                   12245:       /* If line starts with a # it is a comment */
                   12246:       if (line[0] == '#') {
                   12247:        numlinepar++;
                   12248:        fputs(line,stdout);
                   12249:        fputs(line,ficparo);
                   12250:        fputs(line,ficlog);
                   12251:        continue;
                   12252:       }else
                   12253:        break;
1.126     brouard  12254:     }
                   12255:     
                   12256:     
                   12257:     dateprev1=anprev1+(mprev1-1)/12.+(jprev1-1)/365.;
                   12258:     dateprev2=anprev2+(mprev2-1)/12.+(jprev2-1)/365.;
                   12259:     
1.254     brouard  12260:     if((num_filled=sscanf(line,"pop_based=%d\n",&popbased)) !=EOF){
                   12261:       if (num_filled != 1) {
                   12262:        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);
                   12263:        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);
                   12264:        goto end;
                   12265:       }
                   12266:       printf("pop_based=%d\n",popbased);
                   12267:       fprintf(ficlog,"pop_based=%d\n",popbased);
                   12268:       fprintf(ficparo,"pop_based=%d\n",popbased);   
                   12269:       fprintf(ficres,"pop_based=%d\n",popbased);   
                   12270:     }
                   12271:      
1.258     brouard  12272:     /* Results */
                   12273:     nresult=0;
                   12274:     do{
                   12275:       if(!fgets(line, MAXLINE, ficpar)){
                   12276:        endishere=1;
                   12277:        parameterline=14;
                   12278:       }else if (line[0] == '#') {
                   12279:        /* If line starts with a # it is a comment */
1.254     brouard  12280:        numlinepar++;
                   12281:        fputs(line,stdout);
                   12282:        fputs(line,ficparo);
                   12283:        fputs(line,ficlog);
                   12284:        continue;
1.258     brouard  12285:       }else if(sscanf(line,"prevforecast=%[^\n]\n",modeltemp))
                   12286:        parameterline=11;
                   12287:       else if(sscanf(line,"backcast=%[^\n]\n",modeltemp))
                   12288:        parameterline=12;
                   12289:       else if(sscanf(line,"result:%[^\n]\n",modeltemp))
                   12290:        parameterline=13;
                   12291:       else{
                   12292:        parameterline=14;
1.254     brouard  12293:       }
1.258     brouard  12294:       switch (parameterline){ 
                   12295:       case 11:
                   12296:        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){
                   12297:          if (num_filled != 8) {
                   12298:            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);
                   12299:            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);
                   12300:            goto end;
                   12301:          }
                   12302:          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);
                   12303:          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);
                   12304:          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);
                   12305:          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);
                   12306:          /* day and month of proj2 are not used but only year anproj2.*/
1.273     brouard  12307:          dateproj1=anproj1+(mproj1-1)/12.+(jproj1-1)/365.;
                   12308:          dateproj2=anproj2+(mproj2-1)/12.+(jproj2-1)/365.;
                   12309: 
1.258     brouard  12310:        }
1.254     brouard  12311:        break;
1.258     brouard  12312:       case 12:
                   12313:        /*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);*/
                   12314:        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){
                   12315:          if (num_filled != 8) {
1.262     brouard  12316:            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);
                   12317:            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  12318:            goto end;
                   12319:          }
                   12320:          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);
                   12321:          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);
                   12322:          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);
                   12323:          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);
                   12324:          /* day and month of proj2 are not used but only year anproj2.*/
1.273     brouard  12325:          dateback1=anback1+(mback1-1)/12.+(jback1-1)/365.;
                   12326:          dateback2=anback2+(mback2-1)/12.+(jback2-1)/365.;
1.258     brouard  12327:        }
1.230     brouard  12328:        break;
1.258     brouard  12329:       case 13:
                   12330:        if((num_filled=sscanf(line,"result:%[^\n]\n",resultline)) !=EOF){
                   12331:          if (num_filled == 0){
                   12332:            resultline[0]='\0';
                   12333:            printf("Warning %d: no result line! It should be at minimum 'result: V2=0 V1=1 or result:.\n%s\n", num_filled, line);
                   12334:            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);
                   12335:            break;
                   12336:          } else if (num_filled != 1){
                   12337:            printf("ERROR %d: result line! It should be at minimum 'result: V2=0 V1=1 or result:.' %s\n",num_filled, line);
                   12338:            fprintf(ficlog,"ERROR %d: result line! It should be at minimum 'result: V2=0 V1=1 or result:.' %s\n",num_filled, line);
                   12339:          }
                   12340:          nresult++; /* Sum of resultlines */
                   12341:          printf("Result %d: result=%s\n",nresult, resultline);
                   12342:          if(nresult > MAXRESULTLINES){
                   12343:            printf("ERROR: Current version of IMaCh limits the number of resultlines to %d, you used %d\n",MAXRESULTLINES,nresult);
                   12344:            fprintf(ficlog,"ERROR: Current version of IMaCh limits the number of resultlines to %d, you used %d\n",MAXRESULTLINES,nresult);
                   12345:            goto end;
                   12346:          }
                   12347:          decoderesult(resultline, nresult); /* Fills TKresult[nresult] combination and Tresult[nresult][k4+1] combination values */
                   12348:          fprintf(ficparo,"result: %s\n",resultline);
                   12349:          fprintf(ficres,"result: %s\n",resultline);
                   12350:          fprintf(ficlog,"result: %s\n",resultline);
1.230     brouard  12351:          break;
1.258     brouard  12352:        case 14: 
1.259     brouard  12353:          if(ncovmodel >2 && nresult==0 ){
                   12354:            printf("ERROR: no result lines! It should be at minimum 'result: V2=0 V1=1 or result:.' %s\n",line);
1.258     brouard  12355:            goto end;
                   12356:          }
1.259     brouard  12357:          break;
1.258     brouard  12358:        default:
                   12359:          nresult=1;
                   12360:          decoderesult(".",nresult ); /* No covariate */
                   12361:        }
                   12362:       } /* End switch parameterline */
                   12363:     }while(endishere==0); /* End do */
1.126     brouard  12364:     
1.230     brouard  12365:     /* freqsummary(fileres, agemin, agemax, s, agev, nlstate, imx,Tvaraff,nbcode, ncodemax,mint,anint); */
1.145     brouard  12366:     /* ,dateprev1,dateprev2,jprev1, mprev1,anprev1,jprev2, mprev2,anprev2); */
1.126     brouard  12367:     
                   12368:     replace_back_to_slash(pathc,pathcd); /* Even gnuplot wants a / */
1.194     brouard  12369:     if(ageminpar == AGEOVERFLOW ||agemaxpar == -AGEOVERFLOW){
1.230     brouard  12370:       printf("Warning! Error in gnuplot file with ageminpar %f or agemaxpar %f overflow\n\
1.194     brouard  12371: This is probably because your parameter file doesn't \n  contain the exact number of lines (or columns) corresponding to your model line.\n\
                   12372: Please run with mle=-1 to get a correct covariance matrix.\n",ageminpar,agemaxpar);
1.230     brouard  12373:       fprintf(ficlog,"Warning! Error in gnuplot file with ageminpar %f or agemaxpar %f overflow\n\
1.194     brouard  12374: This is probably because your parameter file doesn't \n  contain the exact number of lines (or columns) corresponding to your model line.\n\
                   12375: Please run with mle=-1 to get a correct covariance matrix.\n",ageminpar,agemaxpar);
1.220     brouard  12376:     }else{
1.270     brouard  12377:       /* printinggnuplot(fileresu, optionfilefiname,ageminpar,agemaxpar,fage, prevfcast, backcast, pathc,p, (int)anproj1-(int)agemin, (int)anback1-(int)agemax+1); */
                   12378:       printinggnuplot(fileresu, optionfilefiname,ageminpar,agemaxpar,bage, fage, prevfcast, backcast, pathc,p, (int)anproj1-bage, (int)anback1-fage);
1.220     brouard  12379:     }
                   12380:     printinghtml(fileresu,title,datafile, firstpass, lastpass, stepm, weightopt, \
1.258     brouard  12381:                 model,imx,jmin,jmax,jmean,rfileres,popforecast,mobilav,prevfcast,mobilavproj,backcast, estepm, \
1.273     brouard  12382:                 jprev1,mprev1,anprev1,dateprev1, dateproj1, dateback1,jprev2,mprev2,anprev2,dateprev2,dateproj2, dateback2);
1.220     brouard  12383:                
1.225     brouard  12384:     /*------------ free_vector  -------------*/
                   12385:     /*  chdir(path); */
1.220     brouard  12386:                
1.215     brouard  12387:     /* free_ivector(wav,1,imx); */  /* Moved after last prevalence call */
                   12388:     /* free_imatrix(dh,1,lastpass-firstpass+2,1,imx); */
                   12389:     /* free_imatrix(bh,1,lastpass-firstpass+2,1,imx); */
                   12390:     /* free_imatrix(mw,1,lastpass-firstpass+2,1,imx);    */
1.290     brouard  12391:     free_lvector(num,firstobs,lastobs);
                   12392:     free_vector(agedc,firstobs,lastobs);
1.126     brouard  12393:     /*free_matrix(covar,0,NCOVMAX,1,n);*/
                   12394:     /*free_matrix(covar,1,NCOVMAX,1,n);*/
                   12395:     fclose(ficparo);
                   12396:     fclose(ficres);
1.220     brouard  12397:                
                   12398:                
1.186     brouard  12399:     /* Other results (useful)*/
1.220     brouard  12400:                
                   12401:                
1.126     brouard  12402:     /*--------------- Prevalence limit  (period or stable prevalence) --------------*/
1.180     brouard  12403:     /*#include "prevlim.h"*/  /* Use ficrespl, ficlog */
                   12404:     prlim=matrix(1,nlstate,1,nlstate);
1.209     brouard  12405:     prevalence_limit(p, prlim,  ageminpar, agemaxpar, ftolpl, &ncvyear);
1.126     brouard  12406:     fclose(ficrespl);
                   12407: 
                   12408:     /*------------- h Pij x at various ages ------------*/
1.180     brouard  12409:     /*#include "hpijx.h"*/
                   12410:     hPijx(p, bage, fage);
1.145     brouard  12411:     fclose(ficrespij);
1.227     brouard  12412:     
1.220     brouard  12413:     /* ncovcombmax=  pow(2,cptcoveff); */
1.219     brouard  12414:     /*-------------- Variance of one-step probabilities---*/
1.145     brouard  12415:     k=1;
1.126     brouard  12416:     varprob(optionfilefiname, matcov, p, delti, nlstate, bage, fage,k,Tvar,nbcode, ncodemax,strstart);
1.227     brouard  12417:     
1.269     brouard  12418:     /* Prevalence for each covariate combination in probs[age][status][cov] */
                   12419:     probs= ma3x(AGEINF,AGESUP,1,nlstate+ndeath, 1,ncovcombmax);
                   12420:     for(i=AGEINF;i<=AGESUP;i++)
1.219     brouard  12421:       for(j=1;j<=nlstate+ndeath;j++) /* ndeath is useless but a necessity to be compared with mobaverages */
1.225     brouard  12422:        for(k=1;k<=ncovcombmax;k++)
                   12423:          probs[i][j][k]=0.;
1.269     brouard  12424:     prevalence(probs, ageminpar, agemaxpar, s, agev, nlstate, imx, Tvar, nbcode, 
                   12425:               ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass);
1.219     brouard  12426:     if (mobilav!=0 ||mobilavproj !=0 ) {
1.269     brouard  12427:       mobaverages= ma3x(AGEINF, AGESUP,1,nlstate+ndeath, 1,ncovcombmax);
                   12428:       for(i=AGEINF;i<=AGESUP;i++)
1.268     brouard  12429:        for(j=1;j<=nlstate+ndeath;j++)
1.227     brouard  12430:          for(k=1;k<=ncovcombmax;k++)
                   12431:            mobaverages[i][j][k]=0.;
1.219     brouard  12432:       mobaverage=mobaverages;
                   12433:       if (mobilav!=0) {
1.235     brouard  12434:        printf("Movingaveraging observed prevalence\n");
1.258     brouard  12435:        fprintf(ficlog,"Movingaveraging observed prevalence\n");
1.227     brouard  12436:        if (movingaverage(probs, ageminpar, agemaxpar, mobaverage, mobilav)!=0){
                   12437:          fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);
                   12438:          printf(" Error in movingaverage mobilav=%d\n",mobilav);
                   12439:        }
1.269     brouard  12440:       } else if (mobilavproj !=0) {
1.235     brouard  12441:        printf("Movingaveraging projected observed prevalence\n");
1.258     brouard  12442:        fprintf(ficlog,"Movingaveraging projected observed prevalence\n");
1.227     brouard  12443:        if (movingaverage(probs, ageminpar, agemaxpar, mobaverage, mobilavproj)!=0){
                   12444:          fprintf(ficlog," Error in movingaverage mobilavproj=%d\n",mobilavproj);
                   12445:          printf(" Error in movingaverage mobilavproj=%d\n",mobilavproj);
                   12446:        }
1.269     brouard  12447:       }else{
                   12448:        printf("Internal error moving average\n");
                   12449:        fflush(stdout);
                   12450:        exit(1);
1.219     brouard  12451:       }
                   12452:     }/* end if moving average */
1.227     brouard  12453:     
1.126     brouard  12454:     /*---------- Forecasting ------------------*/
                   12455:     if(prevfcast==1){
                   12456:       /*    if(stepm ==1){*/
1.269     brouard  12457:       prevforecast(fileresu, anproj1, mproj1, jproj1, agemin, agemax, dateprev1, dateprev2, mobilavproj, mobaverage, bage, fage, firstpass, lastpass, anproj2, p, cptcoveff);
1.126     brouard  12458:     }
1.269     brouard  12459: 
                   12460:     /* Backcasting */
1.217     brouard  12461:     if(backcast==1){
1.219     brouard  12462:       ddnewms=matrix(1,nlstate+ndeath,1,nlstate+ndeath);       
                   12463:       ddoldms=matrix(1,nlstate+ndeath,1,nlstate+ndeath);       
                   12464:       ddsavms=matrix(1,nlstate+ndeath,1,nlstate+ndeath);
                   12465: 
                   12466:       /*--------------- Back Prevalence limit  (period or stable prevalence) --------------*/
                   12467: 
                   12468:       bprlim=matrix(1,nlstate,1,nlstate);
1.269     brouard  12469: 
1.219     brouard  12470:       back_prevalence_limit(p, bprlim,  ageminpar, agemaxpar, ftolpl, &ncvyear, dateprev1, dateprev2, firstpass, lastpass, mobilavproj);
                   12471:       fclose(ficresplb);
                   12472: 
1.222     brouard  12473:       hBijx(p, bage, fage, mobaverage);
                   12474:       fclose(ficrespijb);
1.219     brouard  12475: 
1.269     brouard  12476:       prevbackforecast(fileresu, mobaverage, anback1, mback1, jback1, agemin, agemax, dateprev1, dateprev2,
                   12477:                       mobilavproj, bage, fage, firstpass, lastpass, anback2, p, cptcoveff);
                   12478:       varbprlim(fileresu, nresult, mobaverage, mobilavproj, bage, fage, bprlim, &ncvyear, ftolpl, p, matcov, delti, stepm, cptcoveff);
1.268     brouard  12479: 
                   12480:       
1.269     brouard  12481:       free_matrix(bprlim,1,nlstate,1,nlstate); /*here or after loop ? */
1.219     brouard  12482:       free_matrix(ddnewms, 1, nlstate+ndeath, 1, nlstate+ndeath);
                   12483:       free_matrix(ddsavms, 1, nlstate+ndeath, 1, nlstate+ndeath);
                   12484:       free_matrix(ddoldms, 1, nlstate+ndeath, 1, nlstate+ndeath);
1.269     brouard  12485:     }    /* end  Backcasting */
1.268     brouard  12486:  
1.186     brouard  12487:  
                   12488:     /* ------ Other prevalence ratios------------ */
1.126     brouard  12489: 
1.215     brouard  12490:     free_ivector(wav,1,imx);
                   12491:     free_imatrix(dh,1,lastpass-firstpass+2,1,imx);
                   12492:     free_imatrix(bh,1,lastpass-firstpass+2,1,imx);
                   12493:     free_imatrix(mw,1,lastpass-firstpass+2,1,imx);   
1.218     brouard  12494:                
                   12495:                
1.127     brouard  12496:     /*---------- Health expectancies, no variances ------------*/
1.218     brouard  12497:                
1.201     brouard  12498:     strcpy(filerese,"E_");
                   12499:     strcat(filerese,fileresu);
1.126     brouard  12500:     if((ficreseij=fopen(filerese,"w"))==NULL) {
                   12501:       printf("Problem with Health Exp. resultfile: %s\n", filerese); exit(0);
                   12502:       fprintf(ficlog,"Problem with Health Exp. resultfile: %s\n", filerese); exit(0);
                   12503:     }
1.208     brouard  12504:     printf("Computing Health Expectancies: result on file '%s' ...", filerese);fflush(stdout);
                   12505:     fprintf(ficlog,"Computing Health Expectancies: result on file '%s' ...", filerese);fflush(ficlog);
1.238     brouard  12506: 
                   12507:     pstamp(ficreseij);
1.219     brouard  12508:                
1.235     brouard  12509:     i1=pow(2,cptcoveff); /* Number of combination of dummy covariates */
                   12510:     if (cptcovn < 1){i1=1;}
                   12511:     
                   12512:     for(nres=1; nres <= nresult; nres++) /* For each resultline */
                   12513:     for(k=1; k<=i1;k++){ /* For any combination of dummy covariates, fixed and varying */
1.253     brouard  12514:       if(i1 != 1 && TKresult[nres]!= k)
1.235     brouard  12515:        continue;
1.219     brouard  12516:       fprintf(ficreseij,"\n#****** ");
1.235     brouard  12517:       printf("\n#****** ");
1.225     brouard  12518:       for(j=1;j<=cptcoveff;j++) {
1.227     brouard  12519:        fprintf(ficreseij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
1.235     brouard  12520:        printf("V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   12521:       }
                   12522:       for (j=1; j<= nsq; j++){ /* For each selected (single) quantitative value */
                   12523:        printf(" V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]);
                   12524:        fprintf(ficreseij," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]);
1.219     brouard  12525:       }
                   12526:       fprintf(ficreseij,"******\n");
1.235     brouard  12527:       printf("******\n");
1.219     brouard  12528:       
                   12529:       eij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
                   12530:       oldm=oldms;savm=savms;
1.235     brouard  12531:       evsij(eij, p, nlstate, stepm, (int) bage, (int)fage, oldm, savm, k, estepm, strstart, nres);  
1.127     brouard  12532:       
1.219     brouard  12533:       free_ma3x(eij,1,nlstate,1,nlstate,(int) bage, (int)fage);
1.127     brouard  12534:     }
                   12535:     fclose(ficreseij);
1.208     brouard  12536:     printf("done evsij\n");fflush(stdout);
                   12537:     fprintf(ficlog,"done evsij\n");fflush(ficlog);
1.269     brouard  12538: 
1.218     brouard  12539:                
1.227     brouard  12540:     /*---------- State-specific expectancies and variances ------------*/
1.218     brouard  12541:                
1.201     brouard  12542:     strcpy(filerest,"T_");
                   12543:     strcat(filerest,fileresu);
1.127     brouard  12544:     if((ficrest=fopen(filerest,"w"))==NULL) {
                   12545:       printf("Problem with total LE resultfile: %s\n", filerest);goto end;
                   12546:       fprintf(ficlog,"Problem with total LE resultfile: %s\n", filerest);goto end;
                   12547:     }
1.208     brouard  12548:     printf("Computing Total Life expectancies with their standard errors: file '%s' ...\n", filerest); fflush(stdout);
                   12549:     fprintf(ficlog,"Computing Total Life expectancies with their standard errors: file '%s' ...\n", filerest); fflush(ficlog);
1.201     brouard  12550:     strcpy(fileresstde,"STDE_");
                   12551:     strcat(fileresstde,fileresu);
1.126     brouard  12552:     if((ficresstdeij=fopen(fileresstde,"w"))==NULL) {
1.227     brouard  12553:       printf("Problem with State specific Exp. and std errors resultfile: %s\n", fileresstde); exit(0);
                   12554:       fprintf(ficlog,"Problem with State specific Exp. and std errors resultfile: %s\n", fileresstde); exit(0);
1.126     brouard  12555:     }
1.227     brouard  12556:     printf("  Computing State-specific Expectancies and standard errors: result on file '%s' \n", fileresstde);
                   12557:     fprintf(ficlog,"  Computing State-specific Expectancies and standard errors: result on file '%s' \n", fileresstde);
1.126     brouard  12558: 
1.201     brouard  12559:     strcpy(filerescve,"CVE_");
                   12560:     strcat(filerescve,fileresu);
1.126     brouard  12561:     if((ficrescveij=fopen(filerescve,"w"))==NULL) {
1.227     brouard  12562:       printf("Problem with Covar. State-specific Exp. resultfile: %s\n", filerescve); exit(0);
                   12563:       fprintf(ficlog,"Problem with Covar. State-specific Exp. resultfile: %s\n", filerescve); exit(0);
1.126     brouard  12564:     }
1.227     brouard  12565:     printf("    Computing Covar. of State-specific Expectancies: result on file '%s' \n", filerescve);
                   12566:     fprintf(ficlog,"    Computing Covar. of State-specific Expectancies: result on file '%s' \n", filerescve);
1.126     brouard  12567: 
1.201     brouard  12568:     strcpy(fileresv,"V_");
                   12569:     strcat(fileresv,fileresu);
1.126     brouard  12570:     if((ficresvij=fopen(fileresv,"w"))==NULL) {
                   12571:       printf("Problem with variance resultfile: %s\n", fileresv);exit(0);
                   12572:       fprintf(ficlog,"Problem with variance resultfile: %s\n", fileresv);exit(0);
                   12573:     }
1.227     brouard  12574:     printf("      Computing Variance-covariance of State-specific Expectancies: file '%s' ... ", fileresv);fflush(stdout);
                   12575:     fprintf(ficlog,"      Computing Variance-covariance of State-specific Expectancies: file '%s' ... ", fileresv);fflush(ficlog);
1.126     brouard  12576: 
1.235     brouard  12577:     i1=pow(2,cptcoveff); /* Number of combination of dummy covariates */
                   12578:     if (cptcovn < 1){i1=1;}
                   12579:     
                   12580:     for(nres=1; nres <= nresult; nres++) /* For each resultline */
                   12581:     for(k=1; k<=i1;k++){ /* For any combination of dummy covariates, fixed and varying */
1.253     brouard  12582:       if(i1 != 1 && TKresult[nres]!= k)
1.235     brouard  12583:        continue;
1.242     brouard  12584:       printf("\n#****** Result for:");
                   12585:       fprintf(ficrest,"\n#****** Result for:");
                   12586:       fprintf(ficlog,"\n#****** Result for:");
1.227     brouard  12587:       for(j=1;j<=cptcoveff;j++){ 
                   12588:        printf("V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   12589:        fprintf(ficrest,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   12590:        fprintf(ficlog,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   12591:       }
1.235     brouard  12592:       for (j=1; j<= nsq; j++){ /* For each selected (single) quantitative value */
                   12593:        printf(" V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]);
                   12594:        fprintf(ficrest," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]);
                   12595:        fprintf(ficlog," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]);
                   12596:       }        
1.208     brouard  12597:       fprintf(ficrest,"******\n");
1.227     brouard  12598:       fprintf(ficlog,"******\n");
                   12599:       printf("******\n");
1.208     brouard  12600:       
                   12601:       fprintf(ficresstdeij,"\n#****** ");
                   12602:       fprintf(ficrescveij,"\n#****** ");
1.225     brouard  12603:       for(j=1;j<=cptcoveff;j++) {
1.227     brouard  12604:        fprintf(ficresstdeij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   12605:        fprintf(ficrescveij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
1.208     brouard  12606:       }
1.235     brouard  12607:       for (j=1; j<= nsq; j++){ /* For each selected (single) quantitative value */
                   12608:        fprintf(ficresstdeij," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]);
                   12609:        fprintf(ficrescveij," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]);
                   12610:       }        
1.208     brouard  12611:       fprintf(ficresstdeij,"******\n");
                   12612:       fprintf(ficrescveij,"******\n");
                   12613:       
                   12614:       fprintf(ficresvij,"\n#****** ");
1.238     brouard  12615:       /* pstamp(ficresvij); */
1.225     brouard  12616:       for(j=1;j<=cptcoveff;j++) 
1.227     brouard  12617:        fprintf(ficresvij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
1.235     brouard  12618:       for (j=1; j<= nsq; j++){ /* For each selected (single) quantitative value */
                   12619:        fprintf(ficresvij," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]);
                   12620:       }        
1.208     brouard  12621:       fprintf(ficresvij,"******\n");
                   12622:       
                   12623:       eij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
                   12624:       oldm=oldms;savm=savms;
1.235     brouard  12625:       printf(" cvevsij ");
                   12626:       fprintf(ficlog, " cvevsij ");
                   12627:       cvevsij(eij, p, nlstate, stepm, (int) bage, (int)fage, oldm, savm, k, estepm, delti, matcov, strstart, nres);
1.208     brouard  12628:       printf(" end cvevsij \n ");
                   12629:       fprintf(ficlog, " end cvevsij \n ");
                   12630:       
                   12631:       /*
                   12632:        */
                   12633:       /* goto endfree; */
                   12634:       
                   12635:       vareij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
                   12636:       pstamp(ficrest);
                   12637:       
1.269     brouard  12638:       epj=vector(1,nlstate+1);
1.208     brouard  12639:       for(vpopbased=0; vpopbased <= popbased; vpopbased++){ /* Done for vpopbased=0 and vpopbased=1 if popbased==1*/
1.227     brouard  12640:        oldm=oldms;savm=savms; /* ZZ Segmentation fault */
                   12641:        cptcod= 0; /* To be deleted */
                   12642:        printf("varevsij vpopbased=%d \n",vpopbased);
                   12643:        fprintf(ficlog, "varevsij vpopbased=%d \n",vpopbased);
1.235     brouard  12644:        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  12645:        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 ");
                   12646:        if(vpopbased==1)
                   12647:          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);
                   12648:        else
1.288     brouard  12649:          fprintf(ficrest,"the age specific forward period (stable) prevalences in each health state \n");
1.227     brouard  12650:        fprintf(ficrest,"# Age popbased mobilav e.. (std) ");
                   12651:        for (i=1;i<=nlstate;i++) fprintf(ficrest,"e.%d (std) ",i);
                   12652:        fprintf(ficrest,"\n");
                   12653:        /* printf("Which p?\n"); for(i=1;i<=npar;i++)printf("p[i=%d]=%lf,",i,p[i]);printf("\n"); */
1.288     brouard  12654:        printf("Computing age specific forward period (stable) prevalences in each health state \n");
                   12655:        fprintf(ficlog,"Computing age specific forward period (stable) prevalences in each health state \n");
1.227     brouard  12656:        for(age=bage; age <=fage ;age++){
1.235     brouard  12657:          prevalim(prlim, nlstate, p, age, oldm, savm, ftolpl, &ncvyear, k, nres); /*ZZ Is it the correct prevalim */
1.227     brouard  12658:          if (vpopbased==1) {
                   12659:            if(mobilav ==0){
                   12660:              for(i=1; i<=nlstate;i++)
                   12661:                prlim[i][i]=probs[(int)age][i][k];
                   12662:            }else{ /* mobilav */ 
                   12663:              for(i=1; i<=nlstate;i++)
                   12664:                prlim[i][i]=mobaverage[(int)age][i][k];
                   12665:            }
                   12666:          }
1.219     brouard  12667:          
1.227     brouard  12668:          fprintf(ficrest," %4.0f %d %d",age, vpopbased, mobilav);
                   12669:          /* fprintf(ficrest," %4.0f %d %d %d %d",age, vpopbased, mobilav,Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]); */ /* to be done */
                   12670:          /* printf(" age %4.0f ",age); */
                   12671:          for(j=1, epj[nlstate+1]=0.;j <=nlstate;j++){
                   12672:            for(i=1, epj[j]=0.;i <=nlstate;i++) {
                   12673:              epj[j] += prlim[i][i]*eij[i][j][(int)age];
                   12674:              /*ZZZ  printf("%lf %lf ", prlim[i][i] ,eij[i][j][(int)age]);*/
                   12675:              /* printf("%lf %lf ", prlim[i][i] ,eij[i][j][(int)age]); */
                   12676:            }
                   12677:            epj[nlstate+1] +=epj[j];
                   12678:          }
                   12679:          /* printf(" age %4.0f \n",age); */
1.219     brouard  12680:          
1.227     brouard  12681:          for(i=1, vepp=0.;i <=nlstate;i++)
                   12682:            for(j=1;j <=nlstate;j++)
                   12683:              vepp += vareij[i][j][(int)age];
                   12684:          fprintf(ficrest," %7.3f (%7.3f)", epj[nlstate+1],sqrt(vepp));
                   12685:          for(j=1;j <=nlstate;j++){
                   12686:            fprintf(ficrest," %7.3f (%7.3f)", epj[j],sqrt(vareij[j][j][(int)age]));
                   12687:          }
                   12688:          fprintf(ficrest,"\n");
                   12689:        }
1.208     brouard  12690:       } /* End vpopbased */
1.269     brouard  12691:       free_vector(epj,1,nlstate+1);
1.208     brouard  12692:       free_ma3x(eij,1,nlstate,1,nlstate,(int) bage, (int)fage);
                   12693:       free_ma3x(vareij,1,nlstate,1,nlstate,(int) bage, (int)fage);
1.235     brouard  12694:       printf("done selection\n");fflush(stdout);
                   12695:       fprintf(ficlog,"done selection\n");fflush(ficlog);
1.208     brouard  12696:       
1.235     brouard  12697:     } /* End k selection */
1.227     brouard  12698: 
                   12699:     printf("done State-specific expectancies\n");fflush(stdout);
                   12700:     fprintf(ficlog,"done State-specific expectancies\n");fflush(ficlog);
                   12701: 
1.288     brouard  12702:     /* variance-covariance of forward period prevalence*/
1.269     brouard  12703:     varprlim(fileresu, nresult, mobaverage, mobilavproj, bage, fage, prlim, &ncvyear, ftolpl, p, matcov, delti, stepm, cptcoveff);
1.268     brouard  12704: 
1.227     brouard  12705:     
1.290     brouard  12706:     free_vector(weight,firstobs,lastobs);
1.227     brouard  12707:     free_imatrix(Tvard,1,NCOVMAX,1,2);
1.290     brouard  12708:     free_imatrix(s,1,maxwav+1,firstobs,lastobs);
                   12709:     free_matrix(anint,1,maxwav,firstobs,lastobs); 
                   12710:     free_matrix(mint,1,maxwav,firstobs,lastobs);
                   12711:     free_ivector(cod,firstobs,lastobs);
1.227     brouard  12712:     free_ivector(tab,1,NCOVMAX);
                   12713:     fclose(ficresstdeij);
                   12714:     fclose(ficrescveij);
                   12715:     fclose(ficresvij);
                   12716:     fclose(ficrest);
                   12717:     fclose(ficpar);
                   12718:     
                   12719:     
1.126     brouard  12720:     /*---------- End : free ----------------*/
1.219     brouard  12721:     if (mobilav!=0 ||mobilavproj !=0)
1.269     brouard  12722:       free_ma3x(mobaverages,AGEINF, AGESUP,1,nlstate+ndeath, 1,ncovcombmax); /* We need to have a squared matrix with prevalence of the dead! */
                   12723:     free_ma3x(probs,AGEINF,AGESUP,1,nlstate+ndeath, 1,ncovcombmax);
1.220     brouard  12724:     free_matrix(prlim,1,nlstate,1,nlstate); /*here or after loop ? */
                   12725:     free_matrix(pmmij,1,nlstate+ndeath,1,nlstate+ndeath);
1.126     brouard  12726:   }  /* mle==-3 arrives here for freeing */
1.227     brouard  12727:   /* endfree:*/
                   12728:   free_matrix(oldms, 1,nlstate+ndeath,1,nlstate+ndeath);
                   12729:   free_matrix(newms, 1,nlstate+ndeath,1,nlstate+ndeath);
                   12730:   free_matrix(savms, 1,nlstate+ndeath,1,nlstate+ndeath);
1.290     brouard  12731:   if(ntv+nqtv>=1)free_ma3x(cotvar,1,maxwav,1,ntv+nqtv,firstobs,lastobs);
                   12732:   if(nqtv>=1)free_ma3x(cotqvar,1,maxwav,1,nqtv,firstobs,lastobs);
                   12733:   if(nqv>=1)free_matrix(coqvar,1,nqv,firstobs,lastobs);
                   12734:   free_matrix(covar,0,NCOVMAX,firstobs,lastobs);
1.227     brouard  12735:   free_matrix(matcov,1,npar,1,npar);
                   12736:   free_matrix(hess,1,npar,1,npar);
                   12737:   /*free_vector(delti,1,npar);*/
                   12738:   free_ma3x(delti3,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel); 
                   12739:   free_matrix(agev,1,maxwav,1,imx);
1.269     brouard  12740:   free_ma3x(paramstart,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel);
1.227     brouard  12741:   free_ma3x(param,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel);
                   12742:   
                   12743:   free_ivector(ncodemax,1,NCOVMAX);
                   12744:   free_ivector(ncodemaxwundef,1,NCOVMAX);
                   12745:   free_ivector(Dummy,-1,NCOVMAX);
                   12746:   free_ivector(Fixed,-1,NCOVMAX);
1.238     brouard  12747:   free_ivector(DummyV,1,NCOVMAX);
                   12748:   free_ivector(FixedV,1,NCOVMAX);
1.227     brouard  12749:   free_ivector(Typevar,-1,NCOVMAX);
                   12750:   free_ivector(Tvar,1,NCOVMAX);
1.234     brouard  12751:   free_ivector(TvarsQ,1,NCOVMAX);
                   12752:   free_ivector(TvarsQind,1,NCOVMAX);
                   12753:   free_ivector(TvarsD,1,NCOVMAX);
                   12754:   free_ivector(TvarsDind,1,NCOVMAX);
1.231     brouard  12755:   free_ivector(TvarFD,1,NCOVMAX);
                   12756:   free_ivector(TvarFDind,1,NCOVMAX);
1.232     brouard  12757:   free_ivector(TvarF,1,NCOVMAX);
                   12758:   free_ivector(TvarFind,1,NCOVMAX);
                   12759:   free_ivector(TvarV,1,NCOVMAX);
                   12760:   free_ivector(TvarVind,1,NCOVMAX);
                   12761:   free_ivector(TvarA,1,NCOVMAX);
                   12762:   free_ivector(TvarAind,1,NCOVMAX);
1.231     brouard  12763:   free_ivector(TvarFQ,1,NCOVMAX);
                   12764:   free_ivector(TvarFQind,1,NCOVMAX);
                   12765:   free_ivector(TvarVD,1,NCOVMAX);
                   12766:   free_ivector(TvarVDind,1,NCOVMAX);
                   12767:   free_ivector(TvarVQ,1,NCOVMAX);
                   12768:   free_ivector(TvarVQind,1,NCOVMAX);
1.230     brouard  12769:   free_ivector(Tvarsel,1,NCOVMAX);
                   12770:   free_vector(Tvalsel,1,NCOVMAX);
1.227     brouard  12771:   free_ivector(Tposprod,1,NCOVMAX);
                   12772:   free_ivector(Tprod,1,NCOVMAX);
                   12773:   free_ivector(Tvaraff,1,NCOVMAX);
                   12774:   free_ivector(invalidvarcomb,1,ncovcombmax);
                   12775:   free_ivector(Tage,1,NCOVMAX);
                   12776:   free_ivector(Tmodelind,1,NCOVMAX);
1.228     brouard  12777:   free_ivector(TmodelInvind,1,NCOVMAX);
                   12778:   free_ivector(TmodelInvQind,1,NCOVMAX);
1.227     brouard  12779:   
                   12780:   free_imatrix(nbcode,0,NCOVMAX,0,NCOVMAX);
                   12781:   /* free_imatrix(codtab,1,100,1,10); */
1.126     brouard  12782:   fflush(fichtm);
                   12783:   fflush(ficgp);
                   12784:   
1.227     brouard  12785:   
1.126     brouard  12786:   if((nberr >0) || (nbwarn>0)){
1.216     brouard  12787:     printf("End of Imach with %d errors and/or %d warnings. Please look at the log file for details.\n",nberr,nbwarn);
                   12788:     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  12789:   }else{
                   12790:     printf("End of Imach\n");
                   12791:     fprintf(ficlog,"End of Imach\n");
                   12792:   }
                   12793:   printf("See log file on %s\n",filelog);
                   12794:   /*  gettimeofday(&end_time, (struct timezone*)0);*/  /* after time */
1.157     brouard  12795:   /*(void) gettimeofday(&end_time,&tzp);*/
                   12796:   rend_time = time(NULL);  
                   12797:   end_time = *localtime(&rend_time);
                   12798:   /* tml = *localtime(&end_time.tm_sec); */
                   12799:   strcpy(strtend,asctime(&end_time));
1.126     brouard  12800:   printf("Local time at start %s\nLocal time at end   %s",strstart, strtend); 
                   12801:   fprintf(ficlog,"Local time at start %s\nLocal time at end   %s\n",strstart, strtend); 
1.157     brouard  12802:   printf("Total time used %s\n", asc_diff_time(rend_time -rstart_time,tmpout));
1.227     brouard  12803:   
1.157     brouard  12804:   printf("Total time was %.0lf Sec.\n", difftime(rend_time,rstart_time));
                   12805:   fprintf(ficlog,"Total time used %s\n", asc_diff_time(rend_time -rstart_time,tmpout));
                   12806:   fprintf(ficlog,"Total time was %.0lf Sec.\n", difftime(rend_time,rstart_time));
1.126     brouard  12807:   /*  printf("Total time was %d uSec.\n", total_usecs);*/
                   12808: /*   if(fileappend(fichtm,optionfilehtm)){ */
                   12809:   fprintf(fichtm,"<br>Local time at start %s<br>Local time at end   %s<br>\n</body></html>",strstart, strtend);
                   12810:   fclose(fichtm);
                   12811:   fprintf(fichtmcov,"<br>Local time at start %s<br>Local time at end   %s<br>\n</body></html>",strstart, strtend);
                   12812:   fclose(fichtmcov);
                   12813:   fclose(ficgp);
                   12814:   fclose(ficlog);
                   12815:   /*------ End -----------*/
1.227     brouard  12816:   
1.281     brouard  12817: 
                   12818: /* Executes gnuplot */
1.227     brouard  12819:   
                   12820:   printf("Before Current directory %s!\n",pathcd);
1.184     brouard  12821: #ifdef WIN32
1.227     brouard  12822:   if (_chdir(pathcd) != 0)
                   12823:     printf("Can't move to directory %s!\n",path);
                   12824:   if(_getcwd(pathcd,MAXLINE) > 0)
1.184     brouard  12825: #else
1.227     brouard  12826:     if(chdir(pathcd) != 0)
                   12827:       printf("Can't move to directory %s!\n", path);
                   12828:   if (getcwd(pathcd, MAXLINE) > 0)
1.184     brouard  12829: #endif 
1.126     brouard  12830:     printf("Current directory %s!\n",pathcd);
                   12831:   /*strcat(plotcmd,CHARSEPARATOR);*/
                   12832:   sprintf(plotcmd,"gnuplot");
1.157     brouard  12833: #ifdef _WIN32
1.126     brouard  12834:   sprintf(plotcmd,"\"%sgnuplot.exe\"",pathimach);
                   12835: #endif
                   12836:   if(!stat(plotcmd,&info)){
1.158     brouard  12837:     printf("Error or gnuplot program not found: '%s'\n",plotcmd);fflush(stdout);
1.126     brouard  12838:     if(!stat(getenv("GNUPLOTBIN"),&info)){
1.158     brouard  12839:       printf("Error or gnuplot program not found: '%s' Environment GNUPLOTBIN not set.\n",plotcmd);fflush(stdout);
1.126     brouard  12840:     }else
                   12841:       strcpy(pplotcmd,plotcmd);
1.157     brouard  12842: #ifdef __unix
1.126     brouard  12843:     strcpy(plotcmd,GNUPLOTPROGRAM);
                   12844:     if(!stat(plotcmd,&info)){
1.158     brouard  12845:       printf("Error gnuplot program not found: '%s'\n",plotcmd);fflush(stdout);
1.126     brouard  12846:     }else
                   12847:       strcpy(pplotcmd,plotcmd);
                   12848: #endif
                   12849:   }else
                   12850:     strcpy(pplotcmd,plotcmd);
                   12851:   
                   12852:   sprintf(plotcmd,"%s %s",pplotcmd, optionfilegnuplot);
1.158     brouard  12853:   printf("Starting graphs with: '%s'\n",plotcmd);fflush(stdout);
1.292     brouard  12854:   strcpy(pplotcmd,plotcmd);
1.227     brouard  12855:   
1.126     brouard  12856:   if((outcmd=system(plotcmd)) != 0){
1.292     brouard  12857:     printf("Error in gnuplot, command might not be in your path: '%s', err=%d\n", plotcmd, outcmd);
1.154     brouard  12858:     printf("\n Trying if gnuplot resides on the same directory that IMaCh\n");
1.152     brouard  12859:     sprintf(plotcmd,"%sgnuplot %s", pathimach, optionfilegnuplot);
1.292     brouard  12860:     if((outcmd=system(plotcmd)) != 0){
1.153     brouard  12861:       printf("\n Still a problem with gnuplot command %s, err=%d\n", plotcmd, outcmd);
1.292     brouard  12862:       strcpy(plotcmd,pplotcmd);
                   12863:     }
1.126     brouard  12864:   }
1.158     brouard  12865:   printf(" Successful, please wait...");
1.126     brouard  12866:   while (z[0] != 'q') {
                   12867:     /* chdir(path); */
1.154     brouard  12868:     printf("\nType e to edit results with your browser, g to graph again and q for exit: ");
1.126     brouard  12869:     scanf("%s",z);
                   12870: /*     if (z[0] == 'c') system("./imach"); */
                   12871:     if (z[0] == 'e') {
1.158     brouard  12872: #ifdef __APPLE__
1.152     brouard  12873:       sprintf(pplotcmd, "open %s", optionfilehtm);
1.157     brouard  12874: #elif __linux
                   12875:       sprintf(pplotcmd, "xdg-open %s", optionfilehtm);
1.153     brouard  12876: #else
1.152     brouard  12877:       sprintf(pplotcmd, "%s", optionfilehtm);
1.153     brouard  12878: #endif
                   12879:       printf("Starting browser with: %s",pplotcmd);fflush(stdout);
                   12880:       system(pplotcmd);
1.126     brouard  12881:     }
                   12882:     else if (z[0] == 'g') system(plotcmd);
                   12883:     else if (z[0] == 'q') exit(0);
                   12884:   }
1.227     brouard  12885: end:
1.126     brouard  12886:   while (z[0] != 'q') {
1.195     brouard  12887:     printf("\nType  q for exiting: "); fflush(stdout);
1.126     brouard  12888:     scanf("%s",z);
                   12889:   }
1.283     brouard  12890:   printf("End\n");
1.282     brouard  12891:   exit(0);
1.126     brouard  12892: }

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