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

1.298   ! brouard     1: /* $Id: imach.c,v 1.297 2019/05/22 17:56:10 brouard Exp $
1.126     brouard     2:   $State: Exp $
1.163     brouard     3:   $Log: imach.c,v $
1.298   ! brouard     4:   Revision 1.297  2019/05/22 17:56:10  brouard
        !             5:   Summary: Fix bug by moving date2dmy and nhstepm which gaefin=-1
        !             6: 
1.297     brouard     7:   Revision 1.296  2019/05/20 13:03:18  brouard
                      8:   Summary: Projection syntax simplified
                      9: 
                     10: 
                     11:   We can now start projections, forward or backward, from the mean date
                     12:   of inteviews up to or down to a number of years of projection:
                     13:   prevforecast=1 yearsfproj=15.3 mobil_average=0
                     14:   or
                     15:   prevforecast=1 starting-proj-date=1/1/2007 final-proj-date=12/31/2017 mobil_average=0
                     16:   or
                     17:   prevbackcast=1 yearsbproj=12.3 mobil_average=1
                     18:   or
                     19:   prevbackcast=1 starting-back-date=1/10/1999 final-back-date=1/1/1985 mobil_average=1
                     20: 
1.296     brouard    21:   Revision 1.295  2019/05/18 09:52:50  brouard
                     22:   Summary: doxygen tex bug
                     23: 
1.295     brouard    24:   Revision 1.294  2019/05/16 14:54:33  brouard
                     25:   Summary: There was some wrong lines added
                     26: 
1.294     brouard    27:   Revision 1.293  2019/05/09 15:17:34  brouard
                     28:   *** empty log message ***
                     29: 
1.293     brouard    30:   Revision 1.292  2019/05/09 14:17:20  brouard
                     31:   Summary: Some updates
                     32: 
1.292     brouard    33:   Revision 1.291  2019/05/09 13:44:18  brouard
                     34:   Summary: Before ncovmax
                     35: 
1.291     brouard    36:   Revision 1.290  2019/05/09 13:39:37  brouard
                     37:   Summary: 0.99r18 unlimited number of individuals
                     38: 
                     39:   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.
                     40: 
1.290     brouard    41:   Revision 1.289  2018/12/13 09:16:26  brouard
                     42:   Summary: Bug for young ages (<-30) will be in r17
                     43: 
1.289     brouard    44:   Revision 1.288  2018/05/02 20:58:27  brouard
                     45:   Summary: Some bugs fixed
                     46: 
1.288     brouard    47:   Revision 1.287  2018/05/01 17:57:25  brouard
                     48:   Summary: Bug fixed by providing frequencies only for non missing covariates
                     49: 
1.287     brouard    50:   Revision 1.286  2018/04/27 14:27:04  brouard
                     51:   Summary: some minor bugs
                     52: 
1.286     brouard    53:   Revision 1.285  2018/04/21 21:02:16  brouard
                     54:   Summary: Some bugs fixed, valgrind tested
                     55: 
1.285     brouard    56:   Revision 1.284  2018/04/20 05:22:13  brouard
                     57:   Summary: Computing mean and stdeviation of fixed quantitative variables
                     58: 
1.284     brouard    59:   Revision 1.283  2018/04/19 14:49:16  brouard
                     60:   Summary: Some minor bugs fixed
                     61: 
1.283     brouard    62:   Revision 1.282  2018/02/27 22:50:02  brouard
                     63:   *** empty log message ***
                     64: 
1.282     brouard    65:   Revision 1.281  2018/02/27 19:25:23  brouard
                     66:   Summary: Adding second argument for quitting
                     67: 
1.281     brouard    68:   Revision 1.280  2018/02/21 07:58:13  brouard
                     69:   Summary: 0.99r15
                     70: 
                     71:   New Makefile with recent VirtualBox 5.26. Bug in sqrt negatve in imach.c
                     72: 
1.280     brouard    73:   Revision 1.279  2017/07/20 13:35:01  brouard
                     74:   Summary: temporary working
                     75: 
1.279     brouard    76:   Revision 1.278  2017/07/19 14:09:02  brouard
                     77:   Summary: Bug for mobil_average=0 and prevforecast fixed(?)
                     78: 
1.278     brouard    79:   Revision 1.277  2017/07/17 08:53:49  brouard
                     80:   Summary: BOM files can be read now
                     81: 
1.277     brouard    82:   Revision 1.276  2017/06/30 15:48:31  brouard
                     83:   Summary: Graphs improvements
                     84: 
1.276     brouard    85:   Revision 1.275  2017/06/30 13:39:33  brouard
                     86:   Summary: Saito's color
                     87: 
1.275     brouard    88:   Revision 1.274  2017/06/29 09:47:08  brouard
                     89:   Summary: Version 0.99r14
                     90: 
1.274     brouard    91:   Revision 1.273  2017/06/27 11:06:02  brouard
                     92:   Summary: More documentation on projections
                     93: 
1.273     brouard    94:   Revision 1.272  2017/06/27 10:22:40  brouard
                     95:   Summary: Color of backprojection changed from 6 to 5(yellow)
                     96: 
1.272     brouard    97:   Revision 1.271  2017/06/27 10:17:50  brouard
                     98:   Summary: Some bug with rint
                     99: 
1.271     brouard   100:   Revision 1.270  2017/05/24 05:45:29  brouard
                    101:   *** empty log message ***
                    102: 
1.270     brouard   103:   Revision 1.269  2017/05/23 08:39:25  brouard
                    104:   Summary: Code into subroutine, cleanings
                    105: 
1.269     brouard   106:   Revision 1.268  2017/05/18 20:09:32  brouard
                    107:   Summary: backprojection and confidence intervals of backprevalence
                    108: 
1.268     brouard   109:   Revision 1.267  2017/05/13 10:25:05  brouard
                    110:   Summary: temporary save for backprojection
                    111: 
1.267     brouard   112:   Revision 1.266  2017/05/13 07:26:12  brouard
                    113:   Summary: Version 0.99r13 (improvements and bugs fixed)
                    114: 
1.266     brouard   115:   Revision 1.265  2017/04/26 16:22:11  brouard
                    116:   Summary: imach 0.99r13 Some bugs fixed
                    117: 
1.265     brouard   118:   Revision 1.264  2017/04/26 06:01:29  brouard
                    119:   Summary: Labels in graphs
                    120: 
1.264     brouard   121:   Revision 1.263  2017/04/24 15:23:15  brouard
                    122:   Summary: to save
                    123: 
1.263     brouard   124:   Revision 1.262  2017/04/18 16:48:12  brouard
                    125:   *** empty log message ***
                    126: 
1.262     brouard   127:   Revision 1.261  2017/04/05 10:14:09  brouard
                    128:   Summary: Bug in E_ as well as in T_ fixed nres-1 vs k1-1
                    129: 
1.261     brouard   130:   Revision 1.260  2017/04/04 17:46:59  brouard
                    131:   Summary: Gnuplot indexations fixed (humm)
                    132: 
1.260     brouard   133:   Revision 1.259  2017/04/04 13:01:16  brouard
                    134:   Summary: Some errors to warnings only if date of death is unknown but status is death we could set to pi3
                    135: 
1.259     brouard   136:   Revision 1.258  2017/04/03 10:17:47  brouard
                    137:   Summary: Version 0.99r12
                    138: 
                    139:   Some cleanings, conformed with updated documentation.
                    140: 
1.258     brouard   141:   Revision 1.257  2017/03/29 16:53:30  brouard
                    142:   Summary: Temp
                    143: 
1.257     brouard   144:   Revision 1.256  2017/03/27 05:50:23  brouard
                    145:   Summary: Temporary
                    146: 
1.256     brouard   147:   Revision 1.255  2017/03/08 16:02:28  brouard
                    148:   Summary: IMaCh version 0.99r10 bugs in gnuplot fixed
                    149: 
1.255     brouard   150:   Revision 1.254  2017/03/08 07:13:00  brouard
                    151:   Summary: Fixing data parameter line
                    152: 
1.254     brouard   153:   Revision 1.253  2016/12/15 11:59:41  brouard
                    154:   Summary: 0.99 in progress
                    155: 
1.253     brouard   156:   Revision 1.252  2016/09/15 21:15:37  brouard
                    157:   *** empty log message ***
                    158: 
1.252     brouard   159:   Revision 1.251  2016/09/15 15:01:13  brouard
                    160:   Summary: not working
                    161: 
1.251     brouard   162:   Revision 1.250  2016/09/08 16:07:27  brouard
                    163:   Summary: continue
                    164: 
1.250     brouard   165:   Revision 1.249  2016/09/07 17:14:18  brouard
                    166:   Summary: Starting values from frequencies
                    167: 
1.249     brouard   168:   Revision 1.248  2016/09/07 14:10:18  brouard
                    169:   *** empty log message ***
                    170: 
1.248     brouard   171:   Revision 1.247  2016/09/02 11:11:21  brouard
                    172:   *** empty log message ***
                    173: 
1.247     brouard   174:   Revision 1.246  2016/09/02 08:49:22  brouard
                    175:   *** empty log message ***
                    176: 
1.246     brouard   177:   Revision 1.245  2016/09/02 07:25:01  brouard
                    178:   *** empty log message ***
                    179: 
1.245     brouard   180:   Revision 1.244  2016/09/02 07:17:34  brouard
                    181:   *** empty log message ***
                    182: 
1.244     brouard   183:   Revision 1.243  2016/09/02 06:45:35  brouard
                    184:   *** empty log message ***
                    185: 
1.243     brouard   186:   Revision 1.242  2016/08/30 15:01:20  brouard
                    187:   Summary: Fixing a lots
                    188: 
1.242     brouard   189:   Revision 1.241  2016/08/29 17:17:25  brouard
                    190:   Summary: gnuplot problem in Back projection to fix
                    191: 
1.241     brouard   192:   Revision 1.240  2016/08/29 07:53:18  brouard
                    193:   Summary: Better
                    194: 
1.240     brouard   195:   Revision 1.239  2016/08/26 15:51:03  brouard
                    196:   Summary: Improvement in Powell output in order to copy and paste
                    197: 
                    198:   Author:
                    199: 
1.239     brouard   200:   Revision 1.238  2016/08/26 14:23:35  brouard
                    201:   Summary: Starting tests of 0.99
                    202: 
1.238     brouard   203:   Revision 1.237  2016/08/26 09:20:19  brouard
                    204:   Summary: to valgrind
                    205: 
1.237     brouard   206:   Revision 1.236  2016/08/25 10:50:18  brouard
                    207:   *** empty log message ***
                    208: 
1.236     brouard   209:   Revision 1.235  2016/08/25 06:59:23  brouard
                    210:   *** empty log message ***
                    211: 
1.235     brouard   212:   Revision 1.234  2016/08/23 16:51:20  brouard
                    213:   *** empty log message ***
                    214: 
1.234     brouard   215:   Revision 1.233  2016/08/23 07:40:50  brouard
                    216:   Summary: not working
                    217: 
1.233     brouard   218:   Revision 1.232  2016/08/22 14:20:21  brouard
                    219:   Summary: not working
                    220: 
1.232     brouard   221:   Revision 1.231  2016/08/22 07:17:15  brouard
                    222:   Summary: not working
                    223: 
1.231     brouard   224:   Revision 1.230  2016/08/22 06:55:53  brouard
                    225:   Summary: Not working
                    226: 
1.230     brouard   227:   Revision 1.229  2016/07/23 09:45:53  brouard
                    228:   Summary: Completing for func too
                    229: 
1.229     brouard   230:   Revision 1.228  2016/07/22 17:45:30  brouard
                    231:   Summary: Fixing some arrays, still debugging
                    232: 
1.227     brouard   233:   Revision 1.226  2016/07/12 18:42:34  brouard
                    234:   Summary: temp
                    235: 
1.226     brouard   236:   Revision 1.225  2016/07/12 08:40:03  brouard
                    237:   Summary: saving but not running
                    238: 
1.225     brouard   239:   Revision 1.224  2016/07/01 13:16:01  brouard
                    240:   Summary: Fixes
                    241: 
1.224     brouard   242:   Revision 1.223  2016/02/19 09:23:35  brouard
                    243:   Summary: temporary
                    244: 
1.223     brouard   245:   Revision 1.222  2016/02/17 08:14:50  brouard
                    246:   Summary: Probably last 0.98 stable version 0.98r6
                    247: 
1.222     brouard   248:   Revision 1.221  2016/02/15 23:35:36  brouard
                    249:   Summary: minor bug
                    250: 
1.220     brouard   251:   Revision 1.219  2016/02/15 00:48:12  brouard
                    252:   *** empty log message ***
                    253: 
1.219     brouard   254:   Revision 1.218  2016/02/12 11:29:23  brouard
                    255:   Summary: 0.99 Back projections
                    256: 
1.218     brouard   257:   Revision 1.217  2015/12/23 17:18:31  brouard
                    258:   Summary: Experimental backcast
                    259: 
1.217     brouard   260:   Revision 1.216  2015/12/18 17:32:11  brouard
                    261:   Summary: 0.98r4 Warning and status=-2
                    262: 
                    263:   Version 0.98r4 is now:
                    264:    - displaying an error when status is -1, date of interview unknown and date of death known;
                    265:    - permitting a status -2 when the vital status is unknown at a known date of right truncation.
                    266:   Older changes concerning s=-2, dating from 2005 have been supersed.
                    267: 
1.216     brouard   268:   Revision 1.215  2015/12/16 08:52:24  brouard
                    269:   Summary: 0.98r4 working
                    270: 
1.215     brouard   271:   Revision 1.214  2015/12/16 06:57:54  brouard
                    272:   Summary: temporary not working
                    273: 
1.214     brouard   274:   Revision 1.213  2015/12/11 18:22:17  brouard
                    275:   Summary: 0.98r4
                    276: 
1.213     brouard   277:   Revision 1.212  2015/11/21 12:47:24  brouard
                    278:   Summary: minor typo
                    279: 
1.212     brouard   280:   Revision 1.211  2015/11/21 12:41:11  brouard
                    281:   Summary: 0.98r3 with some graph of projected cross-sectional
                    282: 
                    283:   Author: Nicolas Brouard
                    284: 
1.211     brouard   285:   Revision 1.210  2015/11/18 17:41:20  brouard
1.252     brouard   286:   Summary: Start working on projected prevalences  Revision 1.209  2015/11/17 22:12:03  brouard
1.210     brouard   287:   Summary: Adding ftolpl parameter
                    288:   Author: N Brouard
                    289: 
                    290:   We had difficulties to get smoothed confidence intervals. It was due
                    291:   to the period prevalence which wasn't computed accurately. The inner
                    292:   parameter ftolpl is now an outer parameter of the .imach parameter
                    293:   file after estepm. If ftolpl is small 1.e-4 and estepm too,
                    294:   computation are long.
                    295: 
1.209     brouard   296:   Revision 1.208  2015/11/17 14:31:57  brouard
                    297:   Summary: temporary
                    298: 
1.208     brouard   299:   Revision 1.207  2015/10/27 17:36:57  brouard
                    300:   *** empty log message ***
                    301: 
1.207     brouard   302:   Revision 1.206  2015/10/24 07:14:11  brouard
                    303:   *** empty log message ***
                    304: 
1.206     brouard   305:   Revision 1.205  2015/10/23 15:50:53  brouard
                    306:   Summary: 0.98r3 some clarification for graphs on likelihood contributions
                    307: 
1.205     brouard   308:   Revision 1.204  2015/10/01 16:20:26  brouard
                    309:   Summary: Some new graphs of contribution to likelihood
                    310: 
1.204     brouard   311:   Revision 1.203  2015/09/30 17:45:14  brouard
                    312:   Summary: looking at better estimation of the hessian
                    313: 
                    314:   Also a better criteria for convergence to the period prevalence And
                    315:   therefore adding the number of years needed to converge. (The
                    316:   prevalence in any alive state shold sum to one
                    317: 
1.203     brouard   318:   Revision 1.202  2015/09/22 19:45:16  brouard
                    319:   Summary: Adding some overall graph on contribution to likelihood. Might change
                    320: 
1.202     brouard   321:   Revision 1.201  2015/09/15 17:34:58  brouard
                    322:   Summary: 0.98r0
                    323: 
                    324:   - Some new graphs like suvival functions
                    325:   - Some bugs fixed like model=1+age+V2.
                    326: 
1.201     brouard   327:   Revision 1.200  2015/09/09 16:53:55  brouard
                    328:   Summary: Big bug thanks to Flavia
                    329: 
                    330:   Even model=1+age+V2. did not work anymore
                    331: 
1.200     brouard   332:   Revision 1.199  2015/09/07 14:09:23  brouard
                    333:   Summary: 0.98q6 changing default small png format for graph to vectorized svg.
                    334: 
1.199     brouard   335:   Revision 1.198  2015/09/03 07:14:39  brouard
                    336:   Summary: 0.98q5 Flavia
                    337: 
1.198     brouard   338:   Revision 1.197  2015/09/01 18:24:39  brouard
                    339:   *** empty log message ***
                    340: 
1.197     brouard   341:   Revision 1.196  2015/08/18 23:17:52  brouard
                    342:   Summary: 0.98q5
                    343: 
1.196     brouard   344:   Revision 1.195  2015/08/18 16:28:39  brouard
                    345:   Summary: Adding a hack for testing purpose
                    346: 
                    347:   After reading the title, ftol and model lines, if the comment line has
                    348:   a q, starting with #q, the answer at the end of the run is quit. It
                    349:   permits to run test files in batch with ctest. The former workaround was
                    350:   $ echo q | imach foo.imach
                    351: 
1.195     brouard   352:   Revision 1.194  2015/08/18 13:32:00  brouard
                    353:   Summary:  Adding error when the covariance matrix doesn't contain the exact number of lines required by the model line.
                    354: 
1.194     brouard   355:   Revision 1.193  2015/08/04 07:17:42  brouard
                    356:   Summary: 0.98q4
                    357: 
1.193     brouard   358:   Revision 1.192  2015/07/16 16:49:02  brouard
                    359:   Summary: Fixing some outputs
                    360: 
1.192     brouard   361:   Revision 1.191  2015/07/14 10:00:33  brouard
                    362:   Summary: Some fixes
                    363: 
1.191     brouard   364:   Revision 1.190  2015/05/05 08:51:13  brouard
                    365:   Summary: Adding digits in output parameters (7 digits instead of 6)
                    366: 
                    367:   Fix 1+age+.
                    368: 
1.190     brouard   369:   Revision 1.189  2015/04/30 14:45:16  brouard
                    370:   Summary: 0.98q2
                    371: 
1.189     brouard   372:   Revision 1.188  2015/04/30 08:27:53  brouard
                    373:   *** empty log message ***
                    374: 
1.188     brouard   375:   Revision 1.187  2015/04/29 09:11:15  brouard
                    376:   *** empty log message ***
                    377: 
1.187     brouard   378:   Revision 1.186  2015/04/23 12:01:52  brouard
                    379:   Summary: V1*age is working now, version 0.98q1
                    380: 
                    381:   Some codes had been disabled in order to simplify and Vn*age was
                    382:   working in the optimization phase, ie, giving correct MLE parameters,
                    383:   but, as usual, outputs were not correct and program core dumped.
                    384: 
1.186     brouard   385:   Revision 1.185  2015/03/11 13:26:42  brouard
                    386:   Summary: Inclusion of compile and links command line for Intel Compiler
                    387: 
1.185     brouard   388:   Revision 1.184  2015/03/11 11:52:39  brouard
                    389:   Summary: Back from Windows 8. Intel Compiler
                    390: 
1.184     brouard   391:   Revision 1.183  2015/03/10 20:34:32  brouard
                    392:   Summary: 0.98q0, trying with directest, mnbrak fixed
                    393: 
                    394:   We use directest instead of original Powell test; probably no
                    395:   incidence on the results, but better justifications;
                    396:   We fixed Numerical Recipes mnbrak routine which was wrong and gave
                    397:   wrong results.
                    398: 
1.183     brouard   399:   Revision 1.182  2015/02/12 08:19:57  brouard
                    400:   Summary: Trying to keep directest which seems simpler and more general
                    401:   Author: Nicolas Brouard
                    402: 
1.182     brouard   403:   Revision 1.181  2015/02/11 23:22:24  brouard
                    404:   Summary: Comments on Powell added
                    405: 
                    406:   Author:
                    407: 
1.181     brouard   408:   Revision 1.180  2015/02/11 17:33:45  brouard
                    409:   Summary: Finishing move from main to function (hpijx and prevalence_limit)
                    410: 
1.180     brouard   411:   Revision 1.179  2015/01/04 09:57:06  brouard
                    412:   Summary: back to OS/X
                    413: 
1.179     brouard   414:   Revision 1.178  2015/01/04 09:35:48  brouard
                    415:   *** empty log message ***
                    416: 
1.178     brouard   417:   Revision 1.177  2015/01/03 18:40:56  brouard
                    418:   Summary: Still testing ilc32 on OSX
                    419: 
1.177     brouard   420:   Revision 1.176  2015/01/03 16:45:04  brouard
                    421:   *** empty log message ***
                    422: 
1.176     brouard   423:   Revision 1.175  2015/01/03 16:33:42  brouard
                    424:   *** empty log message ***
                    425: 
1.175     brouard   426:   Revision 1.174  2015/01/03 16:15:49  brouard
                    427:   Summary: Still in cross-compilation
                    428: 
1.174     brouard   429:   Revision 1.173  2015/01/03 12:06:26  brouard
                    430:   Summary: trying to detect cross-compilation
                    431: 
1.173     brouard   432:   Revision 1.172  2014/12/27 12:07:47  brouard
                    433:   Summary: Back from Visual Studio and Intel, options for compiling for Windows XP
                    434: 
1.172     brouard   435:   Revision 1.171  2014/12/23 13:26:59  brouard
                    436:   Summary: Back from Visual C
                    437: 
                    438:   Still problem with utsname.h on Windows
                    439: 
1.171     brouard   440:   Revision 1.170  2014/12/23 11:17:12  brouard
                    441:   Summary: Cleaning some \%% back to %%
                    442: 
                    443:   The escape was mandatory for a specific compiler (which one?), but too many warnings.
                    444: 
1.170     brouard   445:   Revision 1.169  2014/12/22 23:08:31  brouard
                    446:   Summary: 0.98p
                    447: 
                    448:   Outputs some informations on compiler used, OS etc. Testing on different platforms.
                    449: 
1.169     brouard   450:   Revision 1.168  2014/12/22 15:17:42  brouard
1.170     brouard   451:   Summary: update
1.169     brouard   452: 
1.168     brouard   453:   Revision 1.167  2014/12/22 13:50:56  brouard
                    454:   Summary: Testing uname and compiler version and if compiled 32 or 64
                    455: 
                    456:   Testing on Linux 64
                    457: 
1.167     brouard   458:   Revision 1.166  2014/12/22 11:40:47  brouard
                    459:   *** empty log message ***
                    460: 
1.166     brouard   461:   Revision 1.165  2014/12/16 11:20:36  brouard
                    462:   Summary: After compiling on Visual C
                    463: 
                    464:   * imach.c (Module): Merging 1.61 to 1.162
                    465: 
1.165     brouard   466:   Revision 1.164  2014/12/16 10:52:11  brouard
                    467:   Summary: Merging with Visual C after suppressing some warnings for unused variables. Also fixing Saito's bug 0.98Xn
                    468: 
                    469:   * imach.c (Module): Merging 1.61 to 1.162
                    470: 
1.164     brouard   471:   Revision 1.163  2014/12/16 10:30:11  brouard
                    472:   * imach.c (Module): Merging 1.61 to 1.162
                    473: 
1.163     brouard   474:   Revision 1.162  2014/09/25 11:43:39  brouard
                    475:   Summary: temporary backup 0.99!
                    476: 
1.162     brouard   477:   Revision 1.1  2014/09/16 11:06:58  brouard
                    478:   Summary: With some code (wrong) for nlopt
                    479: 
                    480:   Author:
                    481: 
                    482:   Revision 1.161  2014/09/15 20:41:41  brouard
                    483:   Summary: Problem with macro SQR on Intel compiler
                    484: 
1.161     brouard   485:   Revision 1.160  2014/09/02 09:24:05  brouard
                    486:   *** empty log message ***
                    487: 
1.160     brouard   488:   Revision 1.159  2014/09/01 10:34:10  brouard
                    489:   Summary: WIN32
                    490:   Author: Brouard
                    491: 
1.159     brouard   492:   Revision 1.158  2014/08/27 17:11:51  brouard
                    493:   *** empty log message ***
                    494: 
1.158     brouard   495:   Revision 1.157  2014/08/27 16:26:55  brouard
                    496:   Summary: Preparing windows Visual studio version
                    497:   Author: Brouard
                    498: 
                    499:   In order to compile on Visual studio, time.h is now correct and time_t
                    500:   and tm struct should be used. difftime should be used but sometimes I
                    501:   just make the differences in raw time format (time(&now).
                    502:   Trying to suppress #ifdef LINUX
                    503:   Add xdg-open for __linux in order to open default browser.
                    504: 
1.157     brouard   505:   Revision 1.156  2014/08/25 20:10:10  brouard
                    506:   *** empty log message ***
                    507: 
1.156     brouard   508:   Revision 1.155  2014/08/25 18:32:34  brouard
                    509:   Summary: New compile, minor changes
                    510:   Author: Brouard
                    511: 
1.155     brouard   512:   Revision 1.154  2014/06/20 17:32:08  brouard
                    513:   Summary: Outputs now all graphs of convergence to period prevalence
                    514: 
1.154     brouard   515:   Revision 1.153  2014/06/20 16:45:46  brouard
                    516:   Summary: If 3 live state, convergence to period prevalence on same graph
                    517:   Author: Brouard
                    518: 
1.153     brouard   519:   Revision 1.152  2014/06/18 17:54:09  brouard
                    520:   Summary: open browser, use gnuplot on same dir than imach if not found in the path
                    521: 
1.152     brouard   522:   Revision 1.151  2014/06/18 16:43:30  brouard
                    523:   *** empty log message ***
                    524: 
1.151     brouard   525:   Revision 1.150  2014/06/18 16:42:35  brouard
                    526:   Summary: If gnuplot is not in the path try on same directory than imach binary (OSX)
                    527:   Author: brouard
                    528: 
1.150     brouard   529:   Revision 1.149  2014/06/18 15:51:14  brouard
                    530:   Summary: Some fixes in parameter files errors
                    531:   Author: Nicolas Brouard
                    532: 
1.149     brouard   533:   Revision 1.148  2014/06/17 17:38:48  brouard
                    534:   Summary: Nothing new
                    535:   Author: Brouard
                    536: 
                    537:   Just a new packaging for OS/X version 0.98nS
                    538: 
1.148     brouard   539:   Revision 1.147  2014/06/16 10:33:11  brouard
                    540:   *** empty log message ***
                    541: 
1.147     brouard   542:   Revision 1.146  2014/06/16 10:20:28  brouard
                    543:   Summary: Merge
                    544:   Author: Brouard
                    545: 
                    546:   Merge, before building revised version.
                    547: 
1.146     brouard   548:   Revision 1.145  2014/06/10 21:23:15  brouard
                    549:   Summary: Debugging with valgrind
                    550:   Author: Nicolas Brouard
                    551: 
                    552:   Lot of changes in order to output the results with some covariates
                    553:   After the Edimburgh REVES conference 2014, it seems mandatory to
                    554:   improve the code.
                    555:   No more memory valgrind error but a lot has to be done in order to
                    556:   continue the work of splitting the code into subroutines.
                    557:   Also, decodemodel has been improved. Tricode is still not
                    558:   optimal. nbcode should be improved. Documentation has been added in
                    559:   the source code.
                    560: 
1.144     brouard   561:   Revision 1.143  2014/01/26 09:45:38  brouard
                    562:   Summary: Version 0.98nR (to be improved, but gives same optimization results as 0.98k. Nice, promising
                    563: 
                    564:   * imach.c (Module): Trying to merge old staffs together while being at Tokyo. Not tested...
                    565:   (Module): Version 0.98nR Running ok, but output format still only works for three covariates.
                    566: 
1.143     brouard   567:   Revision 1.142  2014/01/26 03:57:36  brouard
                    568:   Summary: gnuplot changed plot w l 1 has to be changed to plot w l lt 2
                    569: 
                    570:   * imach.c (Module): Trying to merge old staffs together while being at Tokyo. Not tested...
                    571: 
1.142     brouard   572:   Revision 1.141  2014/01/26 02:42:01  brouard
                    573:   * imach.c (Module): Trying to merge old staffs together while being at Tokyo. Not tested...
                    574: 
1.141     brouard   575:   Revision 1.140  2011/09/02 10:37:54  brouard
                    576:   Summary: times.h is ok with mingw32 now.
                    577: 
1.140     brouard   578:   Revision 1.139  2010/06/14 07:50:17  brouard
                    579:   After the theft of my laptop, I probably lost some lines of codes which were not uploaded to the CVS tree.
                    580:   I remember having already fixed agemin agemax which are pointers now but not cvs saved.
                    581: 
1.139     brouard   582:   Revision 1.138  2010/04/30 18:19:40  brouard
                    583:   *** empty log message ***
                    584: 
1.138     brouard   585:   Revision 1.137  2010/04/29 18:11:38  brouard
                    586:   (Module): Checking covariates for more complex models
                    587:   than V1+V2. A lot of change to be done. Unstable.
                    588: 
1.137     brouard   589:   Revision 1.136  2010/04/26 20:30:53  brouard
                    590:   (Module): merging some libgsl code. Fixing computation
                    591:   of likelione (using inter/intrapolation if mle = 0) in order to
                    592:   get same likelihood as if mle=1.
                    593:   Some cleaning of code and comments added.
                    594: 
1.136     brouard   595:   Revision 1.135  2009/10/29 15:33:14  brouard
                    596:   (Module): Now imach stops if date of birth, at least year of birth, is not given. Some cleaning of the code.
                    597: 
1.135     brouard   598:   Revision 1.134  2009/10/29 13:18:53  brouard
                    599:   (Module): Now imach stops if date of birth, at least year of birth, is not given. Some cleaning of the code.
                    600: 
1.134     brouard   601:   Revision 1.133  2009/07/06 10:21:25  brouard
                    602:   just nforces
                    603: 
1.133     brouard   604:   Revision 1.132  2009/07/06 08:22:05  brouard
                    605:   Many tings
                    606: 
1.132     brouard   607:   Revision 1.131  2009/06/20 16:22:47  brouard
                    608:   Some dimensions resccaled
                    609: 
1.131     brouard   610:   Revision 1.130  2009/05/26 06:44:34  brouard
                    611:   (Module): Max Covariate is now set to 20 instead of 8. A
                    612:   lot of cleaning with variables initialized to 0. Trying to make
                    613:   V2+V3*age+V1+V4 strb=V3*age+V1+V4 working better.
                    614: 
1.130     brouard   615:   Revision 1.129  2007/08/31 13:49:27  lievre
                    616:   Modification of the way of exiting when the covariate is not binary in order to see on the window the error message before exiting
                    617: 
1.129     lievre    618:   Revision 1.128  2006/06/30 13:02:05  brouard
                    619:   (Module): Clarifications on computing e.j
                    620: 
1.128     brouard   621:   Revision 1.127  2006/04/28 18:11:50  brouard
                    622:   (Module): Yes the sum of survivors was wrong since
                    623:   imach-114 because nhstepm was no more computed in the age
                    624:   loop. Now we define nhstepma in the age loop.
                    625:   (Module): In order to speed up (in case of numerous covariates) we
                    626:   compute health expectancies (without variances) in a first step
                    627:   and then all the health expectancies with variances or standard
                    628:   deviation (needs data from the Hessian matrices) which slows the
                    629:   computation.
                    630:   In the future we should be able to stop the program is only health
                    631:   expectancies and graph are needed without standard deviations.
                    632: 
1.127     brouard   633:   Revision 1.126  2006/04/28 17:23:28  brouard
                    634:   (Module): Yes the sum of survivors was wrong since
                    635:   imach-114 because nhstepm was no more computed in the age
                    636:   loop. Now we define nhstepma in the age loop.
                    637:   Version 0.98h
                    638: 
1.126     brouard   639:   Revision 1.125  2006/04/04 15:20:31  lievre
                    640:   Errors in calculation of health expectancies. Age was not initialized.
                    641:   Forecasting file added.
                    642: 
                    643:   Revision 1.124  2006/03/22 17:13:53  lievre
                    644:   Parameters are printed with %lf instead of %f (more numbers after the comma).
                    645:   The log-likelihood is printed in the log file
                    646: 
                    647:   Revision 1.123  2006/03/20 10:52:43  brouard
                    648:   * imach.c (Module): <title> changed, corresponds to .htm file
                    649:   name. <head> headers where missing.
                    650: 
                    651:   * imach.c (Module): Weights can have a decimal point as for
                    652:   English (a comma might work with a correct LC_NUMERIC environment,
                    653:   otherwise the weight is truncated).
                    654:   Modification of warning when the covariates values are not 0 or
                    655:   1.
                    656:   Version 0.98g
                    657: 
                    658:   Revision 1.122  2006/03/20 09:45:41  brouard
                    659:   (Module): Weights can have a decimal point as for
                    660:   English (a comma might work with a correct LC_NUMERIC environment,
                    661:   otherwise the weight is truncated).
                    662:   Modification of warning when the covariates values are not 0 or
                    663:   1.
                    664:   Version 0.98g
                    665: 
                    666:   Revision 1.121  2006/03/16 17:45:01  lievre
                    667:   * imach.c (Module): Comments concerning covariates added
                    668: 
                    669:   * imach.c (Module): refinements in the computation of lli if
                    670:   status=-2 in order to have more reliable computation if stepm is
                    671:   not 1 month. Version 0.98f
                    672: 
                    673:   Revision 1.120  2006/03/16 15:10:38  lievre
                    674:   (Module): refinements in the computation of lli if
                    675:   status=-2 in order to have more reliable computation if stepm is
                    676:   not 1 month. Version 0.98f
                    677: 
                    678:   Revision 1.119  2006/03/15 17:42:26  brouard
                    679:   (Module): Bug if status = -2, the loglikelihood was
                    680:   computed as likelihood omitting the logarithm. Version O.98e
                    681: 
                    682:   Revision 1.118  2006/03/14 18:20:07  brouard
                    683:   (Module): varevsij Comments added explaining the second
                    684:   table of variances if popbased=1 .
                    685:   (Module): Covariances of eij, ekl added, graphs fixed, new html link.
                    686:   (Module): Function pstamp added
                    687:   (Module): Version 0.98d
                    688: 
                    689:   Revision 1.117  2006/03/14 17:16:22  brouard
                    690:   (Module): varevsij Comments added explaining the second
                    691:   table of variances if popbased=1 .
                    692:   (Module): Covariances of eij, ekl added, graphs fixed, new html link.
                    693:   (Module): Function pstamp added
                    694:   (Module): Version 0.98d
                    695: 
                    696:   Revision 1.116  2006/03/06 10:29:27  brouard
                    697:   (Module): Variance-covariance wrong links and
                    698:   varian-covariance of ej. is needed (Saito).
                    699: 
                    700:   Revision 1.115  2006/02/27 12:17:45  brouard
                    701:   (Module): One freematrix added in mlikeli! 0.98c
                    702: 
                    703:   Revision 1.114  2006/02/26 12:57:58  brouard
                    704:   (Module): Some improvements in processing parameter
                    705:   filename with strsep.
                    706: 
                    707:   Revision 1.113  2006/02/24 14:20:24  brouard
                    708:   (Module): Memory leaks checks with valgrind and:
                    709:   datafile was not closed, some imatrix were not freed and on matrix
                    710:   allocation too.
                    711: 
                    712:   Revision 1.112  2006/01/30 09:55:26  brouard
                    713:   (Module): Back to gnuplot.exe instead of wgnuplot.exe
                    714: 
                    715:   Revision 1.111  2006/01/25 20:38:18  brouard
                    716:   (Module): Lots of cleaning and bugs added (Gompertz)
                    717:   (Module): Comments can be added in data file. Missing date values
                    718:   can be a simple dot '.'.
                    719: 
                    720:   Revision 1.110  2006/01/25 00:51:50  brouard
                    721:   (Module): Lots of cleaning and bugs added (Gompertz)
                    722: 
                    723:   Revision 1.109  2006/01/24 19:37:15  brouard
                    724:   (Module): Comments (lines starting with a #) are allowed in data.
                    725: 
                    726:   Revision 1.108  2006/01/19 18:05:42  lievre
                    727:   Gnuplot problem appeared...
                    728:   To be fixed
                    729: 
                    730:   Revision 1.107  2006/01/19 16:20:37  brouard
                    731:   Test existence of gnuplot in imach path
                    732: 
                    733:   Revision 1.106  2006/01/19 13:24:36  brouard
                    734:   Some cleaning and links added in html output
                    735: 
                    736:   Revision 1.105  2006/01/05 20:23:19  lievre
                    737:   *** empty log message ***
                    738: 
                    739:   Revision 1.104  2005/09/30 16:11:43  lievre
                    740:   (Module): sump fixed, loop imx fixed, and simplifications.
                    741:   (Module): If the status is missing at the last wave but we know
                    742:   that the person is alive, then we can code his/her status as -2
                    743:   (instead of missing=-1 in earlier versions) and his/her
                    744:   contributions to the likelihood is 1 - Prob of dying from last
                    745:   health status (= 1-p13= p11+p12 in the easiest case of somebody in
                    746:   the healthy state at last known wave). Version is 0.98
                    747: 
                    748:   Revision 1.103  2005/09/30 15:54:49  lievre
                    749:   (Module): sump fixed, loop imx fixed, and simplifications.
                    750: 
                    751:   Revision 1.102  2004/09/15 17:31:30  brouard
                    752:   Add the possibility to read data file including tab characters.
                    753: 
                    754:   Revision 1.101  2004/09/15 10:38:38  brouard
                    755:   Fix on curr_time
                    756: 
                    757:   Revision 1.100  2004/07/12 18:29:06  brouard
                    758:   Add version for Mac OS X. Just define UNIX in Makefile
                    759: 
                    760:   Revision 1.99  2004/06/05 08:57:40  brouard
                    761:   *** empty log message ***
                    762: 
                    763:   Revision 1.98  2004/05/16 15:05:56  brouard
                    764:   New version 0.97 . First attempt to estimate force of mortality
                    765:   directly from the data i.e. without the need of knowing the health
                    766:   state at each age, but using a Gompertz model: log u =a + b*age .
                    767:   This is the basic analysis of mortality and should be done before any
                    768:   other analysis, in order to test if the mortality estimated from the
                    769:   cross-longitudinal survey is different from the mortality estimated
                    770:   from other sources like vital statistic data.
                    771: 
                    772:   The same imach parameter file can be used but the option for mle should be -3.
                    773: 
1.133     brouard   774:   Agnès, who wrote this part of the code, tried to keep most of the
1.126     brouard   775:   former routines in order to include the new code within the former code.
                    776: 
                    777:   The output is very simple: only an estimate of the intercept and of
                    778:   the slope with 95% confident intervals.
                    779: 
                    780:   Current limitations:
                    781:   A) Even if you enter covariates, i.e. with the
                    782:   model= V1+V2 equation for example, the programm does only estimate a unique global model without covariates.
                    783:   B) There is no computation of Life Expectancy nor Life Table.
                    784: 
                    785:   Revision 1.97  2004/02/20 13:25:42  lievre
                    786:   Version 0.96d. Population forecasting command line is (temporarily)
                    787:   suppressed.
                    788: 
                    789:   Revision 1.96  2003/07/15 15:38:55  brouard
                    790:   * imach.c (Repository): Errors in subdirf, 2, 3 while printing tmpout is
                    791:   rewritten within the same printf. Workaround: many printfs.
                    792: 
                    793:   Revision 1.95  2003/07/08 07:54:34  brouard
                    794:   * imach.c (Repository):
                    795:   (Repository): Using imachwizard code to output a more meaningful covariance
                    796:   matrix (cov(a12,c31) instead of numbers.
                    797: 
                    798:   Revision 1.94  2003/06/27 13:00:02  brouard
                    799:   Just cleaning
                    800: 
                    801:   Revision 1.93  2003/06/25 16:33:55  brouard
                    802:   (Module): On windows (cygwin) function asctime_r doesn't
                    803:   exist so I changed back to asctime which exists.
                    804:   (Module): Version 0.96b
                    805: 
                    806:   Revision 1.92  2003/06/25 16:30:45  brouard
                    807:   (Module): On windows (cygwin) function asctime_r doesn't
                    808:   exist so I changed back to asctime which exists.
                    809: 
                    810:   Revision 1.91  2003/06/25 15:30:29  brouard
                    811:   * imach.c (Repository): Duplicated warning errors corrected.
                    812:   (Repository): Elapsed time after each iteration is now output. It
                    813:   helps to forecast when convergence will be reached. Elapsed time
                    814:   is stamped in powell.  We created a new html file for the graphs
                    815:   concerning matrix of covariance. It has extension -cov.htm.
                    816: 
                    817:   Revision 1.90  2003/06/24 12:34:15  brouard
                    818:   (Module): Some bugs corrected for windows. Also, when
                    819:   mle=-1 a template is output in file "or"mypar.txt with the design
                    820:   of the covariance matrix to be input.
                    821: 
                    822:   Revision 1.89  2003/06/24 12:30:52  brouard
                    823:   (Module): Some bugs corrected for windows. Also, when
                    824:   mle=-1 a template is output in file "or"mypar.txt with the design
                    825:   of the covariance matrix to be input.
                    826: 
                    827:   Revision 1.88  2003/06/23 17:54:56  brouard
                    828:   * 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.
                    829: 
                    830:   Revision 1.87  2003/06/18 12:26:01  brouard
                    831:   Version 0.96
                    832: 
                    833:   Revision 1.86  2003/06/17 20:04:08  brouard
                    834:   (Module): Change position of html and gnuplot routines and added
                    835:   routine fileappend.
                    836: 
                    837:   Revision 1.85  2003/06/17 13:12:43  brouard
                    838:   * imach.c (Repository): Check when date of death was earlier that
                    839:   current date of interview. It may happen when the death was just
                    840:   prior to the death. In this case, dh was negative and likelihood
                    841:   was wrong (infinity). We still send an "Error" but patch by
                    842:   assuming that the date of death was just one stepm after the
                    843:   interview.
                    844:   (Repository): Because some people have very long ID (first column)
                    845:   we changed int to long in num[] and we added a new lvector for
                    846:   memory allocation. But we also truncated to 8 characters (left
                    847:   truncation)
                    848:   (Repository): No more line truncation errors.
                    849: 
                    850:   Revision 1.84  2003/06/13 21:44:43  brouard
                    851:   * imach.c (Repository): Replace "freqsummary" at a correct
                    852:   place. It differs from routine "prevalence" which may be called
                    853:   many times. Probs is memory consuming and must be used with
                    854:   parcimony.
                    855:   Version 0.95a3 (should output exactly the same maximization than 0.8a2)
                    856: 
                    857:   Revision 1.83  2003/06/10 13:39:11  lievre
                    858:   *** empty log message ***
                    859: 
                    860:   Revision 1.82  2003/06/05 15:57:20  brouard
                    861:   Add log in  imach.c and  fullversion number is now printed.
                    862: 
                    863: */
                    864: /*
                    865:    Interpolated Markov Chain
                    866: 
                    867:   Short summary of the programme:
                    868:   
1.227     brouard   869:   This program computes Healthy Life Expectancies or State-specific
                    870:   (if states aren't health statuses) Expectancies from
                    871:   cross-longitudinal data. Cross-longitudinal data consist in: 
                    872: 
                    873:   -1- a first survey ("cross") where individuals from different ages
                    874:   are interviewed on their health status or degree of disability (in
                    875:   the case of a health survey which is our main interest)
                    876: 
                    877:   -2- at least a second wave of interviews ("longitudinal") which
                    878:   measure each change (if any) in individual health status.  Health
                    879:   expectancies are computed from the time spent in each health state
                    880:   according to a model. More health states you consider, more time is
                    881:   necessary to reach the Maximum Likelihood of the parameters involved
                    882:   in the model.  The simplest model is the multinomial logistic model
                    883:   where pij is the probability to be observed in state j at the second
                    884:   wave conditional to be observed in state i at the first
                    885:   wave. Therefore the model is: log(pij/pii)= aij + bij*age+ cij*sex +
                    886:   etc , where 'age' is age and 'sex' is a covariate. If you want to
                    887:   have a more complex model than "constant and age", you should modify
                    888:   the program where the markup *Covariates have to be included here
                    889:   again* invites you to do it.  More covariates you add, slower the
1.126     brouard   890:   convergence.
                    891: 
                    892:   The advantage of this computer programme, compared to a simple
                    893:   multinomial logistic model, is clear when the delay between waves is not
                    894:   identical for each individual. Also, if a individual missed an
                    895:   intermediate interview, the information is lost, but taken into
                    896:   account using an interpolation or extrapolation.  
                    897: 
                    898:   hPijx is the probability to be observed in state i at age x+h
                    899:   conditional to the observed state i at age x. The delay 'h' can be
                    900:   split into an exact number (nh*stepm) of unobserved intermediate
                    901:   states. This elementary transition (by month, quarter,
                    902:   semester or year) is modelled as a multinomial logistic.  The hPx
                    903:   matrix is simply the matrix product of nh*stepm elementary matrices
                    904:   and the contribution of each individual to the likelihood is simply
                    905:   hPijx.
                    906: 
                    907:   Also this programme outputs the covariance matrix of the parameters but also
1.218     brouard   908:   of the life expectancies. It also computes the period (stable) prevalence.
                    909: 
                    910: Back prevalence and projections:
1.227     brouard   911: 
                    912:  - back_prevalence_limit(double *p, double **bprlim, double ageminpar,
                    913:    double agemaxpar, double ftolpl, int *ncvyearp, double
                    914:    dateprev1,double dateprev2, int firstpass, int lastpass, int
                    915:    mobilavproj)
                    916: 
                    917:     Computes the back prevalence limit for any combination of
                    918:     covariate values k at any age between ageminpar and agemaxpar and
                    919:     returns it in **bprlim. In the loops,
                    920: 
                    921:    - **bprevalim(**bprlim, ***mobaverage, nlstate, *p, age, **oldm,
                    922:        **savm, **dnewm, **doldm, **dsavm, ftolpl, ncvyearp, k);
                    923: 
                    924:    - hBijx Back Probability to be in state i at age x-h being in j at x
1.218     brouard   925:    Computes for any combination of covariates k and any age between bage and fage 
                    926:    p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                    927:                        oldm=oldms;savm=savms;
1.227     brouard   928: 
1.267     brouard   929:    - hbxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k, nres);
1.218     brouard   930:      Computes the transition matrix starting at age 'age' over
                    931:      'nhstepm*hstepm*stepm' months (i.e. until
                    932:      age (in years)  age+nhstepm*hstepm*stepm/12) by multiplying
1.227     brouard   933:      nhstepm*hstepm matrices. 
                    934: 
                    935:      Returns p3mat[i][j][h] after calling
                    936:      p3mat[i][j][h]=matprod2(newm,
                    937:      bmij(pmmij,cov,ncovmodel,x,nlstate,prevacurrent, dnewm, doldm,
                    938:      dsavm,ij),\ 1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath,
                    939:      oldm);
1.226     brouard   940: 
                    941: Important routines
                    942: 
                    943: - func (or funcone), computes logit (pij) distinguishing
                    944:   o fixed variables (single or product dummies or quantitative);
                    945:   o varying variables by:
                    946:    (1) wave (single, product dummies, quantitative), 
                    947:    (2) by age (can be month) age (done), age*age (done), age*Vn where Vn can be:
                    948:        % fixed dummy (treated) or quantitative (not done because time-consuming);
                    949:        % varying dummy (not done) or quantitative (not done);
                    950: - Tricode which tests the modality of dummy variables (in order to warn with wrong or empty modalities)
                    951:   and returns the number of efficient covariates cptcoveff and modalities nbcode[Tvar[k]][1]= 0 and nbcode[Tvar[k]][2]= 1 usually.
                    952: - printinghtml which outputs results like life expectancy in and from a state for a combination of modalities of dummy variables
                    953:   o There are 2*cptcoveff combinations of (0,1) for cptcoveff variables. Outputting only combinations with people, éliminating 1 1 if
                    954:     race White (0 0), Black vs White (1 0), Hispanic (0 1) and 1 1 being meaningless.
1.218     brouard   955: 
1.226     brouard   956: 
                    957:   
1.133     brouard   958:   Authors: Nicolas Brouard (brouard@ined.fr) and Agnès Lièvre (lievre@ined.fr).
                    959:            Institut national d'études démographiques, Paris.
1.126     brouard   960:   This software have been partly granted by Euro-REVES, a concerted action
                    961:   from the European Union.
                    962:   It is copyrighted identically to a GNU software product, ie programme and
                    963:   software can be distributed freely for non commercial use. Latest version
                    964:   can be accessed at http://euroreves.ined.fr/imach .
                    965: 
                    966:   Help to debug: LD_PRELOAD=/usr/local/lib/libnjamd.so ./imach foo.imach
                    967:   or better on gdb : set env LD_PRELOAD=/usr/local/lib/libnjamd.so
                    968:   
                    969:   **********************************************************************/
                    970: /*
                    971:   main
                    972:   read parameterfile
                    973:   read datafile
                    974:   concatwav
                    975:   freqsummary
                    976:   if (mle >= 1)
                    977:     mlikeli
                    978:   print results files
                    979:   if mle==1 
                    980:      computes hessian
                    981:   read end of parameter file: agemin, agemax, bage, fage, estepm
                    982:       begin-prev-date,...
                    983:   open gnuplot file
                    984:   open html file
1.145     brouard   985:   period (stable) prevalence      | pl_nom    1-1 2-2 etc by covariate
                    986:    for age prevalim()             | #****** V1=0  V2=1  V3=1  V4=0 ******
                    987:                                   | 65 1 0 2 1 3 1 4 0  0.96326 0.03674
                    988:     freexexit2 possible for memory heap.
                    989: 
                    990:   h Pij x                         | pij_nom  ficrestpij
                    991:    # Cov Agex agex+h hpijx with i,j= 1-1 1-2     1-3     2-1     2-2     2-3
                    992:        1  85   85    1.00000             0.00000 0.00000 0.00000 1.00000 0.00000
                    993:        1  85   86    0.68299             0.22291 0.09410 0.71093 0.00000 0.28907
                    994: 
                    995:        1  65   99    0.00364             0.00322 0.99314 0.00350 0.00310 0.99340
                    996:        1  65  100    0.00214             0.00204 0.99581 0.00206 0.00196 0.99597
                    997:   variance of p one-step probabilities varprob  | prob_nom   ficresprob #One-step probabilities and stand. devi in ()
                    998:    Standard deviation of one-step probabilities | probcor_nom   ficresprobcor #One-step probabilities and correlation matrix
                    999:    Matrix of variance covariance of one-step probabilities |  probcov_nom ficresprobcov #One-step probabilities and covariance matrix
                   1000: 
1.126     brouard  1001:   forecasting if prevfcast==1 prevforecast call prevalence()
                   1002:   health expectancies
                   1003:   Variance-covariance of DFLE
                   1004:   prevalence()
                   1005:    movingaverage()
                   1006:   varevsij() 
                   1007:   if popbased==1 varevsij(,popbased)
                   1008:   total life expectancies
                   1009:   Variance of period (stable) prevalence
                   1010:  end
                   1011: */
                   1012: 
1.187     brouard  1013: /* #define DEBUG */
                   1014: /* #define DEBUGBRENT */
1.203     brouard  1015: /* #define DEBUGLINMIN */
                   1016: /* #define DEBUGHESS */
                   1017: #define DEBUGHESSIJ
1.224     brouard  1018: /* #define LINMINORIGINAL  /\* Don't use loop on scale in linmin (accepting nan) *\/ */
1.165     brouard  1019: #define POWELL /* Instead of NLOPT */
1.224     brouard  1020: #define POWELLNOF3INFF1TEST /* Skip test */
1.186     brouard  1021: /* #define POWELLORIGINAL /\* Don't use Directest to decide new direction but original Powell test *\/ */
                   1022: /* #define MNBRAKORIGINAL /\* Don't use mnbrak fix *\/ */
1.126     brouard  1023: 
                   1024: #include <math.h>
                   1025: #include <stdio.h>
                   1026: #include <stdlib.h>
                   1027: #include <string.h>
1.226     brouard  1028: #include <ctype.h>
1.159     brouard  1029: 
                   1030: #ifdef _WIN32
                   1031: #include <io.h>
1.172     brouard  1032: #include <windows.h>
                   1033: #include <tchar.h>
1.159     brouard  1034: #else
1.126     brouard  1035: #include <unistd.h>
1.159     brouard  1036: #endif
1.126     brouard  1037: 
                   1038: #include <limits.h>
                   1039: #include <sys/types.h>
1.171     brouard  1040: 
                   1041: #if defined(__GNUC__)
                   1042: #include <sys/utsname.h> /* Doesn't work on Windows */
                   1043: #endif
                   1044: 
1.126     brouard  1045: #include <sys/stat.h>
                   1046: #include <errno.h>
1.159     brouard  1047: /* extern int errno; */
1.126     brouard  1048: 
1.157     brouard  1049: /* #ifdef LINUX */
                   1050: /* #include <time.h> */
                   1051: /* #include "timeval.h" */
                   1052: /* #else */
                   1053: /* #include <sys/time.h> */
                   1054: /* #endif */
                   1055: 
1.126     brouard  1056: #include <time.h>
                   1057: 
1.136     brouard  1058: #ifdef GSL
                   1059: #include <gsl/gsl_errno.h>
                   1060: #include <gsl/gsl_multimin.h>
                   1061: #endif
                   1062: 
1.167     brouard  1063: 
1.162     brouard  1064: #ifdef NLOPT
                   1065: #include <nlopt.h>
                   1066: typedef struct {
                   1067:   double (* function)(double [] );
                   1068: } myfunc_data ;
                   1069: #endif
                   1070: 
1.126     brouard  1071: /* #include <libintl.h> */
                   1072: /* #define _(String) gettext (String) */
                   1073: 
1.251     brouard  1074: #define MAXLINE 2048 /* Was 256 and 1024. Overflow with 312 with 2 states and 4 covariates. Should be ok */
1.126     brouard  1075: 
                   1076: #define GNUPLOTPROGRAM "gnuplot"
                   1077: /*#define GNUPLOTPROGRAM "..\\gp37mgw\\wgnuplot"*/
                   1078: #define FILENAMELENGTH 132
                   1079: 
                   1080: #define        GLOCK_ERROR_NOPATH              -1      /* empty path */
                   1081: #define        GLOCK_ERROR_GETCWD              -2      /* cannot get cwd */
                   1082: 
1.144     brouard  1083: #define MAXPARM 128 /**< Maximum number of parameters for the optimization */
                   1084: #define NPARMAX 64 /**< (nlstate+ndeath-1)*nlstate*ncovmodel */
1.126     brouard  1085: 
                   1086: #define NINTERVMAX 8
1.144     brouard  1087: #define NLSTATEMAX 8 /**< Maximum number of live states (for func) */
                   1088: #define NDEATHMAX 8 /**< Maximum number of dead states (for func) */
1.291     brouard  1089: #define NCOVMAX 20  /**< Maximum number of covariates, including generated covariates V1*V2 */
1.197     brouard  1090: #define codtabm(h,k)  (1 & (h-1) >> (k-1))+1
1.211     brouard  1091: /*#define decodtabm(h,k,cptcoveff)= (h <= (1<<cptcoveff)?(((h-1) >> (k-1)) & 1) +1 : -1)*/
                   1092: #define decodtabm(h,k,cptcoveff) (((h-1) >> (k-1)) & 1) +1 
1.290     brouard  1093: /*#define MAXN 20000 */ /* Should by replaced by nobs, real number of observations and unlimited */
1.144     brouard  1094: #define YEARM 12. /**< Number of months per year */
1.218     brouard  1095: /* #define AGESUP 130 */
1.288     brouard  1096: /* #define AGESUP 150 */
                   1097: #define AGESUP 200
1.268     brouard  1098: #define AGEINF 0
1.218     brouard  1099: #define AGEMARGE 25 /* Marge for agemin and agemax for(iage=agemin-AGEMARGE; iage <= agemax+3+AGEMARGE; iage++) */
1.126     brouard  1100: #define AGEBASE 40
1.194     brouard  1101: #define AGEOVERFLOW 1.e20
1.164     brouard  1102: #define AGEGOMP 10 /**< Minimal age for Gompertz adjustment */
1.157     brouard  1103: #ifdef _WIN32
                   1104: #define DIRSEPARATOR '\\'
                   1105: #define CHARSEPARATOR "\\"
                   1106: #define ODIRSEPARATOR '/'
                   1107: #else
1.126     brouard  1108: #define DIRSEPARATOR '/'
                   1109: #define CHARSEPARATOR "/"
                   1110: #define ODIRSEPARATOR '\\'
                   1111: #endif
                   1112: 
1.298   ! brouard  1113: /* $Id: imach.c,v 1.297 2019/05/22 17:56:10 brouard Exp $ */
1.126     brouard  1114: /* $State: Exp $ */
1.196     brouard  1115: #include "version.h"
                   1116: char version[]=__IMACH_VERSION__;
1.283     brouard  1117: 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.298   ! brouard  1118: char fullversion[]="$Revision: 1.297 $ $Date: 2019/05/22 17:56:10 $"; 
1.126     brouard  1119: char strstart[80];
                   1120: char optionfilext[10], optionfilefiname[FILENAMELENGTH];
1.130     brouard  1121: int erreur=0, nberr=0, nbwarn=0; /* Error number, number of errors number of warnings  */
1.187     brouard  1122: int nagesqr=0, nforce=0; /* nagesqr=1 if model is including age*age, number of forces */
1.145     brouard  1123: /* Number of covariates model=V2+V1+ V3*age+V2*V4 */
                   1124: int cptcovn=0; /**< cptcovn number of covariates added in the model (excepting constant and age and age*product) */
                   1125: int cptcovt=0; /**< cptcovt number of covariates added in the model (excepting constant and age) */
1.225     brouard  1126: int cptcovs=0; /**< cptcovs number of simple covariates in the model V2+V1 =2 */
                   1127: int cptcovsnq=0; /**< cptcovsnq number of simple covariates in the model but non quantitative V2+V1 =2 */
1.145     brouard  1128: int cptcovage=0; /**< Number of covariates with age: V3*age only =1 */
                   1129: int cptcovprodnoage=0; /**< Number of covariate products without age */   
                   1130: int cptcoveff=0; /* Total number of covariates to vary for printing results */
1.233     brouard  1131: int ncovf=0; /* Total number of effective fixed covariates (dummy or quantitative) in the model */
                   1132: int ncovv=0; /* Total number of effective (wave) varying covariates (dummy or quantitative) in the model */
1.232     brouard  1133: int ncova=0; /* Total number of effective (wave and stepm) varying with age covariates (dummy of quantitative) in the model */
1.234     brouard  1134: int nsd=0; /**< Total number of single dummy variables (output) */
                   1135: int nsq=0; /**< Total number of single quantitative variables (output) */
1.232     brouard  1136: int ncoveff=0; /* Total number of effective fixed dummy covariates in the model */
1.225     brouard  1137: int nqfveff=0; /**< nqfveff Number of Quantitative Fixed Variables Effective */
1.224     brouard  1138: int ntveff=0; /**< ntveff number of effective time varying variables */
                   1139: int nqtveff=0; /**< ntqveff number of effective time varying quantitative variables */
1.145     brouard  1140: int cptcov=0; /* Working variable */
1.290     brouard  1141: int nobs=10;  /* Number of observations in the data lastobs-firstobs */
1.218     brouard  1142: int ncovcombmax=NCOVMAX; /* Maximum calculated number of covariate combination = pow(2, cptcoveff) */
1.126     brouard  1143: int npar=NPARMAX;
                   1144: int nlstate=2; /* Number of live states */
                   1145: int ndeath=1; /* Number of dead states */
1.130     brouard  1146: int ncovmodel=0, ncovcol=0;     /* Total number of covariables including constant a12*1 +b12*x ncovmodel=2 */
1.223     brouard  1147: int  nqv=0, ntv=0, nqtv=0;    /* Total number of quantitative variables, time variable (dummy), quantitative and time variable */ 
1.126     brouard  1148: int popbased=0;
                   1149: 
                   1150: int *wav; /* Number of waves for this individuual 0 is possible */
1.130     brouard  1151: int maxwav=0; /* Maxim number of waves */
                   1152: int jmin=0, jmax=0; /* min, max spacing between 2 waves */
                   1153: int ijmin=0, ijmax=0; /* Individuals having jmin and jmax */ 
                   1154: int gipmx=0, gsw=0; /* Global variables on the number of contributions 
1.126     brouard  1155:                   to the likelihood and the sum of weights (done by funcone)*/
1.130     brouard  1156: int mle=1, weightopt=0;
1.126     brouard  1157: int **mw; /* mw[mi][i] is number of the mi wave for this individual */
                   1158: int **dh; /* dh[mi][i] is number of steps between mi,mi+1 for this individual */
                   1159: int **bh; /* bh[mi][i] is the bias (+ or -) for this individual if the delay between
                   1160:           * wave mi and wave mi+1 is not an exact multiple of stepm. */
1.162     brouard  1161: int countcallfunc=0;  /* Count the number of calls to func */
1.230     brouard  1162: int selected(int kvar); /* Is covariate kvar selected for printing results */
                   1163: 
1.130     brouard  1164: double jmean=1; /* Mean space between 2 waves */
1.145     brouard  1165: double **matprod2(); /* test */
1.126     brouard  1166: double **oldm, **newm, **savm; /* Working pointers to matrices */
                   1167: double **oldms, **newms, **savms; /* Fixed working pointers to matrices */
1.218     brouard  1168: double  **ddnewms, **ddoldms, **ddsavms; /* for freeing later */
                   1169: 
1.136     brouard  1170: /*FILE *fic ; */ /* Used in readdata only */
1.217     brouard  1171: FILE *ficpar, *ficparo,*ficres, *ficresp, *ficresphtm, *ficresphtmfr, *ficrespl, *ficresplb,*ficrespij, *ficrespijb, *ficrest,*ficresf, *ficresfb,*ficrespop;
1.126     brouard  1172: FILE *ficlog, *ficrespow;
1.130     brouard  1173: int globpr=0; /* Global variable for printing or not */
1.126     brouard  1174: double fretone; /* Only one call to likelihood */
1.130     brouard  1175: long ipmx=0; /* Number of contributions */
1.126     brouard  1176: double sw; /* Sum of weights */
                   1177: char filerespow[FILENAMELENGTH];
                   1178: char fileresilk[FILENAMELENGTH]; /* File of individual contributions to the likelihood */
                   1179: FILE *ficresilk;
                   1180: FILE *ficgp,*ficresprob,*ficpop, *ficresprobcov, *ficresprobcor;
                   1181: FILE *ficresprobmorprev;
                   1182: FILE *fichtm, *fichtmcov; /* Html File */
                   1183: FILE *ficreseij;
                   1184: char filerese[FILENAMELENGTH];
                   1185: FILE *ficresstdeij;
                   1186: char fileresstde[FILENAMELENGTH];
                   1187: FILE *ficrescveij;
                   1188: char filerescve[FILENAMELENGTH];
                   1189: FILE  *ficresvij;
                   1190: char fileresv[FILENAMELENGTH];
1.269     brouard  1191: 
1.126     brouard  1192: char title[MAXLINE];
1.234     brouard  1193: char model[MAXLINE]; /**< The model line */
1.217     brouard  1194: char optionfile[FILENAMELENGTH], datafile[FILENAMELENGTH],  filerespl[FILENAMELENGTH],  fileresplb[FILENAMELENGTH];
1.126     brouard  1195: char plotcmd[FILENAMELENGTH], pplotcmd[FILENAMELENGTH];
                   1196: char tmpout[FILENAMELENGTH],  tmpout2[FILENAMELENGTH]; 
                   1197: char command[FILENAMELENGTH];
                   1198: int  outcmd=0;
                   1199: 
1.217     brouard  1200: char fileres[FILENAMELENGTH], filerespij[FILENAMELENGTH], filerespijb[FILENAMELENGTH], filereso[FILENAMELENGTH], rfileres[FILENAMELENGTH];
1.202     brouard  1201: char fileresu[FILENAMELENGTH]; /* fileres without r in front */
1.126     brouard  1202: char filelog[FILENAMELENGTH]; /* Log file */
                   1203: char filerest[FILENAMELENGTH];
                   1204: char fileregp[FILENAMELENGTH];
                   1205: char popfile[FILENAMELENGTH];
                   1206: 
                   1207: char optionfilegnuplot[FILENAMELENGTH], optionfilehtm[FILENAMELENGTH], optionfilehtmcov[FILENAMELENGTH] ;
                   1208: 
1.157     brouard  1209: /* struct timeval start_time, end_time, curr_time, last_time, forecast_time; */
                   1210: /* struct timezone tzp; */
                   1211: /* extern int gettimeofday(); */
                   1212: struct tm tml, *gmtime(), *localtime();
                   1213: 
                   1214: extern time_t time();
                   1215: 
                   1216: struct tm start_time, end_time, curr_time, last_time, forecast_time;
                   1217: time_t  rstart_time, rend_time, rcurr_time, rlast_time, rforecast_time; /* raw time */
                   1218: struct tm tm;
                   1219: 
1.126     brouard  1220: char strcurr[80], strfor[80];
                   1221: 
                   1222: char *endptr;
                   1223: long lval;
                   1224: double dval;
                   1225: 
                   1226: #define NR_END 1
                   1227: #define FREE_ARG char*
                   1228: #define FTOL 1.0e-10
                   1229: 
                   1230: #define NRANSI 
1.240     brouard  1231: #define ITMAX 200
                   1232: #define ITPOWMAX 20 /* This is now multiplied by the number of parameters */ 
1.126     brouard  1233: 
                   1234: #define TOL 2.0e-4 
                   1235: 
                   1236: #define CGOLD 0.3819660 
                   1237: #define ZEPS 1.0e-10 
                   1238: #define SHFT(a,b,c,d) (a)=(b);(b)=(c);(c)=(d); 
                   1239: 
                   1240: #define GOLD 1.618034 
                   1241: #define GLIMIT 100.0 
                   1242: #define TINY 1.0e-20 
                   1243: 
                   1244: static double maxarg1,maxarg2;
                   1245: #define FMAX(a,b) (maxarg1=(a),maxarg2=(b),(maxarg1)>(maxarg2)? (maxarg1):(maxarg2))
                   1246: #define FMIN(a,b) (maxarg1=(a),maxarg2=(b),(maxarg1)<(maxarg2)? (maxarg1):(maxarg2))
                   1247:   
                   1248: #define SIGN(a,b) ((b)>0.0 ? fabs(a) : -fabs(a))
                   1249: #define rint(a) floor(a+0.5)
1.166     brouard  1250: /* http://www.thphys.uni-heidelberg.de/~robbers/cmbeasy/doc/html/myutils_8h-source.html */
1.183     brouard  1251: #define mytinydouble 1.0e-16
1.166     brouard  1252: /* #define DEQUAL(a,b) (fabs((a)-(b))<mytinydouble) */
                   1253: /* http://www.thphys.uni-heidelberg.de/~robbers/cmbeasy/doc/html/mynrutils_8h-source.html */
                   1254: /* static double dsqrarg; */
                   1255: /* #define DSQR(a) (DEQUAL((dsqrarg=(a)),0.0) ? 0.0 : dsqrarg*dsqrarg) */
1.126     brouard  1256: static double sqrarg;
                   1257: #define SQR(a) ((sqrarg=(a)) == 0.0 ? 0.0 :sqrarg*sqrarg)
                   1258: #define SWAP(a,b) {temp=(a);(a)=(b);(b)=temp;} 
                   1259: int agegomp= AGEGOMP;
                   1260: 
                   1261: int imx; 
                   1262: int stepm=1;
                   1263: /* Stepm, step in month: minimum step interpolation*/
                   1264: 
                   1265: int estepm;
                   1266: /* Estepm, step in month to interpolate survival function in order to approximate Life Expectancy*/
                   1267: 
                   1268: int m,nb;
                   1269: long *num;
1.197     brouard  1270: int firstpass=0, lastpass=4,*cod, *cens;
1.192     brouard  1271: int *ncodemax;  /* ncodemax[j]= Number of modalities of the j th
                   1272:                   covariate for which somebody answered excluding 
                   1273:                   undefined. Usually 2: 0 and 1. */
                   1274: int *ncodemaxwundef;  /* ncodemax[j]= Number of modalities of the j th
                   1275:                             covariate for which somebody answered including 
                   1276:                             undefined. Usually 3: -1, 0 and 1. */
1.126     brouard  1277: double **agev,*moisnais, *annais, *moisdc, *andc,**mint, **anint;
1.218     brouard  1278: double **pmmij, ***probs; /* Global pointer */
1.219     brouard  1279: double ***mobaverage, ***mobaverages; /* New global variable */
1.126     brouard  1280: double *ageexmed,*agecens;
                   1281: double dateintmean=0;
1.296     brouard  1282:   double anprojd, mprojd, jprojd; /* For eventual projections */
                   1283:   double anprojf, mprojf, jprojf;
1.126     brouard  1284: 
1.296     brouard  1285:   double anbackd, mbackd, jbackd; /* For eventual backprojections */
                   1286:   double anbackf, mbackf, jbackf;
                   1287:   double jintmean,mintmean,aintmean;  
1.126     brouard  1288: double *weight;
                   1289: int **s; /* Status */
1.141     brouard  1290: double *agedc;
1.145     brouard  1291: double  **covar; /**< covar[j,i], value of jth covariate for individual i,
1.141     brouard  1292:                  * covar=matrix(0,NCOVMAX,1,n); 
1.187     brouard  1293:                  * cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*age; */
1.268     brouard  1294: double **coqvar; /* Fixed quantitative covariate nqv */
                   1295: double ***cotvar; /* Time varying covariate ntv */
1.225     brouard  1296: double ***cotqvar; /* Time varying quantitative covariate itqv */
1.141     brouard  1297: double  idx; 
                   1298: int **nbcode, *Tvar; /**< model=V2 => Tvar[1]= 2 */
1.234     brouard  1299: /*           V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
                   1300: /*k          1  2   3   4     5    6    7     8    9 */
                   1301: /*Tvar[k]=   5  4   3   6     5    2    7     1    1 */
                   1302: /* Tndvar[k]    1   2   3               4          5 */
                   1303: /*TDvar         4   3   6               7          1 */ /* For outputs only; combination of dummies fixed or varying */
                   1304: /* Tns[k]    1  2   2              4               5 */ /* Number of single cova */
                   1305: /* TvarsD[k]    1   2                              3 */ /* Number of single dummy cova */
                   1306: /* TvarsDind    2   3                              9 */ /* position K of single dummy cova */
                   1307: /* TvarsQ[k] 1                     2                 */ /* Number of single quantitative cova */
                   1308: /* TvarsQind 1                     6                 */ /* position K of single quantitative cova */
                   1309: /* Tprod[i]=k           4               7            */
                   1310: /* Tage[i]=k                  5               8      */
                   1311: /* */
                   1312: /* Type                    */
                   1313: /* V         1  2  3  4  5 */
                   1314: /*           F  F  V  V  V */
                   1315: /*           D  Q  D  D  Q */
                   1316: /*                         */
                   1317: int *TvarsD;
                   1318: int *TvarsDind;
                   1319: int *TvarsQ;
                   1320: int *TvarsQind;
                   1321: 
1.235     brouard  1322: #define MAXRESULTLINES 10
                   1323: int nresult=0;
1.258     brouard  1324: int parameterline=0; /* # of the parameter (type) line */
1.235     brouard  1325: int TKresult[MAXRESULTLINES];
1.237     brouard  1326: int Tresult[MAXRESULTLINES][NCOVMAX];/* For dummy variable , value (output) */
                   1327: int Tinvresult[MAXRESULTLINES][NCOVMAX];/* For dummy variable , value (output) */
1.235     brouard  1328: int Tvresult[MAXRESULTLINES][NCOVMAX]; /* For dummy variable , variable # (output) */
                   1329: double Tqresult[MAXRESULTLINES][NCOVMAX]; /* For quantitative variable , value (output) */
1.237     brouard  1330: double Tqinvresult[MAXRESULTLINES][NCOVMAX]; /* For quantitative variable , value (output) */
1.235     brouard  1331: int Tvqresult[MAXRESULTLINES][NCOVMAX]; /* For quantitative variable , variable # (output) */
                   1332: 
1.234     brouard  1333: /* 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  1334: 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 */
                   1335: 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 */
                   1336: 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 */
                   1337: int *TvarVind; /**< TvarVind[1]=1, TvarVind[2]=2  in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
                   1338: 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 */
                   1339: 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  1340: int *TvarFD; /**< TvarFD[1]=V1 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
                   1341: int *TvarFDind; /* TvarFDind[1]=9 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
                   1342: int *TvarFQ; /* TvarFQ[1]=V2 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */ /* Only simple fixed quantitative variable */
                   1343: int *TvarFQind; /* TvarFQind[1]=6 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */ /* Only simple fixed quantitative variable */
                   1344: int *TvarVD; /* TvarVD[1]=V5 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */ /* Only simple fixed quantitative variable */
                   1345: int *TvarVDind; /* TvarVDind[1]=1 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */ /* Only simple fixed quantitative variable */
                   1346: 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 */
                   1347: 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 */
                   1348: 
1.230     brouard  1349: int *Tvarsel; /**< Selected covariates for output */
                   1350: double *Tvalsel; /**< Selected modality value of covariate for output */
1.226     brouard  1351: int *Typevar; /**< 0 for simple covariate (dummy, quantitative, fixed or varying), 1 for age product, 2 for  product */
1.227     brouard  1352: int *Fixed; /** Fixed[k] 0=fixed, 1 varying, 2 fixed with age product, 3 varying with age product */ 
                   1353: 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  1354: int *DummyV; /** Dummy[v] 0=dummy (0 1), 1 quantitative */
                   1355: int *FixedV; /** FixedV[v] 0 fixed, 1 varying */
1.197     brouard  1356: int *Tage;
1.227     brouard  1357: int anyvaryingduminmodel=0; /**< Any varying dummy in Model=1 yes, 0 no, to avoid a loop on waves in freq */ 
1.228     brouard  1358: 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  1359: 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*/ 
                   1360: 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  1361: int *Ndum; /** Freq of modality (tricode */
1.200     brouard  1362: /* int **codtab;*/ /**< codtab=imatrix(1,100,1,10); */
1.227     brouard  1363: int **Tvard;
                   1364: int *Tprod;/**< Gives the k position of the k1 product */
1.238     brouard  1365: /* Tprod[k1=1]=3(=V1*V4) for V2+V1+V1*V4+age*V3  */
1.227     brouard  1366: int *Tposprod; /**< Gives the k1 product from the k position */
1.238     brouard  1367:    /* if  V2+V1+V1*V4+age*V3+V3*V2   TProd[k1=2]=5 (V3*V2) */
                   1368:    /* Tposprod[k]=k1 , Tposprod[3]=1, Tposprod[5(V3*V2)]=2 (2nd product without age) */
1.227     brouard  1369: int cptcovprod, *Tvaraff, *invalidvarcomb;
1.126     brouard  1370: double *lsurv, *lpop, *tpop;
                   1371: 
1.231     brouard  1372: #define FD 1; /* Fixed dummy covariate */
                   1373: #define FQ 2; /* Fixed quantitative covariate */
                   1374: #define FP 3; /* Fixed product covariate */
                   1375: #define FPDD 7; /* Fixed product dummy*dummy covariate */
                   1376: #define FPDQ 8; /* Fixed product dummy*quantitative covariate */
                   1377: #define FPQQ 9; /* Fixed product quantitative*quantitative covariate */
                   1378: #define VD 10; /* Varying dummy covariate */
                   1379: #define VQ 11; /* Varying quantitative covariate */
                   1380: #define VP 12; /* Varying product covariate */
                   1381: #define VPDD 13; /* Varying product dummy*dummy covariate */
                   1382: #define VPDQ 14; /* Varying product dummy*quantitative covariate */
                   1383: #define VPQQ 15; /* Varying product quantitative*quantitative covariate */
                   1384: #define APFD 16; /* Age product * fixed dummy covariate */
                   1385: #define APFQ 17; /* Age product * fixed quantitative covariate */
                   1386: #define APVD 18; /* Age product * varying dummy covariate */
                   1387: #define APVQ 19; /* Age product * varying quantitative covariate */
                   1388: 
                   1389: #define FTYPE 1; /* Fixed covariate */
                   1390: #define VTYPE 2; /* Varying covariate (loop in wave) */
                   1391: #define ATYPE 2; /* Age product covariate (loop in dh within wave)*/
                   1392: 
                   1393: struct kmodel{
                   1394:        int maintype; /* main type */
                   1395:        int subtype; /* subtype */
                   1396: };
                   1397: struct kmodel modell[NCOVMAX];
                   1398: 
1.143     brouard  1399: double ftol=FTOL; /**< Tolerance for computing Max Likelihood */
                   1400: double ftolhess; /**< Tolerance for computing hessian */
1.126     brouard  1401: 
                   1402: /**************** split *************************/
                   1403: static int split( char *path, char *dirc, char *name, char *ext, char *finame )
                   1404: {
                   1405:   /* From a file name with (full) path (either Unix or Windows) we extract the directory (dirc)
                   1406:      the name of the file (name), its extension only (ext) and its first part of the name (finame)
                   1407:   */ 
                   1408:   char *ss;                            /* pointer */
1.186     brouard  1409:   int  l1=0, l2=0;                             /* length counters */
1.126     brouard  1410: 
                   1411:   l1 = strlen(path );                  /* length of path */
                   1412:   if ( l1 == 0 ) return( GLOCK_ERROR_NOPATH );
                   1413:   ss= strrchr( path, DIRSEPARATOR );           /* find last / */
                   1414:   if ( ss == NULL ) {                  /* no directory, so determine current directory */
                   1415:     strcpy( name, path );              /* we got the fullname name because no directory */
                   1416:     /*if(strrchr(path, ODIRSEPARATOR )==NULL)
                   1417:       printf("Warning you should use %s as a separator\n",DIRSEPARATOR);*/
                   1418:     /* get current working directory */
                   1419:     /*    extern  char* getcwd ( char *buf , int len);*/
1.184     brouard  1420: #ifdef WIN32
                   1421:     if (_getcwd( dirc, FILENAME_MAX ) == NULL ) {
                   1422: #else
                   1423:        if (getcwd(dirc, FILENAME_MAX) == NULL) {
                   1424: #endif
1.126     brouard  1425:       return( GLOCK_ERROR_GETCWD );
                   1426:     }
                   1427:     /* got dirc from getcwd*/
                   1428:     printf(" DIRC = %s \n",dirc);
1.205     brouard  1429:   } else {                             /* strip directory from path */
1.126     brouard  1430:     ss++;                              /* after this, the filename */
                   1431:     l2 = strlen( ss );                 /* length of filename */
                   1432:     if ( l2 == 0 ) return( GLOCK_ERROR_NOPATH );
                   1433:     strcpy( name, ss );                /* save file name */
                   1434:     strncpy( dirc, path, l1 - l2 );    /* now the directory */
1.186     brouard  1435:     dirc[l1-l2] = '\0';                        /* add zero */
1.126     brouard  1436:     printf(" DIRC2 = %s \n",dirc);
                   1437:   }
                   1438:   /* We add a separator at the end of dirc if not exists */
                   1439:   l1 = strlen( dirc );                 /* length of directory */
                   1440:   if( dirc[l1-1] != DIRSEPARATOR ){
                   1441:     dirc[l1] =  DIRSEPARATOR;
                   1442:     dirc[l1+1] = 0; 
                   1443:     printf(" DIRC3 = %s \n",dirc);
                   1444:   }
                   1445:   ss = strrchr( name, '.' );           /* find last / */
                   1446:   if (ss >0){
                   1447:     ss++;
                   1448:     strcpy(ext,ss);                    /* save extension */
                   1449:     l1= strlen( name);
                   1450:     l2= strlen(ss)+1;
                   1451:     strncpy( finame, name, l1-l2);
                   1452:     finame[l1-l2]= 0;
                   1453:   }
                   1454: 
                   1455:   return( 0 );                         /* we're done */
                   1456: }
                   1457: 
                   1458: 
                   1459: /******************************************/
                   1460: 
                   1461: void replace_back_to_slash(char *s, char*t)
                   1462: {
                   1463:   int i;
                   1464:   int lg=0;
                   1465:   i=0;
                   1466:   lg=strlen(t);
                   1467:   for(i=0; i<= lg; i++) {
                   1468:     (s[i] = t[i]);
                   1469:     if (t[i]== '\\') s[i]='/';
                   1470:   }
                   1471: }
                   1472: 
1.132     brouard  1473: char *trimbb(char *out, char *in)
1.137     brouard  1474: { /* Trim multiple blanks in line but keeps first blanks if line starts with blanks */
1.132     brouard  1475:   char *s;
                   1476:   s=out;
                   1477:   while (*in != '\0'){
1.137     brouard  1478:     while( *in == ' ' && *(in+1) == ' '){ /* && *(in+1) != '\0'){*/
1.132     brouard  1479:       in++;
                   1480:     }
                   1481:     *out++ = *in++;
                   1482:   }
                   1483:   *out='\0';
                   1484:   return s;
                   1485: }
                   1486: 
1.187     brouard  1487: /* char *substrchaine(char *out, char *in, char *chain) */
                   1488: /* { */
                   1489: /*   /\* Substract chain 'chain' from 'in', return and output 'out' *\/ */
                   1490: /*   char *s, *t; */
                   1491: /*   t=in;s=out; */
                   1492: /*   while ((*in != *chain) && (*in != '\0')){ */
                   1493: /*     *out++ = *in++; */
                   1494: /*   } */
                   1495: 
                   1496: /*   /\* *in matches *chain *\/ */
                   1497: /*   while ((*in++ == *chain++) && (*in != '\0')){ */
                   1498: /*     printf("*in = %c, *out= %c *chain= %c \n", *in, *out, *chain);  */
                   1499: /*   } */
                   1500: /*   in--; chain--; */
                   1501: /*   while ( (*in != '\0')){ */
                   1502: /*     printf("Bef *in = %c, *out= %c *chain= %c \n", *in, *out, *chain);  */
                   1503: /*     *out++ = *in++; */
                   1504: /*     printf("Aft *in = %c, *out= %c *chain= %c \n", *in, *out, *chain);  */
                   1505: /*   } */
                   1506: /*   *out='\0'; */
                   1507: /*   out=s; */
                   1508: /*   return out; */
                   1509: /* } */
                   1510: char *substrchaine(char *out, char *in, char *chain)
                   1511: {
                   1512:   /* Substract chain 'chain' from 'in', return and output 'out' */
                   1513:   /* in="V1+V1*age+age*age+V2", chain="age*age" */
                   1514: 
                   1515:   char *strloc;
                   1516: 
                   1517:   strcpy (out, in); 
                   1518:   strloc = strstr(out, chain); /* strloc points to out at age*age+V2 */
                   1519:   printf("Bef strloc=%s chain=%s out=%s \n", strloc, chain, out);
                   1520:   if(strloc != NULL){ 
                   1521:     /* will affect out */ /* strloc+strlenc(chain)=+V2 */ /* Will also work in Unicode */
                   1522:     memmove(strloc,strloc+strlen(chain), strlen(strloc+strlen(chain))+1);
                   1523:     /* strcpy (strloc, strloc +strlen(chain));*/
                   1524:   }
                   1525:   printf("Aft strloc=%s chain=%s in=%s out=%s \n", strloc, chain, in, out);
                   1526:   return out;
                   1527: }
                   1528: 
                   1529: 
1.145     brouard  1530: char *cutl(char *blocc, char *alocc, char *in, char occ)
                   1531: {
1.187     brouard  1532:   /* cuts string in into blocc and alocc where blocc ends before FIRST occurence of char 'occ' 
1.145     brouard  1533:      and alocc starts after first occurence of char 'occ' : ex cutv(blocc,alocc,"abcdef2ghi2j",'2')
1.187     brouard  1534:      gives blocc="abcdef" and alocc="ghi2j".
1.145     brouard  1535:      If occ is not found blocc is null and alocc is equal to in. Returns blocc
                   1536:   */
1.160     brouard  1537:   char *s, *t;
1.145     brouard  1538:   t=in;s=in;
                   1539:   while ((*in != occ) && (*in != '\0')){
                   1540:     *alocc++ = *in++;
                   1541:   }
                   1542:   if( *in == occ){
                   1543:     *(alocc)='\0';
                   1544:     s=++in;
                   1545:   }
                   1546:  
                   1547:   if (s == t) {/* occ not found */
                   1548:     *(alocc-(in-s))='\0';
                   1549:     in=s;
                   1550:   }
                   1551:   while ( *in != '\0'){
                   1552:     *blocc++ = *in++;
                   1553:   }
                   1554: 
                   1555:   *blocc='\0';
                   1556:   return t;
                   1557: }
1.137     brouard  1558: char *cutv(char *blocc, char *alocc, char *in, char occ)
                   1559: {
1.187     brouard  1560:   /* cuts string in into blocc and alocc where blocc ends before LAST occurence of char 'occ' 
1.137     brouard  1561:      and alocc starts after last occurence of char 'occ' : ex cutv(blocc,alocc,"abcdef2ghi2j",'2')
                   1562:      gives blocc="abcdef2ghi" and alocc="j".
                   1563:      If occ is not found blocc is null and alocc is equal to in. Returns alocc
                   1564:   */
                   1565:   char *s, *t;
                   1566:   t=in;s=in;
                   1567:   while (*in != '\0'){
                   1568:     while( *in == occ){
                   1569:       *blocc++ = *in++;
                   1570:       s=in;
                   1571:     }
                   1572:     *blocc++ = *in++;
                   1573:   }
                   1574:   if (s == t) /* occ not found */
                   1575:     *(blocc-(in-s))='\0';
                   1576:   else
                   1577:     *(blocc-(in-s)-1)='\0';
                   1578:   in=s;
                   1579:   while ( *in != '\0'){
                   1580:     *alocc++ = *in++;
                   1581:   }
                   1582: 
                   1583:   *alocc='\0';
                   1584:   return s;
                   1585: }
                   1586: 
1.126     brouard  1587: int nbocc(char *s, char occ)
                   1588: {
                   1589:   int i,j=0;
                   1590:   int lg=20;
                   1591:   i=0;
                   1592:   lg=strlen(s);
                   1593:   for(i=0; i<= lg; i++) {
1.234     brouard  1594:     if  (s[i] == occ ) j++;
1.126     brouard  1595:   }
                   1596:   return j;
                   1597: }
                   1598: 
1.137     brouard  1599: /* void cutv(char *u,char *v, char*t, char occ) */
                   1600: /* { */
                   1601: /*   /\* cuts string t into u and v where u ends before last occurence of char 'occ'  */
                   1602: /*      and v starts after last occurence of char 'occ' : ex cutv(u,v,"abcdef2ghi2j",'2') */
                   1603: /*      gives u="abcdef2ghi" and v="j" *\/ */
                   1604: /*   int i,lg,j,p=0; */
                   1605: /*   i=0; */
                   1606: /*   lg=strlen(t); */
                   1607: /*   for(j=0; j<=lg-1; j++) { */
                   1608: /*     if((t[j]!= occ) && (t[j+1]== occ)) p=j+1; */
                   1609: /*   } */
1.126     brouard  1610: 
1.137     brouard  1611: /*   for(j=0; j<p; j++) { */
                   1612: /*     (u[j] = t[j]); */
                   1613: /*   } */
                   1614: /*      u[p]='\0'; */
1.126     brouard  1615: 
1.137     brouard  1616: /*    for(j=0; j<= lg; j++) { */
                   1617: /*     if (j>=(p+1))(v[j-p-1] = t[j]); */
                   1618: /*   } */
                   1619: /* } */
1.126     brouard  1620: 
1.160     brouard  1621: #ifdef _WIN32
                   1622: char * strsep(char **pp, const char *delim)
                   1623: {
                   1624:   char *p, *q;
                   1625:          
                   1626:   if ((p = *pp) == NULL)
                   1627:     return 0;
                   1628:   if ((q = strpbrk (p, delim)) != NULL)
                   1629:   {
                   1630:     *pp = q + 1;
                   1631:     *q = '\0';
                   1632:   }
                   1633:   else
                   1634:     *pp = 0;
                   1635:   return p;
                   1636: }
                   1637: #endif
                   1638: 
1.126     brouard  1639: /********************** nrerror ********************/
                   1640: 
                   1641: void nrerror(char error_text[])
                   1642: {
                   1643:   fprintf(stderr,"ERREUR ...\n");
                   1644:   fprintf(stderr,"%s\n",error_text);
                   1645:   exit(EXIT_FAILURE);
                   1646: }
                   1647: /*********************** vector *******************/
                   1648: double *vector(int nl, int nh)
                   1649: {
                   1650:   double *v;
                   1651:   v=(double *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(double)));
                   1652:   if (!v) nrerror("allocation failure in vector");
                   1653:   return v-nl+NR_END;
                   1654: }
                   1655: 
                   1656: /************************ free vector ******************/
                   1657: void free_vector(double*v, int nl, int nh)
                   1658: {
                   1659:   free((FREE_ARG)(v+nl-NR_END));
                   1660: }
                   1661: 
                   1662: /************************ivector *******************************/
                   1663: int *ivector(long nl,long nh)
                   1664: {
                   1665:   int *v;
                   1666:   v=(int *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(int)));
                   1667:   if (!v) nrerror("allocation failure in ivector");
                   1668:   return v-nl+NR_END;
                   1669: }
                   1670: 
                   1671: /******************free ivector **************************/
                   1672: void free_ivector(int *v, long nl, long nh)
                   1673: {
                   1674:   free((FREE_ARG)(v+nl-NR_END));
                   1675: }
                   1676: 
                   1677: /************************lvector *******************************/
                   1678: long *lvector(long nl,long nh)
                   1679: {
                   1680:   long *v;
                   1681:   v=(long *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(long)));
                   1682:   if (!v) nrerror("allocation failure in ivector");
                   1683:   return v-nl+NR_END;
                   1684: }
                   1685: 
                   1686: /******************free lvector **************************/
                   1687: void free_lvector(long *v, long nl, long nh)
                   1688: {
                   1689:   free((FREE_ARG)(v+nl-NR_END));
                   1690: }
                   1691: 
                   1692: /******************* imatrix *******************************/
                   1693: int **imatrix(long nrl, long nrh, long ncl, long nch) 
                   1694:      /* allocate a int matrix with subscript range m[nrl..nrh][ncl..nch] */ 
                   1695: { 
                   1696:   long i, nrow=nrh-nrl+1,ncol=nch-ncl+1; 
                   1697:   int **m; 
                   1698:   
                   1699:   /* allocate pointers to rows */ 
                   1700:   m=(int **) malloc((size_t)((nrow+NR_END)*sizeof(int*))); 
                   1701:   if (!m) nrerror("allocation failure 1 in matrix()"); 
                   1702:   m += NR_END; 
                   1703:   m -= nrl; 
                   1704:   
                   1705:   
                   1706:   /* allocate rows and set pointers to them */ 
                   1707:   m[nrl]=(int *) malloc((size_t)((nrow*ncol+NR_END)*sizeof(int))); 
                   1708:   if (!m[nrl]) nrerror("allocation failure 2 in matrix()"); 
                   1709:   m[nrl] += NR_END; 
                   1710:   m[nrl] -= ncl; 
                   1711:   
                   1712:   for(i=nrl+1;i<=nrh;i++) m[i]=m[i-1]+ncol; 
                   1713:   
                   1714:   /* return pointer to array of pointers to rows */ 
                   1715:   return m; 
                   1716: } 
                   1717: 
                   1718: /****************** free_imatrix *************************/
                   1719: void free_imatrix(m,nrl,nrh,ncl,nch)
                   1720:       int **m;
                   1721:       long nch,ncl,nrh,nrl; 
                   1722:      /* free an int matrix allocated by imatrix() */ 
                   1723: { 
                   1724:   free((FREE_ARG) (m[nrl]+ncl-NR_END)); 
                   1725:   free((FREE_ARG) (m+nrl-NR_END)); 
                   1726: } 
                   1727: 
                   1728: /******************* matrix *******************************/
                   1729: double **matrix(long nrl, long nrh, long ncl, long nch)
                   1730: {
                   1731:   long i, nrow=nrh-nrl+1, ncol=nch-ncl+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:   return m;
1.145     brouard  1746:   /* print *(*(m+1)+70) or print m[1][70]; print m+1 or print &(m[1]) or &(m[1][0])
                   1747: m[i] = address of ith row of the table. &(m[i]) is its value which is another adress
                   1748: that of m[i][0]. In order to get the value p m[i][0] but it is unitialized.
1.126     brouard  1749:    */
                   1750: }
                   1751: 
                   1752: /*************************free matrix ************************/
                   1753: void free_matrix(double **m, long nrl, long nrh, long ncl, long nch)
                   1754: {
                   1755:   free((FREE_ARG)(m[nrl]+ncl-NR_END));
                   1756:   free((FREE_ARG)(m+nrl-NR_END));
                   1757: }
                   1758: 
                   1759: /******************* ma3x *******************************/
                   1760: double ***ma3x(long nrl, long nrh, long ncl, long nch, long nll, long nlh)
                   1761: {
                   1762:   long i, j, nrow=nrh-nrl+1, ncol=nch-ncl+1, nlay=nlh-nll+1;
                   1763:   double ***m;
                   1764: 
                   1765:   m=(double ***) malloc((size_t)((nrow+NR_END)*sizeof(double*)));
                   1766:   if (!m) nrerror("allocation failure 1 in matrix()");
                   1767:   m += NR_END;
                   1768:   m -= nrl;
                   1769: 
                   1770:   m[nrl]=(double **) malloc((size_t)((nrow*ncol+NR_END)*sizeof(double)));
                   1771:   if (!m[nrl]) nrerror("allocation failure 2 in matrix()");
                   1772:   m[nrl] += NR_END;
                   1773:   m[nrl] -= ncl;
                   1774: 
                   1775:   for (i=nrl+1; i<=nrh; i++) m[i]=m[i-1]+ncol;
                   1776: 
                   1777:   m[nrl][ncl]=(double *) malloc((size_t)((nrow*ncol*nlay+NR_END)*sizeof(double)));
                   1778:   if (!m[nrl][ncl]) nrerror("allocation failure 3 in matrix()");
                   1779:   m[nrl][ncl] += NR_END;
                   1780:   m[nrl][ncl] -= nll;
                   1781:   for (j=ncl+1; j<=nch; j++) 
                   1782:     m[nrl][j]=m[nrl][j-1]+nlay;
                   1783:   
                   1784:   for (i=nrl+1; i<=nrh; i++) {
                   1785:     m[i][ncl]=m[i-1l][ncl]+ncol*nlay;
                   1786:     for (j=ncl+1; j<=nch; j++) 
                   1787:       m[i][j]=m[i][j-1]+nlay;
                   1788:   }
                   1789:   return m; 
                   1790:   /*  gdb: p *(m+1) <=> p m[1] and p (m+1) <=> p (m+1) <=> p &(m[1])
                   1791:            &(m[i][j][k]) <=> *((*(m+i) + j)+k)
                   1792:   */
                   1793: }
                   1794: 
                   1795: /*************************free ma3x ************************/
                   1796: void free_ma3x(double ***m, long nrl, long nrh, long ncl, long nch,long nll, long nlh)
                   1797: {
                   1798:   free((FREE_ARG)(m[nrl][ncl]+ nll-NR_END));
                   1799:   free((FREE_ARG)(m[nrl]+ncl-NR_END));
                   1800:   free((FREE_ARG)(m+nrl-NR_END));
                   1801: }
                   1802: 
                   1803: /*************** function subdirf ***********/
                   1804: char *subdirf(char fileres[])
                   1805: {
                   1806:   /* Caution optionfilefiname is hidden */
                   1807:   strcpy(tmpout,optionfilefiname);
                   1808:   strcat(tmpout,"/"); /* Add to the right */
                   1809:   strcat(tmpout,fileres);
                   1810:   return tmpout;
                   1811: }
                   1812: 
                   1813: /*************** function subdirf2 ***********/
                   1814: char *subdirf2(char fileres[], char *preop)
                   1815: {
                   1816:   
                   1817:   /* Caution optionfilefiname is hidden */
                   1818:   strcpy(tmpout,optionfilefiname);
                   1819:   strcat(tmpout,"/");
                   1820:   strcat(tmpout,preop);
                   1821:   strcat(tmpout,fileres);
                   1822:   return tmpout;
                   1823: }
                   1824: 
                   1825: /*************** function subdirf3 ***********/
                   1826: char *subdirf3(char fileres[], char *preop, char *preop2)
                   1827: {
                   1828:   
                   1829:   /* Caution optionfilefiname is hidden */
                   1830:   strcpy(tmpout,optionfilefiname);
                   1831:   strcat(tmpout,"/");
                   1832:   strcat(tmpout,preop);
                   1833:   strcat(tmpout,preop2);
                   1834:   strcat(tmpout,fileres);
                   1835:   return tmpout;
                   1836: }
1.213     brouard  1837:  
                   1838: /*************** function subdirfext ***********/
                   1839: char *subdirfext(char fileres[], char *preop, char *postop)
                   1840: {
                   1841:   
                   1842:   strcpy(tmpout,preop);
                   1843:   strcat(tmpout,fileres);
                   1844:   strcat(tmpout,postop);
                   1845:   return tmpout;
                   1846: }
1.126     brouard  1847: 
1.213     brouard  1848: /*************** function subdirfext3 ***********/
                   1849: char *subdirfext3(char fileres[], char *preop, char *postop)
                   1850: {
                   1851:   
                   1852:   /* Caution optionfilefiname is hidden */
                   1853:   strcpy(tmpout,optionfilefiname);
                   1854:   strcat(tmpout,"/");
                   1855:   strcat(tmpout,preop);
                   1856:   strcat(tmpout,fileres);
                   1857:   strcat(tmpout,postop);
                   1858:   return tmpout;
                   1859: }
                   1860:  
1.162     brouard  1861: char *asc_diff_time(long time_sec, char ascdiff[])
                   1862: {
                   1863:   long sec_left, days, hours, minutes;
                   1864:   days = (time_sec) / (60*60*24);
                   1865:   sec_left = (time_sec) % (60*60*24);
                   1866:   hours = (sec_left) / (60*60) ;
                   1867:   sec_left = (sec_left) %(60*60);
                   1868:   minutes = (sec_left) /60;
                   1869:   sec_left = (sec_left) % (60);
                   1870:   sprintf(ascdiff,"%ld day(s) %ld hour(s) %ld minute(s) %ld second(s)",days, hours, minutes, sec_left);  
                   1871:   return ascdiff;
                   1872: }
                   1873: 
1.126     brouard  1874: /***************** f1dim *************************/
                   1875: extern int ncom; 
                   1876: extern double *pcom,*xicom;
                   1877: extern double (*nrfunc)(double []); 
                   1878:  
                   1879: double f1dim(double x) 
                   1880: { 
                   1881:   int j; 
                   1882:   double f;
                   1883:   double *xt; 
                   1884:  
                   1885:   xt=vector(1,ncom); 
                   1886:   for (j=1;j<=ncom;j++) xt[j]=pcom[j]+x*xicom[j]; 
                   1887:   f=(*nrfunc)(xt); 
                   1888:   free_vector(xt,1,ncom); 
                   1889:   return f; 
                   1890: } 
                   1891: 
                   1892: /*****************brent *************************/
                   1893: double brent(double ax, double bx, double cx, double (*f)(double), double tol,         double *xmin) 
1.187     brouard  1894: {
                   1895:   /* Given a function f, and given a bracketing triplet of abscissas ax, bx, cx (such that bx is
                   1896:    * between ax and cx, and f(bx) is less than both f(ax) and f(cx) ), this routine isolates
                   1897:    * the minimum to a fractional precision of about tol using Brent’s method. The abscissa of
                   1898:    * the minimum is returned as xmin, and the minimum function value is returned as brent , the
                   1899:    * returned function value. 
                   1900:   */
1.126     brouard  1901:   int iter; 
                   1902:   double a,b,d,etemp;
1.159     brouard  1903:   double fu=0,fv,fw,fx;
1.164     brouard  1904:   double ftemp=0.;
1.126     brouard  1905:   double p,q,r,tol1,tol2,u,v,w,x,xm; 
                   1906:   double e=0.0; 
                   1907:  
                   1908:   a=(ax < cx ? ax : cx); 
                   1909:   b=(ax > cx ? ax : cx); 
                   1910:   x=w=v=bx; 
                   1911:   fw=fv=fx=(*f)(x); 
                   1912:   for (iter=1;iter<=ITMAX;iter++) { 
                   1913:     xm=0.5*(a+b); 
                   1914:     tol2=2.0*(tol1=tol*fabs(x)+ZEPS); 
                   1915:     /*         if (2.0*fabs(fp-(*fret)) <= ftol*(fabs(fp)+fabs(*fret)))*/
                   1916:     printf(".");fflush(stdout);
                   1917:     fprintf(ficlog,".");fflush(ficlog);
1.162     brouard  1918: #ifdef DEBUGBRENT
1.126     brouard  1919:     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);
                   1920:     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);
                   1921:     /*         if ((fabs(x-xm) <= (tol2-0.5*(b-a)))||(2.0*fabs(fu-ftemp) <= ftol*1.e-2*(fabs(fu)+fabs(ftemp)))) { */
                   1922: #endif
                   1923:     if (fabs(x-xm) <= (tol2-0.5*(b-a))){ 
                   1924:       *xmin=x; 
                   1925:       return fx; 
                   1926:     } 
                   1927:     ftemp=fu;
                   1928:     if (fabs(e) > tol1) { 
                   1929:       r=(x-w)*(fx-fv); 
                   1930:       q=(x-v)*(fx-fw); 
                   1931:       p=(x-v)*q-(x-w)*r; 
                   1932:       q=2.0*(q-r); 
                   1933:       if (q > 0.0) p = -p; 
                   1934:       q=fabs(q); 
                   1935:       etemp=e; 
                   1936:       e=d; 
                   1937:       if (fabs(p) >= fabs(0.5*q*etemp) || p <= q*(a-x) || p >= q*(b-x)) 
1.224     brouard  1938:                                d=CGOLD*(e=(x >= xm ? a-x : b-x)); 
1.126     brouard  1939:       else { 
1.224     brouard  1940:                                d=p/q; 
                   1941:                                u=x+d; 
                   1942:                                if (u-a < tol2 || b-u < tol2) 
                   1943:                                        d=SIGN(tol1,xm-x); 
1.126     brouard  1944:       } 
                   1945:     } else { 
                   1946:       d=CGOLD*(e=(x >= xm ? a-x : b-x)); 
                   1947:     } 
                   1948:     u=(fabs(d) >= tol1 ? x+d : x+SIGN(tol1,d)); 
                   1949:     fu=(*f)(u); 
                   1950:     if (fu <= fx) { 
                   1951:       if (u >= x) a=x; else b=x; 
                   1952:       SHFT(v,w,x,u) 
1.183     brouard  1953:       SHFT(fv,fw,fx,fu) 
                   1954:     } else { 
                   1955:       if (u < x) a=u; else b=u; 
                   1956:       if (fu <= fw || w == x) { 
1.224     brouard  1957:                                v=w; 
                   1958:                                w=u; 
                   1959:                                fv=fw; 
                   1960:                                fw=fu; 
1.183     brouard  1961:       } else if (fu <= fv || v == x || v == w) { 
1.224     brouard  1962:                                v=u; 
                   1963:                                fv=fu; 
1.183     brouard  1964:       } 
                   1965:     } 
1.126     brouard  1966:   } 
                   1967:   nrerror("Too many iterations in brent"); 
                   1968:   *xmin=x; 
                   1969:   return fx; 
                   1970: } 
                   1971: 
                   1972: /****************** mnbrak ***********************/
                   1973: 
                   1974: void mnbrak(double *ax, double *bx, double *cx, double *fa, double *fb, double *fc, 
                   1975:            double (*func)(double)) 
1.183     brouard  1976: { /* Given a function func , and given distinct initial points ax and bx , this routine searches in
                   1977: the downhill direction (defined by the function as evaluated at the initial points) and returns
                   1978: new points ax , bx , cx that bracket a minimum of the function. Also returned are the function
                   1979: values at the three points, fa, fb , and fc such that fa > fb and fb < fc.
                   1980:    */
1.126     brouard  1981:   double ulim,u,r,q, dum;
                   1982:   double fu; 
1.187     brouard  1983: 
                   1984:   double scale=10.;
                   1985:   int iterscale=0;
                   1986: 
                   1987:   *fa=(*func)(*ax); /*  xta[j]=pcom[j]+(*ax)*xicom[j]; fa=f(xta[j])*/
                   1988:   *fb=(*func)(*bx); /*  xtb[j]=pcom[j]+(*bx)*xicom[j]; fb=f(xtb[j]) */
                   1989: 
                   1990: 
                   1991:   /* while(*fb != *fb){ /\* *ax should be ok, reducing distance to *ax *\/ */
                   1992:   /*   printf("Warning mnbrak *fb = %lf, *bx=%lf *ax=%lf *fa==%lf iter=%d\n",*fb, *bx, *ax, *fa, iterscale++); */
                   1993:   /*   *bx = *ax - (*ax - *bx)/scale; */
                   1994:   /*   *fb=(*func)(*bx);  /\*  xtb[j]=pcom[j]+(*bx)*xicom[j]; fb=f(xtb[j]) *\/ */
                   1995:   /* } */
                   1996: 
1.126     brouard  1997:   if (*fb > *fa) { 
                   1998:     SHFT(dum,*ax,*bx,dum) 
1.183     brouard  1999:     SHFT(dum,*fb,*fa,dum) 
                   2000:   } 
1.126     brouard  2001:   *cx=(*bx)+GOLD*(*bx-*ax); 
                   2002:   *fc=(*func)(*cx); 
1.183     brouard  2003: #ifdef DEBUG
1.224     brouard  2004:   printf("mnbrak0 a=%lf *fa=%lf, b=%lf *fb=%lf, c=%lf *fc=%lf\n",*ax,*fa,*bx,*fb,*cx, *fc);
                   2005:   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  2006: #endif
1.224     brouard  2007:   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  2008:     r=(*bx-*ax)*(*fb-*fc); 
1.224     brouard  2009:     q=(*bx-*cx)*(*fb-*fa); /* What if fa=inf */
1.126     brouard  2010:     u=(*bx)-((*bx-*cx)*q-(*bx-*ax)*r)/ 
1.183     brouard  2011:       (2.0*SIGN(FMAX(fabs(q-r),TINY),q-r)); /* Minimum abscissa of a parabolic estimated from (a,fa), (b,fb) and (c,fc). */
                   2012:     ulim=(*bx)+GLIMIT*(*cx-*bx); /* Maximum abscissa where function should be evaluated */
                   2013:     if ((*bx-u)*(u-*cx) > 0.0) { /* if u_p is between b and c */
1.126     brouard  2014:       fu=(*func)(u); 
1.163     brouard  2015: #ifdef DEBUG
                   2016:       /* f(x)=A(x-u)**2+f(u) */
                   2017:       double A, fparabu; 
                   2018:       A= (*fb - *fa)/(*bx-*ax)/(*bx+*ax-2*u);
                   2019:       fparabu= *fa - A*(*ax-u)*(*ax-u);
1.224     brouard  2020:       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);
                   2021:       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  2022:       /* And thus,it can be that fu > *fc even if fparabu < *fc */
                   2023:       /* mnbrak (*ax=7.666299858533, *fa=299039.693133272231), (*bx=8.595447774979, *fb=298976.598289369489),
                   2024:         (*cx=10.098840694817, *fc=298946.631474258087),  (*u=9.852501168332, fu=298948.773013752128, fparabu=298945.434711494134) */
                   2025:       /* In that case, there is no bracket in the output! Routine is wrong with many consequences.*/
1.163     brouard  2026: #endif 
1.184     brouard  2027: #ifdef MNBRAKORIGINAL
1.183     brouard  2028: #else
1.191     brouard  2029: /*       if (fu > *fc) { */
                   2030: /* #ifdef DEBUG */
                   2031: /*       printf("mnbrak4  fu > fc \n"); */
                   2032: /*       fprintf(ficlog, "mnbrak4 fu > fc\n"); */
                   2033: /* #endif */
                   2034: /*     /\* 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 *\\/  *\/ */
                   2035: /*     /\* SHFT(*fa,*fc,fu,*fc) /\\* (b, u, c) is a bracket while test fb > fc will be fu > fc  will exit *\\/ *\/ */
                   2036: /*     dum=u; /\* Shifting c and u *\/ */
                   2037: /*     u = *cx; */
                   2038: /*     *cx = dum; */
                   2039: /*     dum = fu; */
                   2040: /*     fu = *fc; */
                   2041: /*     *fc =dum; */
                   2042: /*       } else { /\* end *\/ */
                   2043: /* #ifdef DEBUG */
                   2044: /*       printf("mnbrak3  fu < fc \n"); */
                   2045: /*       fprintf(ficlog, "mnbrak3 fu < fc\n"); */
                   2046: /* #endif */
                   2047: /*     dum=u; /\* Shifting c and u *\/ */
                   2048: /*     u = *cx; */
                   2049: /*     *cx = dum; */
                   2050: /*     dum = fu; */
                   2051: /*     fu = *fc; */
                   2052: /*     *fc =dum; */
                   2053: /*       } */
1.224     brouard  2054: #ifdef DEBUGMNBRAK
                   2055:                 double A, fparabu; 
                   2056:      A= (*fb - *fa)/(*bx-*ax)/(*bx+*ax-2*u);
                   2057:      fparabu= *fa - A*(*ax-u)*(*ax-u);
                   2058:      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);
                   2059:      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  2060: #endif
1.191     brouard  2061:       dum=u; /* Shifting c and u */
                   2062:       u = *cx;
                   2063:       *cx = dum;
                   2064:       dum = fu;
                   2065:       fu = *fc;
                   2066:       *fc =dum;
1.183     brouard  2067: #endif
1.162     brouard  2068:     } else if ((*cx-u)*(u-ulim) > 0.0) { /* u is after c but before ulim */
1.183     brouard  2069: #ifdef DEBUG
1.224     brouard  2070:       printf("\nmnbrak2  u=%lf after c=%lf but before ulim\n",u,*cx);
                   2071:       fprintf(ficlog,"\nmnbrak2  u=%lf after c=%lf but before ulim\n",u,*cx);
1.183     brouard  2072: #endif
1.126     brouard  2073:       fu=(*func)(u); 
                   2074:       if (fu < *fc) { 
1.183     brouard  2075: #ifdef DEBUG
1.224     brouard  2076:                                printf("\nmnbrak2  u=%lf after c=%lf but before ulim=%lf AND fu=%lf < %lf=fc\n",u,*cx,ulim,fu, *fc);
                   2077:                          fprintf(ficlog,"\nmnbrak2  u=%lf after c=%lf but before ulim=%lf AND fu=%lf < %lf=fc\n",u,*cx,ulim,fu, *fc);
                   2078: #endif
                   2079:                          SHFT(*bx,*cx,u,*cx+GOLD*(*cx-*bx)) 
                   2080:                                SHFT(*fb,*fc,fu,(*func)(u)) 
                   2081: #ifdef DEBUG
                   2082:                                        printf("\nmnbrak2 shift GOLD c=%lf",*cx+GOLD*(*cx-*bx));
1.183     brouard  2083: #endif
                   2084:       } 
1.162     brouard  2085:     } else if ((u-ulim)*(ulim-*cx) >= 0.0) { /* u outside ulim (verifying that ulim is beyond c) */
1.183     brouard  2086: #ifdef DEBUG
1.224     brouard  2087:       printf("\nmnbrak2  u=%lf outside ulim=%lf (verifying that ulim is beyond c=%lf)\n",u,ulim,*cx);
                   2088:       fprintf(ficlog,"\nmnbrak2  u=%lf outside ulim=%lf (verifying that ulim is beyond c=%lf)\n",u,ulim,*cx);
1.183     brouard  2089: #endif
1.126     brouard  2090:       u=ulim; 
                   2091:       fu=(*func)(u); 
1.183     brouard  2092:     } else { /* u could be left to b (if r > q parabola has a maximum) */
                   2093: #ifdef DEBUG
1.224     brouard  2094:       printf("\nmnbrak2  u=%lf could be left to b=%lf (if r=%lf > q=%lf parabola has a maximum)\n",u,*bx,r,q);
                   2095:       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  2096: #endif
1.126     brouard  2097:       u=(*cx)+GOLD*(*cx-*bx); 
                   2098:       fu=(*func)(u); 
1.224     brouard  2099: #ifdef DEBUG
                   2100:       printf("\nmnbrak2 new u=%lf fu=%lf shifted gold left from c=%lf and b=%lf \n",u,fu,*cx,*bx);
                   2101:       fprintf(ficlog,"\nmnbrak2 new u=%lf fu=%lf shifted gold left from c=%lf and b=%lf \n",u,fu,*cx,*bx);
                   2102: #endif
1.183     brouard  2103:     } /* end tests */
1.126     brouard  2104:     SHFT(*ax,*bx,*cx,u) 
1.183     brouard  2105:     SHFT(*fa,*fb,*fc,fu) 
                   2106: #ifdef DEBUG
1.224     brouard  2107:       printf("\nmnbrak2 shift (*ax=%.12f, *fa=%.12lf), (*bx=%.12f, *fb=%.12lf), (*cx=%.12f, *fc=%.12lf)\n",*ax,*fa,*bx,*fb,*cx,*fc);
                   2108:       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  2109: #endif
                   2110:   } /* 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  2111: } 
                   2112: 
                   2113: /*************** linmin ************************/
1.162     brouard  2114: /* Given an n -dimensional point p[1..n] and an n -dimensional direction xi[1..n] , moves and
                   2115: resets p to where the function func(p) takes on a minimum along the direction xi from p ,
                   2116: and replaces xi by the actual vector displacement that p was moved. Also returns as fret
                   2117: the value of func at the returned location p . This is actually all accomplished by calling the
                   2118: routines mnbrak and brent .*/
1.126     brouard  2119: int ncom; 
                   2120: double *pcom,*xicom;
                   2121: double (*nrfunc)(double []); 
                   2122:  
1.224     brouard  2123: #ifdef LINMINORIGINAL
1.126     brouard  2124: void linmin(double p[], double xi[], int n, double *fret,double (*func)(double [])) 
1.224     brouard  2125: #else
                   2126: void linmin(double p[], double xi[], int n, double *fret,double (*func)(double []), int *flat) 
                   2127: #endif
1.126     brouard  2128: { 
                   2129:   double brent(double ax, double bx, double cx, 
                   2130:               double (*f)(double), double tol, double *xmin); 
                   2131:   double f1dim(double x); 
                   2132:   void mnbrak(double *ax, double *bx, double *cx, double *fa, double *fb, 
                   2133:              double *fc, double (*func)(double)); 
                   2134:   int j; 
                   2135:   double xx,xmin,bx,ax; 
                   2136:   double fx,fb,fa;
1.187     brouard  2137: 
1.203     brouard  2138: #ifdef LINMINORIGINAL
                   2139: #else
                   2140:   double scale=10., axs, xxs; /* Scale added for infinity */
                   2141: #endif
                   2142:   
1.126     brouard  2143:   ncom=n; 
                   2144:   pcom=vector(1,n); 
                   2145:   xicom=vector(1,n); 
                   2146:   nrfunc=func; 
                   2147:   for (j=1;j<=n;j++) { 
                   2148:     pcom[j]=p[j]; 
1.202     brouard  2149:     xicom[j]=xi[j]; /* Former scale xi[j] of currrent direction i */
1.126     brouard  2150:   } 
1.187     brouard  2151: 
1.203     brouard  2152: #ifdef LINMINORIGINAL
                   2153:   xx=1.;
                   2154: #else
                   2155:   axs=0.0;
                   2156:   xxs=1.;
                   2157:   do{
                   2158:     xx= xxs;
                   2159: #endif
1.187     brouard  2160:     ax=0.;
                   2161:     mnbrak(&ax,&xx,&bx,&fa,&fx,&fb,f1dim);  /* Outputs: xtx[j]=pcom[j]+(*xx)*xicom[j]; fx=f(xtx[j]) */
                   2162:     /* brackets with inputs ax=0 and xx=1, but points, pcom=p, and directions values, xicom=xi, are sent via f1dim(x) */
                   2163:     /* 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))   */
                   2164:     /* Outputs: fa=f(p(j)) and fx=f(p(j) + xxs * xi(j) ) and f(bx)= f(p(j)+ bx* xi(j)) */
                   2165:     /* Given input ax=axs and xx=xxs, xx might be too far from ax to get a finite f(xx) */
                   2166:     /* Searches on line, outputs (ax, xx, bx) such that fx < min(fa and fb) */
                   2167:     /* 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  2168: #ifdef LINMINORIGINAL
                   2169: #else
                   2170:     if (fx != fx){
1.224     brouard  2171:                        xxs=xxs/scale; /* Trying a smaller xx, closer to initial ax=0 */
                   2172:                        printf("|");
                   2173:                        fprintf(ficlog,"|");
1.203     brouard  2174: #ifdef DEBUGLINMIN
1.224     brouard  2175:                        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  2176: #endif
                   2177:     }
1.224     brouard  2178:   }while(fx != fx && xxs > 1.e-5);
1.203     brouard  2179: #endif
                   2180:   
1.191     brouard  2181: #ifdef DEBUGLINMIN
                   2182:   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  2183:   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  2184: #endif
1.224     brouard  2185: #ifdef LINMINORIGINAL
                   2186: #else
                   2187:        if(fb == fx){ /* Flat function in the direction */
                   2188:                xmin=xx;
                   2189:     *flat=1;
                   2190:        }else{
                   2191:     *flat=0;
                   2192: #endif
                   2193:                /*Flat mnbrak2 shift (*ax=0.000000000000, *fa=51626.272983130431), (*bx=-1.618034000000, *fb=51590.149499362531), (*cx=-4.236068025156, *fc=51590.149499362531) */
1.187     brouard  2194:   *fret=brent(ax,xx,bx,f1dim,TOL,&xmin); /* Giving a bracketting triplet (ax, xx, bx), find a minimum, xmin, according to f1dim, *fret(xmin),*/
                   2195:   /* fa = f(p[j] + ax * xi[j]), fx = f(p[j] + xx * xi[j]), fb = f(p[j] + bx * xi[j]) */
                   2196:   /* fmin = f(p[j] + xmin * xi[j]) */
                   2197:   /* P+lambda n in that direction (lambdamin), with TOL between abscisses */
                   2198:   /* f1dim(xmin): for (j=1;j<=ncom;j++) xt[j]=pcom[j]+xmin*xicom[j]; */
1.126     brouard  2199: #ifdef DEBUG
1.224     brouard  2200:   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);
                   2201:   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);
                   2202: #endif
                   2203: #ifdef LINMINORIGINAL
                   2204: #else
                   2205:                        }
1.126     brouard  2206: #endif
1.191     brouard  2207: #ifdef DEBUGLINMIN
                   2208:   printf("linmin end ");
1.202     brouard  2209:   fprintf(ficlog,"linmin end ");
1.191     brouard  2210: #endif
1.126     brouard  2211:   for (j=1;j<=n;j++) { 
1.203     brouard  2212: #ifdef LINMINORIGINAL
                   2213:     xi[j] *= xmin; 
                   2214: #else
                   2215: #ifdef DEBUGLINMIN
                   2216:     if(xxs <1.0)
                   2217:       printf(" before xi[%d]=%12.8f", j,xi[j]);
                   2218: #endif
                   2219:     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) */
                   2220: #ifdef DEBUGLINMIN
                   2221:     if(xxs <1.0)
                   2222:       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 );
                   2223: #endif
                   2224: #endif
1.187     brouard  2225:     p[j] += xi[j]; /* Parameters values are updated accordingly */
1.126     brouard  2226:   } 
1.191     brouard  2227: #ifdef DEBUGLINMIN
1.203     brouard  2228:   printf("\n");
1.191     brouard  2229:   printf("Comparing last *frec(xmin=%12.8f)=%12.8f from Brent and frec(0.)=%12.8f \n", xmin, *fret, (*func)(p));
1.202     brouard  2230:   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  2231:   for (j=1;j<=n;j++) { 
1.202     brouard  2232:     printf(" xi[%d]= %14.10f p[%d]= %12.7f",j,xi[j],j,p[j]);
                   2233:     fprintf(ficlog," xi[%d]= %14.10f p[%d]= %12.7f",j,xi[j],j,p[j]);
                   2234:     if(j % ncovmodel == 0){
1.191     brouard  2235:       printf("\n");
1.202     brouard  2236:       fprintf(ficlog,"\n");
                   2237:     }
1.191     brouard  2238:   }
1.203     brouard  2239: #else
1.191     brouard  2240: #endif
1.126     brouard  2241:   free_vector(xicom,1,n); 
                   2242:   free_vector(pcom,1,n); 
                   2243: } 
                   2244: 
                   2245: 
                   2246: /*************** powell ************************/
1.162     brouard  2247: /*
                   2248: Minimization of a function func of n variables. Input consists of an initial starting point
                   2249: p[1..n] ; an initial matrix xi[1..n][1..n] , whose columns contain the initial set of di-
                   2250: rections (usually the n unit vectors); and ftol , the fractional tolerance in the function value
                   2251: such that failure to decrease by more than this amount on one iteration signals doneness. On
                   2252: output, p is set to the best point found, xi is the then-current direction set, fret is the returned
                   2253: function value at p , and iter is the number of iterations taken. The routine linmin is used.
                   2254:  */
1.224     brouard  2255: #ifdef LINMINORIGINAL
                   2256: #else
                   2257:        int *flatdir; /* Function is vanishing in that direction */
1.225     brouard  2258:        int flat=0, flatd=0; /* Function is vanishing in that direction */
1.224     brouard  2259: #endif
1.126     brouard  2260: void powell(double p[], double **xi, int n, double ftol, int *iter, double *fret, 
                   2261:            double (*func)(double [])) 
                   2262: { 
1.224     brouard  2263: #ifdef LINMINORIGINAL
                   2264:  void linmin(double p[], double xi[], int n, double *fret, 
1.126     brouard  2265:              double (*func)(double [])); 
1.224     brouard  2266: #else 
1.241     brouard  2267:  void linmin(double p[], double xi[], int n, double *fret,
                   2268:             double (*func)(double []),int *flat); 
1.224     brouard  2269: #endif
1.239     brouard  2270:  int i,ibig,j,jk,k; 
1.126     brouard  2271:   double del,t,*pt,*ptt,*xit;
1.181     brouard  2272:   double directest;
1.126     brouard  2273:   double fp,fptt;
                   2274:   double *xits;
                   2275:   int niterf, itmp;
1.224     brouard  2276: #ifdef LINMINORIGINAL
                   2277: #else
                   2278: 
                   2279:   flatdir=ivector(1,n); 
                   2280:   for (j=1;j<=n;j++) flatdir[j]=0; 
                   2281: #endif
1.126     brouard  2282: 
                   2283:   pt=vector(1,n); 
                   2284:   ptt=vector(1,n); 
                   2285:   xit=vector(1,n); 
                   2286:   xits=vector(1,n); 
                   2287:   *fret=(*func)(p); 
                   2288:   for (j=1;j<=n;j++) pt[j]=p[j]; 
1.202     brouard  2289:   rcurr_time = time(NULL);  
1.126     brouard  2290:   for (*iter=1;;++(*iter)) { 
1.187     brouard  2291:     fp=(*fret); /* From former iteration or initial value */
1.126     brouard  2292:     ibig=0; 
                   2293:     del=0.0; 
1.157     brouard  2294:     rlast_time=rcurr_time;
                   2295:     /* (void) gettimeofday(&curr_time,&tzp); */
                   2296:     rcurr_time = time(NULL);  
                   2297:     curr_time = *localtime(&rcurr_time);
                   2298:     printf("\nPowell iter=%d -2*LL=%.12f %ld sec. %ld sec.",*iter,*fret, rcurr_time-rlast_time, rcurr_time-rstart_time);fflush(stdout);
                   2299:     fprintf(ficlog,"\nPowell iter=%d -2*LL=%.12f %ld sec. %ld sec.",*iter,*fret,rcurr_time-rlast_time, rcurr_time-rstart_time); fflush(ficlog);
                   2300: /*     fprintf(ficrespow,"%d %.12f %ld",*iter,*fret,curr_time.tm_sec-start_time.tm_sec); */
1.192     brouard  2301:     for (i=1;i<=n;i++) {
1.126     brouard  2302:       fprintf(ficrespow," %.12lf", p[i]);
                   2303:     }
1.239     brouard  2304:     fprintf(ficrespow,"\n");fflush(ficrespow);
                   2305:     printf("\n#model=  1      +     age ");
                   2306:     fprintf(ficlog,"\n#model=  1      +     age ");
                   2307:     if(nagesqr==1){
1.241     brouard  2308:        printf("  + age*age  ");
                   2309:        fprintf(ficlog,"  + age*age  ");
1.239     brouard  2310:     }
                   2311:     for(j=1;j <=ncovmodel-2;j++){
                   2312:       if(Typevar[j]==0) {
                   2313:        printf("  +      V%d  ",Tvar[j]);
                   2314:        fprintf(ficlog,"  +      V%d  ",Tvar[j]);
                   2315:       }else if(Typevar[j]==1) {
                   2316:        printf("  +    V%d*age ",Tvar[j]);
                   2317:        fprintf(ficlog,"  +    V%d*age ",Tvar[j]);
                   2318:       }else if(Typevar[j]==2) {
                   2319:        printf("  +    V%d*V%d ",Tvard[Tposprod[j]][1],Tvard[Tposprod[j]][2]);
                   2320:        fprintf(ficlog,"  +    V%d*V%d ",Tvard[Tposprod[j]][1],Tvard[Tposprod[j]][2]);
                   2321:       }
                   2322:     }
1.126     brouard  2323:     printf("\n");
1.239     brouard  2324: /*     printf("12   47.0114589    0.0154322   33.2424412    0.3279905    2.3731903  */
                   2325: /* 13  -21.5392400    0.1118147    1.2680506    1.2973408   -1.0663662  */
1.126     brouard  2326:     fprintf(ficlog,"\n");
1.239     brouard  2327:     for(i=1,jk=1; i <=nlstate; i++){
                   2328:       for(k=1; k <=(nlstate+ndeath); k++){
                   2329:        if (k != i) {
                   2330:          printf("%d%d ",i,k);
                   2331:          fprintf(ficlog,"%d%d ",i,k);
                   2332:          for(j=1; j <=ncovmodel; j++){
                   2333:            printf("%12.7f ",p[jk]);
                   2334:            fprintf(ficlog,"%12.7f ",p[jk]);
                   2335:            jk++; 
                   2336:          }
                   2337:          printf("\n");
                   2338:          fprintf(ficlog,"\n");
                   2339:        }
                   2340:       }
                   2341:     }
1.241     brouard  2342:     if(*iter <=3 && *iter >1){
1.157     brouard  2343:       tml = *localtime(&rcurr_time);
                   2344:       strcpy(strcurr,asctime(&tml));
                   2345:       rforecast_time=rcurr_time; 
1.126     brouard  2346:       itmp = strlen(strcurr);
                   2347:       if(strcurr[itmp-1]=='\n')  /* Windows outputs with a new line */
1.241     brouard  2348:        strcurr[itmp-1]='\0';
1.162     brouard  2349:       printf("\nConsidering the time needed for the last iteration #%d: %ld seconds,\n",*iter,rcurr_time-rlast_time);
1.157     brouard  2350:       fprintf(ficlog,"\nConsidering the time needed for this last iteration #%d: %ld seconds,\n",*iter,rcurr_time-rlast_time);
1.126     brouard  2351:       for(niterf=10;niterf<=30;niterf+=10){
1.241     brouard  2352:        rforecast_time=rcurr_time+(niterf-*iter)*(rcurr_time-rlast_time);
                   2353:        forecast_time = *localtime(&rforecast_time);
                   2354:        strcpy(strfor,asctime(&forecast_time));
                   2355:        itmp = strlen(strfor);
                   2356:        if(strfor[itmp-1]=='\n')
                   2357:          strfor[itmp-1]='\0';
                   2358:        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);
                   2359:        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  2360:       }
                   2361:     }
1.187     brouard  2362:     for (i=1;i<=n;i++) { /* For each direction i */
                   2363:       for (j=1;j<=n;j++) xit[j]=xi[j][i]; /* Directions stored from previous iteration with previous scales */
1.126     brouard  2364:       fptt=(*fret); 
                   2365: #ifdef DEBUG
1.203     brouard  2366:       printf("fret=%lf, %lf, %lf \n", *fret, *fret, *fret);
                   2367:       fprintf(ficlog, "fret=%lf, %lf, %lf \n", *fret, *fret, *fret);
1.126     brouard  2368: #endif
1.203     brouard  2369:       printf("%d",i);fflush(stdout); /* print direction (parameter) i */
1.126     brouard  2370:       fprintf(ficlog,"%d",i);fflush(ficlog);
1.224     brouard  2371: #ifdef LINMINORIGINAL
1.188     brouard  2372:       linmin(p,xit,n,fret,func); /* Point p[n]. xit[n] has been loaded for direction i as input.*/
1.224     brouard  2373: #else
                   2374:       linmin(p,xit,n,fret,func,&flat); /* Point p[n]. xit[n] has been loaded for direction i as input.*/
                   2375:                        flatdir[i]=flat; /* Function is vanishing in that direction i */
                   2376: #endif
                   2377:                        /* Outputs are fret(new point p) p is updated and xit rescaled */
1.188     brouard  2378:       if (fabs(fptt-(*fret)) > del) { /* We are keeping the max gain on each of the n directions */
1.224     brouard  2379:                                /* because that direction will be replaced unless the gain del is small */
                   2380:                                /* in comparison with the 'probable' gain, mu^2, with the last average direction. */
                   2381:                                /* Unless the n directions are conjugate some gain in the determinant may be obtained */
                   2382:                                /* with the new direction. */
                   2383:                                del=fabs(fptt-(*fret)); 
                   2384:                                ibig=i; 
1.126     brouard  2385:       } 
                   2386: #ifdef DEBUG
                   2387:       printf("%d %.12e",i,(*fret));
                   2388:       fprintf(ficlog,"%d %.12e",i,(*fret));
                   2389:       for (j=1;j<=n;j++) {
1.224     brouard  2390:                                xits[j]=FMAX(fabs(p[j]-pt[j]),1.e-5);
                   2391:                                printf(" x(%d)=%.12e",j,xit[j]);
                   2392:                                fprintf(ficlog," x(%d)=%.12e",j,xit[j]);
1.126     brouard  2393:       }
                   2394:       for(j=1;j<=n;j++) {
1.225     brouard  2395:                                printf(" p(%d)=%.12e",j,p[j]);
                   2396:                                fprintf(ficlog," p(%d)=%.12e",j,p[j]);
1.126     brouard  2397:       }
                   2398:       printf("\n");
                   2399:       fprintf(ficlog,"\n");
                   2400: #endif
1.187     brouard  2401:     } /* end loop on each direction i */
                   2402:     /* Convergence test will use last linmin estimation (fret) and compare former iteration (fp) */ 
1.188     brouard  2403:     /* But p and xit have been updated at the end of linmin, *fret corresponds to new p, xit  */
1.187     brouard  2404:     /* New value of last point Pn is not computed, P(n-1) */
1.224     brouard  2405:       for(j=1;j<=n;j++) {
1.225     brouard  2406:                                if(flatdir[j] >0){
                   2407:                                        printf(" p(%d)=%lf flat=%d ",j,p[j],flatdir[j]);
                   2408:                                        fprintf(ficlog," p(%d)=%lf flat=%d ",j,p[j],flatdir[j]);
                   2409:                                }
                   2410:                                /* printf("\n"); */
                   2411:                                /* fprintf(ficlog,"\n"); */
                   2412:                        }
1.243     brouard  2413:     /* if (2.0*fabs(fp-(*fret)) <= ftol*(fabs(fp)+fabs(*fret))) { /\* Did we reach enough precision? *\/ */
                   2414:     if (2.0*fabs(fp-(*fret)) <= ftol) { /* Did we reach enough precision? */
1.188     brouard  2415:       /* We could compare with a chi^2. chisquare(0.95,ddl=1)=3.84 */
                   2416:       /* By adding age*age in a model, the new -2LL should be lower and the difference follows a */
                   2417:       /* a chisquare statistics with 1 degree. To be significant at the 95% level, it should have */
                   2418:       /* decreased of more than 3.84  */
                   2419:       /* By adding age*age and V1*age the gain (-2LL) should be more than 5.99 (ddl=2) */
                   2420:       /* By using V1+V2+V3, the gain should be  7.82, compared with basic 1+age. */
                   2421:       /* By adding 10 parameters more the gain should be 18.31 */
1.224     brouard  2422:                        
1.188     brouard  2423:       /* Starting the program with initial values given by a former maximization will simply change */
                   2424:       /* the scales of the directions and the directions, because the are reset to canonical directions */
                   2425:       /* Thus the first calls to linmin will give new points and better maximizations until fp-(*fret) is */
                   2426:       /* under the tolerance value. If the tolerance is very small 1.e-9, it could last long.  */
1.126     brouard  2427: #ifdef DEBUG
                   2428:       int k[2],l;
                   2429:       k[0]=1;
                   2430:       k[1]=-1;
                   2431:       printf("Max: %.12e",(*func)(p));
                   2432:       fprintf(ficlog,"Max: %.12e",(*func)(p));
                   2433:       for (j=1;j<=n;j++) {
                   2434:        printf(" %.12e",p[j]);
                   2435:        fprintf(ficlog," %.12e",p[j]);
                   2436:       }
                   2437:       printf("\n");
                   2438:       fprintf(ficlog,"\n");
                   2439:       for(l=0;l<=1;l++) {
                   2440:        for (j=1;j<=n;j++) {
                   2441:          ptt[j]=p[j]+(p[j]-pt[j])*k[l];
                   2442:          printf("l=%d j=%d ptt=%.12e, xits=%.12e, p=%.12e, xit=%.12e", l,j,ptt[j],xits[j],p[j],xit[j]);
                   2443:          fprintf(ficlog,"l=%d j=%d ptt=%.12e, xits=%.12e, p=%.12e, xit=%.12e", l,j,ptt[j],xits[j],p[j],xit[j]);
                   2444:        }
                   2445:        printf("func(ptt)=%.12e, deriv=%.12e\n",(*func)(ptt),(ptt[j]-p[j])/((*func)(ptt)-(*func)(p)));
                   2446:        fprintf(ficlog,"func(ptt)=%.12e, deriv=%.12e\n",(*func)(ptt),(ptt[j]-p[j])/((*func)(ptt)-(*func)(p)));
                   2447:       }
                   2448: #endif
                   2449: 
1.224     brouard  2450: #ifdef LINMINORIGINAL
                   2451: #else
                   2452:       free_ivector(flatdir,1,n); 
                   2453: #endif
1.126     brouard  2454:       free_vector(xit,1,n); 
                   2455:       free_vector(xits,1,n); 
                   2456:       free_vector(ptt,1,n); 
                   2457:       free_vector(pt,1,n); 
                   2458:       return; 
1.192     brouard  2459:     } /* enough precision */ 
1.240     brouard  2460:     if (*iter == ITMAX*n) nrerror("powell exceeding maximum iterations."); 
1.181     brouard  2461:     for (j=1;j<=n;j++) { /* Computes the extrapolated point P_0 + 2 (P_n-P_0) */
1.126     brouard  2462:       ptt[j]=2.0*p[j]-pt[j]; 
                   2463:       xit[j]=p[j]-pt[j]; 
                   2464:       pt[j]=p[j]; 
                   2465:     } 
1.181     brouard  2466:     fptt=(*func)(ptt); /* f_3 */
1.224     brouard  2467: #ifdef NODIRECTIONCHANGEDUNTILNITER  /* No change in drections until some iterations are done */
                   2468:                if (*iter <=4) {
1.225     brouard  2469: #else
                   2470: #endif
1.224     brouard  2471: #ifdef POWELLNOF3INFF1TEST    /* skips test F3 <F1 */
1.192     brouard  2472: #else
1.161     brouard  2473:     if (fptt < fp) { /* If extrapolated point is better, decide if we keep that new direction or not */
1.192     brouard  2474: #endif
1.162     brouard  2475:       /* (x1 f1=fp), (x2 f2=*fret), (x3 f3=fptt), (xm fm) */
1.161     brouard  2476:       /* From x1 (P0) distance of x2 is at h and x3 is 2h */
1.162     brouard  2477:       /* Let f"(x2) be the 2nd derivative equal everywhere.  */
                   2478:       /* Then the parabolic through (x1,f1), (x2,f2) and (x3,f3) */
                   2479:       /* will reach at f3 = fm + h^2/2 f"m  ; f" = (f1 -2f2 +f3 ) / h**2 */
1.224     brouard  2480:       /* Conditional for using this new direction is that mu^2 = (f1-2f2+f3)^2 /2 < del or directest <0 */
                   2481:       /* also  lamda^2=(f1-f2)^2/mu² is a parasite solution of powell */
                   2482:       /* For powell, inclusion of this average direction is only if t(del)<0 or del inbetween mu^2 and lambda^2 */
1.161     brouard  2483:       /* t=2.0*(fp-2.0*(*fret)+fptt)*SQR(fp-(*fret)-del)-del*SQR(fp-fptt); */
1.224     brouard  2484:       /*  Even if f3 <f1, directest can be negative and t >0 */
                   2485:       /* mu² and del² are equal when f3=f1 */
                   2486:                        /* f3 < f1 : mu² < del <= lambda^2 both test are equivalent */
                   2487:                        /* f3 < f1 : mu² < lambda^2 < del then directtest is negative and powell t is positive */
                   2488:                        /* f3 > f1 : lambda² < mu^2 < del then t is negative and directest >0  */
                   2489:                        /* f3 > f1 : lambda² < del < mu^2 then t is positive and directest >0  */
1.183     brouard  2490: #ifdef NRCORIGINAL
                   2491:       t=2.0*(fp-2.0*(*fret)+fptt)*SQR(fp-(*fret)-del)- del*SQR(fp-fptt); /* Original Numerical Recipes in C*/
                   2492: #else
                   2493:       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  2494:       t= t- del*SQR(fp-fptt);
1.183     brouard  2495: #endif
1.202     brouard  2496:       directest = fp-2.0*(*fret)+fptt - 2.0 * del; /* If delta was big enough we change it for a new direction */
1.161     brouard  2497: #ifdef DEBUG
1.181     brouard  2498:       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);
                   2499:       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  2500:       printf("t3= %.12lf, t4= %.12lf, t3*= %.12lf, t4*= %.12lf\n",SQR(fp-(*fret)-del),SQR(fp-fptt),
                   2501:             (fp-(*fret)-del)*(fp-(*fret)-del),(fp-fptt)*(fp-fptt));
                   2502:       fprintf(ficlog,"t3= %.12lf, t4= %.12lf, t3*= %.12lf, t4*= %.12lf\n",SQR(fp-(*fret)-del),SQR(fp-fptt),
                   2503:             (fp-(*fret)-del)*(fp-(*fret)-del),(fp-fptt)*(fp-fptt));
                   2504:       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);
                   2505:       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);
                   2506: #endif
1.183     brouard  2507: #ifdef POWELLORIGINAL
                   2508:       if (t < 0.0) { /* Then we use it for new direction */
                   2509: #else
1.182     brouard  2510:       if (directest*t < 0.0) { /* Contradiction between both tests */
1.224     brouard  2511:                                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  2512:         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  2513:         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  2514:         fprintf(ficlog,"f1-2f2+f3= %.12lf, f1-f2-del= %.12lf, f1-f3= %.12lf\n",fp-2.0*(*fret)+fptt, fp -(*fret) -del, fp-fptt);
                   2515:       } 
1.181     brouard  2516:       if (directest < 0.0) { /* Then we use it for new direction */
                   2517: #endif
1.191     brouard  2518: #ifdef DEBUGLINMIN
1.234     brouard  2519:        printf("Before linmin in direction P%d-P0\n",n);
                   2520:        for (j=1;j<=n;j++) {
                   2521:          printf(" Before xit[%d]= %12.7f p[%d]= %12.7f",j,xit[j],j,p[j]);
                   2522:          fprintf(ficlog," Before xit[%d]= %12.7f p[%d]= %12.7f",j,xit[j],j,p[j]);
                   2523:          if(j % ncovmodel == 0){
                   2524:            printf("\n");
                   2525:            fprintf(ficlog,"\n");
                   2526:          }
                   2527:        }
1.224     brouard  2528: #endif
                   2529: #ifdef LINMINORIGINAL
1.234     brouard  2530:        linmin(p,xit,n,fret,func); /* computes minimum on the extrapolated direction: changes p and rescales xit.*/
1.224     brouard  2531: #else
1.234     brouard  2532:        linmin(p,xit,n,fret,func,&flat); /* computes minimum on the extrapolated direction: changes p and rescales xit.*/
                   2533:        flatdir[i]=flat; /* Function is vanishing in that direction i */
1.191     brouard  2534: #endif
1.234     brouard  2535:        
1.191     brouard  2536: #ifdef DEBUGLINMIN
1.234     brouard  2537:        for (j=1;j<=n;j++) { 
                   2538:          printf("After xit[%d]= %12.7f p[%d]= %12.7f",j,xit[j],j,p[j]);
                   2539:          fprintf(ficlog,"After xit[%d]= %12.7f p[%d]= %12.7f",j,xit[j],j,p[j]);
                   2540:          if(j % ncovmodel == 0){
                   2541:            printf("\n");
                   2542:            fprintf(ficlog,"\n");
                   2543:          }
                   2544:        }
1.224     brouard  2545: #endif
1.234     brouard  2546:        for (j=1;j<=n;j++) { 
                   2547:          xi[j][ibig]=xi[j][n]; /* Replace direction with biggest decrease by last direction n */
                   2548:          xi[j][n]=xit[j];      /* and this nth direction by the by the average p_0 p_n */
                   2549:        }
1.224     brouard  2550: #ifdef LINMINORIGINAL
                   2551: #else
1.234     brouard  2552:        for (j=1, flatd=0;j<=n;j++) {
                   2553:          if(flatdir[j]>0)
                   2554:            flatd++;
                   2555:        }
                   2556:        if(flatd >0){
1.255     brouard  2557:          printf("%d flat directions: ",flatd);
                   2558:          fprintf(ficlog,"%d flat directions :",flatd);
1.234     brouard  2559:          for (j=1;j<=n;j++) { 
                   2560:            if(flatdir[j]>0){
                   2561:              printf("%d ",j);
                   2562:              fprintf(ficlog,"%d ",j);
                   2563:            }
                   2564:          }
                   2565:          printf("\n");
                   2566:          fprintf(ficlog,"\n");
                   2567:        }
1.191     brouard  2568: #endif
1.234     brouard  2569:        printf("Gaining to use new average direction of P0 P%d instead of biggest increase direction %d :\n",n,ibig);
                   2570:        fprintf(ficlog,"Gaining to use new average direction of P0 P%d instead of biggest increase direction %d :\n",n,ibig);
                   2571:        
1.126     brouard  2572: #ifdef DEBUG
1.234     brouard  2573:        printf("Direction changed  last moved %d in place of ibig=%d, new last is the average:\n",n,ibig);
                   2574:        fprintf(ficlog,"Direction changed  last moved %d in place of ibig=%d, new last is the average:\n",n,ibig);
                   2575:        for(j=1;j<=n;j++){
                   2576:          printf(" %lf",xit[j]);
                   2577:          fprintf(ficlog," %lf",xit[j]);
                   2578:        }
                   2579:        printf("\n");
                   2580:        fprintf(ficlog,"\n");
1.126     brouard  2581: #endif
1.192     brouard  2582:       } /* end of t or directest negative */
1.224     brouard  2583: #ifdef POWELLNOF3INFF1TEST
1.192     brouard  2584: #else
1.234     brouard  2585:       } /* end if (fptt < fp)  */
1.192     brouard  2586: #endif
1.225     brouard  2587: #ifdef NODIRECTIONCHANGEDUNTILNITER  /* No change in drections until some iterations are done */
1.234     brouard  2588:     } /*NODIRECTIONCHANGEDUNTILNITER  No change in drections until some iterations are done */
1.225     brouard  2589: #else
1.224     brouard  2590: #endif
1.234     brouard  2591:                } /* loop iteration */ 
1.126     brouard  2592: } 
1.234     brouard  2593:   
1.126     brouard  2594: /**** Prevalence limit (stable or period prevalence)  ****************/
1.234     brouard  2595:   
1.235     brouard  2596:   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  2597:   {
1.279     brouard  2598:     /**< Computes the prevalence limit in each live state at age x and for covariate combination ij 
                   2599:      *   (and selected quantitative values in nres)
                   2600:      *  by left multiplying the unit
                   2601:      *  matrix by transitions matrix until convergence is reached with precision ftolpl 
                   2602:      * Wx= Wx-1 Px-1= Wx-2 Px-2 Px-1  = Wx-n Px-n ... Px-2 Px-1 I
                   2603:      * Wx is row vector: population in state 1, population in state 2, population dead
                   2604:      * or prevalence in state 1, prevalence in state 2, 0
                   2605:      * newm is the matrix after multiplications, its rows are identical at a factor.
                   2606:      * Inputs are the parameter, age, a tolerance for the prevalence limit ftolpl.
                   2607:      * Output is prlim.
                   2608:      * Initial matrix pimij 
                   2609:      */
1.206     brouard  2610:   /* {0.85204250825084937, 0.13044499163996345, 0.017512500109187184, */
                   2611:   /* 0.090851990222114765, 0.88271245433047185, 0.026435555447413338, */
                   2612:   /*  0,                   0                  , 1} */
                   2613:   /*
                   2614:    * and after some iteration: */
                   2615:   /* {0.45504275246439968, 0.42731458730878791, 0.11764266022681241, */
                   2616:   /*  0.45201005341706885, 0.42865420071559901, 0.11933574586733192, */
                   2617:   /*  0,                   0                  , 1} */
                   2618:   /* And prevalence by suppressing the deaths are close to identical rows in prlim: */
                   2619:   /* {0.51571254859325999, 0.4842874514067399, */
                   2620:   /*  0.51326036147820708, 0.48673963852179264} */
                   2621:   /* If we start from prlim again, prlim tends to a constant matrix */
1.234     brouard  2622:     
1.126     brouard  2623:   int i, ii,j,k;
1.209     brouard  2624:   double *min, *max, *meandiff, maxmax,sumnew=0.;
1.145     brouard  2625:   /* double **matprod2(); */ /* test */
1.218     brouard  2626:   double **out, cov[NCOVMAX+1], **pmij(); /* **pmmij is a global variable feeded with oldms etc */
1.126     brouard  2627:   double **newm;
1.209     brouard  2628:   double agefin, delaymax=200. ; /* 100 Max number of years to converge */
1.203     brouard  2629:   int ncvloop=0;
1.288     brouard  2630:   int first=0;
1.169     brouard  2631:   
1.209     brouard  2632:   min=vector(1,nlstate);
                   2633:   max=vector(1,nlstate);
                   2634:   meandiff=vector(1,nlstate);
                   2635: 
1.218     brouard  2636:        /* Starting with matrix unity */
1.126     brouard  2637:   for (ii=1;ii<=nlstate+ndeath;ii++)
                   2638:     for (j=1;j<=nlstate+ndeath;j++){
                   2639:       oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   2640:     }
1.169     brouard  2641:   
                   2642:   cov[1]=1.;
                   2643:   
                   2644:   /* Even if hstepm = 1, at least one multiplication by the unit matrix */
1.202     brouard  2645:   /* Start at agefin= age, computes the matrix of passage and loops decreasing agefin until convergence is reached */
1.126     brouard  2646:   for(agefin=age-stepm/YEARM; agefin>=age-delaymax; agefin=agefin-stepm/YEARM){
1.202     brouard  2647:     ncvloop++;
1.126     brouard  2648:     newm=savm;
                   2649:     /* Covariates have to be included here again */
1.138     brouard  2650:     cov[2]=agefin;
1.187     brouard  2651:     if(nagesqr==1)
                   2652:       cov[3]= agefin*agefin;;
1.234     brouard  2653:     for (k=1; k<=nsd;k++) { /* For single dummy covariates only */
                   2654:                        /* Here comes the value of the covariate 'ij' after renumbering k with single dummy covariates */
                   2655:       cov[2+nagesqr+TvarsDind[k]]=nbcode[TvarsD[k]][codtabm(ij,k)];
1.235     brouard  2656:       /* 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  2657:     }
                   2658:     for (k=1; k<=nsq;k++) { /* For single varying covariates only */
                   2659:                        /* Here comes the value of quantitative after renumbering k with single quantitative covariates */
1.235     brouard  2660:       cov[2+nagesqr+TvarsQind[k]]=Tqresult[nres][k]; 
                   2661:       /* 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  2662:     }
1.237     brouard  2663:     for (k=1; k<=cptcovage;k++){  /* For product with age */
1.234     brouard  2664:       if(Dummy[Tvar[Tage[k]]]){
                   2665:        cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,k)]*cov[2];
                   2666:       } else{
1.235     brouard  2667:        cov[2+nagesqr+Tage[k]]=Tqresult[nres][k]; 
1.234     brouard  2668:       }
1.235     brouard  2669:       /* 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  2670:     }
1.237     brouard  2671:     for (k=1; k<=cptcovprod;k++){ /* For product without age */
1.235     brouard  2672:       /* 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  2673:       if(Dummy[Tvard[k][1]==0]){
                   2674:        if(Dummy[Tvard[k][2]==0]){
                   2675:          cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)] * nbcode[Tvard[k][2]][codtabm(ij,k)];
                   2676:        }else{
                   2677:          cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)] * Tqresult[nres][k];
                   2678:        }
                   2679:       }else{
                   2680:        if(Dummy[Tvard[k][2]==0]){
                   2681:          cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][2]][codtabm(ij,k)] * Tqinvresult[nres][Tvard[k][1]];
                   2682:        }else{
                   2683:          cov[2+nagesqr+Tprod[k]]=Tqinvresult[nres][Tvard[k][1]]*  Tqinvresult[nres][Tvard[k][2]];
                   2684:        }
                   2685:       }
1.234     brouard  2686:     }
1.138     brouard  2687:     /*printf("ij=%d cptcovprod=%d tvar=%d ", ij, cptcovprod, Tvar[1]);*/
                   2688:     /*printf("ij=%d cov[3]=%lf cov[4]=%lf \n",ij, cov[3],cov[4]);*/
                   2689:     /*printf("ij=%d cov[3]=%lf \n",ij, cov[3]);*/
1.145     brouard  2690:     /* savm=pmij(pmmij,cov,ncovmodel,x,nlstate); */
                   2691:     /* out=matprod2(newm, pmij(pmmij,cov,ncovmodel,x,nlstate),1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm); /\* Bug Valgrind *\/ */
1.218     brouard  2692:                /* age and covariate values of ij are in 'cov' */
1.142     brouard  2693:     out=matprod2(newm, pmij(pmmij,cov,ncovmodel,x,nlstate),1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm); /* Bug Valgrind */
1.138     brouard  2694:     
1.126     brouard  2695:     savm=oldm;
                   2696:     oldm=newm;
1.209     brouard  2697: 
                   2698:     for(j=1; j<=nlstate; j++){
                   2699:       max[j]=0.;
                   2700:       min[j]=1.;
                   2701:     }
                   2702:     for(i=1;i<=nlstate;i++){
                   2703:       sumnew=0;
                   2704:       for(k=1; k<=ndeath; k++) sumnew+=newm[i][nlstate+k];
                   2705:       for(j=1; j<=nlstate; j++){ 
                   2706:        prlim[i][j]= newm[i][j]/(1-sumnew);
                   2707:        max[j]=FMAX(max[j],prlim[i][j]);
                   2708:        min[j]=FMIN(min[j],prlim[i][j]);
                   2709:       }
                   2710:     }
                   2711: 
1.126     brouard  2712:     maxmax=0.;
1.209     brouard  2713:     for(j=1; j<=nlstate; j++){
                   2714:       meandiff[j]=(max[j]-min[j])/(max[j]+min[j])*2.; /* mean difference for each column */
                   2715:       maxmax=FMAX(maxmax,meandiff[j]);
                   2716:       /* 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  2717:     } /* j loop */
1.203     brouard  2718:     *ncvyear= (int)age- (int)agefin;
1.208     brouard  2719:     /* 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  2720:     if(maxmax < ftolpl){
1.209     brouard  2721:       /* printf("maxmax=%lf ncvloop=%ld, age=%d, agefin=%d ncvyear=%d \n", maxmax, ncvloop, (int)age, (int)agefin, *ncvyear); */
                   2722:       free_vector(min,1,nlstate);
                   2723:       free_vector(max,1,nlstate);
                   2724:       free_vector(meandiff,1,nlstate);
1.126     brouard  2725:       return prlim;
                   2726:     }
1.288     brouard  2727:   } /* agefin loop */
1.208     brouard  2728:     /* After some age loop it doesn't converge */
1.288     brouard  2729:   if(!first){
                   2730:     first=1;
                   2731:     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);
                   2732:   }
                   2733:   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);
                   2734: 
1.209     brouard  2735:   /* 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); */
                   2736:   free_vector(min,1,nlstate);
                   2737:   free_vector(max,1,nlstate);
                   2738:   free_vector(meandiff,1,nlstate);
1.208     brouard  2739:   
1.169     brouard  2740:   return prlim; /* should not reach here */
1.126     brouard  2741: }
                   2742: 
1.217     brouard  2743: 
                   2744:  /**** Back Prevalence limit (stable or period prevalence)  ****************/
                   2745: 
1.218     brouard  2746:  /* 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) */
                   2747:  /* 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  2748:   double **bprevalim(double **bprlim, double ***prevacurrent, int nlstate, double x[], double age, double ftolpl, int *ncvyear, int ij, int nres)
1.217     brouard  2749: {
1.264     brouard  2750:   /* 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  2751:      matrix by transitions matrix until convergence is reached with precision ftolpl */
                   2752:   /* Wx= Wx-1 Px-1= Wx-2 Px-2 Px-1  = Wx-n Px-n ... Px-2 Px-1 I */
                   2753:   /* Wx is row vector: population in state 1, population in state 2, population dead */
                   2754:   /* or prevalence in state 1, prevalence in state 2, 0 */
                   2755:   /* newm is the matrix after multiplications, its rows are identical at a factor */
                   2756:   /* Initial matrix pimij */
                   2757:   /* {0.85204250825084937, 0.13044499163996345, 0.017512500109187184, */
                   2758:   /* 0.090851990222114765, 0.88271245433047185, 0.026435555447413338, */
                   2759:   /*  0,                   0                  , 1} */
                   2760:   /*
                   2761:    * and after some iteration: */
                   2762:   /* {0.45504275246439968, 0.42731458730878791, 0.11764266022681241, */
                   2763:   /*  0.45201005341706885, 0.42865420071559901, 0.11933574586733192, */
                   2764:   /*  0,                   0                  , 1} */
                   2765:   /* And prevalence by suppressing the deaths are close to identical rows in prlim: */
                   2766:   /* {0.51571254859325999, 0.4842874514067399, */
                   2767:   /*  0.51326036147820708, 0.48673963852179264} */
                   2768:   /* If we start from prlim again, prlim tends to a constant matrix */
                   2769: 
                   2770:   int i, ii,j,k;
1.247     brouard  2771:   int first=0;
1.217     brouard  2772:   double *min, *max, *meandiff, maxmax,sumnew=0.;
                   2773:   /* double **matprod2(); */ /* test */
                   2774:   double **out, cov[NCOVMAX+1], **bmij();
                   2775:   double **newm;
1.218     brouard  2776:   double        **dnewm, **doldm, **dsavm;  /* for use */
                   2777:   double        **oldm, **savm;  /* for use */
                   2778: 
1.217     brouard  2779:   double agefin, delaymax=200. ; /* 100 Max number of years to converge */
                   2780:   int ncvloop=0;
                   2781:   
                   2782:   min=vector(1,nlstate);
                   2783:   max=vector(1,nlstate);
                   2784:   meandiff=vector(1,nlstate);
                   2785: 
1.266     brouard  2786:   dnewm=ddnewms; doldm=ddoldms; dsavm=ddsavms;
                   2787:   oldm=oldms; savm=savms;
                   2788:   
                   2789:   /* Starting with matrix unity */
                   2790:   for (ii=1;ii<=nlstate+ndeath;ii++)
                   2791:     for (j=1;j<=nlstate+ndeath;j++){
1.217     brouard  2792:       oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   2793:     }
                   2794:   
                   2795:   cov[1]=1.;
                   2796:   
                   2797:   /* Even if hstepm = 1, at least one multiplication by the unit matrix */
                   2798:   /* Start at agefin= age, computes the matrix of passage and loops decreasing agefin until convergence is reached */
1.218     brouard  2799:   /* for(agefin=age+stepm/YEARM; agefin<=age+delaymax; agefin=agefin+stepm/YEARM){ /\* A changer en age *\/ */
1.288     brouard  2800:   /* for(agefin=age; agefin<AGESUP; agefin=agefin+stepm/YEARM){ /\* A changer en age *\/ */
                   2801:   for(agefin=age; agefin<FMIN(AGESUP,age+delaymax); agefin=agefin+stepm/YEARM){ /* A changer en age */
1.217     brouard  2802:     ncvloop++;
1.218     brouard  2803:     newm=savm; /* oldm should be kept from previous iteration or unity at start */
                   2804:                /* newm points to the allocated table savm passed by the function it can be written, savm could be reallocated */
1.217     brouard  2805:     /* Covariates have to be included here again */
                   2806:     cov[2]=agefin;
                   2807:     if(nagesqr==1)
                   2808:       cov[3]= agefin*agefin;;
1.242     brouard  2809:     for (k=1; k<=nsd;k++) { /* For single dummy covariates only */
                   2810:                        /* Here comes the value of the covariate 'ij' after renumbering k with single dummy covariates */
                   2811:       cov[2+nagesqr+TvarsDind[k]]=nbcode[TvarsD[k]][codtabm(ij,k)];
1.264     brouard  2812:       /* 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  2813:     }
                   2814:     /* for (k=1; k<=cptcovn;k++) { */
                   2815:     /*   /\* cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,Tvar[k])]; *\/ */
                   2816:     /*   cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,k)]; */
                   2817:     /*   /\* 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])]); *\/ */
                   2818:     /* } */
                   2819:     for (k=1; k<=nsq;k++) { /* For single varying covariates only */
                   2820:                        /* Here comes the value of quantitative after renumbering k with single quantitative covariates */
                   2821:       cov[2+nagesqr+TvarsQind[k]]=Tqresult[nres][k]; 
                   2822:       /* 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]); */
                   2823:     }
                   2824:     /* for (k=1; k<=cptcovage;k++) cov[2+nagesqr+Tage[k]]=nbcode[Tvar[k]][codtabm(ij,k)]*cov[2]; */
                   2825:     /* for (k=1; k<=cptcovprod;k++) /\* Useless *\/ */
                   2826:     /*   /\* cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,Tvard[k][1])] * nbcode[Tvard[k][2]][codtabm(ij,Tvard[k][2])]; *\/ */
                   2827:     /*   cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)] * nbcode[Tvard[k][2]][codtabm(ij,k)]; */
                   2828:     for (k=1; k<=cptcovage;k++){  /* For product with age */
                   2829:       if(Dummy[Tvar[Tage[k]]]){
                   2830:        cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,k)]*cov[2];
                   2831:       } else{
                   2832:        cov[2+nagesqr+Tage[k]]=Tqresult[nres][k]; 
                   2833:       }
                   2834:       /* 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]); */
                   2835:     }
                   2836:     for (k=1; k<=cptcovprod;k++){ /* For product without age */
                   2837:       /* 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]); */
                   2838:       if(Dummy[Tvard[k][1]==0]){
                   2839:        if(Dummy[Tvard[k][2]==0]){
                   2840:          cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)] * nbcode[Tvard[k][2]][codtabm(ij,k)];
                   2841:        }else{
                   2842:          cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)] * Tqresult[nres][k];
                   2843:        }
                   2844:       }else{
                   2845:        if(Dummy[Tvard[k][2]==0]){
                   2846:          cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][2]][codtabm(ij,k)] * Tqinvresult[nres][Tvard[k][1]];
                   2847:        }else{
                   2848:          cov[2+nagesqr+Tprod[k]]=Tqinvresult[nres][Tvard[k][1]]*  Tqinvresult[nres][Tvard[k][2]];
                   2849:        }
                   2850:       }
1.217     brouard  2851:     }
                   2852:     
                   2853:     /*printf("ij=%d cptcovprod=%d tvar=%d ", ij, cptcovprod, Tvar[1]);*/
                   2854:     /*printf("ij=%d cov[3]=%lf cov[4]=%lf \n",ij, cov[3],cov[4]);*/
                   2855:     /*printf("ij=%d cov[3]=%lf \n",ij, cov[3]);*/
                   2856:     /* savm=pmij(pmmij,cov,ncovmodel,x,nlstate); */
                   2857:     /* out=matprod2(newm, pmij(pmmij,cov,ncovmodel,x,nlstate),1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm); /\* Bug Valgrind *\/ */
1.218     brouard  2858:                /* ij should be linked to the correct index of cov */
                   2859:                /* age and covariate values ij are in 'cov', but we need to pass
                   2860:                 * ij for the observed prevalence at age and status and covariate
                   2861:                 * number:  prevacurrent[(int)agefin][ii][ij]
                   2862:                 */
                   2863:     /* 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 *\/ */
                   2864:     /* 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 *\/ */
                   2865:     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  2866:     /* if((int)age == 86 || (int)age == 87){ */
1.266     brouard  2867:     /*   printf(" Backward prevalim age=%d agefin=%d \n", (int) age, (int) agefin); */
                   2868:     /*   for(i=1; i<=nlstate+ndeath; i++) { */
                   2869:     /*         printf("%d newm= ",i); */
                   2870:     /*         for(j=1;j<=nlstate+ndeath;j++) { */
                   2871:     /*           printf("%f ",newm[i][j]); */
                   2872:     /*         } */
                   2873:     /*         printf("oldm * "); */
                   2874:     /*         for(j=1;j<=nlstate+ndeath;j++) { */
                   2875:     /*           printf("%f ",oldm[i][j]); */
                   2876:     /*         } */
1.268     brouard  2877:     /*         printf(" bmmij "); */
1.266     brouard  2878:     /*         for(j=1;j<=nlstate+ndeath;j++) { */
                   2879:     /*           printf("%f ",pmmij[i][j]); */
                   2880:     /*         } */
                   2881:     /*         printf("\n"); */
                   2882:     /*   } */
                   2883:     /* } */
1.217     brouard  2884:     savm=oldm;
                   2885:     oldm=newm;
1.266     brouard  2886: 
1.217     brouard  2887:     for(j=1; j<=nlstate; j++){
                   2888:       max[j]=0.;
                   2889:       min[j]=1.;
                   2890:     }
                   2891:     for(j=1; j<=nlstate; j++){ 
                   2892:       for(i=1;i<=nlstate;i++){
1.234     brouard  2893:        /* bprlim[i][j]= newm[i][j]/(1-sumnew); */
                   2894:        bprlim[i][j]= newm[i][j];
                   2895:        max[i]=FMAX(max[i],bprlim[i][j]); /* Max in line */
                   2896:        min[i]=FMIN(min[i],bprlim[i][j]);
1.217     brouard  2897:       }
                   2898:     }
1.218     brouard  2899:                
1.217     brouard  2900:     maxmax=0.;
                   2901:     for(i=1; i<=nlstate; i++){
                   2902:       meandiff[i]=(max[i]-min[i])/(max[i]+min[i])*2.; /* mean difference for each column */
                   2903:       maxmax=FMAX(maxmax,meandiff[i]);
                   2904:       /* 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  2905:     } /* i loop */
1.217     brouard  2906:     *ncvyear= -( (int)age- (int)agefin);
1.268     brouard  2907:     /* printf("Back maxmax=%lf ncvloop=%d, age=%d, agefin=%d ncvyear=%d \n", maxmax, ncvloop, (int)age, (int)agefin, *ncvyear); */
1.217     brouard  2908:     if(maxmax < ftolpl){
1.220     brouard  2909:       /* printf("OK Back maxmax=%lf ncvloop=%d, age=%d, agefin=%d ncvyear=%d \n", maxmax, ncvloop, (int)age, (int)agefin, *ncvyear); */
1.217     brouard  2910:       free_vector(min,1,nlstate);
                   2911:       free_vector(max,1,nlstate);
                   2912:       free_vector(meandiff,1,nlstate);
                   2913:       return bprlim;
                   2914:     }
1.288     brouard  2915:   } /* agefin loop */
1.217     brouard  2916:     /* After some age loop it doesn't converge */
1.288     brouard  2917:   if(!first){
1.247     brouard  2918:     first=1;
                   2919:     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\
                   2920: 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);
                   2921:   }
                   2922:   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  2923: Oldest age to start was %d-%d=%d, ncvloop=%d, ncvyear=%d\n", (int)age, maxmax, ftolpl, delaymax, (int)age, (int)delaymax, (int)agefin, ncvloop, *ncvyear);
                   2924:   /* 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); */
                   2925:   free_vector(min,1,nlstate);
                   2926:   free_vector(max,1,nlstate);
                   2927:   free_vector(meandiff,1,nlstate);
                   2928:   
                   2929:   return bprlim; /* should not reach here */
                   2930: }
                   2931: 
1.126     brouard  2932: /*************** transition probabilities ***************/ 
                   2933: 
                   2934: double **pmij(double **ps, double *cov, int ncovmodel, double *x, int nlstate )
                   2935: {
1.138     brouard  2936:   /* According to parameters values stored in x and the covariate's values stored in cov,
1.266     brouard  2937:      computes the probability to be observed in state j (after stepm years) being in state i by appying the
1.138     brouard  2938:      model to the ncovmodel covariates (including constant and age).
                   2939:      lnpijopii=ln(pij/pii)= aij+bij*age+cij*v1+dij*v2+... = sum_nc=1^ncovmodel xij(nc)*cov[nc]
                   2940:      and, according on how parameters are entered, the position of the coefficient xij(nc) of the
                   2941:      ncth covariate in the global vector x is given by the formula:
                   2942:      j<i nc+((i-1)*(nlstate+ndeath-1)+j-1)*ncovmodel
                   2943:      j>=i nc + ((i-1)*(nlstate+ndeath-1)+(j-2))*ncovmodel
                   2944:      Computes ln(pij/pii) (lnpijopii), deduces pij/pii by exponentiation,
                   2945:      sums on j different of i to get 1-pii/pii, deduces pii, and then all pij.
1.266     brouard  2946:      Outputs ps[i][j] or probability to be observed in j being in i according to
1.138     brouard  2947:      the values of the covariates cov[nc] and corresponding parameter values x[nc+shiftij]
1.266     brouard  2948:      Sum on j ps[i][j] should equal to 1.
1.138     brouard  2949:   */
                   2950:   double s1, lnpijopii;
1.126     brouard  2951:   /*double t34;*/
1.164     brouard  2952:   int i,j, nc, ii, jj;
1.126     brouard  2953: 
1.223     brouard  2954:   for(i=1; i<= nlstate; i++){
                   2955:     for(j=1; j<i;j++){
                   2956:       for (nc=1, lnpijopii=0.;nc <=ncovmodel; nc++){
                   2957:        /*lnpijopii += param[i][j][nc]*cov[nc];*/
                   2958:        lnpijopii += x[nc+((i-1)*(nlstate+ndeath-1)+j-1)*ncovmodel]*cov[nc];
                   2959:        /*       printf("Int j<i s1=%.17e, lnpijopii=%.17e\n",s1,lnpijopii); */
                   2960:       }
                   2961:       ps[i][j]=lnpijopii; /* In fact ln(pij/pii) */
                   2962:       /*       printf("s1=%.17e, lnpijopii=%.17e\n",s1,lnpijopii); */
                   2963:     }
                   2964:     for(j=i+1; j<=nlstate+ndeath;j++){
                   2965:       for (nc=1, lnpijopii=0.;nc <=ncovmodel; nc++){
                   2966:        /*lnpijopii += x[(i-1)*nlstate*ncovmodel+(j-2)*ncovmodel+nc+(i-1)*(ndeath-1)*ncovmodel]*cov[nc];*/
                   2967:        lnpijopii += x[nc + ((i-1)*(nlstate+ndeath-1)+(j-2))*ncovmodel]*cov[nc];
                   2968:        /*        printf("Int j>i s1=%.17e, lnpijopii=%.17e %lx %lx\n",s1,lnpijopii,s1,lnpijopii); */
                   2969:       }
                   2970:       ps[i][j]=lnpijopii; /* In fact ln(pij/pii) */
                   2971:     }
                   2972:   }
1.218     brouard  2973:   
1.223     brouard  2974:   for(i=1; i<= nlstate; i++){
                   2975:     s1=0;
                   2976:     for(j=1; j<i; j++){
                   2977:       s1+=exp(ps[i][j]); /* In fact sums pij/pii */
                   2978:       /*printf("debug1 %d %d ps=%lf exp(ps)=%lf s1+=%lf\n",i,j,ps[i][j],exp(ps[i][j]),s1); */
                   2979:     }
                   2980:     for(j=i+1; j<=nlstate+ndeath; j++){
                   2981:       s1+=exp(ps[i][j]); /* In fact sums pij/pii */
                   2982:       /*printf("debug2 %d %d ps=%lf exp(ps)=%lf s1+=%lf\n",i,j,ps[i][j],exp(ps[i][j]),s1); */
                   2983:     }
                   2984:     /* s1= sum_{j<>i} pij/pii=(1-pii)/pii and thus pii is known from s1 */
                   2985:     ps[i][i]=1./(s1+1.);
                   2986:     /* Computing other pijs */
                   2987:     for(j=1; j<i; j++)
                   2988:       ps[i][j]= exp(ps[i][j])*ps[i][i];
                   2989:     for(j=i+1; j<=nlstate+ndeath; j++)
                   2990:       ps[i][j]= exp(ps[i][j])*ps[i][i];
                   2991:     /* ps[i][nlstate+1]=1.-s1- ps[i][i];*/ /* Sum should be 1 */
                   2992:   } /* end i */
1.218     brouard  2993:   
1.223     brouard  2994:   for(ii=nlstate+1; ii<= nlstate+ndeath; ii++){
                   2995:     for(jj=1; jj<= nlstate+ndeath; jj++){
                   2996:       ps[ii][jj]=0;
                   2997:       ps[ii][ii]=1;
                   2998:     }
                   2999:   }
1.294     brouard  3000: 
                   3001: 
1.223     brouard  3002:   /* for(ii=1; ii<= nlstate+ndeath; ii++){ */
                   3003:   /*   for(jj=1; jj<= nlstate+ndeath; jj++){ */
                   3004:   /*   printf(" pmij  ps[%d][%d]=%lf ",ii,jj,ps[ii][jj]); */
                   3005:   /*   } */
                   3006:   /*   printf("\n "); */
                   3007:   /* } */
                   3008:   /* printf("\n ");printf("%lf ",cov[2]);*/
                   3009:   /*
                   3010:     for(i=1; i<= npar; i++) printf("%f ",x[i]);
1.218     brouard  3011:                goto end;*/
1.266     brouard  3012:   return ps; /* Pointer is unchanged since its call */
1.126     brouard  3013: }
                   3014: 
1.218     brouard  3015: /*************** backward transition probabilities ***************/ 
                   3016: 
                   3017:  /* 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 ) */
                   3018: /* double **bmij(double **ps, double *cov, int ncovmodel, double *x, int nlstate,  double ***prevacurrent, double ***dnewm, double **doldm, double **dsavm, int ij ) */
                   3019:  double **bmij(double **ps, double *cov, int ncovmodel, double *x, int nlstate,  double ***prevacurrent, int ij )
                   3020: {
1.266     brouard  3021:   /* Computes the backward probability at age agefin and covariate combination ij. In fact cov is already filled and x too.
                   3022:    * 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  3023:    */
1.218     brouard  3024:   int i, ii, j,k;
1.222     brouard  3025:   
                   3026:   double **out, **pmij();
                   3027:   double sumnew=0.;
1.218     brouard  3028:   double agefin;
1.292     brouard  3029:   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  3030:   double **dnewm, **dsavm, **doldm;
                   3031:   double **bbmij;
                   3032:   
1.218     brouard  3033:   doldm=ddoldms; /* global pointers */
1.222     brouard  3034:   dnewm=ddnewms;
                   3035:   dsavm=ddsavms;
                   3036:   
                   3037:   agefin=cov[2];
1.268     brouard  3038:   /* Bx = Diag(w_x) P_x Diag(Sum_i w^i_x p^ij_x */
1.222     brouard  3039:   /* bmij *//* age is cov[2], ij is included in cov, but we need for
1.266     brouard  3040:      the observed prevalence (with this covariate ij) at beginning of transition */
                   3041:   /* dsavm=pmij(pmmij,cov,ncovmodel,x,nlstate); */
1.268     brouard  3042: 
                   3043:   /* P_x */
1.266     brouard  3044:   pmmij=pmij(pmmij,cov,ncovmodel,x,nlstate); /*This is forward probability from agefin to agefin + stepm */
1.268     brouard  3045:   /* outputs pmmij which is a stochastic matrix in row */
                   3046: 
                   3047:   /* Diag(w_x) */
1.292     brouard  3048:   /* Rescaling the cross-sectional prevalence: Problem with prevacurrent which can be zero */
1.268     brouard  3049:   sumnew=0.;
1.269     brouard  3050:   /*for (ii=1;ii<=nlstate+ndeath;ii++){*/
1.268     brouard  3051:   for (ii=1;ii<=nlstate;ii++){ /* Only on live states */
1.297     brouard  3052:     /* printf(" agefin=%d, ii=%d, ij=%d, prev=%f\n",(int)agefin,ii, ij, prevacurrent[(int)agefin][ii][ij]); */
1.268     brouard  3053:     sumnew+=prevacurrent[(int)agefin][ii][ij];
                   3054:   }
                   3055:   if(sumnew >0.01){  /* At least some value in the prevalence */
                   3056:     for (ii=1;ii<=nlstate+ndeath;ii++){
                   3057:       for (j=1;j<=nlstate+ndeath;j++)
1.269     brouard  3058:        doldm[ii][j]=(ii==j ? prevacurrent[(int)agefin][ii][ij]/sumnew : 0.0);
1.268     brouard  3059:     }
                   3060:   }else{
                   3061:     for (ii=1;ii<=nlstate+ndeath;ii++){
                   3062:       for (j=1;j<=nlstate+ndeath;j++)
                   3063:       doldm[ii][j]=(ii==j ? 1./nlstate : 0.0);
                   3064:     }
                   3065:     /* if(sumnew <0.9){ */
                   3066:     /*   printf("Problem internal bmij B: sum on i wi <0.9: j=%d, sum_i wi=%lf,agefin=%d\n",j,sumnew, (int)agefin); */
                   3067:     /* } */
                   3068:   }
                   3069:   k3=0.0;  /* We put the last diagonal to 0 */
                   3070:   for (ii=nlstate+1;ii<=nlstate+ndeath;ii++){
                   3071:       doldm[ii][ii]= k3;
                   3072:   }
                   3073:   /* End doldm, At the end doldm is diag[(w_i)] */
                   3074:   
1.292     brouard  3075:   /* Left product of this diag matrix by pmmij=Px (dnewm=dsavm*doldm): diag[(w_i)*Px */
                   3076:   bbmij=matprod2(dnewm, doldm,1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, pmmij); /* was a Bug Valgrind */
1.268     brouard  3077: 
1.292     brouard  3078:   /* Diag(Sum_i w^i_x p^ij_x, should be the prevalence at age x+stepm */
1.268     brouard  3079:   /* 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  3080:   for (j=1;j<=nlstate+ndeath;j++){
1.268     brouard  3081:     sumnew=0.;
1.222     brouard  3082:     for (ii=1;ii<=nlstate;ii++){
1.266     brouard  3083:       /* sumnew+=dsavm[ii][j]*prevacurrent[(int)agefin][ii][ij]; */
1.268     brouard  3084:       sumnew+=pmmij[ii][j]*doldm[ii][ii]; /* Yes prevalence at beginning of transition */
1.222     brouard  3085:     } /* sumnew is (N11+N21)/N..= N.1/N.. = sum on i of w_i pij */
1.268     brouard  3086:     for (ii=1;ii<=nlstate+ndeath;ii++){
1.222     brouard  3087:        /* if(agefin >= agemaxpar && agefin <= agemaxpar+stepm/YEARM){ */
1.268     brouard  3088:        /*      dsavm[ii][j]=(ii==j ? 1./sumnew : 0.0); */
1.222     brouard  3089:        /* }else if(agefin >= agemaxpar+stepm/YEARM){ */
1.268     brouard  3090:        /*      dsavm[ii][j]=(ii==j ? 1./sumnew : 0.0); */
1.222     brouard  3091:        /* }else */
1.268     brouard  3092:       dsavm[ii][j]=(ii==j ? 1./sumnew : 0.0);
                   3093:     } /*End ii */
                   3094:   } /* 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 */
                   3095: 
1.292     brouard  3096:   ps=matprod2(ps, dnewm,1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, dsavm); /* was a Bug Valgrind */
1.268     brouard  3097:   /* ps is now diag[w_i] * Px * diag [1/(w_1p1i+w_2 p2i)] */
1.222     brouard  3098:   /* end bmij */
1.266     brouard  3099:   return ps; /*pointer is unchanged */
1.218     brouard  3100: }
1.217     brouard  3101: /*************** transition probabilities ***************/ 
                   3102: 
1.218     brouard  3103: double **bpmij(double **ps, double *cov, int ncovmodel, double *x, int nlstate )
1.217     brouard  3104: {
                   3105:   /* According to parameters values stored in x and the covariate's values stored in cov,
                   3106:      computes the probability to be observed in state j being in state i by appying the
                   3107:      model to the ncovmodel covariates (including constant and age).
                   3108:      lnpijopii=ln(pij/pii)= aij+bij*age+cij*v1+dij*v2+... = sum_nc=1^ncovmodel xij(nc)*cov[nc]
                   3109:      and, according on how parameters are entered, the position of the coefficient xij(nc) of the
                   3110:      ncth covariate in the global vector x is given by the formula:
                   3111:      j<i nc+((i-1)*(nlstate+ndeath-1)+j-1)*ncovmodel
                   3112:      j>=i nc + ((i-1)*(nlstate+ndeath-1)+(j-2))*ncovmodel
                   3113:      Computes ln(pij/pii) (lnpijopii), deduces pij/pii by exponentiation,
                   3114:      sums on j different of i to get 1-pii/pii, deduces pii, and then all pij.
                   3115:      Outputs ps[i][j] the probability to be observed in j being in j according to
                   3116:      the values of the covariates cov[nc] and corresponding parameter values x[nc+shiftij]
                   3117:   */
                   3118:   double s1, lnpijopii;
                   3119:   /*double t34;*/
                   3120:   int i,j, nc, ii, jj;
                   3121: 
1.234     brouard  3122:   for(i=1; i<= nlstate; i++){
                   3123:     for(j=1; j<i;j++){
                   3124:       for (nc=1, lnpijopii=0.;nc <=ncovmodel; nc++){
                   3125:        /*lnpijopii += param[i][j][nc]*cov[nc];*/
                   3126:        lnpijopii += x[nc+((i-1)*(nlstate+ndeath-1)+j-1)*ncovmodel]*cov[nc];
                   3127:        /*       printf("Int j<i s1=%.17e, lnpijopii=%.17e\n",s1,lnpijopii); */
                   3128:       }
                   3129:       ps[i][j]=lnpijopii; /* In fact ln(pij/pii) */
                   3130:       /*       printf("s1=%.17e, lnpijopii=%.17e\n",s1,lnpijopii); */
                   3131:     }
                   3132:     for(j=i+1; j<=nlstate+ndeath;j++){
                   3133:       for (nc=1, lnpijopii=0.;nc <=ncovmodel; nc++){
                   3134:        /*lnpijopii += x[(i-1)*nlstate*ncovmodel+(j-2)*ncovmodel+nc+(i-1)*(ndeath-1)*ncovmodel]*cov[nc];*/
                   3135:        lnpijopii += x[nc + ((i-1)*(nlstate+ndeath-1)+(j-2))*ncovmodel]*cov[nc];
                   3136:        /*        printf("Int j>i s1=%.17e, lnpijopii=%.17e %lx %lx\n",s1,lnpijopii,s1,lnpijopii); */
                   3137:       }
                   3138:       ps[i][j]=lnpijopii; /* In fact ln(pij/pii) */
                   3139:     }
                   3140:   }
                   3141:   
                   3142:   for(i=1; i<= nlstate; i++){
                   3143:     s1=0;
                   3144:     for(j=1; j<i; j++){
                   3145:       s1+=exp(ps[i][j]); /* In fact sums pij/pii */
                   3146:       /*printf("debug1 %d %d ps=%lf exp(ps)=%lf s1+=%lf\n",i,j,ps[i][j],exp(ps[i][j]),s1); */
                   3147:     }
                   3148:     for(j=i+1; j<=nlstate+ndeath; j++){
                   3149:       s1+=exp(ps[i][j]); /* In fact sums pij/pii */
                   3150:       /*printf("debug2 %d %d ps=%lf exp(ps)=%lf s1+=%lf\n",i,j,ps[i][j],exp(ps[i][j]),s1); */
                   3151:     }
                   3152:     /* s1= sum_{j<>i} pij/pii=(1-pii)/pii and thus pii is known from s1 */
                   3153:     ps[i][i]=1./(s1+1.);
                   3154:     /* Computing other pijs */
                   3155:     for(j=1; j<i; j++)
                   3156:       ps[i][j]= exp(ps[i][j])*ps[i][i];
                   3157:     for(j=i+1; j<=nlstate+ndeath; j++)
                   3158:       ps[i][j]= exp(ps[i][j])*ps[i][i];
                   3159:     /* ps[i][nlstate+1]=1.-s1- ps[i][i];*/ /* Sum should be 1 */
                   3160:   } /* end i */
                   3161:   
                   3162:   for(ii=nlstate+1; ii<= nlstate+ndeath; ii++){
                   3163:     for(jj=1; jj<= nlstate+ndeath; jj++){
                   3164:       ps[ii][jj]=0;
                   3165:       ps[ii][ii]=1;
                   3166:     }
                   3167:   }
1.296     brouard  3168:   /* Added for prevbcast */ /* Transposed matrix too */
1.234     brouard  3169:   for(jj=1; jj<= nlstate+ndeath; jj++){
                   3170:     s1=0.;
                   3171:     for(ii=1; ii<= nlstate+ndeath; ii++){
                   3172:       s1+=ps[ii][jj];
                   3173:     }
                   3174:     for(ii=1; ii<= nlstate; ii++){
                   3175:       ps[ii][jj]=ps[ii][jj]/s1;
                   3176:     }
                   3177:   }
                   3178:   /* Transposition */
                   3179:   for(jj=1; jj<= nlstate+ndeath; jj++){
                   3180:     for(ii=jj; ii<= nlstate+ndeath; ii++){
                   3181:       s1=ps[ii][jj];
                   3182:       ps[ii][jj]=ps[jj][ii];
                   3183:       ps[jj][ii]=s1;
                   3184:     }
                   3185:   }
                   3186:   /* for(ii=1; ii<= nlstate+ndeath; ii++){ */
                   3187:   /*   for(jj=1; jj<= nlstate+ndeath; jj++){ */
                   3188:   /*   printf(" pmij  ps[%d][%d]=%lf ",ii,jj,ps[ii][jj]); */
                   3189:   /*   } */
                   3190:   /*   printf("\n "); */
                   3191:   /* } */
                   3192:   /* printf("\n ");printf("%lf ",cov[2]);*/
                   3193:   /*
                   3194:     for(i=1; i<= npar; i++) printf("%f ",x[i]);
                   3195:     goto end;*/
                   3196:   return ps;
1.217     brouard  3197: }
                   3198: 
                   3199: 
1.126     brouard  3200: /**************** Product of 2 matrices ******************/
                   3201: 
1.145     brouard  3202: double **matprod2(double **out, double **in,int nrl, int nrh, int ncl, int nch, int ncolol, int ncoloh, double **b)
1.126     brouard  3203: {
                   3204:   /* Computes the matrix product of in(1,nrh-nrl+1)(1,nch-ncl+1) times
                   3205:      b(1,nch-ncl+1)(1,ncoloh-ncolol+1) into out(...) */
                   3206:   /* in, b, out are matrice of pointers which should have been initialized 
                   3207:      before: only the contents of out is modified. The function returns
                   3208:      a pointer to pointers identical to out */
1.145     brouard  3209:   int i, j, k;
1.126     brouard  3210:   for(i=nrl; i<= nrh; i++)
1.145     brouard  3211:     for(k=ncolol; k<=ncoloh; k++){
                   3212:       out[i][k]=0.;
                   3213:       for(j=ncl; j<=nch; j++)
                   3214:        out[i][k] +=in[i][j]*b[j][k];
                   3215:     }
1.126     brouard  3216:   return out;
                   3217: }
                   3218: 
                   3219: 
                   3220: /************* Higher Matrix Product ***************/
                   3221: 
1.235     brouard  3222: 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  3223: {
1.218     brouard  3224:   /* Computes the transition matrix starting at age 'age' and combination of covariate values corresponding to ij over 
1.126     brouard  3225:      'nhstepm*hstepm*stepm' months (i.e. until
                   3226:      age (in years)  age+nhstepm*hstepm*stepm/12) by multiplying 
                   3227:      nhstepm*hstepm matrices. 
                   3228:      Output is stored in matrix po[i][j][h] for h every 'hstepm' step 
                   3229:      (typically every 2 years instead of every month which is too big 
                   3230:      for the memory).
                   3231:      Model is determined by parameters x and covariates have to be 
                   3232:      included manually here. 
                   3233: 
                   3234:      */
                   3235: 
                   3236:   int i, j, d, h, k;
1.131     brouard  3237:   double **out, cov[NCOVMAX+1];
1.126     brouard  3238:   double **newm;
1.187     brouard  3239:   double agexact;
1.214     brouard  3240:   double agebegin, ageend;
1.126     brouard  3241: 
                   3242:   /* Hstepm could be zero and should return the unit matrix */
                   3243:   for (i=1;i<=nlstate+ndeath;i++)
                   3244:     for (j=1;j<=nlstate+ndeath;j++){
                   3245:       oldm[i][j]=(i==j ? 1.0 : 0.0);
                   3246:       po[i][j][0]=(i==j ? 1.0 : 0.0);
                   3247:     }
                   3248:   /* Even if hstepm = 1, at least one multiplication by the unit matrix */
                   3249:   for(h=1; h <=nhstepm; h++){
                   3250:     for(d=1; d <=hstepm; d++){
                   3251:       newm=savm;
                   3252:       /* Covariates have to be included here again */
                   3253:       cov[1]=1.;
1.214     brouard  3254:       agexact=age+((h-1)*hstepm + (d-1))*stepm/YEARM; /* age just before transition */
1.187     brouard  3255:       cov[2]=agexact;
                   3256:       if(nagesqr==1)
1.227     brouard  3257:        cov[3]= agexact*agexact;
1.235     brouard  3258:       for (k=1; k<=nsd;k++) { /* For single dummy covariates only */
                   3259:                        /* Here comes the value of the covariate 'ij' after renumbering k with single dummy covariates */
                   3260:        cov[2+nagesqr+TvarsDind[k]]=nbcode[TvarsD[k]][codtabm(ij,k)];
                   3261:        /* 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)); */
                   3262:       }
                   3263:       for (k=1; k<=nsq;k++) { /* For single varying covariates only */
                   3264:        /* Here comes the value of quantitative after renumbering k with single quantitative covariates */
                   3265:        cov[2+nagesqr+TvarsQind[k]]=Tqresult[nres][k]; 
                   3266:        /* 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]); */
                   3267:       }
                   3268:       for (k=1; k<=cptcovage;k++){
                   3269:        if(Dummy[Tvar[Tage[k]]]){
                   3270:          cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,k)]*cov[2];
                   3271:        } else{
                   3272:          cov[2+nagesqr+Tage[k]]=Tqresult[nres][k]; 
                   3273:        }
                   3274:        /* 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]); */
                   3275:       }
                   3276:       for (k=1; k<=cptcovprod;k++){ /*  */
                   3277:        /* 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]); */
                   3278:        cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)] * nbcode[Tvard[k][2]][codtabm(ij,k)];
                   3279:       }
                   3280:       /* for (k=1; k<=cptcovn;k++)  */
                   3281:       /*       cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,k)]; */
                   3282:       /* for (k=1; k<=cptcovage;k++) /\* Should start at cptcovn+1 *\/ */
                   3283:       /*       cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,k)]*cov[2]; */
                   3284:       /* for (k=1; k<=cptcovprod;k++) /\* Useless because included in cptcovn *\/ */
                   3285:       /*       cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)]*nbcode[Tvard[k][2]][codtabm(ij,k)]; */
1.227     brouard  3286:       
                   3287:       
1.126     brouard  3288:       /*printf("hxi cptcov=%d cptcode=%d\n",cptcov,cptcode);*/
                   3289:       /*printf("h=%d d=%d age=%f cov=%f\n",h,d,age,cov[2]);*/
1.218     brouard  3290:                        /* right multiplication of oldm by the current matrix */
1.126     brouard  3291:       out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, 
                   3292:                   pmij(pmmij,cov,ncovmodel,x,nlstate));
1.217     brouard  3293:       /* if((int)age == 70){ */
                   3294:       /*       printf(" Forward hpxij age=%d agexact=%f d=%d nhstepm=%d hstepm=%d\n", (int) age, agexact, d, nhstepm, hstepm); */
                   3295:       /*       for(i=1; i<=nlstate+ndeath; i++) { */
                   3296:       /*         printf("%d pmmij ",i); */
                   3297:       /*         for(j=1;j<=nlstate+ndeath;j++) { */
                   3298:       /*           printf("%f ",pmmij[i][j]); */
                   3299:       /*         } */
                   3300:       /*         printf(" oldm "); */
                   3301:       /*         for(j=1;j<=nlstate+ndeath;j++) { */
                   3302:       /*           printf("%f ",oldm[i][j]); */
                   3303:       /*         } */
                   3304:       /*         printf("\n"); */
                   3305:       /*       } */
                   3306:       /* } */
1.126     brouard  3307:       savm=oldm;
                   3308:       oldm=newm;
                   3309:     }
                   3310:     for(i=1; i<=nlstate+ndeath; i++)
                   3311:       for(j=1;j<=nlstate+ndeath;j++) {
1.267     brouard  3312:        po[i][j][h]=newm[i][j];
                   3313:        /*if(h==nhstepm) printf("po[%d][%d][%d]=%f ",i,j,h,po[i][j][h]);*/
1.126     brouard  3314:       }
1.128     brouard  3315:     /*printf("h=%d ",h);*/
1.126     brouard  3316:   } /* end h */
1.267     brouard  3317:   /*     printf("\n H=%d \n",h); */
1.126     brouard  3318:   return po;
                   3319: }
                   3320: 
1.217     brouard  3321: /************* Higher Back Matrix Product ***************/
1.218     brouard  3322: /* 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  3323: 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  3324: {
1.266     brouard  3325:   /* For a combination of dummy covariate ij, computes the transition matrix starting at age 'age' over
1.217     brouard  3326:      'nhstepm*hstepm*stepm' months (i.e. until
1.218     brouard  3327:      age (in years)  age+nhstepm*hstepm*stepm/12) by multiplying
                   3328:      nhstepm*hstepm matrices.
                   3329:      Output is stored in matrix po[i][j][h] for h every 'hstepm' step
                   3330:      (typically every 2 years instead of every month which is too big
1.217     brouard  3331:      for the memory).
1.218     brouard  3332:      Model is determined by parameters x and covariates have to be
1.266     brouard  3333:      included manually here. Then we use a call to bmij(x and cov)
                   3334:      The addresss of po (p3mat allocated to the dimension of nhstepm) should be stored for output
1.222     brouard  3335:   */
1.217     brouard  3336: 
                   3337:   int i, j, d, h, k;
1.266     brouard  3338:   double **out, cov[NCOVMAX+1], **bmij();
                   3339:   double **newm, ***newmm;
1.217     brouard  3340:   double agexact;
                   3341:   double agebegin, ageend;
1.222     brouard  3342:   double **oldm, **savm;
1.217     brouard  3343: 
1.266     brouard  3344:   newmm=po; /* To be saved */
                   3345:   oldm=oldms;savm=savms; /* Global pointers */
1.217     brouard  3346:   /* Hstepm could be zero and should return the unit matrix */
                   3347:   for (i=1;i<=nlstate+ndeath;i++)
                   3348:     for (j=1;j<=nlstate+ndeath;j++){
                   3349:       oldm[i][j]=(i==j ? 1.0 : 0.0);
                   3350:       po[i][j][0]=(i==j ? 1.0 : 0.0);
                   3351:     }
                   3352:   /* Even if hstepm = 1, at least one multiplication by the unit matrix */
                   3353:   for(h=1; h <=nhstepm; h++){
                   3354:     for(d=1; d <=hstepm; d++){
                   3355:       newm=savm;
                   3356:       /* Covariates have to be included here again */
                   3357:       cov[1]=1.;
1.271     brouard  3358:       agexact=age-( (h-1)*hstepm + (d)  )*stepm/YEARM; /* age just before transition, d or d-1? */
1.217     brouard  3359:       /* agexact=age+((h-1)*hstepm + (d-1))*stepm/YEARM; /\* age just before transition *\/ */
                   3360:       cov[2]=agexact;
                   3361:       if(nagesqr==1)
1.222     brouard  3362:        cov[3]= agexact*agexact;
1.266     brouard  3363:       for (k=1; k<=cptcovn;k++){
                   3364:       /*       cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,k)]; */
                   3365:       /* /\* cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,Tvar[k])]; *\/ */
                   3366:        cov[2+nagesqr+TvarsDind[k]]=nbcode[TvarsD[k]][codtabm(ij,k)];
                   3367:         /* 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)); */
                   3368:       }
1.267     brouard  3369:       for (k=1; k<=nsq;k++) { /* For single varying covariates only */
                   3370:        /* Here comes the value of quantitative after renumbering k with single quantitative covariates */
                   3371:        cov[2+nagesqr+TvarsQind[k]]=Tqresult[nres][k]; 
                   3372:        /* 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]); */
                   3373:       }
                   3374:       for (k=1; k<=cptcovage;k++){ /* Should start at cptcovn+1 */
                   3375:        if(Dummy[Tvar[Tage[k]]]){
                   3376:          cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,k)]*cov[2];
                   3377:        } else{
                   3378:          cov[2+nagesqr+Tage[k]]=Tqresult[nres][k]; 
                   3379:        }
                   3380:        /* 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]); */
                   3381:       }
                   3382:       for (k=1; k<=cptcovprod;k++){ /* Useless because included in cptcovn */
1.222     brouard  3383:        cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)]*nbcode[Tvard[k][2]][codtabm(ij,k)];
1.267     brouard  3384:       }                        
1.217     brouard  3385:       /*printf("hxi cptcov=%d cptcode=%d\n",cptcov,cptcode);*/
                   3386:       /*printf("h=%d d=%d age=%f cov=%f\n",h,d,age,cov[2]);*/
1.267     brouard  3387: 
1.218     brouard  3388:       /* Careful transposed matrix */
1.266     brouard  3389:       /* age is in cov[2], prevacurrent at beginning of transition. */
1.218     brouard  3390:       /* out=matprod2(newm, bmij(pmmij,cov,ncovmodel,x,nlstate,prevacurrent, dnewm, doldm, dsavm,ij),\ */
1.222     brouard  3391:       /*                                                1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm); */
1.218     brouard  3392:       out=matprod2(newm, bmij(pmmij,cov,ncovmodel,x,nlstate,prevacurrent,ij),\
1.222     brouard  3393:                   1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm);
1.217     brouard  3394:       /* if((int)age == 70){ */
                   3395:       /*       printf(" Backward hbxij age=%d agexact=%f d=%d nhstepm=%d hstepm=%d\n", (int) age, agexact, d, nhstepm, hstepm); */
                   3396:       /*       for(i=1; i<=nlstate+ndeath; i++) { */
                   3397:       /*         printf("%d pmmij ",i); */
                   3398:       /*         for(j=1;j<=nlstate+ndeath;j++) { */
                   3399:       /*           printf("%f ",pmmij[i][j]); */
                   3400:       /*         } */
                   3401:       /*         printf(" oldm "); */
                   3402:       /*         for(j=1;j<=nlstate+ndeath;j++) { */
                   3403:       /*           printf("%f ",oldm[i][j]); */
                   3404:       /*         } */
                   3405:       /*         printf("\n"); */
                   3406:       /*       } */
                   3407:       /* } */
                   3408:       savm=oldm;
                   3409:       oldm=newm;
                   3410:     }
                   3411:     for(i=1; i<=nlstate+ndeath; i++)
                   3412:       for(j=1;j<=nlstate+ndeath;j++) {
1.222     brouard  3413:        po[i][j][h]=newm[i][j];
1.268     brouard  3414:        /* if(h==nhstepm) */
                   3415:        /*   printf("po[%d][%d][%d]=%f ",i,j,h,po[i][j][h]); */
1.217     brouard  3416:       }
1.268     brouard  3417:     /* printf("h=%d %.1f ",h, agexact); */
1.217     brouard  3418:   } /* end h */
1.268     brouard  3419:   /* printf("\n H=%d nhs=%d \n",h, nhstepm); */
1.217     brouard  3420:   return po;
                   3421: }
                   3422: 
                   3423: 
1.162     brouard  3424: #ifdef NLOPT
                   3425:   double  myfunc(unsigned n, const double *p1, double *grad, void *pd){
                   3426:   double fret;
                   3427:   double *xt;
                   3428:   int j;
                   3429:   myfunc_data *d2 = (myfunc_data *) pd;
                   3430: /* xt = (p1-1); */
                   3431:   xt=vector(1,n); 
                   3432:   for (j=1;j<=n;j++)   xt[j]=p1[j-1]; /* xt[1]=p1[0] */
                   3433: 
                   3434:   fret=(d2->function)(xt); /*  p xt[1]@8 is fine */
                   3435:   /* fret=(*func)(xt); /\*  p xt[1]@8 is fine *\/ */
                   3436:   printf("Function = %.12lf ",fret);
                   3437:   for (j=1;j<=n;j++) printf(" %d %.8lf", j, xt[j]); 
                   3438:   printf("\n");
                   3439:  free_vector(xt,1,n);
                   3440:   return fret;
                   3441: }
                   3442: #endif
1.126     brouard  3443: 
                   3444: /*************** log-likelihood *************/
                   3445: double func( double *x)
                   3446: {
1.226     brouard  3447:   int i, ii, j, k, mi, d, kk;
                   3448:   int ioffset=0;
                   3449:   double l, ll[NLSTATEMAX+1], cov[NCOVMAX+1];
                   3450:   double **out;
                   3451:   double lli; /* Individual log likelihood */
                   3452:   int s1, s2;
1.228     brouard  3453:   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  3454:   double bbh, survp;
                   3455:   long ipmx;
                   3456:   double agexact;
                   3457:   /*extern weight */
                   3458:   /* We are differentiating ll according to initial status */
                   3459:   /*  for (i=1;i<=npar;i++) printf("%f ", x[i]);*/
                   3460:   /*for(i=1;i<imx;i++) 
                   3461:     printf(" %d\n",s[4][i]);
                   3462:   */
1.162     brouard  3463: 
1.226     brouard  3464:   ++countcallfunc;
1.162     brouard  3465: 
1.226     brouard  3466:   cov[1]=1.;
1.126     brouard  3467: 
1.226     brouard  3468:   for(k=1; k<=nlstate; k++) ll[k]=0.;
1.224     brouard  3469:   ioffset=0;
1.226     brouard  3470:   if(mle==1){
                   3471:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
                   3472:       /* Computes the values of the ncovmodel covariates of the model
                   3473:         depending if the covariates are fixed or varying (age dependent) and stores them in cov[]
                   3474:         Then computes with function pmij which return a matrix p[i][j] giving the elementary probability
                   3475:         to be observed in j being in i according to the model.
                   3476:       */
1.243     brouard  3477:       ioffset=2+nagesqr ;
1.233     brouard  3478:    /* Fixed */
1.234     brouard  3479:       for (k=1; k<=ncovf;k++){ /* Simple and product fixed covariates without age* products */
                   3480:        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)*/
                   3481:       }
1.226     brouard  3482:       /* In model V2+V1*V4+age*V3+V3*V2 Tvar[1] is V2, Tvar[2=V1*V4] 
                   3483:         is 6, Tvar[3=age*V3] should not be computed because of age Tvar[4=V3*V2] 
                   3484:         has been calculated etc */
                   3485:       /* For an individual i, wav[i] gives the number of effective waves */
                   3486:       /* We compute the contribution to Likelihood of each effective transition
                   3487:         mw[mi][i] is real wave of the mi th effectve wave */
                   3488:       /* Then statuses are computed at each begin and end of an effective wave s1=s[ mw[mi][i] ][i];
                   3489:         s2=s[mw[mi+1][i]][i];
                   3490:         And the iv th varying covariate is the cotvar[mw[mi+1][i]][iv][i]
                   3491:         But if the variable is not in the model TTvar[iv] is the real variable effective in the model:
                   3492:         meaning that decodemodel should be used cotvar[mw[mi+1][i]][TTvar[iv]][i]
                   3493:       */
                   3494:       for(mi=1; mi<= wav[i]-1; mi++){
1.234     brouard  3495:        for(k=1; k <= ncovv ; k++){ /* Varying  covariates (single and product but no age )*/
1.242     brouard  3496:          /* cov[ioffset+TvarVind[k]]=cotvar[mw[mi][i]][Tvar[TvarVind[k]]][i]; */
                   3497:          cov[ioffset+TvarVind[k]]=cotvar[mw[mi][i]][Tvar[TvarVind[k]]-ncovcol-nqv][i];
1.234     brouard  3498:        }
                   3499:        for (ii=1;ii<=nlstate+ndeath;ii++)
                   3500:          for (j=1;j<=nlstate+ndeath;j++){
                   3501:            oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   3502:            savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   3503:          }
                   3504:        for(d=0; d<dh[mi][i]; d++){
                   3505:          newm=savm;
                   3506:          agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
                   3507:          cov[2]=agexact;
                   3508:          if(nagesqr==1)
                   3509:            cov[3]= agexact*agexact;  /* Should be changed here */
                   3510:          for (kk=1; kk<=cptcovage;kk++) {
1.242     brouard  3511:          if(!FixedV[Tvar[Tage[kk]]])
1.234     brouard  3512:            cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact; /* Tage[kk] gives the data-covariate associated with age */
1.242     brouard  3513:          else
                   3514:            cov[Tage[kk]+2+nagesqr]=cotvar[mw[mi][i]][Tvar[Tage[kk]]-ncovcol-nqv][i]*agexact;
1.234     brouard  3515:          }
                   3516:          out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   3517:                       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   3518:          savm=oldm;
                   3519:          oldm=newm;
                   3520:        } /* end mult */
                   3521:        
                   3522:        /*lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]);*/ /* Original formula */
                   3523:        /* But now since version 0.9 we anticipate for bias at large stepm.
                   3524:         * If stepm is larger than one month (smallest stepm) and if the exact delay 
                   3525:         * (in months) between two waves is not a multiple of stepm, we rounded to 
                   3526:         * the nearest (and in case of equal distance, to the lowest) interval but now
                   3527:         * we keep into memory the bias bh[mi][i] and also the previous matrix product
                   3528:         * (i.e to dh[mi][i]-1) saved in 'savm'. Then we inter(extra)polate the
                   3529:         * probability in order to take into account the bias as a fraction of the way
1.231     brouard  3530:                                 * from savm to out if bh is negative or even beyond if bh is positive. bh varies
                   3531:                                 * -stepm/2 to stepm/2 .
                   3532:                                 * For stepm=1 the results are the same as for previous versions of Imach.
                   3533:                                 * For stepm > 1 the results are less biased than in previous versions. 
                   3534:                                 */
1.234     brouard  3535:        s1=s[mw[mi][i]][i];
                   3536:        s2=s[mw[mi+1][i]][i];
                   3537:        bbh=(double)bh[mi][i]/(double)stepm; 
                   3538:        /* bias bh is positive if real duration
                   3539:         * is higher than the multiple of stepm and negative otherwise.
                   3540:         */
                   3541:        /* lli= (savm[s1][s2]>1.e-8 ?(1.+bbh)*log(out[s1][s2])- bbh*log(savm[s1][s2]):log((1.+bbh)*out[s1][s2]));*/
                   3542:        if( s2 > nlstate){ 
                   3543:          /* i.e. if s2 is a death state and if the date of death is known 
                   3544:             then the contribution to the likelihood is the probability to 
                   3545:             die between last step unit time and current  step unit time, 
                   3546:             which is also equal to probability to die before dh 
                   3547:             minus probability to die before dh-stepm . 
                   3548:             In version up to 0.92 likelihood was computed
                   3549:             as if date of death was unknown. Death was treated as any other
                   3550:             health state: the date of the interview describes the actual state
                   3551:             and not the date of a change in health state. The former idea was
                   3552:             to consider that at each interview the state was recorded
                   3553:             (healthy, disable or death) and IMaCh was corrected; but when we
                   3554:             introduced the exact date of death then we should have modified
                   3555:             the contribution of an exact death to the likelihood. This new
                   3556:             contribution is smaller and very dependent of the step unit
                   3557:             stepm. It is no more the probability to die between last interview
                   3558:             and month of death but the probability to survive from last
                   3559:             interview up to one month before death multiplied by the
                   3560:             probability to die within a month. Thanks to Chris
                   3561:             Jackson for correcting this bug.  Former versions increased
                   3562:             mortality artificially. The bad side is that we add another loop
                   3563:             which slows down the processing. The difference can be up to 10%
                   3564:             lower mortality.
                   3565:          */
                   3566:          /* If, at the beginning of the maximization mostly, the
                   3567:             cumulative probability or probability to be dead is
                   3568:             constant (ie = 1) over time d, the difference is equal to
                   3569:             0.  out[s1][3] = savm[s1][3]: probability, being at state
                   3570:             s1 at precedent wave, to be dead a month before current
                   3571:             wave is equal to probability, being at state s1 at
                   3572:             precedent wave, to be dead at mont of the current
                   3573:             wave. Then the observed probability (that this person died)
                   3574:             is null according to current estimated parameter. In fact,
                   3575:             it should be very low but not zero otherwise the log go to
                   3576:             infinity.
                   3577:          */
1.183     brouard  3578: /* #ifdef INFINITYORIGINAL */
                   3579: /*         lli=log(out[s1][s2] - savm[s1][s2]); */
                   3580: /* #else */
                   3581: /*       if ((out[s1][s2] - savm[s1][s2]) < mytinydouble)  */
                   3582: /*         lli=log(mytinydouble); */
                   3583: /*       else */
                   3584: /*         lli=log(out[s1][s2] - savm[s1][s2]); */
                   3585: /* #endif */
1.226     brouard  3586:          lli=log(out[s1][s2] - savm[s1][s2]);
1.216     brouard  3587:          
1.226     brouard  3588:        } else if  ( s2==-1 ) { /* alive */
                   3589:          for (j=1,survp=0. ; j<=nlstate; j++) 
                   3590:            survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
                   3591:          /*survp += out[s1][j]; */
                   3592:          lli= log(survp);
                   3593:        }
                   3594:        else if  (s2==-4) { 
                   3595:          for (j=3,survp=0. ; j<=nlstate; j++)  
                   3596:            survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
                   3597:          lli= log(survp); 
                   3598:        } 
                   3599:        else if  (s2==-5) { 
                   3600:          for (j=1,survp=0. ; j<=2; j++)  
                   3601:            survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
                   3602:          lli= log(survp); 
                   3603:        } 
                   3604:        else{
                   3605:          lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */
                   3606:          /*  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 */
                   3607:        } 
                   3608:        /*lli=(1.+bbh)*log(out[s1][s2])- bbh*log(savm[s1][s2]);*/
                   3609:        /*if(lli ==000.0)*/
                   3610:        /*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); */
                   3611:        ipmx +=1;
                   3612:        sw += weight[i];
                   3613:        ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
                   3614:        /* if (lli < log(mytinydouble)){ */
                   3615:        /*   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); */
                   3616:        /*   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]); */
                   3617:        /* } */
                   3618:       } /* end of wave */
                   3619:     } /* end of individual */
                   3620:   }  else if(mle==2){
                   3621:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
                   3622:       for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i];
                   3623:       for(mi=1; mi<= wav[i]-1; mi++){
                   3624:        for (ii=1;ii<=nlstate+ndeath;ii++)
                   3625:          for (j=1;j<=nlstate+ndeath;j++){
                   3626:            oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   3627:            savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   3628:          }
                   3629:        for(d=0; d<=dh[mi][i]; d++){
                   3630:          newm=savm;
                   3631:          agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
                   3632:          cov[2]=agexact;
                   3633:          if(nagesqr==1)
                   3634:            cov[3]= agexact*agexact;
                   3635:          for (kk=1; kk<=cptcovage;kk++) {
                   3636:            cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact;
                   3637:          }
                   3638:          out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   3639:                       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   3640:          savm=oldm;
                   3641:          oldm=newm;
                   3642:        } /* end mult */
                   3643:       
                   3644:        s1=s[mw[mi][i]][i];
                   3645:        s2=s[mw[mi+1][i]][i];
                   3646:        bbh=(double)bh[mi][i]/(double)stepm; 
                   3647:        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 */
                   3648:        ipmx +=1;
                   3649:        sw += weight[i];
                   3650:        ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
                   3651:       } /* end of wave */
                   3652:     } /* end of individual */
                   3653:   }  else if(mle==3){  /* exponential inter-extrapolation */
                   3654:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
                   3655:       for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i];
                   3656:       for(mi=1; mi<= wav[i]-1; mi++){
                   3657:        for (ii=1;ii<=nlstate+ndeath;ii++)
                   3658:          for (j=1;j<=nlstate+ndeath;j++){
                   3659:            oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   3660:            savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   3661:          }
                   3662:        for(d=0; d<dh[mi][i]; d++){
                   3663:          newm=savm;
                   3664:          agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
                   3665:          cov[2]=agexact;
                   3666:          if(nagesqr==1)
                   3667:            cov[3]= agexact*agexact;
                   3668:          for (kk=1; kk<=cptcovage;kk++) {
                   3669:            cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact;
                   3670:          }
                   3671:          out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   3672:                       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   3673:          savm=oldm;
                   3674:          oldm=newm;
                   3675:        } /* end mult */
                   3676:       
                   3677:        s1=s[mw[mi][i]][i];
                   3678:        s2=s[mw[mi+1][i]][i];
                   3679:        bbh=(double)bh[mi][i]/(double)stepm; 
                   3680:        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 */
                   3681:        ipmx +=1;
                   3682:        sw += weight[i];
                   3683:        ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
                   3684:       } /* end of wave */
                   3685:     } /* end of individual */
                   3686:   }else if (mle==4){  /* ml=4 no inter-extrapolation */
                   3687:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
                   3688:       for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i];
                   3689:       for(mi=1; mi<= wav[i]-1; mi++){
                   3690:        for (ii=1;ii<=nlstate+ndeath;ii++)
                   3691:          for (j=1;j<=nlstate+ndeath;j++){
                   3692:            oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   3693:            savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   3694:          }
                   3695:        for(d=0; d<dh[mi][i]; d++){
                   3696:          newm=savm;
                   3697:          agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
                   3698:          cov[2]=agexact;
                   3699:          if(nagesqr==1)
                   3700:            cov[3]= agexact*agexact;
                   3701:          for (kk=1; kk<=cptcovage;kk++) {
                   3702:            cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact;
                   3703:          }
1.126     brouard  3704:        
1.226     brouard  3705:          out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   3706:                       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   3707:          savm=oldm;
                   3708:          oldm=newm;
                   3709:        } /* end mult */
                   3710:       
                   3711:        s1=s[mw[mi][i]][i];
                   3712:        s2=s[mw[mi+1][i]][i];
                   3713:        if( s2 > nlstate){ 
                   3714:          lli=log(out[s1][s2] - savm[s1][s2]);
                   3715:        } else if  ( s2==-1 ) { /* alive */
                   3716:          for (j=1,survp=0. ; j<=nlstate; j++) 
                   3717:            survp += out[s1][j];
                   3718:          lli= log(survp);
                   3719:        }else{
                   3720:          lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]); /* Original formula */
                   3721:        }
                   3722:        ipmx +=1;
                   3723:        sw += weight[i];
                   3724:        ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
1.126     brouard  3725: /*     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  3726:       } /* end of wave */
                   3727:     } /* end of individual */
                   3728:   }else{  /* ml=5 no inter-extrapolation no jackson =0.8a */
                   3729:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
                   3730:       for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i];
                   3731:       for(mi=1; mi<= wav[i]-1; mi++){
                   3732:        for (ii=1;ii<=nlstate+ndeath;ii++)
                   3733:          for (j=1;j<=nlstate+ndeath;j++){
                   3734:            oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   3735:            savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   3736:          }
                   3737:        for(d=0; d<dh[mi][i]; d++){
                   3738:          newm=savm;
                   3739:          agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
                   3740:          cov[2]=agexact;
                   3741:          if(nagesqr==1)
                   3742:            cov[3]= agexact*agexact;
                   3743:          for (kk=1; kk<=cptcovage;kk++) {
                   3744:            cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact;
                   3745:          }
1.126     brouard  3746:        
1.226     brouard  3747:          out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   3748:                       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   3749:          savm=oldm;
                   3750:          oldm=newm;
                   3751:        } /* end mult */
                   3752:       
                   3753:        s1=s[mw[mi][i]][i];
                   3754:        s2=s[mw[mi+1][i]][i];
                   3755:        lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]); /* Original formula */
                   3756:        ipmx +=1;
                   3757:        sw += weight[i];
                   3758:        ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
                   3759:        /*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]);*/
                   3760:       } /* end of wave */
                   3761:     } /* end of individual */
                   3762:   } /* End of if */
                   3763:   for(k=1,l=0.; k<=nlstate; k++) l += ll[k];
                   3764:   /* printf("l1=%f l2=%f ",ll[1],ll[2]); */
                   3765:   l= l*ipmx/sw; /* To get the same order of magnitude as if weight=1 for every body */
                   3766:   return -l;
1.126     brouard  3767: }
                   3768: 
                   3769: /*************** log-likelihood *************/
                   3770: double funcone( double *x)
                   3771: {
1.228     brouard  3772:   /* Same as func but slower because of a lot of printf and if */
1.126     brouard  3773:   int i, ii, j, k, mi, d, kk;
1.228     brouard  3774:   int ioffset=0;
1.131     brouard  3775:   double l, ll[NLSTATEMAX+1], cov[NCOVMAX+1];
1.126     brouard  3776:   double **out;
                   3777:   double lli; /* Individual log likelihood */
                   3778:   double llt;
                   3779:   int s1, s2;
1.228     brouard  3780:   int iv=0, iqv=0, itv=0, iqtv=0 ; /* Index of varying covariate, fixed quantitative cov, time varying covariate, quantitative time varying covariate */
                   3781: 
1.126     brouard  3782:   double bbh, survp;
1.187     brouard  3783:   double agexact;
1.214     brouard  3784:   double agebegin, ageend;
1.126     brouard  3785:   /*extern weight */
                   3786:   /* We are differentiating ll according to initial status */
                   3787:   /*  for (i=1;i<=npar;i++) printf("%f ", x[i]);*/
                   3788:   /*for(i=1;i<imx;i++) 
                   3789:     printf(" %d\n",s[4][i]);
                   3790:   */
                   3791:   cov[1]=1.;
                   3792: 
                   3793:   for(k=1; k<=nlstate; k++) ll[k]=0.;
1.224     brouard  3794:   ioffset=0;
                   3795:   for (i=1,ipmx=0, sw=0.; i<=imx; i++){
1.243     brouard  3796:     /* ioffset=2+nagesqr+cptcovage; */
                   3797:     ioffset=2+nagesqr;
1.232     brouard  3798:     /* Fixed */
1.224     brouard  3799:     /* for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i]; */
1.232     brouard  3800:     /* for (k=1; k<=ncoveff;k++){ /\* Simple and product fixed Dummy covariates without age* products *\/ */
                   3801:     for (k=1; k<=ncovf;k++){ /* Simple and product fixed covariates without age* products */
                   3802:       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)*/
                   3803: /*    cov[ioffset+TvarFind[1]]=covar[Tvar[TvarFind[1]]][i];  */
                   3804: /*    cov[2+6]=covar[Tvar[6]][i];  */
                   3805: /*    cov[2+6]=covar[2][i]; V2  */
                   3806: /*    cov[TvarFind[2]]=covar[Tvar[TvarFind[2]]][i];  */
                   3807: /*    cov[2+7]=covar[Tvar[7]][i];  */
                   3808: /*    cov[2+7]=covar[7][i]; V7=V1*V2  */
                   3809: /*    cov[TvarFind[3]]=covar[Tvar[TvarFind[3]]][i];  */
                   3810: /*    cov[2+9]=covar[Tvar[9]][i];  */
                   3811: /*    cov[2+9]=covar[1][i]; V1  */
1.225     brouard  3812:     }
1.232     brouard  3813:     /* for (k=1; k<=nqfveff;k++){ /\* Simple and product fixed Quantitative covariates without age* products *\/ */
                   3814:     /*   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?)*\/ */
                   3815:     /* } */
1.231     brouard  3816:     /* for(iqv=1; iqv <= nqfveff; iqv++){ /\* Quantitative fixed covariates *\/ */
                   3817:     /*   cov[++ioffset]=coqvar[Tvar[iqv]][i]; /\* Only V2 k=6 and V1*V2 7 *\/ */
                   3818:     /* } */
1.225     brouard  3819:     
1.233     brouard  3820: 
                   3821:     for(mi=1; mi<= wav[i]-1; mi++){  /* Varying with waves */
1.232     brouard  3822:     /* Wave varying (but not age varying) */
                   3823:       for(k=1; k <= ncovv ; k++){ /* Varying  covariates (single and product but no age )*/
1.242     brouard  3824:        /* cov[ioffset+TvarVind[k]]=cotvar[mw[mi][i]][Tvar[TvarVind[k]]][i]; */
                   3825:        cov[ioffset+TvarVind[k]]=cotvar[mw[mi][i]][Tvar[TvarVind[k]]-ncovcol-nqv][i];
                   3826:       }
1.232     brouard  3827:       /* for(itv=1; itv <= ntveff; itv++){ /\* Varying dummy covariates (single??)*\/ */
1.242     brouard  3828:       /* iv= Tvar[Tmodelind[ioffset-2-nagesqr-cptcovage+itv]]-ncovcol-nqv; /\* Counting the # varying covariate from 1 to ntveff *\/ */
                   3829:       /* cov[ioffset+iv]=cotvar[mw[mi][i]][iv][i]; */
                   3830:       /* k=ioffset-2-nagesqr-cptcovage+itv; /\* position in simple model *\/ */
                   3831:       /* cov[ioffset+itv]=cotvar[mw[mi][i]][TmodelInvind[itv]][i]; */
                   3832:       /* 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  3833:       /* for(iqtv=1; iqtv <= nqtveff; iqtv++){ /\* Varying quantitatives covariates *\/ */
1.242     brouard  3834:       /*       iv=TmodelInvQind[iqtv]; /\* Counting the # varying covariate from 1 to ntveff *\/ */
                   3835:       /*       /\* 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]); *\/ */
                   3836:       /*       cov[ioffset+ntveff+iqtv]=cotqvar[mw[mi][i]][TmodelInvQind[iqtv]][i]; */
1.232     brouard  3837:       /* } */
1.126     brouard  3838:       for (ii=1;ii<=nlstate+ndeath;ii++)
1.242     brouard  3839:        for (j=1;j<=nlstate+ndeath;j++){
                   3840:          oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   3841:          savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   3842:        }
1.214     brouard  3843:       
                   3844:       agebegin=agev[mw[mi][i]][i]; /* Age at beginning of effective wave */
                   3845:       ageend=agev[mw[mi][i]][i] + (dh[mi][i])*stepm/YEARM; /* Age at end of effective wave and at the end of transition */
                   3846:       for(d=0; d<dh[mi][i]; d++){  /* Delay between two effective waves */
1.247     brouard  3847:       /* for(d=0; d<=0; d++){  /\* Delay between two effective waves Only one matrix to speed up*\/ */
1.242     brouard  3848:        /*dh[m][i] or dh[mw[mi][i]][i] is the delay between two effective waves m=mw[mi][i]
                   3849:          and mw[mi+1][i]. dh depends on stepm.*/
                   3850:        newm=savm;
1.247     brouard  3851:        agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;  /* Here d is needed */
1.242     brouard  3852:        cov[2]=agexact;
                   3853:        if(nagesqr==1)
                   3854:          cov[3]= agexact*agexact;
                   3855:        for (kk=1; kk<=cptcovage;kk++) {
                   3856:          if(!FixedV[Tvar[Tage[kk]]])
                   3857:            cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact;
                   3858:          else
                   3859:            cov[Tage[kk]+2+nagesqr]=cotvar[mw[mi][i]][Tvar[Tage[kk]]-ncovcol-nqv][i]*agexact;
                   3860:        }
                   3861:        /* printf("i=%d,mi=%d,d=%d,mw[mi][i]=%d\n",i, mi,d,mw[mi][i]); */
                   3862:        /* savm=pmij(pmmij,cov,ncovmodel,x,nlstate); */
                   3863:        out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   3864:                     1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   3865:        /* out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath, */
                   3866:        /*           1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate)); */
                   3867:        savm=oldm;
                   3868:        oldm=newm;
1.126     brouard  3869:       } /* end mult */
                   3870:       
                   3871:       s1=s[mw[mi][i]][i];
                   3872:       s2=s[mw[mi+1][i]][i];
1.217     brouard  3873:       /* if(s2==-1){ */
1.268     brouard  3874:       /*       printf(" ERROR s1=%d, s2=%d i=%d \n", s1, s2, i); */
1.217     brouard  3875:       /*       /\* exit(1); *\/ */
                   3876:       /* } */
1.126     brouard  3877:       bbh=(double)bh[mi][i]/(double)stepm; 
                   3878:       /* bias is positive if real duration
                   3879:        * is higher than the multiple of stepm and negative otherwise.
                   3880:        */
                   3881:       if( s2 > nlstate && (mle <5) ){  /* Jackson */
1.242     brouard  3882:        lli=log(out[s1][s2] - savm[s1][s2]);
1.216     brouard  3883:       } else if  ( s2==-1 ) { /* alive */
1.242     brouard  3884:        for (j=1,survp=0. ; j<=nlstate; j++) 
                   3885:          survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
                   3886:        lli= log(survp);
1.126     brouard  3887:       }else if (mle==1){
1.242     brouard  3888:        lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */
1.126     brouard  3889:       } else if(mle==2){
1.242     brouard  3890:        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  3891:       } else if(mle==3){  /* exponential inter-extrapolation */
1.242     brouard  3892:        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  3893:       } else if (mle==4){  /* mle=4 no inter-extrapolation */
1.242     brouard  3894:        lli=log(out[s1][s2]); /* Original formula */
1.136     brouard  3895:       } else{  /* mle=0 back to 1 */
1.242     brouard  3896:        lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */
                   3897:        /*lli=log(out[s1][s2]); */ /* Original formula */
1.126     brouard  3898:       } /* End of if */
                   3899:       ipmx +=1;
                   3900:       sw += weight[i];
                   3901:       ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
1.132     brouard  3902:       /*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  3903:       if(globpr){
1.246     brouard  3904:        fprintf(ficresilk,"%09ld %6.1f %6.1f %6d %2d %2d %2d %2d %3d %15.6f %8.4f %8.3f\
1.126     brouard  3905:  %11.6f %11.6f %11.6f ", \
1.242     brouard  3906:                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  3907:                2*weight[i]*lli,(s2==-1? -1: out[s1][s2]),(s2==-1? -1: savm[s1][s2]));
1.242     brouard  3908:        for(k=1,llt=0.,l=0.; k<=nlstate; k++){
                   3909:          llt +=ll[k]*gipmx/gsw;
                   3910:          fprintf(ficresilk," %10.6f",-ll[k]*gipmx/gsw);
                   3911:        }
                   3912:        fprintf(ficresilk," %10.6f\n", -llt);
1.126     brouard  3913:       }
1.232     brouard  3914:        } /* end of wave */
                   3915: } /* end of individual */
                   3916: for(k=1,l=0.; k<=nlstate; k++) l += ll[k];
                   3917: /* printf("l1=%f l2=%f ",ll[1],ll[2]); */
                   3918: l= l*ipmx/sw; /* To get the same order of magnitude as if weight=1 for every body */
                   3919: if(globpr==0){ /* First time we count the contributions and weights */
                   3920:        gipmx=ipmx;
                   3921:        gsw=sw;
                   3922: }
                   3923: return -l;
1.126     brouard  3924: }
                   3925: 
                   3926: 
                   3927: /*************** function likelione ***********/
1.292     brouard  3928: void likelione(FILE *ficres,double p[], int npar, int nlstate, int *globpri, long *ipmx, double *sw, double *fretone, double (*func)(double []))
1.126     brouard  3929: {
                   3930:   /* This routine should help understanding what is done with 
                   3931:      the selection of individuals/waves and
                   3932:      to check the exact contribution to the likelihood.
                   3933:      Plotting could be done.
                   3934:    */
                   3935:   int k;
                   3936: 
                   3937:   if(*globpri !=0){ /* Just counts and sums, no printings */
1.201     brouard  3938:     strcpy(fileresilk,"ILK_"); 
1.202     brouard  3939:     strcat(fileresilk,fileresu);
1.126     brouard  3940:     if((ficresilk=fopen(fileresilk,"w"))==NULL) {
                   3941:       printf("Problem with resultfile: %s\n", fileresilk);
                   3942:       fprintf(ficlog,"Problem with resultfile: %s\n", fileresilk);
                   3943:     }
1.214     brouard  3944:     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");
                   3945:     fprintf(ficresilk, "#num_i ageb agend i s1 s2 mi mw dh likeli weight %%weight 2wlli out sav ");
1.126     brouard  3946:     /*         i,s1,s2,mi,mw[mi][i],dh[mi][i],exp(lli),weight[i],2*weight[i]*lli,out[s1][s2],savm[s1][s2]); */
                   3947:     for(k=1; k<=nlstate; k++) 
                   3948:       fprintf(ficresilk," -2*gipw/gsw*weight*ll[%d]++",k);
                   3949:     fprintf(ficresilk," -2*gipw/gsw*weight*ll(total)\n");
                   3950:   }
                   3951: 
1.292     brouard  3952:   *fretone=(*func)(p);
1.126     brouard  3953:   if(*globpri !=0){
                   3954:     fclose(ficresilk);
1.205     brouard  3955:     if (mle ==0)
                   3956:       fprintf(fichtm,"\n<br>File of contributions to the likelihood computed with initial parameters and mle = %d.",mle);
                   3957:     else if(mle >=1)
                   3958:       fprintf(fichtm,"\n<br>File of contributions to the likelihood computed with optimized parameters mle = %d.",mle);
                   3959:     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  3960:     fprintf(fichtm,"\n<br>Equation of the model: <b>model=1+age+%s</b><br>\n",model); 
1.208     brouard  3961:       
                   3962:     for (k=1; k<= nlstate ; k++) {
1.211     brouard  3963:       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  3964: <img src=\"%s-p%dj.png\">",k,k,subdirf2(optionfilefiname,"ILK_"),k,subdirf2(optionfilefiname,"ILK_"),k,subdirf2(optionfilefiname,"ILK_"),k);
                   3965:     }
1.207     brouard  3966:     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  3967: <img src=\"%s-ori.png\">",subdirf2(optionfilefiname,"ILK_"),subdirf2(optionfilefiname,"ILK_"),subdirf2(optionfilefiname,"ILK_"));
1.207     brouard  3968:     fprintf(fichtm,"<br>- and by state of destination <a href=\"%s-dest.png\">%s-dest.png</a><br> \
1.204     brouard  3969: <img src=\"%s-dest.png\">",subdirf2(optionfilefiname,"ILK_"),subdirf2(optionfilefiname,"ILK_"),subdirf2(optionfilefiname,"ILK_"));
1.207     brouard  3970:     fflush(fichtm);
1.205     brouard  3971:   }
1.126     brouard  3972:   return;
                   3973: }
                   3974: 
                   3975: 
                   3976: /*********** Maximum Likelihood Estimation ***************/
                   3977: 
                   3978: void mlikeli(FILE *ficres,double p[], int npar, int ncovmodel, int nlstate, double ftol, double (*func)(double []))
                   3979: {
1.165     brouard  3980:   int i,j, iter=0;
1.126     brouard  3981:   double **xi;
                   3982:   double fret;
                   3983:   double fretone; /* Only one call to likelihood */
                   3984:   /*  char filerespow[FILENAMELENGTH];*/
1.162     brouard  3985: 
                   3986: #ifdef NLOPT
                   3987:   int creturn;
                   3988:   nlopt_opt opt;
                   3989:   /* double lb[9] = { -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL }; /\* lower bounds *\/ */
                   3990:   double *lb;
                   3991:   double minf; /* the minimum objective value, upon return */
                   3992:   double * p1; /* Shifted parameters from 0 instead of 1 */
                   3993:   myfunc_data dinst, *d = &dinst;
                   3994: #endif
                   3995: 
                   3996: 
1.126     brouard  3997:   xi=matrix(1,npar,1,npar);
                   3998:   for (i=1;i<=npar;i++)
                   3999:     for (j=1;j<=npar;j++)
                   4000:       xi[i][j]=(i==j ? 1.0 : 0.0);
                   4001:   printf("Powell\n");  fprintf(ficlog,"Powell\n");
1.201     brouard  4002:   strcpy(filerespow,"POW_"); 
1.126     brouard  4003:   strcat(filerespow,fileres);
                   4004:   if((ficrespow=fopen(filerespow,"w"))==NULL) {
                   4005:     printf("Problem with resultfile: %s\n", filerespow);
                   4006:     fprintf(ficlog,"Problem with resultfile: %s\n", filerespow);
                   4007:   }
                   4008:   fprintf(ficrespow,"# Powell\n# iter -2*LL");
                   4009:   for (i=1;i<=nlstate;i++)
                   4010:     for(j=1;j<=nlstate+ndeath;j++)
                   4011:       if(j!=i)fprintf(ficrespow," p%1d%1d",i,j);
                   4012:   fprintf(ficrespow,"\n");
1.162     brouard  4013: #ifdef POWELL
1.126     brouard  4014:   powell(p,xi,npar,ftol,&iter,&fret,func);
1.162     brouard  4015: #endif
1.126     brouard  4016: 
1.162     brouard  4017: #ifdef NLOPT
                   4018: #ifdef NEWUOA
                   4019:   opt = nlopt_create(NLOPT_LN_NEWUOA,npar);
                   4020: #else
                   4021:   opt = nlopt_create(NLOPT_LN_BOBYQA,npar);
                   4022: #endif
                   4023:   lb=vector(0,npar-1);
                   4024:   for (i=0;i<npar;i++) lb[i]= -HUGE_VAL;
                   4025:   nlopt_set_lower_bounds(opt, lb);
                   4026:   nlopt_set_initial_step1(opt, 0.1);
                   4027:   
                   4028:   p1= (p+1); /*  p *(p+1)@8 and p *(p1)@8 are equal p1[0]=p[1] */
                   4029:   d->function = func;
                   4030:   printf(" Func %.12lf \n",myfunc(npar,p1,NULL,d));
                   4031:   nlopt_set_min_objective(opt, myfunc, d);
                   4032:   nlopt_set_xtol_rel(opt, ftol);
                   4033:   if ((creturn=nlopt_optimize(opt, p1, &minf)) < 0) {
                   4034:     printf("nlopt failed! %d\n",creturn); 
                   4035:   }
                   4036:   else {
                   4037:     printf("found minimum after %d evaluations (NLOPT=%d)\n", countcallfunc ,NLOPT);
                   4038:     printf("found minimum at f(%g,%g) = %0.10g\n", p[0], p[1], minf);
                   4039:     iter=1; /* not equal */
                   4040:   }
                   4041:   nlopt_destroy(opt);
                   4042: #endif
1.126     brouard  4043:   free_matrix(xi,1,npar,1,npar);
                   4044:   fclose(ficrespow);
1.203     brouard  4045:   printf("\n#Number of iterations & function calls = %d & %d, -2 Log likelihood = %.12f\n",iter, countcallfunc,func(p));
                   4046:   fprintf(ficlog,"\n#Number of iterations & function calls = %d & %d, -2 Log likelihood = %.12f\n",iter, countcallfunc,func(p));
1.180     brouard  4047:   fprintf(ficres,"#Number of iterations & function calls = %d & %d, -2 Log likelihood = %.12f\n",iter, countcallfunc,func(p));
1.126     brouard  4048: 
                   4049: }
                   4050: 
                   4051: /**** Computes Hessian and covariance matrix ***/
1.203     brouard  4052: void hesscov(double **matcov, double **hess, double p[], int npar, double delti[], double ftolhess, double (*func)(double []))
1.126     brouard  4053: {
                   4054:   double  **a,**y,*x,pd;
1.203     brouard  4055:   /* double **hess; */
1.164     brouard  4056:   int i, j;
1.126     brouard  4057:   int *indx;
                   4058: 
                   4059:   double hessii(double p[], double delta, int theta, double delti[],double (*func)(double []),int npar);
1.203     brouard  4060:   double hessij(double p[], double **hess, double delti[], int i, int j,double (*func)(double []),int npar);
1.126     brouard  4061:   void lubksb(double **a, int npar, int *indx, double b[]) ;
                   4062:   void ludcmp(double **a, int npar, int *indx, double *d) ;
                   4063:   double gompertz(double p[]);
1.203     brouard  4064:   /* hess=matrix(1,npar,1,npar); */
1.126     brouard  4065: 
                   4066:   printf("\nCalculation of the hessian matrix. Wait...\n");
                   4067:   fprintf(ficlog,"\nCalculation of the hessian matrix. Wait...\n");
                   4068:   for (i=1;i<=npar;i++){
1.203     brouard  4069:     printf("%d-",i);fflush(stdout);
                   4070:     fprintf(ficlog,"%d-",i);fflush(ficlog);
1.126     brouard  4071:    
                   4072:      hess[i][i]=hessii(p,ftolhess,i,delti,func,npar);
                   4073:     
                   4074:     /*  printf(" %f ",p[i]);
                   4075:        printf(" %lf %lf %lf",hess[i][i],ftolhess,delti[i]);*/
                   4076:   }
                   4077:   
                   4078:   for (i=1;i<=npar;i++) {
                   4079:     for (j=1;j<=npar;j++)  {
                   4080:       if (j>i) { 
1.203     brouard  4081:        printf(".%d-%d",i,j);fflush(stdout);
                   4082:        fprintf(ficlog,".%d-%d",i,j);fflush(ficlog);
                   4083:        hess[i][j]=hessij(p,hess, delti,i,j,func,npar);
1.126     brouard  4084:        
                   4085:        hess[j][i]=hess[i][j];    
                   4086:        /*printf(" %lf ",hess[i][j]);*/
                   4087:       }
                   4088:     }
                   4089:   }
                   4090:   printf("\n");
                   4091:   fprintf(ficlog,"\n");
                   4092: 
                   4093:   printf("\nInverting the hessian to get the covariance matrix. Wait...\n");
                   4094:   fprintf(ficlog,"\nInverting the hessian to get the covariance matrix. Wait...\n");
                   4095:   
                   4096:   a=matrix(1,npar,1,npar);
                   4097:   y=matrix(1,npar,1,npar);
                   4098:   x=vector(1,npar);
                   4099:   indx=ivector(1,npar);
                   4100:   for (i=1;i<=npar;i++)
                   4101:     for (j=1;j<=npar;j++) a[i][j]=hess[i][j];
                   4102:   ludcmp(a,npar,indx,&pd);
                   4103: 
                   4104:   for (j=1;j<=npar;j++) {
                   4105:     for (i=1;i<=npar;i++) x[i]=0;
                   4106:     x[j]=1;
                   4107:     lubksb(a,npar,indx,x);
                   4108:     for (i=1;i<=npar;i++){ 
                   4109:       matcov[i][j]=x[i];
                   4110:     }
                   4111:   }
                   4112: 
                   4113:   printf("\n#Hessian matrix#\n");
                   4114:   fprintf(ficlog,"\n#Hessian matrix#\n");
                   4115:   for (i=1;i<=npar;i++) { 
                   4116:     for (j=1;j<=npar;j++) { 
1.203     brouard  4117:       printf("%.6e ",hess[i][j]);
                   4118:       fprintf(ficlog,"%.6e ",hess[i][j]);
1.126     brouard  4119:     }
                   4120:     printf("\n");
                   4121:     fprintf(ficlog,"\n");
                   4122:   }
                   4123: 
1.203     brouard  4124:   /* printf("\n#Covariance matrix#\n"); */
                   4125:   /* fprintf(ficlog,"\n#Covariance matrix#\n"); */
                   4126:   /* for (i=1;i<=npar;i++) {  */
                   4127:   /*   for (j=1;j<=npar;j++) {  */
                   4128:   /*     printf("%.6e ",matcov[i][j]); */
                   4129:   /*     fprintf(ficlog,"%.6e ",matcov[i][j]); */
                   4130:   /*   } */
                   4131:   /*   printf("\n"); */
                   4132:   /*   fprintf(ficlog,"\n"); */
                   4133:   /* } */
                   4134: 
1.126     brouard  4135:   /* Recompute Inverse */
1.203     brouard  4136:   /* for (i=1;i<=npar;i++) */
                   4137:   /*   for (j=1;j<=npar;j++) a[i][j]=matcov[i][j]; */
                   4138:   /* ludcmp(a,npar,indx,&pd); */
                   4139: 
                   4140:   /*  printf("\n#Hessian matrix recomputed#\n"); */
                   4141: 
                   4142:   /* for (j=1;j<=npar;j++) { */
                   4143:   /*   for (i=1;i<=npar;i++) x[i]=0; */
                   4144:   /*   x[j]=1; */
                   4145:   /*   lubksb(a,npar,indx,x); */
                   4146:   /*   for (i=1;i<=npar;i++){  */
                   4147:   /*     y[i][j]=x[i]; */
                   4148:   /*     printf("%.3e ",y[i][j]); */
                   4149:   /*     fprintf(ficlog,"%.3e ",y[i][j]); */
                   4150:   /*   } */
                   4151:   /*   printf("\n"); */
                   4152:   /*   fprintf(ficlog,"\n"); */
                   4153:   /* } */
                   4154: 
                   4155:   /* Verifying the inverse matrix */
                   4156: #ifdef DEBUGHESS
                   4157:   y=matprod2(y,hess,1,npar,1,npar,1,npar,matcov);
1.126     brouard  4158: 
1.203     brouard  4159:    printf("\n#Verification: multiplying the matrix of covariance by the Hessian matrix, should be unity:#\n");
                   4160:    fprintf(ficlog,"\n#Verification: multiplying the matrix of covariance by the Hessian matrix. Should be unity:#\n");
1.126     brouard  4161: 
                   4162:   for (j=1;j<=npar;j++) {
                   4163:     for (i=1;i<=npar;i++){ 
1.203     brouard  4164:       printf("%.2f ",y[i][j]);
                   4165:       fprintf(ficlog,"%.2f ",y[i][j]);
1.126     brouard  4166:     }
                   4167:     printf("\n");
                   4168:     fprintf(ficlog,"\n");
                   4169:   }
1.203     brouard  4170: #endif
1.126     brouard  4171: 
                   4172:   free_matrix(a,1,npar,1,npar);
                   4173:   free_matrix(y,1,npar,1,npar);
                   4174:   free_vector(x,1,npar);
                   4175:   free_ivector(indx,1,npar);
1.203     brouard  4176:   /* free_matrix(hess,1,npar,1,npar); */
1.126     brouard  4177: 
                   4178: 
                   4179: }
                   4180: 
                   4181: /*************** hessian matrix ****************/
                   4182: double hessii(double x[], double delta, int theta, double delti[], double (*func)(double []), int npar)
1.203     brouard  4183: { /* Around values of x, computes the function func and returns the scales delti and hessian */
1.126     brouard  4184:   int i;
                   4185:   int l=1, lmax=20;
1.203     brouard  4186:   double k1,k2, res, fx;
1.132     brouard  4187:   double p2[MAXPARM+1]; /* identical to x */
1.126     brouard  4188:   double delt=0.0001, delts, nkhi=10.,nkhif=1., khi=1.e-4;
                   4189:   int k=0,kmax=10;
                   4190:   double l1;
                   4191: 
                   4192:   fx=func(x);
                   4193:   for (i=1;i<=npar;i++) p2[i]=x[i];
1.145     brouard  4194:   for(l=0 ; l <=lmax; l++){  /* Enlarging the zone around the Maximum */
1.126     brouard  4195:     l1=pow(10,l);
                   4196:     delts=delt;
                   4197:     for(k=1 ; k <kmax; k=k+1){
                   4198:       delt = delta*(l1*k);
                   4199:       p2[theta]=x[theta] +delt;
1.145     brouard  4200:       k1=func(p2)-fx;   /* Might be negative if too close to the theoretical maximum */
1.126     brouard  4201:       p2[theta]=x[theta]-delt;
                   4202:       k2=func(p2)-fx;
                   4203:       /*res= (k1-2.0*fx+k2)/delt/delt; */
1.203     brouard  4204:       res= (k1+k2)/delt/delt/2.; /* Divided by 2 because L and not 2*L */
1.126     brouard  4205:       
1.203     brouard  4206: #ifdef DEBUGHESSII
1.126     brouard  4207:       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);
                   4208:       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);
                   4209: #endif
                   4210:       /*if(fabs(k1-2.0*fx+k2) <1.e-13){ */
                   4211:       if((k1 <khi/nkhi/2.) || (k2 <khi/nkhi/2.)){
                   4212:        k=kmax;
                   4213:       }
                   4214:       else if((k1 >khi/nkhif) || (k2 >khi/nkhif)){ /* Keeps lastvalue before 3.84/2 KHI2 5% 1d.f. */
1.164     brouard  4215:        k=kmax; l=lmax*10;
1.126     brouard  4216:       }
                   4217:       else if((k1 >khi/nkhi) || (k2 >khi/nkhi)){ 
                   4218:        delts=delt;
                   4219:       }
1.203     brouard  4220:     } /* End loop k */
1.126     brouard  4221:   }
                   4222:   delti[theta]=delts;
                   4223:   return res; 
                   4224:   
                   4225: }
                   4226: 
1.203     brouard  4227: double hessij( double x[], double **hess, double delti[], int thetai,int thetaj,double (*func)(double []),int npar)
1.126     brouard  4228: {
                   4229:   int i;
1.164     brouard  4230:   int l=1, lmax=20;
1.126     brouard  4231:   double k1,k2,k3,k4,res,fx;
1.132     brouard  4232:   double p2[MAXPARM+1];
1.203     brouard  4233:   int k, kmax=1;
                   4234:   double v1, v2, cv12, lc1, lc2;
1.208     brouard  4235: 
                   4236:   int firstime=0;
1.203     brouard  4237:   
1.126     brouard  4238:   fx=func(x);
1.203     brouard  4239:   for (k=1; k<=kmax; k=k+10) {
1.126     brouard  4240:     for (i=1;i<=npar;i++) p2[i]=x[i];
1.203     brouard  4241:     p2[thetai]=x[thetai]+delti[thetai]*k;
                   4242:     p2[thetaj]=x[thetaj]+delti[thetaj]*k;
1.126     brouard  4243:     k1=func(p2)-fx;
                   4244:   
1.203     brouard  4245:     p2[thetai]=x[thetai]+delti[thetai]*k;
                   4246:     p2[thetaj]=x[thetaj]-delti[thetaj]*k;
1.126     brouard  4247:     k2=func(p2)-fx;
                   4248:   
1.203     brouard  4249:     p2[thetai]=x[thetai]-delti[thetai]*k;
                   4250:     p2[thetaj]=x[thetaj]+delti[thetaj]*k;
1.126     brouard  4251:     k3=func(p2)-fx;
                   4252:   
1.203     brouard  4253:     p2[thetai]=x[thetai]-delti[thetai]*k;
                   4254:     p2[thetaj]=x[thetaj]-delti[thetaj]*k;
1.126     brouard  4255:     k4=func(p2)-fx;
1.203     brouard  4256:     res=(k1-k2-k3+k4)/4.0/delti[thetai]/k/delti[thetaj]/k/2.; /* Because of L not 2*L */
                   4257:     if(k1*k2*k3*k4 <0.){
1.208     brouard  4258:       firstime=1;
1.203     brouard  4259:       kmax=kmax+10;
1.208     brouard  4260:     }
                   4261:     if(kmax >=10 || firstime ==1){
1.246     brouard  4262:       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);
                   4263:       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  4264:       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);
                   4265:       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);
                   4266:     }
                   4267: #ifdef DEBUGHESSIJ
                   4268:     v1=hess[thetai][thetai];
                   4269:     v2=hess[thetaj][thetaj];
                   4270:     cv12=res;
                   4271:     /* Computing eigen value of Hessian matrix */
                   4272:     lc1=((v1+v2)+sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
                   4273:     lc2=((v1+v2)-sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
                   4274:     if ((lc2 <0) || (lc1 <0) ){
                   4275:       printf("Warning: sub Hessian matrix '%d%d' does not have positive eigen values \n",thetai,thetaj);
                   4276:       fprintf(ficlog, "Warning: sub Hessian matrix '%d%d' does not have positive eigen values \n",thetai,thetaj);
                   4277:       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);
                   4278:       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);
                   4279:     }
1.126     brouard  4280: #endif
                   4281:   }
                   4282:   return res;
                   4283: }
                   4284: 
1.203     brouard  4285:     /* Not done yet: Was supposed to fix if not exactly at the maximum */
                   4286: /* double hessij( double x[], double delti[], int thetai,int thetaj,double (*func)(double []),int npar) */
                   4287: /* { */
                   4288: /*   int i; */
                   4289: /*   int l=1, lmax=20; */
                   4290: /*   double k1,k2,k3,k4,res,fx; */
                   4291: /*   double p2[MAXPARM+1]; */
                   4292: /*   double delt=0.0001, delts, nkhi=10.,nkhif=1., khi=1.e-4; */
                   4293: /*   int k=0,kmax=10; */
                   4294: /*   double l1; */
                   4295:   
                   4296: /*   fx=func(x); */
                   4297: /*   for(l=0 ; l <=lmax; l++){  /\* Enlarging the zone around the Maximum *\/ */
                   4298: /*     l1=pow(10,l); */
                   4299: /*     delts=delt; */
                   4300: /*     for(k=1 ; k <kmax; k=k+1){ */
                   4301: /*       delt = delti*(l1*k); */
                   4302: /*       for (i=1;i<=npar;i++) p2[i]=x[i]; */
                   4303: /*       p2[thetai]=x[thetai]+delti[thetai]/k; */
                   4304: /*       p2[thetaj]=x[thetaj]+delti[thetaj]/k; */
                   4305: /*       k1=func(p2)-fx; */
                   4306:       
                   4307: /*       p2[thetai]=x[thetai]+delti[thetai]/k; */
                   4308: /*       p2[thetaj]=x[thetaj]-delti[thetaj]/k; */
                   4309: /*       k2=func(p2)-fx; */
                   4310:       
                   4311: /*       p2[thetai]=x[thetai]-delti[thetai]/k; */
                   4312: /*       p2[thetaj]=x[thetaj]+delti[thetaj]/k; */
                   4313: /*       k3=func(p2)-fx; */
                   4314:       
                   4315: /*       p2[thetai]=x[thetai]-delti[thetai]/k; */
                   4316: /*       p2[thetaj]=x[thetaj]-delti[thetaj]/k; */
                   4317: /*       k4=func(p2)-fx; */
                   4318: /*       res=(k1-k2-k3+k4)/4.0/delti[thetai]*k/delti[thetaj]*k/2.; /\* Because of L not 2*L *\/ */
                   4319: /* #ifdef DEBUGHESSIJ */
                   4320: /*       printf("%d %d k=%d, k1=%.12e k2=%.12e k3=%.12e k4=%.12e delti/k=%.12e deltj/k=%.12e, xi-de/k=%.12e xj-de/k=%.12e  res=%.12e k1234=%.12e,k1-2=%.12e,k3-4=%.12e\n",thetai,thetaj,k,k1,k2,k3,k4,delti[thetai]/k,delti[thetaj]/k,x[thetai]-delti[thetai]/k,x[thetaj]-delti[thetaj]/k, res,k1-k2-k3+k4,k1-k2,k3-k4); */
                   4321: /*       fprintf(ficlog,"%d %d k=%d, k1=%.12e k2=%.12e k3=%.12e k4=%.12e delti/k=%.12e deltj/k=%.12e, xi-de/k=%.12e xj-de/k=%.12e  res=%.12e k1234=%.12e,k1-2=%.12e,k3-4=%.12e\n",thetai,thetaj,k,k1,k2,k3,k4,delti[thetai]/k,delti[thetaj]/k,x[thetai]-delti[thetai]/k,x[thetaj]-delti[thetaj]/k, res,k1-k2-k3+k4,k1-k2,k3-k4); */
                   4322: /* #endif */
                   4323: /*       if((k1 <khi/nkhi/2.) || (k2 <khi/nkhi/2.)|| (k4 <khi/nkhi/2.)|| (k4 <khi/nkhi/2.)){ */
                   4324: /*     k=kmax; */
                   4325: /*       } */
                   4326: /*       else if((k1 >khi/nkhif) || (k2 >khi/nkhif) || (k4 >khi/nkhif) || (k4 >khi/nkhif)){ /\* Keeps lastvalue before 3.84/2 KHI2 5% 1d.f. *\/ */
                   4327: /*     k=kmax; l=lmax*10; */
                   4328: /*       } */
                   4329: /*       else if((k1 >khi/nkhi) || (k2 >khi/nkhi)){  */
                   4330: /*     delts=delt; */
                   4331: /*       } */
                   4332: /*     } /\* End loop k *\/ */
                   4333: /*   } */
                   4334: /*   delti[theta]=delts; */
                   4335: /*   return res;  */
                   4336: /* } */
                   4337: 
                   4338: 
1.126     brouard  4339: /************** Inverse of matrix **************/
                   4340: void ludcmp(double **a, int n, int *indx, double *d) 
                   4341: { 
                   4342:   int i,imax,j,k; 
                   4343:   double big,dum,sum,temp; 
                   4344:   double *vv; 
                   4345:  
                   4346:   vv=vector(1,n); 
                   4347:   *d=1.0; 
                   4348:   for (i=1;i<=n;i++) { 
                   4349:     big=0.0; 
                   4350:     for (j=1;j<=n;j++) 
                   4351:       if ((temp=fabs(a[i][j])) > big) big=temp; 
1.256     brouard  4352:     if (big == 0.0){
                   4353:       printf(" Singular Hessian matrix at row %d:\n",i);
                   4354:       for (j=1;j<=n;j++) {
                   4355:        printf(" a[%d][%d]=%f,",i,j,a[i][j]);
                   4356:        fprintf(ficlog," a[%d][%d]=%f,",i,j,a[i][j]);
                   4357:       }
                   4358:       fflush(ficlog);
                   4359:       fclose(ficlog);
                   4360:       nrerror("Singular matrix in routine ludcmp"); 
                   4361:     }
1.126     brouard  4362:     vv[i]=1.0/big; 
                   4363:   } 
                   4364:   for (j=1;j<=n;j++) { 
                   4365:     for (i=1;i<j;i++) { 
                   4366:       sum=a[i][j]; 
                   4367:       for (k=1;k<i;k++) sum -= a[i][k]*a[k][j]; 
                   4368:       a[i][j]=sum; 
                   4369:     } 
                   4370:     big=0.0; 
                   4371:     for (i=j;i<=n;i++) { 
                   4372:       sum=a[i][j]; 
                   4373:       for (k=1;k<j;k++) 
                   4374:        sum -= a[i][k]*a[k][j]; 
                   4375:       a[i][j]=sum; 
                   4376:       if ( (dum=vv[i]*fabs(sum)) >= big) { 
                   4377:        big=dum; 
                   4378:        imax=i; 
                   4379:       } 
                   4380:     } 
                   4381:     if (j != imax) { 
                   4382:       for (k=1;k<=n;k++) { 
                   4383:        dum=a[imax][k]; 
                   4384:        a[imax][k]=a[j][k]; 
                   4385:        a[j][k]=dum; 
                   4386:       } 
                   4387:       *d = -(*d); 
                   4388:       vv[imax]=vv[j]; 
                   4389:     } 
                   4390:     indx[j]=imax; 
                   4391:     if (a[j][j] == 0.0) a[j][j]=TINY; 
                   4392:     if (j != n) { 
                   4393:       dum=1.0/(a[j][j]); 
                   4394:       for (i=j+1;i<=n;i++) a[i][j] *= dum; 
                   4395:     } 
                   4396:   } 
                   4397:   free_vector(vv,1,n);  /* Doesn't work */
                   4398: ;
                   4399: } 
                   4400: 
                   4401: void lubksb(double **a, int n, int *indx, double b[]) 
                   4402: { 
                   4403:   int i,ii=0,ip,j; 
                   4404:   double sum; 
                   4405:  
                   4406:   for (i=1;i<=n;i++) { 
                   4407:     ip=indx[i]; 
                   4408:     sum=b[ip]; 
                   4409:     b[ip]=b[i]; 
                   4410:     if (ii) 
                   4411:       for (j=ii;j<=i-1;j++) sum -= a[i][j]*b[j]; 
                   4412:     else if (sum) ii=i; 
                   4413:     b[i]=sum; 
                   4414:   } 
                   4415:   for (i=n;i>=1;i--) { 
                   4416:     sum=b[i]; 
                   4417:     for (j=i+1;j<=n;j++) sum -= a[i][j]*b[j]; 
                   4418:     b[i]=sum/a[i][i]; 
                   4419:   } 
                   4420: } 
                   4421: 
                   4422: void pstamp(FILE *fichier)
                   4423: {
1.196     brouard  4424:   fprintf(fichier,"# %s.%s\n#IMaCh version %s, %s\n#%s\n# %s", optionfilefiname,optionfilext,version,copyright, fullversion, strstart);
1.126     brouard  4425: }
                   4426: 
1.297     brouard  4427: void date2dmy(double date,double *day, double *month, double *year){
                   4428:   double yp=0., yp1=0., yp2=0.;
                   4429:   
                   4430:   yp1=modf(date,&yp);/* extracts integral of date in yp  and
                   4431:                        fractional in yp1 */
                   4432:   *year=yp;
                   4433:   yp2=modf((yp1*12),&yp);
                   4434:   *month=yp;
                   4435:   yp1=modf((yp2*30.5),&yp);
                   4436:   *day=yp;
                   4437:   if(*day==0) *day=1;
                   4438:   if(*month==0) *month=1;
                   4439: }
                   4440: 
1.253     brouard  4441: 
                   4442: 
1.126     brouard  4443: /************ Frequencies ********************/
1.251     brouard  4444: void  freqsummary(char fileres[], double p[], double pstart[], int iagemin, int iagemax, int **s, double **agev, int nlstate, int imx, \
1.226     brouard  4445:                  int *Tvaraff, int *invalidvarcomb, int **nbcode, int *ncodemax,double **mint,double **anint, char strstart[], \
                   4446:                  int firstpass,  int lastpass, int stepm, int weightopt, char model[])
1.250     brouard  4447: {  /* Some frequencies as well as proposing some starting values */
1.226     brouard  4448:   
1.265     brouard  4449:   int i, m, jk, j1, bool, z1,j, nj, nl, k, iv, jj=0, s1=1, s2=1;
1.226     brouard  4450:   int iind=0, iage=0;
                   4451:   int mi; /* Effective wave */
                   4452:   int first;
                   4453:   double ***freq; /* Frequencies */
1.268     brouard  4454:   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 */
                   4455:   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  4456:   double *meanq, *stdq, *idq;
1.226     brouard  4457:   double **meanqt;
                   4458:   double *pp, **prop, *posprop, *pospropt;
                   4459:   double pos=0., posproptt=0., pospropta=0., k2, dateintsum=0,k2cpt=0;
                   4460:   char fileresp[FILENAMELENGTH], fileresphtm[FILENAMELENGTH], fileresphtmfr[FILENAMELENGTH];
                   4461:   double agebegin, ageend;
                   4462:     
                   4463:   pp=vector(1,nlstate);
1.251     brouard  4464:   prop=matrix(1,nlstate,iagemin-AGEMARGE,iagemax+4+AGEMARGE); 
1.226     brouard  4465:   posprop=vector(1,nlstate); /* Counting the number of transition starting from a live state per age */ 
                   4466:   pospropt=vector(1,nlstate); /* Counting the number of transition starting from a live state */ 
                   4467:   /* prop=matrix(1,nlstate,iagemin,iagemax+3); */
                   4468:   meanq=vector(1,nqfveff); /* Number of Quantitative Fixed Variables Effective */
1.284     brouard  4469:   stdq=vector(1,nqfveff); /* Number of Quantitative Fixed Variables Effective */
1.283     brouard  4470:   idq=vector(1,nqfveff); /* Number of Quantitative Fixed Variables Effective */
1.226     brouard  4471:   meanqt=matrix(1,lastpass,1,nqtveff);
                   4472:   strcpy(fileresp,"P_");
                   4473:   strcat(fileresp,fileresu);
                   4474:   /*strcat(fileresphtm,fileresu);*/
                   4475:   if((ficresp=fopen(fileresp,"w"))==NULL) {
                   4476:     printf("Problem with prevalence resultfile: %s\n", fileresp);
                   4477:     fprintf(ficlog,"Problem with prevalence resultfile: %s\n", fileresp);
                   4478:     exit(0);
                   4479:   }
1.240     brouard  4480:   
1.226     brouard  4481:   strcpy(fileresphtm,subdirfext(optionfilefiname,"PHTM_",".htm"));
                   4482:   if((ficresphtm=fopen(fileresphtm,"w"))==NULL) {
                   4483:     printf("Problem with prevalence HTM resultfile '%s' with errno='%s'\n",fileresphtm,strerror(errno));
                   4484:     fprintf(ficlog,"Problem with prevalence HTM resultfile '%s' with errno='%s'\n",fileresphtm,strerror(errno));
                   4485:     fflush(ficlog);
                   4486:     exit(70); 
                   4487:   }
                   4488:   else{
                   4489:     fprintf(ficresphtm,"<html><head>\n<title>IMaCh PHTM_ %s</title></head>\n <body><font size=\"2\">%s <br> %s</font> \
1.240     brouard  4490: <hr size=\"2\" color=\"#EC5E5E\"> \n                                   \
1.214     brouard  4491: Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=1+age+%s<br>\n",\
1.226     brouard  4492:            fileresphtm,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model);
                   4493:   }
1.237     brouard  4494:   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  4495:   
1.226     brouard  4496:   strcpy(fileresphtmfr,subdirfext(optionfilefiname,"PHTMFR_",".htm"));
                   4497:   if((ficresphtmfr=fopen(fileresphtmfr,"w"))==NULL) {
                   4498:     printf("Problem with frequency table HTM resultfile '%s' with errno='%s'\n",fileresphtmfr,strerror(errno));
                   4499:     fprintf(ficlog,"Problem with frequency table HTM resultfile '%s' with errno='%s'\n",fileresphtmfr,strerror(errno));
                   4500:     fflush(ficlog);
                   4501:     exit(70); 
1.240     brouard  4502:   } else{
1.226     brouard  4503:     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  4504: <hr size=\"2\" color=\"#EC5E5E\"> \n                                   \
1.214     brouard  4505: Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=1+age+%s<br>\n",\
1.226     brouard  4506:            fileresphtmfr,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model);
                   4507:   }
1.240     brouard  4508:   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);
                   4509:   
1.253     brouard  4510:   y= vector(iagemin-AGEMARGE,iagemax+4+AGEMARGE);
                   4511:   x= vector(iagemin-AGEMARGE,iagemax+4+AGEMARGE);
1.251     brouard  4512:   freq= ma3x(-5,nlstate+ndeath,-5,nlstate+ndeath,iagemin-AGEMARGE,iagemax+4+AGEMARGE);
1.226     brouard  4513:   j1=0;
1.126     brouard  4514:   
1.227     brouard  4515:   /* j=ncoveff;  /\* Only fixed dummy covariates *\/ */
                   4516:   j=cptcoveff;  /* Only dummy covariates of the model */
1.226     brouard  4517:   if (cptcovn<1) {j=1;ncodemax[1]=1;}
1.240     brouard  4518:   
                   4519:   
1.226     brouard  4520:   /* Detects if a combination j1 is empty: for a multinomial variable like 3 education levels:
                   4521:      reference=low_education V1=0,V2=0
                   4522:      med_educ                V1=1 V2=0, 
                   4523:      high_educ               V1=0 V2=1
                   4524:      Then V1=1 and V2=1 is a noisy combination that we want to exclude for the list 2**cptcoveff 
                   4525:   */
1.249     brouard  4526:   dateintsum=0;
                   4527:   k2cpt=0;
                   4528: 
1.253     brouard  4529:   if(cptcoveff == 0 )
1.265     brouard  4530:     nl=1;  /* Constant and age model only */
1.253     brouard  4531:   else
                   4532:     nl=2;
1.265     brouard  4533: 
                   4534:   /* if a constant only model, one pass to compute frequency tables and to write it on ficresp */
                   4535:   /* Loop on nj=1 or 2 if dummy covariates j!=0
                   4536:    *   Loop on j1(1 to 2**cptcoveff) covariate combination
                   4537:    *     freq[s1][s2][iage] =0.
                   4538:    *     Loop on iind
                   4539:    *       ++freq[s1][s2][iage] weighted
                   4540:    *     end iind
                   4541:    *     if covariate and j!0
                   4542:    *       headers Variable on one line
                   4543:    *     endif cov j!=0
                   4544:    *     header of frequency table by age
                   4545:    *     Loop on age
                   4546:    *       pp[s1]+=freq[s1][s2][iage] weighted
                   4547:    *       pos+=freq[s1][s2][iage] weighted
                   4548:    *       Loop on s1 initial state
                   4549:    *         fprintf(ficresp
                   4550:    *       end s1
                   4551:    *     end age
                   4552:    *     if j!=0 computes starting values
                   4553:    *     end compute starting values
                   4554:    *   end j1
                   4555:    * end nl 
                   4556:    */
1.253     brouard  4557:   for (nj = 1; nj <= nl; nj++){   /* nj= 1 constant model, nl number of loops. */
                   4558:     if(nj==1)
                   4559:       j=0;  /* First pass for the constant */
1.265     brouard  4560:     else{
1.253     brouard  4561:       j=cptcoveff; /* Other passes for the covariate values */
1.265     brouard  4562:     }
1.251     brouard  4563:     first=1;
1.265     brouard  4564:     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  4565:       posproptt=0.;
                   4566:       /*printf("cptcoveff=%d Tvaraff=%d", cptcoveff,Tvaraff[1]);
                   4567:        scanf("%d", i);*/
                   4568:       for (i=-5; i<=nlstate+ndeath; i++)  
1.265     brouard  4569:        for (s2=-5; s2<=nlstate+ndeath; s2++)  
1.251     brouard  4570:          for(m=iagemin; m <= iagemax+3; m++)
1.265     brouard  4571:            freq[i][s2][m]=0;
1.251     brouard  4572:       
                   4573:       for (i=1; i<=nlstate; i++)  {
1.240     brouard  4574:        for(m=iagemin; m <= iagemax+3; m++)
1.251     brouard  4575:          prop[i][m]=0;
                   4576:        posprop[i]=0;
                   4577:        pospropt[i]=0;
                   4578:       }
1.283     brouard  4579:       for (z1=1; z1<= nqfveff; z1++) { /* zeroing for each combination j1 as well as for the total */
1.284     brouard  4580:         idq[z1]=0.;
                   4581:         meanq[z1]=0.;
                   4582:         stdq[z1]=0.;
1.283     brouard  4583:       }
                   4584:       /* for (z1=1; z1<= nqtveff; z1++) { */
1.251     brouard  4585:       /*   for(m=1;m<=lastpass;m++){ */
1.283     brouard  4586:       /*         meanqt[m][z1]=0.; */
                   4587:       /*       } */
                   4588:       /* }       */
1.251     brouard  4589:       /* dateintsum=0; */
                   4590:       /* k2cpt=0; */
                   4591:       
1.265     brouard  4592:       /* For that combination of covariates j1 (V4=1 V3=0 for example), we count and print the frequencies in one pass */
1.251     brouard  4593:       for (iind=1; iind<=imx; iind++) { /* For each individual iind */
                   4594:        bool=1;
                   4595:        if(j !=0){
                   4596:          if(anyvaryingduminmodel==0){ /* If All fixed covariates */
                   4597:            if (cptcoveff >0) { /* Filter is here: Must be looked at for model=V1+V2+V3+V4 */
                   4598:              for (z1=1; z1<=cptcoveff; z1++) { /* loops on covariates in the model */
                   4599:                /* if(Tvaraff[z1] ==-20){ */
                   4600:                /*       /\* sumnew+=cotvar[mw[mi][iind]][z1][iind]; *\/ */
                   4601:                /* }else  if(Tvaraff[z1] ==-10){ */
                   4602:                /*       /\* sumnew+=coqvar[z1][iind]; *\/ */
                   4603:                /* }else  */
                   4604:                if (covar[Tvaraff[z1]][iind]!= nbcode[Tvaraff[z1]][codtabm(j1,z1)]){ /* for combination j1 of covariates */
1.265     brouard  4605:                  /* Tests if the value of the covariate z1 for this individual iind responded to combination j1 (V4=1 V3=0) */
1.251     brouard  4606:                  bool=0; /* bool should be equal to 1 to be selected, one covariate value failed */
                   4607:                  /* 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", 
                   4608:                     bool,i,z1, z1, Tvaraff[z1],i,covar[Tvaraff[z1]][i],j1,z1,codtabm(j1,z1),
                   4609:                     j1,z1,nbcode[Tvaraff[z1]][codtabm(j1,z1)],j1);*/
                   4610:                  /* For j1=7 in V1+V2+V3+V4 = 0 1 1 0 and codtabm(7,3)=1 and nbcde[3][?]=1*/
                   4611:                } /* Onlyf fixed */
                   4612:              } /* end z1 */
                   4613:            } /* cptcovn > 0 */
                   4614:          } /* end any */
                   4615:        }/* end j==0 */
1.265     brouard  4616:        if (bool==1){ /* We selected an individual iind satisfying combination j1 (V4=1 V3=0) or all fixed covariates */
1.251     brouard  4617:          /* for(m=firstpass; m<=lastpass; m++){ */
1.284     brouard  4618:          for(mi=1; mi<wav[iind];mi++){ /* For each wave */
1.251     brouard  4619:            m=mw[mi][iind];
                   4620:            if(j!=0){
                   4621:              if(anyvaryingduminmodel==1){ /* Some are varying covariates */
                   4622:                for (z1=1; z1<=cptcoveff; z1++) {
                   4623:                  if( Fixed[Tmodelind[z1]]==1){
                   4624:                    iv= Tvar[Tmodelind[z1]]-ncovcol-nqv;
                   4625:                    if (cotvar[m][iv][iind]!= nbcode[Tvaraff[z1]][codtabm(j1,z1)]) /* iv=1 to ntv, right modality. If covariate's 
                   4626:                                                                                      value is -1, we don't select. It differs from the 
                   4627:                                                                                      constant and age model which counts them. */
                   4628:                      bool=0; /* not selected */
                   4629:                  }else if( Fixed[Tmodelind[z1]]== 0) { /* fixed */
                   4630:                    if (covar[Tvaraff[z1]][iind]!= nbcode[Tvaraff[z1]][codtabm(j1,z1)]) {
                   4631:                      bool=0;
                   4632:                    }
                   4633:                  }
                   4634:                }
                   4635:              }/* Some are varying covariates, we tried to speed up if all fixed covariates in the model, avoiding waves loop  */
                   4636:            } /* end j==0 */
                   4637:            /* bool =0 we keep that guy which corresponds to the combination of dummy values */
1.284     brouard  4638:            if(bool==1){ /*Selected */
1.251     brouard  4639:              /* dh[m][iind] or dh[mw[mi][iind]][iind] is the delay between two effective (mi) waves m=mw[mi][iind]
                   4640:                 and mw[mi+1][iind]. dh depends on stepm. */
                   4641:              agebegin=agev[m][iind]; /* Age at beginning of wave before transition*/
                   4642:              ageend=agev[m][iind]+(dh[m][iind])*stepm/YEARM; /* Age at end of wave and transition */
                   4643:              if(m >=firstpass && m <=lastpass){
                   4644:                k2=anint[m][iind]+(mint[m][iind]/12.);
                   4645:                /*if ((k2>=dateprev1) && (k2<=dateprev2)) {*/
                   4646:                if(agev[m][iind]==0) agev[m][iind]=iagemax+1;  /* All ages equal to 0 are in iagemax+1 */
                   4647:                if(agev[m][iind]==1) agev[m][iind]=iagemax+2;  /* All ages equal to 1 are in iagemax+2 */
                   4648:                if (s[m][iind]>0 && s[m][iind]<=nlstate)  /* If status at wave m is known and a live state */
                   4649:                  prop[s[m][iind]][(int)agev[m][iind]] += weight[iind];  /* At age of beginning of transition, where status is known */
                   4650:                if (m<lastpass) {
                   4651:                  /* if(s[m][iind]==4 && s[m+1][iind]==4) */
                   4652:                  /*   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]); */
                   4653:                  if(s[m][iind]==-1)
                   4654:                    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.));
                   4655:                  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  4656:                  for (z1=1; z1<= nqfveff; z1++) { /* Quantitative variables, calculating mean */
                   4657:                    idq[z1]=idq[z1]+weight[iind];
                   4658:                    meanq[z1]+=covar[ncovcol+z1][iind]*weight[iind];  /* Computes mean of quantitative with selected filter */
                   4659:                    stdq[z1]+=covar[ncovcol+z1][iind]*covar[ncovcol+z1][iind]*weight[iind]*weight[iind]; /* *weight[iind];*/  /* Computes mean of quantitative with selected filter */
                   4660:                  }
1.251     brouard  4661:                  /* if((int)agev[m][iind] == 55) */
                   4662:                  /*   printf("j=%d, j1=%d Age %d, iind=%d, num=%09ld m=%d\n",j,j1,(int)agev[m][iind],iind, num[iind],m); */
                   4663:                  /* freq[s[m][iind]][s[m+1][iind]][(int)((agebegin+ageend)/2.)] += weight[iind]; */
                   4664:                  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  4665:                }
1.251     brouard  4666:              } /* end if between passes */  
                   4667:              if ((agev[m][iind]>1) && (agev[m][iind]< (iagemax+3)) && (anint[m][iind]!=9999) && (mint[m][iind]!=99) && (j==0)) {
                   4668:                dateintsum=dateintsum+k2; /* on all covariates ?*/
                   4669:                k2cpt++;
                   4670:                /* printf("iind=%ld dateintmean = %lf dateintsum=%lf k2cpt=%lf k2=%lf\n",iind, dateintsum/k2cpt, dateintsum,k2cpt, k2); */
1.234     brouard  4671:              }
1.251     brouard  4672:            }else{
                   4673:              bool=1;
                   4674:            }/* end bool 2 */
                   4675:          } /* end m */
1.284     brouard  4676:          /* for (z1=1; z1<= nqfveff; z1++) { /\* Quantitative variables, calculating mean *\/ */
                   4677:          /*   idq[z1]=idq[z1]+weight[iind]; */
                   4678:          /*   meanq[z1]+=covar[ncovcol+z1][iind]*weight[iind];  /\* Computes mean of quantitative with selected filter *\/ */
                   4679:          /*   stdq[z1]+=covar[ncovcol+z1][iind]*covar[ncovcol+z1][iind]*weight[iind]*weight[iind]; /\* *weight[iind];*\/  /\* Computes mean of quantitative with selected filter *\/ */
                   4680:          /* } */
1.251     brouard  4681:        } /* end bool */
                   4682:       } /* end iind = 1 to imx */
                   4683:       /* prop[s][age] is feeded for any initial and valid live state as well as
                   4684:         freq[s1][s2][age] at single age of beginning the transition, for a combination j1 */
                   4685:       
                   4686:       
                   4687:       /*      fprintf(ficresp, "#Count between %.lf/%.lf/%.lf and %.lf/%.lf/%.lf\n",jprev1, mprev1,anprev1,jprev2, mprev2,anprev2);*/
1.265     brouard  4688:       if(cptcoveff==0 && nj==1) /* no covariate and first pass */
                   4689:         pstamp(ficresp);
1.251     brouard  4690:       if  (cptcoveff>0 && j!=0){
1.265     brouard  4691:         pstamp(ficresp);
1.251     brouard  4692:        printf( "\n#********** Variable "); 
                   4693:        fprintf(ficresp, "\n#********** Variable "); 
                   4694:        fprintf(ficresphtm, "\n<br/><br/><h3>********** Variable "); 
                   4695:        fprintf(ficresphtmfr, "\n<br/><br/><h3>********** Variable "); 
                   4696:        fprintf(ficlog, "\n#********** Variable "); 
                   4697:        for (z1=1; z1<=cptcoveff; z1++){
                   4698:          if(!FixedV[Tvaraff[z1]]){
                   4699:            printf( "V%d(fixed)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
                   4700:            fprintf(ficresp, "V%d(fixed)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
                   4701:            fprintf(ficresphtm, "V%d(fixed)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
                   4702:            fprintf(ficresphtmfr, "V%d(fixed)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
                   4703:            fprintf(ficlog, "V%d(fixed)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
1.250     brouard  4704:          }else{
1.251     brouard  4705:            printf( "V%d(varying)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
                   4706:            fprintf(ficresp, "V%d(varying)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
                   4707:            fprintf(ficresphtm, "V%d(varying)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
                   4708:            fprintf(ficresphtmfr, "V%d(varying)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
                   4709:            fprintf(ficlog, "V%d(varying)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
                   4710:          }
                   4711:        }
                   4712:        printf( "**********\n#");
                   4713:        fprintf(ficresp, "**********\n#");
                   4714:        fprintf(ficresphtm, "**********</h3>\n");
                   4715:        fprintf(ficresphtmfr, "**********</h3>\n");
                   4716:        fprintf(ficlog, "**********\n");
                   4717:       }
1.284     brouard  4718:       /*
                   4719:        Printing means of quantitative variables if any
                   4720:       */
                   4721:       for (z1=1; z1<= nqfveff; z1++) {
1.285     brouard  4722:        fprintf(ficlog,"Mean of fixed quantitative variable V%d on %.0f individuals sum=%f", ncovcol+z1, idq[z1], meanq[z1]);
1.284     brouard  4723:        fprintf(ficlog,", mean=%.3g\n",meanq[z1]/idq[z1]);
                   4724:        if(weightopt==1){
                   4725:          printf(" Weighted mean and standard deviation of");
                   4726:          fprintf(ficlog," Weighted mean and standard deviation of");
                   4727:          fprintf(ficresphtmfr," Weighted mean and standard deviation of");
                   4728:        }
1.285     brouard  4729:        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]));
                   4730:        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]));
                   4731:        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  4732:       }
                   4733:       /* for (z1=1; z1<= nqtveff; z1++) { */
                   4734:       /*       for(m=1;m<=lastpass;m++){ */
                   4735:       /*         fprintf(ficresphtmfr,"V quantitative id %d, pass id=%d, mean=%f<p>\n", z1, m, meanqt[m][z1]); */
                   4736:       /*   } */
                   4737:       /* } */
1.283     brouard  4738: 
1.251     brouard  4739:       fprintf(ficresphtm,"<table style=\"text-align:center; border: 1px solid\">");
1.265     brouard  4740:       if((cptcoveff==0 && nj==1)|| nj==2 ) /* no covariate and first pass */
                   4741:         fprintf(ficresp, " Age");
                   4742:       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  4743:       for(i=1; i<=nlstate;i++) {
1.265     brouard  4744:        if((cptcoveff==0 && nj==1)|| nj==2 ) fprintf(ficresp," Prev(%d)  N(%d)  N  ",i,i);
1.251     brouard  4745:        fprintf(ficresphtm, "<th>Age</th><th>Prev(%d)</th><th>N(%d)</th><th>N</th>",i,i);
                   4746:       }
1.265     brouard  4747:       if((cptcoveff==0 && nj==1)|| nj==2 ) fprintf(ficresp, "\n");
1.251     brouard  4748:       fprintf(ficresphtm, "\n");
                   4749:       
                   4750:       /* Header of frequency table by age */
                   4751:       fprintf(ficresphtmfr,"<table style=\"text-align:center; border: 1px solid\">");
                   4752:       fprintf(ficresphtmfr,"<th>Age</th> ");
1.265     brouard  4753:       for(s2=-1; s2 <=nlstate+ndeath; s2++){
1.251     brouard  4754:        for(m=-1; m <=nlstate+ndeath; m++){
1.265     brouard  4755:          if(s2!=0 && m!=0)
                   4756:            fprintf(ficresphtmfr,"<th>%d%d</th> ",s2,m);
1.240     brouard  4757:        }
1.226     brouard  4758:       }
1.251     brouard  4759:       fprintf(ficresphtmfr, "\n");
                   4760:     
                   4761:       /* For each age */
                   4762:       for(iage=iagemin; iage <= iagemax+3; iage++){
                   4763:        fprintf(ficresphtm,"<tr>");
                   4764:        if(iage==iagemax+1){
                   4765:          fprintf(ficlog,"1");
                   4766:          fprintf(ficresphtmfr,"<tr><th>0</th> ");
                   4767:        }else if(iage==iagemax+2){
                   4768:          fprintf(ficlog,"0");
                   4769:          fprintf(ficresphtmfr,"<tr><th>Unknown</th> ");
                   4770:        }else if(iage==iagemax+3){
                   4771:          fprintf(ficlog,"Total");
                   4772:          fprintf(ficresphtmfr,"<tr><th>Total</th> ");
                   4773:        }else{
1.240     brouard  4774:          if(first==1){
1.251     brouard  4775:            first=0;
                   4776:            printf("See log file for details...\n");
                   4777:          }
                   4778:          fprintf(ficresphtmfr,"<tr><th>%d</th> ",iage);
                   4779:          fprintf(ficlog,"Age %d", iage);
                   4780:        }
1.265     brouard  4781:        for(s1=1; s1 <=nlstate ; s1++){
                   4782:          for(m=-1, pp[s1]=0; m <=nlstate+ndeath ; m++)
                   4783:            pp[s1] += freq[s1][m][iage]; 
1.251     brouard  4784:        }
1.265     brouard  4785:        for(s1=1; s1 <=nlstate ; s1++){
1.251     brouard  4786:          for(m=-1, pos=0; m <=0 ; m++)
1.265     brouard  4787:            pos += freq[s1][m][iage];
                   4788:          if(pp[s1]>=1.e-10){
1.251     brouard  4789:            if(first==1){
1.265     brouard  4790:              printf(" %d.=%.0f loss[%d]=%.1f%%",s1,pp[s1],s1,100*pos/pp[s1]);
1.251     brouard  4791:            }
1.265     brouard  4792:            fprintf(ficlog," %d.=%.0f loss[%d]=%.1f%%",s1,pp[s1],s1,100*pos/pp[s1]);
1.251     brouard  4793:          }else{
                   4794:            if(first==1)
1.265     brouard  4795:              printf(" %d.=%.0f loss[%d]=NaNQ%%",s1,pp[s1],s1);
                   4796:            fprintf(ficlog," %d.=%.0f loss[%d]=NaNQ%%",s1,pp[s1],s1);
1.240     brouard  4797:          }
                   4798:        }
                   4799:       
1.265     brouard  4800:        for(s1=1; s1 <=nlstate ; s1++){ 
                   4801:          /* posprop[s1]=0; */
                   4802:          for(m=0, pp[s1]=0; m <=nlstate+ndeath; m++)/* Summing on all ages */
                   4803:            pp[s1] += freq[s1][m][iage];
                   4804:        }       /* pp[s1] is the total number of transitions starting from state s1 and any ending status until this age */
                   4805:       
                   4806:        for(s1=1,pos=0, pospropta=0.; s1 <=nlstate ; s1++){
                   4807:          pos += pp[s1]; /* pos is the total number of transitions until this age */
                   4808:          posprop[s1] += prop[s1][iage]; /* prop is the number of transitions from a live state
                   4809:                                            from s1 at age iage prop[s[m][iind]][(int)agev[m][iind]] += weight[iind] */
                   4810:          pospropta += prop[s1][iage]; /* prop is the number of transitions from a live state
                   4811:                                          from s1 at age iage prop[s[m][iind]][(int)agev[m][iind]] += weight[iind] */
                   4812:        }
                   4813:        
                   4814:        /* Writing ficresp */
                   4815:        if(cptcoveff==0 && nj==1){ /* no covariate and first pass */
                   4816:           if( iage <= iagemax){
                   4817:            fprintf(ficresp," %d",iage);
                   4818:           }
                   4819:         }else if( nj==2){
                   4820:           if( iage <= iagemax){
                   4821:            fprintf(ficresp," %d",iage);
                   4822:             for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresp, " %d %d",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
                   4823:           }
1.240     brouard  4824:        }
1.265     brouard  4825:        for(s1=1; s1 <=nlstate ; s1++){
1.240     brouard  4826:          if(pos>=1.e-5){
1.251     brouard  4827:            if(first==1)
1.265     brouard  4828:              printf(" %d.=%.0f prev[%d]=%.1f%%",s1,pp[s1],s1,100*pp[s1]/pos);
                   4829:            fprintf(ficlog," %d.=%.0f prev[%d]=%.1f%%",s1,pp[s1],s1,100*pp[s1]/pos);
1.251     brouard  4830:          }else{
                   4831:            if(first==1)
1.265     brouard  4832:              printf(" %d.=%.0f prev[%d]=NaNQ%%",s1,pp[s1],s1);
                   4833:            fprintf(ficlog," %d.=%.0f prev[%d]=NaNQ%%",s1,pp[s1],s1);
1.251     brouard  4834:          }
                   4835:          if( iage <= iagemax){
                   4836:            if(pos>=1.e-5){
1.265     brouard  4837:              if(cptcoveff==0 && nj==1){ /* no covariate and first pass */
                   4838:                fprintf(ficresp," %.5f %.0f %.0f",prop[s1][iage]/pospropta, prop[s1][iage],pospropta);
                   4839:               }else if( nj==2){
                   4840:                fprintf(ficresp," %.5f %.0f %.0f",prop[s1][iage]/pospropta, prop[s1][iage],pospropta);
                   4841:               }
                   4842:              fprintf(ficresphtm,"<th>%d</th><td>%.5f</td><td>%.0f</td><td>%.0f</td>",iage,prop[s1][iage]/pospropta, prop[s1][iage],pospropta);
                   4843:              /*probs[iage][s1][j1]= pp[s1]/pos;*/
                   4844:              /*printf("\niage=%d s1=%d j1=%d %.5f %.0f %.0f %f",iage,s1,j1,pp[s1]/pos, pp[s1],pos,probs[iage][s1][j1]);*/
                   4845:            } else{
                   4846:              if((cptcoveff==0 && nj==1)|| nj==2 ) fprintf(ficresp," NaNq %.0f %.0f",prop[s1][iage],pospropta);
                   4847:              fprintf(ficresphtm,"<th>%d</th><td>NaNq</td><td>%.0f</td><td>%.0f</td>",iage, prop[s1][iage],pospropta);
1.251     brouard  4848:            }
1.240     brouard  4849:          }
1.265     brouard  4850:          pospropt[s1] +=posprop[s1];
                   4851:        } /* end loop s1 */
1.251     brouard  4852:        /* pospropt=0.; */
1.265     brouard  4853:        for(s1=-1; s1 <=nlstate+ndeath; s1++){
1.251     brouard  4854:          for(m=-1; m <=nlstate+ndeath; m++){
1.265     brouard  4855:            if(freq[s1][m][iage] !=0 ) { /* minimizing output */
1.251     brouard  4856:              if(first==1){
1.265     brouard  4857:                printf(" %d%d=%.0f",s1,m,freq[s1][m][iage]);
1.251     brouard  4858:              }
1.265     brouard  4859:              /* printf(" %d%d=%.0f",s1,m,freq[s1][m][iage]); */
                   4860:              fprintf(ficlog," %d%d=%.0f",s1,m,freq[s1][m][iage]);
1.251     brouard  4861:            }
1.265     brouard  4862:            if(s1!=0 && m!=0)
                   4863:              fprintf(ficresphtmfr,"<td>%.0f</td> ",freq[s1][m][iage]);
1.240     brouard  4864:          }
1.265     brouard  4865:        } /* end loop s1 */
1.251     brouard  4866:        posproptt=0.; 
1.265     brouard  4867:        for(s1=1; s1 <=nlstate; s1++){
                   4868:          posproptt += pospropt[s1];
1.251     brouard  4869:        }
                   4870:        fprintf(ficresphtmfr,"</tr>\n ");
1.265     brouard  4871:        fprintf(ficresphtm,"</tr>\n");
                   4872:        if((cptcoveff==0 && nj==1)|| nj==2 ) {
                   4873:          if(iage <= iagemax)
                   4874:            fprintf(ficresp,"\n");
1.240     brouard  4875:        }
1.251     brouard  4876:        if(first==1)
                   4877:          printf("Others in log...\n");
                   4878:        fprintf(ficlog,"\n");
                   4879:       } /* end loop age iage */
1.265     brouard  4880:       
1.251     brouard  4881:       fprintf(ficresphtm,"<tr><th>Tot</th>");
1.265     brouard  4882:       for(s1=1; s1 <=nlstate ; s1++){
1.251     brouard  4883:        if(posproptt < 1.e-5){
1.265     brouard  4884:          fprintf(ficresphtm,"<td>Nanq</td><td>%.0f</td><td>%.0f</td>",pospropt[s1],posproptt); 
1.251     brouard  4885:        }else{
1.265     brouard  4886:          fprintf(ficresphtm,"<td>%.5f</td><td>%.0f</td><td>%.0f</td>",pospropt[s1]/posproptt,pospropt[s1],posproptt);  
1.240     brouard  4887:        }
1.226     brouard  4888:       }
1.251     brouard  4889:       fprintf(ficresphtm,"</tr>\n");
                   4890:       fprintf(ficresphtm,"</table>\n");
                   4891:       fprintf(ficresphtmfr,"</table>\n");
1.226     brouard  4892:       if(posproptt < 1.e-5){
1.251     brouard  4893:        fprintf(ficresphtm,"\n <p><b> This combination (%d) is not valid and no result will be produced</b></p>",j1);
                   4894:        fprintf(ficresphtmfr,"\n <p><b> This combination (%d) is not valid and no result will be produced</b></p>",j1);
1.260     brouard  4895:        fprintf(ficlog,"#  This combination (%d) is not valid and no result will be produced\n",j1);
                   4896:        printf("#  This combination (%d) is not valid and no result will be produced\n",j1);
1.251     brouard  4897:        invalidvarcomb[j1]=1;
1.226     brouard  4898:       }else{
1.251     brouard  4899:        fprintf(ficresphtm,"\n <p> This combination (%d) is valid and result will be produced.</p>",j1);
                   4900:        invalidvarcomb[j1]=0;
1.226     brouard  4901:       }
1.251     brouard  4902:       fprintf(ficresphtmfr,"</table>\n");
                   4903:       fprintf(ficlog,"\n");
                   4904:       if(j!=0){
                   4905:        printf("#Freqsummary: Starting values for combination j1=%d:\n", j1);
1.265     brouard  4906:        for(i=1,s1=1; i <=nlstate; i++){
1.251     brouard  4907:          for(k=1; k <=(nlstate+ndeath); k++){
                   4908:            if (k != i) {
1.265     brouard  4909:              for(jj=1; jj <=ncovmodel; jj++){ /* For counting s1 */
1.253     brouard  4910:                if(jj==1){  /* Constant case (in fact cste + age) */
1.251     brouard  4911:                  if(j1==1){ /* All dummy covariates to zero */
                   4912:                    freq[i][k][iagemax+4]=freq[i][k][iagemax+3]; /* Stores case 0 0 0 */
                   4913:                    freq[i][i][iagemax+4]=freq[i][i][iagemax+3]; /* Stores case 0 0 0 */
1.252     brouard  4914:                    printf("%d%d ",i,k);
                   4915:                    fprintf(ficlog,"%d%d ",i,k);
1.265     brouard  4916:                    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]));
                   4917:                    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]));
                   4918:                    pstart[s1]= log(freq[i][k][iagemax+3]/freq[i][i][iagemax+3]);
1.251     brouard  4919:                  }
1.253     brouard  4920:                }else if((j1==1) && (jj==2 || nagesqr==1)){ /* age or age*age parameter without covariate V4*age (to be done later) */
                   4921:                  for(iage=iagemin; iage <= iagemax+3; iage++){
                   4922:                    x[iage]= (double)iage;
                   4923:                    y[iage]= log(freq[i][k][iage]/freq[i][i][iage]);
1.265     brouard  4924:                    /* 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  4925:                  }
1.268     brouard  4926:                  /* Some are not finite, but linreg will ignore these ages */
                   4927:                  no=0;
1.253     brouard  4928:                  linreg(iagemin,iagemax,&no,x,y,&a,&b,&r, &sa, &sb ); /* y= a+b*x with standard errors */
1.265     brouard  4929:                  pstart[s1]=b;
                   4930:                  pstart[s1-1]=a;
1.252     brouard  4931:                }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 */ 
                   4932:                  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]);
                   4933:                  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  4934:                  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  4935:                  printf("%d%d ",i,k);
                   4936:                  fprintf(ficlog,"%d%d ",i,k);
1.265     brouard  4937:                  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  4938:                }else{ /* Other cases, like quantitative fixed or varying covariates */
                   4939:                  ;
                   4940:                }
                   4941:                /* printf("%12.7f )", param[i][jj][k]); */
                   4942:                /* fprintf(ficlog,"%12.7f )", param[i][jj][k]); */
1.265     brouard  4943:                s1++; 
1.251     brouard  4944:              } /* end jj */
                   4945:            } /* end k!= i */
                   4946:          } /* end k */
1.265     brouard  4947:        } /* end i, s1 */
1.251     brouard  4948:       } /* end j !=0 */
                   4949:     } /* end selected combination of covariate j1 */
                   4950:     if(j==0){ /* We can estimate starting values from the occurences in each case */
                   4951:       printf("#Freqsummary: Starting values for the constants:\n");
                   4952:       fprintf(ficlog,"\n");
1.265     brouard  4953:       for(i=1,s1=1; i <=nlstate; i++){
1.251     brouard  4954:        for(k=1; k <=(nlstate+ndeath); k++){
                   4955:          if (k != i) {
                   4956:            printf("%d%d ",i,k);
                   4957:            fprintf(ficlog,"%d%d ",i,k);
                   4958:            for(jj=1; jj <=ncovmodel; jj++){
1.265     brouard  4959:              pstart[s1]=p[s1]; /* Setting pstart to p values by default */
1.253     brouard  4960:              if(jj==1){ /* Age has to be done */
1.265     brouard  4961:                pstart[s1]= log(freq[i][k][iagemax+3]/freq[i][i][iagemax+3]);
                   4962:                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]));
                   4963:                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  4964:              }
                   4965:              /* printf("%12.7f )", param[i][jj][k]); */
                   4966:              /* fprintf(ficlog,"%12.7f )", param[i][jj][k]); */
1.265     brouard  4967:              s1++; 
1.250     brouard  4968:            }
1.251     brouard  4969:            printf("\n");
                   4970:            fprintf(ficlog,"\n");
1.250     brouard  4971:          }
                   4972:        }
1.284     brouard  4973:       } /* end of state i */
1.251     brouard  4974:       printf("#Freqsummary\n");
                   4975:       fprintf(ficlog,"\n");
1.265     brouard  4976:       for(s1=-1; s1 <=nlstate+ndeath; s1++){
                   4977:        for(s2=-1; s2 <=nlstate+ndeath; s2++){
                   4978:          /* param[i]|j][k]= freq[s1][s2][iagemax+3] */
                   4979:          printf(" %d%d=%.0f",s1,s2,freq[s1][s2][iagemax+3]);
                   4980:          fprintf(ficlog," %d%d=%.0f",s1,s2,freq[s1][s2][iagemax+3]);
                   4981:          /* if(freq[s1][s2][iage] !=0 ) { /\* minimizing output *\/ */
                   4982:          /*   printf(" %d%d=%.0f",s1,s2,freq[s1][s2][iagemax+3]); */
                   4983:          /*   fprintf(ficlog," %d%d=%.0f",s1,s2,freq[s1][s2][iagemax+3]); */
1.251     brouard  4984:          /* } */
                   4985:        }
1.265     brouard  4986:       } /* end loop s1 */
1.251     brouard  4987:       
                   4988:       printf("\n");
                   4989:       fprintf(ficlog,"\n");
                   4990:     } /* end j=0 */
1.249     brouard  4991:   } /* end j */
1.252     brouard  4992: 
1.253     brouard  4993:   if(mle == -2){  /* We want to use these values as starting values */
1.252     brouard  4994:     for(i=1, jk=1; i <=nlstate; i++){
                   4995:       for(j=1; j <=nlstate+ndeath; j++){
                   4996:        if(j!=i){
                   4997:          /*ca[0]= k+'a'-1;ca[1]='\0';*/
                   4998:          printf("%1d%1d",i,j);
                   4999:          fprintf(ficparo,"%1d%1d",i,j);
                   5000:          for(k=1; k<=ncovmodel;k++){
                   5001:            /*    printf(" %lf",param[i][j][k]); */
                   5002:            /*    fprintf(ficparo," %lf",param[i][j][k]); */
                   5003:            p[jk]=pstart[jk];
                   5004:            printf(" %f ",pstart[jk]);
                   5005:            fprintf(ficparo," %f ",pstart[jk]);
                   5006:            jk++;
                   5007:          }
                   5008:          printf("\n");
                   5009:          fprintf(ficparo,"\n");
                   5010:        }
                   5011:       }
                   5012:     }
                   5013:   } /* end mle=-2 */
1.226     brouard  5014:   dateintmean=dateintsum/k2cpt; 
1.296     brouard  5015:   date2dmy(dateintmean,&jintmean,&mintmean,&aintmean);
1.240     brouard  5016:   
1.226     brouard  5017:   fclose(ficresp);
                   5018:   fclose(ficresphtm);
                   5019:   fclose(ficresphtmfr);
1.283     brouard  5020:   free_vector(idq,1,nqfveff);
1.226     brouard  5021:   free_vector(meanq,1,nqfveff);
1.284     brouard  5022:   free_vector(stdq,1,nqfveff);
1.226     brouard  5023:   free_matrix(meanqt,1,lastpass,1,nqtveff);
1.253     brouard  5024:   free_vector(x, iagemin-AGEMARGE, iagemax+4+AGEMARGE);
                   5025:   free_vector(y, iagemin-AGEMARGE, iagemax+4+AGEMARGE);
1.251     brouard  5026:   free_ma3x(freq,-5,nlstate+ndeath,-5,nlstate+ndeath, iagemin-AGEMARGE, iagemax+4+AGEMARGE);
1.226     brouard  5027:   free_vector(pospropt,1,nlstate);
                   5028:   free_vector(posprop,1,nlstate);
1.251     brouard  5029:   free_matrix(prop,1,nlstate,iagemin-AGEMARGE, iagemax+4+AGEMARGE);
1.226     brouard  5030:   free_vector(pp,1,nlstate);
                   5031:   /* End of freqsummary */
                   5032: }
1.126     brouard  5033: 
1.268     brouard  5034: /* Simple linear regression */
                   5035: int linreg(int ifi, int ila, int *no, const double x[], const double y[], double* a, double* b, double* r, double* sa, double * sb) {
                   5036: 
                   5037:   /* y=a+bx regression */
                   5038:   double   sumx = 0.0;                        /* sum of x                      */
                   5039:   double   sumx2 = 0.0;                       /* sum of x**2                   */
                   5040:   double   sumxy = 0.0;                       /* sum of x * y                  */
                   5041:   double   sumy = 0.0;                        /* sum of y                      */
                   5042:   double   sumy2 = 0.0;                       /* sum of y**2                   */
                   5043:   double   sume2 = 0.0;                       /* sum of square or residuals */
                   5044:   double yhat;
                   5045:   
                   5046:   double denom=0;
                   5047:   int i;
                   5048:   int ne=*no;
                   5049:   
                   5050:   for ( i=ifi, ne=0;i<=ila;i++) {
                   5051:     if(!isfinite(x[i]) || !isfinite(y[i])){
                   5052:       /* printf(" x[%d]=%f, y[%d]=%f\n",i,x[i],i,y[i]); */
                   5053:       continue;
                   5054:     }
                   5055:     ne=ne+1;
                   5056:     sumx  += x[i];       
                   5057:     sumx2 += x[i]*x[i];  
                   5058:     sumxy += x[i] * y[i];
                   5059:     sumy  += y[i];      
                   5060:     sumy2 += y[i]*y[i]; 
                   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:   
                   5065:   denom = (ne * sumx2 - sumx*sumx);
                   5066:   if (denom == 0) {
                   5067:     // vertical, slope m is infinity
                   5068:     *b = INFINITY;
                   5069:     *a = 0;
                   5070:     if (r) *r = 0;
                   5071:     return 1;
                   5072:   }
                   5073:   
                   5074:   *b = (ne * sumxy  -  sumx * sumy) / denom;
                   5075:   *a = (sumy * sumx2  -  sumx * sumxy) / denom;
                   5076:   if (r!=NULL) {
                   5077:     *r = (sumxy - sumx * sumy / ne) /          /* compute correlation coeff     */
                   5078:       sqrt((sumx2 - sumx*sumx/ne) *
                   5079:           (sumy2 - sumy*sumy/ne));
                   5080:   }
                   5081:   *no=ne;
                   5082:   for ( i=ifi, ne=0;i<=ila;i++) {
                   5083:     if(!isfinite(x[i]) || !isfinite(y[i])){
                   5084:       /* printf(" x[%d]=%f, y[%d]=%f\n",i,x[i],i,y[i]); */
                   5085:       continue;
                   5086:     }
                   5087:     ne=ne+1;
                   5088:     yhat = y[i] - *a -*b* x[i];
                   5089:     sume2  += yhat * yhat ;       
                   5090:     
                   5091:     denom = (ne * sumx2 - sumx*sumx);
                   5092:     /* 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); */
                   5093:   } 
                   5094:   *sb = sqrt(sume2/(double)(ne-2)/(sumx2 - sumx * sumx /(double)ne));
                   5095:   *sa= *sb * sqrt(sumx2/ne);
                   5096:   
                   5097:   return 0; 
                   5098: }
                   5099: 
1.126     brouard  5100: /************ Prevalence ********************/
1.227     brouard  5101: 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)
                   5102: {  
                   5103:   /* Compute observed prevalence between dateprev1 and dateprev2 by counting the number of people
                   5104:      in each health status at the date of interview (if between dateprev1 and dateprev2).
                   5105:      We still use firstpass and lastpass as another selection.
                   5106:   */
1.126     brouard  5107:  
1.227     brouard  5108:   int i, m, jk, j1, bool, z1,j, iv;
                   5109:   int mi; /* Effective wave */
                   5110:   int iage;
                   5111:   double agebegin, ageend;
                   5112: 
                   5113:   double **prop;
                   5114:   double posprop; 
                   5115:   double  y2; /* in fractional years */
                   5116:   int iagemin, iagemax;
                   5117:   int first; /** to stop verbosity which is redirected to log file */
                   5118: 
                   5119:   iagemin= (int) agemin;
                   5120:   iagemax= (int) agemax;
                   5121:   /*pp=vector(1,nlstate);*/
1.251     brouard  5122:   prop=matrix(1,nlstate,iagemin-AGEMARGE,iagemax+4+AGEMARGE); 
1.227     brouard  5123:   /*  freq=ma3x(-1,nlstate+ndeath,-1,nlstate+ndeath,iagemin,iagemax+3);*/
                   5124:   j1=0;
1.222     brouard  5125:   
1.227     brouard  5126:   /*j=cptcoveff;*/
                   5127:   if (cptcovn<1) {j=1;ncodemax[1]=1;}
1.222     brouard  5128:   
1.288     brouard  5129:   first=0;
1.227     brouard  5130:   for(j1=1; j1<= (int) pow(2,cptcoveff);j1++){ /* For each combination of covariate */
                   5131:     for (i=1; i<=nlstate; i++)  
1.251     brouard  5132:       for(iage=iagemin-AGEMARGE; iage <= iagemax+4+AGEMARGE; iage++)
1.227     brouard  5133:        prop[i][iage]=0.0;
                   5134:     printf("Prevalence combination of varying and fixed dummies %d\n",j1);
                   5135:     /* fprintf(ficlog," V%d=%d ",Tvaraff[j1],nbcode[Tvaraff[j1]][codtabm(k,j1)]); */
                   5136:     fprintf(ficlog,"Prevalence combination of varying and fixed dummies %d\n",j1);
                   5137:     
                   5138:     for (i=1; i<=imx; i++) { /* Each individual */
                   5139:       bool=1;
                   5140:       /* for(m=firstpass; m<=lastpass; m++){/\* Other selection (we can limit to certain interviews*\/ */
                   5141:       for(mi=1; mi<wav[i];mi++){ /* For this wave too look where individual can be counted V4=0 V3=0 */
                   5142:        m=mw[mi][i];
                   5143:        /* Tmodelind[z1]=k is the position of the varying covariate in the model, but which # within 1 to ntv? */
                   5144:        /* Tvar[Tmodelind[z1]] is the n of Vn; n-ncovcol-nqv is the first time varying covariate or iv */
                   5145:        for (z1=1; z1<=cptcoveff; z1++){
                   5146:          if( Fixed[Tmodelind[z1]]==1){
                   5147:            iv= Tvar[Tmodelind[z1]]-ncovcol-nqv;
                   5148:            if (cotvar[m][iv][i]!= nbcode[Tvaraff[z1]][codtabm(j1,z1)]) /* iv=1 to ntv, right modality */
                   5149:              bool=0;
                   5150:          }else if( Fixed[Tmodelind[z1]]== 0)  /* fixed */
                   5151:            if (covar[Tvaraff[z1]][i]!= nbcode[Tvaraff[z1]][codtabm(j1,z1)]) {
                   5152:              bool=0;
                   5153:            }
                   5154:        }
                   5155:        if(bool==1){ /* Otherwise we skip that wave/person */
                   5156:          agebegin=agev[m][i]; /* Age at beginning of wave before transition*/
                   5157:          /* ageend=agev[m][i]+(dh[m][i])*stepm/YEARM; /\* Age at end of wave and transition *\/ */
                   5158:          if(m >=firstpass && m <=lastpass){
                   5159:            y2=anint[m][i]+(mint[m][i]/12.); /* Fractional date in year */
                   5160:            if ((y2>=dateprev1) && (y2<=dateprev2)) { /* Here is the main selection (fractional years) */
                   5161:              if(agev[m][i]==0) agev[m][i]=iagemax+1;
                   5162:              if(agev[m][i]==1) agev[m][i]=iagemax+2;
1.251     brouard  5163:              if((int)agev[m][i] <iagemin-AGEMARGE || (int)agev[m][i] >iagemax+4+AGEMARGE){
1.227     brouard  5164:                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); 
                   5165:                exit(1);
                   5166:              }
                   5167:              if (s[m][i]>0 && s[m][i]<=nlstate) { 
                   5168:                /*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]]);*/
                   5169:                prop[s[m][i]][(int)agev[m][i]] += weight[i];/* At age of beginning of transition, where status is known */
                   5170:                prop[s[m][i]][iagemax+3] += weight[i]; 
                   5171:              } /* end valid statuses */ 
                   5172:            } /* end selection of dates */
                   5173:          } /* end selection of waves */
                   5174:        } /* end bool */
                   5175:       } /* end wave */
                   5176:     } /* end individual */
                   5177:     for(i=iagemin; i <= iagemax+3; i++){  
                   5178:       for(jk=1,posprop=0; jk <=nlstate ; jk++) { 
                   5179:        posprop += prop[jk][i]; 
                   5180:       } 
                   5181:       
                   5182:       for(jk=1; jk <=nlstate ; jk++){      
                   5183:        if( i <=  iagemax){ 
                   5184:          if(posprop>=1.e-5){ 
                   5185:            probs[i][jk][j1]= prop[jk][i]/posprop;
                   5186:          } else{
1.288     brouard  5187:            if(!first){
                   5188:              first=1;
1.266     brouard  5189:              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]);
                   5190:            }else{
1.288     brouard  5191:              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  5192:            }
                   5193:          }
                   5194:        } 
                   5195:       }/* end jk */ 
                   5196:     }/* end i */ 
1.222     brouard  5197:      /*} *//* end i1 */
1.227     brouard  5198:   } /* end j1 */
1.222     brouard  5199:   
1.227     brouard  5200:   /*  free_ma3x(freq,-1,nlstate+ndeath,-1,nlstate+ndeath, iagemin, iagemax+3);*/
                   5201:   /*free_vector(pp,1,nlstate);*/
1.251     brouard  5202:   free_matrix(prop,1,nlstate, iagemin-AGEMARGE,iagemax+4+AGEMARGE);
1.227     brouard  5203: }  /* End of prevalence */
1.126     brouard  5204: 
                   5205: /************* Waves Concatenation ***************/
                   5206: 
                   5207: 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)
                   5208: {
1.298   ! brouard  5209:   /* Concatenates waves: wav[i] is the number of effective (useful waves in the sense that a non interview is useless) of individual i.
1.126     brouard  5210:      Death is a valid wave (if date is known).
                   5211:      mw[mi][i] is the mi (mi=1 to wav[i])  effective wave of individual i
                   5212:      dh[m][i] or dh[mw[mi][i]][i] is the delay between two effective waves m=mw[mi][i]
1.298   ! brouard  5213:      and mw[mi+1][i]. dh depends on stepm. s[m][i] exists for any wave from firstpass to lastpass
1.227     brouard  5214:   */
1.126     brouard  5215: 
1.224     brouard  5216:   int i=0, mi=0, m=0, mli=0;
1.126     brouard  5217:   /* int j, k=0,jk, ju, jl,jmin=1e+5, jmax=-1;
                   5218:      double sum=0., jmean=0.;*/
1.224     brouard  5219:   int first=0, firstwo=0, firsthree=0, firstfour=0, firstfiv=0;
1.126     brouard  5220:   int j, k=0,jk, ju, jl;
                   5221:   double sum=0.;
                   5222:   first=0;
1.214     brouard  5223:   firstwo=0;
1.217     brouard  5224:   firsthree=0;
1.218     brouard  5225:   firstfour=0;
1.164     brouard  5226:   jmin=100000;
1.126     brouard  5227:   jmax=-1;
                   5228:   jmean=0.;
1.224     brouard  5229: 
                   5230: /* Treating live states */
1.214     brouard  5231:   for(i=1; i<=imx; i++){  /* For simple cases and if state is death */
1.224     brouard  5232:     mi=0;  /* First valid wave */
1.227     brouard  5233:     mli=0; /* Last valid wave */
1.126     brouard  5234:     m=firstpass;
1.214     brouard  5235:     while(s[m][i] <= nlstate){  /* a live state */
1.227     brouard  5236:       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 */
                   5237:        mli=m-1;/* mw[++mi][i]=m-1; */
                   5238:       }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 */
                   5239:        mw[++mi][i]=m;
                   5240:        mli=m;
1.224     brouard  5241:       } /* else might be a useless wave  -1 and mi is not incremented and mw[mi] not updated */
                   5242:       if(m < lastpass){ /* m < lastpass, standard case */
1.227     brouard  5243:        m++; /* mi gives the "effective" current wave, m the current wave, go to next wave by incrementing m */
1.216     brouard  5244:       }
1.227     brouard  5245:       else{ /* m >= lastpass, eventual special issue with warning */
1.224     brouard  5246: #ifdef UNKNOWNSTATUSNOTCONTRIBUTING
1.227     brouard  5247:        break;
1.224     brouard  5248: #else
1.227     brouard  5249:        if(s[m][i]==-1 && (int) andc[i] == 9999 && (int)anint[m][i] != 9999){
                   5250:          if(firsthree == 0){
1.262     brouard  5251:            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  5252:            firsthree=1;
                   5253:          }
1.262     brouard  5254:          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  5255:          mw[++mi][i]=m;
                   5256:          mli=m;
                   5257:        }
                   5258:        if(s[m][i]==-2){ /* Vital status is really unknown */
                   5259:          nbwarn++;
                   5260:          if((int)anint[m][i] == 9999){  /*  Has the vital status really been verified? */
                   5261:            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);
                   5262:            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);
                   5263:          }
                   5264:          break;
                   5265:        }
                   5266:        break;
1.224     brouard  5267: #endif
1.227     brouard  5268:       }/* End m >= lastpass */
1.126     brouard  5269:     }/* end while */
1.224     brouard  5270: 
1.227     brouard  5271:     /* 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  5272:     /* After last pass */
1.224     brouard  5273: /* Treating death states */
1.214     brouard  5274:     if (s[m][i] > nlstate){  /* In a death state */
1.227     brouard  5275:       /* if( mint[m][i]==mdc[m][i] && anint[m][i]==andc[m][i]){ /\* same date of death and date of interview *\/ */
                   5276:       /* } */
1.126     brouard  5277:       mi++;    /* Death is another wave */
                   5278:       /* if(mi==0)  never been interviewed correctly before death */
1.227     brouard  5279:       /* Only death is a correct wave */
1.126     brouard  5280:       mw[mi][i]=m;
1.257     brouard  5281:     } /* else not in a death state */
1.224     brouard  5282: #ifndef DISPATCHINGKNOWNDEATHAFTERLASTWAVE
1.257     brouard  5283:     else if ((int) andc[i] != 9999) {  /* Date of death is known */
1.218     brouard  5284:       if ((int)anint[m][i]!= 9999) { /* date of last interview is known */
1.227     brouard  5285:        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 */
                   5286:          nbwarn++;
                   5287:          if(firstfiv==0){
                   5288:            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 );
                   5289:            firstfiv=1;
                   5290:          }else{
                   5291:            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 );
                   5292:          }
                   5293:        }else{ /* Death occured afer last wave potential bias */
                   5294:          nberr++;
                   5295:          if(firstwo==0){
1.257     brouard  5296:            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  5297:            firstwo=1;
                   5298:          }
1.257     brouard  5299:          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  5300:        }
1.257     brouard  5301:       }else{ /* if date of interview is unknown */
1.227     brouard  5302:        /* death is known but not confirmed by death status at any wave */
                   5303:        if(firstfour==0){
                   5304:          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 );
                   5305:          firstfour=1;
                   5306:        }
                   5307:        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  5308:       }
1.224     brouard  5309:     } /* end if date of death is known */
                   5310: #endif
                   5311:     wav[i]=mi; /* mi should be the last effective wave (or mli) */
                   5312:     /* wav[i]=mw[mi][i]; */
1.126     brouard  5313:     if(mi==0){
                   5314:       nbwarn++;
                   5315:       if(first==0){
1.227     brouard  5316:        printf("Warning! No valid information for individual %ld line=%d (skipped) and may be others, see log file\n",num[i],i);
                   5317:        first=1;
1.126     brouard  5318:       }
                   5319:       if(first==1){
1.227     brouard  5320:        fprintf(ficlog,"Warning! No valid information for individual %ld line=%d (skipped)\n",num[i],i);
1.126     brouard  5321:       }
                   5322:     } /* end mi==0 */
                   5323:   } /* End individuals */
1.214     brouard  5324:   /* wav and mw are no more changed */
1.223     brouard  5325:        
1.214     brouard  5326:   
1.126     brouard  5327:   for(i=1; i<=imx; i++){
                   5328:     for(mi=1; mi<wav[i];mi++){
                   5329:       if (stepm <=0)
1.227     brouard  5330:        dh[mi][i]=1;
1.126     brouard  5331:       else{
1.260     brouard  5332:        if (s[mw[mi+1][i]][i] > nlstate) { /* A death, but what if date is unknown? */
1.227     brouard  5333:          if (agedc[i] < 2*AGESUP) {
                   5334:            j= rint(agedc[i]*12-agev[mw[mi][i]][i]*12); 
                   5335:            if(j==0) j=1;  /* Survives at least one month after exam */
                   5336:            else if(j<0){
                   5337:              nberr++;
                   5338:              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]);
                   5339:              j=1; /* Temporary Dangerous patch */
                   5340:              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);
                   5341:              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]);
                   5342:              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);
                   5343:            }
                   5344:            k=k+1;
                   5345:            if (j >= jmax){
                   5346:              jmax=j;
                   5347:              ijmax=i;
                   5348:            }
                   5349:            if (j <= jmin){
                   5350:              jmin=j;
                   5351:              ijmin=i;
                   5352:            }
                   5353:            sum=sum+j;
                   5354:            /*if (j<0) printf("j=%d num=%d \n",j,i);*/
                   5355:            /*    printf("%d %d %d %d\n", s[mw[mi][i]][i] ,s[mw[mi+1][i]][i],j,i);*/
                   5356:          }
                   5357:        }
                   5358:        else{
                   5359:          j= rint( (agev[mw[mi+1][i]][i]*12 - agev[mw[mi][i]][i]*12));
1.126     brouard  5360: /*       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  5361:                                        
1.227     brouard  5362:          k=k+1;
                   5363:          if (j >= jmax) {
                   5364:            jmax=j;
                   5365:            ijmax=i;
                   5366:          }
                   5367:          else if (j <= jmin){
                   5368:            jmin=j;
                   5369:            ijmin=i;
                   5370:          }
                   5371:          /*        if (j<10) printf("j=%d jmin=%d num=%d ",j,jmin,i); */
                   5372:          /*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]);*/
                   5373:          if(j<0){
                   5374:            nberr++;
                   5375:            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]);
                   5376:            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]);
                   5377:          }
                   5378:          sum=sum+j;
                   5379:        }
                   5380:        jk= j/stepm;
                   5381:        jl= j -jk*stepm;
                   5382:        ju= j -(jk+1)*stepm;
                   5383:        if(mle <=1){ /* only if we use a the linear-interpoloation pseudo-likelihood */
                   5384:          if(jl==0){
                   5385:            dh[mi][i]=jk;
                   5386:            bh[mi][i]=0;
                   5387:          }else{ /* We want a negative bias in order to only have interpolation ie
                   5388:                  * to avoid the price of an extra matrix product in likelihood */
                   5389:            dh[mi][i]=jk+1;
                   5390:            bh[mi][i]=ju;
                   5391:          }
                   5392:        }else{
                   5393:          if(jl <= -ju){
                   5394:            dh[mi][i]=jk;
                   5395:            bh[mi][i]=jl;       /* bias is positive if real duration
                   5396:                                 * is higher than the multiple of stepm and negative otherwise.
                   5397:                                 */
                   5398:          }
                   5399:          else{
                   5400:            dh[mi][i]=jk+1;
                   5401:            bh[mi][i]=ju;
                   5402:          }
                   5403:          if(dh[mi][i]==0){
                   5404:            dh[mi][i]=1; /* At least one step */
                   5405:            bh[mi][i]=ju; /* At least one step */
                   5406:            /*  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);*/
                   5407:          }
                   5408:        } /* end if mle */
1.126     brouard  5409:       }
                   5410:     } /* end wave */
                   5411:   }
                   5412:   jmean=sum/k;
                   5413:   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  5414:   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  5415: }
1.126     brouard  5416: 
                   5417: /*********** Tricode ****************************/
1.220     brouard  5418:  void tricode(int *cptcov, int *Tvar, int **nbcode, int imx, int *Ndum)
1.242     brouard  5419:  {
                   5420:    /**< Uses cptcovn+2*cptcovprod as the number of covariates */
                   5421:    /*    Tvar[i]=atoi(stre);  find 'n' in Vn and stores in Tvar. If model=V2+V1 Tvar[1]=2 and Tvar[2]=1 
                   5422:     * Boring subroutine which should only output nbcode[Tvar[j]][k]
                   5423:     * Tvar[5] in V2+V1+V3*age+V2*V4 is 4 (V4) even it is a time varying or quantitative variable
                   5424:     * nbcode[Tvar[5]][1]= nbcode[4][1]=0, nbcode[4][2]=1 (usually);
                   5425:     */
1.130     brouard  5426: 
1.242     brouard  5427:    int ij=1, k=0, j=0, i=0, maxncov=NCOVMAX;
                   5428:    int modmaxcovj=0; /* Modality max of covariates j */
                   5429:    int cptcode=0; /* Modality max of covariates j */
                   5430:    int modmincovj=0; /* Modality min of covariates j */
1.145     brouard  5431: 
                   5432: 
1.242     brouard  5433:    /* cptcoveff=0;  */
                   5434:    /* *cptcov=0; */
1.126     brouard  5435:  
1.242     brouard  5436:    for (k=1; k <= maxncov; k++) ncodemax[k]=0; /* Horrible constant again replaced by NCOVMAX */
1.285     brouard  5437:    for (k=1; k <= maxncov; k++)
                   5438:      for(j=1; j<=2; j++)
                   5439:        nbcode[k][j]=0; /* Valgrind */
1.126     brouard  5440: 
1.242     brouard  5441:    /* Loop on covariates without age and products and no quantitative variable */
                   5442:    for (k=1; k<=cptcovt; k++) { /* From model V1 + V2*age + V3 + V3*V4 keeps V1 + V3 = 2 only */
                   5443:      for (j=-1; (j < maxncov); j++) Ndum[j]=0;
                   5444:      if(Dummy[k]==0 && Typevar[k] !=1){ /* Dummy covariate and not age product */ 
                   5445:        switch(Fixed[k]) {
                   5446:        case 0: /* Testing on fixed dummy covariate, simple or product of fixed */
                   5447:         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*/
                   5448:           ij=(int)(covar[Tvar[k]][i]);
                   5449:           /* ij=0 or 1 or -1. Value of the covariate Tvar[j] for individual i
                   5450:            * If product of Vn*Vm, still boolean *:
                   5451:            * If it was coded 1, 2, 3, 4 should be splitted into 3 boolean variables
                   5452:            * 1 => 0 0 0, 2 => 0 0 1, 3 => 0 1 1, 4=1 0 0   */
                   5453:           /* Finds for covariate j, n=Tvar[j] of Vn . ij is the
                   5454:              modality of the nth covariate of individual i. */
                   5455:           if (ij > modmaxcovj)
                   5456:             modmaxcovj=ij; 
                   5457:           else if (ij < modmincovj) 
                   5458:             modmincovj=ij; 
1.287     brouard  5459:           if (ij <0 || ij >1 ){
                   5460:             printf("Information, IMaCh doesn't treat covariate with missing values (-1), individual %d will be skipped.\n",i);
                   5461:             fprintf(ficlog,"Information, currently IMaCh doesn't treat covariate with missing values (-1), individual %d will be skipped.\n",i);
                   5462:           }
                   5463:           if ((ij < -1) || (ij > NCOVMAX)){
1.242     brouard  5464:             printf( "Error: minimal is less than -1 or maximal is bigger than %d. Exiting. \n", NCOVMAX );
                   5465:             exit(1);
                   5466:           }else
                   5467:             Ndum[ij]++; /*counts and stores the occurence of this modality 0, 1, -1*/
                   5468:           /*  If coded 1, 2, 3 , counts the number of 1 Ndum[1], number of 2, Ndum[2], etc */
                   5469:           /*printf("i=%d ij=%d Ndum[ij]=%d imx=%d",i,ij,Ndum[ij],imx);*/
                   5470:           /* getting the maximum value of the modality of the covariate
                   5471:              (should be 0 or 1 now) Tvar[j]. If V=sex and male is coded 0 and
                   5472:              female ies 1, then modmaxcovj=1.
                   5473:           */
                   5474:         } /* end for loop on individuals i */
                   5475:         printf(" Minimal and maximal values of %d th (fixed) covariate V%d: min=%d max=%d \n", k, Tvar[k], modmincovj, modmaxcovj);
                   5476:         fprintf(ficlog," Minimal and maximal values of %d th (fixed) covariate V%d: min=%d max=%d \n", k, Tvar[k], modmincovj, modmaxcovj);
                   5477:         cptcode=modmaxcovj;
                   5478:         /* Ndum[0] = frequency of 0 for model-covariate j, Ndum[1] frequency of 1 etc. */
                   5479:         /*for (i=0; i<=cptcode; i++) {*/
                   5480:         for (j=modmincovj;  j<=modmaxcovj; j++) { /* j=-1 ? 0 and 1*//* For each value j of the modality of model-cov k */
                   5481:           printf("Frequencies of (fixed) covariate %d ie V%d with value %d: %d\n", k, Tvar[k], j, Ndum[j]);
                   5482:           fprintf(ficlog, "Frequencies of (fixed) covariate %d ie V%d with value %d: %d\n", k, Tvar[k], j, Ndum[j]);
                   5483:           if( Ndum[j] != 0 ){ /* Counts if nobody answered modality j ie empty modality, we skip it and reorder */
                   5484:             if( j != -1){
                   5485:               ncodemax[k]++;  /* ncodemax[k]= Number of modalities of the k th
                   5486:                                  covariate for which somebody answered excluding 
                   5487:                                  undefined. Usually 2: 0 and 1. */
                   5488:             }
                   5489:             ncodemaxwundef[k]++; /* ncodemax[j]= Number of modalities of the k th
                   5490:                                     covariate for which somebody answered including 
                   5491:                                     undefined. Usually 3: -1, 0 and 1. */
                   5492:           }    /* In fact  ncodemax[k]=2 (dichotom. variables only) but it could be more for
                   5493:                 * historical reasons: 3 if coded 1, 2, 3 and 4 and Ndum[2]=0 */
                   5494:         } /* Ndum[-1] number of undefined modalities */
1.231     brouard  5495:                        
1.242     brouard  5496:         /* j is a covariate, n=Tvar[j] of Vn; Fills nbcode */
                   5497:         /* For covariate j, modalities could be 1, 2, 3, 4, 5, 6, 7. */
                   5498:         /* If Ndum[1]=0, Ndum[2]=0, Ndum[3]= 635, Ndum[4]=0, Ndum[5]=0, Ndum[6]=27, Ndum[7]=125; */
                   5499:         /* modmincovj=3; modmaxcovj = 7; */
                   5500:         /* There are only 3 modalities non empty 3, 6, 7 (or 2 if 27 is too few) : ncodemax[j]=3; */
                   5501:         /* which will be coded 0, 1, 2 which in binary on 2=3-1 digits are 0=00 1=01, 2=10; */
                   5502:         /*              defining two dummy variables: variables V1_1 and V1_2.*/
                   5503:         /* nbcode[Tvar[j]][ij]=k; */
                   5504:         /* nbcode[Tvar[j]][1]=0; */
                   5505:         /* nbcode[Tvar[j]][2]=1; */
                   5506:         /* nbcode[Tvar[j]][3]=2; */
                   5507:         /* To be continued (not working yet). */
                   5508:         ij=0; /* ij is similar to i but can jump over null modalities */
1.287     brouard  5509: 
                   5510:         /* 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*/
                   5511:         /* Skipping the case of missing values by reducing nbcode to 0 and 1 and not -1, 0, 1 */
                   5512:         /* model=V1+V2+V3, if V2=-1, 0 or 1, then nbcode[2][1]=0 and nbcode[2][2]=1 instead of
                   5513:          * nbcode[2][1]=-1, nbcode[2][2]=0 and nbcode[2][3]=1 */
                   5514:         /*, could be restored in the future */
                   5515:         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  5516:           if (Ndum[i] == 0) { /* If nobody responded to this modality k */
                   5517:             break;
                   5518:           }
                   5519:           ij++;
1.287     brouard  5520:           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  5521:           cptcode = ij; /* New max modality for covar j */
                   5522:         } /* end of loop on modality i=-1 to 1 or more */
                   5523:         break;
                   5524:        case 1: /* Testing on varying covariate, could be simple and
                   5525:                * should look at waves or product of fixed *
                   5526:                * varying. No time to test -1, assuming 0 and 1 only */
                   5527:         ij=0;
                   5528:         for(i=0; i<=1;i++){
                   5529:           nbcode[Tvar[k]][++ij]=i;
                   5530:         }
                   5531:         break;
                   5532:        default:
                   5533:         break;
                   5534:        } /* end switch */
                   5535:      } /* end dummy test */
1.287     brouard  5536:    } /* 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  5537:   
                   5538:    for (k=-1; k< maxncov; k++) Ndum[k]=0; 
                   5539:    /* Look at fixed dummy (single or product) covariates to check empty modalities */
                   5540:    for (i=1; i<=ncovmodel-2-nagesqr; i++) { /* -2, cste and age and eventually age*age */ 
                   5541:      /* Listing of all covariables in statement model to see if some covariates appear twice. For example, V1 appears twice in V1+V1*V2.*/ 
                   5542:      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 */ 
                   5543:      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 */
                   5544:      /* V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1,  {2, 1, 1, 1, 2, 1, 1, 0, 0} */
                   5545:    } /* V4+V3+V5, Ndum[1]@5={0, 0, 1, 1, 1} */
                   5546:   
                   5547:    ij=0;
                   5548:    /* for (i=0; i<=  maxncov-1; i++) { /\* modmaxcovj is unknown here. Only Ndum[2(V2),3(age*V3), 5(V3*V2) 6(V1*V4) *\/ */
                   5549:    for (k=1; k<=  cptcovt; k++) { /* modmaxcovj is unknown here. Only Ndum[2(V2),3(age*V3), 5(V3*V2) 6(V1*V4) */
                   5550:      /*printf("Ndum[%d]=%d\n",i, Ndum[i]);*/
                   5551:      /* if((Ndum[i]!=0) && (i<=ncovcol)){  /\* Tvar[i] <= ncovmodel ? *\/ */
                   5552:      if(Ndum[Tvar[k]]!=0 && Dummy[k] == 0 && Typevar[k]==0){  /* Only Dummy and non empty in the model */
                   5553:        /* If product not in single variable we don't print results */
                   5554:        /*printf("diff Ndum[%d]=%d\n",i, Ndum[i]);*/
                   5555:        ++ij;/* V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1, */
                   5556:        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*/
                   5557:        Tmodelind[ij]=k; /* Tmodelind: index in model of dummies Tmodelind[1]=2 V4: pos=2; V3: pos=3, V1=9 {2, 3, 9, ?, ?,} */
                   5558:        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 */
                   5559:        if(Fixed[k]!=0)
                   5560:         anyvaryingduminmodel=1;
                   5561:        /* }else if((Ndum[i]!=0) && (i<=ncovcol+nqv)){ */
                   5562:        /*   Tvaraff[++ij]=-10; /\* Dont'n know how to treat quantitative variables yet *\/ */
                   5563:        /* }else if((Ndum[i]!=0) && (i<=ncovcol+nqv+ntv)){ */
                   5564:        /*   Tvaraff[++ij]=i; /\*For printing (unclear) *\/ */
                   5565:        /* }else if((Ndum[i]!=0) && (i<=ncovcol+nqv+ntv+nqtv)){ */
                   5566:        /*   Tvaraff[++ij]=-20; /\* Dont'n know how to treat quantitative variables yet *\/ */
                   5567:      } 
                   5568:    } /* Tvaraff[1]@5 {3, 4, -20, 0, 0} Very strange */
                   5569:    /* ij--; */
                   5570:    /* cptcoveff=ij; /\*Number of total covariates*\/ */
                   5571:    *cptcov=ij; /*Number of total real effective covariates: effective
                   5572:                * because they can be excluded from the model and real
                   5573:                * if in the model but excluded because missing values, but how to get k from ij?*/
                   5574:    for(j=ij+1; j<= cptcovt; j++){
                   5575:      Tvaraff[j]=0;
                   5576:      Tmodelind[j]=0;
                   5577:    }
                   5578:    for(j=ntveff+1; j<= cptcovt; j++){
                   5579:      TmodelInvind[j]=0;
                   5580:    }
                   5581:    /* To be sorted */
                   5582:    ;
                   5583:  }
1.126     brouard  5584: 
1.145     brouard  5585: 
1.126     brouard  5586: /*********** Health Expectancies ****************/
                   5587: 
1.235     brouard  5588:  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  5589: 
                   5590: {
                   5591:   /* Health expectancies, no variances */
1.164     brouard  5592:   int i, j, nhstepm, hstepm, h, nstepm;
1.126     brouard  5593:   int nhstepma, nstepma; /* Decreasing with age */
                   5594:   double age, agelim, hf;
                   5595:   double ***p3mat;
                   5596:   double eip;
                   5597: 
1.238     brouard  5598:   /* pstamp(ficreseij); */
1.126     brouard  5599:   fprintf(ficreseij,"# (a) Life expectancies by health status at initial age and (b) health expectancies by health status at initial age\n");
                   5600:   fprintf(ficreseij,"# Age");
                   5601:   for(i=1; i<=nlstate;i++){
                   5602:     for(j=1; j<=nlstate;j++){
                   5603:       fprintf(ficreseij," e%1d%1d ",i,j);
                   5604:     }
                   5605:     fprintf(ficreseij," e%1d. ",i);
                   5606:   }
                   5607:   fprintf(ficreseij,"\n");
                   5608: 
                   5609:   
                   5610:   if(estepm < stepm){
                   5611:     printf ("Problem %d lower than %d\n",estepm, stepm);
                   5612:   }
                   5613:   else  hstepm=estepm;   
                   5614:   /* We compute the life expectancy from trapezoids spaced every estepm months
                   5615:    * This is mainly to measure the difference between two models: for example
                   5616:    * if stepm=24 months pijx are given only every 2 years and by summing them
                   5617:    * we are calculating an estimate of the Life Expectancy assuming a linear 
                   5618:    * progression in between and thus overestimating or underestimating according
                   5619:    * to the curvature of the survival function. If, for the same date, we 
                   5620:    * estimate the model with stepm=1 month, we can keep estepm to 24 months
                   5621:    * to compare the new estimate of Life expectancy with the same linear 
                   5622:    * hypothesis. A more precise result, taking into account a more precise
                   5623:    * curvature will be obtained if estepm is as small as stepm. */
                   5624: 
                   5625:   /* For example we decided to compute the life expectancy with the smallest unit */
                   5626:   /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm. 
                   5627:      nhstepm is the number of hstepm from age to agelim 
                   5628:      nstepm is the number of stepm from age to agelin. 
1.270     brouard  5629:      Look at hpijx to understand the reason which relies in memory size consideration
1.126     brouard  5630:      and note for a fixed period like estepm months */
                   5631:   /* We decided (b) to get a life expectancy respecting the most precise curvature of the
                   5632:      survival function given by stepm (the optimization length). Unfortunately it
                   5633:      means that if the survival funtion is printed only each two years of age and if
                   5634:      you sum them up and add 1 year (area under the trapezoids) you won't get the same 
                   5635:      results. So we changed our mind and took the option of the best precision.
                   5636:   */
                   5637:   hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */ 
                   5638: 
                   5639:   agelim=AGESUP;
                   5640:   /* If stepm=6 months */
                   5641:     /* Computed by stepm unit matrices, product of hstepm matrices, stored
                   5642:        in an array of nhstepm length: nhstepm=10, hstepm=4, stepm=6 months */
                   5643:     
                   5644: /* nhstepm age range expressed in number of stepm */
                   5645:   nstepm=(int) rint((agelim-bage)*YEARM/stepm); /* Biggest nstepm */
                   5646:   /* Typically if 20 years nstepm = 20*12/6=40 stepm */ 
                   5647:   /* if (stepm >= YEARM) hstepm=1;*/
                   5648:   nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
                   5649:   p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   5650: 
                   5651:   for (age=bage; age<=fage; age ++){ 
                   5652:     nstepma=(int) rint((agelim-bage)*YEARM/stepm); /* Biggest nstepm */
                   5653:     /* Typically if 20 years nstepm = 20*12/6=40 stepm */ 
                   5654:     /* if (stepm >= YEARM) hstepm=1;*/
                   5655:     nhstepma = nstepma/hstepm;/* Expressed in hstepm, typically nhstepma=40/4=10 */
                   5656: 
                   5657:     /* If stepm=6 months */
                   5658:     /* Computed by stepm unit matrices, product of hstepma matrices, stored
                   5659:        in an array of nhstepma length: nhstepma=10, hstepm=4, stepm=6 months */
                   5660:     
1.235     brouard  5661:     hpxij(p3mat,nhstepma,age,hstepm,x,nlstate,stepm,oldm, savm, cij, nres);  
1.126     brouard  5662:     
                   5663:     hf=hstepm*stepm/YEARM;  /* Duration of hstepm expressed in year unit. */
                   5664:     
                   5665:     printf("%d|",(int)age);fflush(stdout);
                   5666:     fprintf(ficlog,"%d|",(int)age);fflush(ficlog);
                   5667:     
                   5668:     /* Computing expectancies */
                   5669:     for(i=1; i<=nlstate;i++)
                   5670:       for(j=1; j<=nlstate;j++)
                   5671:        for (h=0, eij[i][j][(int)age]=0; h<=nhstepm-1; h++){
                   5672:          eij[i][j][(int)age] += (p3mat[i][j][h]+p3mat[i][j][h+1])/2.0*hf;
                   5673:          
                   5674:          /* 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]);*/
                   5675: 
                   5676:        }
                   5677: 
                   5678:     fprintf(ficreseij,"%3.0f",age );
                   5679:     for(i=1; i<=nlstate;i++){
                   5680:       eip=0;
                   5681:       for(j=1; j<=nlstate;j++){
                   5682:        eip +=eij[i][j][(int)age];
                   5683:        fprintf(ficreseij,"%9.4f", eij[i][j][(int)age] );
                   5684:       }
                   5685:       fprintf(ficreseij,"%9.4f", eip );
                   5686:     }
                   5687:     fprintf(ficreseij,"\n");
                   5688:     
                   5689:   }
                   5690:   free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   5691:   printf("\n");
                   5692:   fprintf(ficlog,"\n");
                   5693:   
                   5694: }
                   5695: 
1.235     brouard  5696:  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  5697: 
                   5698: {
                   5699:   /* Covariances of health expectancies eij and of total life expectancies according
1.222     brouard  5700:      to initial status i, ei. .
1.126     brouard  5701:   */
                   5702:   int i, j, nhstepm, hstepm, h, nstepm, k, cptj, cptj2, i2, j2, ij, ji;
                   5703:   int nhstepma, nstepma; /* Decreasing with age */
                   5704:   double age, agelim, hf;
                   5705:   double ***p3matp, ***p3matm, ***varhe;
                   5706:   double **dnewm,**doldm;
                   5707:   double *xp, *xm;
                   5708:   double **gp, **gm;
                   5709:   double ***gradg, ***trgradg;
                   5710:   int theta;
                   5711: 
                   5712:   double eip, vip;
                   5713: 
                   5714:   varhe=ma3x(1,nlstate*nlstate,1,nlstate*nlstate,(int) bage, (int) fage);
                   5715:   xp=vector(1,npar);
                   5716:   xm=vector(1,npar);
                   5717:   dnewm=matrix(1,nlstate*nlstate,1,npar);
                   5718:   doldm=matrix(1,nlstate*nlstate,1,nlstate*nlstate);
                   5719:   
                   5720:   pstamp(ficresstdeij);
                   5721:   fprintf(ficresstdeij,"# Health expectancies with standard errors\n");
                   5722:   fprintf(ficresstdeij,"# Age");
                   5723:   for(i=1; i<=nlstate;i++){
                   5724:     for(j=1; j<=nlstate;j++)
                   5725:       fprintf(ficresstdeij," e%1d%1d (SE)",i,j);
                   5726:     fprintf(ficresstdeij," e%1d. ",i);
                   5727:   }
                   5728:   fprintf(ficresstdeij,"\n");
                   5729: 
                   5730:   pstamp(ficrescveij);
                   5731:   fprintf(ficrescveij,"# Subdiagonal matrix of covariances of health expectancies by age: cov(eij,ekl)\n");
                   5732:   fprintf(ficrescveij,"# Age");
                   5733:   for(i=1; i<=nlstate;i++)
                   5734:     for(j=1; j<=nlstate;j++){
                   5735:       cptj= (j-1)*nlstate+i;
                   5736:       for(i2=1; i2<=nlstate;i2++)
                   5737:        for(j2=1; j2<=nlstate;j2++){
                   5738:          cptj2= (j2-1)*nlstate+i2;
                   5739:          if(cptj2 <= cptj)
                   5740:            fprintf(ficrescveij,"  %1d%1d,%1d%1d",i,j,i2,j2);
                   5741:        }
                   5742:     }
                   5743:   fprintf(ficrescveij,"\n");
                   5744:   
                   5745:   if(estepm < stepm){
                   5746:     printf ("Problem %d lower than %d\n",estepm, stepm);
                   5747:   }
                   5748:   else  hstepm=estepm;   
                   5749:   /* We compute the life expectancy from trapezoids spaced every estepm months
                   5750:    * This is mainly to measure the difference between two models: for example
                   5751:    * if stepm=24 months pijx are given only every 2 years and by summing them
                   5752:    * we are calculating an estimate of the Life Expectancy assuming a linear 
                   5753:    * progression in between and thus overestimating or underestimating according
                   5754:    * to the curvature of the survival function. If, for the same date, we 
                   5755:    * estimate the model with stepm=1 month, we can keep estepm to 24 months
                   5756:    * to compare the new estimate of Life expectancy with the same linear 
                   5757:    * hypothesis. A more precise result, taking into account a more precise
                   5758:    * curvature will be obtained if estepm is as small as stepm. */
                   5759: 
                   5760:   /* For example we decided to compute the life expectancy with the smallest unit */
                   5761:   /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm. 
                   5762:      nhstepm is the number of hstepm from age to agelim 
                   5763:      nstepm is the number of stepm from age to agelin. 
                   5764:      Look at hpijx to understand the reason of that which relies in memory size
                   5765:      and note for a fixed period like estepm months */
                   5766:   /* We decided (b) to get a life expectancy respecting the most precise curvature of the
                   5767:      survival function given by stepm (the optimization length). Unfortunately it
                   5768:      means that if the survival funtion is printed only each two years of age and if
                   5769:      you sum them up and add 1 year (area under the trapezoids) you won't get the same 
                   5770:      results. So we changed our mind and took the option of the best precision.
                   5771:   */
                   5772:   hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */ 
                   5773: 
                   5774:   /* If stepm=6 months */
                   5775:   /* nhstepm age range expressed in number of stepm */
                   5776:   agelim=AGESUP;
                   5777:   nstepm=(int) rint((agelim-bage)*YEARM/stepm); 
                   5778:   /* Typically if 20 years nstepm = 20*12/6=40 stepm */ 
                   5779:   /* if (stepm >= YEARM) hstepm=1;*/
                   5780:   nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
                   5781:   
                   5782:   p3matp=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   5783:   p3matm=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   5784:   gradg=ma3x(0,nhstepm,1,npar,1,nlstate*nlstate);
                   5785:   trgradg =ma3x(0,nhstepm,1,nlstate*nlstate,1,npar);
                   5786:   gp=matrix(0,nhstepm,1,nlstate*nlstate);
                   5787:   gm=matrix(0,nhstepm,1,nlstate*nlstate);
                   5788: 
                   5789:   for (age=bage; age<=fage; age ++){ 
                   5790:     nstepma=(int) rint((agelim-bage)*YEARM/stepm); /* Biggest nstepm */
                   5791:     /* Typically if 20 years nstepm = 20*12/6=40 stepm */ 
                   5792:     /* if (stepm >= YEARM) hstepm=1;*/
                   5793:     nhstepma = nstepma/hstepm;/* Expressed in hstepm, typically nhstepma=40/4=10 */
1.218     brouard  5794:                
1.126     brouard  5795:     /* If stepm=6 months */
                   5796:     /* Computed by stepm unit matrices, product of hstepma matrices, stored
                   5797:        in an array of nhstepma length: nhstepma=10, hstepm=4, stepm=6 months */
                   5798:     
                   5799:     hf=hstepm*stepm/YEARM;  /* Duration of hstepm expressed in year unit. */
1.218     brouard  5800:                
1.126     brouard  5801:     /* Computing  Variances of health expectancies */
                   5802:     /* Gradient is computed with plus gp and minus gm. Code is duplicated in order to
                   5803:        decrease memory allocation */
                   5804:     for(theta=1; theta <=npar; theta++){
                   5805:       for(i=1; i<=npar; i++){ 
1.222     brouard  5806:        xp[i] = x[i] + (i==theta ?delti[theta]:0);
                   5807:        xm[i] = x[i] - (i==theta ?delti[theta]:0);
1.126     brouard  5808:       }
1.235     brouard  5809:       hpxij(p3matp,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, cij, nres);  
                   5810:       hpxij(p3matm,nhstepm,age,hstepm,xm,nlstate,stepm,oldm,savm, cij, nres);  
1.218     brouard  5811:                        
1.126     brouard  5812:       for(j=1; j<= nlstate; j++){
1.222     brouard  5813:        for(i=1; i<=nlstate; i++){
                   5814:          for(h=0; h<=nhstepm-1; h++){
                   5815:            gp[h][(j-1)*nlstate + i] = (p3matp[i][j][h]+p3matp[i][j][h+1])/2.;
                   5816:            gm[h][(j-1)*nlstate + i] = (p3matm[i][j][h]+p3matm[i][j][h+1])/2.;
                   5817:          }
                   5818:        }
1.126     brouard  5819:       }
1.218     brouard  5820:                        
1.126     brouard  5821:       for(ij=1; ij<= nlstate*nlstate; ij++)
1.222     brouard  5822:        for(h=0; h<=nhstepm-1; h++){
                   5823:          gradg[h][theta][ij]= (gp[h][ij]-gm[h][ij])/2./delti[theta];
                   5824:        }
1.126     brouard  5825:     }/* End theta */
                   5826:     
                   5827:     
                   5828:     for(h=0; h<=nhstepm-1; h++)
                   5829:       for(j=1; j<=nlstate*nlstate;j++)
1.222     brouard  5830:        for(theta=1; theta <=npar; theta++)
                   5831:          trgradg[h][j][theta]=gradg[h][theta][j];
1.126     brouard  5832:     
1.218     brouard  5833:                
1.222     brouard  5834:     for(ij=1;ij<=nlstate*nlstate;ij++)
1.126     brouard  5835:       for(ji=1;ji<=nlstate*nlstate;ji++)
1.222     brouard  5836:        varhe[ij][ji][(int)age] =0.;
1.218     brouard  5837:                
1.222     brouard  5838:     printf("%d|",(int)age);fflush(stdout);
                   5839:     fprintf(ficlog,"%d|",(int)age);fflush(ficlog);
                   5840:     for(h=0;h<=nhstepm-1;h++){
1.126     brouard  5841:       for(k=0;k<=nhstepm-1;k++){
1.222     brouard  5842:        matprod2(dnewm,trgradg[h],1,nlstate*nlstate,1,npar,1,npar,matcov);
                   5843:        matprod2(doldm,dnewm,1,nlstate*nlstate,1,npar,1,nlstate*nlstate,gradg[k]);
                   5844:        for(ij=1;ij<=nlstate*nlstate;ij++)
                   5845:          for(ji=1;ji<=nlstate*nlstate;ji++)
                   5846:            varhe[ij][ji][(int)age] += doldm[ij][ji]*hf*hf;
1.126     brouard  5847:       }
                   5848:     }
1.218     brouard  5849:                
1.126     brouard  5850:     /* Computing expectancies */
1.235     brouard  5851:     hpxij(p3matm,nhstepm,age,hstepm,x,nlstate,stepm,oldm, savm, cij,nres);  
1.126     brouard  5852:     for(i=1; i<=nlstate;i++)
                   5853:       for(j=1; j<=nlstate;j++)
1.222     brouard  5854:        for (h=0, eij[i][j][(int)age]=0; h<=nhstepm-1; h++){
                   5855:          eij[i][j][(int)age] += (p3matm[i][j][h]+p3matm[i][j][h+1])/2.0*hf;
1.218     brouard  5856:                                        
1.222     brouard  5857:          /* 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  5858:                                        
1.222     brouard  5859:        }
1.269     brouard  5860: 
                   5861:     /* Standard deviation of expectancies ij */                
1.126     brouard  5862:     fprintf(ficresstdeij,"%3.0f",age );
                   5863:     for(i=1; i<=nlstate;i++){
                   5864:       eip=0.;
                   5865:       vip=0.;
                   5866:       for(j=1; j<=nlstate;j++){
1.222     brouard  5867:        eip += eij[i][j][(int)age];
                   5868:        for(k=1; k<=nlstate;k++) /* Sum on j and k of cov(eij,eik) */
                   5869:          vip += varhe[(j-1)*nlstate+i][(k-1)*nlstate+i][(int)age];
                   5870:        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  5871:       }
                   5872:       fprintf(ficresstdeij," %9.4f (%.4f)", eip, sqrt(vip));
                   5873:     }
                   5874:     fprintf(ficresstdeij,"\n");
1.218     brouard  5875:                
1.269     brouard  5876:     /* Variance of expectancies ij */          
1.126     brouard  5877:     fprintf(ficrescveij,"%3.0f",age );
                   5878:     for(i=1; i<=nlstate;i++)
                   5879:       for(j=1; j<=nlstate;j++){
1.222     brouard  5880:        cptj= (j-1)*nlstate+i;
                   5881:        for(i2=1; i2<=nlstate;i2++)
                   5882:          for(j2=1; j2<=nlstate;j2++){
                   5883:            cptj2= (j2-1)*nlstate+i2;
                   5884:            if(cptj2 <= cptj)
                   5885:              fprintf(ficrescveij," %.4f", varhe[cptj][cptj2][(int)age]);
                   5886:          }
1.126     brouard  5887:       }
                   5888:     fprintf(ficrescveij,"\n");
1.218     brouard  5889:                
1.126     brouard  5890:   }
                   5891:   free_matrix(gm,0,nhstepm,1,nlstate*nlstate);
                   5892:   free_matrix(gp,0,nhstepm,1,nlstate*nlstate);
                   5893:   free_ma3x(gradg,0,nhstepm,1,npar,1,nlstate*nlstate);
                   5894:   free_ma3x(trgradg,0,nhstepm,1,nlstate*nlstate,1,npar);
                   5895:   free_ma3x(p3matm,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   5896:   free_ma3x(p3matp,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   5897:   printf("\n");
                   5898:   fprintf(ficlog,"\n");
1.218     brouard  5899:        
1.126     brouard  5900:   free_vector(xm,1,npar);
                   5901:   free_vector(xp,1,npar);
                   5902:   free_matrix(dnewm,1,nlstate*nlstate,1,npar);
                   5903:   free_matrix(doldm,1,nlstate*nlstate,1,nlstate*nlstate);
                   5904:   free_ma3x(varhe,1,nlstate*nlstate,1,nlstate*nlstate,(int) bage, (int)fage);
                   5905: }
1.218     brouard  5906:  
1.126     brouard  5907: /************ Variance ******************/
1.235     brouard  5908:  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  5909:  {
1.279     brouard  5910:    /** Variance of health expectancies 
                   5911:     *  double **prevalim(double **prlim, int nlstate, double *xp, double age, double **oldm, double ** savm,double ftolpl);
                   5912:     * double **newm;
                   5913:     * int movingaverage(double ***probs, double bage,double fage, double ***mobaverage, int mobilav) 
                   5914:     */
1.218     brouard  5915:   
                   5916:    /* int movingaverage(); */
                   5917:    double **dnewm,**doldm;
                   5918:    double **dnewmp,**doldmp;
                   5919:    int i, j, nhstepm, hstepm, h, nstepm ;
1.288     brouard  5920:    int first=0;
1.218     brouard  5921:    int k;
                   5922:    double *xp;
1.279     brouard  5923:    double **gp, **gm;  /**< for var eij */
                   5924:    double ***gradg, ***trgradg; /**< for var eij */
                   5925:    double **gradgp, **trgradgp; /**< for var p point j */
                   5926:    double *gpp, *gmp; /**< for var p point j */
                   5927:    double **varppt; /**< for var p point j nlstate to nlstate+ndeath */
1.218     brouard  5928:    double ***p3mat;
                   5929:    double age,agelim, hf;
                   5930:    /* double ***mobaverage; */
                   5931:    int theta;
                   5932:    char digit[4];
                   5933:    char digitp[25];
                   5934: 
                   5935:    char fileresprobmorprev[FILENAMELENGTH];
                   5936: 
                   5937:    if(popbased==1){
                   5938:      if(mobilav!=0)
                   5939:        strcpy(digitp,"-POPULBASED-MOBILAV_");
                   5940:      else strcpy(digitp,"-POPULBASED-NOMOBIL_");
                   5941:    }
                   5942:    else 
                   5943:      strcpy(digitp,"-STABLBASED_");
1.126     brouard  5944: 
1.218     brouard  5945:    /* if (mobilav!=0) { */
                   5946:    /*   mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX); */
                   5947:    /*   if (movingaverage(probs, bage, fage, mobaverage,mobilav)!=0){ */
                   5948:    /*     fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav); */
                   5949:    /*     printf(" Error in movingaverage mobilav=%d\n",mobilav); */
                   5950:    /*   } */
                   5951:    /* } */
                   5952: 
                   5953:    strcpy(fileresprobmorprev,"PRMORPREV-"); 
                   5954:    sprintf(digit,"%-d",ij);
                   5955:    /*printf("DIGIT=%s, ij=%d ijr=%-d|\n",digit, ij,ij);*/
                   5956:    strcat(fileresprobmorprev,digit); /* Tvar to be done */
                   5957:    strcat(fileresprobmorprev,digitp); /* Popbased or not, mobilav or not */
                   5958:    strcat(fileresprobmorprev,fileresu);
                   5959:    if((ficresprobmorprev=fopen(fileresprobmorprev,"w"))==NULL) {
                   5960:      printf("Problem with resultfile: %s\n", fileresprobmorprev);
                   5961:      fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobmorprev);
                   5962:    }
                   5963:    printf("Computing total mortality p.j=w1*p1j+w2*p2j+..: result on file '%s' \n",fileresprobmorprev);
                   5964:    fprintf(ficlog,"Computing total mortality p.j=w1*p1j+w2*p2j+..: result on file '%s' \n",fileresprobmorprev);
                   5965:    pstamp(ficresprobmorprev);
                   5966:    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  5967:    fprintf(ficresprobmorprev,"# Selected quantitative variables and dummies");
                   5968:    for (j=1; j<= nsq; j++){ /* For each selected (single) quantitative value */
                   5969:      fprintf(ficresprobmorprev," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]);
                   5970:    }
                   5971:    for(j=1;j<=cptcoveff;j++) 
                   5972:      fprintf(ficresprobmorprev,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(ij,j)]);
                   5973:    fprintf(ficresprobmorprev,"\n");
                   5974: 
1.218     brouard  5975:    fprintf(ficresprobmorprev,"# Age cov=%-d",ij);
                   5976:    for(j=nlstate+1; j<=(nlstate+ndeath);j++){
                   5977:      fprintf(ficresprobmorprev," p.%-d SE",j);
                   5978:      for(i=1; i<=nlstate;i++)
                   5979:        fprintf(ficresprobmorprev," w%1d p%-d%-d",i,i,j);
                   5980:    }  
                   5981:    fprintf(ficresprobmorprev,"\n");
                   5982:   
                   5983:    fprintf(ficgp,"\n# Routine varevsij");
                   5984:    fprintf(ficgp,"\nunset title \n");
                   5985:    /* fprintf(fichtm, "#Local time at start: %s", strstart);*/
                   5986:    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");
                   5987:    fprintf(fichtm,"\n<br>%s  <br>\n",digitp);
1.279     brouard  5988: 
1.218     brouard  5989:    varppt = matrix(nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
                   5990:    pstamp(ficresvij);
                   5991:    fprintf(ficresvij,"# Variance and covariance of health expectancies e.j \n#  (weighted average of eij where weights are ");
                   5992:    if(popbased==1)
                   5993:      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);
                   5994:    else
                   5995:      fprintf(ficresvij,"the age specific period (stable) prevalences in each health state \n");
                   5996:    fprintf(ficresvij,"# Age");
                   5997:    for(i=1; i<=nlstate;i++)
                   5998:      for(j=1; j<=nlstate;j++)
                   5999:        fprintf(ficresvij," Cov(e.%1d, e.%1d)",i,j);
                   6000:    fprintf(ficresvij,"\n");
                   6001: 
                   6002:    xp=vector(1,npar);
                   6003:    dnewm=matrix(1,nlstate,1,npar);
                   6004:    doldm=matrix(1,nlstate,1,nlstate);
                   6005:    dnewmp= matrix(nlstate+1,nlstate+ndeath,1,npar);
                   6006:    doldmp= matrix(nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
                   6007: 
                   6008:    gradgp=matrix(1,npar,nlstate+1,nlstate+ndeath);
                   6009:    gpp=vector(nlstate+1,nlstate+ndeath);
                   6010:    gmp=vector(nlstate+1,nlstate+ndeath);
                   6011:    trgradgp =matrix(nlstate+1,nlstate+ndeath,1,npar); /* mu or p point j*/
1.126     brouard  6012:   
1.218     brouard  6013:    if(estepm < stepm){
                   6014:      printf ("Problem %d lower than %d\n",estepm, stepm);
                   6015:    }
                   6016:    else  hstepm=estepm;   
                   6017:    /* For example we decided to compute the life expectancy with the smallest unit */
                   6018:    /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm. 
                   6019:       nhstepm is the number of hstepm from age to agelim 
                   6020:       nstepm is the number of stepm from age to agelim. 
                   6021:       Look at function hpijx to understand why because of memory size limitations, 
                   6022:       we decided (b) to get a life expectancy respecting the most precise curvature of the
                   6023:       survival function given by stepm (the optimization length). Unfortunately it
                   6024:       means that if the survival funtion is printed every two years of age and if
                   6025:       you sum them up and add 1 year (area under the trapezoids) you won't get the same 
                   6026:       results. So we changed our mind and took the option of the best precision.
                   6027:    */
                   6028:    hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */ 
                   6029:    agelim = AGESUP;
                   6030:    for (age=bage; age<=fage; age ++){ /* If stepm=6 months */
                   6031:      nstepm=(int) rint((agelim-age)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */ 
                   6032:      nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
                   6033:      p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   6034:      gradg=ma3x(0,nhstepm,1,npar,1,nlstate);
                   6035:      gp=matrix(0,nhstepm,1,nlstate);
                   6036:      gm=matrix(0,nhstepm,1,nlstate);
                   6037:                
                   6038:                
                   6039:      for(theta=1; theta <=npar; theta++){
                   6040:        for(i=1; i<=npar; i++){ /* Computes gradient x + delta*/
                   6041:         xp[i] = x[i] + (i==theta ?delti[theta]:0);
                   6042:        }
1.279     brouard  6043:        /**< Computes the prevalence limit with parameter theta shifted of delta up to ftolpl precision and 
                   6044:        * returns into prlim .
1.288     brouard  6045:        */
1.242     brouard  6046:        prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp,ij, nres);
1.279     brouard  6047: 
                   6048:        /* If popbased = 1 we use crossection prevalences. Previous step is useless but prlim is created */
1.218     brouard  6049:        if (popbased==1) {
                   6050:         if(mobilav ==0){
                   6051:           for(i=1; i<=nlstate;i++)
                   6052:             prlim[i][i]=probs[(int)age][i][ij];
                   6053:         }else{ /* mobilav */ 
                   6054:           for(i=1; i<=nlstate;i++)
                   6055:             prlim[i][i]=mobaverage[(int)age][i][ij];
                   6056:         }
                   6057:        }
1.295     brouard  6058:        /**< Computes the shifted transition matrix \f$ {}{h}_p^{ij}x\f$ at horizon h.
1.279     brouard  6059:        */                      
                   6060:        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  6061:        /**< 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  6062:        * at horizon h in state j including mortality.
                   6063:        */
1.218     brouard  6064:        for(j=1; j<= nlstate; j++){
                   6065:         for(h=0; h<=nhstepm; h++){
                   6066:           for(i=1, gp[h][j]=0.;i<=nlstate;i++)
                   6067:             gp[h][j] += prlim[i][i]*p3mat[i][j][h];
                   6068:         }
                   6069:        }
1.279     brouard  6070:        /* Next for computing shifted+ probability of death (h=1 means
1.218     brouard  6071:          computed over hstepm matrices product = hstepm*stepm months) 
1.279     brouard  6072:          as a weighted average of prlim(i) * p(i,j) p.3=w1*p13 + w2*p23 .
1.218     brouard  6073:        */
                   6074:        for(j=nlstate+1;j<=nlstate+ndeath;j++){
                   6075:         for(i=1,gpp[j]=0.; i<= nlstate; i++)
                   6076:           gpp[j] += prlim[i][i]*p3mat[i][j][1];
1.279     brouard  6077:        }
                   6078:        
                   6079:        /* Again with minus shift */
1.218     brouard  6080:                        
                   6081:        for(i=1; i<=npar; i++) /* Computes gradient x - delta */
                   6082:         xp[i] = x[i] - (i==theta ?delti[theta]:0);
1.288     brouard  6083: 
1.242     brouard  6084:        prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp, ij, nres);
1.218     brouard  6085:                        
                   6086:        if (popbased==1) {
                   6087:         if(mobilav ==0){
                   6088:           for(i=1; i<=nlstate;i++)
                   6089:             prlim[i][i]=probs[(int)age][i][ij];
                   6090:         }else{ /* mobilav */ 
                   6091:           for(i=1; i<=nlstate;i++)
                   6092:             prlim[i][i]=mobaverage[(int)age][i][ij];
                   6093:         }
                   6094:        }
                   6095:                        
1.235     brouard  6096:        hpxij(p3mat,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, ij,nres);  
1.218     brouard  6097:                        
                   6098:        for(j=1; j<= nlstate; j++){  /* Sum of wi * eij = e.j */
                   6099:         for(h=0; h<=nhstepm; h++){
                   6100:           for(i=1, gm[h][j]=0.;i<=nlstate;i++)
                   6101:             gm[h][j] += prlim[i][i]*p3mat[i][j][h];
                   6102:         }
                   6103:        }
                   6104:        /* This for computing probability of death (h=1 means
                   6105:          computed over hstepm matrices product = hstepm*stepm months) 
                   6106:          as a weighted average of prlim.
                   6107:        */
                   6108:        for(j=nlstate+1;j<=nlstate+ndeath;j++){
                   6109:         for(i=1,gmp[j]=0.; i<= nlstate; i++)
                   6110:           gmp[j] += prlim[i][i]*p3mat[i][j][1];
                   6111:        }    
1.279     brouard  6112:        /* end shifting computations */
                   6113: 
                   6114:        /**< Computing gradient matrix at horizon h 
                   6115:        */
1.218     brouard  6116:        for(j=1; j<= nlstate; j++) /* vareij */
                   6117:         for(h=0; h<=nhstepm; h++){
                   6118:           gradg[h][theta][j]= (gp[h][j]-gm[h][j])/2./delti[theta];
                   6119:         }
1.279     brouard  6120:        /**< Gradient of overall mortality p.3 (or p.j) 
                   6121:        */
                   6122:        for(j=nlstate+1; j<= nlstate+ndeath; j++){ /* var mu mortality from j */
1.218     brouard  6123:         gradgp[theta][j]= (gpp[j]-gmp[j])/2./delti[theta];
                   6124:        }
                   6125:                        
                   6126:      } /* End theta */
1.279     brouard  6127:      
                   6128:      /* We got the gradient matrix for each theta and state j */               
1.218     brouard  6129:      trgradg =ma3x(0,nhstepm,1,nlstate,1,npar); /* veij */
                   6130:                
                   6131:      for(h=0; h<=nhstepm; h++) /* veij */
                   6132:        for(j=1; j<=nlstate;j++)
                   6133:         for(theta=1; theta <=npar; theta++)
                   6134:           trgradg[h][j][theta]=gradg[h][theta][j];
                   6135:                
                   6136:      for(j=nlstate+1; j<=nlstate+ndeath;j++) /* mu */
                   6137:        for(theta=1; theta <=npar; theta++)
                   6138:         trgradgp[j][theta]=gradgp[theta][j];
1.279     brouard  6139:      /**< as well as its transposed matrix 
                   6140:       */               
1.218     brouard  6141:                
                   6142:      hf=hstepm*stepm/YEARM;  /* Duration of hstepm expressed in year unit. */
                   6143:      for(i=1;i<=nlstate;i++)
                   6144:        for(j=1;j<=nlstate;j++)
                   6145:         vareij[i][j][(int)age] =0.;
1.279     brouard  6146: 
                   6147:      /* Computing trgradg by matcov by gradg at age and summing over h
                   6148:       * and k (nhstepm) formula 15 of article
                   6149:       * Lievre-Brouard-Heathcote
                   6150:       */
                   6151:      
1.218     brouard  6152:      for(h=0;h<=nhstepm;h++){
                   6153:        for(k=0;k<=nhstepm;k++){
                   6154:         matprod2(dnewm,trgradg[h],1,nlstate,1,npar,1,npar,matcov);
                   6155:         matprod2(doldm,dnewm,1,nlstate,1,npar,1,nlstate,gradg[k]);
                   6156:         for(i=1;i<=nlstate;i++)
                   6157:           for(j=1;j<=nlstate;j++)
                   6158:             vareij[i][j][(int)age] += doldm[i][j]*hf*hf;
                   6159:        }
                   6160:      }
                   6161:                
1.279     brouard  6162:      /* pptj is p.3 or p.j = trgradgp by cov by gradgp, variance of
                   6163:       * p.j overall mortality formula 49 but computed directly because
                   6164:       * we compute the grad (wix pijx) instead of grad (pijx),even if
                   6165:       * wix is independent of theta.
                   6166:       */
1.218     brouard  6167:      matprod2(dnewmp,trgradgp,nlstate+1,nlstate+ndeath,1,npar,1,npar,matcov);
                   6168:      matprod2(doldmp,dnewmp,nlstate+1,nlstate+ndeath,1,npar,nlstate+1,nlstate+ndeath,gradgp);
                   6169:      for(j=nlstate+1;j<=nlstate+ndeath;j++)
                   6170:        for(i=nlstate+1;i<=nlstate+ndeath;i++)
                   6171:         varppt[j][i]=doldmp[j][i];
                   6172:      /* end ppptj */
                   6173:      /*  x centered again */
                   6174:                
1.242     brouard  6175:      prevalim(prlim,nlstate,x,age,oldm,savm,ftolpl,ncvyearp,ij, nres);
1.218     brouard  6176:                
                   6177:      if (popbased==1) {
                   6178:        if(mobilav ==0){
                   6179:         for(i=1; i<=nlstate;i++)
                   6180:           prlim[i][i]=probs[(int)age][i][ij];
                   6181:        }else{ /* mobilav */ 
                   6182:         for(i=1; i<=nlstate;i++)
                   6183:           prlim[i][i]=mobaverage[(int)age][i][ij];
                   6184:        }
                   6185:      }
                   6186:                
                   6187:      /* This for computing probability of death (h=1 means
                   6188:        computed over hstepm (estepm) matrices product = hstepm*stepm months) 
                   6189:        as a weighted average of prlim.
                   6190:      */
1.235     brouard  6191:      hpxij(p3mat,nhstepm,age,hstepm,x,nlstate,stepm,oldm,savm, ij, nres);  
1.218     brouard  6192:      for(j=nlstate+1;j<=nlstate+ndeath;j++){
                   6193:        for(i=1,gmp[j]=0.;i<= nlstate; i++) 
                   6194:         gmp[j] += prlim[i][i]*p3mat[i][j][1]; 
                   6195:      }    
                   6196:      /* end probability of death */
                   6197:                
                   6198:      fprintf(ficresprobmorprev,"%3d %d ",(int) age, ij);
                   6199:      for(j=nlstate+1; j<=(nlstate+ndeath);j++){
                   6200:        fprintf(ficresprobmorprev," %11.3e %11.3e",gmp[j], sqrt(varppt[j][j]));
                   6201:        for(i=1; i<=nlstate;i++){
                   6202:         fprintf(ficresprobmorprev," %11.3e %11.3e ",prlim[i][i],p3mat[i][j][1]);
                   6203:        }
                   6204:      } 
                   6205:      fprintf(ficresprobmorprev,"\n");
                   6206:                
                   6207:      fprintf(ficresvij,"%.0f ",age );
                   6208:      for(i=1; i<=nlstate;i++)
                   6209:        for(j=1; j<=nlstate;j++){
                   6210:         fprintf(ficresvij," %.4f", vareij[i][j][(int)age]);
                   6211:        }
                   6212:      fprintf(ficresvij,"\n");
                   6213:      free_matrix(gp,0,nhstepm,1,nlstate);
                   6214:      free_matrix(gm,0,nhstepm,1,nlstate);
                   6215:      free_ma3x(gradg,0,nhstepm,1,npar,1,nlstate);
                   6216:      free_ma3x(trgradg,0,nhstepm,1,nlstate,1,npar);
                   6217:      free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   6218:    } /* End age */
                   6219:    free_vector(gpp,nlstate+1,nlstate+ndeath);
                   6220:    free_vector(gmp,nlstate+1,nlstate+ndeath);
                   6221:    free_matrix(gradgp,1,npar,nlstate+1,nlstate+ndeath);
                   6222:    free_matrix(trgradgp,nlstate+1,nlstate+ndeath,1,npar); /* mu or p point j*/
                   6223:    /* fprintf(ficgp,"\nunset parametric;unset label; set ter png small size 320, 240"); */
                   6224:    fprintf(ficgp,"\nunset parametric;unset label; set ter svg size 640, 480");
                   6225:    /* for(j=nlstate+1; j<= nlstate+ndeath; j++){ *//* Only the first actually */
                   6226:    fprintf(ficgp,"\n set log y; unset log x;set xlabel \"Age\"; set ylabel \"Force of mortality (year-1)\";");
                   6227:    fprintf(ficgp,"\nset out \"%s%s.svg\";",subdirf3(optionfilefiname,"VARMUPTJGR-",digitp),digit);
                   6228:    /*   fprintf(ficgp,"\n plot \"%s\"  u 1:($3*%6.3f) not w l 1 ",fileresprobmorprev,YEARM/estepm); */
                   6229:    /*   fprintf(ficgp,"\n replot \"%s\"  u 1:(($3+1.96*$4)*%6.3f) t \"95\%% interval\" w l 2 ",fileresprobmorprev,YEARM/estepm); */
                   6230:    /*   fprintf(ficgp,"\n replot \"%s\"  u 1:(($3-1.96*$4)*%6.3f) not w l 2 ",fileresprobmorprev,YEARM/estepm); */
                   6231:    fprintf(ficgp,"\n plot \"%s\"  u 1:($3) not w l lt 1 ",subdirf(fileresprobmorprev));
                   6232:    fprintf(ficgp,"\n replot \"%s\"  u 1:(($3+1.96*$4)) t \"95%% interval\" w l lt 2 ",subdirf(fileresprobmorprev));
                   6233:    fprintf(ficgp,"\n replot \"%s\"  u 1:(($3-1.96*$4)) not w l lt 2 ",subdirf(fileresprobmorprev));
                   6234:    fprintf(fichtm,"\n<br> File (multiple files are possible if covariates are present): <A href=\"%s\">%s</a>\n",subdirf(fileresprobmorprev),subdirf(fileresprobmorprev));
                   6235:    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);
                   6236:    /*  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  6237:     */
1.218     brouard  6238:    /*   fprintf(ficgp,"\nset out \"varmuptjgr%s%s%s.svg\";replot;",digitp,optionfilefiname,digit); */
                   6239:    fprintf(ficgp,"\nset out;\nset out \"%s%s.svg\";replot;set out;\n",subdirf3(optionfilefiname,"VARMUPTJGR-",digitp),digit);
1.126     brouard  6240: 
1.218     brouard  6241:    free_vector(xp,1,npar);
                   6242:    free_matrix(doldm,1,nlstate,1,nlstate);
                   6243:    free_matrix(dnewm,1,nlstate,1,npar);
                   6244:    free_matrix(doldmp,nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
                   6245:    free_matrix(dnewmp,nlstate+1,nlstate+ndeath,1,npar);
                   6246:    free_matrix(varppt,nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
                   6247:    /* if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX); */
                   6248:    fclose(ficresprobmorprev);
                   6249:    fflush(ficgp);
                   6250:    fflush(fichtm); 
                   6251:  }  /* end varevsij */
1.126     brouard  6252: 
                   6253: /************ Variance of prevlim ******************/
1.269     brouard  6254:  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  6255: {
1.205     brouard  6256:   /* Variance of prevalence limit  for each state ij using current parameters x[] and estimates of neighbourhood give by delti*/
1.126     brouard  6257:   /*  double **prevalim(double **prlim, int nlstate, double *xp, double age, double **oldm, double **savm,double ftolpl);*/
1.164     brouard  6258: 
1.268     brouard  6259:   double **dnewmpar,**doldm;
1.126     brouard  6260:   int i, j, nhstepm, hstepm;
                   6261:   double *xp;
                   6262:   double *gp, *gm;
                   6263:   double **gradg, **trgradg;
1.208     brouard  6264:   double **mgm, **mgp;
1.126     brouard  6265:   double age,agelim;
                   6266:   int theta;
                   6267:   
                   6268:   pstamp(ficresvpl);
1.288     brouard  6269:   fprintf(ficresvpl,"# Standard deviation of period (forward stable) prevalences \n");
1.241     brouard  6270:   fprintf(ficresvpl,"# Age ");
                   6271:   if(nresult >=1)
                   6272:     fprintf(ficresvpl," Result# ");
1.126     brouard  6273:   for(i=1; i<=nlstate;i++)
                   6274:       fprintf(ficresvpl," %1d-%1d",i,i);
                   6275:   fprintf(ficresvpl,"\n");
                   6276: 
                   6277:   xp=vector(1,npar);
1.268     brouard  6278:   dnewmpar=matrix(1,nlstate,1,npar);
1.126     brouard  6279:   doldm=matrix(1,nlstate,1,nlstate);
                   6280:   
                   6281:   hstepm=1*YEARM; /* Every year of age */
                   6282:   hstepm=hstepm/stepm; /* Typically in stepm units, if j= 2 years, = 2/6 months = 4 */ 
                   6283:   agelim = AGESUP;
                   6284:   for (age=bage; age<=fage; age ++){ /* If stepm=6 months */
                   6285:     nhstepm=(int) rint((agelim-age)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */ 
                   6286:     if (stepm >= YEARM) hstepm=1;
                   6287:     nhstepm = nhstepm/hstepm; /* Typically 40/4=10 */
                   6288:     gradg=matrix(1,npar,1,nlstate);
1.208     brouard  6289:     mgp=matrix(1,npar,1,nlstate);
                   6290:     mgm=matrix(1,npar,1,nlstate);
1.126     brouard  6291:     gp=vector(1,nlstate);
                   6292:     gm=vector(1,nlstate);
                   6293: 
                   6294:     for(theta=1; theta <=npar; theta++){
                   6295:       for(i=1; i<=npar; i++){ /* Computes gradient */
                   6296:        xp[i] = x[i] + (i==theta ?delti[theta]:0);
                   6297:       }
1.288     brouard  6298:       /* if((int)age==79 ||(int)age== 80 ||(int)age== 81 ) */
                   6299:       /*       prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp,ij,nres); */
                   6300:       /* else */
                   6301:       prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp,ij,nres);
1.208     brouard  6302:       for(i=1;i<=nlstate;i++){
1.126     brouard  6303:        gp[i] = prlim[i][i];
1.208     brouard  6304:        mgp[theta][i] = prlim[i][i];
                   6305:       }
1.126     brouard  6306:       for(i=1; i<=npar; i++) /* Computes gradient */
                   6307:        xp[i] = x[i] - (i==theta ?delti[theta]:0);
1.288     brouard  6308:       /* if((int)age==79 ||(int)age== 80 ||(int)age== 81 ) */
                   6309:       /*       prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp,ij,nres); */
                   6310:       /* else */
                   6311:       prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp,ij,nres);
1.208     brouard  6312:       for(i=1;i<=nlstate;i++){
1.126     brouard  6313:        gm[i] = prlim[i][i];
1.208     brouard  6314:        mgm[theta][i] = prlim[i][i];
                   6315:       }
1.126     brouard  6316:       for(i=1;i<=nlstate;i++)
                   6317:        gradg[theta][i]= (gp[i]-gm[i])/2./delti[theta];
1.209     brouard  6318:       /* gradg[theta][2]= -gradg[theta][1]; */ /* For testing if nlstate=2 */
1.126     brouard  6319:     } /* End theta */
                   6320: 
                   6321:     trgradg =matrix(1,nlstate,1,npar);
                   6322: 
                   6323:     for(j=1; j<=nlstate;j++)
                   6324:       for(theta=1; theta <=npar; theta++)
                   6325:        trgradg[j][theta]=gradg[theta][j];
1.209     brouard  6326:     /* if((int)age==79 ||(int)age== 80 ||(int)age== 81 ){ */
                   6327:     /*   printf("\nmgm mgp %d ",(int)age); */
                   6328:     /*   for(j=1; j<=nlstate;j++){ */
                   6329:     /*         printf(" %d ",j); */
                   6330:     /*         for(theta=1; theta <=npar; theta++) */
                   6331:     /*           printf(" %d %lf %lf",theta,mgm[theta][j],mgp[theta][j]); */
                   6332:     /*         printf("\n "); */
                   6333:     /*   } */
                   6334:     /* } */
                   6335:     /* if((int)age==79 ||(int)age== 80 ||(int)age== 81 ){ */
                   6336:     /*   printf("\n gradg %d ",(int)age); */
                   6337:     /*   for(j=1; j<=nlstate;j++){ */
                   6338:     /*         printf("%d ",j); */
                   6339:     /*         for(theta=1; theta <=npar; theta++) */
                   6340:     /*           printf("%d %lf ",theta,gradg[theta][j]); */
                   6341:     /*         printf("\n "); */
                   6342:     /*   } */
                   6343:     /* } */
1.126     brouard  6344: 
                   6345:     for(i=1;i<=nlstate;i++)
                   6346:       varpl[i][(int)age] =0.;
1.209     brouard  6347:     if((int)age==79 ||(int)age== 80  ||(int)age== 81){
1.268     brouard  6348:     matprod2(dnewmpar,trgradg,1,nlstate,1,npar,1,npar,matcov);
                   6349:     matprod2(doldm,dnewmpar,1,nlstate,1,npar,1,nlstate,gradg);
1.205     brouard  6350:     }else{
1.268     brouard  6351:     matprod2(dnewmpar,trgradg,1,nlstate,1,npar,1,npar,matcov);
                   6352:     matprod2(doldm,dnewmpar,1,nlstate,1,npar,1,nlstate,gradg);
1.205     brouard  6353:     }
1.126     brouard  6354:     for(i=1;i<=nlstate;i++)
                   6355:       varpl[i][(int)age] = doldm[i][i]; /* Covariances are useless */
                   6356: 
                   6357:     fprintf(ficresvpl,"%.0f ",age );
1.241     brouard  6358:     if(nresult >=1)
                   6359:       fprintf(ficresvpl,"%d ",nres );
1.288     brouard  6360:     for(i=1; i<=nlstate;i++){
1.126     brouard  6361:       fprintf(ficresvpl," %.5f (%.5f)",prlim[i][i],sqrt(varpl[i][(int)age]));
1.288     brouard  6362:       /* for(j=1;j<=nlstate;j++) */
                   6363:       /*       fprintf(ficresvpl," %d %.5f ",j,prlim[j][i]); */
                   6364:     }
1.126     brouard  6365:     fprintf(ficresvpl,"\n");
                   6366:     free_vector(gp,1,nlstate);
                   6367:     free_vector(gm,1,nlstate);
1.208     brouard  6368:     free_matrix(mgm,1,npar,1,nlstate);
                   6369:     free_matrix(mgp,1,npar,1,nlstate);
1.126     brouard  6370:     free_matrix(gradg,1,npar,1,nlstate);
                   6371:     free_matrix(trgradg,1,nlstate,1,npar);
                   6372:   } /* End age */
                   6373: 
                   6374:   free_vector(xp,1,npar);
                   6375:   free_matrix(doldm,1,nlstate,1,npar);
1.268     brouard  6376:   free_matrix(dnewmpar,1,nlstate,1,nlstate);
                   6377: 
                   6378: }
                   6379: 
                   6380: 
                   6381: /************ Variance of backprevalence limit ******************/
1.269     brouard  6382:  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  6383: {
                   6384:   /* Variance of backward prevalence limit  for each state ij using current parameters x[] and estimates of neighbourhood give by delti*/
                   6385:   /*  double **prevalim(double **prlim, int nlstate, double *xp, double age, double **oldm, double **savm,double ftolpl);*/
                   6386: 
                   6387:   double **dnewmpar,**doldm;
                   6388:   int i, j, nhstepm, hstepm;
                   6389:   double *xp;
                   6390:   double *gp, *gm;
                   6391:   double **gradg, **trgradg;
                   6392:   double **mgm, **mgp;
                   6393:   double age,agelim;
                   6394:   int theta;
                   6395:   
                   6396:   pstamp(ficresvbl);
                   6397:   fprintf(ficresvbl,"# Standard deviation of back (stable) prevalences \n");
                   6398:   fprintf(ficresvbl,"# Age ");
                   6399:   if(nresult >=1)
                   6400:     fprintf(ficresvbl," Result# ");
                   6401:   for(i=1; i<=nlstate;i++)
                   6402:       fprintf(ficresvbl," %1d-%1d",i,i);
                   6403:   fprintf(ficresvbl,"\n");
                   6404: 
                   6405:   xp=vector(1,npar);
                   6406:   dnewmpar=matrix(1,nlstate,1,npar);
                   6407:   doldm=matrix(1,nlstate,1,nlstate);
                   6408:   
                   6409:   hstepm=1*YEARM; /* Every year of age */
                   6410:   hstepm=hstepm/stepm; /* Typically in stepm units, if j= 2 years, = 2/6 months = 4 */ 
                   6411:   agelim = AGEINF;
                   6412:   for (age=fage; age>=bage; age --){ /* If stepm=6 months */
                   6413:     nhstepm=(int) rint((age-agelim)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */ 
                   6414:     if (stepm >= YEARM) hstepm=1;
                   6415:     nhstepm = nhstepm/hstepm; /* Typically 40/4=10 */
                   6416:     gradg=matrix(1,npar,1,nlstate);
                   6417:     mgp=matrix(1,npar,1,nlstate);
                   6418:     mgm=matrix(1,npar,1,nlstate);
                   6419:     gp=vector(1,nlstate);
                   6420:     gm=vector(1,nlstate);
                   6421: 
                   6422:     for(theta=1; theta <=npar; theta++){
                   6423:       for(i=1; i<=npar; i++){ /* Computes gradient */
                   6424:        xp[i] = x[i] + (i==theta ?delti[theta]:0);
                   6425:       }
                   6426:       if(mobilavproj > 0 )
                   6427:        bprevalim(bprlim, mobaverage,nlstate,xp,age,ftolpl,ncvyearp,ij,nres);
                   6428:       else
                   6429:        bprevalim(bprlim, mobaverage,nlstate,xp,age,ftolpl,ncvyearp,ij,nres);
                   6430:       for(i=1;i<=nlstate;i++){
                   6431:        gp[i] = bprlim[i][i];
                   6432:        mgp[theta][i] = bprlim[i][i];
                   6433:       }
                   6434:      for(i=1; i<=npar; i++) /* Computes gradient */
                   6435:        xp[i] = x[i] - (i==theta ?delti[theta]:0);
                   6436:        if(mobilavproj > 0 )
                   6437:        bprevalim(bprlim, mobaverage,nlstate,xp,age,ftolpl,ncvyearp,ij,nres);
                   6438:        else
                   6439:        bprevalim(bprlim, mobaverage,nlstate,xp,age,ftolpl,ncvyearp,ij,nres);
                   6440:       for(i=1;i<=nlstate;i++){
                   6441:        gm[i] = bprlim[i][i];
                   6442:        mgm[theta][i] = bprlim[i][i];
                   6443:       }
                   6444:       for(i=1;i<=nlstate;i++)
                   6445:        gradg[theta][i]= (gp[i]-gm[i])/2./delti[theta];
                   6446:       /* gradg[theta][2]= -gradg[theta][1]; */ /* For testing if nlstate=2 */
                   6447:     } /* End theta */
                   6448: 
                   6449:     trgradg =matrix(1,nlstate,1,npar);
                   6450: 
                   6451:     for(j=1; j<=nlstate;j++)
                   6452:       for(theta=1; theta <=npar; theta++)
                   6453:        trgradg[j][theta]=gradg[theta][j];
                   6454:     /* if((int)age==79 ||(int)age== 80 ||(int)age== 81 ){ */
                   6455:     /*   printf("\nmgm mgp %d ",(int)age); */
                   6456:     /*   for(j=1; j<=nlstate;j++){ */
                   6457:     /*         printf(" %d ",j); */
                   6458:     /*         for(theta=1; theta <=npar; theta++) */
                   6459:     /*           printf(" %d %lf %lf",theta,mgm[theta][j],mgp[theta][j]); */
                   6460:     /*         printf("\n "); */
                   6461:     /*   } */
                   6462:     /* } */
                   6463:     /* if((int)age==79 ||(int)age== 80 ||(int)age== 81 ){ */
                   6464:     /*   printf("\n gradg %d ",(int)age); */
                   6465:     /*   for(j=1; j<=nlstate;j++){ */
                   6466:     /*         printf("%d ",j); */
                   6467:     /*         for(theta=1; theta <=npar; theta++) */
                   6468:     /*           printf("%d %lf ",theta,gradg[theta][j]); */
                   6469:     /*         printf("\n "); */
                   6470:     /*   } */
                   6471:     /* } */
                   6472: 
                   6473:     for(i=1;i<=nlstate;i++)
                   6474:       varbpl[i][(int)age] =0.;
                   6475:     if((int)age==79 ||(int)age== 80  ||(int)age== 81){
                   6476:     matprod2(dnewmpar,trgradg,1,nlstate,1,npar,1,npar,matcov);
                   6477:     matprod2(doldm,dnewmpar,1,nlstate,1,npar,1,nlstate,gradg);
                   6478:     }else{
                   6479:     matprod2(dnewmpar,trgradg,1,nlstate,1,npar,1,npar,matcov);
                   6480:     matprod2(doldm,dnewmpar,1,nlstate,1,npar,1,nlstate,gradg);
                   6481:     }
                   6482:     for(i=1;i<=nlstate;i++)
                   6483:       varbpl[i][(int)age] = doldm[i][i]; /* Covariances are useless */
                   6484: 
                   6485:     fprintf(ficresvbl,"%.0f ",age );
                   6486:     if(nresult >=1)
                   6487:       fprintf(ficresvbl,"%d ",nres );
                   6488:     for(i=1; i<=nlstate;i++)
                   6489:       fprintf(ficresvbl," %.5f (%.5f)",bprlim[i][i],sqrt(varbpl[i][(int)age]));
                   6490:     fprintf(ficresvbl,"\n");
                   6491:     free_vector(gp,1,nlstate);
                   6492:     free_vector(gm,1,nlstate);
                   6493:     free_matrix(mgm,1,npar,1,nlstate);
                   6494:     free_matrix(mgp,1,npar,1,nlstate);
                   6495:     free_matrix(gradg,1,npar,1,nlstate);
                   6496:     free_matrix(trgradg,1,nlstate,1,npar);
                   6497:   } /* End age */
                   6498: 
                   6499:   free_vector(xp,1,npar);
                   6500:   free_matrix(doldm,1,nlstate,1,npar);
                   6501:   free_matrix(dnewmpar,1,nlstate,1,nlstate);
1.126     brouard  6502: 
                   6503: }
                   6504: 
                   6505: /************ Variance of one-step probabilities  ******************/
                   6506: 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  6507:  {
                   6508:    int i, j=0,  k1, l1, tj;
                   6509:    int k2, l2, j1,  z1;
                   6510:    int k=0, l;
                   6511:    int first=1, first1, first2;
                   6512:    double cv12, mu1, mu2, lc1, lc2, v12, v21, v11, v22,v1,v2, c12, tnalp;
                   6513:    double **dnewm,**doldm;
                   6514:    double *xp;
                   6515:    double *gp, *gm;
                   6516:    double **gradg, **trgradg;
                   6517:    double **mu;
                   6518:    double age, cov[NCOVMAX+1];
                   6519:    double std=2.0; /* Number of standard deviation wide of confidence ellipsoids */
                   6520:    int theta;
                   6521:    char fileresprob[FILENAMELENGTH];
                   6522:    char fileresprobcov[FILENAMELENGTH];
                   6523:    char fileresprobcor[FILENAMELENGTH];
                   6524:    double ***varpij;
                   6525: 
                   6526:    strcpy(fileresprob,"PROB_"); 
                   6527:    strcat(fileresprob,fileres);
                   6528:    if((ficresprob=fopen(fileresprob,"w"))==NULL) {
                   6529:      printf("Problem with resultfile: %s\n", fileresprob);
                   6530:      fprintf(ficlog,"Problem with resultfile: %s\n", fileresprob);
                   6531:    }
                   6532:    strcpy(fileresprobcov,"PROBCOV_"); 
                   6533:    strcat(fileresprobcov,fileresu);
                   6534:    if((ficresprobcov=fopen(fileresprobcov,"w"))==NULL) {
                   6535:      printf("Problem with resultfile: %s\n", fileresprobcov);
                   6536:      fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobcov);
                   6537:    }
                   6538:    strcpy(fileresprobcor,"PROBCOR_"); 
                   6539:    strcat(fileresprobcor,fileresu);
                   6540:    if((ficresprobcor=fopen(fileresprobcor,"w"))==NULL) {
                   6541:      printf("Problem with resultfile: %s\n", fileresprobcor);
                   6542:      fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobcor);
                   6543:    }
                   6544:    printf("Computing standard deviation of one-step probabilities: result on file '%s' \n",fileresprob);
                   6545:    fprintf(ficlog,"Computing standard deviation of one-step probabilities: result on file '%s' \n",fileresprob);
                   6546:    printf("Computing matrix of variance covariance of one-step probabilities: result on file '%s' \n",fileresprobcov);
                   6547:    fprintf(ficlog,"Computing matrix of variance covariance of one-step probabilities: result on file '%s' \n",fileresprobcov);
                   6548:    printf("and correlation matrix of one-step probabilities: result on file '%s' \n",fileresprobcor);
                   6549:    fprintf(ficlog,"and correlation matrix of one-step probabilities: result on file '%s' \n",fileresprobcor);
                   6550:    pstamp(ficresprob);
                   6551:    fprintf(ficresprob,"#One-step probabilities and stand. devi in ()\n");
                   6552:    fprintf(ficresprob,"# Age");
                   6553:    pstamp(ficresprobcov);
                   6554:    fprintf(ficresprobcov,"#One-step probabilities and covariance matrix\n");
                   6555:    fprintf(ficresprobcov,"# Age");
                   6556:    pstamp(ficresprobcor);
                   6557:    fprintf(ficresprobcor,"#One-step probabilities and correlation matrix\n");
                   6558:    fprintf(ficresprobcor,"# Age");
1.126     brouard  6559: 
                   6560: 
1.222     brouard  6561:    for(i=1; i<=nlstate;i++)
                   6562:      for(j=1; j<=(nlstate+ndeath);j++){
                   6563:        fprintf(ficresprob," p%1d-%1d (SE)",i,j);
                   6564:        fprintf(ficresprobcov," p%1d-%1d ",i,j);
                   6565:        fprintf(ficresprobcor," p%1d-%1d ",i,j);
                   6566:      }  
                   6567:    /* fprintf(ficresprob,"\n");
                   6568:       fprintf(ficresprobcov,"\n");
                   6569:       fprintf(ficresprobcor,"\n");
                   6570:    */
                   6571:    xp=vector(1,npar);
                   6572:    dnewm=matrix(1,(nlstate)*(nlstate+ndeath),1,npar);
                   6573:    doldm=matrix(1,(nlstate)*(nlstate+ndeath),1,(nlstate)*(nlstate+ndeath));
                   6574:    mu=matrix(1,(nlstate)*(nlstate+ndeath), (int) bage, (int)fage);
                   6575:    varpij=ma3x(1,nlstate*(nlstate+ndeath),1,nlstate*(nlstate+ndeath),(int) bage, (int) fage);
                   6576:    first=1;
                   6577:    fprintf(ficgp,"\n# Routine varprob");
                   6578:    fprintf(fichtm,"\n<li><h4> Computing and drawing one step probabilities with their confidence intervals</h4></li>\n");
                   6579:    fprintf(fichtm,"\n");
                   6580: 
1.288     brouard  6581:    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  6582:    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);
                   6583:    fprintf(fichtmcov,"\nEllipsoids of confidence centered on point (p<inf>ij</inf>, p<inf>kl</inf>) are estimated \
1.126     brouard  6584: and drawn. It helps understanding how is the covariance between two incidences.\
                   6585:  They are expressed in year<sup>-1</sup> in order to be less dependent of stepm.<br>\n");
1.222     brouard  6586:    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  6587: It can be understood this way: if pij and pkl where uncorrelated the (2x2) matrix of covariance \
                   6588: would have been (1/(var pij), 0 , 0, 1/(var pkl)), and the confidence interval would be 2 \
                   6589: standard deviations wide on each axis. <br>\
                   6590:  Now, if both incidences are correlated (usual case) we diagonalised the inverse of the covariance matrix\
                   6591:  and made the appropriate rotation to look at the uncorrelated principal directions.<br>\
                   6592: To be simple, these graphs help to understand the significativity of each parameter in relation to a second other one.<br> \n");
                   6593: 
1.222     brouard  6594:    cov[1]=1;
                   6595:    /* tj=cptcoveff; */
1.225     brouard  6596:    tj = (int) pow(2,cptcoveff);
1.222     brouard  6597:    if (cptcovn<1) {tj=1;ncodemax[1]=1;}
                   6598:    j1=0;
1.224     brouard  6599:    for(j1=1; j1<=tj;j1++){  /* For each valid combination of covariates or only once*/
1.222     brouard  6600:      if  (cptcovn>0) {
                   6601:        fprintf(ficresprob, "\n#********** Variable "); 
1.225     brouard  6602:        for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresprob, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
1.222     brouard  6603:        fprintf(ficresprob, "**********\n#\n");
                   6604:        fprintf(ficresprobcov, "\n#********** Variable "); 
1.225     brouard  6605:        for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresprobcov, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
1.222     brouard  6606:        fprintf(ficresprobcov, "**********\n#\n");
1.220     brouard  6607:                        
1.222     brouard  6608:        fprintf(ficgp, "\n#********** Variable "); 
1.225     brouard  6609:        for (z1=1; z1<=cptcoveff; z1++) fprintf(ficgp, " V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
1.222     brouard  6610:        fprintf(ficgp, "**********\n#\n");
1.220     brouard  6611:                        
                   6612:                        
1.222     brouard  6613:        fprintf(fichtmcov, "\n<hr  size=\"2\" color=\"#EC5E5E\">********** Variable "); 
1.225     brouard  6614:        for (z1=1; z1<=cptcoveff; z1++) fprintf(fichtm, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
1.222     brouard  6615:        fprintf(fichtmcov, "**********\n<hr size=\"2\" color=\"#EC5E5E\">");
1.220     brouard  6616:                        
1.222     brouard  6617:        fprintf(ficresprobcor, "\n#********** Variable ");    
1.225     brouard  6618:        for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresprobcor, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
1.222     brouard  6619:        fprintf(ficresprobcor, "**********\n#");    
                   6620:        if(invalidvarcomb[j1]){
                   6621:         fprintf(ficgp,"\n#Combination (%d) ignored because no cases \n",j1); 
                   6622:         fprintf(fichtmcov,"\n<h3>Combination (%d) ignored because no cases </h3>\n",j1); 
                   6623:         continue;
                   6624:        }
                   6625:      }
                   6626:      gradg=matrix(1,npar,1,(nlstate)*(nlstate+ndeath));
                   6627:      trgradg=matrix(1,(nlstate)*(nlstate+ndeath),1,npar);
                   6628:      gp=vector(1,(nlstate)*(nlstate+ndeath));
                   6629:      gm=vector(1,(nlstate)*(nlstate+ndeath));
                   6630:      for (age=bage; age<=fage; age ++){ 
                   6631:        cov[2]=age;
                   6632:        if(nagesqr==1)
                   6633:         cov[3]= age*age;
                   6634:        for (k=1; k<=cptcovn;k++) {
                   6635:         cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(j1,k)];
                   6636:         /*cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(j1,Tvar[k])];*//* j1 1 2 3 4
                   6637:                                                                    * 1  1 1 1 1
                   6638:                                                                    * 2  2 1 1 1
                   6639:                                                                    * 3  1 2 1 1
                   6640:                                                                    */
                   6641:         /* nbcode[1][1]=0 nbcode[1][2]=1;*/
                   6642:        }
                   6643:        /* for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2]; */
                   6644:        for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,k)]*cov[2];
                   6645:        for (k=1; k<=cptcovprod;k++)
                   6646:         cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)]*nbcode[Tvard[k][2]][codtabm(ij,k)];
1.220     brouard  6647:                        
                   6648:                        
1.222     brouard  6649:        for(theta=1; theta <=npar; theta++){
                   6650:         for(i=1; i<=npar; i++)
                   6651:           xp[i] = x[i] + (i==theta ?delti[theta]:(double)0);
1.220     brouard  6652:                                
1.222     brouard  6653:         pmij(pmmij,cov,ncovmodel,xp,nlstate);
1.220     brouard  6654:                                
1.222     brouard  6655:         k=0;
                   6656:         for(i=1; i<= (nlstate); i++){
                   6657:           for(j=1; j<=(nlstate+ndeath);j++){
                   6658:             k=k+1;
                   6659:             gp[k]=pmmij[i][j];
                   6660:           }
                   6661:         }
1.220     brouard  6662:                                
1.222     brouard  6663:         for(i=1; i<=npar; i++)
                   6664:           xp[i] = x[i] - (i==theta ?delti[theta]:(double)0);
1.220     brouard  6665:                                
1.222     brouard  6666:         pmij(pmmij,cov,ncovmodel,xp,nlstate);
                   6667:         k=0;
                   6668:         for(i=1; i<=(nlstate); i++){
                   6669:           for(j=1; j<=(nlstate+ndeath);j++){
                   6670:             k=k+1;
                   6671:             gm[k]=pmmij[i][j];
                   6672:           }
                   6673:         }
1.220     brouard  6674:                                
1.222     brouard  6675:         for(i=1; i<= (nlstate)*(nlstate+ndeath); i++) 
                   6676:           gradg[theta][i]=(gp[i]-gm[i])/(double)2./delti[theta];  
                   6677:        }
1.126     brouard  6678: 
1.222     brouard  6679:        for(j=1; j<=(nlstate)*(nlstate+ndeath);j++)
                   6680:         for(theta=1; theta <=npar; theta++)
                   6681:           trgradg[j][theta]=gradg[theta][j];
1.220     brouard  6682:                        
1.222     brouard  6683:        matprod2(dnewm,trgradg,1,(nlstate)*(nlstate+ndeath),1,npar,1,npar,matcov); 
                   6684:        matprod2(doldm,dnewm,1,(nlstate)*(nlstate+ndeath),1,npar,1,(nlstate)*(nlstate+ndeath),gradg);
1.220     brouard  6685:                        
1.222     brouard  6686:        pmij(pmmij,cov,ncovmodel,x,nlstate);
1.220     brouard  6687:                        
1.222     brouard  6688:        k=0;
                   6689:        for(i=1; i<=(nlstate); i++){
                   6690:         for(j=1; j<=(nlstate+ndeath);j++){
                   6691:           k=k+1;
                   6692:           mu[k][(int) age]=pmmij[i][j];
                   6693:         }
                   6694:        }
                   6695:        for(i=1;i<=(nlstate)*(nlstate+ndeath);i++)
                   6696:         for(j=1;j<=(nlstate)*(nlstate+ndeath);j++)
                   6697:           varpij[i][j][(int)age] = doldm[i][j];
1.220     brouard  6698:                        
1.222     brouard  6699:        /*printf("\n%d ",(int)age);
                   6700:         for (i=1; i<=(nlstate)*(nlstate+ndeath);i++){
                   6701:         printf("%e [%e ;%e] ",gm[i],gm[i]-2*sqrt(doldm[i][i]),gm[i]+2*sqrt(doldm[i][i]));
                   6702:         fprintf(ficlog,"%e [%e ;%e] ",gm[i],gm[i]-2*sqrt(doldm[i][i]),gm[i]+2*sqrt(doldm[i][i]));
                   6703:         }*/
1.220     brouard  6704:                        
1.222     brouard  6705:        fprintf(ficresprob,"\n%d ",(int)age);
                   6706:        fprintf(ficresprobcov,"\n%d ",(int)age);
                   6707:        fprintf(ficresprobcor,"\n%d ",(int)age);
1.220     brouard  6708:                        
1.222     brouard  6709:        for (i=1; i<=(nlstate)*(nlstate+ndeath);i++)
                   6710:         fprintf(ficresprob,"%11.3e (%11.3e) ",mu[i][(int) age],sqrt(varpij[i][i][(int)age]));
                   6711:        for (i=1; i<=(nlstate)*(nlstate+ndeath);i++){
                   6712:         fprintf(ficresprobcov,"%11.3e ",mu[i][(int) age]);
                   6713:         fprintf(ficresprobcor,"%11.3e ",mu[i][(int) age]);
                   6714:        }
                   6715:        i=0;
                   6716:        for (k=1; k<=(nlstate);k++){
                   6717:         for (l=1; l<=(nlstate+ndeath);l++){ 
                   6718:           i++;
                   6719:           fprintf(ficresprobcov,"\n%d %d-%d",(int)age,k,l);
                   6720:           fprintf(ficresprobcor,"\n%d %d-%d",(int)age,k,l);
                   6721:           for (j=1; j<=i;j++){
                   6722:             /* printf(" k=%d l=%d i=%d j=%d\n",k,l,i,j);fflush(stdout); */
                   6723:             fprintf(ficresprobcov," %11.3e",varpij[i][j][(int)age]);
                   6724:             fprintf(ficresprobcor," %11.3e",varpij[i][j][(int) age]/sqrt(varpij[i][i][(int) age])/sqrt(varpij[j][j][(int)age]));
                   6725:           }
                   6726:         }
                   6727:        }/* end of loop for state */
                   6728:      } /* end of loop for age */
                   6729:      free_vector(gp,1,(nlstate+ndeath)*(nlstate+ndeath));
                   6730:      free_vector(gm,1,(nlstate+ndeath)*(nlstate+ndeath));
                   6731:      free_matrix(trgradg,1,(nlstate+ndeath)*(nlstate+ndeath),1,npar);
                   6732:      free_matrix(gradg,1,(nlstate+ndeath)*(nlstate+ndeath),1,npar);
                   6733:     
                   6734:      /* Confidence intervalle of pij  */
                   6735:      /*
                   6736:        fprintf(ficgp,"\nunset parametric;unset label");
                   6737:        fprintf(ficgp,"\nset log y;unset log x; set xlabel \"Age\";set ylabel \"probability (year-1)\"");
                   6738:        fprintf(ficgp,"\nset ter png small\nset size 0.65,0.65");
                   6739:        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);
                   6740:        fprintf(fichtm,"\n<br><img src=\"pijgr%s.png\"> ",optionfilefiname);
                   6741:        fprintf(ficgp,"\nset out \"pijgr%s.png\"",optionfilefiname);
                   6742:        fprintf(ficgp,"\nplot \"%s\" every :::%d::%d u 1:2 \"\%%lf",k1,k2,xfilevarprob);
                   6743:      */
                   6744:                
                   6745:      /* Drawing ellipsoids of confidence of two variables p(k1-l1,k2-l2)*/
                   6746:      first1=1;first2=2;
                   6747:      for (k2=1; k2<=(nlstate);k2++){
                   6748:        for (l2=1; l2<=(nlstate+ndeath);l2++){ 
                   6749:         if(l2==k2) continue;
                   6750:         j=(k2-1)*(nlstate+ndeath)+l2;
                   6751:         for (k1=1; k1<=(nlstate);k1++){
                   6752:           for (l1=1; l1<=(nlstate+ndeath);l1++){ 
                   6753:             if(l1==k1) continue;
                   6754:             i=(k1-1)*(nlstate+ndeath)+l1;
                   6755:             if(i<=j) continue;
                   6756:             for (age=bage; age<=fage; age ++){ 
                   6757:               if ((int)age %5==0){
                   6758:                 v1=varpij[i][i][(int)age]/stepm*YEARM/stepm*YEARM;
                   6759:                 v2=varpij[j][j][(int)age]/stepm*YEARM/stepm*YEARM;
                   6760:                 cv12=varpij[i][j][(int)age]/stepm*YEARM/stepm*YEARM;
                   6761:                 mu1=mu[i][(int) age]/stepm*YEARM ;
                   6762:                 mu2=mu[j][(int) age]/stepm*YEARM;
                   6763:                 c12=cv12/sqrt(v1*v2);
                   6764:                 /* Computing eigen value of matrix of covariance */
                   6765:                 lc1=((v1+v2)+sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
                   6766:                 lc2=((v1+v2)-sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
                   6767:                 if ((lc2 <0) || (lc1 <0) ){
                   6768:                   if(first2==1){
                   6769:                     first1=0;
                   6770:                     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);
                   6771:                   }
                   6772:                   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);
                   6773:                   /* lc1=fabs(lc1); */ /* If we want to have them positive */
                   6774:                   /* lc2=fabs(lc2); */
                   6775:                 }
1.220     brouard  6776:                                                                
1.222     brouard  6777:                 /* Eigen vectors */
1.280     brouard  6778:                 if(1+(v1-lc1)*(v1-lc1)/cv12/cv12 <1.e-5){
                   6779:                   printf(" Error sqrt of a negative number: %lf\n",1+(v1-lc1)*(v1-lc1)/cv12/cv12);
                   6780:                   fprintf(ficlog," Error sqrt of a negative number: %lf\n",1+(v1-lc1)*(v1-lc1)/cv12/cv12);
                   6781:                   v11=(1./sqrt(fabs(1+(v1-lc1)*(v1-lc1)/cv12/cv12)));
                   6782:                 }else
                   6783:                   v11=(1./sqrt(1+(v1-lc1)*(v1-lc1)/cv12/cv12));
1.222     brouard  6784:                 /*v21=sqrt(1.-v11*v11); *//* error */
                   6785:                 v21=(lc1-v1)/cv12*v11;
                   6786:                 v12=-v21;
                   6787:                 v22=v11;
                   6788:                 tnalp=v21/v11;
                   6789:                 if(first1==1){
                   6790:                   first1=0;
                   6791:                   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);
                   6792:                 }
                   6793:                 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);
                   6794:                 /*printf(fignu*/
                   6795:                 /* mu1+ v11*lc1*cost + v12*lc2*sin(t) */
                   6796:                 /* mu2+ v21*lc1*cost + v22*lc2*sin(t) */
                   6797:                 if(first==1){
                   6798:                   first=0;
                   6799:                   fprintf(ficgp,"\n# Ellipsoids of confidence\n#\n");
                   6800:                   fprintf(ficgp,"\nset parametric;unset label");
                   6801:                   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);
                   6802:                   fprintf(ficgp,"\nset ter svg size 640, 480");
1.266     brouard  6803:                   fprintf(fichtmcov,"\n<p><br>Ellipsoids of confidence cov(p%1d%1d,p%1d%1d) expressed in year<sup>-1</sup>\
1.220     brouard  6804:  :<a href=\"%s_%d%1d%1d-%1d%1d.svg\">                                                                                                                                          \
1.201     brouard  6805: %s_%d%1d%1d-%1d%1d.svg</A>, ",k1,l1,k2,l2,\
1.222     brouard  6806:                           subdirf2(optionfilefiname,"VARPIJGR_"), j1,k1,l1,k2,l2,      \
                   6807:                           subdirf2(optionfilefiname,"VARPIJGR_"), j1,k1,l1,k2,l2);
                   6808:                   fprintf(fichtmcov,"\n<br><img src=\"%s_%d%1d%1d-%1d%1d.svg\"> ",subdirf2(optionfilefiname,"VARPIJGR_"), j1,k1,l1,k2,l2);
                   6809:                   fprintf(fichtmcov,"\n<br> Correlation at age %d (%.3f),",(int) age, c12);
                   6810:                   fprintf(ficgp,"\nset out \"%s_%d%1d%1d-%1d%1d.svg\"",subdirf2(optionfilefiname,"VARPIJGR_"), j1,k1,l1,k2,l2);
                   6811:                   fprintf(ficgp,"\nset label \"%d\" at %11.3e,%11.3e center",(int) age, mu1,mu2);
                   6812:                   fprintf(ficgp,"\n# Age %d, p%1d%1d - p%1d%1d",(int) age, k1,l1,k2,l2);
                   6813:                   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  6814:                           mu1,std,v11,sqrt(fabs(lc1)),v12,sqrt(fabs(lc2)), \
                   6815:                           mu2,std,v21,sqrt(fabs(lc1)),v22,sqrt(fabs(lc2))); /* For gnuplot only */
1.222     brouard  6816:                 }else{
                   6817:                   first=0;
                   6818:                   fprintf(fichtmcov," %d (%.3f),",(int) age, c12);
                   6819:                   fprintf(ficgp,"\n# Age %d, p%1d%1d - p%1d%1d",(int) age, k1,l1,k2,l2);
                   6820:                   fprintf(ficgp,"\nset label \"%d\" at %11.3e,%11.3e center",(int) age, mu1,mu2);
                   6821:                   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  6822:                           mu1,std,v11,sqrt(lc1),v12,sqrt(fabs(lc2)),   \
                   6823:                           mu2,std,v21,sqrt(lc1),v22,sqrt(fabs(lc2)));
1.222     brouard  6824:                 }/* if first */
                   6825:               } /* age mod 5 */
                   6826:             } /* end loop age */
                   6827:             fprintf(ficgp,"\nset out;\nset out \"%s_%d%1d%1d-%1d%1d.svg\";replot;set out;",subdirf2(optionfilefiname,"VARPIJGR_"), j1,k1,l1,k2,l2);
                   6828:             first=1;
                   6829:           } /*l12 */
                   6830:         } /* k12 */
                   6831:        } /*l1 */
                   6832:      }/* k1 */
                   6833:    }  /* loop on combination of covariates j1 */
                   6834:    free_ma3x(varpij,1,nlstate,1,nlstate+ndeath,(int) bage, (int)fage);
                   6835:    free_matrix(mu,1,(nlstate+ndeath)*(nlstate+ndeath),(int) bage, (int)fage);
                   6836:    free_matrix(doldm,1,(nlstate)*(nlstate+ndeath),1,(nlstate)*(nlstate+ndeath));
                   6837:    free_matrix(dnewm,1,(nlstate)*(nlstate+ndeath),1,npar);
                   6838:    free_vector(xp,1,npar);
                   6839:    fclose(ficresprob);
                   6840:    fclose(ficresprobcov);
                   6841:    fclose(ficresprobcor);
                   6842:    fflush(ficgp);
                   6843:    fflush(fichtmcov);
                   6844:  }
1.126     brouard  6845: 
                   6846: 
                   6847: /******************* Printing html file ***********/
1.201     brouard  6848: void printinghtml(char fileresu[], char title[], char datafile[], int firstpass, \
1.126     brouard  6849:                  int lastpass, int stepm, int weightopt, char model[],\
                   6850:                  int imx,int jmin, int jmax, double jmeanint,char rfileres[],\
1.296     brouard  6851:                  int popforecast, int mobilav, int prevfcast, int mobilavproj, int prevbcast, int estepm , \
                   6852:                  double jprev1, double mprev1,double anprev1, double dateprev1, double dateprojd, double dateback1, \
                   6853:                  double jprev2, double mprev2,double anprev2, double dateprev2, double dateprojf, double dateback2){
1.237     brouard  6854:   int jj1, k1, i1, cpt, k4, nres;
1.126     brouard  6855: 
                   6856:    fprintf(fichtm,"<ul><li><a href='#firstorder'>Result files (first order: no variance)</a>\n \
                   6857:    <li><a href='#secondorder'>Result files (second order (variance)</a>\n \
                   6858: </ul>");
1.237     brouard  6859:    fprintf(fichtm,"<ul><li> model=1+age+%s\n \
                   6860: </ul>", model);
1.214     brouard  6861:    fprintf(fichtm,"<ul><li><h4><a name='firstorder'>Result files (first order: no variance)</a></h4>\n");
                   6862:    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",
                   6863:           jprev1, mprev1,anprev1,jprev2, mprev2,anprev2,subdirfext3(optionfilefiname,"PHTMFR_",".htm"),subdirfext3(optionfilefiname,"PHTMFR_",".htm"));
                   6864:    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  6865:           jprev1, mprev1,anprev1,jprev2, mprev2,anprev2,subdirfext3(optionfilefiname,"PHTM_",".htm"),subdirfext3(optionfilefiname,"PHTM_",".htm"));
                   6866:    fprintf(fichtm,",  <a href=\"%s\">%s</a> (text file) <br>\n",subdirf2(fileresu,"P_"),subdirf2(fileresu,"P_"));
1.126     brouard  6867:    fprintf(fichtm,"\
                   6868:  - Estimated transition probabilities over %d (stepm) months: <a href=\"%s\">%s</a><br>\n ",
1.201     brouard  6869:           stepm,subdirf2(fileresu,"PIJ_"),subdirf2(fileresu,"PIJ_"));
1.126     brouard  6870:    fprintf(fichtm,"\
1.217     brouard  6871:  - Estimated back transition probabilities over %d (stepm) months: <a href=\"%s\">%s</a><br>\n ",
                   6872:           stepm,subdirf2(fileresu,"PIJB_"),subdirf2(fileresu,"PIJB_"));
                   6873:    fprintf(fichtm,"\
1.288     brouard  6874:  - Period (forward) prevalence in each health state: <a href=\"%s\">%s</a> <br>\n",
1.201     brouard  6875:           subdirf2(fileresu,"PL_"),subdirf2(fileresu,"PL_"));
1.126     brouard  6876:    fprintf(fichtm,"\
1.288     brouard  6877:  - Backward prevalence in each health state: <a href=\"%s\">%s</a> <br>\n",
1.217     brouard  6878:           subdirf2(fileresu,"PLB_"),subdirf2(fileresu,"PLB_"));
                   6879:    fprintf(fichtm,"\
1.211     brouard  6880:  - (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  6881:    <a href=\"%s\">%s</a> <br>\n",
1.201     brouard  6882:           estepm,subdirf2(fileresu,"E_"),subdirf2(fileresu,"E_"));
1.211     brouard  6883:    if(prevfcast==1){
                   6884:      fprintf(fichtm,"\
                   6885:  - Prevalence projections by age and states:                           \
1.201     brouard  6886:    <a href=\"%s\">%s</a> <br>\n</li>", subdirf2(fileresu,"F_"),subdirf2(fileresu,"F_"));
1.211     brouard  6887:    }
1.126     brouard  6888: 
                   6889: 
1.225     brouard  6890:    m=pow(2,cptcoveff);
1.222     brouard  6891:    if (cptcovn < 1) {m=1;ncodemax[1]=1;}
1.126     brouard  6892: 
1.264     brouard  6893:    fprintf(fichtm," \n<ul><li><b>Graphs</b></li><p>");
                   6894: 
                   6895:    jj1=0;
                   6896: 
                   6897:    fprintf(fichtm," \n<ul>");
                   6898:    for(nres=1; nres <= nresult; nres++) /* For each resultline */
                   6899:    for(k1=1; k1<=m;k1++){ /* For each combination of covariate */
                   6900:      if(m != 1 && TKresult[nres]!= k1)
                   6901:        continue;
                   6902:      jj1++;
                   6903:      if (cptcovn > 0) {
                   6904:        fprintf(fichtm,"\n<li><a  size=\"1\" color=\"#EC5E5E\" href=\"#rescov");
                   6905:        for (cpt=1; cpt<=cptcoveff;cpt++){ 
                   6906:         fprintf(fichtm,"_V%d=%d_",Tvresult[nres][cpt],(int)Tresult[nres][cpt]);
                   6907:        }
                   6908:        for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
                   6909:         fprintf(fichtm,"_V%d=%f_",Tvqresult[nres][k4],Tqresult[nres][k4]);
                   6910:        }
                   6911:        fprintf(fichtm,"\">");
                   6912:        
                   6913:        /* if(nqfveff+nqtveff 0) */ /* Test to be done */
                   6914:        fprintf(fichtm,"************ Results for covariates");
                   6915:        for (cpt=1; cpt<=cptcoveff;cpt++){ 
                   6916:         fprintf(fichtm," V%d=%d ",Tvresult[nres][cpt],(int)Tresult[nres][cpt]);
                   6917:        }
                   6918:        for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
                   6919:         fprintf(fichtm," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
                   6920:        }
                   6921:        if(invalidvarcomb[k1]){
                   6922:         fprintf(fichtm," Warning Combination (%d) ignored because no cases ",k1); 
                   6923:         continue;
                   6924:        }
                   6925:        fprintf(fichtm,"</a></li>");
                   6926:      } /* cptcovn >0 */
                   6927:    }
                   6928:      fprintf(fichtm," \n</ul>");
                   6929: 
1.222     brouard  6930:    jj1=0;
1.237     brouard  6931: 
                   6932:    for(nres=1; nres <= nresult; nres++) /* For each resultline */
1.241     brouard  6933:    for(k1=1; k1<=m;k1++){ /* For each combination of covariate */
1.253     brouard  6934:      if(m != 1 && TKresult[nres]!= k1)
1.237     brouard  6935:        continue;
1.220     brouard  6936: 
1.222     brouard  6937:      /* for(i1=1; i1<=ncodemax[k1];i1++){ */
                   6938:      jj1++;
                   6939:      if (cptcovn > 0) {
1.264     brouard  6940:        fprintf(fichtm,"\n<p><a name=\"rescov");
                   6941:        for (cpt=1; cpt<=cptcoveff;cpt++){ 
                   6942:         fprintf(fichtm,"_V%d=%d_",Tvresult[nres][cpt],(int)Tresult[nres][cpt]);
                   6943:        }
                   6944:        for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
                   6945:         fprintf(fichtm,"_V%d=%f_",Tvqresult[nres][k4],Tqresult[nres][k4]);
                   6946:        }
                   6947:        fprintf(fichtm,"\"</a>");
                   6948:  
1.222     brouard  6949:        fprintf(fichtm,"<hr  size=\"2\" color=\"#EC5E5E\">************ Results for covariates");
1.225     brouard  6950:        for (cpt=1; cpt<=cptcoveff;cpt++){ 
1.237     brouard  6951:         fprintf(fichtm," V%d=%d ",Tvresult[nres][cpt],(int)Tresult[nres][cpt]);
                   6952:         printf(" V%d=%d ",Tvresult[nres][cpt],Tresult[nres][cpt]);fflush(stdout);
                   6953:         /* fprintf(fichtm," V%d=%d ",Tvaraff[cpt],nbcode[Tvaraff[cpt]][codtabm(jj1,cpt)]); */
                   6954:         /* printf(" V%d=%d ",Tvaraff[cpt],nbcode[Tvaraff[cpt]][codtabm(jj1,cpt)]);fflush(stdout); */
1.222     brouard  6955:        }
1.237     brouard  6956:        for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
                   6957:        fprintf(fichtm," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
                   6958:        printf(" V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);fflush(stdout);
                   6959:       }
                   6960:        
1.230     brouard  6961:        /* if(nqfveff+nqtveff 0) */ /* Test to be done */
1.222     brouard  6962:        fprintf(fichtm," ************\n<hr size=\"2\" color=\"#EC5E5E\">");
                   6963:        if(invalidvarcomb[k1]){
                   6964:         fprintf(fichtm,"\n<h3>Combination (%d) ignored because no cases </h3>\n",k1); 
                   6965:         printf("\nCombination (%d) ignored because no cases \n",k1); 
                   6966:         continue;
                   6967:        }
                   6968:      }
                   6969:      /* aij, bij */
1.259     brouard  6970:      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  6971: <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  6972:      /* Pij */
1.241     brouard  6973:      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> \
                   6974: <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  6975:      /* Quasi-incidences */
                   6976:      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  6977:  before but expressed in per year i.e. quasi incidences if stepm is small and probabilities too, \
1.211     brouard  6978:  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  6979: 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> \
                   6980: <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  6981:      /* Survival functions (period) in state j */
                   6982:      for(cpt=1; cpt<=nlstate;cpt++){
1.292     brouard  6983:        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  6984: <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  6985:      }
                   6986:      /* State specific survival functions (period) */
                   6987:      for(cpt=1; cpt<=nlstate;cpt++){
1.292     brouard  6988:        fprintf(fichtm,"<br>\n- Survival functions in state %d and in any other live state (total).\
                   6989:  And probability to be observed in various states (up to %d) being in state %d at different ages.      \
1.283     brouard  6990:  <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  6991:      }
1.288     brouard  6992:      /* Period (forward stable) prevalence in each health state */
1.222     brouard  6993:      for(cpt=1; cpt<=nlstate;cpt++){
1.264     brouard  6994:        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> \
                   6995: <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  6996:      }
1.296     brouard  6997:      if(prevbcast==1){
1.288     brouard  6998:        /* Backward prevalence in each health state */
1.222     brouard  6999:        for(cpt=1; cpt<=nlstate;cpt++){
1.264     brouard  7000:         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  7001: <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  7002:        }
1.217     brouard  7003:      }
1.222     brouard  7004:      if(prevfcast==1){
1.288     brouard  7005:        /* Projection of prevalence up to period (forward stable) prevalence in each health state */
1.222     brouard  7006:        for(cpt=1; cpt<=nlstate;cpt++){
1.288     brouard  7007:         fprintf(fichtm,"<br>\n- Projection of cross-sectional prevalence (estimated with cases observed from %.1f to %.1f and mobil_average=%d), from year %.1f up to year %.1f tending to period (stable) forward prevalence in state %d. Or probability to be in state %d being in an observed weighted state (from 1 to %d). <a href=\"%s_%d-%d-%d.svg\">%s_%d-%d-%d.svg</a><br> \
1.296     brouard  7008: <img src=\"%s_%d-%d-%d.svg\">", dateprev1, dateprev2, mobilavproj, dateprojd, dateprojf, cpt, cpt, nlstate, subdirf2(optionfilefiname,"PROJ_"),cpt,k1,nres,subdirf2(optionfilefiname,"PROJ_"),cpt,k1,nres,subdirf2(optionfilefiname,"PROJ_"),cpt,k1,nres);
1.222     brouard  7009:        }
                   7010:      }
1.296     brouard  7011:      if(prevbcast==1){
1.268     brouard  7012:       /* Back projection of prevalence up to stable (mixed) back-prevalence in each health state */
                   7013:        for(cpt=1; cpt<=nlstate;cpt++){
1.273     brouard  7014:         fprintf(fichtm,"<br>\n- Back projection of cross-sectional prevalence (estimated with cases observed from %.1f to %.1f and mobil_average=%d), \
                   7015:  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 \
                   7016:  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) \
                   7017: with weights corresponding to observed prevalence at different ages. <a href=\"%s_%d-%d-%d.svg\">%s_%d-%d-%d.svg</a><br> \
                   7018:  <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  7019:        }
                   7020:      }
1.220     brouard  7021:         
1.222     brouard  7022:      for(cpt=1; cpt<=nlstate;cpt++) {
1.241     brouard  7023:        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> \
                   7024: <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  7025:      }
                   7026:      /* } /\* end i1 *\/ */
                   7027:    }/* End k1 */
                   7028:    fprintf(fichtm,"</ul>");
1.126     brouard  7029: 
1.222     brouard  7030:    fprintf(fichtm,"\
1.126     brouard  7031: \n<br><li><h4> <a name='secondorder'>Result files (second order: variances)</a></h4>\n\
1.193     brouard  7032:  - Parameter file with estimated parameters and covariance matrix: <a href=\"%s\">%s</a> <br> \
1.203     brouard  7033:  - 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  7034: But because parameters are usually highly correlated (a higher incidence of disability \
                   7035: and a higher incidence of recovery can give very close observed transition) it might \
                   7036: be very useful to look not only at linear confidence intervals estimated from the \
                   7037: variances but at the covariance matrix. And instead of looking at the estimated coefficients \
                   7038: (parameters) of the logistic regression, it might be more meaningful to visualize the \
                   7039: covariance matrix of the one-step probabilities. \
                   7040: See page 'Matrix of variance-covariance of one-step probabilities' below. \n", rfileres,rfileres);
1.126     brouard  7041: 
1.222     brouard  7042:    fprintf(fichtm," - Standard deviation of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
                   7043:           subdirf2(fileresu,"PROB_"),subdirf2(fileresu,"PROB_"));
                   7044:    fprintf(fichtm,"\
1.126     brouard  7045:  - Variance-covariance of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
1.222     brouard  7046:           subdirf2(fileresu,"PROBCOV_"),subdirf2(fileresu,"PROBCOV_"));
1.126     brouard  7047: 
1.222     brouard  7048:    fprintf(fichtm,"\
1.126     brouard  7049:  - Correlation matrix of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
1.222     brouard  7050:           subdirf2(fileresu,"PROBCOR_"),subdirf2(fileresu,"PROBCOR_"));
                   7051:    fprintf(fichtm,"\
1.126     brouard  7052:  - 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): \
                   7053:    <a href=\"%s\">%s</a> <br>\n</li>",
1.201     brouard  7054:           estepm,subdirf2(fileresu,"CVE_"),subdirf2(fileresu,"CVE_"));
1.222     brouard  7055:    fprintf(fichtm,"\
1.126     brouard  7056:  - (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): \
                   7057:    <a href=\"%s\">%s</a> <br>\n</li>",
1.201     brouard  7058:           estepm,subdirf2(fileresu,"STDE_"),subdirf2(fileresu,"STDE_"));
1.222     brouard  7059:    fprintf(fichtm,"\
1.288     brouard  7060:  - 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  7061:           estepm, subdirf2(fileresu,"V_"),subdirf2(fileresu,"V_"));
                   7062:    fprintf(fichtm,"\
1.128     brouard  7063:  - 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  7064:           estepm, subdirf2(fileresu,"T_"),subdirf2(fileresu,"T_"));
                   7065:    fprintf(fichtm,"\
1.288     brouard  7066:  - Standard deviation of forward (period) prevalences: <a href=\"%s\">%s</a> <br>\n",\
1.222     brouard  7067:           subdirf2(fileresu,"VPL_"),subdirf2(fileresu,"VPL_"));
1.126     brouard  7068: 
                   7069: /*  if(popforecast==1) fprintf(fichtm,"\n */
                   7070: /*  - Prevalences forecasting: <a href=\"f%s\">f%s</a> <br>\n */
                   7071: /*  - Population forecasting (if popforecast=1): <a href=\"pop%s\">pop%s</a> <br>\n */
                   7072: /*     <br>",fileres,fileres,fileres,fileres); */
                   7073: /*  else  */
                   7074: /*    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  7075:    fflush(fichtm);
                   7076:    fprintf(fichtm," <ul><li><b>Graphs</b></li><p>");
1.126     brouard  7077: 
1.225     brouard  7078:    m=pow(2,cptcoveff);
1.222     brouard  7079:    if (cptcovn < 1) {m=1;ncodemax[1]=1;}
1.126     brouard  7080: 
1.222     brouard  7081:    jj1=0;
1.237     brouard  7082: 
1.241     brouard  7083:    for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.222     brouard  7084:    for(k1=1; k1<=m;k1++){
1.253     brouard  7085:      if(m != 1 && TKresult[nres]!= k1)
1.237     brouard  7086:        continue;
1.222     brouard  7087:      /* for(i1=1; i1<=ncodemax[k1];i1++){ */
                   7088:      jj1++;
1.126     brouard  7089:      if (cptcovn > 0) {
                   7090:        fprintf(fichtm,"<hr  size=\"2\" color=\"#EC5E5E\">************ Results for covariates");
1.225     brouard  7091:        for (cpt=1; cpt<=cptcoveff;cpt++)  /**< cptcoveff number of variables */
1.237     brouard  7092:         fprintf(fichtm," V%d=%d ",Tvresult[nres][cpt],Tresult[nres][cpt]);
                   7093:         /* fprintf(fichtm," V%d=%d ",Tvaraff[cpt],nbcode[Tvaraff[cpt]][codtabm(jj1,cpt)]); */
                   7094:        for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
                   7095:        fprintf(fichtm," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
                   7096:       }
                   7097: 
1.126     brouard  7098:        fprintf(fichtm," ************\n<hr size=\"2\" color=\"#EC5E5E\">");
1.220     brouard  7099: 
1.222     brouard  7100:        if(invalidvarcomb[k1]){
                   7101:         fprintf(fichtm,"\n<h4>Combination (%d) ignored because no cases </h4>\n",k1); 
                   7102:         continue;
                   7103:        }
1.126     brouard  7104:      }
                   7105:      for(cpt=1; cpt<=nlstate;cpt++) {
1.258     brouard  7106:        fprintf(fichtm,"\n<br>- Observed (cross-sectional with mov_average=%d) and period (incidence based) \
1.241     brouard  7107: 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  7108: <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  7109:      }
                   7110:      fprintf(fichtm,"\n<br>- Total life expectancy by age and \
1.128     brouard  7111: health expectancies in states (1) and (2). If popbased=1 the smooth (due to the model) \
                   7112: true period expectancies (those weighted with period prevalences are also\
                   7113:  drawn in addition to the population based expectancies computed using\
1.241     brouard  7114:  observed and cahotic prevalences:  <a href=\"%s_%d-%d.svg\">%s_%d-%d.svg</a>\n<br>\
                   7115: <img src=\"%s_%d-%d.svg\">",subdirf2(optionfilefiname,"E_"),k1,nres,subdirf2(optionfilefiname,"E_"),k1,nres,subdirf2(optionfilefiname,"E_"),k1,nres);
1.222     brouard  7116:      /* } /\* end i1 *\/ */
                   7117:    }/* End k1 */
1.241     brouard  7118:   }/* End nres */
1.222     brouard  7119:    fprintf(fichtm,"</ul>");
                   7120:    fflush(fichtm);
1.126     brouard  7121: }
                   7122: 
                   7123: /******************* Gnuplot file **************/
1.296     brouard  7124: void printinggnuplot(char fileresu[], char optionfilefiname[], double ageminpar, double agemaxpar, double bage, double fage , int prevfcast, int prevbcast, char pathc[], double p[], int offyear, int offbyear){
1.126     brouard  7125: 
                   7126:   char dirfileres[132],optfileres[132];
1.264     brouard  7127:   char gplotcondition[132], gplotlabel[132];
1.237     brouard  7128:   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  7129:   int lv=0, vlv=0, kl=0;
1.130     brouard  7130:   int ng=0;
1.201     brouard  7131:   int vpopbased;
1.223     brouard  7132:   int ioffset; /* variable offset for columns */
1.270     brouard  7133:   int iyearc=1; /* variable column for year of projection  */
                   7134:   int iagec=1; /* variable column for age of projection  */
1.235     brouard  7135:   int nres=0; /* Index of resultline */
1.266     brouard  7136:   int istart=1; /* For starting graphs in projections */
1.219     brouard  7137: 
1.126     brouard  7138: /*   if((ficgp=fopen(optionfilegnuplot,"a"))==NULL) { */
                   7139: /*     printf("Problem with file %s",optionfilegnuplot); */
                   7140: /*     fprintf(ficlog,"Problem with file %s",optionfilegnuplot); */
                   7141: /*   } */
                   7142: 
                   7143:   /*#ifdef windows */
                   7144:   fprintf(ficgp,"cd \"%s\" \n",pathc);
1.223     brouard  7145:   /*#endif */
1.225     brouard  7146:   m=pow(2,cptcoveff);
1.126     brouard  7147: 
1.274     brouard  7148:   /* diagram of the model */
                   7149:   fprintf(ficgp,"\n#Diagram of the model \n");
                   7150:   fprintf(ficgp,"\ndelta=0.03;delta2=0.07;unset arrow;\n");
                   7151:   fprintf(ficgp,"yoff=(%d > 2? 0:1);\n",nlstate);
                   7152:   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);
                   7153: 
                   7154:   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);
                   7155:   fprintf(ficgp,"\n#show arrow\nunset label\n");
                   7156:   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);
                   7157:   fprintf(ficgp,"\nset label %d+1 sprintf(\"State %%d\",%d+1) center at 0.,0.  font \"helvetica, 16\" tc rgbcolor \"red\"\n",nlstate,nlstate);
                   7158:   fprintf(ficgp,"\n#show label\nunset border;unset xtics; unset ytics;\n");
                   7159:   fprintf(ficgp,"\n\nset ter svg size 640, 480;set out \"%s_.svg\" \n",subdirf2(optionfilefiname,"D_"));
                   7160:   fprintf(ficgp,"unset log y; plot [-1.2:1.2][yoff-1.2:1.2] 1/0 not; set out;reset;\n");
                   7161: 
1.202     brouard  7162:   /* Contribution to likelihood */
                   7163:   /* Plot the probability implied in the likelihood */
1.223     brouard  7164:   fprintf(ficgp,"\n# Contributions to the Likelihood, mle >=1. For mle=4 no interpolation, pure matrix products.\n#\n");
                   7165:   fprintf(ficgp,"\n set log y; unset log x;set xlabel \"Age\"; set ylabel \"Likelihood (-2Log(L))\";");
                   7166:   /* fprintf(ficgp,"\nset ter svg size 640, 480"); */ /* Too big for svg */
                   7167:   fprintf(ficgp,"\nset ter pngcairo size 640, 480");
1.204     brouard  7168: /* nice for mle=4 plot by number of matrix products.
1.202     brouard  7169:    replot  "rrtest1/toto.txt" u 2:($4 == 1 && $5==2 ? $9 : 1/0):5 t "p12" with point lc 1 */
                   7170: /* replot exp(p1+p2*x)/(1+exp(p1+p2*x)+exp(p3+p4*x)+exp(p5+p6*x)) t "p12(x)"  */
1.223     brouard  7171:   /* fprintf(ficgp,"\nset out \"%s.svg\";",subdirf2(optionfilefiname,"ILK_")); */
                   7172:   fprintf(ficgp,"\nset out \"%s-dest.png\";",subdirf2(optionfilefiname,"ILK_"));
                   7173:   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));
                   7174:   fprintf(ficgp,"\nset out \"%s-ori.png\";",subdirf2(optionfilefiname,"ILK_"));
                   7175:   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));
                   7176:   for (i=1; i<= nlstate ; i ++) {
                   7177:     fprintf(ficgp,"\nset out \"%s-p%dj.png\";set ylabel \"Probability for each individual/wave\";",subdirf2(optionfilefiname,"ILK_"),i);
                   7178:     fprintf(ficgp,"unset log;\n# plot weighted, mean weight should have point size of 0.5\n plot  \"%s\"",subdirf(fileresilk));
                   7179:     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);
                   7180:     for (j=2; j<= nlstate+ndeath ; j ++) {
                   7181:       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);
                   7182:     }
                   7183:     fprintf(ficgp,";\nset out; unset ylabel;\n"); 
                   7184:   }
                   7185:   /* 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 */               
                   7186:   /* fprintf(ficgp,"\nset log y;plot  \"%s\" u 2:(-$11):3 t \"All sample, all transitions\" with dots lc variable",subdirf(fileresilk)); */
                   7187:   /* fprintf(ficgp,"\nreplot  \"%s\" u 2:($3 <= 3 ? -$11 : 1/0):3 t \"First 3 individuals\" with line lc variable", subdirf(fileresilk)); */
                   7188:   fprintf(ficgp,"\nset out;unset log\n");
                   7189:   /* fprintf(ficgp,"\nset out \"%s.svg\"; replot; set out; # bug gnuplot",subdirf2(optionfilefiname,"ILK_")); */
1.202     brouard  7190: 
1.126     brouard  7191:   strcpy(dirfileres,optionfilefiname);
                   7192:   strcpy(optfileres,"vpl");
1.223     brouard  7193:   /* 1eme*/
1.238     brouard  7194:   for (cpt=1; cpt<= nlstate ; cpt ++){ /* For each live state */
                   7195:     for (k1=1; k1<= m ; k1 ++){ /* For each valid combination of covariate */
1.236     brouard  7196:       for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.238     brouard  7197:        /* plot [100000000000000000000:-100000000000000000000] "mysbiaspar/vplrmysbiaspar.txt to check */
1.253     brouard  7198:        if(m != 1 && TKresult[nres]!= k1)
1.238     brouard  7199:          continue;
                   7200:        /* We are interested in selected combination by the resultline */
1.246     brouard  7201:        /* printf("\n# 1st: Period (stable) prevalence with CI: 'VPL_' files and live state =%d ", cpt); */
1.288     brouard  7202:        fprintf(ficgp,"\n# 1st: Forward (stable period) prevalence with CI: 'VPL_' files  and live state =%d ", cpt);
1.264     brouard  7203:        strcpy(gplotlabel,"(");
1.238     brouard  7204:        for (k=1; k<=cptcoveff; k++){    /* For each covariate k get corresponding value lv for combination k1 */
                   7205:          lv= decodtabm(k1,k,cptcoveff); /* Should be the value of the covariate corresponding to k1 combination */
                   7206:          /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   7207:          /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   7208:          /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
                   7209:          vlv= nbcode[Tvaraff[k]][lv]; /* vlv is the value of the covariate lv, 0 or 1 */
                   7210:          /* For each combination of covariate k1 (V1=1, V3=0), we printed the current covariate k and its value vlv */
1.246     brouard  7211:          /* printf(" V%d=%d ",Tvaraff[k],vlv); */
1.238     brouard  7212:          fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv);
1.264     brouard  7213:          sprintf(gplotlabel+strlen(gplotlabel)," V%d=%d ",Tvaraff[k],vlv);
1.238     brouard  7214:        }
                   7215:        for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
1.246     brouard  7216:          /* printf(" V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]); */
1.238     brouard  7217:          fprintf(ficgp," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
1.264     brouard  7218:          sprintf(gplotlabel+strlen(gplotlabel)," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
                   7219:        }
                   7220:        strcpy(gplotlabel+strlen(gplotlabel),")");
1.246     brouard  7221:        /* printf("\n#\n"); */
1.238     brouard  7222:        fprintf(ficgp,"\n#\n");
                   7223:        if(invalidvarcomb[k1]){
1.260     brouard  7224:           /*k1=k1-1;*/ /* To be checked */
1.238     brouard  7225:          fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   7226:          continue;
                   7227:        }
1.235     brouard  7228:       
1.241     brouard  7229:        fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" \n",subdirf2(optionfilefiname,"V_"),cpt,k1,nres);
                   7230:        fprintf(ficgp,"\n#set out \"V_%s_%d-%d-%d.svg\" \n",optionfilefiname,cpt,k1,nres);
1.276     brouard  7231:        /* fprintf(ficgp,"set label \"Alive state %d %s\" at graph 0.98,0.5 center rotate font \"Helvetica,12\"\n",cpt,gplotlabel); */
                   7232:        fprintf(ficgp,"set title \"Alive state %d %s\" font \"Helvetica,12\"\n",cpt,gplotlabel);
1.260     brouard  7233:        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);
                   7234:        /* 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); */
                   7235:       /* k1-1 error should be nres-1*/
1.238     brouard  7236:        for (i=1; i<= nlstate ; i ++) {
                   7237:          if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
                   7238:          else        fprintf(ficgp," %%*lf (%%*lf)");
                   7239:        }
1.288     brouard  7240:        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  7241:        for (i=1; i<= nlstate ; i ++) {
                   7242:          if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
                   7243:          else fprintf(ficgp," %%*lf (%%*lf)");
                   7244:        } 
1.260     brouard  7245:        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  7246:        for (i=1; i<= nlstate ; i ++) {
                   7247:          if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
                   7248:          else fprintf(ficgp," %%*lf (%%*lf)");
                   7249:        }  
1.265     brouard  7250:        /* 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)); */
                   7251:        
                   7252:        fprintf(ficgp,"\" t\"\" w l lt 1,\"%s\" u 1:((",subdirf2(fileresu,"P_"));
                   7253:         if(cptcoveff ==0){
1.271     brouard  7254:          fprintf(ficgp,"$%d)) t 'Observed prevalence in state %d' with line lt 3",      2+3*(cpt-1),  cpt );
1.265     brouard  7255:        }else{
                   7256:          kl=0;
                   7257:          for (k=1; k<=cptcoveff; k++){    /* For each combination of covariate  */
                   7258:            lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate value corresponding to k1 combination and kth covariate */
                   7259:            /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   7260:            /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   7261:            /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
                   7262:            vlv= nbcode[Tvaraff[k]][lv];
                   7263:            kl++;
                   7264:            /* 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 *\/ */
                   7265:            /*6+(cpt-1)*(nlstate+1)+1+(i-1)+(nlstate+1)*nlstate; 6+(1-1)*(2+1)+1+(1-1) +(2+1)*2=13 */ 
                   7266:            /*6+1+(i-1)+(nlstate+1)*nlstate; 6+1+(1-1) +(2+1)*2=13 */ 
                   7267:            /* ''  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*/
                   7268:            if(k==cptcoveff){
                   7269:              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], \
                   7270:                      2+cptcoveff*2+3*(cpt-1),  cpt );  /* 4 or 6 ?*/
                   7271:            }else{
                   7272:              fprintf(ficgp,"$%d==%d && $%d==%d && ",kl+1, Tvaraff[k],kl+1+1,nbcode[Tvaraff[k]][lv]);
                   7273:              kl++;
                   7274:            }
                   7275:          } /* end covariate */
                   7276:        } /* end if no covariate */
                   7277: 
1.296     brouard  7278:        if(prevbcast==1){ /* We need to get the corresponding values of the covariates involved in this combination k1 */
1.238     brouard  7279:          /* 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  7280:          fprintf(ficgp,",\"%s\" u 1:((",subdirf2(fileresu,"PLB_")); /* Age is in 1, nres in 2 to be fixed */
1.238     brouard  7281:          if(cptcoveff ==0){
1.245     brouard  7282:            fprintf(ficgp,"$%d)) t 'Backward prevalence in state %d' with line lt 3",    2+(cpt-1),  cpt );
1.238     brouard  7283:          }else{
                   7284:            kl=0;
                   7285:            for (k=1; k<=cptcoveff; k++){    /* For each combination of covariate  */
                   7286:              lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate value corresponding to k1 combination and kth covariate */
                   7287:              /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   7288:              /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   7289:              /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
                   7290:              vlv= nbcode[Tvaraff[k]][lv];
1.223     brouard  7291:              kl++;
1.238     brouard  7292:              /* 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 *\/ */
                   7293:              /*6+(cpt-1)*(nlstate+1)+1+(i-1)+(nlstate+1)*nlstate; 6+(1-1)*(2+1)+1+(1-1) +(2+1)*2=13 */ 
                   7294:              /*6+1+(i-1)+(nlstate+1)*nlstate; 6+1+(1-1) +(2+1)*2=13 */ 
                   7295:              /* ''  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*/
                   7296:              if(k==cptcoveff){
1.245     brouard  7297:                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  7298:                        2+cptcoveff*2+(cpt-1),  cpt );  /* 4 or 6 ?*/
1.238     brouard  7299:              }else{
                   7300:                fprintf(ficgp,"$%d==%d && $%d==%d && ",kl+1, Tvaraff[k],kl+1+1,nbcode[Tvaraff[k]][lv]);
                   7301:                kl++;
                   7302:              }
                   7303:            } /* end covariate */
                   7304:          } /* end if no covariate */
1.296     brouard  7305:          if(prevbcast == 1){
1.268     brouard  7306:            fprintf(ficgp,", \"%s\" every :::%d::%d u 1:($2==%d ? $3:1/0) \"%%lf %%lf",subdirf2(fileresu,"VBL_"),nres-1,nres-1,nres);
                   7307:            /* k1-1 error should be nres-1*/
                   7308:            for (i=1; i<= nlstate ; i ++) {
                   7309:              if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
                   7310:              else        fprintf(ficgp," %%*lf (%%*lf)");
                   7311:            }
1.271     brouard  7312:            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  7313:            for (i=1; i<= nlstate ; i ++) {
                   7314:              if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
                   7315:              else fprintf(ficgp," %%*lf (%%*lf)");
                   7316:            } 
1.276     brouard  7317:            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  7318:            for (i=1; i<= nlstate ; i ++) {
                   7319:              if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
                   7320:              else fprintf(ficgp," %%*lf (%%*lf)");
                   7321:            } 
1.274     brouard  7322:            fprintf(ficgp,"\" t\"\" w l lt 4");
1.268     brouard  7323:          } /* end if backprojcast */
1.296     brouard  7324:        } /* end if prevbcast */
1.276     brouard  7325:        /* fprintf(ficgp,"\nset out ;unset label;\n"); */
                   7326:        fprintf(ficgp,"\nset out ;unset title;\n");
1.238     brouard  7327:       } /* nres */
1.201     brouard  7328:     } /* k1 */
                   7329:   } /* cpt */
1.235     brouard  7330: 
                   7331:   
1.126     brouard  7332:   /*2 eme*/
1.238     brouard  7333:   for (k1=1; k1<= m ; k1 ++){  
                   7334:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.253     brouard  7335:       if(m != 1 && TKresult[nres]!= k1)
1.238     brouard  7336:        continue;
                   7337:       fprintf(ficgp,"\n# 2nd: Total life expectancy with CI: 't' files ");
1.264     brouard  7338:       strcpy(gplotlabel,"(");
1.238     brouard  7339:       for (k=1; k<=cptcoveff; k++){    /* For each covariate and each value */
1.225     brouard  7340:        lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate number corresponding to k1 combination */
1.223     brouard  7341:        /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   7342:        /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   7343:        /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
                   7344:        vlv= nbcode[Tvaraff[k]][lv];
                   7345:        fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv);
1.264     brouard  7346:        sprintf(gplotlabel+strlen(gplotlabel)," V%d=%d ",Tvaraff[k],vlv);
1.211     brouard  7347:       }
1.237     brouard  7348:       /* for(k=1; k <= ncovds; k++){ */
1.236     brouard  7349:       for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
1.238     brouard  7350:        printf(" V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
1.236     brouard  7351:        fprintf(ficgp," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
1.264     brouard  7352:        sprintf(gplotlabel+strlen(gplotlabel)," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
1.238     brouard  7353:       }
1.264     brouard  7354:       strcpy(gplotlabel+strlen(gplotlabel),")");
1.211     brouard  7355:       fprintf(ficgp,"\n#\n");
1.223     brouard  7356:       if(invalidvarcomb[k1]){
                   7357:        fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   7358:        continue;
                   7359:       }
1.219     brouard  7360:                        
1.241     brouard  7361:       fprintf(ficgp,"\nset out \"%s_%d-%d.svg\" \n",subdirf2(optionfilefiname,"E_"),k1,nres);
1.238     brouard  7362:       for(vpopbased=0; vpopbased <= popbased; vpopbased++){ /* Done for vpopbased=0 and vpopbased=1 if popbased==1*/
1.264     brouard  7363:        fprintf(ficgp,"\nset label \"popbased %d %s\" at graph 0.98,0.5 center rotate font \"Helvetica,12\"\n",vpopbased,gplotlabel);
                   7364:        if(vpopbased==0){
1.238     brouard  7365:          fprintf(ficgp,"set ylabel \"Years\" \nset ter svg size 640, 480\nplot [%.f:%.f] ",ageminpar,fage);
1.264     brouard  7366:        }else
1.238     brouard  7367:          fprintf(ficgp,"\nreplot ");
                   7368:        for (i=1; i<= nlstate+1 ; i ++) {
                   7369:          k=2*i;
1.261     brouard  7370:          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  7371:          for (j=1; j<= nlstate+1 ; j ++) {
                   7372:            if (j==i) fprintf(ficgp," %%lf (%%lf)");
                   7373:            else fprintf(ficgp," %%*lf (%%*lf)");
                   7374:          }   
                   7375:          if (i== 1) fprintf(ficgp,"\" t\"TLE\" w l lt %d, \\\n",i);
                   7376:          else fprintf(ficgp,"\" t\"LE in state (%d)\" w l lt %d, \\\n",i-1,i+1);
1.261     brouard  7377:          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  7378:          for (j=1; j<= nlstate+1 ; j ++) {
                   7379:            if (j==i) fprintf(ficgp," %%lf (%%lf)");
                   7380:            else fprintf(ficgp," %%*lf (%%*lf)");
                   7381:          }   
                   7382:          fprintf(ficgp,"\" t\"\" w l lt 0,");
1.261     brouard  7383:          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  7384:          for (j=1; j<= nlstate+1 ; j ++) {
                   7385:            if (j==i) fprintf(ficgp," %%lf (%%lf)");
                   7386:            else fprintf(ficgp," %%*lf (%%*lf)");
                   7387:          }   
                   7388:          if (i== (nlstate+1)) fprintf(ficgp,"\" t\"\" w l lt 0");
                   7389:          else fprintf(ficgp,"\" t\"\" w l lt 0,\\\n");
                   7390:        } /* state */
                   7391:       } /* vpopbased */
1.264     brouard  7392:       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  7393:     } /* end nres */
                   7394:   } /* k1 end 2 eme*/
                   7395:        
                   7396:        
                   7397:   /*3eme*/
                   7398:   for (k1=1; k1<= m ; k1 ++){
                   7399:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.253     brouard  7400:       if(m != 1 && TKresult[nres]!= k1)
1.238     brouard  7401:        continue;
                   7402: 
                   7403:       for (cpt=1; cpt<= nlstate ; cpt ++) {
1.261     brouard  7404:        fprintf(ficgp,"\n\n# 3d: Life expectancy with EXP_ files:  combination=%d state=%d",k1, cpt);
1.264     brouard  7405:        strcpy(gplotlabel,"(");
1.238     brouard  7406:        for (k=1; k<=cptcoveff; k++){    /* For each covariate and each value */
                   7407:          lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate number corresponding to k1 combination */
                   7408:          /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   7409:          /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   7410:          /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
                   7411:          vlv= nbcode[Tvaraff[k]][lv];
                   7412:          fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv);
1.264     brouard  7413:          sprintf(gplotlabel+strlen(gplotlabel)," V%d=%d ",Tvaraff[k],vlv);
1.238     brouard  7414:        }
                   7415:        for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
                   7416:          fprintf(ficgp," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
1.264     brouard  7417:          sprintf(gplotlabel+strlen(gplotlabel)," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
1.238     brouard  7418:        }       
1.264     brouard  7419:        strcpy(gplotlabel+strlen(gplotlabel),")");
1.238     brouard  7420:        fprintf(ficgp,"\n#\n");
                   7421:        if(invalidvarcomb[k1]){
                   7422:          fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   7423:          continue;
                   7424:        }
                   7425:                        
                   7426:        /*       k=2+nlstate*(2*cpt-2); */
                   7427:        k=2+(nlstate+1)*(cpt-1);
1.241     brouard  7428:        fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" \n",subdirf2(optionfilefiname,"EXP_"),cpt,k1,nres);
1.264     brouard  7429:        fprintf(ficgp,"set label \"%s\" at graph 0.98,0.5 center rotate font \"Helvetica,12\"\n",gplotlabel);
1.238     brouard  7430:        fprintf(ficgp,"set ter svg size 640, 480\n\
1.261     brouard  7431: 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  7432:        /*fprintf(ficgp,",\"e%s\" every :::%d::%d u 1:($%d-2*$%d) \"\%%lf ",fileres,k1-1,k1-1,k,k+1);
                   7433:          for (i=1; i<= nlstate*2 ; i ++) fprintf(ficgp,"\%%lf (\%%lf) ");
                   7434:          fprintf(ficgp,"\" t \"e%d1\" w l",cpt);
                   7435:          fprintf(ficgp,",\"e%s\" every :::%d::%d u 1:($%d+2*$%d) \"\%%lf ",fileres,k1-1,k1-1,k,k+1);
                   7436:          for (i=1; i<= nlstate*2 ; i ++) fprintf(ficgp,"\%%lf (\%%lf) ");
                   7437:          fprintf(ficgp,"\" t \"e%d1\" w l",cpt);
1.219     brouard  7438:                                
1.238     brouard  7439:        */
                   7440:        for (i=1; i< nlstate ; i ++) {
1.261     brouard  7441:          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  7442:          /*    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  7443:                                
1.238     brouard  7444:        } 
1.261     brouard  7445:        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  7446:       }
1.264     brouard  7447:       fprintf(ficgp,"\nunset label;\n");
1.238     brouard  7448:     } /* end nres */
                   7449:   } /* end kl 3eme */
1.126     brouard  7450:   
1.223     brouard  7451:   /* 4eme */
1.201     brouard  7452:   /* Survival functions (period) from state i in state j by initial state i */
1.238     brouard  7453:   for (k1=1; k1<=m; k1++){    /* For each covariate and each value */
                   7454:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.253     brouard  7455:       if(m != 1 && TKresult[nres]!= k1)
1.223     brouard  7456:        continue;
1.238     brouard  7457:       for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each life state cpt*/
1.264     brouard  7458:        strcpy(gplotlabel,"(");
1.238     brouard  7459:        fprintf(ficgp,"\n#\n#\n# Survival functions in state j : 'LIJ_' files, cov=%d state=%d",k1, cpt);
                   7460:        for (k=1; k<=cptcoveff; k++){    /* For each covariate and each value */
                   7461:          lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate number corresponding to k1 combination */
                   7462:          /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   7463:          /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   7464:          /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
                   7465:          vlv= nbcode[Tvaraff[k]][lv];
                   7466:          fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv);
1.264     brouard  7467:          sprintf(gplotlabel+strlen(gplotlabel)," V%d=%d ",Tvaraff[k],vlv);
1.238     brouard  7468:        }
                   7469:        for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
                   7470:          fprintf(ficgp," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
1.264     brouard  7471:          sprintf(gplotlabel+strlen(gplotlabel)," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
1.238     brouard  7472:        }       
1.264     brouard  7473:        strcpy(gplotlabel+strlen(gplotlabel),")");
1.238     brouard  7474:        fprintf(ficgp,"\n#\n");
                   7475:        if(invalidvarcomb[k1]){
                   7476:          fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   7477:          continue;
1.223     brouard  7478:        }
1.238     brouard  7479:       
1.241     brouard  7480:        fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" \n",subdirf2(optionfilefiname,"LIJ_"),cpt,k1,nres);
1.264     brouard  7481:        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  7482:        fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Probability to be alive\" \n\
                   7483: set ter svg size 640, 480\nunset log y\nplot [%.f:%.f]  ", ageminpar, agemaxpar);
                   7484:        k=3;
                   7485:        for (i=1; i<= nlstate ; i ++){
                   7486:          if(i==1){
                   7487:            fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"PIJ_"));
                   7488:          }else{
                   7489:            fprintf(ficgp,", '' ");
                   7490:          }
                   7491:          l=(nlstate+ndeath)*(i-1)+1;
                   7492:          fprintf(ficgp," u ($1==%d ? ($3):1/0):($%d/($%d",k1,k+l+(cpt-1),k+l);
                   7493:          for (j=2; j<= nlstate+ndeath ; j ++)
                   7494:            fprintf(ficgp,"+$%d",k+l+j-1);
                   7495:          fprintf(ficgp,")) t \"l(%d,%d)\" w l",i,cpt);
                   7496:        } /* nlstate */
1.264     brouard  7497:        fprintf(ficgp,"\nset out; unset label;\n");
1.238     brouard  7498:       } /* end cpt state*/ 
                   7499:     } /* end nres */
                   7500:   } /* end covariate k1 */  
                   7501: 
1.220     brouard  7502: /* 5eme */
1.201     brouard  7503:   /* Survival functions (period) from state i in state j by final state j */
1.238     brouard  7504:   for (k1=1; k1<= m ; k1++){ /* For each covariate combination if any */
                   7505:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.253     brouard  7506:       if(m != 1 && TKresult[nres]!= k1)
1.227     brouard  7507:        continue;
1.238     brouard  7508:       for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each inital state  */
1.264     brouard  7509:        strcpy(gplotlabel,"(");
1.238     brouard  7510:        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);
                   7511:        for (k=1; k<=cptcoveff; k++){    /* For each covariate and each value */
                   7512:          lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate number corresponding to k1 combination */
                   7513:          /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   7514:          /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   7515:          /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
                   7516:          vlv= nbcode[Tvaraff[k]][lv];
                   7517:          fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv);
1.264     brouard  7518:          sprintf(gplotlabel+strlen(gplotlabel)," V%d=%d ",Tvaraff[k],vlv);
1.238     brouard  7519:        }
                   7520:        for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
                   7521:          fprintf(ficgp," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
1.264     brouard  7522:          sprintf(gplotlabel+strlen(gplotlabel)," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
1.238     brouard  7523:        }       
1.264     brouard  7524:        strcpy(gplotlabel+strlen(gplotlabel),")");
1.238     brouard  7525:        fprintf(ficgp,"\n#\n");
                   7526:        if(invalidvarcomb[k1]){
                   7527:          fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   7528:          continue;
                   7529:        }
1.227     brouard  7530:       
1.241     brouard  7531:        fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" \n",subdirf2(optionfilefiname,"LIJT_"),cpt,k1,nres);
1.264     brouard  7532:        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  7533:        fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Probability to be alive\" \n\
                   7534: set ter svg size 640, 480\nunset log y\nplot [%.f:%.f]  ", ageminpar, agemaxpar);
                   7535:        k=3;
                   7536:        for (j=1; j<= nlstate ; j ++){ /* Lived in state j */
                   7537:          if(j==1)
                   7538:            fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"PIJ_"));
                   7539:          else
                   7540:            fprintf(ficgp,", '' ");
                   7541:          l=(nlstate+ndeath)*(cpt-1) +j;
                   7542:          fprintf(ficgp," u (($1==%d && (floor($2)%%5 == 0)) ? ($3):1/0):($%d",k1,k+l);
                   7543:          /* for (i=2; i<= nlstate+ndeath ; i ++) */
                   7544:          /*   fprintf(ficgp,"+$%d",k+l+i-1); */
                   7545:          fprintf(ficgp,") t \"l(%d,%d)\" w l",cpt,j);
                   7546:        } /* nlstate */
                   7547:        fprintf(ficgp,", '' ");
                   7548:        fprintf(ficgp," u (($1==%d && (floor($2)%%5 == 0)) ? ($3):1/0):(",k1);
                   7549:        for (j=1; j<= nlstate ; j ++){ /* Lived in state j */
                   7550:          l=(nlstate+ndeath)*(cpt-1) +j;
                   7551:          if(j < nlstate)
                   7552:            fprintf(ficgp,"$%d +",k+l);
                   7553:          else
                   7554:            fprintf(ficgp,"$%d) t\"l(%d,.)\" w l",k+l,cpt);
                   7555:        }
1.264     brouard  7556:        fprintf(ficgp,"\nset out; unset label;\n");
1.238     brouard  7557:       } /* end cpt state*/ 
                   7558:     } /* end covariate */  
                   7559:   } /* end nres */
1.227     brouard  7560:   
1.220     brouard  7561: /* 6eme */
1.202     brouard  7562:   /* CV preval stable (period) for each covariate */
1.237     brouard  7563:   for (k1=1; k1<= m ; k1 ++) /* For each covariate combination if any */
                   7564:   for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.253     brouard  7565:     if(m != 1 && TKresult[nres]!= k1)
1.237     brouard  7566:       continue;
1.255     brouard  7567:     for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each life state of arrival */
1.264     brouard  7568:       strcpy(gplotlabel,"(");      
1.288     brouard  7569:       fprintf(ficgp,"\n#\n#\n#CV preval stable (forward): 'pij' files, covariatecombination#=%d state=%d",k1, cpt);
1.225     brouard  7570:       for (k=1; k<=cptcoveff; k++){    /* For each covariate and each value */
1.227     brouard  7571:        lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate number corresponding to k1 combination */
                   7572:        /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   7573:        /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   7574:        /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
                   7575:        vlv= nbcode[Tvaraff[k]][lv];
                   7576:        fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv);
1.264     brouard  7577:        sprintf(gplotlabel+strlen(gplotlabel)," V%d=%d ",Tvaraff[k],vlv);
1.211     brouard  7578:       }
1.237     brouard  7579:       for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
                   7580:        fprintf(ficgp," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
1.264     brouard  7581:        sprintf(gplotlabel+strlen(gplotlabel)," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
1.237     brouard  7582:       }        
1.264     brouard  7583:       strcpy(gplotlabel+strlen(gplotlabel),")");
1.211     brouard  7584:       fprintf(ficgp,"\n#\n");
1.223     brouard  7585:       if(invalidvarcomb[k1]){
1.227     brouard  7586:        fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   7587:        continue;
1.223     brouard  7588:       }
1.227     brouard  7589:       
1.241     brouard  7590:       fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" \n",subdirf2(optionfilefiname,"P_"),cpt,k1,nres);
1.264     brouard  7591:       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  7592:       fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Probability\" \n\
1.238     brouard  7593: set ter svg size 640, 480\nunset log y\nplot [%.f:%.f]  ", ageminpar, agemaxpar);
1.211     brouard  7594:       k=3; /* Offset */
1.255     brouard  7595:       for (i=1; i<= nlstate ; i ++){ /* State of origin */
1.227     brouard  7596:        if(i==1)
                   7597:          fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"PIJ_"));
                   7598:        else
                   7599:          fprintf(ficgp,", '' ");
1.255     brouard  7600:        l=(nlstate+ndeath)*(i-1)+1; /* 1, 1+ nlstate+ndeath, 1+2*(nlstate+ndeath) */
1.227     brouard  7601:        fprintf(ficgp," u ($1==%d ? ($3):1/0):($%d/($%d",k1,k+l+(cpt-1),k+l);
                   7602:        for (j=2; j<= nlstate ; j ++)
                   7603:          fprintf(ficgp,"+$%d",k+l+j-1);
                   7604:        fprintf(ficgp,")) t \"prev(%d,%d)\" w l",i,cpt);
1.153     brouard  7605:       } /* nlstate */
1.264     brouard  7606:       fprintf(ficgp,"\nset out; unset label;\n");
1.153     brouard  7607:     } /* end cpt state*/ 
                   7608:   } /* end covariate */  
1.227     brouard  7609:   
                   7610:   
1.220     brouard  7611: /* 7eme */
1.296     brouard  7612:   if(prevbcast == 1){
1.288     brouard  7613:     /* CV backward prevalence  for each covariate */
1.237     brouard  7614:     for (k1=1; k1<= m ; k1 ++) /* For each covariate combination if any */
                   7615:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.253     brouard  7616:       if(m != 1 && TKresult[nres]!= k1)
1.237     brouard  7617:        continue;
1.268     brouard  7618:       for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each life origin state */
1.264     brouard  7619:        strcpy(gplotlabel,"(");      
1.288     brouard  7620:        fprintf(ficgp,"\n#\n#\n#CV Backward stable prevalence: 'pijb' files, covariatecombination#=%d state=%d",k1, cpt);
1.227     brouard  7621:        for (k=1; k<=cptcoveff; k++){    /* For each covariate and each value */
                   7622:          lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate number corresponding to k1 combination */
                   7623:          /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   7624:          /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
1.223     brouard  7625:          /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
1.227     brouard  7626:          vlv= nbcode[Tvaraff[k]][lv];
                   7627:          fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv);
1.264     brouard  7628:          sprintf(gplotlabel+strlen(gplotlabel)," V%d=%d ",Tvaraff[k],vlv);
1.227     brouard  7629:        }
1.237     brouard  7630:        for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
                   7631:          fprintf(ficgp," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
1.264     brouard  7632:          sprintf(gplotlabel+strlen(gplotlabel)," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
1.237     brouard  7633:        }       
1.264     brouard  7634:        strcpy(gplotlabel+strlen(gplotlabel),")");
1.227     brouard  7635:        fprintf(ficgp,"\n#\n");
                   7636:        if(invalidvarcomb[k1]){
                   7637:          fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   7638:          continue;
                   7639:        }
                   7640:        
1.241     brouard  7641:        fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" \n",subdirf2(optionfilefiname,"PB_"),cpt,k1,nres);
1.268     brouard  7642:        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  7643:        fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Probability\" \n\
1.238     brouard  7644: set ter svg size 640, 480\nunset log y\nplot [%.f:%.f]  ", ageminpar, agemaxpar);
1.227     brouard  7645:        k=3; /* Offset */
1.268     brouard  7646:        for (i=1; i<= nlstate ; i ++){ /* State of arrival */
1.227     brouard  7647:          if(i==1)
                   7648:            fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"PIJB_"));
                   7649:          else
                   7650:            fprintf(ficgp,", '' ");
                   7651:          /* l=(nlstate+ndeath)*(i-1)+1; */
1.255     brouard  7652:          l=(nlstate+ndeath)*(cpt-1)+1; /* fixed for i; cpt=1 1, cpt=2 1+ nlstate+ndeath, 1+2*(nlstate+ndeath) */
1.227     brouard  7653:          /* fprintf(ficgp," u ($1==%d ? ($3):1/0):($%d/($%d",k1,k+l+(cpt-1),k+l); /\* a vérifier *\/ */
                   7654:          /* 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  7655:          fprintf(ficgp," u ($1==%d ? ($3):1/0):($%d",k1,k+l+i-1); /* To be verified */
1.227     brouard  7656:          /* for (j=2; j<= nlstate ; j ++) */
                   7657:          /*    fprintf(ficgp,"+$%d",k+l+j-1); */
                   7658:          /*    /\* fprintf(ficgp,"+$%d",k+l+j-1); *\/ */
1.268     brouard  7659:          fprintf(ficgp,") t \"bprev(%d,%d)\" w l",cpt,i);
1.227     brouard  7660:        } /* nlstate */
1.264     brouard  7661:        fprintf(ficgp,"\nset out; unset label;\n");
1.218     brouard  7662:       } /* end cpt state*/ 
                   7663:     } /* end covariate */  
1.296     brouard  7664:   } /* End if prevbcast */
1.218     brouard  7665:   
1.223     brouard  7666:   /* 8eme */
1.218     brouard  7667:   if(prevfcast==1){
1.288     brouard  7668:     /* Projection from cross-sectional to forward stable (period) prevalence for each covariate */
1.218     brouard  7669:     
1.237     brouard  7670:     for (k1=1; k1<= m ; k1 ++) /* For each covariate combination if any */
                   7671:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.253     brouard  7672:       if(m != 1 && TKresult[nres]!= k1)
1.237     brouard  7673:        continue;
1.211     brouard  7674:       for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each life state */
1.264     brouard  7675:        strcpy(gplotlabel,"(");      
1.288     brouard  7676:        fprintf(ficgp,"\n#\n#\n#Projection of prevalence to forward stable prevalence (period): 'PROJ_' files, covariatecombination#=%d state=%d",k1, cpt);
1.227     brouard  7677:        for (k=1; k<=cptcoveff; k++){    /* For each correspondig covariate value  */
                   7678:          lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate value corresponding to k1 combination and kth covariate */
                   7679:          /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   7680:          /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   7681:          /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
                   7682:          vlv= nbcode[Tvaraff[k]][lv];
                   7683:          fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv);
1.264     brouard  7684:          sprintf(gplotlabel+strlen(gplotlabel)," V%d=%d ",Tvaraff[k],vlv);
1.227     brouard  7685:        }
1.237     brouard  7686:        for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
                   7687:          fprintf(ficgp," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
1.264     brouard  7688:          sprintf(gplotlabel+strlen(gplotlabel)," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
1.237     brouard  7689:        }       
1.264     brouard  7690:        strcpy(gplotlabel+strlen(gplotlabel),")");
1.227     brouard  7691:        fprintf(ficgp,"\n#\n");
                   7692:        if(invalidvarcomb[k1]){
                   7693:          fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   7694:          continue;
                   7695:        }
                   7696:        
                   7697:        fprintf(ficgp,"# hpijx=probability over h years, hp.jx is weighted by observed prev\n ");
1.241     brouard  7698:        fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" \n",subdirf2(optionfilefiname,"PROJ_"),cpt,k1,nres);
1.264     brouard  7699:        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  7700:        fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Prevalence\" \n\
1.238     brouard  7701: set ter svg size 640, 480\nunset log y\nplot [%.f:%.f]  ", ageminpar, agemaxpar);
1.266     brouard  7702: 
                   7703:        /* for (i=1; i<= nlstate+1 ; i ++){  /\* nlstate +1 p11 p21 p.1 *\/ */
                   7704:        istart=nlstate+1; /* Could be one if by state, but nlstate+1 is w.i projection only */
                   7705:        /*istart=1;*/ /* Could be one if by state, but nlstate+1 is w.i projection only */
                   7706:        for (i=istart; i<= nlstate+1 ; i ++){  /* nlstate +1 p11 p21 p.1 */
1.227     brouard  7707:          /*#  V1  = 1  V2 =  0 yearproj age p11 p21 p.1 p12 p22 p.2 p13 p23 p.3*/
                   7708:          /*#   1    2   3    4    5      6  7   8   9   10   11 12  13   14  15 */   
                   7709:          /*# yearproj age p11 p21 p.1 p12 p22 p.2 p13 p23 p.3*/
                   7710:          /*#   1       2   3    4    5      6  7   8   9   10   11 12  13   14  15 */   
1.266     brouard  7711:          if(i==istart){
1.227     brouard  7712:            fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"F_"));
                   7713:          }else{
                   7714:            fprintf(ficgp,",\\\n '' ");
                   7715:          }
                   7716:          if(cptcoveff ==0){ /* No covariate */
                   7717:            ioffset=2; /* Age is in 2 */
                   7718:            /*# yearproj age p11 p21 p31 p.1 p12 p22 p32 p.2 p13 p23 p33 p.3 p14 p24 p34 p.4*/
                   7719:            /*#   1       2   3   4   5  6    7  8   9   10  11  12  13  14  15  16  17  18 */
                   7720:            /*# V1  = 1 yearproj age p11 p21 p31 p.1 p12 p22 p32 p.2 p13 p23 p33 p.3 p14 p24 p34 p.4*/
                   7721:            /*#  1    2        3   4   5  6    7  8   9   10  11  12  13  14  15  16  17  18 */
                   7722:            fprintf(ficgp," u %d:(", ioffset); 
1.266     brouard  7723:            if(i==nlstate+1){
1.270     brouard  7724:              fprintf(ficgp," $%d/(1.-$%d)):1 t 'pw.%d' with line lc variable ",        \
1.266     brouard  7725:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1),  ioffset+1+(i-1)+(nlstate+1)*nlstate,cpt );
                   7726:              fprintf(ficgp,",\\\n '' ");
                   7727:              fprintf(ficgp," u %d:(",ioffset); 
1.270     brouard  7728:              fprintf(ficgp," (($1-$2) == %d ) ? $%d/(1.-$%d) : 1/0):1 with labels center not ", \
1.266     brouard  7729:                     offyear,                           \
1.268     brouard  7730:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1),  ioffset+1+(i-1)+(nlstate+1)*nlstate );
1.266     brouard  7731:            }else
1.227     brouard  7732:              fprintf(ficgp," $%d/(1.-$%d)) t 'p%d%d' with line ",      \
                   7733:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1),  ioffset+1+(i-1)+(nlstate+1)*nlstate,i,cpt );
                   7734:          }else{ /* more than 2 covariates */
1.270     brouard  7735:            ioffset=2*cptcoveff+2; /* Age is in 4 or 6 or etc.*/
                   7736:            /*#  V1  = 1  V2 =  0 yearproj age p11 p21 p.1 p12 p22 p.2 p13 p23 p.3*/
                   7737:            /*#   1    2   3    4    5      6  7   8   9   10   11 12  13   14  15 */
                   7738:            iyearc=ioffset-1;
                   7739:            iagec=ioffset;
1.227     brouard  7740:            fprintf(ficgp," u %d:(",ioffset); 
                   7741:            kl=0;
                   7742:            strcpy(gplotcondition,"(");
                   7743:            for (k=1; k<=cptcoveff; k++){    /* For each covariate writing the chain of conditions */
                   7744:              lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate value corresponding to combination k1 and covariate k */
                   7745:              /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   7746:              /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   7747:              /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
                   7748:              vlv= nbcode[Tvaraff[k]][lv]; /* Value of the modality of Tvaraff[k] */
                   7749:              kl++;
                   7750:              sprintf(gplotcondition+strlen(gplotcondition),"$%d==%d && $%d==%d " ,kl,Tvaraff[k], kl+1, nbcode[Tvaraff[k]][lv]);
                   7751:              kl++;
                   7752:              if(k <cptcoveff && cptcoveff>1)
                   7753:                sprintf(gplotcondition+strlen(gplotcondition)," && ");
                   7754:            }
                   7755:            strcpy(gplotcondition+strlen(gplotcondition),")");
                   7756:            /* 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 *\/ */
                   7757:            /*6+(cpt-1)*(nlstate+1)+1+(i-1)+(nlstate+1)*nlstate; 6+(1-1)*(2+1)+1+(1-1) +(2+1)*2=13 */ 
                   7758:            /*6+1+(i-1)+(nlstate+1)*nlstate; 6+1+(1-1) +(2+1)*2=13 */ 
                   7759:            /* ''  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*/
                   7760:            if(i==nlstate+1){
1.270     brouard  7761:              fprintf(ficgp,"%s ? $%d/(1.-$%d) : 1/0):%d t 'p.%d' with line lc variable", gplotcondition, \
                   7762:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1),  ioffset+1+(i-1)+(nlstate+1)*nlstate,iyearc, cpt );
1.266     brouard  7763:              fprintf(ficgp,",\\\n '' ");
1.270     brouard  7764:              fprintf(ficgp," u %d:(",iagec); 
                   7765:              fprintf(ficgp,"%s && (($%d-$%d) == %d ) ? $%d/(1.-$%d) : 1/0):%d with labels center not ", gplotcondition, \
                   7766:                      iyearc, iagec, offyear,                           \
                   7767:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1),  ioffset+1+(i-1)+(nlstate+1)*nlstate, iyearc );
1.266     brouard  7768: /*  '' 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  7769:            }else{
                   7770:              fprintf(ficgp,"%s ? $%d/(1.-$%d) : 1/0) t 'p%d%d' with line ", gplotcondition, \
                   7771:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1), ioffset +1+(i-1)+(nlstate+1)*nlstate,i,cpt );
                   7772:            }
                   7773:          } /* end if covariate */
                   7774:        } /* nlstate */
1.264     brouard  7775:        fprintf(ficgp,"\nset out; unset label;\n");
1.223     brouard  7776:       } /* end cpt state*/
                   7777:     } /* end covariate */
                   7778:   } /* End if prevfcast */
1.227     brouard  7779:   
1.296     brouard  7780:   if(prevbcast==1){
1.268     brouard  7781:     /* Back projection from cross-sectional to stable (mixed) for each covariate */
                   7782:     
                   7783:     for (k1=1; k1<= m ; k1 ++) /* For each covariate combination if any */
                   7784:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
                   7785:       if(m != 1 && TKresult[nres]!= k1)
                   7786:        continue;
                   7787:       for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each life state */
                   7788:        strcpy(gplotlabel,"(");      
                   7789:        fprintf(ficgp,"\n#\n#\n#Back projection of prevalence to stable (mixed) back prevalence: 'BPROJ_' files, covariatecombination#=%d originstate=%d",k1, cpt);
                   7790:        for (k=1; k<=cptcoveff; k++){    /* For each correspondig covariate value  */
                   7791:          lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate value corresponding to k1 combination and kth covariate */
                   7792:          /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   7793:          /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   7794:          /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
                   7795:          vlv= nbcode[Tvaraff[k]][lv];
                   7796:          fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv);
                   7797:          sprintf(gplotlabel+strlen(gplotlabel)," V%d=%d ",Tvaraff[k],vlv);
                   7798:        }
                   7799:        for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
                   7800:          fprintf(ficgp," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
                   7801:          sprintf(gplotlabel+strlen(gplotlabel)," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
                   7802:        }       
                   7803:        strcpy(gplotlabel+strlen(gplotlabel),")");
                   7804:        fprintf(ficgp,"\n#\n");
                   7805:        if(invalidvarcomb[k1]){
                   7806:          fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   7807:          continue;
                   7808:        }
                   7809:        
                   7810:        fprintf(ficgp,"# hbijx=backprobability over h years, hb.jx is weighted by observed prev at destination state\n ");
                   7811:        fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" \n",subdirf2(optionfilefiname,"PROJB_"),cpt,k1,nres);
                   7812:        fprintf(ficgp,"set label \"Origin alive state %d %s\" at graph 0.98,0.5 center rotate font \"Helvetica,12\"\n",cpt,gplotlabel);
                   7813:        fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Prevalence\" \n\
                   7814: set ter svg size 640, 480\nunset log y\nplot [%.f:%.f]  ", ageminpar, agemaxpar);
                   7815: 
                   7816:        /* for (i=1; i<= nlstate+1 ; i ++){  /\* nlstate +1 p11 p21 p.1 *\/ */
                   7817:        istart=nlstate+1; /* Could be one if by state, but nlstate+1 is w.i projection only */
                   7818:        /*istart=1;*/ /* Could be one if by state, but nlstate+1 is w.i projection only */
                   7819:        for (i=istart; i<= nlstate+1 ; i ++){  /* nlstate +1 p11 p21 p.1 */
                   7820:          /*#  V1  = 1  V2 =  0 yearproj age p11 p21 p.1 p12 p22 p.2 p13 p23 p.3*/
                   7821:          /*#   1    2   3    4    5      6  7   8   9   10   11 12  13   14  15 */   
                   7822:          /*# yearproj age p11 p21 p.1 p12 p22 p.2 p13 p23 p.3*/
                   7823:          /*#   1       2   3    4    5      6  7   8   9   10   11 12  13   14  15 */   
                   7824:          if(i==istart){
                   7825:            fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"FB_"));
                   7826:          }else{
                   7827:            fprintf(ficgp,",\\\n '' ");
                   7828:          }
                   7829:          if(cptcoveff ==0){ /* No covariate */
                   7830:            ioffset=2; /* Age is in 2 */
                   7831:            /*# yearproj age p11 p21 p31 p.1 p12 p22 p32 p.2 p13 p23 p33 p.3 p14 p24 p34 p.4*/
                   7832:            /*#   1       2   3   4   5  6    7  8   9   10  11  12  13  14  15  16  17  18 */
                   7833:            /*# V1  = 1 yearproj age p11 p21 p31 p.1 p12 p22 p32 p.2 p13 p23 p33 p.3 p14 p24 p34 p.4*/
                   7834:            /*#  1    2        3   4   5  6    7  8   9   10  11  12  13  14  15  16  17  18 */
                   7835:            fprintf(ficgp," u %d:(", ioffset); 
                   7836:            if(i==nlstate+1){
1.270     brouard  7837:              fprintf(ficgp," $%d/(1.-$%d)):1 t 'bw%d' with line lc variable ", \
1.268     brouard  7838:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1),  ioffset+1+(i-1)+(nlstate+1)*nlstate,cpt );
                   7839:              fprintf(ficgp,",\\\n '' ");
                   7840:              fprintf(ficgp," u %d:(",ioffset); 
1.270     brouard  7841:              fprintf(ficgp," (($1-$2) == %d ) ? $%d : 1/0):1 with labels center not ", \
1.268     brouard  7842:                     offbyear,                          \
                   7843:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1) );
                   7844:            }else
                   7845:              fprintf(ficgp," $%d/(1.-$%d)) t 'b%d%d' with line ",      \
                   7846:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1),  ioffset+1+(i-1)+(nlstate+1)*nlstate,cpt,i );
                   7847:          }else{ /* more than 2 covariates */
1.270     brouard  7848:            ioffset=2*cptcoveff+2; /* Age is in 4 or 6 or etc.*/
                   7849:            /*#  V1  = 1  V2 =  0 yearproj age p11 p21 p.1 p12 p22 p.2 p13 p23 p.3*/
                   7850:            /*#   1    2   3    4    5      6  7   8   9   10   11 12  13   14  15 */
                   7851:            iyearc=ioffset-1;
                   7852:            iagec=ioffset;
1.268     brouard  7853:            fprintf(ficgp," u %d:(",ioffset); 
                   7854:            kl=0;
                   7855:            strcpy(gplotcondition,"(");
                   7856:            for (k=1; k<=cptcoveff; k++){    /* For each covariate writing the chain of conditions */
                   7857:              lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate value corresponding to combination k1 and covariate k */
                   7858:              /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   7859:              /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   7860:              /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
                   7861:              vlv= nbcode[Tvaraff[k]][lv]; /* Value of the modality of Tvaraff[k] */
                   7862:              kl++;
                   7863:              sprintf(gplotcondition+strlen(gplotcondition),"$%d==%d && $%d==%d " ,kl,Tvaraff[k], kl+1, nbcode[Tvaraff[k]][lv]);
                   7864:              kl++;
                   7865:              if(k <cptcoveff && cptcoveff>1)
                   7866:                sprintf(gplotcondition+strlen(gplotcondition)," && ");
                   7867:            }
                   7868:            strcpy(gplotcondition+strlen(gplotcondition),")");
                   7869:            /* 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 *\/ */
                   7870:            /*6+(cpt-1)*(nlstate+1)+1+(i-1)+(nlstate+1)*nlstate; 6+(1-1)*(2+1)+1+(1-1) +(2+1)*2=13 */ 
                   7871:            /*6+1+(i-1)+(nlstate+1)*nlstate; 6+1+(1-1) +(2+1)*2=13 */ 
                   7872:            /* ''  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*/
                   7873:            if(i==nlstate+1){
1.270     brouard  7874:              fprintf(ficgp,"%s ? $%d : 1/0):%d t 'bw%d' with line lc variable", gplotcondition, \
                   7875:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1),iyearc,cpt );
1.268     brouard  7876:              fprintf(ficgp,",\\\n '' ");
1.270     brouard  7877:              fprintf(ficgp," u %d:(",iagec); 
1.268     brouard  7878:              /* fprintf(ficgp,"%s && (($5-$6) == %d ) ? $%d/(1.-$%d) : 1/0):5 with labels center not ", gplotcondition, \ */
1.270     brouard  7879:              fprintf(ficgp,"%s && (($%d-$%d) == %d ) ? $%d : 1/0):%d with labels center not ", gplotcondition, \
                   7880:                      iyearc,iagec,offbyear,                            \
                   7881:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1), iyearc );
1.268     brouard  7882: /*  '' u 6:(($1==1 && $2==0  && $3==2 && $4==0) && (($5-$6) == 1947) ? $10/(1.-$22) : 1/0):5 with labels center boxed not*/
                   7883:            }else{
                   7884:              /* fprintf(ficgp,"%s ? $%d/(1.-$%d) : 1/0) t 'p%d%d' with line ", gplotcondition, \ */
                   7885:              fprintf(ficgp,"%s ? $%d : 1/0) t 'b%d%d' with line ", gplotcondition, \
                   7886:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1), cpt,i );
                   7887:            }
                   7888:          } /* end if covariate */
                   7889:        } /* nlstate */
                   7890:        fprintf(ficgp,"\nset out; unset label;\n");
                   7891:       } /* end cpt state*/
                   7892:     } /* end covariate */
1.296     brouard  7893:   } /* End if prevbcast */
1.268     brouard  7894:   
1.227     brouard  7895:   
1.238     brouard  7896:   /* 9eme writing MLE parameters */
                   7897:   fprintf(ficgp,"\n##############\n#9eme MLE estimated parameters\n#############\n");
1.126     brouard  7898:   for(i=1,jk=1; i <=nlstate; i++){
1.187     brouard  7899:     fprintf(ficgp,"# initial state %d\n",i);
1.126     brouard  7900:     for(k=1; k <=(nlstate+ndeath); k++){
                   7901:       if (k != i) {
1.227     brouard  7902:        fprintf(ficgp,"#   current state %d\n",k);
                   7903:        for(j=1; j <=ncovmodel; j++){
                   7904:          fprintf(ficgp,"p%d=%f; ",jk,p[jk]);
                   7905:          jk++; 
                   7906:        }
                   7907:        fprintf(ficgp,"\n");
1.126     brouard  7908:       }
                   7909:     }
1.223     brouard  7910:   }
1.187     brouard  7911:   fprintf(ficgp,"##############\n#\n");
1.227     brouard  7912:   
1.145     brouard  7913:   /*goto avoid;*/
1.238     brouard  7914:   /* 10eme Graphics of probabilities or incidences using written MLE parameters */
                   7915:   fprintf(ficgp,"\n##############\n#10eme Graphics of probabilities or incidences\n#############\n");
1.187     brouard  7916:   fprintf(ficgp,"# logi(p12/p11)=a12+b12*age+c12age*age+d12*V1+e12*V1*age\n");
                   7917:   fprintf(ficgp,"# logi(p12/p11)=p1 +p2*age +p3*age*age+ p4*V1+ p5*V1*age\n");
                   7918:   fprintf(ficgp,"# logi(p13/p11)=a13+b13*age+c13age*age+d13*V1+e13*V1*age\n");
                   7919:   fprintf(ficgp,"# logi(p13/p11)=p6 +p7*age +p8*age*age+ p9*V1+ p10*V1*age\n");
                   7920:   fprintf(ficgp,"# p12+p13+p14+p11=1=p11(1+exp(a12+b12*age+c12age*age+d12*V1+e12*V1*age)\n");
                   7921:   fprintf(ficgp,"#                      +exp(a13+b13*age+c13age*age+d13*V1+e13*V1*age)+...)\n");
                   7922:   fprintf(ficgp,"# p11=1/(1+exp(a12+b12*age+c12age*age+d12*V1+e12*V1*age)\n");
                   7923:   fprintf(ficgp,"#                      +exp(a13+b13*age+c13age*age+d13*V1+e13*V1*age)+...)\n");
                   7924:   fprintf(ficgp,"# p12=exp(a12+b12*age+c12age*age+d12*V1+e12*V1*age)/\n");
                   7925:   fprintf(ficgp,"#     (1+exp(a12+b12*age+c12age*age+d12*V1+e12*V1*age)\n");
                   7926:   fprintf(ficgp,"#       +exp(a13+b13*age+c13age*age+d13*V1+e13*V1*age))\n");
                   7927:   fprintf(ficgp,"#       +exp(a14+b14*age+c14age*age+d14*V1+e14*V1*age)+...)\n");
                   7928:   fprintf(ficgp,"#\n");
1.223     brouard  7929:   for(ng=1; ng<=3;ng++){ /* Number of graphics: first is logit, 2nd is probabilities, third is incidences per year*/
1.238     brouard  7930:     fprintf(ficgp,"#Number of graphics: first is logit, 2nd is probabilities, third is incidences per year\n");
1.237     brouard  7931:     fprintf(ficgp,"#model=%s \n",model);
1.238     brouard  7932:     fprintf(ficgp,"# Type of graphic ng=%d\n",ng);
1.264     brouard  7933:     fprintf(ficgp,"#   k1=1 to 2^%d=%d\n",cptcoveff,m);/* to be checked */
                   7934:     for(k1=1; k1 <=m; k1++)  /* For each combination of covariate */
1.237     brouard  7935:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.264     brouard  7936:       if(m != 1 && TKresult[nres]!= k1)
1.237     brouard  7937:        continue;
1.264     brouard  7938:       fprintf(ficgp,"\n\n# Combination of dummy  k1=%d which is ",k1);
                   7939:       strcpy(gplotlabel,"(");
1.276     brouard  7940:       /*sprintf(gplotlabel+strlen(gplotlabel)," Dummy combination %d ",k1);*/
1.264     brouard  7941:       for (k=1; k<=cptcoveff; k++){    /* For each correspondig covariate value  */
                   7942:        lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate value corresponding to k1 combination and kth covariate */
                   7943:        /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   7944:        /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   7945:        /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
                   7946:        vlv= nbcode[Tvaraff[k]][lv];
                   7947:        fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv);
                   7948:        sprintf(gplotlabel+strlen(gplotlabel)," V%d=%d ",Tvaraff[k],vlv);
                   7949:       }
1.237     brouard  7950:       for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
                   7951:        fprintf(ficgp," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
1.264     brouard  7952:        sprintf(gplotlabel+strlen(gplotlabel)," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
1.237     brouard  7953:       }        
1.264     brouard  7954:       strcpy(gplotlabel+strlen(gplotlabel),")");
1.237     brouard  7955:       fprintf(ficgp,"\n#\n");
1.264     brouard  7956:       fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" ",subdirf2(optionfilefiname,"PE_"),k1,ng,nres);
1.276     brouard  7957:       fprintf(ficgp,"\nset key outside ");
                   7958:       /* fprintf(ficgp,"\nset label \"%s\" at graph 1.2,0.5 center rotate font \"Helvetica,12\"\n",gplotlabel); */
                   7959:       fprintf(ficgp,"\nset title \"%s\" font \"Helvetica,12\"\n",gplotlabel);
1.223     brouard  7960:       fprintf(ficgp,"\nset ter svg size 640, 480 ");
                   7961:       if (ng==1){
                   7962:        fprintf(ficgp,"\nset ylabel \"Value of the logit of the model\"\n"); /* exp(a12+b12*x) could be nice */
                   7963:        fprintf(ficgp,"\nunset log y");
                   7964:       }else if (ng==2){
                   7965:        fprintf(ficgp,"\nset ylabel \"Probability\"\n");
                   7966:        fprintf(ficgp,"\nset log y");
                   7967:       }else if (ng==3){
                   7968:        fprintf(ficgp,"\nset ylabel \"Quasi-incidence per year\"\n");
                   7969:        fprintf(ficgp,"\nset log y");
                   7970:       }else
                   7971:        fprintf(ficgp,"\nunset title ");
                   7972:       fprintf(ficgp,"\nplot  [%.f:%.f] ",ageminpar,agemaxpar);
                   7973:       i=1;
                   7974:       for(k2=1; k2<=nlstate; k2++) {
                   7975:        k3=i;
                   7976:        for(k=1; k<=(nlstate+ndeath); k++) {
                   7977:          if (k != k2){
                   7978:            switch( ng) {
                   7979:            case 1:
                   7980:              if(nagesqr==0)
                   7981:                fprintf(ficgp," p%d+p%d*x",i,i+1);
                   7982:              else /* nagesqr =1 */
                   7983:                fprintf(ficgp," p%d+p%d*x+p%d*x*x",i,i+1,i+1+nagesqr);
                   7984:              break;
                   7985:            case 2: /* ng=2 */
                   7986:              if(nagesqr==0)
                   7987:                fprintf(ficgp," exp(p%d+p%d*x",i,i+1);
                   7988:              else /* nagesqr =1 */
                   7989:                fprintf(ficgp," exp(p%d+p%d*x+p%d*x*x",i,i+1,i+1+nagesqr);
                   7990:              break;
                   7991:            case 3:
                   7992:              if(nagesqr==0)
                   7993:                fprintf(ficgp," %f*exp(p%d+p%d*x",YEARM/stepm,i,i+1);
                   7994:              else /* nagesqr =1 */
                   7995:                fprintf(ficgp," %f*exp(p%d+p%d*x+p%d*x*x",YEARM/stepm,i,i+1,i+1+nagesqr);
                   7996:              break;
                   7997:            }
                   7998:            ij=1;/* To be checked else nbcode[0][0] wrong */
1.237     brouard  7999:            ijp=1; /* product no age */
                   8000:            /* for(j=3; j <=ncovmodel-nagesqr; j++) { */
                   8001:            for(j=1; j <=cptcovt; j++) { /* For each covariate of the simplified model */
1.223     brouard  8002:              /* printf("Tage[%d]=%d, j=%d\n", ij, Tage[ij], j); */
1.268     brouard  8003:              if(cptcovage >0){ /* V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1, 2 V5 and V1 */
                   8004:                if(j==Tage[ij]) { /* Product by age  To be looked at!!*/
                   8005:                  if(ij <=cptcovage) { /* V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1, 2 V5 and V1 */
                   8006:                    if(DummyV[j]==0){
                   8007:                      fprintf(ficgp,"+p%d*%d*x",i+j+2+nagesqr-1,Tinvresult[nres][Tvar[j]]);;
                   8008:                    }else{ /* quantitative */
                   8009:                      fprintf(ficgp,"+p%d*%f*x",i+j+2+nagesqr-1,Tqinvresult[nres][Tvar[j]]); /* Tqinvresult in decoderesult */
                   8010:                      /* fprintf(ficgp,"+p%d*%d*x",i+j+nagesqr-1,nbcode[Tvar[j-2]][codtabm(k1,Tvar[j-2])]); */
                   8011:                    }
                   8012:                    ij++;
1.237     brouard  8013:                  }
1.268     brouard  8014:                } 
                   8015:              }else if(cptcovprod >0){
                   8016:                if(j==Tprod[ijp]) { /* */ 
                   8017:                  /* printf("Tprod[%d]=%d, j=%d\n", ij, Tprod[ijp], j); */
                   8018:                  if(ijp <=cptcovprod) { /* Product */
                   8019:                    if(DummyV[Tvard[ijp][1]]==0){/* Vn is dummy */
                   8020:                      if(DummyV[Tvard[ijp][2]]==0){/* Vn and Vm are dummy */
                   8021:                        /* 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)]); */
                   8022:                        fprintf(ficgp,"+p%d*%d*%d",i+j+2+nagesqr-1,Tinvresult[nres][Tvard[ijp][1]],Tinvresult[nres][Tvard[ijp][2]]);
                   8023:                      }else{ /* Vn is dummy and Vm is quanti */
                   8024:                        /* fprintf(ficgp,"+p%d*%d*%f",i+j+2+nagesqr-1,nbcode[Tvard[ijp][1]][codtabm(k1,j)],Tqinvresult[nres][Tvard[ijp][2]]); */
                   8025:                        fprintf(ficgp,"+p%d*%d*%f",i+j+2+nagesqr-1,Tinvresult[nres][Tvard[ijp][1]],Tqinvresult[nres][Tvard[ijp][2]]);
                   8026:                      }
                   8027:                    }else{ /* Vn*Vm Vn is quanti */
                   8028:                      if(DummyV[Tvard[ijp][2]]==0){
                   8029:                        fprintf(ficgp,"+p%d*%d*%f",i+j+2+nagesqr-1,Tinvresult[nres][Tvard[ijp][2]],Tqinvresult[nres][Tvard[ijp][1]]);
                   8030:                      }else{ /* Both quanti */
                   8031:                        fprintf(ficgp,"+p%d*%f*%f",i+j+2+nagesqr-1,Tqinvresult[nres][Tvard[ijp][1]],Tqinvresult[nres][Tvard[ijp][2]]);
                   8032:                      }
1.237     brouard  8033:                    }
1.268     brouard  8034:                    ijp++;
1.237     brouard  8035:                  }
1.268     brouard  8036:                } /* end Tprod */
1.237     brouard  8037:              } else{  /* simple covariate */
1.264     brouard  8038:                /* fprintf(ficgp,"+p%d*%d",i+j+2+nagesqr-1,nbcode[Tvar[j]][codtabm(k1,j)]); /\* Valgrind bug nbcode *\/ */
1.237     brouard  8039:                if(Dummy[j]==0){
                   8040:                  fprintf(ficgp,"+p%d*%d",i+j+2+nagesqr-1,Tinvresult[nres][Tvar[j]]); /*  */
                   8041:                }else{ /* quantitative */
                   8042:                  fprintf(ficgp,"+p%d*%f",i+j+2+nagesqr-1,Tqinvresult[nres][Tvar[j]]); /* */
1.264     brouard  8043:                  /* fprintf(ficgp,"+p%d*%d*x",i+j+nagesqr-1,nbcode[Tvar[j-2]][codtabm(k1,Tvar[j-2])]); */
1.223     brouard  8044:                }
1.237     brouard  8045:              } /* end simple */
                   8046:            } /* end j */
1.223     brouard  8047:          }else{
                   8048:            i=i-ncovmodel;
                   8049:            if(ng !=1 ) /* For logit formula of log p11 is more difficult to get */
                   8050:              fprintf(ficgp," (1.");
                   8051:          }
1.227     brouard  8052:          
1.223     brouard  8053:          if(ng != 1){
                   8054:            fprintf(ficgp,")/(1");
1.227     brouard  8055:            
1.264     brouard  8056:            for(cpt=1; cpt <=nlstate; cpt++){ 
1.223     brouard  8057:              if(nagesqr==0)
1.264     brouard  8058:                fprintf(ficgp,"+exp(p%d+p%d*x",k3+(cpt-1)*ncovmodel,k3+(cpt-1)*ncovmodel+1);
1.223     brouard  8059:              else /* nagesqr =1 */
1.264     brouard  8060:                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  8061:               
1.223     brouard  8062:              ij=1;
                   8063:              for(j=3; j <=ncovmodel-nagesqr; j++){
1.268     brouard  8064:                 if(cptcovage >0){ 
                   8065:                   if((j-2)==Tage[ij]) { /* Bug valgrind */
                   8066:                     if(ij <=cptcovage) { /* Bug valgrind */
                   8067:                       fprintf(ficgp,"+p%d*%d*x",k3+(cpt-1)*ncovmodel+1+j-2+nagesqr,nbcode[Tvar[j-2]][codtabm(k1,j-2)]);
                   8068:                       /* fprintf(ficgp,"+p%d*%d*x",k3+(cpt-1)*ncovmodel+1+j-2+nagesqr,nbcode[Tvar[j-2]][codtabm(k1,Tvar[j-2])]); */
                   8069:                       ij++;
                   8070:                     }
                   8071:                   }
                   8072:                 }else
                   8073:                   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  8074:              }
                   8075:              fprintf(ficgp,")");
                   8076:            }
                   8077:            fprintf(ficgp,")");
                   8078:            if(ng ==2)
1.276     brouard  8079:              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  8080:            else /* ng= 3 */
1.276     brouard  8081:              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  8082:          }else{ /* end ng <> 1 */
                   8083:            if( k !=k2) /* logit p11 is hard to draw */
1.276     brouard  8084:              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  8085:          }
                   8086:          if ((k+k2)!= (nlstate*2+ndeath) && ng != 1)
                   8087:            fprintf(ficgp,",");
                   8088:          if (ng == 1 && k!=k2 && (k+k2)!= (nlstate*2+ndeath))
                   8089:            fprintf(ficgp,",");
                   8090:          i=i+ncovmodel;
                   8091:        } /* end k */
                   8092:       } /* end k2 */
1.276     brouard  8093:       /* fprintf(ficgp,"\n set out; unset label;set key default;\n"); */
                   8094:       fprintf(ficgp,"\n set out; unset title;set key default;\n");
1.264     brouard  8095:     } /* end k1 */
1.223     brouard  8096:   } /* end ng */
                   8097:   /* avoid: */
                   8098:   fflush(ficgp); 
1.126     brouard  8099: }  /* end gnuplot */
                   8100: 
                   8101: 
                   8102: /*************** Moving average **************/
1.219     brouard  8103: /* int movingaverage(double ***probs, double bage, double fage, double ***mobaverage, int mobilav, double bageout, double fageout){ */
1.222     brouard  8104:  int movingaverage(double ***probs, double bage, double fage, double ***mobaverage, int mobilav){
1.218     brouard  8105:    
1.222     brouard  8106:    int i, cpt, cptcod;
                   8107:    int modcovmax =1;
                   8108:    int mobilavrange, mob;
                   8109:    int iage=0;
1.288     brouard  8110:    int firstA1=0, firstA2=0;
1.222     brouard  8111: 
1.266     brouard  8112:    double sum=0., sumr=0.;
1.222     brouard  8113:    double age;
1.266     brouard  8114:    double *sumnewp, *sumnewm, *sumnewmr;
                   8115:    double *agemingood, *agemaxgood; 
                   8116:    double *agemingoodr, *agemaxgoodr; 
1.222     brouard  8117:   
                   8118:   
1.278     brouard  8119:    /* modcovmax=2*cptcoveff;  Max number of modalities. We suppose  */
                   8120:    /*             a covariate has 2 modalities, should be equal to ncovcombmax   */
1.222     brouard  8121: 
                   8122:    sumnewp = vector(1,ncovcombmax);
                   8123:    sumnewm = vector(1,ncovcombmax);
1.266     brouard  8124:    sumnewmr = vector(1,ncovcombmax);
1.222     brouard  8125:    agemingood = vector(1,ncovcombmax); 
1.266     brouard  8126:    agemingoodr = vector(1,ncovcombmax);        
1.222     brouard  8127:    agemaxgood = vector(1,ncovcombmax);
1.266     brouard  8128:    agemaxgoodr = vector(1,ncovcombmax);
1.222     brouard  8129: 
                   8130:    for (cptcod=1;cptcod<=ncovcombmax;cptcod++){
1.266     brouard  8131:      sumnewm[cptcod]=0.; sumnewmr[cptcod]=0.;
1.222     brouard  8132:      sumnewp[cptcod]=0.;
1.266     brouard  8133:      agemingood[cptcod]=0, agemingoodr[cptcod]=0;
                   8134:      agemaxgood[cptcod]=0, agemaxgoodr[cptcod]=0;
1.222     brouard  8135:    }
                   8136:    if (cptcovn<1) ncovcombmax=1; /* At least 1 pass */
                   8137:   
1.266     brouard  8138:    if(mobilav==-1 || mobilav==1||mobilav ==3 ||mobilav==5 ||mobilav== 7){
                   8139:      if(mobilav==1 || mobilav==-1) mobilavrange=5; /* default */
1.222     brouard  8140:      else mobilavrange=mobilav;
                   8141:      for (age=bage; age<=fage; age++)
                   8142:        for (i=1; i<=nlstate;i++)
                   8143:         for (cptcod=1;cptcod<=ncovcombmax;cptcod++)
                   8144:           mobaverage[(int)age][i][cptcod]=probs[(int)age][i][cptcod];
                   8145:      /* We keep the original values on the extreme ages bage, fage and for 
                   8146:        fage+1 and bage-1 we use a 3 terms moving average; for fage+2 bage+2
                   8147:        we use a 5 terms etc. until the borders are no more concerned. 
                   8148:      */ 
                   8149:      for (mob=3;mob <=mobilavrange;mob=mob+2){
                   8150:        for (age=bage+(mob-1)/2; age<=fage-(mob-1)/2; age++){
1.266     brouard  8151:         for (cptcod=1;cptcod<=ncovcombmax;cptcod++){
                   8152:           sumnewm[cptcod]=0.;
                   8153:           for (i=1; i<=nlstate;i++){
1.222     brouard  8154:             mobaverage[(int)age][i][cptcod] =probs[(int)age][i][cptcod];
                   8155:             for (cpt=1;cpt<=(mob-1)/2;cpt++){
                   8156:               mobaverage[(int)age][i][cptcod] +=probs[(int)age-cpt][i][cptcod];
                   8157:               mobaverage[(int)age][i][cptcod] +=probs[(int)age+cpt][i][cptcod];
                   8158:             }
                   8159:             mobaverage[(int)age][i][cptcod]=mobaverage[(int)age][i][cptcod]/mob;
1.266     brouard  8160:             sumnewm[cptcod]+=mobaverage[(int)age][i][cptcod];
                   8161:           } /* end i */
                   8162:           if(sumnewm[cptcod] >1.e-3) mobaverage[(int)age][i][cptcod]=mobaverage[(int)age][i][cptcod]/sumnewm[cptcod]; /* Rescaling to sum one */
                   8163:         } /* end cptcod */
1.222     brouard  8164:        }/* end age */
                   8165:      }/* end mob */
1.266     brouard  8166:    }else{
                   8167:      printf("Error internal in movingaverage, mobilav=%d.\n",mobilav);
1.222     brouard  8168:      return -1;
1.266     brouard  8169:    }
                   8170: 
                   8171:    for (cptcod=1;cptcod<=ncovcombmax;cptcod++){ /* for each combination */
1.222     brouard  8172:      /* for (age=bage+(mob-1)/2; age<=fage-(mob-1)/2; age++){ */
                   8173:      if(invalidvarcomb[cptcod]){
                   8174:        printf("\nCombination (%d) ignored because no cases \n",cptcod); 
                   8175:        continue;
                   8176:      }
1.219     brouard  8177: 
1.266     brouard  8178:      for (age=fage-(mob-1)/2; age>=bage+(mob-1)/2; age--){ /*looking for the youngest and oldest good age */
                   8179:        sumnewm[cptcod]=0.;
                   8180:        sumnewmr[cptcod]=0.;
                   8181:        for (i=1; i<=nlstate;i++){
                   8182:         sumnewm[cptcod]+=mobaverage[(int)age][i][cptcod];
                   8183:         sumnewmr[cptcod]+=probs[(int)age][i][cptcod];
                   8184:        }
                   8185:        if(fabs(sumnewmr[cptcod] - 1.) <= 1.e-3) { /* good without smoothing */
                   8186:         agemingoodr[cptcod]=age;
                   8187:        }
                   8188:        if(fabs(sumnewm[cptcod] - 1.) <= 1.e-3) { /* good */
                   8189:           agemingood[cptcod]=age;
                   8190:        }
                   8191:      } /* age */
                   8192:      for (age=bage+(mob-1)/2; age<=fage-(mob-1)/2; age++){ /*looking for the youngest and oldest good age */
1.222     brouard  8193:        sumnewm[cptcod]=0.;
1.266     brouard  8194:        sumnewmr[cptcod]=0.;
1.222     brouard  8195:        for (i=1; i<=nlstate;i++){
                   8196:         sumnewm[cptcod]+=mobaverage[(int)age][i][cptcod];
1.266     brouard  8197:         sumnewmr[cptcod]+=probs[(int)age][i][cptcod];
                   8198:        }
                   8199:        if(fabs(sumnewmr[cptcod] - 1.) <= 1.e-3) { /* good without smoothing */
                   8200:         agemaxgoodr[cptcod]=age;
1.222     brouard  8201:        }
                   8202:        if(fabs(sumnewm[cptcod] - 1.) <= 1.e-3) { /* good */
1.266     brouard  8203:         agemaxgood[cptcod]=age;
                   8204:        }
                   8205:      } /* age */
                   8206:      /* Thus we have agemingood and agemaxgood as well as goodr for raw (preobs) */
                   8207:      /* but they will change */
1.288     brouard  8208:      firstA1=0;firstA2=0;
1.266     brouard  8209:      for (age=fage-(mob-1)/2; age>=bage; age--){/* From oldest to youngest, filling up to the youngest */
                   8210:        sumnewm[cptcod]=0.;
                   8211:        sumnewmr[cptcod]=0.;
                   8212:        for (i=1; i<=nlstate;i++){
                   8213:         sumnewm[cptcod]+=mobaverage[(int)age][i][cptcod];
                   8214:         sumnewmr[cptcod]+=probs[(int)age][i][cptcod];
                   8215:        }
                   8216:        if(mobilav==-1){ /* Forcing raw ages if good else agemingood */
                   8217:         if(fabs(sumnewmr[cptcod] - 1.) <= 1.e-3) { /* good without smoothing */
                   8218:           agemaxgoodr[cptcod]=age;  /* age min */
                   8219:           for (i=1; i<=nlstate;i++)
                   8220:             mobaverage[(int)age][i][cptcod]=probs[(int)age][i][cptcod];
                   8221:         }else{ /* bad we change the value with the values of good ages */
                   8222:           for (i=1; i<=nlstate;i++){
                   8223:             mobaverage[(int)age][i][cptcod]=mobaverage[(int)agemaxgoodr[cptcod]][i][cptcod];
                   8224:           } /* i */
                   8225:         } /* end bad */
                   8226:        }else{
                   8227:         if(fabs(sumnewm[cptcod] - 1.) <= 1.e-3) { /* good */
                   8228:           agemaxgood[cptcod]=age;
                   8229:         }else{ /* bad we change the value with the values of good ages */
                   8230:           for (i=1; i<=nlstate;i++){
                   8231:             mobaverage[(int)age][i][cptcod]=mobaverage[(int)agemaxgood[cptcod]][i][cptcod];
                   8232:           } /* i */
                   8233:         } /* end bad */
                   8234:        }/* end else */
                   8235:        sum=0.;sumr=0.;
                   8236:        for (i=1; i<=nlstate;i++){
                   8237:         sum+=mobaverage[(int)age][i][cptcod];
                   8238:         sumr+=probs[(int)age][i][cptcod];
                   8239:        }
                   8240:        if(fabs(sum - 1.) > 1.e-3) { /* bad */
1.288     brouard  8241:         if(!firstA1){
                   8242:           firstA1=1;
                   8243:           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);
                   8244:         }
                   8245:         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  8246:        } /* end bad */
                   8247:        /* else{ /\* We found some ages summing to one, we will smooth the oldest *\/ */
                   8248:        if(fabs(sumr - 1.) > 1.e-3) { /* bad */
1.288     brouard  8249:         if(!firstA2){
                   8250:           firstA2=1;
                   8251:           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);
                   8252:         }
                   8253:         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  8254:        } /* end bad */
                   8255:      }/* age */
1.266     brouard  8256: 
                   8257:      for (age=bage+(mob-1)/2; age<=fage; age++){/* From youngest, finding the oldest wrong */
1.222     brouard  8258:        sumnewm[cptcod]=0.;
1.266     brouard  8259:        sumnewmr[cptcod]=0.;
1.222     brouard  8260:        for (i=1; i<=nlstate;i++){
                   8261:         sumnewm[cptcod]+=mobaverage[(int)age][i][cptcod];
1.266     brouard  8262:         sumnewmr[cptcod]+=probs[(int)age][i][cptcod];
                   8263:        } 
                   8264:        if(mobilav==-1){ /* Forcing raw ages if good else agemingood */
                   8265:         if(fabs(sumnewmr[cptcod] - 1.) <= 1.e-3) { /* good */
                   8266:           agemingoodr[cptcod]=age;
                   8267:           for (i=1; i<=nlstate;i++)
                   8268:             mobaverage[(int)age][i][cptcod]=probs[(int)age][i][cptcod];
                   8269:         }else{ /* bad we change the value with the values of good ages */
                   8270:           for (i=1; i<=nlstate;i++){
                   8271:             mobaverage[(int)age][i][cptcod]=mobaverage[(int)agemingoodr[cptcod]][i][cptcod];
                   8272:           } /* i */
                   8273:         } /* end bad */
                   8274:        }else{
                   8275:         if(fabs(sumnewm[cptcod] - 1.) <= 1.e-3) { /* good */
                   8276:           agemingood[cptcod]=age;
                   8277:         }else{ /* bad */
                   8278:           for (i=1; i<=nlstate;i++){
                   8279:             mobaverage[(int)age][i][cptcod]=mobaverage[(int)agemingood[cptcod]][i][cptcod];
                   8280:           } /* i */
                   8281:         } /* end bad */
                   8282:        }/* end else */
                   8283:        sum=0.;sumr=0.;
                   8284:        for (i=1; i<=nlstate;i++){
                   8285:         sum+=mobaverage[(int)age][i][cptcod];
                   8286:         sumr+=mobaverage[(int)age][i][cptcod];
1.222     brouard  8287:        }
1.266     brouard  8288:        if(fabs(sum - 1.) > 1.e-3) { /* bad */
1.268     brouard  8289:         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  8290:        } /* end bad */
                   8291:        /* else{ /\* We found some ages summing to one, we will smooth the oldest *\/ */
                   8292:        if(fabs(sumr - 1.) > 1.e-3) { /* bad */
1.268     brouard  8293:         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  8294:        } /* end bad */
                   8295:      }/* age */
1.266     brouard  8296: 
1.222     brouard  8297:                
                   8298:      for (age=bage; age<=fage; age++){
1.235     brouard  8299:        /* printf("%d %d ", cptcod, (int)age); */
1.222     brouard  8300:        sumnewp[cptcod]=0.;
                   8301:        sumnewm[cptcod]=0.;
                   8302:        for (i=1; i<=nlstate;i++){
                   8303:         sumnewp[cptcod]+=probs[(int)age][i][cptcod];
                   8304:         sumnewm[cptcod]+=mobaverage[(int)age][i][cptcod];
                   8305:         /* printf("%.4f %.4f ",probs[(int)age][i][cptcod], mobaverage[(int)age][i][cptcod]); */
                   8306:        }
                   8307:        /* printf("%.4f %.4f \n",sumnewp[cptcod], sumnewm[cptcod]); */
                   8308:      }
                   8309:      /* printf("\n"); */
                   8310:      /* } */
1.266     brouard  8311: 
1.222     brouard  8312:      /* brutal averaging */
1.266     brouard  8313:      /* for (i=1; i<=nlstate;i++){ */
                   8314:      /*   for (age=1; age<=bage; age++){ */
                   8315:      /*         mobaverage[(int)age][i][cptcod]=mobaverage[(int)agemingood[cptcod]][i][cptcod]; */
                   8316:      /*         /\* printf("age=%d i=%d cptcod=%d mobaverage=%.4f \n",(int)age,i, cptcod, mobaverage[(int)age][i][cptcod]); *\/ */
                   8317:      /*   }     */
                   8318:      /*   for (age=fage; age<=AGESUP; age++){ */
                   8319:      /*         mobaverage[(int)age][i][cptcod]=mobaverage[(int)agemaxgood[cptcod]][i][cptcod]; */
                   8320:      /*         /\* printf("age=%d i=%d cptcod=%d mobaverage=%.4f \n",(int)age,i, cptcod, mobaverage[(int)age][i][cptcod]); *\/ */
                   8321:      /*   } */
                   8322:      /* } /\* end i status *\/ */
                   8323:      /* for (i=nlstate+1; i<=nlstate+ndeath;i++){ */
                   8324:      /*   for (age=1; age<=AGESUP; age++){ */
                   8325:      /*         /\*printf("i=%d, age=%d, cptcod=%d\n",i, (int)age, cptcod);*\/ */
                   8326:      /*         mobaverage[(int)age][i][cptcod]=0.; */
                   8327:      /*   } */
                   8328:      /* } */
1.222     brouard  8329:    }/* end cptcod */
1.266     brouard  8330:    free_vector(agemaxgoodr,1, ncovcombmax);
                   8331:    free_vector(agemaxgood,1, ncovcombmax);
                   8332:    free_vector(agemingood,1, ncovcombmax);
                   8333:    free_vector(agemingoodr,1, ncovcombmax);
                   8334:    free_vector(sumnewmr,1, ncovcombmax);
1.222     brouard  8335:    free_vector(sumnewm,1, ncovcombmax);
                   8336:    free_vector(sumnewp,1, ncovcombmax);
                   8337:    return 0;
                   8338:  }/* End movingaverage */
1.218     brouard  8339:  
1.126     brouard  8340: 
1.296     brouard  8341:  
1.126     brouard  8342: /************** Forecasting ******************/
1.296     brouard  8343: /* void prevforecast(char fileres[], double dateintmean, double anprojd, double mprojd, double jprojd, double ageminpar, double agemax, double dateprev1, double dateprev2, int mobilav, double ***prev, double bage, double fage, int firstpass, int lastpass, double anprojf, double p[], int cptcoveff)*/
                   8344: void prevforecast(char fileres[], double dateintmean, double dateprojd, double dateprojf, double ageminpar, double agemax, double dateprev1, double dateprev2, int mobilav, double ***prev, double bage, double fage, int firstpass, int lastpass, double p[], int cptcoveff){
                   8345:   /* dateintemean, mean date of interviews
                   8346:      dateprojd, year, month, day of starting projection 
                   8347:      dateprojf date of end of projection;year of end of projection (same day and month as proj1).
1.126     brouard  8348:      agemin, agemax range of age
                   8349:      dateprev1 dateprev2 range of dates during which prevalence is computed
                   8350:   */
1.296     brouard  8351:   /* double anprojd, mprojd, jprojd; */
                   8352:   /* double anprojf, mprojf, jprojf; */
1.267     brouard  8353:   int yearp, stepsize, hstepm, nhstepm, j, k, cptcod, i, h, i1, k4, nres=0;
1.126     brouard  8354:   double agec; /* generic age */
1.296     brouard  8355:   double agelim, ppij, yp,yp1,yp2;
1.126     brouard  8356:   double *popeffectif,*popcount;
                   8357:   double ***p3mat;
1.218     brouard  8358:   /* double ***mobaverage; */
1.126     brouard  8359:   char fileresf[FILENAMELENGTH];
                   8360: 
                   8361:   agelim=AGESUP;
1.211     brouard  8362:   /* Compute observed prevalence between dateprev1 and dateprev2 by counting the number of people
                   8363:      in each health status at the date of interview (if between dateprev1 and dateprev2).
                   8364:      We still use firstpass and lastpass as another selection.
                   8365:   */
1.214     brouard  8366:   /* freqsummary(fileres, agemin, agemax, s, agev, nlstate, imx,Tvaraff,nbcode, ncodemax,mint,anint,strstart,\ */
                   8367:   /*         firstpass, lastpass,  stepm,  weightopt, model); */
1.126     brouard  8368:  
1.201     brouard  8369:   strcpy(fileresf,"F_"); 
                   8370:   strcat(fileresf,fileresu);
1.126     brouard  8371:   if((ficresf=fopen(fileresf,"w"))==NULL) {
                   8372:     printf("Problem with forecast resultfile: %s\n", fileresf);
                   8373:     fprintf(ficlog,"Problem with forecast resultfile: %s\n", fileresf);
                   8374:   }
1.235     brouard  8375:   printf("\nComputing forecasting: result on file '%s', please wait... \n", fileresf);
                   8376:   fprintf(ficlog,"\nComputing forecasting: result on file '%s', please wait... \n", fileresf);
1.126     brouard  8377: 
1.225     brouard  8378:   if (cptcoveff==0) ncodemax[cptcoveff]=1;
1.126     brouard  8379: 
                   8380: 
                   8381:   stepsize=(int) (stepm+YEARM-1)/YEARM;
                   8382:   if (stepm<=12) stepsize=1;
                   8383:   if(estepm < stepm){
                   8384:     printf ("Problem %d lower than %d\n",estepm, stepm);
                   8385:   }
1.270     brouard  8386:   else{
                   8387:     hstepm=estepm;   
                   8388:   }
                   8389:   if(estepm > stepm){ /* Yes every two year */
                   8390:     stepsize=2;
                   8391:   }
1.296     brouard  8392:   hstepm=hstepm/stepm;
1.126     brouard  8393: 
1.296     brouard  8394:   
                   8395:   /* yp1=modf(dateintmean,&yp);/\* extracts integral of datemean in yp  and */
                   8396:   /*                              fractional in yp1 *\/ */
                   8397:   /* aintmean=yp; */
                   8398:   /* yp2=modf((yp1*12),&yp); */
                   8399:   /* mintmean=yp; */
                   8400:   /* yp1=modf((yp2*30.5),&yp); */
                   8401:   /* jintmean=yp; */
                   8402:   /* if(jintmean==0) jintmean=1; */
                   8403:   /* if(mintmean==0) mintmean=1; */
1.126     brouard  8404: 
1.296     brouard  8405: 
                   8406:   /* date2dmy(dateintmean,&jintmean,&mintmean,&aintmean); */
                   8407:   /* date2dmy(dateprojd,&jprojd, &mprojd, &anprojd); */
                   8408:   /* date2dmy(dateprojf,&jprojf, &mprojf, &anprojf); */
1.227     brouard  8409:   i1=pow(2,cptcoveff);
1.126     brouard  8410:   if (cptcovn < 1){i1=1;}
                   8411:   
1.296     brouard  8412:   fprintf(ficresf,"# Mean day of interviews %.lf/%.lf/%.lf (%.2f) between %.2f and %.2f \n",jintmean,mintmean,aintmean,dateintmean,dateprev1,dateprev2); 
1.126     brouard  8413:   
                   8414:   fprintf(ficresf,"#****** Routine prevforecast **\n");
1.227     brouard  8415:   
1.126     brouard  8416: /*           if (h==(int)(YEARM*yearp)){ */
1.235     brouard  8417:   for(nres=1; nres <= nresult; nres++) /* For each resultline */
                   8418:   for(k=1; k<=i1;k++){
1.253     brouard  8419:     if(i1 != 1 && TKresult[nres]!= k)
1.235     brouard  8420:       continue;
1.227     brouard  8421:     if(invalidvarcomb[k]){
                   8422:       printf("\nCombination (%d) projection ignored because no cases \n",k); 
                   8423:       continue;
                   8424:     }
                   8425:     fprintf(ficresf,"\n#****** hpijx=probability over h years, hp.jx is weighted by observed prev \n#");
                   8426:     for(j=1;j<=cptcoveff;j++) {
                   8427:       fprintf(ficresf," V%d (=) %d",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   8428:     }
1.235     brouard  8429:     for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
1.238     brouard  8430:       fprintf(ficresf," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
1.235     brouard  8431:     }
1.227     brouard  8432:     fprintf(ficresf," yearproj age");
                   8433:     for(j=1; j<=nlstate+ndeath;j++){ 
                   8434:       for(i=1; i<=nlstate;i++)               
                   8435:        fprintf(ficresf," p%d%d",i,j);
                   8436:       fprintf(ficresf," wp.%d",j);
                   8437:     }
1.296     brouard  8438:     for (yearp=0; yearp<=(anprojf-anprojd);yearp +=stepsize) {
1.227     brouard  8439:       fprintf(ficresf,"\n");
1.296     brouard  8440:       fprintf(ficresf,"\n# Forecasting at date %.lf/%.lf/%.lf ",jprojd,mprojd,anprojd+yearp);   
1.270     brouard  8441:       /* for (agec=fage; agec>=(ageminpar-1); agec--){  */
                   8442:       for (agec=fage; agec>=(bage); agec--){ 
1.227     brouard  8443:        nhstepm=(int) rint((agelim-agec)*YEARM/stepm); 
                   8444:        nhstepm = nhstepm/hstepm; 
                   8445:        p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   8446:        oldm=oldms;savm=savms;
1.268     brouard  8447:        /* We compute pii at age agec over nhstepm);*/
1.235     brouard  8448:        hpxij(p3mat,nhstepm,agec,hstepm,p,nlstate,stepm,oldm,savm, k,nres);
1.268     brouard  8449:        /* Then we print p3mat for h corresponding to the right agec+h*stepms=yearp */
1.227     brouard  8450:        for (h=0; h<=nhstepm; h++){
                   8451:          if (h*hstepm/YEARM*stepm ==yearp) {
1.268     brouard  8452:            break;
                   8453:          }
                   8454:        }
                   8455:        fprintf(ficresf,"\n");
                   8456:        for(j=1;j<=cptcoveff;j++) 
                   8457:          fprintf(ficresf,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
1.296     brouard  8458:        fprintf(ficresf,"%.f %.f ",anprojd+yearp,agec+h*hstepm/YEARM*stepm);
1.268     brouard  8459:        
                   8460:        for(j=1; j<=nlstate+ndeath;j++) {
                   8461:          ppij=0.;
                   8462:          for(i=1; i<=nlstate;i++) {
1.278     brouard  8463:            if (mobilav>=1)
                   8464:             ppij=ppij+p3mat[i][j][h]*prev[(int)agec][i][k];
                   8465:            else { /* even if mobilav==-1 we use mobaverage, probs may not sums to 1 */
                   8466:                ppij=ppij+p3mat[i][j][h]*probs[(int)(agec)][i][k];
                   8467:            }
1.268     brouard  8468:            fprintf(ficresf," %.3f", p3mat[i][j][h]);
                   8469:          } /* end i */
                   8470:          fprintf(ficresf," %.3f", ppij);
                   8471:        }/* end j */
1.227     brouard  8472:        free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   8473:       } /* end agec */
1.266     brouard  8474:       /* diffyear=(int) anproj1+yearp-ageminpar-1; */
                   8475:       /*printf("Prevforecast %d+%d-%d=diffyear=%d\n",(int) anproj1, (int)yearp,(int)ageminpar,(int) anproj1-(int)ageminpar);*/
1.227     brouard  8476:     } /* end yearp */
                   8477:   } /* end  k */
1.219     brouard  8478:        
1.126     brouard  8479:   fclose(ficresf);
1.215     brouard  8480:   printf("End of Computing forecasting \n");
                   8481:   fprintf(ficlog,"End of Computing forecasting\n");
                   8482: 
1.126     brouard  8483: }
                   8484: 
1.269     brouard  8485: /************** Back Forecasting ******************/
1.296     brouard  8486:  /* 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){ */
                   8487:  void prevbackforecast(char fileres[], double ***prevacurrent, double dateintmean, double dateprojd, double dateprojf, double ageminpar, double agemax, double dateprev1, double dateprev2, int mobilav, double bage, double fage, int firstpass, int lastpass, double p[], int cptcoveff){
                   8488:   /* back1, year, month, day of starting backprojection
1.267     brouard  8489:      agemin, agemax range of age
                   8490:      dateprev1 dateprev2 range of dates during which prevalence is computed
1.269     brouard  8491:      anback2 year of end of backprojection (same day and month as back1).
                   8492:      prevacurrent and prev are prevalences.
1.267     brouard  8493:   */
                   8494:   int yearp, stepsize, hstepm, nhstepm, j, k, cptcod, i, h, i1, k4, nres=0;
                   8495:   double agec; /* generic age */
1.296     brouard  8496:   double agelim, ppij, ppi, yp,yp1,yp2,jintmean,mintmean,aintmean;
1.267     brouard  8497:   double *popeffectif,*popcount;
                   8498:   double ***p3mat;
                   8499:   /* double ***mobaverage; */
                   8500:   char fileresfb[FILENAMELENGTH];
                   8501:  
1.268     brouard  8502:   agelim=AGEINF;
1.267     brouard  8503:   /* Compute observed prevalence between dateprev1 and dateprev2 by counting the number of people
                   8504:      in each health status at the date of interview (if between dateprev1 and dateprev2).
                   8505:      We still use firstpass and lastpass as another selection.
                   8506:   */
                   8507:   /* freqsummary(fileres, agemin, agemax, s, agev, nlstate, imx,Tvaraff,nbcode, ncodemax,mint,anint,strstart,\ */
                   8508:   /*         firstpass, lastpass,  stepm,  weightopt, model); */
                   8509: 
                   8510:   /*Do we need to compute prevalence again?*/
                   8511: 
                   8512:   /* prevalence(probs, ageminpar, agemax, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass); */
                   8513:   
                   8514:   strcpy(fileresfb,"FB_");
                   8515:   strcat(fileresfb,fileresu);
                   8516:   if((ficresfb=fopen(fileresfb,"w"))==NULL) {
                   8517:     printf("Problem with back forecast resultfile: %s\n", fileresfb);
                   8518:     fprintf(ficlog,"Problem with back forecast resultfile: %s\n", fileresfb);
                   8519:   }
                   8520:   printf("\nComputing back forecasting: result on file '%s', please wait... \n", fileresfb);
                   8521:   fprintf(ficlog,"\nComputing back forecasting: result on file '%s', please wait... \n", fileresfb);
                   8522:   
                   8523:   if (cptcoveff==0) ncodemax[cptcoveff]=1;
                   8524:   
                   8525:    
                   8526:   stepsize=(int) (stepm+YEARM-1)/YEARM;
                   8527:   if (stepm<=12) stepsize=1;
                   8528:   if(estepm < stepm){
                   8529:     printf ("Problem %d lower than %d\n",estepm, stepm);
                   8530:   }
1.270     brouard  8531:   else{
                   8532:     hstepm=estepm;   
                   8533:   }
                   8534:   if(estepm >= stepm){ /* Yes every two year */
                   8535:     stepsize=2;
                   8536:   }
1.267     brouard  8537:   
                   8538:   hstepm=hstepm/stepm;
1.296     brouard  8539:   /* yp1=modf(dateintmean,&yp);/\* extracts integral of datemean in yp  and */
                   8540:   /*                              fractional in yp1 *\/ */
                   8541:   /* aintmean=yp; */
                   8542:   /* yp2=modf((yp1*12),&yp); */
                   8543:   /* mintmean=yp; */
                   8544:   /* yp1=modf((yp2*30.5),&yp); */
                   8545:   /* jintmean=yp; */
                   8546:   /* if(jintmean==0) jintmean=1; */
                   8547:   /* if(mintmean==0) jintmean=1; */
1.267     brouard  8548:   
                   8549:   i1=pow(2,cptcoveff);
                   8550:   if (cptcovn < 1){i1=1;}
                   8551:   
1.296     brouard  8552:   fprintf(ficresfb,"# Mean day of interviews %.lf/%.lf/%.lf (%.2f) between %.2f and %.2f \n",jintmean,mintmean,aintmean,dateintmean,dateprev1,dateprev2);
                   8553:   printf("# Mean day of interviews %.lf/%.lf/%.lf (%.2f) between %.2f and %.2f \n",jintmean,mintmean,aintmean,dateintmean,dateprev1,dateprev2);
1.267     brouard  8554:   
                   8555:   fprintf(ficresfb,"#****** Routine prevbackforecast **\n");
                   8556:   
                   8557:   for(nres=1; nres <= nresult; nres++) /* For each resultline */
                   8558:   for(k=1; k<=i1;k++){
                   8559:     if(i1 != 1 && TKresult[nres]!= k)
                   8560:       continue;
                   8561:     if(invalidvarcomb[k]){
                   8562:       printf("\nCombination (%d) projection ignored because no cases \n",k); 
                   8563:       continue;
                   8564:     }
1.268     brouard  8565:     fprintf(ficresfb,"\n#****** hbijx=probability over h years, hb.jx is weighted by observed prev \n#");
1.267     brouard  8566:     for(j=1;j<=cptcoveff;j++) {
                   8567:       fprintf(ficresfb," V%d (=) %d",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   8568:     }
                   8569:     for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
                   8570:       fprintf(ficresf," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
                   8571:     }
                   8572:     fprintf(ficresfb," yearbproj age");
                   8573:     for(j=1; j<=nlstate+ndeath;j++){
                   8574:       for(i=1; i<=nlstate;i++)
1.268     brouard  8575:        fprintf(ficresfb," b%d%d",i,j);
                   8576:       fprintf(ficresfb," b.%d",j);
1.267     brouard  8577:     }
1.296     brouard  8578:     for (yearp=0; yearp>=(anbackf-anbackd);yearp -=stepsize) {
1.267     brouard  8579:       /* for (yearp=0; yearp<=(anproj2-anproj1);yearp +=stepsize) {  */
                   8580:       fprintf(ficresfb,"\n");
1.296     brouard  8581:       fprintf(ficresfb,"\n# Back Forecasting at date %.lf/%.lf/%.lf ",jbackd,mbackd,anbackd+yearp);
1.273     brouard  8582:       /* printf("\n# Back Forecasting at date %.lf/%.lf/%.lf ",jback1,mback1,anback1+yearp); */
1.270     brouard  8583:       /* for (agec=bage; agec<=agemax-1; agec++){  /\* testing *\/ */
                   8584:       for (agec=bage; agec<=fage; agec++){  /* testing */
1.268     brouard  8585:        /* We compute bij at age agec over nhstepm, nhstepm decreases when agec increases because of agemax;*/
1.271     brouard  8586:        nhstepm=(int) (agec-agelim) *YEARM/stepm;/*     nhstepm=(int) rint((agec-agelim)*YEARM/stepm);*/
1.267     brouard  8587:        nhstepm = nhstepm/hstepm;
                   8588:        p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   8589:        oldm=oldms;savm=savms;
1.268     brouard  8590:        /* computes hbxij at age agec over 1 to nhstepm */
1.271     brouard  8591:        /* printf("####prevbackforecast debug  agec=%.2f nhstepm=%d\n",agec, nhstepm);fflush(stdout); */
1.267     brouard  8592:        hbxij(p3mat,nhstepm,agec,hstepm,p,prevacurrent,nlstate,stepm, k, nres);
1.268     brouard  8593:        /* hpxij(p3mat,nhstepm,agec,hstepm,p,             nlstate,stepm,oldm,savm, k,nres); */
                   8594:        /* Then we print p3mat for h corresponding to the right agec+h*stepms=yearp */
                   8595:        /* printf(" agec=%.2f\n",agec);fflush(stdout); */
1.267     brouard  8596:        for (h=0; h<=nhstepm; h++){
1.268     brouard  8597:          if (h*hstepm/YEARM*stepm ==-yearp) {
                   8598:            break;
                   8599:          }
                   8600:        }
                   8601:        fprintf(ficresfb,"\n");
                   8602:        for(j=1;j<=cptcoveff;j++)
                   8603:          fprintf(ficresfb,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
1.296     brouard  8604:        fprintf(ficresfb,"%.f %.f ",anbackd+yearp,agec-h*hstepm/YEARM*stepm);
1.268     brouard  8605:        for(i=1; i<=nlstate+ndeath;i++) {
                   8606:          ppij=0.;ppi=0.;
                   8607:          for(j=1; j<=nlstate;j++) {
                   8608:            /* if (mobilav==1) */
1.269     brouard  8609:            ppij=ppij+p3mat[i][j][h]*prevacurrent[(int)agec][j][k];
                   8610:            ppi=ppi+prevacurrent[(int)agec][j][k];
                   8611:            /* ppij=ppij+p3mat[i][j][h]*mobaverage[(int)agec][j][k]; */
                   8612:            /* ppi=ppi+mobaverage[(int)agec][j][k]; */
1.267     brouard  8613:              /* else { */
                   8614:              /*        ppij=ppij+p3mat[i][j][h]*probs[(int)(agec)][i][k]; */
                   8615:              /* } */
1.268     brouard  8616:            fprintf(ficresfb," %.3f", p3mat[i][j][h]);
                   8617:          } /* end j */
                   8618:          if(ppi <0.99){
                   8619:            printf("Error in prevbackforecast, prevalence doesn't sum to 1 for state %d: %3f\n",i, ppi);
                   8620:            fprintf(ficlog,"Error in prevbackforecast, prevalence doesn't sum to 1 for state %d: %3f\n",i, ppi);
                   8621:          }
                   8622:          fprintf(ficresfb," %.3f", ppij);
                   8623:        }/* end j */
1.267     brouard  8624:        free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   8625:       } /* end agec */
                   8626:     } /* end yearp */
                   8627:   } /* end k */
1.217     brouard  8628:   
1.267     brouard  8629:   /* if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX); */
1.217     brouard  8630:   
1.267     brouard  8631:   fclose(ficresfb);
                   8632:   printf("End of Computing Back forecasting \n");
                   8633:   fprintf(ficlog,"End of Computing Back forecasting\n");
1.218     brouard  8634:        
1.267     brouard  8635: }
1.217     brouard  8636: 
1.269     brouard  8637: /* Variance of prevalence limit: varprlim */
                   8638:  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  8639:     /*------- Variance of forward period (stable) prevalence------*/   
1.269     brouard  8640:  
                   8641:    char fileresvpl[FILENAMELENGTH];  
                   8642:    FILE *ficresvpl;
                   8643:    double **oldm, **savm;
                   8644:    double **varpl; /* Variances of prevalence limits by age */   
                   8645:    int i1, k, nres, j ;
                   8646:    
                   8647:     strcpy(fileresvpl,"VPL_");
                   8648:     strcat(fileresvpl,fileresu);
                   8649:     if((ficresvpl=fopen(fileresvpl,"w"))==NULL) {
1.288     brouard  8650:       printf("Problem with variance of forward period (stable) prevalence  resultfile: %s\n", fileresvpl);
1.269     brouard  8651:       exit(0);
                   8652:     }
1.288     brouard  8653:     printf("Computing Variance-covariance of forward period (stable) prevalence: file '%s' ...", fileresvpl);fflush(stdout);
                   8654:     fprintf(ficlog, "Computing Variance-covariance of forward period (stable) prevalence: file '%s' ...", fileresvpl);fflush(ficlog);
1.269     brouard  8655:     
                   8656:     /*for(cptcov=1,k=0;cptcov<=i1;cptcov++){
                   8657:       for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*/
                   8658:     
                   8659:     i1=pow(2,cptcoveff);
                   8660:     if (cptcovn < 1){i1=1;}
                   8661: 
                   8662:     for(nres=1; nres <= nresult; nres++) /* For each resultline */
                   8663:     for(k=1; k<=i1;k++){
                   8664:       if(i1 != 1 && TKresult[nres]!= k)
                   8665:        continue;
                   8666:       fprintf(ficresvpl,"\n#****** ");
                   8667:       printf("\n#****** ");
                   8668:       fprintf(ficlog,"\n#****** ");
                   8669:       for(j=1;j<=cptcoveff;j++) {
                   8670:        fprintf(ficresvpl,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   8671:        fprintf(ficlog,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   8672:        printf("V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   8673:       }
                   8674:       for (j=1; j<= nsq; j++){ /* For each selected (single) quantitative value */
                   8675:        printf(" V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]);
                   8676:        fprintf(ficresvpl," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]);
                   8677:        fprintf(ficlog," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]);
                   8678:       }        
                   8679:       fprintf(ficresvpl,"******\n");
                   8680:       printf("******\n");
                   8681:       fprintf(ficlog,"******\n");
                   8682:       
                   8683:       varpl=matrix(1,nlstate,(int) bage, (int) fage);
                   8684:       oldm=oldms;savm=savms;
                   8685:       varprevlim(fileresvpl, ficresvpl, varpl, matcov, p, delti, nlstate, stepm, (int) bage, (int) fage, oldm, savm, prlim, ftolpl, ncvyearp, k, strstart, nres);
                   8686:       free_matrix(varpl,1,nlstate,(int) bage, (int)fage);
                   8687:       /*}*/
                   8688:     }
                   8689:     
                   8690:     fclose(ficresvpl);
1.288     brouard  8691:     printf("done variance-covariance of forward period prevalence\n");fflush(stdout);
                   8692:     fprintf(ficlog,"done variance-covariance of forward period prevalence\n");fflush(ficlog);
1.269     brouard  8693: 
                   8694:  }
                   8695: /* Variance of back prevalence: varbprlim */
                   8696:  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){
                   8697:       /*------- Variance of back (stable) prevalence------*/
                   8698: 
                   8699:    char fileresvbl[FILENAMELENGTH];  
                   8700:    FILE  *ficresvbl;
                   8701: 
                   8702:    double **oldm, **savm;
                   8703:    double **varbpl; /* Variances of back prevalence limits by age */   
                   8704:    int i1, k, nres, j ;
                   8705: 
                   8706:    strcpy(fileresvbl,"VBL_");
                   8707:    strcat(fileresvbl,fileresu);
                   8708:    if((ficresvbl=fopen(fileresvbl,"w"))==NULL) {
                   8709:      printf("Problem with variance of back (stable) prevalence  resultfile: %s\n", fileresvbl);
                   8710:      exit(0);
                   8711:    }
                   8712:    printf("Computing Variance-covariance of back (stable) prevalence: file '%s' ...", fileresvbl);fflush(stdout);
                   8713:    fprintf(ficlog, "Computing Variance-covariance of back (stable) prevalence: file '%s' ...", fileresvbl);fflush(ficlog);
                   8714:    
                   8715:    
                   8716:    i1=pow(2,cptcoveff);
                   8717:    if (cptcovn < 1){i1=1;}
                   8718:    
                   8719:    for(nres=1; nres <= nresult; nres++) /* For each resultline */
                   8720:      for(k=1; k<=i1;k++){
                   8721:        if(i1 != 1 && TKresult[nres]!= k)
                   8722:         continue;
                   8723:        fprintf(ficresvbl,"\n#****** ");
                   8724:        printf("\n#****** ");
                   8725:        fprintf(ficlog,"\n#****** ");
                   8726:        for(j=1;j<=cptcoveff;j++) {
                   8727:         fprintf(ficresvbl,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   8728:         fprintf(ficlog,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   8729:         printf("V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   8730:        }
                   8731:        for (j=1; j<= nsq; j++){ /* For each selected (single) quantitative value */
                   8732:         printf(" V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]);
                   8733:         fprintf(ficresvbl," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]);
                   8734:         fprintf(ficlog," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]);
                   8735:        }
                   8736:        fprintf(ficresvbl,"******\n");
                   8737:        printf("******\n");
                   8738:        fprintf(ficlog,"******\n");
                   8739:        
                   8740:        varbpl=matrix(1,nlstate,(int) bage, (int) fage);
                   8741:        oldm=oldms;savm=savms;
                   8742:        
                   8743:        varbrevlim(fileresvbl, ficresvbl, varbpl, matcov, p, delti, nlstate, stepm, (int) bage, (int) fage, oldm, savm, bprlim, ftolpl, mobilavproj, ncvyearp, k, strstart, nres);
                   8744:        free_matrix(varbpl,1,nlstate,(int) bage, (int)fage);
                   8745:        /*}*/
                   8746:      }
                   8747:    
                   8748:    fclose(ficresvbl);
                   8749:    printf("done variance-covariance of back prevalence\n");fflush(stdout);
                   8750:    fprintf(ficlog,"done variance-covariance of back prevalence\n");fflush(ficlog);
                   8751: 
                   8752:  } /* End of varbprlim */
                   8753: 
1.126     brouard  8754: /************** Forecasting *****not tested NB*************/
1.227     brouard  8755: /* 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  8756:   
1.227     brouard  8757: /*   int cpt, stepsize, hstepm, nhstepm, j,k,c, cptcod, i,h; */
                   8758: /*   int *popage; */
                   8759: /*   double calagedatem, agelim, kk1, kk2; */
                   8760: /*   double *popeffectif,*popcount; */
                   8761: /*   double ***p3mat,***tabpop,***tabpopprev; */
                   8762: /*   /\* double ***mobaverage; *\/ */
                   8763: /*   char filerespop[FILENAMELENGTH]; */
1.126     brouard  8764: 
1.227     brouard  8765: /*   tabpop= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX); */
                   8766: /*   tabpopprev= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX); */
                   8767: /*   agelim=AGESUP; */
                   8768: /*   calagedatem=(anpyram+mpyram/12.+jpyram/365.-dateintmean)*YEARM; */
1.126     brouard  8769:   
1.227     brouard  8770: /*   prevalence(probs, ageminpar, agemax, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass); */
1.126     brouard  8771:   
                   8772:   
1.227     brouard  8773: /*   strcpy(filerespop,"POP_");  */
                   8774: /*   strcat(filerespop,fileresu); */
                   8775: /*   if((ficrespop=fopen(filerespop,"w"))==NULL) { */
                   8776: /*     printf("Problem with forecast resultfile: %s\n", filerespop); */
                   8777: /*     fprintf(ficlog,"Problem with forecast resultfile: %s\n", filerespop); */
                   8778: /*   } */
                   8779: /*   printf("Computing forecasting: result on file '%s' \n", filerespop); */
                   8780: /*   fprintf(ficlog,"Computing forecasting: result on file '%s' \n", filerespop); */
1.126     brouard  8781: 
1.227     brouard  8782: /*   if (cptcoveff==0) ncodemax[cptcoveff]=1; */
1.126     brouard  8783: 
1.227     brouard  8784: /*   /\* if (mobilav!=0) { *\/ */
                   8785: /*   /\*   mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX); *\/ */
                   8786: /*   /\*   if (movingaverage(probs, ageminpar, fage, mobaverage,mobilav)!=0){ *\/ */
                   8787: /*   /\*     fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav); *\/ */
                   8788: /*   /\*     printf(" Error in movingaverage mobilav=%d\n",mobilav); *\/ */
                   8789: /*   /\*   } *\/ */
                   8790: /*   /\* } *\/ */
1.126     brouard  8791: 
1.227     brouard  8792: /*   stepsize=(int) (stepm+YEARM-1)/YEARM; */
                   8793: /*   if (stepm<=12) stepsize=1; */
1.126     brouard  8794:   
1.227     brouard  8795: /*   agelim=AGESUP; */
1.126     brouard  8796:   
1.227     brouard  8797: /*   hstepm=1; */
                   8798: /*   hstepm=hstepm/stepm;  */
1.218     brouard  8799:        
1.227     brouard  8800: /*   if (popforecast==1) { */
                   8801: /*     if((ficpop=fopen(popfile,"r"))==NULL) { */
                   8802: /*       printf("Problem with population file : %s\n",popfile);exit(0); */
                   8803: /*       fprintf(ficlog,"Problem with population file : %s\n",popfile);exit(0); */
                   8804: /*     }  */
                   8805: /*     popage=ivector(0,AGESUP); */
                   8806: /*     popeffectif=vector(0,AGESUP); */
                   8807: /*     popcount=vector(0,AGESUP); */
1.126     brouard  8808:     
1.227     brouard  8809: /*     i=1;    */
                   8810: /*     while ((c=fscanf(ficpop,"%d %lf\n",&popage[i],&popcount[i])) != EOF) i=i+1; */
1.218     brouard  8811:     
1.227     brouard  8812: /*     imx=i; */
                   8813: /*     for (i=1; i<imx;i++) popeffectif[popage[i]]=popcount[i]; */
                   8814: /*   } */
1.218     brouard  8815:   
1.227     brouard  8816: /*   for(cptcov=1,k=0;cptcov<=i2;cptcov++){ */
                   8817: /*     for(cptcod=1;cptcod<=ncodemax[cptcoveff];cptcod++){ */
                   8818: /*       k=k+1; */
                   8819: /*       fprintf(ficrespop,"\n#******"); */
                   8820: /*       for(j=1;j<=cptcoveff;j++) { */
                   8821: /*     fprintf(ficrespop," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]); */
                   8822: /*       } */
                   8823: /*       fprintf(ficrespop,"******\n"); */
                   8824: /*       fprintf(ficrespop,"# Age"); */
                   8825: /*       for(j=1; j<=nlstate+ndeath;j++) fprintf(ficrespop," P.%d",j); */
                   8826: /*       if (popforecast==1)  fprintf(ficrespop," [Population]"); */
1.126     brouard  8827:       
1.227     brouard  8828: /*       for (cpt=0; cpt<=0;cpt++) {  */
                   8829: /*     fprintf(ficrespop,"\n\n# Forecasting at date %.lf/%.lf/%.lf ",jpyram,mpyram,anpyram+cpt);    */
1.126     brouard  8830:        
1.227     brouard  8831: /*     for (agedeb=(fage-((int)calagedatem %12/12.)); agedeb>=(ageminpar-((int)calagedatem %12)/12.); agedeb--){  */
                   8832: /*       nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm);  */
                   8833: /*       nhstepm = nhstepm/hstepm;  */
1.126     brouard  8834:          
1.227     brouard  8835: /*       p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm); */
                   8836: /*       oldm=oldms;savm=savms; */
                   8837: /*       hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);   */
1.218     brouard  8838:          
1.227     brouard  8839: /*       for (h=0; h<=nhstepm; h++){ */
                   8840: /*         if (h==(int) (calagedatem+YEARM*cpt)) { */
                   8841: /*           fprintf(ficrespop,"\n %3.f ",agedeb+h*hstepm/YEARM*stepm); */
                   8842: /*         }  */
                   8843: /*         for(j=1; j<=nlstate+ndeath;j++) { */
                   8844: /*           kk1=0.;kk2=0; */
                   8845: /*           for(i=1; i<=nlstate;i++) {               */
                   8846: /*             if (mobilav==1)  */
                   8847: /*               kk1=kk1+p3mat[i][j][h]*mobaverage[(int)agedeb+1][i][cptcod]; */
                   8848: /*             else { */
                   8849: /*               kk1=kk1+p3mat[i][j][h]*probs[(int)(agedeb+1)][i][cptcod]; */
                   8850: /*             } */
                   8851: /*           } */
                   8852: /*           if (h==(int)(calagedatem+12*cpt)){ */
                   8853: /*             tabpop[(int)(agedeb)][j][cptcod]=kk1; */
                   8854: /*             /\*fprintf(ficrespop," %.3f", kk1); */
                   8855: /*               if (popforecast==1) fprintf(ficrespop," [%.f]", kk1*popeffectif[(int)agedeb+1]);*\/ */
                   8856: /*           } */
                   8857: /*         } */
                   8858: /*         for(i=1; i<=nlstate;i++){ */
                   8859: /*           kk1=0.; */
                   8860: /*           for(j=1; j<=nlstate;j++){ */
                   8861: /*             kk1= kk1+tabpop[(int)(agedeb)][j][cptcod];  */
                   8862: /*           } */
                   8863: /*           tabpopprev[(int)(agedeb)][i][cptcod]=tabpop[(int)(agedeb)][i][cptcod]/kk1*popeffectif[(int)(agedeb+(calagedatem+12*cpt)*hstepm/YEARM*stepm-1)]; */
                   8864: /*         } */
1.218     brouard  8865:            
1.227     brouard  8866: /*         if (h==(int)(calagedatem+12*cpt)) */
                   8867: /*           for(j=1; j<=nlstate;j++)  */
                   8868: /*             fprintf(ficrespop," %15.2f",tabpopprev[(int)(agedeb+1)][j][cptcod]); */
                   8869: /*       } */
                   8870: /*       free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm); */
                   8871: /*     } */
                   8872: /*       } */
1.218     brouard  8873:       
1.227     brouard  8874: /*       /\******\/ */
1.218     brouard  8875:       
1.227     brouard  8876: /*       for (cpt=1; cpt<=(anpyram1-anpyram);cpt++) {  */
                   8877: /*     fprintf(ficrespop,"\n\n# Forecasting at date %.lf/%.lf/%.lf ",jpyram,mpyram,anpyram+cpt);    */
                   8878: /*     for (agedeb=(fage-((int)calagedatem %12/12.)); agedeb>=(ageminpar-((int)calagedatem %12)/12.); agedeb--){  */
                   8879: /*       nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm);  */
                   8880: /*       nhstepm = nhstepm/hstepm;  */
1.126     brouard  8881:          
1.227     brouard  8882: /*       p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm); */
                   8883: /*       oldm=oldms;savm=savms; */
                   8884: /*       hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);   */
                   8885: /*       for (h=0; h<=nhstepm; h++){ */
                   8886: /*         if (h==(int) (calagedatem+YEARM*cpt)) { */
                   8887: /*           fprintf(ficresf,"\n %3.f ",agedeb+h*hstepm/YEARM*stepm); */
                   8888: /*         }  */
                   8889: /*         for(j=1; j<=nlstate+ndeath;j++) { */
                   8890: /*           kk1=0.;kk2=0; */
                   8891: /*           for(i=1; i<=nlstate;i++) {               */
                   8892: /*             kk1=kk1+p3mat[i][j][h]*tabpopprev[(int)agedeb+1][i][cptcod];     */
                   8893: /*           } */
                   8894: /*           if (h==(int)(calagedatem+12*cpt)) fprintf(ficresf," %15.2f", kk1);         */
                   8895: /*         } */
                   8896: /*       } */
                   8897: /*       free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm); */
                   8898: /*     } */
                   8899: /*       } */
                   8900: /*     }  */
                   8901: /*   } */
1.218     brouard  8902:   
1.227     brouard  8903: /*   /\* if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX); *\/ */
1.218     brouard  8904:   
1.227     brouard  8905: /*   if (popforecast==1) { */
                   8906: /*     free_ivector(popage,0,AGESUP); */
                   8907: /*     free_vector(popeffectif,0,AGESUP); */
                   8908: /*     free_vector(popcount,0,AGESUP); */
                   8909: /*   } */
                   8910: /*   free_ma3x(tabpop,1, AGESUP,1,NCOVMAX, 1,NCOVMAX); */
                   8911: /*   free_ma3x(tabpopprev,1, AGESUP,1,NCOVMAX, 1,NCOVMAX); */
                   8912: /*   fclose(ficrespop); */
                   8913: /* } /\* End of popforecast *\/ */
1.218     brouard  8914:  
1.126     brouard  8915: int fileappend(FILE *fichier, char *optionfich)
                   8916: {
                   8917:   if((fichier=fopen(optionfich,"a"))==NULL) {
                   8918:     printf("Problem with file: %s\n", optionfich);
                   8919:     fprintf(ficlog,"Problem with file: %s\n", optionfich);
                   8920:     return (0);
                   8921:   }
                   8922:   fflush(fichier);
                   8923:   return (1);
                   8924: }
                   8925: 
                   8926: 
                   8927: /**************** function prwizard **********************/
                   8928: void prwizard(int ncovmodel, int nlstate, int ndeath,  char model[], FILE *ficparo)
                   8929: {
                   8930: 
                   8931:   /* Wizard to print covariance matrix template */
                   8932: 
1.164     brouard  8933:   char ca[32], cb[32];
                   8934:   int i,j, k, li, lj, lk, ll, jj, npar, itimes;
1.126     brouard  8935:   int numlinepar;
                   8936: 
                   8937:   printf("# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
                   8938:   fprintf(ficparo,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
                   8939:   for(i=1; i <=nlstate; i++){
                   8940:     jj=0;
                   8941:     for(j=1; j <=nlstate+ndeath; j++){
                   8942:       if(j==i) continue;
                   8943:       jj++;
                   8944:       /*ca[0]= k+'a'-1;ca[1]='\0';*/
                   8945:       printf("%1d%1d",i,j);
                   8946:       fprintf(ficparo,"%1d%1d",i,j);
                   8947:       for(k=1; k<=ncovmodel;k++){
                   8948:        /*        printf(" %lf",param[i][j][k]); */
                   8949:        /*        fprintf(ficparo," %lf",param[i][j][k]); */
                   8950:        printf(" 0.");
                   8951:        fprintf(ficparo," 0.");
                   8952:       }
                   8953:       printf("\n");
                   8954:       fprintf(ficparo,"\n");
                   8955:     }
                   8956:   }
                   8957:   printf("# Scales (for hessian or gradient estimation)\n");
                   8958:   fprintf(ficparo,"# Scales (for hessian or gradient estimation)\n");
                   8959:   npar= (nlstate+ndeath-1)*nlstate*ncovmodel; /* Number of parameters*/ 
                   8960:   for(i=1; i <=nlstate; i++){
                   8961:     jj=0;
                   8962:     for(j=1; j <=nlstate+ndeath; j++){
                   8963:       if(j==i) continue;
                   8964:       jj++;
                   8965:       fprintf(ficparo,"%1d%1d",i,j);
                   8966:       printf("%1d%1d",i,j);
                   8967:       fflush(stdout);
                   8968:       for(k=1; k<=ncovmodel;k++){
                   8969:        /*      printf(" %le",delti3[i][j][k]); */
                   8970:        /*      fprintf(ficparo," %le",delti3[i][j][k]); */
                   8971:        printf(" 0.");
                   8972:        fprintf(ficparo," 0.");
                   8973:       }
                   8974:       numlinepar++;
                   8975:       printf("\n");
                   8976:       fprintf(ficparo,"\n");
                   8977:     }
                   8978:   }
                   8979:   printf("# Covariance matrix\n");
                   8980: /* # 121 Var(a12)\n\ */
                   8981: /* # 122 Cov(b12,a12) Var(b12)\n\ */
                   8982: /* # 131 Cov(a13,a12) Cov(a13,b12, Var(a13)\n\ */
                   8983: /* # 132 Cov(b13,a12) Cov(b13,b12, Cov(b13,a13) Var(b13)\n\ */
                   8984: /* # 212 Cov(a21,a12) Cov(a21,b12, Cov(a21,a13) Cov(a21,b13) Var(a21)\n\ */
                   8985: /* # 212 Cov(b21,a12) Cov(b21,b12, Cov(b21,a13) Cov(b21,b13) Cov(b21,a21) Var(b21)\n\ */
                   8986: /* # 232 Cov(a23,a12) Cov(a23,b12, Cov(a23,a13) Cov(a23,b13) Cov(a23,a21) Cov(a23,b21) Var(a23)\n\ */
                   8987: /* # 232 Cov(b23,a12) Cov(b23,b12) ... Var (b23)\n" */
                   8988:   fflush(stdout);
                   8989:   fprintf(ficparo,"# Covariance matrix\n");
                   8990:   /* # 121 Var(a12)\n\ */
                   8991:   /* # 122 Cov(b12,a12) Var(b12)\n\ */
                   8992:   /* #   ...\n\ */
                   8993:   /* # 232 Cov(b23,a12)  Cov(b23,b12) ... Var (b23)\n" */
                   8994:   
                   8995:   for(itimes=1;itimes<=2;itimes++){
                   8996:     jj=0;
                   8997:     for(i=1; i <=nlstate; i++){
                   8998:       for(j=1; j <=nlstate+ndeath; j++){
                   8999:        if(j==i) continue;
                   9000:        for(k=1; k<=ncovmodel;k++){
                   9001:          jj++;
                   9002:          ca[0]= k+'a'-1;ca[1]='\0';
                   9003:          if(itimes==1){
                   9004:            printf("#%1d%1d%d",i,j,k);
                   9005:            fprintf(ficparo,"#%1d%1d%d",i,j,k);
                   9006:          }else{
                   9007:            printf("%1d%1d%d",i,j,k);
                   9008:            fprintf(ficparo,"%1d%1d%d",i,j,k);
                   9009:            /*  printf(" %.5le",matcov[i][j]); */
                   9010:          }
                   9011:          ll=0;
                   9012:          for(li=1;li <=nlstate; li++){
                   9013:            for(lj=1;lj <=nlstate+ndeath; lj++){
                   9014:              if(lj==li) continue;
                   9015:              for(lk=1;lk<=ncovmodel;lk++){
                   9016:                ll++;
                   9017:                if(ll<=jj){
                   9018:                  cb[0]= lk +'a'-1;cb[1]='\0';
                   9019:                  if(ll<jj){
                   9020:                    if(itimes==1){
                   9021:                      printf(" Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
                   9022:                      fprintf(ficparo," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
                   9023:                    }else{
                   9024:                      printf(" 0.");
                   9025:                      fprintf(ficparo," 0.");
                   9026:                    }
                   9027:                  }else{
                   9028:                    if(itimes==1){
                   9029:                      printf(" Var(%s%1d%1d)",ca,i,j);
                   9030:                      fprintf(ficparo," Var(%s%1d%1d)",ca,i,j);
                   9031:                    }else{
                   9032:                      printf(" 0.");
                   9033:                      fprintf(ficparo," 0.");
                   9034:                    }
                   9035:                  }
                   9036:                }
                   9037:              } /* end lk */
                   9038:            } /* end lj */
                   9039:          } /* end li */
                   9040:          printf("\n");
                   9041:          fprintf(ficparo,"\n");
                   9042:          numlinepar++;
                   9043:        } /* end k*/
                   9044:       } /*end j */
                   9045:     } /* end i */
                   9046:   } /* end itimes */
                   9047: 
                   9048: } /* end of prwizard */
                   9049: /******************* Gompertz Likelihood ******************************/
                   9050: double gompertz(double x[])
                   9051: { 
                   9052:   double A,B,L=0.0,sump=0.,num=0.;
                   9053:   int i,n=0; /* n is the size of the sample */
                   9054: 
1.220     brouard  9055:   for (i=1;i<=imx ; i++) {
1.126     brouard  9056:     sump=sump+weight[i];
                   9057:     /*    sump=sump+1;*/
                   9058:     num=num+1;
                   9059:   }
                   9060:  
                   9061:  
                   9062:   /* for (i=0; i<=imx; i++) 
                   9063:      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]);*/
                   9064: 
                   9065:   for (i=1;i<=imx ; i++)
                   9066:     {
                   9067:       if (cens[i] == 1 && wav[i]>1)
                   9068:        A=-x[1]/(x[2])*(exp(x[2]*(agecens[i]-agegomp))-exp(x[2]*(ageexmed[i]-agegomp)));
                   9069:       
                   9070:       if (cens[i] == 0 && wav[i]>1)
                   9071:        A=-x[1]/(x[2])*(exp(x[2]*(agedc[i]-agegomp))-exp(x[2]*(ageexmed[i]-agegomp)))
                   9072:             +log(x[1]/YEARM)+x[2]*(agedc[i]-agegomp)+log(YEARM);  
                   9073:       
                   9074:       /*if (wav[i] > 1 && agecens[i] > 15) {*/ /* ??? */
                   9075:       if (wav[i] > 1 ) { /* ??? */
                   9076:        L=L+A*weight[i];
                   9077:        /*      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]);*/
                   9078:       }
                   9079:     }
                   9080: 
                   9081:  /*printf("x1=%2.9f x2=%2.9f x3=%2.9f L=%f\n",x[1],x[2],x[3],L);*/
                   9082:  
                   9083:   return -2*L*num/sump;
                   9084: }
                   9085: 
1.136     brouard  9086: #ifdef GSL
                   9087: /******************* Gompertz_f Likelihood ******************************/
                   9088: double gompertz_f(const gsl_vector *v, void *params)
                   9089: { 
                   9090:   double A,B,LL=0.0,sump=0.,num=0.;
                   9091:   double *x= (double *) v->data;
                   9092:   int i,n=0; /* n is the size of the sample */
                   9093: 
                   9094:   for (i=0;i<=imx-1 ; i++) {
                   9095:     sump=sump+weight[i];
                   9096:     /*    sump=sump+1;*/
                   9097:     num=num+1;
                   9098:   }
                   9099:  
                   9100:  
                   9101:   /* for (i=0; i<=imx; i++) 
                   9102:      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]);*/
                   9103:   printf("x[0]=%lf x[1]=%lf\n",x[0],x[1]);
                   9104:   for (i=1;i<=imx ; i++)
                   9105:     {
                   9106:       if (cens[i] == 1 && wav[i]>1)
                   9107:        A=-x[0]/(x[1])*(exp(x[1]*(agecens[i]-agegomp))-exp(x[1]*(ageexmed[i]-agegomp)));
                   9108:       
                   9109:       if (cens[i] == 0 && wav[i]>1)
                   9110:        A=-x[0]/(x[1])*(exp(x[1]*(agedc[i]-agegomp))-exp(x[1]*(ageexmed[i]-agegomp)))
                   9111:             +log(x[0]/YEARM)+x[1]*(agedc[i]-agegomp)+log(YEARM);  
                   9112:       
                   9113:       /*if (wav[i] > 1 && agecens[i] > 15) {*/ /* ??? */
                   9114:       if (wav[i] > 1 ) { /* ??? */
                   9115:        LL=LL+A*weight[i];
                   9116:        /*      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]);*/
                   9117:       }
                   9118:     }
                   9119: 
                   9120:  /*printf("x1=%2.9f x2=%2.9f x3=%2.9f L=%f\n",x[1],x[2],x[3],L);*/
                   9121:   printf("x[0]=%lf x[1]=%lf -2*LL*num/sump=%lf\n",x[0],x[1],-2*LL*num/sump);
                   9122:  
                   9123:   return -2*LL*num/sump;
                   9124: }
                   9125: #endif
                   9126: 
1.126     brouard  9127: /******************* Printing html file ***********/
1.201     brouard  9128: void printinghtmlmort(char fileresu[], char title[], char datafile[], int firstpass, \
1.126     brouard  9129:                  int lastpass, int stepm, int weightopt, char model[],\
                   9130:                  int imx,  double p[],double **matcov,double agemortsup){
                   9131:   int i,k;
                   9132: 
                   9133:   fprintf(fichtm,"<ul><li><h4>Result files </h4>\n Force of mortality. Parameters of the Gompertz fit (with confidence interval in brackets):<br>");
                   9134:   fprintf(fichtm,"  mu(age) =%lf*exp(%lf*(age-%d)) per year<br><br>",p[1],p[2],agegomp);
                   9135:   for (i=1;i<=2;i++) 
                   9136:     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  9137:   fprintf(fichtm,"<br><br><img src=\"graphmort.svg\">");
1.126     brouard  9138:   fprintf(fichtm,"</ul>");
                   9139: 
                   9140: fprintf(fichtm,"<ul><li><h4>Life table</h4>\n <br>");
                   9141: 
                   9142:  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>");
                   9143: 
                   9144:  for (k=agegomp;k<(agemortsup-2);k++) 
                   9145:    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]);
                   9146: 
                   9147:  
                   9148:   fflush(fichtm);
                   9149: }
                   9150: 
                   9151: /******************* Gnuplot file **************/
1.201     brouard  9152: void printinggnuplotmort(char fileresu[], char optionfilefiname[], double ageminpar, double agemaxpar, double fage , char pathc[], double p[]){
1.126     brouard  9153: 
                   9154:   char dirfileres[132],optfileres[132];
1.164     brouard  9155: 
1.126     brouard  9156:   int ng;
                   9157: 
                   9158: 
                   9159:   /*#ifdef windows */
                   9160:   fprintf(ficgp,"cd \"%s\" \n",pathc);
                   9161:     /*#endif */
                   9162: 
                   9163: 
                   9164:   strcpy(dirfileres,optionfilefiname);
                   9165:   strcpy(optfileres,"vpl");
1.199     brouard  9166:   fprintf(ficgp,"set out \"graphmort.svg\"\n "); 
1.126     brouard  9167:   fprintf(ficgp,"set xlabel \"Age\"\n set ylabel \"Force of mortality (per year)\" \n "); 
1.199     brouard  9168:   fprintf(ficgp, "set ter svg size 640, 480\n set log y\n"); 
1.145     brouard  9169:   /* fprintf(ficgp, "set size 0.65,0.65\n"); */
1.126     brouard  9170:   fprintf(ficgp,"plot [%d:100] %lf*exp(%lf*(x-%d))",agegomp,p[1],p[2],agegomp);
                   9171: 
                   9172: } 
                   9173: 
1.136     brouard  9174: int readdata(char datafile[], int firstobs, int lastobs, int *imax)
                   9175: {
1.126     brouard  9176: 
1.136     brouard  9177:   /*-------- data file ----------*/
                   9178:   FILE *fic;
                   9179:   char dummy[]="                         ";
1.240     brouard  9180:   int i=0, j=0, n=0, iv=0, v;
1.223     brouard  9181:   int lstra;
1.136     brouard  9182:   int linei, month, year,iout;
                   9183:   char line[MAXLINE], linetmp[MAXLINE];
1.164     brouard  9184:   char stra[MAXLINE], strb[MAXLINE];
1.136     brouard  9185:   char *stratrunc;
1.223     brouard  9186: 
1.240     brouard  9187:   DummyV=ivector(1,NCOVMAX); /* 1 to 3 */
                   9188:   FixedV=ivector(1,NCOVMAX); /* 1 to 3 */
1.126     brouard  9189: 
1.240     brouard  9190:   for(v=1; v <=ncovcol;v++){
                   9191:     DummyV[v]=0;
                   9192:     FixedV[v]=0;
                   9193:   }
                   9194:   for(v=ncovcol+1; v <=ncovcol+nqv;v++){
                   9195:     DummyV[v]=1;
                   9196:     FixedV[v]=0;
                   9197:   }
                   9198:   for(v=ncovcol+nqv+1; v <=ncovcol+nqv+ntv;v++){
                   9199:     DummyV[v]=0;
                   9200:     FixedV[v]=1;
                   9201:   }
                   9202:   for(v=ncovcol+nqv+ntv+1; v <=ncovcol+nqv+ntv+nqtv;v++){
                   9203:     DummyV[v]=1;
                   9204:     FixedV[v]=1;
                   9205:   }
                   9206:   for(v=1; v <=ncovcol+nqv+ntv+nqtv;v++){
                   9207:     printf("Covariate type in the data: V%d, DummyV(V%d)=%d, FixedV(V%d)=%d\n",v,v,DummyV[v],v,FixedV[v]);
                   9208:     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]);
                   9209:   }
1.126     brouard  9210: 
1.136     brouard  9211:   if((fic=fopen(datafile,"r"))==NULL)    {
1.218     brouard  9212:     printf("Problem while opening datafile: %s with errno='%s'\n", datafile,strerror(errno));fflush(stdout);
                   9213:     fprintf(ficlog,"Problem while opening datafile: %s with errno='%s'\n", datafile,strerror(errno));fflush(ficlog);return 1;
1.136     brouard  9214:   }
1.126     brouard  9215: 
1.136     brouard  9216:   i=1;
                   9217:   linei=0;
                   9218:   while ((fgets(line, MAXLINE, fic) != NULL) &&((i >= firstobs) && (i <=lastobs))) {
                   9219:     linei=linei+1;
                   9220:     for(j=strlen(line); j>=0;j--){  /* Untabifies line */
                   9221:       if(line[j] == '\t')
                   9222:        line[j] = ' ';
                   9223:     }
                   9224:     for(j=strlen(line)-1; (line[j]==' ')||(line[j]==10)||(line[j]==13);j--){
                   9225:       ;
                   9226:     };
                   9227:     line[j+1]=0;  /* Trims blanks at end of line */
                   9228:     if(line[0]=='#'){
                   9229:       fprintf(ficlog,"Comment line\n%s\n",line);
                   9230:       printf("Comment line\n%s\n",line);
                   9231:       continue;
                   9232:     }
                   9233:     trimbb(linetmp,line); /* Trims multiple blanks in line */
1.164     brouard  9234:     strcpy(line, linetmp);
1.223     brouard  9235:     
                   9236:     /* Loops on waves */
                   9237:     for (j=maxwav;j>=1;j--){
                   9238:       for (iv=nqtv;iv>=1;iv--){  /* Loop  on time varying quantitative variables */
1.238     brouard  9239:        cutv(stra, strb, line, ' '); 
                   9240:        if(strb[0]=='.') { /* Missing value */
                   9241:          lval=-1;
                   9242:          cotqvar[j][iv][i]=-1; /* 0.0/0.0 */
                   9243:          cotvar[j][ntv+iv][i]=-1; /* For performance reasons */
                   9244:          if(isalpha(strb[1])) { /* .m or .d Really Missing value */
                   9245:            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);
                   9246:            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);
                   9247:            return 1;
                   9248:          }
                   9249:        }else{
                   9250:          errno=0;
                   9251:          /* what_kind_of_number(strb); */
                   9252:          dval=strtod(strb,&endptr); 
                   9253:          /* if( strb[0]=='\0' || (*endptr != '\0')){ */
                   9254:          /* if(strb != endptr && *endptr == '\0') */
                   9255:          /*    dval=dlval; */
                   9256:          /* if (errno == ERANGE && (lval == LONG_MAX || lval == LONG_MIN)) */
                   9257:          if( strb[0]=='\0' || (*endptr != '\0')){
                   9258:            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);
                   9259:            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);
                   9260:            return 1;
                   9261:          }
                   9262:          cotqvar[j][iv][i]=dval; 
                   9263:          cotvar[j][ntv+iv][i]=dval; 
                   9264:        }
                   9265:        strcpy(line,stra);
1.223     brouard  9266:       }/* end loop ntqv */
1.225     brouard  9267:       
1.223     brouard  9268:       for (iv=ntv;iv>=1;iv--){  /* Loop  on time varying dummies */
1.238     brouard  9269:        cutv(stra, strb, line, ' '); 
                   9270:        if(strb[0]=='.') { /* Missing value */
                   9271:          lval=-1;
                   9272:        }else{
                   9273:          errno=0;
                   9274:          lval=strtol(strb,&endptr,10); 
                   9275:          /*    if (errno == ERANGE && (lval == LONG_MAX || lval == LONG_MIN))*/
                   9276:          if( strb[0]=='\0' || (*endptr != '\0')){
                   9277:            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);
                   9278:            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);
                   9279:            return 1;
                   9280:          }
                   9281:        }
                   9282:        if(lval <-1 || lval >1){
                   9283:          printf("Error reading data around '%ld' at line number %d for individual %d, '%s'\n \
1.223     brouard  9284:  Should be a value of %d(nth) covariate (0 should be the value for the reference and 1\n \
                   9285:  for the alternative. IMaCh does not build design variables automatically, do it yourself.\n \
1.238     brouard  9286:  For example, for multinomial values like 1, 2 and 3,\n                        \
                   9287:  build V1=0 V2=0 for the reference value (1),\n                                \
                   9288:         V1=1 V2=0 for (2) \n                                           \
1.223     brouard  9289:  and V1=0 V2=1 for (3). V1=1 V2=1 should not exist and the corresponding\n \
1.238     brouard  9290:  output of IMaCh is often meaningless.\n                               \
1.223     brouard  9291:  Exiting.\n",lval,linei, i,line,j);
1.238     brouard  9292:          fprintf(ficlog,"Error reading data around '%ld' at line number %d for individual %d, '%s'\n \
1.223     brouard  9293:  Should be a value of %d(nth) covariate (0 should be the value for the reference and 1\n \
                   9294:  for the alternative. IMaCh does not build design variables automatically, do it yourself.\n \
1.238     brouard  9295:  For example, for multinomial values like 1, 2 and 3,\n                        \
                   9296:  build V1=0 V2=0 for the reference value (1),\n                                \
                   9297:         V1=1 V2=0 for (2) \n                                           \
1.223     brouard  9298:  and V1=0 V2=1 for (3). V1=1 V2=1 should not exist and the corresponding\n \
1.238     brouard  9299:  output of IMaCh is often meaningless.\n                               \
1.223     brouard  9300:  Exiting.\n",lval,linei, i,line,j);fflush(ficlog);
1.238     brouard  9301:          return 1;
                   9302:        }
                   9303:        cotvar[j][iv][i]=(double)(lval);
                   9304:        strcpy(line,stra);
1.223     brouard  9305:       }/* end loop ntv */
1.225     brouard  9306:       
1.223     brouard  9307:       /* Statuses  at wave */
1.137     brouard  9308:       cutv(stra, strb, line, ' '); 
1.223     brouard  9309:       if(strb[0]=='.') { /* Missing value */
1.238     brouard  9310:        lval=-1;
1.136     brouard  9311:       }else{
1.238     brouard  9312:        errno=0;
                   9313:        lval=strtol(strb,&endptr,10); 
                   9314:        /*      if (errno == ERANGE && (lval == LONG_MAX || lval == LONG_MIN))*/
                   9315:        if( strb[0]=='\0' || (*endptr != '\0')){
                   9316:          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);
                   9317:          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);
                   9318:          return 1;
                   9319:        }
1.136     brouard  9320:       }
1.225     brouard  9321:       
1.136     brouard  9322:       s[j][i]=lval;
1.225     brouard  9323:       
1.223     brouard  9324:       /* Date of Interview */
1.136     brouard  9325:       strcpy(line,stra);
                   9326:       cutv(stra, strb,line,' ');
1.169     brouard  9327:       if( (iout=sscanf(strb,"%d/%d",&month, &year)) != 0){
1.136     brouard  9328:       }
1.169     brouard  9329:       else  if( (iout=sscanf(strb,"%s.",dummy)) != 0){
1.225     brouard  9330:        month=99;
                   9331:        year=9999;
1.136     brouard  9332:       }else{
1.225     brouard  9333:        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);
                   9334:        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);
                   9335:        return 1;
1.136     brouard  9336:       }
                   9337:       anint[j][i]= (double) year; 
                   9338:       mint[j][i]= (double)month; 
                   9339:       strcpy(line,stra);
1.223     brouard  9340:     } /* End loop on waves */
1.225     brouard  9341:     
1.223     brouard  9342:     /* Date of death */
1.136     brouard  9343:     cutv(stra, strb,line,' '); 
1.169     brouard  9344:     if( (iout=sscanf(strb,"%d/%d",&month, &year)) != 0){
1.136     brouard  9345:     }
1.169     brouard  9346:     else  if( (iout=sscanf(strb,"%s.",dummy)) != 0){
1.136     brouard  9347:       month=99;
                   9348:       year=9999;
                   9349:     }else{
1.141     brouard  9350:       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  9351:       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);
                   9352:       return 1;
1.136     brouard  9353:     }
                   9354:     andc[i]=(double) year; 
                   9355:     moisdc[i]=(double) month; 
                   9356:     strcpy(line,stra);
                   9357:     
1.223     brouard  9358:     /* Date of birth */
1.136     brouard  9359:     cutv(stra, strb,line,' '); 
1.169     brouard  9360:     if( (iout=sscanf(strb,"%d/%d",&month, &year)) != 0){
1.136     brouard  9361:     }
1.169     brouard  9362:     else  if( (iout=sscanf(strb,"%s.", dummy)) != 0){
1.136     brouard  9363:       month=99;
                   9364:       year=9999;
                   9365:     }else{
1.141     brouard  9366:       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);
                   9367:       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  9368:       return 1;
1.136     brouard  9369:     }
                   9370:     if (year==9999) {
1.141     brouard  9371:       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);
                   9372:       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  9373:       return 1;
                   9374:       
1.136     brouard  9375:     }
                   9376:     annais[i]=(double)(year);
                   9377:     moisnais[i]=(double)(month); 
                   9378:     strcpy(line,stra);
1.225     brouard  9379:     
1.223     brouard  9380:     /* Sample weight */
1.136     brouard  9381:     cutv(stra, strb,line,' '); 
                   9382:     errno=0;
                   9383:     dval=strtod(strb,&endptr); 
                   9384:     if( strb[0]=='\0' || (*endptr != '\0')){
1.141     brouard  9385:       printf("Error reading data around '%f' at line number %d, \"%s\" for individual %d\nShould be a weight.  Exiting.\n",dval, i,line,linei);
                   9386:       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  9387:       fflush(ficlog);
                   9388:       return 1;
                   9389:     }
                   9390:     weight[i]=dval; 
                   9391:     strcpy(line,stra);
1.225     brouard  9392:     
1.223     brouard  9393:     for (iv=nqv;iv>=1;iv--){  /* Loop  on fixed quantitative variables */
                   9394:       cutv(stra, strb, line, ' '); 
                   9395:       if(strb[0]=='.') { /* Missing value */
1.225     brouard  9396:        lval=-1;
1.223     brouard  9397:       }else{
1.225     brouard  9398:        errno=0;
                   9399:        /* what_kind_of_number(strb); */
                   9400:        dval=strtod(strb,&endptr);
                   9401:        /* if(strb != endptr && *endptr == '\0') */
                   9402:        /*   dval=dlval; */
                   9403:        /* if (errno == ERANGE && (lval == LONG_MAX || lval == LONG_MIN)) */
                   9404:        if( strb[0]=='\0' || (*endptr != '\0')){
                   9405:          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);
                   9406:          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);
                   9407:          return 1;
                   9408:        }
                   9409:        coqvar[iv][i]=dval; 
1.226     brouard  9410:        covar[ncovcol+iv][i]=dval; /* including qvar in standard covar for performance reasons */ 
1.223     brouard  9411:       }
                   9412:       strcpy(line,stra);
                   9413:     }/* end loop nqv */
1.136     brouard  9414:     
1.223     brouard  9415:     /* Covariate values */
1.136     brouard  9416:     for (j=ncovcol;j>=1;j--){
                   9417:       cutv(stra, strb,line,' '); 
1.223     brouard  9418:       if(strb[0]=='.') { /* Missing covariate value */
1.225     brouard  9419:        lval=-1;
1.136     brouard  9420:       }else{
1.225     brouard  9421:        errno=0;
                   9422:        lval=strtol(strb,&endptr,10); 
                   9423:        if( strb[0]=='\0' || (*endptr != '\0')){
                   9424:          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);
                   9425:          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);
                   9426:          return 1;
                   9427:        }
1.136     brouard  9428:       }
                   9429:       if(lval <-1 || lval >1){
1.225     brouard  9430:        printf("Error reading data around '%ld' at line number %d for individual %d, '%s'\n \
1.136     brouard  9431:  Should be a value of %d(nth) covariate (0 should be the value for the reference and 1\n \
                   9432:  for the alternative. IMaCh does not build design variables automatically, do it yourself.\n \
1.225     brouard  9433:  For example, for multinomial values like 1, 2 and 3,\n                        \
                   9434:  build V1=0 V2=0 for the reference value (1),\n                                \
                   9435:         V1=1 V2=0 for (2) \n                                           \
1.136     brouard  9436:  and V1=0 V2=1 for (3). V1=1 V2=1 should not exist and the corresponding\n \
1.225     brouard  9437:  output of IMaCh is often meaningless.\n                               \
1.136     brouard  9438:  Exiting.\n",lval,linei, i,line,j);
1.225     brouard  9439:        fprintf(ficlog,"Error reading data around '%ld' at line number %d for individual %d, '%s'\n \
1.136     brouard  9440:  Should be a value of %d(nth) covariate (0 should be the value for the reference and 1\n \
                   9441:  for the alternative. IMaCh does not build design variables automatically, do it yourself.\n \
1.225     brouard  9442:  For example, for multinomial values like 1, 2 and 3,\n                        \
                   9443:  build V1=0 V2=0 for the reference value (1),\n                                \
                   9444:         V1=1 V2=0 for (2) \n                                           \
1.136     brouard  9445:  and V1=0 V2=1 for (3). V1=1 V2=1 should not exist and the corresponding\n \
1.225     brouard  9446:  output of IMaCh is often meaningless.\n                               \
1.136     brouard  9447:  Exiting.\n",lval,linei, i,line,j);fflush(ficlog);
1.225     brouard  9448:        return 1;
1.136     brouard  9449:       }
                   9450:       covar[j][i]=(double)(lval);
                   9451:       strcpy(line,stra);
                   9452:     }  
                   9453:     lstra=strlen(stra);
1.225     brouard  9454:     
1.136     brouard  9455:     if(lstra > 9){ /* More than 2**32 or max of what printf can write with %ld */
                   9456:       stratrunc = &(stra[lstra-9]);
                   9457:       num[i]=atol(stratrunc);
                   9458:     }
                   9459:     else
                   9460:       num[i]=atol(stra);
                   9461:     /*if((s[2][i]==2) && (s[3][i]==-1)&&(s[4][i]==9)){
                   9462:       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;}*/
                   9463:     
                   9464:     i=i+1;
                   9465:   } /* End loop reading  data */
1.225     brouard  9466:   
1.136     brouard  9467:   *imax=i-1; /* Number of individuals */
                   9468:   fclose(fic);
1.225     brouard  9469:   
1.136     brouard  9470:   return (0);
1.164     brouard  9471:   /* endread: */
1.225     brouard  9472:   printf("Exiting readdata: ");
                   9473:   fclose(fic);
                   9474:   return (1);
1.223     brouard  9475: }
1.126     brouard  9476: 
1.234     brouard  9477: void removefirstspace(char **stri){/*, char stro[]) {*/
1.230     brouard  9478:   char *p1 = *stri, *p2 = *stri;
1.235     brouard  9479:   while (*p2 == ' ')
1.234     brouard  9480:     p2++; 
                   9481:   /* while ((*p1++ = *p2++) !=0) */
                   9482:   /*   ; */
                   9483:   /* do */
                   9484:   /*   while (*p2 == ' ') */
                   9485:   /*     p2++; */
                   9486:   /* while (*p1++ == *p2++); */
                   9487:   *stri=p2; 
1.145     brouard  9488: }
                   9489: 
1.235     brouard  9490: int decoderesult ( char resultline[], int nres)
1.230     brouard  9491: /**< This routine decode one result line and returns the combination # of dummy covariates only **/
                   9492: {
1.235     brouard  9493:   int j=0, k=0, k1=0, k2=0, k3=0, k4=0, match=0, k2q=0, k3q=0, k4q=0;
1.230     brouard  9494:   char resultsav[MAXLINE];
1.234     brouard  9495:   int resultmodel[MAXLINE];
                   9496:   int modelresult[MAXLINE];
1.230     brouard  9497:   char stra[80], strb[80], strc[80], strd[80],stre[80];
                   9498: 
1.234     brouard  9499:   removefirstspace(&resultline);
1.233     brouard  9500:   printf("decoderesult:%s\n",resultline);
1.230     brouard  9501: 
                   9502:   if (strstr(resultline,"v") !=0){
                   9503:     printf("Error. 'v' must be in upper case 'V' result: %s ",resultline);
                   9504:     fprintf(ficlog,"Error. 'v' must be in upper case result: %s ",resultline);fflush(ficlog);
                   9505:     return 1;
                   9506:   }
                   9507:   trimbb(resultsav, resultline);
                   9508:   if (strlen(resultsav) >1){
                   9509:     j=nbocc(resultsav,'='); /**< j=Number of covariate values'=' */
                   9510:   }
1.253     brouard  9511:   if(j == 0){ /* Resultline but no = */
                   9512:     TKresult[nres]=0; /* Combination for the nresult and the model */
                   9513:     return (0);
                   9514:   }
                   9515:     
1.234     brouard  9516:   if( j != cptcovs ){ /* Be careful if a variable is in a product but not single */
                   9517:     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);
                   9518:     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);
                   9519:   }
                   9520:   for(k=1; k<=j;k++){ /* Loop on any covariate of the result line */
                   9521:     if(nbocc(resultsav,'=') >1){
                   9522:        cutl(stra,strb,resultsav,' '); /* keeps in strb after the first ' ' 
                   9523:                                      resultsav= V4=1 V5=25.1 V3=0 strb=V3=0 stra= V4=1 V5=25.1 */
                   9524:        cutl(strc,strd,strb,'=');  /* strb:V4=1 strc=1 strd=V4 */
                   9525:     }else
                   9526:       cutl(strc,strd,resultsav,'=');
1.230     brouard  9527:     Tvalsel[k]=atof(strc); /* 1 */
1.234     brouard  9528:     
1.230     brouard  9529:     cutl(strc,stre,strd,'V'); /* strd='V4' strc=4 stre='V' */;
                   9530:     Tvarsel[k]=atoi(strc);
                   9531:     /* Typevarsel[k]=1;  /\* 1 for age product *\/ */
                   9532:     /* cptcovsel++;     */
                   9533:     if (nbocc(stra,'=') >0)
                   9534:       strcpy(resultsav,stra); /* and analyzes it */
                   9535:   }
1.235     brouard  9536:   /* Checking for missing or useless values in comparison of current model needs */
1.236     brouard  9537:   for(k1=1; k1<= cptcovt ;k1++){ /* model line V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
                   9538:     if(Typevar[k1]==0){ /* Single covariate in model */
1.234     brouard  9539:       match=0;
1.236     brouard  9540:       for(k2=1; k2 <=j;k2++){/* result line V4=1 V5=24.1 V3=1  V2=8 V1=0 */
1.237     brouard  9541:        if(Tvar[k1]==Tvarsel[k2]) {/* Tvar[1]=5 == Tvarsel[2]=5   */
1.236     brouard  9542:          modelresult[k2]=k1;/* modelresult[2]=1 modelresult[1]=2  modelresult[3]=3  modelresult[6]=4 modelresult[9]=5 */
1.234     brouard  9543:          match=1;
                   9544:          break;
                   9545:        }
                   9546:       }
                   9547:       if(match == 0){
                   9548:        printf("Error in result line: %d value missing; result: %s, model=%s\n",k1, resultline, model);
                   9549:       }
                   9550:     }
                   9551:   }
1.235     brouard  9552:   /* Checking for missing or useless values in comparison of current model needs */
                   9553:   for(k2=1; k2 <=j;k2++){ /* result line V4=1 V5=24.1 V3=1  V2=8 V1=0 */
1.234     brouard  9554:     match=0;
1.235     brouard  9555:     for(k1=1; k1<= cptcovt ;k1++){ /* model line V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
                   9556:       if(Typevar[k1]==0){ /* Single */
1.237     brouard  9557:        if(Tvar[k1]==Tvarsel[k2]) { /* Tvar[2]=4 == Tvarsel[1]=4   */
1.235     brouard  9558:          resultmodel[k1]=k2;  /* resultmodel[2]=1 resultmodel[1]=2  resultmodel[3]=3  resultmodel[6]=4 resultmodel[9]=5 */
1.234     brouard  9559:          ++match;
                   9560:        }
                   9561:       }
                   9562:     }
                   9563:     if(match == 0){
                   9564:       printf("Error in result line: %d value missing; result: %s, model=%s\n",k1, resultline, model);
                   9565:     }else if(match > 1){
                   9566:       printf("Error in result line: %d doubled; result: %s, model=%s\n",k2, resultline, model);
                   9567:     }
                   9568:   }
1.235     brouard  9569:       
1.234     brouard  9570:   /* We need to deduce which combination number is chosen and save quantitative values */
1.235     brouard  9571:   /* model line V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
                   9572:   /* result line V4=1 V5=25.1 V3=0  V2=8 V1=1 */
                   9573:   /* should give a combination of dummy V4=1, V3=0, V1=1 => V4*2**(0) + V3*2**(1) + V1*2**(2) = 5 + (1offset) = 6*/
                   9574:   /* result line V4=1 V5=24.1 V3=1  V2=8 V1=0 */
                   9575:   /* should give a combination of dummy V4=1, V3=1, V1=0 => V4*2**(0) + V3*2**(1) + V1*2**(2) = 3 + (1offset) = 4*/
                   9576:   /*    1 0 0 0 */
                   9577:   /*    2 1 0 0 */
                   9578:   /*    3 0 1 0 */ 
                   9579:   /*    4 1 1 0 */ /* V4=1, V3=1, V1=0 */
                   9580:   /*    5 0 0 1 */
                   9581:   /*    6 1 0 1 */ /* V4=1, V3=0, V1=1 */
                   9582:   /*    7 0 1 1 */
                   9583:   /*    8 1 1 1 */
1.237     brouard  9584:   /* V(Tvresult)=Tresult V4=1 V3=0 V1=1 Tresult[nres=1][2]=0 */
                   9585:   /* V(Tvqresult)=Tqresult V5=25.1 V2=8 Tqresult[nres=1][1]=25.1 */
                   9586:   /* V5*age V5 known which value for nres?  */
                   9587:   /* Tqinvresult[2]=8 Tqinvresult[1]=25.1  */
1.235     brouard  9588:   for(k1=1, k=0, k4=0, k4q=0; k1 <=cptcovt;k1++){ /* model line */
                   9589:     if( Dummy[k1]==0 && Typevar[k1]==0 ){ /* Single dummy */
1.237     brouard  9590:       k3= resultmodel[k1]; /* resultmodel[2(V4)] = 1=k3 */
1.235     brouard  9591:       k2=(int)Tvarsel[k3]; /*  Tvarsel[resultmodel[2]]= Tvarsel[1] = 4=k2 */
                   9592:       k+=Tvalsel[k3]*pow(2,k4);  /*  Tvalsel[1]=1  */
1.237     brouard  9593:       Tresult[nres][k4+1]=Tvalsel[k3];/* Tresult[nres][1]=1(V4=1)  Tresult[nres][2]=0(V3=0) */
                   9594:       Tvresult[nres][k4+1]=(int)Tvarsel[k3];/* Tvresult[nres][1]=4 Tvresult[nres][3]=1 */
                   9595:       Tinvresult[nres][(int)Tvarsel[k3]]=Tvalsel[k3]; /* Tinvresult[nres][4]=1 */
1.235     brouard  9596:       printf("Decoderesult Dummy k=%d, V(k2=V%d)= Tvalsel[%d]=%d, 2**(%d)\n",k, k2, k3, (int)Tvalsel[k3], k4);
                   9597:       k4++;;
                   9598:     }  else if( Dummy[k1]==1 && Typevar[k1]==0 ){ /* Single quantitative */
                   9599:       k3q= resultmodel[k1]; /* resultmodel[2] = 1=k3 */
                   9600:       k2q=(int)Tvarsel[k3q]; /*  Tvarsel[resultmodel[2]]= Tvarsel[1] = 4=k2 */
1.237     brouard  9601:       Tqresult[nres][k4q+1]=Tvalsel[k3q]; /* Tqresult[nres][1]=25.1 */
                   9602:       Tvqresult[nres][k4q+1]=(int)Tvarsel[k3q]; /* Tvqresult[nres][1]=5 */
                   9603:       Tqinvresult[nres][(int)Tvarsel[k3q]]=Tvalsel[k3q]; /* Tqinvresult[nres][5]=25.1 */
1.235     brouard  9604:       printf("Decoderesult Quantitative nres=%d, V(k2q=V%d)= Tvalsel[%d]=%d, Tvarsel[%d]=%f\n",nres, k2q, k3q, Tvarsel[k3q], k3q, Tvalsel[k3q]);
                   9605:       k4q++;;
                   9606:     }
                   9607:   }
1.234     brouard  9608:   
1.235     brouard  9609:   TKresult[nres]=++k; /* Combination for the nresult and the model */
1.230     brouard  9610:   return (0);
                   9611: }
1.235     brouard  9612: 
1.230     brouard  9613: int decodemodel( char model[], int lastobs)
                   9614:  /**< This routine decodes the model and returns:
1.224     brouard  9615:        * Model  V1+V2+V3+V8+V7*V8+V5*V6+V8*age+V3*age+age*age
                   9616:        * - nagesqr = 1 if age*age in the model, otherwise 0.
                   9617:        * - cptcovt total number of covariates of the model nbocc(+)+1 = 8 excepting constant and age and age*age
                   9618:        * - cptcovn or number of covariates k of the models excluding age*products =6 and age*age
                   9619:        * - cptcovage number of covariates with age*products =2
                   9620:        * - cptcovs number of simple covariates
                   9621:        * - 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
                   9622:        *     which is a new column after the 9 (ncovcol) variables. 
                   9623:        * - if k is a product Vn*Vm covar[k][i] is filled with correct values for each individual
                   9624:        * - Tprod[l] gives the kth covariates of the product Vn*Vm l=1 to cptcovprod-cptcovage
                   9625:        *    Tprod[1]@2 {5, 6}: position of first product V7*V8 is 5, and second V5*V6 is 6.
                   9626:        * - Tvard[k]  p Tvard[1][1]@4 {7, 8, 5, 6} for V7*V8 and V5*V6 .
                   9627:        */
1.136     brouard  9628: {
1.238     brouard  9629:   int i, j, k, ks, v;
1.227     brouard  9630:   int  j1, k1, k2, k3, k4;
1.136     brouard  9631:   char modelsav[80];
1.145     brouard  9632:   char stra[80], strb[80], strc[80], strd[80],stre[80];
1.187     brouard  9633:   char *strpt;
1.136     brouard  9634: 
1.145     brouard  9635:   /*removespace(model);*/
1.136     brouard  9636:   if (strlen(model) >1){ /* If there is at least 1 covariate */
1.145     brouard  9637:     j=0, j1=0, k1=0, k2=-1, ks=0, cptcovn=0;
1.137     brouard  9638:     if (strstr(model,"AGE") !=0){
1.192     brouard  9639:       printf("Error. AGE must be in lower case 'age' model=1+age+%s. ",model);
                   9640:       fprintf(ficlog,"Error. AGE must be in lower case model=1+age+%s. ",model);fflush(ficlog);
1.136     brouard  9641:       return 1;
                   9642:     }
1.141     brouard  9643:     if (strstr(model,"v") !=0){
                   9644:       printf("Error. 'v' must be in upper case 'V' model=%s ",model);
                   9645:       fprintf(ficlog,"Error. 'v' must be in upper case model=%s ",model);fflush(ficlog);
                   9646:       return 1;
                   9647:     }
1.187     brouard  9648:     strcpy(modelsav,model); 
                   9649:     if ((strpt=strstr(model,"age*age")) !=0){
                   9650:       printf(" strpt=%s, model=%s\n",strpt, model);
                   9651:       if(strpt != model){
1.234     brouard  9652:        printf("Error in model: 'model=%s'; 'age*age' should in first place before other covariates\n \
1.192     brouard  9653:  'model=1+age+age*age+V1.' or 'model=1+age+age*age+V1+V1*age.', please swap as well as \n \
1.187     brouard  9654:  corresponding column of parameters.\n",model);
1.234     brouard  9655:        fprintf(ficlog,"Error in model: 'model=%s'; 'age*age' should in first place before other covariates\n \
1.192     brouard  9656:  'model=1+age+age*age+V1.' or 'model=1+age+age*age+V1+V1*age.', please swap as well as \n \
1.187     brouard  9657:  corresponding column of parameters.\n",model); fflush(ficlog);
1.234     brouard  9658:        return 1;
1.225     brouard  9659:       }
1.187     brouard  9660:       nagesqr=1;
                   9661:       if (strstr(model,"+age*age") !=0)
1.234     brouard  9662:        substrchaine(modelsav, model, "+age*age");
1.187     brouard  9663:       else if (strstr(model,"age*age+") !=0)
1.234     brouard  9664:        substrchaine(modelsav, model, "age*age+");
1.187     brouard  9665:       else 
1.234     brouard  9666:        substrchaine(modelsav, model, "age*age");
1.187     brouard  9667:     }else
                   9668:       nagesqr=0;
                   9669:     if (strlen(modelsav) >1){
                   9670:       j=nbocc(modelsav,'+'); /**< j=Number of '+' */
                   9671:       j1=nbocc(modelsav,'*'); /**< j1=Number of '*' */
1.224     brouard  9672:       cptcovs=j+1-j1; /**<  Number of simple covariates V1+V1*age+V3 +V3*V4+age*age=> V1 + V3 =5-3=2  */
1.187     brouard  9673:       cptcovt= j+1; /* Number of total covariates in the model, not including
1.225     brouard  9674:                     * cst, age and age*age 
                   9675:                     * V1+V1*age+ V3 + V3*V4+age*age=> 3+1=4*/
                   9676:       /* including age products which are counted in cptcovage.
                   9677:        * but the covariates which are products must be treated 
                   9678:        * separately: ncovn=4- 2=2 (V1+V3). */
1.187     brouard  9679:       cptcovprod=j1; /**< Number of products  V1*V2 +v3*age = 2 */
                   9680:       cptcovprodnoage=0; /**< Number of covariate products without age: V3*V4 =1  */
1.225     brouard  9681:       
                   9682:       
1.187     brouard  9683:       /*   Design
                   9684:        *  V1   V2   V3   V4  V5  V6  V7  V8  V9 Weight
                   9685:        *  <          ncovcol=8                >
                   9686:        * Model V2 + V1 + V3*age + V3 + V5*V6 + V7*V8 + V8*age + V8
                   9687:        *   k=  1    2      3       4     5       6      7        8
                   9688:        *  cptcovn number of covariates (not including constant and age ) = # of + plus 1 = 7+1=8
                   9689:        *  covar[k,i], value of kth covariate if not including age for individual i:
1.224     brouard  9690:        *       covar[1][i]= (V1), covar[4][i]=(V4), covar[8][i]=(V8)
                   9691:        *  Tvar[k] # of the kth covariate:  Tvar[1]=2  Tvar[2]=1 Tvar[4]=3 Tvar[8]=8
1.187     brouard  9692:        *       if multiplied by age: V3*age Tvar[3=V3*age]=3 (V3) Tvar[7]=8 and 
                   9693:        *  Tage[++cptcovage]=k
                   9694:        *       if products, new covar are created after ncovcol with k1
                   9695:        *  Tvar[k]=ncovcol+k1; # of the kth covariate product:  Tvar[5]=ncovcol+1=10  Tvar[6]=ncovcol+1=11
                   9696:        *  Tprod[k1]=k; Tprod[1]=5 Tprod[2]= 6; gives the position of the k1th product
                   9697:        *  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
                   9698:        *  Tvar[cptcovn+k2]=Tvard[k1][1];Tvar[cptcovn+k2+1]=Tvard[k1][2];
                   9699:        *  Tvar[8+1]=5;Tvar[8+2]=6;Tvar[8+3]=7;Tvar[8+4]=8 inverted
                   9700:        *  V1   V2   V3   V4  V5  V6  V7  V8  V9  V10  V11
                   9701:        *  <          ncovcol=8                >
                   9702:        *       Model V2 + V1 + V3*age + V3 + V5*V6 + V7*V8 + V8*age + V8    d1   d1   d2  d2
                   9703:        *          k=  1    2      3       4     5       6      7        8    9   10   11  12
                   9704:        *     Tvar[k]= 2    1      3       3    10      11      8        8    5    6    7   8
                   9705:        * p Tvar[1]@12={2,   1,     3,      3,   11,     10,     8,       8,   7,   8,   5,  6}
                   9706:        * p Tprod[1]@2={                         6, 5}
                   9707:        *p Tvard[1][1]@4= {7, 8, 5, 6}
                   9708:        * covar[k][i]= V2   V1      ?      V3    V5*V6?   V7*V8?  ?       V8   
                   9709:        *  cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];
                   9710:        *How to reorganize?
                   9711:        * Model V1 + V2 + V3 + V8 + V5*V6 + V7*V8 + V3*age + V8*age
                   9712:        * Tvars {2,   1,     3,      3,   11,     10,     8,       8,   7,   8,   5,  6}
                   9713:        *       {2,   1,     4,      8,    5,      6,     3,       7}
                   9714:        * Struct []
                   9715:        */
1.225     brouard  9716:       
1.187     brouard  9717:       /* This loop fills the array Tvar from the string 'model'.*/
                   9718:       /* j is the number of + signs in the model V1+V2+V3 j=2 i=3 to 1 */
                   9719:       /*   modelsav=V2+V1+V4+age*V3 strb=age*V3 stra=V2+V1+V4  */
                   9720:       /*       k=4 (age*V3) Tvar[k=4]= 3 (from V3) Tage[cptcovage=1]=4 */
                   9721:       /*       k=3 V4 Tvar[k=3]= 4 (from V4) */
                   9722:       /*       k=2 V1 Tvar[k=2]= 1 (from V1) */
                   9723:       /*       k=1 Tvar[1]=2 (from V2) */
                   9724:       /*       k=5 Tvar[5] */
                   9725:       /* for (k=1; k<=cptcovn;k++) { */
1.198     brouard  9726:       /*       cov[2+k]=nbcode[Tvar[k]][codtabm(ij,Tvar[k])]; */
1.187     brouard  9727:       /*       } */
1.198     brouard  9728:       /* for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,Tvar[Tage[k])]]*cov[2]; */
1.187     brouard  9729:       /*
                   9730:        * Treating invertedly V2+V1+V3*age+V2*V4 is as if written V2*V4 +V3*age + V1 + V2 */
1.227     brouard  9731:       for(k=cptcovt; k>=1;k--){ /**< Number of covariates not including constant and age, neither age*age*/
                   9732:         Tvar[k]=0; Tprod[k]=0; Tposprod[k]=0;
                   9733:       }
1.187     brouard  9734:       cptcovage=0;
                   9735:       for(k=1; k<=cptcovt;k++){ /* Loop on total covariates of the model */
1.234     brouard  9736:        cutl(stra,strb,modelsav,'+'); /* keeps in strb after the first '+' 
1.225     brouard  9737:                                         modelsav==V2+V1+V4+V3*age strb=V3*age stra=V2+V1+V4 */ 
1.234     brouard  9738:        if (nbocc(modelsav,'+')==0) strcpy(strb,modelsav); /* and analyzes it */
                   9739:        /*      printf("i=%d a=%s b=%s sav=%s\n",i, stra,strb,modelsav);*/
                   9740:        /*scanf("%d",i);*/
                   9741:        if (strchr(strb,'*')) {  /**< Model includes a product V2+V1+V4+V3*age strb=V3*age */
                   9742:          cutl(strc,strd,strb,'*'); /**< strd*strc  Vm*Vn: strb=V3*age(input) strc=age strd=V3 ; V3*V2 strc=V2, strd=V3 */
                   9743:          if (strcmp(strc,"age")==0) { /**< Model includes age: Vn*age */
                   9744:            /* covar is not filled and then is empty */
                   9745:            cptcovprod--;
                   9746:            cutl(stre,strb,strd,'V'); /* strd=V3(input): stre="3" */
                   9747:            Tvar[k]=atoi(stre);  /* V2+V1+V4+V3*age Tvar[4]=3 ; V1+V2*age Tvar[2]=2; V1+V1*age Tvar[2]=1 */
                   9748:            Typevar[k]=1;  /* 1 for age product */
                   9749:            cptcovage++; /* Sums the number of covariates which include age as a product */
                   9750:            Tage[cptcovage]=k;  /* Tvar[4]=3, Tage[1] = 4 or V1+V1*age Tvar[2]=1, Tage[1]=2 */
                   9751:            /*printf("stre=%s ", stre);*/
                   9752:          } else if (strcmp(strd,"age")==0) { /* or age*Vn */
                   9753:            cptcovprod--;
                   9754:            cutl(stre,strb,strc,'V');
                   9755:            Tvar[k]=atoi(stre);
                   9756:            Typevar[k]=1;  /* 1 for age product */
                   9757:            cptcovage++;
                   9758:            Tage[cptcovage]=k;
                   9759:          } else {  /* Age is not in the model product V2+V1+V1*V4+V3*age+V3*V2  strb=V3*V2*/
                   9760:            /* loops on k1=1 (V3*V2) and k1=2 V4*V3 */
                   9761:            cptcovn++;
                   9762:            cptcovprodnoage++;k1++;
                   9763:            cutl(stre,strb,strc,'V'); /* strc= Vn, stre is n; strb=V3*V2 stre=3 strc=*/
                   9764:            Tvar[k]=ncovcol+nqv+ntv+nqtv+k1; /* For model-covariate k tells which data-covariate to use but
                   9765:                                                because this model-covariate is a construction we invent a new column
                   9766:                                                which is after existing variables ncovcol+nqv+ntv+nqtv + k1
                   9767:                                                If already ncovcol=4 and model=V2+V1+V1*V4+age*V3+V3*V2
                   9768:                                                Tvar[3=V1*V4]=4+1 Tvar[5=V3*V2]=4 + 2= 6, etc */
                   9769:            Typevar[k]=2;  /* 2 for double fixed dummy covariates */
                   9770:            cutl(strc,strb,strd,'V'); /* strd was Vm, strc is m */
                   9771:            Tprod[k1]=k;  /* Tprod[1]=3(=V1*V4) for V2+V1+V1*V4+age*V3+V3*V2  */
                   9772:            Tposprod[k]=k1; /* Tpsprod[3]=1, Tposprod[2]=5 */
                   9773:            Tvard[k1][1] =atoi(strc); /* m 1 for V1*/
                   9774:            Tvard[k1][2] =atoi(stre); /* n 4 for V4*/
                   9775:            k2=k2+2;  /* k2 is initialize to -1, We want to store the n and m in Vn*Vm at the end of Tvar */
                   9776:            /* Tvar[cptcovt+k2]=Tvard[k1][1]; /\* Tvar[(cptcovt=4+k2=1)=5]= 1 (V1) *\/ */
                   9777:            /* Tvar[cptcovt+k2+1]=Tvard[k1][2];  /\* Tvar[(cptcovt=4+(k2=1)+1)=6]= 4 (V4) *\/ */
1.225     brouard  9778:             /*ncovcol=4 and model=V2+V1+V1*V4+age*V3+V3*V2, Tvar[3]=5, Tvar[4]=6, cptcovt=5 */
1.234     brouard  9779:            /*                     1  2   3      4     5 | Tvar[5+1)=1, Tvar[7]=2   */
                   9780:            for (i=1; i<=lastobs;i++){
                   9781:              /* Computes the new covariate which is a product of
                   9782:                 covar[n][i]* covar[m][i] and stores it at ncovol+k1 May not be defined */
                   9783:              covar[ncovcol+k1][i]=covar[atoi(stre)][i]*covar[atoi(strc)][i];
                   9784:            }
                   9785:          } /* End age is not in the model */
                   9786:        } /* End if model includes a product */
                   9787:        else { /* no more sum */
                   9788:          /*printf("d=%s c=%s b=%s\n", strd,strc,strb);*/
                   9789:          /*  scanf("%d",i);*/
                   9790:          cutl(strd,strc,strb,'V');
                   9791:          ks++; /**< Number of simple covariates dummy or quantitative, fixe or varying */
                   9792:          cptcovn++; /** V4+V3+V5: V4 and V3 timevarying dummy covariates, V5 timevarying quantitative */
                   9793:          Tvar[k]=atoi(strd);
                   9794:          Typevar[k]=0;  /* 0 for simple covariates */
                   9795:        }
                   9796:        strcpy(modelsav,stra);  /* modelsav=V2+V1+V4 stra=V2+V1+V4 */ 
1.223     brouard  9797:                                /*printf("a=%s b=%s sav=%s\n", stra,strb,modelsav);
1.225     brouard  9798:                                  scanf("%d",i);*/
1.187     brouard  9799:       } /* end of loop + on total covariates */
                   9800:     } /* end if strlen(modelsave == 0) age*age might exist */
                   9801:   } /* end if strlen(model == 0) */
1.136     brouard  9802:   
                   9803:   /*The number n of Vn is stored in Tvar. cptcovage =number of age covariate. Tage gives the position of age. cptcovprod= number of products.
                   9804:     If model=V1+V1*age then Tvar[1]=1 Tvar[2]=1 cptcovage=1 Tage[1]=2 cptcovprod=0*/
1.225     brouard  9805:   
1.136     brouard  9806:   /* printf("tvar1=%d tvar2=%d tvar3=%d cptcovage=%d Tage=%d",Tvar[1],Tvar[2],Tvar[3],cptcovage,Tage[1]);
1.225     brouard  9807:      printf("cptcovprod=%d ", cptcovprod);
                   9808:      fprintf(ficlog,"cptcovprod=%d ", cptcovprod);
                   9809:      scanf("%d ",i);*/
                   9810: 
                   9811: 
1.230     brouard  9812: /* Until here, decodemodel knows only the grammar (simple, product, age*) of the model but not what kind
                   9813:    of variable (dummy vs quantitative, fixed vs time varying) is behind. But we know the # of each. */
1.226     brouard  9814: /* ncovcol= 1, nqv=1 | ntv=2, nqtv= 1  = 5 possible variables data: 2 fixed 3, varying
                   9815:    model=        V5 + V4 +V3 + V4*V3 + V5*age + V2 + V1*V2 + V1*age + V5*age, V1 is not used saving its place
                   9816:    k =           1    2   3     4       5       6      7      8        9
                   9817:    Tvar[k]=      5    4   3 1+1+2+1+1=6 5       2      7      1        5
                   9818:    Typevar[k]=   0    0   0     2       1       0      2      1        1
1.227     brouard  9819:    Fixed[k]      1    1   1     1       3       0    0 or 2   2        3
                   9820:    Dummy[k]      1    0   0     0       3       1      1      2        3
                   9821:          Tmodelind[combination of covar]=k;
1.225     brouard  9822: */  
                   9823: /* Dispatching between quantitative and time varying covariates */
1.226     brouard  9824:   /* If Tvar[k] >ncovcol it is a product */
1.225     brouard  9825:   /* 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  9826:        /* Computing effective variables, ie used by the model, that is from the cptcovt variables */
1.227     brouard  9827:   printf("Model=%s\n\
                   9828: Typevar: 0 for simple covariate (dummy, quantitative, fixed or varying), 1 for age product, 2 for  product \n\
                   9829: Fixed[k] 0=fixed (product or simple), 1 varying, 2 fixed with age product, 3 varying with age product \n\
                   9830: 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);
                   9831:   fprintf(ficlog,"Model=%s\n\
                   9832: Typevar: 0 for simple covariate (dummy, quantitative, fixed or varying), 1 for age product, 2 for  product \n\
                   9833: Fixed[k] 0=fixed (product or simple), 1 varying, 2 fixed with age product, 3 varying with age product \n\
                   9834: 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  9835:   for(k=-1;k<=cptcovt; k++){ Fixed[k]=0; Dummy[k]=0;}
1.234     brouard  9836:   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 */
                   9837:     if (Tvar[k] <=ncovcol && Typevar[k]==0 ){ /* Simple fixed dummy (<=ncovcol) covariates */
1.227     brouard  9838:       Fixed[k]= 0;
                   9839:       Dummy[k]= 0;
1.225     brouard  9840:       ncoveff++;
1.232     brouard  9841:       ncovf++;
1.234     brouard  9842:       nsd++;
                   9843:       modell[k].maintype= FTYPE;
                   9844:       TvarsD[nsd]=Tvar[k];
                   9845:       TvarsDind[nsd]=k;
                   9846:       TvarF[ncovf]=Tvar[k];
                   9847:       TvarFind[ncovf]=k;
                   9848:       TvarFD[ncoveff]=Tvar[k]; /* TvarFD[1]=V1 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
                   9849:       TvarFDind[ncoveff]=k; /* TvarFDind[1]=9 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
                   9850:     }else if( Tvar[k] <=ncovcol &&  Typevar[k]==2){ /* Product of fixed dummy (<=ncovcol) covariates */
                   9851:       Fixed[k]= 0;
                   9852:       Dummy[k]= 0;
                   9853:       ncoveff++;
                   9854:       ncovf++;
                   9855:       modell[k].maintype= FTYPE;
                   9856:       TvarF[ncovf]=Tvar[k];
                   9857:       TvarFind[ncovf]=k;
1.230     brouard  9858:       TvarFD[ncoveff]=Tvar[k]; /* TvarFD[1]=V1 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
1.231     brouard  9859:       TvarFDind[ncoveff]=k; /* TvarFDind[1]=9 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
1.240     brouard  9860:     }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  9861:       Fixed[k]= 0;
                   9862:       Dummy[k]= 1;
1.230     brouard  9863:       nqfveff++;
1.234     brouard  9864:       modell[k].maintype= FTYPE;
                   9865:       modell[k].subtype= FQ;
                   9866:       nsq++;
                   9867:       TvarsQ[nsq]=Tvar[k];
                   9868:       TvarsQind[nsq]=k;
1.232     brouard  9869:       ncovf++;
1.234     brouard  9870:       TvarF[ncovf]=Tvar[k];
                   9871:       TvarFind[ncovf]=k;
1.231     brouard  9872:       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  9873:       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  9874:     }else if( Tvar[k] <=ncovcol+nqv+ntv && Typevar[k]==0){/* Only simple time varying dummy variables */
1.227     brouard  9875:       Fixed[k]= 1;
                   9876:       Dummy[k]= 0;
1.225     brouard  9877:       ntveff++; /* Only simple time varying dummy variable */
1.234     brouard  9878:       modell[k].maintype= VTYPE;
                   9879:       modell[k].subtype= VD;
                   9880:       nsd++;
                   9881:       TvarsD[nsd]=Tvar[k];
                   9882:       TvarsDind[nsd]=k;
                   9883:       ncovv++; /* Only simple time varying variables */
                   9884:       TvarV[ncovv]=Tvar[k];
1.242     brouard  9885:       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  9886:       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 */
                   9887:       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  9888:       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);
                   9889:       printf("Quasi TmodelInvind[%d]=%d\n",k,Tvar[k]- ncovcol-nqv);
1.231     brouard  9890:     }else if( Tvar[k] <=ncovcol+nqv+ntv+nqtv  && Typevar[k]==0){ /* Only simple time varying quantitative variable V5*/
1.234     brouard  9891:       Fixed[k]= 1;
                   9892:       Dummy[k]= 1;
                   9893:       nqtveff++;
                   9894:       modell[k].maintype= VTYPE;
                   9895:       modell[k].subtype= VQ;
                   9896:       ncovv++; /* Only simple time varying variables */
                   9897:       nsq++;
                   9898:       TvarsQ[nsq]=Tvar[k];
                   9899:       TvarsQind[nsq]=k;
                   9900:       TvarV[ncovv]=Tvar[k];
1.242     brouard  9901:       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  9902:       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 */
                   9903:       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  9904:       TmodelInvQind[nqtveff]=Tvar[k]- ncovcol-nqv-ntv;/* Only simple time varying quantitative variable */
                   9905:       /* Tmodeliqind[k]=nqtveff;/\* Only simple time varying quantitative variable *\/ */
                   9906:       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  9907:       printf("Quasi TmodelInvQind[%d]=%d\n",k,Tvar[k]- ncovcol-nqv-ntv);
1.227     brouard  9908:     }else if (Typevar[k] == 1) {  /* product with age */
1.234     brouard  9909:       ncova++;
                   9910:       TvarA[ncova]=Tvar[k];
                   9911:       TvarAind[ncova]=k;
1.231     brouard  9912:       if (Tvar[k] <=ncovcol ){ /* Product age with fixed dummy covariatee */
1.240     brouard  9913:        Fixed[k]= 2;
                   9914:        Dummy[k]= 2;
                   9915:        modell[k].maintype= ATYPE;
                   9916:        modell[k].subtype= APFD;
                   9917:        /* ncoveff++; */
1.227     brouard  9918:       }else if( Tvar[k] <=ncovcol+nqv) { /* Remind that product Vn*Vm are added in k*/
1.240     brouard  9919:        Fixed[k]= 2;
                   9920:        Dummy[k]= 3;
                   9921:        modell[k].maintype= ATYPE;
                   9922:        modell[k].subtype= APFQ;                /*      Product age * fixed quantitative */
                   9923:        /* nqfveff++;  /\* Only simple fixed quantitative variable *\/ */
1.227     brouard  9924:       }else if( Tvar[k] <=ncovcol+nqv+ntv ){
1.240     brouard  9925:        Fixed[k]= 3;
                   9926:        Dummy[k]= 2;
                   9927:        modell[k].maintype= ATYPE;
                   9928:        modell[k].subtype= APVD;                /*      Product age * varying dummy */
                   9929:        /* ntveff++; /\* Only simple time varying dummy variable *\/ */
1.227     brouard  9930:       }else if( Tvar[k] <=ncovcol+nqv+ntv+nqtv){
1.240     brouard  9931:        Fixed[k]= 3;
                   9932:        Dummy[k]= 3;
                   9933:        modell[k].maintype= ATYPE;
                   9934:        modell[k].subtype= APVQ;                /*      Product age * varying quantitative */
                   9935:        /* nqtveff++;/\* Only simple time varying quantitative variable *\/ */
1.227     brouard  9936:       }
                   9937:     }else if (Typevar[k] == 2) {  /* product without age */
                   9938:       k1=Tposprod[k];
                   9939:       if(Tvard[k1][1] <=ncovcol){
1.240     brouard  9940:        if(Tvard[k1][2] <=ncovcol){
                   9941:          Fixed[k]= 1;
                   9942:          Dummy[k]= 0;
                   9943:          modell[k].maintype= FTYPE;
                   9944:          modell[k].subtype= FPDD;              /*      Product fixed dummy * fixed dummy */
                   9945:          ncovf++; /* Fixed variables without age */
                   9946:          TvarF[ncovf]=Tvar[k];
                   9947:          TvarFind[ncovf]=k;
                   9948:        }else if(Tvard[k1][2] <=ncovcol+nqv){
                   9949:          Fixed[k]= 0;  /* or 2 ?*/
                   9950:          Dummy[k]= 1;
                   9951:          modell[k].maintype= FTYPE;
                   9952:          modell[k].subtype= FPDQ;              /*      Product fixed dummy * fixed quantitative */
                   9953:          ncovf++; /* Varying variables without age */
                   9954:          TvarF[ncovf]=Tvar[k];
                   9955:          TvarFind[ncovf]=k;
                   9956:        }else if(Tvard[k1][2] <=ncovcol+nqv+ntv){
                   9957:          Fixed[k]= 1;
                   9958:          Dummy[k]= 0;
                   9959:          modell[k].maintype= VTYPE;
                   9960:          modell[k].subtype= VPDD;              /*      Product fixed dummy * varying dummy */
                   9961:          ncovv++; /* Varying variables without age */
                   9962:          TvarV[ncovv]=Tvar[k];
                   9963:          TvarVind[ncovv]=k;
                   9964:        }else if(Tvard[k1][2] <=ncovcol+nqv+ntv+nqtv){
                   9965:          Fixed[k]= 1;
                   9966:          Dummy[k]= 1;
                   9967:          modell[k].maintype= VTYPE;
                   9968:          modell[k].subtype= VPDQ;              /*      Product fixed dummy * varying quantitative */
                   9969:          ncovv++; /* Varying variables without age */
                   9970:          TvarV[ncovv]=Tvar[k];
                   9971:          TvarVind[ncovv]=k;
                   9972:        }
1.227     brouard  9973:       }else if(Tvard[k1][1] <=ncovcol+nqv){
1.240     brouard  9974:        if(Tvard[k1][2] <=ncovcol){
                   9975:          Fixed[k]= 0;  /* or 2 ?*/
                   9976:          Dummy[k]= 1;
                   9977:          modell[k].maintype= FTYPE;
                   9978:          modell[k].subtype= FPDQ;              /*      Product fixed quantitative * fixed dummy */
                   9979:          ncovf++; /* Fixed variables without age */
                   9980:          TvarF[ncovf]=Tvar[k];
                   9981:          TvarFind[ncovf]=k;
                   9982:        }else if(Tvard[k1][2] <=ncovcol+nqv+ntv){
                   9983:          Fixed[k]= 1;
                   9984:          Dummy[k]= 1;
                   9985:          modell[k].maintype= VTYPE;
                   9986:          modell[k].subtype= VPDQ;              /*      Product fixed quantitative * varying dummy */
                   9987:          ncovv++; /* Varying variables without age */
                   9988:          TvarV[ncovv]=Tvar[k];
                   9989:          TvarVind[ncovv]=k;
                   9990:        }else if(Tvard[k1][2] <=ncovcol+nqv+ntv+nqtv){
                   9991:          Fixed[k]= 1;
                   9992:          Dummy[k]= 1;
                   9993:          modell[k].maintype= VTYPE;
                   9994:          modell[k].subtype= VPQQ;              /*      Product fixed quantitative * varying quantitative */
                   9995:          ncovv++; /* Varying variables without age */
                   9996:          TvarV[ncovv]=Tvar[k];
                   9997:          TvarVind[ncovv]=k;
                   9998:          ncovv++; /* Varying variables without age */
                   9999:          TvarV[ncovv]=Tvar[k];
                   10000:          TvarVind[ncovv]=k;
                   10001:        }
1.227     brouard  10002:       }else if(Tvard[k1][1] <=ncovcol+nqv+ntv){
1.240     brouard  10003:        if(Tvard[k1][2] <=ncovcol){
                   10004:          Fixed[k]= 1;
                   10005:          Dummy[k]= 1;
                   10006:          modell[k].maintype= VTYPE;
                   10007:          modell[k].subtype= VPDD;              /*      Product time varying dummy * fixed dummy */
                   10008:          ncovv++; /* Varying variables without age */
                   10009:          TvarV[ncovv]=Tvar[k];
                   10010:          TvarVind[ncovv]=k;
                   10011:        }else if(Tvard[k1][2] <=ncovcol+nqv){
                   10012:          Fixed[k]= 1;
                   10013:          Dummy[k]= 1;
                   10014:          modell[k].maintype= VTYPE;
                   10015:          modell[k].subtype= VPDQ;              /*      Product time varying dummy * fixed quantitative */
                   10016:          ncovv++; /* Varying variables without age */
                   10017:          TvarV[ncovv]=Tvar[k];
                   10018:          TvarVind[ncovv]=k;
                   10019:        }else if(Tvard[k1][2] <=ncovcol+nqv+ntv){
                   10020:          Fixed[k]= 1;
                   10021:          Dummy[k]= 0;
                   10022:          modell[k].maintype= VTYPE;
                   10023:          modell[k].subtype= VPDD;              /*      Product time varying dummy * time varying dummy */
                   10024:          ncovv++; /* Varying variables without age */
                   10025:          TvarV[ncovv]=Tvar[k];
                   10026:          TvarVind[ncovv]=k;
                   10027:        }else if(Tvard[k1][2] <=ncovcol+nqv+ntv+nqtv){
                   10028:          Fixed[k]= 1;
                   10029:          Dummy[k]= 1;
                   10030:          modell[k].maintype= VTYPE;
                   10031:          modell[k].subtype= VPDQ;              /*      Product time varying dummy * time varying quantitative */
                   10032:          ncovv++; /* Varying variables without age */
                   10033:          TvarV[ncovv]=Tvar[k];
                   10034:          TvarVind[ncovv]=k;
                   10035:        }
1.227     brouard  10036:       }else if(Tvard[k1][1] <=ncovcol+nqv+ntv+nqtv){
1.240     brouard  10037:        if(Tvard[k1][2] <=ncovcol){
                   10038:          Fixed[k]= 1;
                   10039:          Dummy[k]= 1;
                   10040:          modell[k].maintype= VTYPE;
                   10041:          modell[k].subtype= VPDQ;              /*      Product time varying quantitative * fixed dummy */
                   10042:          ncovv++; /* Varying variables without age */
                   10043:          TvarV[ncovv]=Tvar[k];
                   10044:          TvarVind[ncovv]=k;
                   10045:        }else if(Tvard[k1][2] <=ncovcol+nqv){
                   10046:          Fixed[k]= 1;
                   10047:          Dummy[k]= 1;
                   10048:          modell[k].maintype= VTYPE;
                   10049:          modell[k].subtype= VPQQ;              /*      Product time varying quantitative * fixed quantitative */
                   10050:          ncovv++; /* Varying variables without age */
                   10051:          TvarV[ncovv]=Tvar[k];
                   10052:          TvarVind[ncovv]=k;
                   10053:        }else if(Tvard[k1][2] <=ncovcol+nqv+ntv){
                   10054:          Fixed[k]= 1;
                   10055:          Dummy[k]= 1;
                   10056:          modell[k].maintype= VTYPE;
                   10057:          modell[k].subtype= VPDQ;              /*      Product time varying quantitative * time varying dummy */
                   10058:          ncovv++; /* Varying variables without age */
                   10059:          TvarV[ncovv]=Tvar[k];
                   10060:          TvarVind[ncovv]=k;
                   10061:        }else if(Tvard[k1][2] <=ncovcol+nqv+ntv+nqtv){
                   10062:          Fixed[k]= 1;
                   10063:          Dummy[k]= 1;
                   10064:          modell[k].maintype= VTYPE;
                   10065:          modell[k].subtype= VPQQ;              /*      Product time varying quantitative * time varying quantitative */
                   10066:          ncovv++; /* Varying variables without age */
                   10067:          TvarV[ncovv]=Tvar[k];
                   10068:          TvarVind[ncovv]=k;
                   10069:        }
1.227     brouard  10070:       }else{
1.240     brouard  10071:        printf("Error unknown type of covariate: Tvard[%d][1]=%d,Tvard[%d][2]=%d\n",k1,Tvard[k1][1],k1,Tvard[k1][2]);
                   10072:        fprintf(ficlog,"Error unknown type of covariate: Tvard[%d][1]=%d,Tvard[%d][2]=%d\n",k1,Tvard[k1][1],k1,Tvard[k1][2]);
                   10073:       } /*end k1*/
1.225     brouard  10074:     }else{
1.226     brouard  10075:       printf("Error, current version can't treat for performance reasons, Tvar[%d]=%d, Typevar[%d]=%d\n", k, Tvar[k], k, Typevar[k]);
                   10076:       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  10077:     }
1.227     brouard  10078:     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  10079:     printf("           modell[%d].maintype=%d, modell[%d].subtype=%d\n",k,modell[k].maintype,k,modell[k].subtype);
1.227     brouard  10080:     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]);
                   10081:   }
                   10082:   /* Searching for doublons in the model */
                   10083:   for(k1=1; k1<= cptcovt;k1++){
                   10084:     for(k2=1; k2 <k1;k2++){
1.285     brouard  10085:       /* if((Typevar[k1]==Typevar[k2]) && (Fixed[Tvar[k1]]==Fixed[Tvar[k2]]) && (Dummy[Tvar[k1]]==Dummy[Tvar[k2]] )){ */
                   10086:       if((Typevar[k1]==Typevar[k2]) && (Fixed[k1]==Fixed[k2]) && (Dummy[k1]==Dummy[k2] )){
1.234     brouard  10087:        if((Typevar[k1] == 0 || Typevar[k1] == 1)){ /* Simple or age product */
                   10088:          if(Tvar[k1]==Tvar[k2]){
1.285     brouard  10089:            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]);
                   10090:            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  10091:            return(1);
                   10092:          }
                   10093:        }else if (Typevar[k1] ==2){
                   10094:          k3=Tposprod[k1];
                   10095:          k4=Tposprod[k2];
                   10096:          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])) ){
                   10097:            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]]);
                   10098:            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);
                   10099:            return(1);
                   10100:          }
                   10101:        }
1.227     brouard  10102:       }
                   10103:     }
1.225     brouard  10104:   }
                   10105:   printf("ncoveff=%d, nqfveff=%d, ntveff=%d, nqtveff=%d, cptcovn=%d\n",ncoveff,nqfveff,ntveff,nqtveff,cptcovn);
                   10106:   fprintf(ficlog,"ncoveff=%d, nqfveff=%d, ntveff=%d, nqtveff=%d, cptcovn=%d\n",ncoveff,nqfveff,ntveff,nqtveff,cptcovn);
1.234     brouard  10107:   printf("ncovf=%d, ncovv=%d, ncova=%d, nsd=%d, nsq=%d\n",ncovf,ncovv,ncova,nsd,nsq);
                   10108:   fprintf(ficlog,"ncovf=%d, ncovv=%d, ncova=%d, nsd=%d, nsq=%d\n",ncovf,ncovv,ncova,nsd, nsq);
1.137     brouard  10109:   return (0); /* with covar[new additional covariate if product] and Tage if age */ 
1.164     brouard  10110:   /*endread:*/
1.225     brouard  10111:   printf("Exiting decodemodel: ");
                   10112:   return (1);
1.136     brouard  10113: }
                   10114: 
1.169     brouard  10115: int calandcheckages(int imx, int maxwav, double *agemin, double *agemax, int *nberr, int *nbwarn )
1.248     brouard  10116: {/* Check ages at death */
1.136     brouard  10117:   int i, m;
1.218     brouard  10118:   int firstone=0;
                   10119:   
1.136     brouard  10120:   for (i=1; i<=imx; i++) {
                   10121:     for(m=2; (m<= maxwav); m++) {
                   10122:       if (((int)mint[m][i]== 99) && (s[m][i] <= nlstate)){
                   10123:        anint[m][i]=9999;
1.216     brouard  10124:        if (s[m][i] != -2) /* Keeping initial status of unknown vital status */
                   10125:          s[m][i]=-1;
1.136     brouard  10126:       }
                   10127:       if((int)moisdc[i]==99 && (int)andc[i]==9999 && s[m][i]>nlstate){
1.260     brouard  10128:        *nberr = *nberr + 1;
1.218     brouard  10129:        if(firstone == 0){
                   10130:          firstone=1;
1.260     brouard  10131:        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  10132:        }
1.262     brouard  10133:        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  10134:        s[m][i]=-1;  /* Droping the death status */
1.136     brouard  10135:       }
                   10136:       if((int)moisdc[i]==99 && (int)andc[i]!=9999 && s[m][i]>nlstate){
1.169     brouard  10137:        (*nberr)++;
1.259     brouard  10138:        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  10139:        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  10140:        s[m][i]=-2; /* We prefer to skip it (and to skip it in version 0.8a1 too */
1.136     brouard  10141:       }
                   10142:     }
                   10143:   }
                   10144: 
                   10145:   for (i=1; i<=imx; i++)  {
                   10146:     agedc[i]=(moisdc[i]/12.+andc[i])-(moisnais[i]/12.+annais[i]);
                   10147:     for(m=firstpass; (m<= lastpass); m++){
1.214     brouard  10148:       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  10149:        if (s[m][i] >= nlstate+1) {
1.169     brouard  10150:          if(agedc[i]>0){
                   10151:            if((int)moisdc[i]!=99 && (int)andc[i]!=9999){
1.136     brouard  10152:              agev[m][i]=agedc[i];
1.214     brouard  10153:              /*if(moisdc[i]==99 && andc[i]==9999) s[m][i]=-1;*/
1.169     brouard  10154:            }else {
1.136     brouard  10155:              if ((int)andc[i]!=9999){
                   10156:                nbwarn++;
                   10157:                printf("Warning negative age at death: %ld line:%d\n",num[i],i);
                   10158:                fprintf(ficlog,"Warning negative age at death: %ld line:%d\n",num[i],i);
                   10159:                agev[m][i]=-1;
                   10160:              }
                   10161:            }
1.169     brouard  10162:          } /* agedc > 0 */
1.214     brouard  10163:        } /* end if */
1.136     brouard  10164:        else if(s[m][i] !=9){ /* Standard case, age in fractional
                   10165:                                 years but with the precision of a month */
                   10166:          agev[m][i]=(mint[m][i]/12.+1./24.+anint[m][i])-(moisnais[i]/12.+1./24.+annais[i]);
                   10167:          if((int)mint[m][i]==99 || (int)anint[m][i]==9999)
                   10168:            agev[m][i]=1;
                   10169:          else if(agev[m][i] < *agemin){ 
                   10170:            *agemin=agev[m][i];
                   10171:            printf(" Min anint[%d][%d]=%.2f annais[%d]=%.2f, agemin=%.2f\n",m,i,anint[m][i], i,annais[i], *agemin);
                   10172:          }
                   10173:          else if(agev[m][i] >*agemax){
                   10174:            *agemax=agev[m][i];
1.156     brouard  10175:            /* printf(" Max anint[%d][%d]=%.0f annais[%d]=%.0f, agemax=%.2f\n",m,i,anint[m][i], i,annais[i], *agemax);*/
1.136     brouard  10176:          }
                   10177:          /*agev[m][i]=anint[m][i]-annais[i];*/
                   10178:          /*     agev[m][i] = age[i]+2*m;*/
1.214     brouard  10179:        } /* en if 9*/
1.136     brouard  10180:        else { /* =9 */
1.214     brouard  10181:          /* printf("Debug num[%d]=%ld s[%d][%d]=%d\n",i,num[i], m,i, s[m][i]); */
1.136     brouard  10182:          agev[m][i]=1;
                   10183:          s[m][i]=-1;
                   10184:        }
                   10185:       }
1.214     brouard  10186:       else if(s[m][i]==0) /*= 0 Unknown */
1.136     brouard  10187:        agev[m][i]=1;
1.214     brouard  10188:       else{
                   10189:        printf("Warning, num[%d]=%ld, s[%d][%d]=%d\n", i, num[i], m, i,s[m][i]); 
                   10190:        fprintf(ficlog, "Warning, num[%d]=%ld, s[%d][%d]=%d\n", i, num[i], m, i,s[m][i]); 
                   10191:        agev[m][i]=0;
                   10192:       }
                   10193:     } /* End for lastpass */
                   10194:   }
1.136     brouard  10195:     
                   10196:   for (i=1; i<=imx; i++)  {
                   10197:     for(m=firstpass; (m<=lastpass); m++){
                   10198:       if (s[m][i] > (nlstate+ndeath)) {
1.169     brouard  10199:        (*nberr)++;
1.136     brouard  10200:        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);     
                   10201:        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);     
                   10202:        return 1;
                   10203:       }
                   10204:     }
                   10205:   }
                   10206: 
                   10207:   /*for (i=1; i<=imx; i++){
                   10208:   for (m=firstpass; (m<lastpass); m++){
                   10209:      printf("%ld %d %.lf %d %d\n", num[i],(covar[1][i]),agev[m][i],s[m][i],s[m+1][i]);
                   10210: }
                   10211: 
                   10212: }*/
                   10213: 
                   10214: 
1.139     brouard  10215:   printf("Total number of individuals= %d, Agemin = %.2f, Agemax= %.2f\n\n", imx, *agemin, *agemax);
                   10216:   fprintf(ficlog,"Total number of individuals= %d, Agemin = %.2f, Agemax= %.2f\n\n", imx, *agemin, *agemax); 
1.136     brouard  10217: 
                   10218:   return (0);
1.164     brouard  10219:  /* endread:*/
1.136     brouard  10220:     printf("Exiting calandcheckages: ");
                   10221:     return (1);
                   10222: }
                   10223: 
1.172     brouard  10224: #if defined(_MSC_VER)
                   10225: /*printf("Visual C++ compiler: %s \n;", _MSC_FULL_VER);*/
                   10226: /*fprintf(ficlog, "Visual C++ compiler: %s \n;", _MSC_FULL_VER);*/
                   10227: //#include "stdafx.h"
                   10228: //#include <stdio.h>
                   10229: //#include <tchar.h>
                   10230: //#include <windows.h>
                   10231: //#include <iostream>
                   10232: typedef BOOL(WINAPI *LPFN_ISWOW64PROCESS) (HANDLE, PBOOL);
                   10233: 
                   10234: LPFN_ISWOW64PROCESS fnIsWow64Process;
                   10235: 
                   10236: BOOL IsWow64()
                   10237: {
                   10238:        BOOL bIsWow64 = FALSE;
                   10239: 
                   10240:        //typedef BOOL (APIENTRY *LPFN_ISWOW64PROCESS)
                   10241:        //  (HANDLE, PBOOL);
                   10242: 
                   10243:        //LPFN_ISWOW64PROCESS fnIsWow64Process;
                   10244: 
                   10245:        HMODULE module = GetModuleHandle(_T("kernel32"));
                   10246:        const char funcName[] = "IsWow64Process";
                   10247:        fnIsWow64Process = (LPFN_ISWOW64PROCESS)
                   10248:                GetProcAddress(module, funcName);
                   10249: 
                   10250:        if (NULL != fnIsWow64Process)
                   10251:        {
                   10252:                if (!fnIsWow64Process(GetCurrentProcess(),
                   10253:                        &bIsWow64))
                   10254:                        //throw std::exception("Unknown error");
                   10255:                        printf("Unknown error\n");
                   10256:        }
                   10257:        return bIsWow64 != FALSE;
                   10258: }
                   10259: #endif
1.177     brouard  10260: 
1.191     brouard  10261: void syscompilerinfo(int logged)
1.292     brouard  10262: {
                   10263: #include <stdint.h>
                   10264: 
                   10265:   /* #include "syscompilerinfo.h"*/
1.185     brouard  10266:    /* command line Intel compiler 32bit windows, XP compatible:*/
                   10267:    /* /GS /W3 /Gy
                   10268:       /Zc:wchar_t /Zi /O2 /Fd"Release\vc120.pdb" /D "WIN32" /D "NDEBUG" /D
                   10269:       "_CONSOLE" /D "_LIB" /D "_USING_V110_SDK71_" /D "_UNICODE" /D
                   10270:       "UNICODE" /Qipo /Zc:forScope /Gd /Oi /MT /Fa"Release\" /EHsc /nologo
1.186     brouard  10271:       /Fo"Release\" /Qprof-dir "Release\" /Fp"Release\IMaCh.pch"
                   10272:    */ 
                   10273:    /* 64 bits */
1.185     brouard  10274:    /*
                   10275:      /GS /W3 /Gy
                   10276:      /Zc:wchar_t /Zi /O2 /Fd"x64\Release\vc120.pdb" /D "WIN32" /D "NDEBUG"
                   10277:      /D "_CONSOLE" /D "_LIB" /D "_UNICODE" /D "UNICODE" /Qipo /Zc:forScope
                   10278:      /Oi /MD /Fa"x64\Release\" /EHsc /nologo /Fo"x64\Release\" /Qprof-dir
                   10279:      "x64\Release\" /Fp"x64\Release\IMaCh.pch" */
                   10280:    /* Optimization are useless and O3 is slower than O2 */
                   10281:    /*
                   10282:      /GS /W3 /Gy /Zc:wchar_t /Zi /O3 /Fd"x64\Release\vc120.pdb" /D "WIN32" 
                   10283:      /D "NDEBUG" /D "_CONSOLE" /D "_LIB" /D "_UNICODE" /D "UNICODE" /Qipo 
                   10284:      /Zc:forScope /Oi /MD /Fa"x64\Release\" /EHsc /nologo /Qparallel 
                   10285:      /Fo"x64\Release\" /Qprof-dir "x64\Release\" /Fp"x64\Release\IMaCh.pch" 
                   10286:    */
1.186     brouard  10287:    /* Link is */ /* /OUT:"visual studio
1.185     brouard  10288:       2013\Projects\IMaCh\Release\IMaCh.exe" /MANIFEST /NXCOMPAT
                   10289:       /PDB:"visual studio
                   10290:       2013\Projects\IMaCh\Release\IMaCh.pdb" /DYNAMICBASE
                   10291:       "kernel32.lib" "user32.lib" "gdi32.lib" "winspool.lib"
                   10292:       "comdlg32.lib" "advapi32.lib" "shell32.lib" "ole32.lib"
                   10293:       "oleaut32.lib" "uuid.lib" "odbc32.lib" "odbccp32.lib"
                   10294:       /MACHINE:X86 /OPT:REF /SAFESEH /INCREMENTAL:NO
                   10295:       /SUBSYSTEM:CONSOLE",5.01" /MANIFESTUAC:"level='asInvoker'
                   10296:       uiAccess='false'"
                   10297:       /ManifestFile:"Release\IMaCh.exe.intermediate.manifest" /OPT:ICF
                   10298:       /NOLOGO /TLBID:1
                   10299:    */
1.292     brouard  10300: 
                   10301: 
1.177     brouard  10302: #if defined __INTEL_COMPILER
1.178     brouard  10303: #if defined(__GNUC__)
                   10304:        struct utsname sysInfo;  /* For Intel on Linux and OS/X */
                   10305: #endif
1.177     brouard  10306: #elif defined(__GNUC__) 
1.179     brouard  10307: #ifndef  __APPLE__
1.174     brouard  10308: #include <gnu/libc-version.h>  /* Only on gnu */
1.179     brouard  10309: #endif
1.177     brouard  10310:    struct utsname sysInfo;
1.178     brouard  10311:    int cross = CROSS;
                   10312:    if (cross){
                   10313:           printf("Cross-");
1.191     brouard  10314:           if(logged) fprintf(ficlog, "Cross-");
1.178     brouard  10315:    }
1.174     brouard  10316: #endif
                   10317: 
1.191     brouard  10318:    printf("Compiled with:");if(logged)fprintf(ficlog,"Compiled with:");
1.169     brouard  10319: #if defined(__clang__)
1.191     brouard  10320:    printf(" Clang/LLVM");if(logged)fprintf(ficlog," Clang/LLVM");      /* Clang/LLVM. ---------------------------------------------- */
1.169     brouard  10321: #endif
                   10322: #if defined(__ICC) || defined(__INTEL_COMPILER)
1.191     brouard  10323:    printf(" Intel ICC/ICPC");if(logged)fprintf(ficlog," Intel ICC/ICPC");/* Intel ICC/ICPC. ------------------------------------------ */
1.169     brouard  10324: #endif
                   10325: #if defined(__GNUC__) || defined(__GNUG__)
1.191     brouard  10326:    printf(" GNU GCC/G++");if(logged)fprintf(ficlog," GNU GCC/G++");/* GNU GCC/G++. --------------------------------------------- */
1.169     brouard  10327: #endif
                   10328: #if defined(__HP_cc) || defined(__HP_aCC)
1.191     brouard  10329:    printf(" Hewlett-Packard C/aC++");if(logged)fprintf(fcilog," Hewlett-Packard C/aC++"); /* Hewlett-Packard C/aC++. ---------------------------------- */
1.169     brouard  10330: #endif
                   10331: #if defined(__IBMC__) || defined(__IBMCPP__)
1.191     brouard  10332:    printf(" IBM XL C/C++"); if(logged) fprintf(ficlog," IBM XL C/C++");/* IBM XL C/C++. -------------------------------------------- */
1.169     brouard  10333: #endif
                   10334: #if defined(_MSC_VER)
1.191     brouard  10335:    printf(" Microsoft Visual Studio");if(logged)fprintf(ficlog," Microsoft Visual Studio");/* Microsoft Visual Studio. --------------------------------- */
1.169     brouard  10336: #endif
                   10337: #if defined(__PGI)
1.191     brouard  10338:    printf(" Portland Group PGCC/PGCPP");if(logged) fprintf(ficlog," Portland Group PGCC/PGCPP");/* Portland Group PGCC/PGCPP. ------------------------------- */
1.169     brouard  10339: #endif
                   10340: #if defined(__SUNPRO_C) || defined(__SUNPRO_CC)
1.191     brouard  10341:    printf(" Oracle Solaris Studio");if(logged)fprintf(ficlog," Oracle Solaris Studio\n");/* Oracle Solaris Studio. ----------------------------------- */
1.167     brouard  10342: #endif
1.191     brouard  10343:    printf(" for "); if (logged) fprintf(ficlog, " for ");
1.169     brouard  10344:    
1.167     brouard  10345: // http://stackoverflow.com/questions/4605842/how-to-identify-platform-compiler-from-preprocessor-macros
                   10346: #ifdef _WIN32 // note the underscore: without it, it's not msdn official!
                   10347:     // Windows (x64 and x86)
1.191     brouard  10348:    printf("Windows (x64 and x86) ");if(logged) fprintf(ficlog,"Windows (x64 and x86) ");
1.167     brouard  10349: #elif __unix__ // all unices, not all compilers
                   10350:     // Unix
1.191     brouard  10351:    printf("Unix ");if(logged) fprintf(ficlog,"Unix ");
1.167     brouard  10352: #elif __linux__
                   10353:     // linux
1.191     brouard  10354:    printf("linux ");if(logged) fprintf(ficlog,"linux ");
1.167     brouard  10355: #elif __APPLE__
1.174     brouard  10356:     // Mac OS, not sure if this is covered by __posix__ and/or __unix__ though..
1.191     brouard  10357:    printf("Mac OS ");if(logged) fprintf(ficlog,"Mac OS ");
1.167     brouard  10358: #endif
                   10359: 
                   10360: /*  __MINGW32__          */
                   10361: /*  __CYGWIN__  */
                   10362: /* __MINGW64__  */
                   10363: // http://msdn.microsoft.com/en-us/library/b0084kay.aspx
                   10364: /* _MSC_VER  //the Visual C++ compiler is 17.00.51106.1, the _MSC_VER macro evaluates to 1700. Type cl /?  */
                   10365: /* _MSC_FULL_VER //the Visual C++ compiler is 15.00.20706.01, the _MSC_FULL_VER macro evaluates to 150020706 */
                   10366: /* _WIN64  // Defined for applications for Win64. */
                   10367: /* _M_X64 // Defined for compilations that target x64 processors. */
                   10368: /* _DEBUG // Defined when you compile with /LDd, /MDd, and /MTd. */
1.171     brouard  10369: 
1.167     brouard  10370: #if UINTPTR_MAX == 0xffffffff
1.191     brouard  10371:    printf(" 32-bit"); if(logged) fprintf(ficlog," 32-bit");/* 32-bit */
1.167     brouard  10372: #elif UINTPTR_MAX == 0xffffffffffffffff
1.191     brouard  10373:    printf(" 64-bit"); if(logged) fprintf(ficlog," 64-bit");/* 64-bit */
1.167     brouard  10374: #else
1.191     brouard  10375:    printf(" wtf-bit"); if(logged) fprintf(ficlog," wtf-bit");/* wtf */
1.167     brouard  10376: #endif
                   10377: 
1.169     brouard  10378: #if defined(__GNUC__)
                   10379: # if defined(__GNUC_PATCHLEVEL__)
                   10380: #  define __GNUC_VERSION__ (__GNUC__ * 10000 \
                   10381:                             + __GNUC_MINOR__ * 100 \
                   10382:                             + __GNUC_PATCHLEVEL__)
                   10383: # else
                   10384: #  define __GNUC_VERSION__ (__GNUC__ * 10000 \
                   10385:                             + __GNUC_MINOR__ * 100)
                   10386: # endif
1.174     brouard  10387:    printf(" using GNU C version %d.\n", __GNUC_VERSION__);
1.191     brouard  10388:    if(logged) fprintf(ficlog, " using GNU C version %d.\n", __GNUC_VERSION__);
1.176     brouard  10389: 
                   10390:    if (uname(&sysInfo) != -1) {
                   10391:      printf("Running on: %s %s %s %s %s\n",sysInfo.sysname, sysInfo.nodename, sysInfo.release, sysInfo.version, sysInfo.machine);
1.191     brouard  10392:         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  10393:    }
                   10394:    else
                   10395:       perror("uname() error");
1.179     brouard  10396:    //#ifndef __INTEL_COMPILER 
                   10397: #if !defined (__INTEL_COMPILER) && !defined(__APPLE__)
1.174     brouard  10398:    printf("GNU libc version: %s\n", gnu_get_libc_version()); 
1.191     brouard  10399:    if(logged) fprintf(ficlog,"GNU libc version: %s\n", gnu_get_libc_version());
1.177     brouard  10400: #endif
1.169     brouard  10401: #endif
1.172     brouard  10402: 
1.286     brouard  10403:    //   void main ()
1.172     brouard  10404:    //   {
1.169     brouard  10405: #if defined(_MSC_VER)
1.174     brouard  10406:    if (IsWow64()){
1.191     brouard  10407:           printf("\nThe program (probably compiled for 32bit) is running under WOW64 (64bit) emulation.\n");
                   10408:           if (logged) fprintf(ficlog, "\nThe program (probably compiled for 32bit) is running under WOW64 (64bit) emulation.\n");
1.174     brouard  10409:    }
                   10410:    else{
1.191     brouard  10411:           printf("\nThe program is not running under WOW64 (i.e probably on a 64bit Windows).\n");
                   10412:           if (logged) fprintf(ficlog, "\nThe programm is not running under WOW64 (i.e probably on a 64bit Windows).\n");
1.174     brouard  10413:    }
1.172     brouard  10414:    //     printf("\nPress Enter to continue...");
                   10415:    //     getchar();
                   10416:    //   }
                   10417: 
1.169     brouard  10418: #endif
                   10419:    
1.167     brouard  10420: 
1.219     brouard  10421: }
1.136     brouard  10422: 
1.219     brouard  10423: int prevalence_limit(double *p, double **prlim, double ageminpar, double agemaxpar, double ftolpl, int *ncvyearp){
1.288     brouard  10424:   /*--------------- Prevalence limit  (forward period or forward stable prevalence) --------------*/
1.235     brouard  10425:   int i, j, k, i1, k4=0, nres=0 ;
1.202     brouard  10426:   /* double ftolpl = 1.e-10; */
1.180     brouard  10427:   double age, agebase, agelim;
1.203     brouard  10428:   double tot;
1.180     brouard  10429: 
1.202     brouard  10430:   strcpy(filerespl,"PL_");
                   10431:   strcat(filerespl,fileresu);
                   10432:   if((ficrespl=fopen(filerespl,"w"))==NULL) {
1.288     brouard  10433:     printf("Problem with forward period (stable) prevalence resultfile: %s\n", filerespl);return 1;
                   10434:     fprintf(ficlog,"Problem with forward period (stable) prevalence resultfile: %s\n", filerespl);return 1;
1.202     brouard  10435:   }
1.288     brouard  10436:   printf("\nComputing forward period (stable) prevalence: result on file '%s' \n", filerespl);
                   10437:   fprintf(ficlog,"\nComputing forward period (stable) prevalence: result on file '%s' \n", filerespl);
1.202     brouard  10438:   pstamp(ficrespl);
1.288     brouard  10439:   fprintf(ficrespl,"# Forward period (stable) prevalence. Precision given by ftolpl=%g \n", ftolpl);
1.202     brouard  10440:   fprintf(ficrespl,"#Age ");
                   10441:   for(i=1; i<=nlstate;i++) fprintf(ficrespl,"%d-%d ",i,i);
                   10442:   fprintf(ficrespl,"\n");
1.180     brouard  10443:   
1.219     brouard  10444:   /* prlim=matrix(1,nlstate,1,nlstate);*/ /* back in main */
1.180     brouard  10445: 
1.219     brouard  10446:   agebase=ageminpar;
                   10447:   agelim=agemaxpar;
1.180     brouard  10448: 
1.227     brouard  10449:   /* i1=pow(2,ncoveff); */
1.234     brouard  10450:   i1=pow(2,cptcoveff); /* Number of combination of dummy covariates */
1.219     brouard  10451:   if (cptcovn < 1){i1=1;}
1.180     brouard  10452: 
1.238     brouard  10453:   for(k=1; k<=i1;k++){ /* For each combination k of dummy covariates in the model */
                   10454:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.253     brouard  10455:       if(i1 != 1 && TKresult[nres]!= k)
1.238     brouard  10456:        continue;
1.235     brouard  10457: 
1.238     brouard  10458:       /* for(cptcov=1,k=0;cptcov<=i1;cptcov++){ */
                   10459:       /* for(cptcov=1,k=0;cptcov<=1;cptcov++){ */
                   10460:       //for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){
                   10461:       /* k=k+1; */
                   10462:       /* to clean */
                   10463:       //printf("cptcov=%d cptcod=%d codtab=%d\n",cptcov, cptcod,codtabm(cptcod,cptcov));
                   10464:       fprintf(ficrespl,"#******");
                   10465:       printf("#******");
                   10466:       fprintf(ficlog,"#******");
                   10467:       for(j=1;j<=cptcoveff ;j++) {/* all covariates */
                   10468:        fprintf(ficrespl," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]); /* Here problem for varying dummy*/
                   10469:        printf(" V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   10470:        fprintf(ficlog," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   10471:       }
                   10472:       for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
                   10473:        printf(" V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
                   10474:        fprintf(ficrespl," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
                   10475:        fprintf(ficlog," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
                   10476:       }
                   10477:       fprintf(ficrespl,"******\n");
                   10478:       printf("******\n");
                   10479:       fprintf(ficlog,"******\n");
                   10480:       if(invalidvarcomb[k]){
                   10481:        printf("\nCombination (%d) ignored because no case \n",k); 
                   10482:        fprintf(ficrespl,"#Combination (%d) ignored because no case \n",k); 
                   10483:        fprintf(ficlog,"\nCombination (%d) ignored because no case \n",k); 
                   10484:        continue;
                   10485:       }
1.219     brouard  10486: 
1.238     brouard  10487:       fprintf(ficrespl,"#Age ");
                   10488:       for(j=1;j<=cptcoveff;j++) {
                   10489:        fprintf(ficrespl,"V%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   10490:       }
                   10491:       for(i=1; i<=nlstate;i++) fprintf(ficrespl,"  %d-%d   ",i,i);
                   10492:       fprintf(ficrespl,"Total Years_to_converge\n");
1.227     brouard  10493:     
1.238     brouard  10494:       for (age=agebase; age<=agelim; age++){
                   10495:        /* for (age=agebase; age<=agebase; age++){ */
                   10496:        prevalim(prlim, nlstate, p, age, oldm, savm, ftolpl, ncvyearp, k, nres);
                   10497:        fprintf(ficrespl,"%.0f ",age );
                   10498:        for(j=1;j<=cptcoveff;j++)
                   10499:          fprintf(ficrespl,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   10500:        tot=0.;
                   10501:        for(i=1; i<=nlstate;i++){
                   10502:          tot +=  prlim[i][i];
                   10503:          fprintf(ficrespl," %.5f", prlim[i][i]);
                   10504:        }
                   10505:        fprintf(ficrespl," %.3f %d\n", tot, *ncvyearp);
                   10506:       } /* Age */
                   10507:       /* was end of cptcod */
                   10508:     } /* cptcov */
                   10509:   } /* nres */
1.219     brouard  10510:   return 0;
1.180     brouard  10511: }
                   10512: 
1.218     brouard  10513: 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  10514:        /*--------------- Back Prevalence limit  (backward stable prevalence) --------------*/
1.218     brouard  10515:        
                   10516:        /* Computes the back prevalence limit  for any combination      of covariate values 
                   10517:    * at any age between ageminpar and agemaxpar
                   10518:         */
1.235     brouard  10519:   int i, j, k, i1, nres=0 ;
1.217     brouard  10520:   /* double ftolpl = 1.e-10; */
                   10521:   double age, agebase, agelim;
                   10522:   double tot;
1.218     brouard  10523:   /* double ***mobaverage; */
                   10524:   /* double     **dnewm, **doldm, **dsavm;  /\* for use *\/ */
1.217     brouard  10525: 
                   10526:   strcpy(fileresplb,"PLB_");
                   10527:   strcat(fileresplb,fileresu);
                   10528:   if((ficresplb=fopen(fileresplb,"w"))==NULL) {
1.288     brouard  10529:     printf("Problem with backward prevalence resultfile: %s\n", fileresplb);return 1;
                   10530:     fprintf(ficlog,"Problem with backward prevalence resultfile: %s\n", fileresplb);return 1;
1.217     brouard  10531:   }
1.288     brouard  10532:   printf("Computing backward prevalence: result on file '%s' \n", fileresplb);
                   10533:   fprintf(ficlog,"Computing backward prevalence: result on file '%s' \n", fileresplb);
1.217     brouard  10534:   pstamp(ficresplb);
1.288     brouard  10535:   fprintf(ficresplb,"# Backward prevalence. Precision given by ftolpl=%g \n", ftolpl);
1.217     brouard  10536:   fprintf(ficresplb,"#Age ");
                   10537:   for(i=1; i<=nlstate;i++) fprintf(ficresplb,"%d-%d ",i,i);
                   10538:   fprintf(ficresplb,"\n");
                   10539:   
1.218     brouard  10540:   
                   10541:   /* prlim=matrix(1,nlstate,1,nlstate);*/ /* back in main */
                   10542:   
                   10543:   agebase=ageminpar;
                   10544:   agelim=agemaxpar;
                   10545:   
                   10546:   
1.227     brouard  10547:   i1=pow(2,cptcoveff);
1.218     brouard  10548:   if (cptcovn < 1){i1=1;}
1.227     brouard  10549:   
1.238     brouard  10550:   for(nres=1; nres <= nresult; nres++){ /* For each resultline */
                   10551:     for(k=1; k<=i1;k++){ /* For any combination of dummy covariates, fixed and varying */
1.253     brouard  10552:      if(i1 != 1 && TKresult[nres]!= k)
1.238     brouard  10553:        continue;
                   10554:       //printf("cptcov=%d cptcod=%d codtab=%d\n",cptcov, cptcod,codtabm(cptcod,cptcov));
                   10555:       fprintf(ficresplb,"#******");
                   10556:       printf("#******");
                   10557:       fprintf(ficlog,"#******");
                   10558:       for(j=1;j<=cptcoveff ;j++) {/* all covariates */
                   10559:        fprintf(ficresplb," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   10560:        printf(" V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   10561:        fprintf(ficlog," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   10562:       }
                   10563:       for (j=1; j<= nsq; j++){ /* For each selected (single) quantitative value */
                   10564:        printf(" V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]);
                   10565:        fprintf(ficresplb," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]);
                   10566:        fprintf(ficlog," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]);
                   10567:       }
                   10568:       fprintf(ficresplb,"******\n");
                   10569:       printf("******\n");
                   10570:       fprintf(ficlog,"******\n");
                   10571:       if(invalidvarcomb[k]){
                   10572:        printf("\nCombination (%d) ignored because no cases \n",k); 
                   10573:        fprintf(ficresplb,"#Combination (%d) ignored because no cases \n",k); 
                   10574:        fprintf(ficlog,"\nCombination (%d) ignored because no cases \n",k); 
                   10575:        continue;
                   10576:       }
1.218     brouard  10577:     
1.238     brouard  10578:       fprintf(ficresplb,"#Age ");
                   10579:       for(j=1;j<=cptcoveff;j++) {
                   10580:        fprintf(ficresplb,"V%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   10581:       }
                   10582:       for(i=1; i<=nlstate;i++) fprintf(ficresplb,"  %d-%d   ",i,i);
                   10583:       fprintf(ficresplb,"Total Years_to_converge\n");
1.218     brouard  10584:     
                   10585:     
1.238     brouard  10586:       for (age=agebase; age<=agelim; age++){
                   10587:        /* for (age=agebase; age<=agebase; age++){ */
                   10588:        if(mobilavproj > 0){
                   10589:          /* bprevalim(bprlim, mobaverage, nlstate, p, age, ageminpar, agemaxpar, oldm, savm, doldm, dsavm, ftolpl, ncvyearp, k); */
                   10590:          /* bprevalim(bprlim, mobaverage, nlstate, p, age, oldm, savm, dnewm, doldm, dsavm, ftolpl, ncvyearp, k); */
1.242     brouard  10591:          bprevalim(bprlim, mobaverage, nlstate, p, age, ftolpl, ncvyearp, k, nres);
1.238     brouard  10592:        }else if (mobilavproj == 0){
                   10593:          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);
                   10594:          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);
                   10595:          exit(1);
                   10596:        }else{
                   10597:          /* bprevalim(bprlim, probs, nlstate, p, age, oldm, savm, dnewm, doldm, dsavm, ftolpl, ncvyearp, k); */
1.242     brouard  10598:          bprevalim(bprlim, probs, nlstate, p, age, ftolpl, ncvyearp, k,nres);
1.266     brouard  10599:          /* printf("TOTOT\n"); */
                   10600:           /* exit(1); */
1.238     brouard  10601:        }
                   10602:        fprintf(ficresplb,"%.0f ",age );
                   10603:        for(j=1;j<=cptcoveff;j++)
                   10604:          fprintf(ficresplb,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   10605:        tot=0.;
                   10606:        for(i=1; i<=nlstate;i++){
                   10607:          tot +=  bprlim[i][i];
                   10608:          fprintf(ficresplb," %.5f", bprlim[i][i]);
                   10609:        }
                   10610:        fprintf(ficresplb," %.3f %d\n", tot, *ncvyearp);
                   10611:       } /* Age */
                   10612:       /* was end of cptcod */
1.255     brouard  10613:       /*fprintf(ficresplb,"\n");*/ /* Seems to be necessary for gnuplot only if two result lines and no covariate. */
1.238     brouard  10614:     } /* end of any combination */
                   10615:   } /* end of nres */  
1.218     brouard  10616:   /* hBijx(p, bage, fage); */
                   10617:   /* fclose(ficrespijb); */
                   10618:   
                   10619:   return 0;
1.217     brouard  10620: }
1.218     brouard  10621:  
1.180     brouard  10622: int hPijx(double *p, int bage, int fage){
                   10623:     /*------------- h Pij x at various ages ------------*/
                   10624: 
                   10625:   int stepsize;
                   10626:   int agelim;
                   10627:   int hstepm;
                   10628:   int nhstepm;
1.235     brouard  10629:   int h, i, i1, j, k, k4, nres=0;
1.180     brouard  10630: 
                   10631:   double agedeb;
                   10632:   double ***p3mat;
                   10633: 
1.201     brouard  10634:     strcpy(filerespij,"PIJ_");  strcat(filerespij,fileresu);
1.180     brouard  10635:     if((ficrespij=fopen(filerespij,"w"))==NULL) {
                   10636:       printf("Problem with Pij resultfile: %s\n", filerespij); return 1;
                   10637:       fprintf(ficlog,"Problem with Pij resultfile: %s\n", filerespij); return 1;
                   10638:     }
                   10639:     printf("Computing pij: result on file '%s' \n", filerespij);
                   10640:     fprintf(ficlog,"Computing pij: result on file '%s' \n", filerespij);
                   10641:   
                   10642:     stepsize=(int) (stepm+YEARM-1)/YEARM;
                   10643:     /*if (stepm<=24) stepsize=2;*/
                   10644: 
                   10645:     agelim=AGESUP;
                   10646:     hstepm=stepsize*YEARM; /* Every year of age */
                   10647:     hstepm=hstepm/stepm; /* Typically 2 years, = 2/6 months = 4 */ 
1.218     brouard  10648:                
1.180     brouard  10649:     /* hstepm=1;   aff par mois*/
                   10650:     pstamp(ficrespij);
                   10651:     fprintf(ficrespij,"#****** h Pij x Probability to be in state j at age x+h being in i at x ");
1.227     brouard  10652:     i1= pow(2,cptcoveff);
1.218     brouard  10653:                /* for(cptcov=1,k=0;cptcov<=i1;cptcov++){ */
                   10654:                /*    /\*for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*\/ */
                   10655:                /*      k=k+1;  */
1.235     brouard  10656:     for(nres=1; nres <= nresult; nres++) /* For each resultline */
                   10657:     for(k=1; k<=i1;k++){
1.253     brouard  10658:       if(i1 != 1 && TKresult[nres]!= k)
1.235     brouard  10659:        continue;
1.183     brouard  10660:       fprintf(ficrespij,"\n#****** ");
1.227     brouard  10661:       for(j=1;j<=cptcoveff;j++) 
1.198     brouard  10662:        fprintf(ficrespij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
1.235     brouard  10663:       for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
                   10664:        printf(" V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
                   10665:        fprintf(ficrespij," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
                   10666:       }
1.183     brouard  10667:       fprintf(ficrespij,"******\n");
                   10668:       
                   10669:       for (agedeb=fage; agedeb>=bage; agedeb--){ /* If stepm=6 months */
                   10670:        nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */ 
                   10671:        nhstepm = nhstepm/hstepm; /* Typically 40/4=10 */
                   10672:        
                   10673:        /*        nhstepm=nhstepm*YEARM; aff par mois*/
1.180     brouard  10674:        
1.183     brouard  10675:        p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   10676:        oldm=oldms;savm=savms;
1.235     brouard  10677:        hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k, nres);  
1.183     brouard  10678:        fprintf(ficrespij,"# Cov Agex agex+h hpijx with i,j=");
                   10679:        for(i=1; i<=nlstate;i++)
                   10680:          for(j=1; j<=nlstate+ndeath;j++)
                   10681:            fprintf(ficrespij," %1d-%1d",i,j);
                   10682:        fprintf(ficrespij,"\n");
                   10683:        for (h=0; h<=nhstepm; h++){
                   10684:          /*agedebphstep = agedeb + h*hstepm/YEARM*stepm;*/
                   10685:          fprintf(ficrespij,"%d %3.f %3.f",k, agedeb, agedeb + h*hstepm/YEARM*stepm );
1.180     brouard  10686:          for(i=1; i<=nlstate;i++)
                   10687:            for(j=1; j<=nlstate+ndeath;j++)
1.183     brouard  10688:              fprintf(ficrespij," %.5f", p3mat[i][j][h]);
1.180     brouard  10689:          fprintf(ficrespij,"\n");
                   10690:        }
1.183     brouard  10691:        free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   10692:        fprintf(ficrespij,"\n");
                   10693:       }
1.180     brouard  10694:       /*}*/
                   10695:     }
1.218     brouard  10696:     return 0;
1.180     brouard  10697: }
1.218     brouard  10698:  
                   10699:  int hBijx(double *p, int bage, int fage, double ***prevacurrent){
1.217     brouard  10700:     /*------------- h Bij x at various ages ------------*/
                   10701: 
                   10702:   int stepsize;
1.218     brouard  10703:   /* int agelim; */
                   10704:        int ageminl;
1.217     brouard  10705:   int hstepm;
                   10706:   int nhstepm;
1.238     brouard  10707:   int h, i, i1, j, k, nres;
1.218     brouard  10708:        
1.217     brouard  10709:   double agedeb;
                   10710:   double ***p3mat;
1.218     brouard  10711:        
                   10712:   strcpy(filerespijb,"PIJB_");  strcat(filerespijb,fileresu);
                   10713:   if((ficrespijb=fopen(filerespijb,"w"))==NULL) {
                   10714:     printf("Problem with Pij back resultfile: %s\n", filerespijb); return 1;
                   10715:     fprintf(ficlog,"Problem with Pij back resultfile: %s\n", filerespijb); return 1;
                   10716:   }
                   10717:   printf("Computing pij back: result on file '%s' \n", filerespijb);
                   10718:   fprintf(ficlog,"Computing pij back: result on file '%s' \n", filerespijb);
                   10719:   
                   10720:   stepsize=(int) (stepm+YEARM-1)/YEARM;
                   10721:   /*if (stepm<=24) stepsize=2;*/
1.217     brouard  10722:   
1.218     brouard  10723:   /* agelim=AGESUP; */
1.289     brouard  10724:   ageminl=AGEINF; /* was 30 */
1.218     brouard  10725:   hstepm=stepsize*YEARM; /* Every year of age */
                   10726:   hstepm=hstepm/stepm; /* Typically 2 years, = 2/6 months = 4 */
                   10727:   
                   10728:   /* hstepm=1;   aff par mois*/
                   10729:   pstamp(ficrespijb);
1.255     brouard  10730:   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  10731:   i1= pow(2,cptcoveff);
1.218     brouard  10732:   /* for(cptcov=1,k=0;cptcov<=i1;cptcov++){ */
                   10733:   /*    /\*for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*\/ */
                   10734:   /*   k=k+1;  */
1.238     brouard  10735:   for(nres=1; nres <= nresult; nres++){ /* For each resultline */
                   10736:     for(k=1; k<=i1;k++){ /* For any combination of dummy covariates, fixed and varying */
1.253     brouard  10737:       if(i1 != 1 && TKresult[nres]!= k)
1.238     brouard  10738:        continue;
                   10739:       fprintf(ficrespijb,"\n#****** ");
                   10740:       for(j=1;j<=cptcoveff;j++)
                   10741:        fprintf(ficrespijb,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   10742:       for (j=1; j<= nsq; j++){ /* For each selected (single) quantitative value */
                   10743:        fprintf(ficrespijb," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]);
                   10744:       }
                   10745:       fprintf(ficrespijb,"******\n");
1.264     brouard  10746:       if(invalidvarcomb[k]){  /* Is it necessary here? */
1.238     brouard  10747:        fprintf(ficrespijb,"\n#Combination (%d) ignored because no cases \n",k); 
                   10748:        continue;
                   10749:       }
                   10750:       
                   10751:       /* for (agedeb=fage; agedeb>=bage; agedeb--){ /\* If stepm=6 months *\/ */
                   10752:       for (agedeb=bage; agedeb<=fage; agedeb++){ /* If stepm=6 months and estepm=24 (2 years) */
                   10753:        /* nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm); /\* Typically 20 years = 20*12/6=40 *\/ */
1.297     brouard  10754:        nhstepm=(int) rint((agedeb-ageminl)*YEARM/stepm+0.1)-1; /* Typically 20 years = 20*12/6=40 or 55*12/24=27.5-1.1=>27 */
                   10755:        nhstepm = nhstepm/hstepm; /* Typically 40/4=10, because estepm=24 stepm=6 => hstepm=24/6=4 or 28*/
1.238     brouard  10756:        
                   10757:        /*        nhstepm=nhstepm*YEARM; aff par mois*/
                   10758:        
1.266     brouard  10759:        p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm); /* We can't have it at an upper level because of nhstepm */
                   10760:        /* and memory limitations if stepm is small */
                   10761: 
1.238     brouard  10762:        /* oldm=oldms;savm=savms; */
                   10763:        /* hbxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);   */
1.267     brouard  10764:        hbxij(p3mat,nhstepm,agedeb,hstepm,p,prevacurrent,nlstate,stepm, k, nres);
1.238     brouard  10765:        /* hbxij(p3mat,nhstepm,agedeb,hstepm,p,prevacurrent,nlstate,stepm,oldm,savm, dnewm, doldm, dsavm, k); */
1.255     brouard  10766:        fprintf(ficrespijb,"# Cov Agex agex-h hbijx with i,j=");
1.217     brouard  10767:        for(i=1; i<=nlstate;i++)
                   10768:          for(j=1; j<=nlstate+ndeath;j++)
1.238     brouard  10769:            fprintf(ficrespijb," %1d-%1d",i,j);
1.217     brouard  10770:        fprintf(ficrespijb,"\n");
1.238     brouard  10771:        for (h=0; h<=nhstepm; h++){
                   10772:          /*agedebphstep = agedeb + h*hstepm/YEARM*stepm;*/
                   10773:          fprintf(ficrespijb,"%d %3.f %3.f",k, agedeb, agedeb - h*hstepm/YEARM*stepm );
                   10774:          /* fprintf(ficrespijb,"%d %3.f %3.f",k, agedeb, agedeb + h*hstepm/YEARM*stepm ); */
                   10775:          for(i=1; i<=nlstate;i++)
                   10776:            for(j=1; j<=nlstate+ndeath;j++)
                   10777:              fprintf(ficrespijb," %.5f", p3mat[i][j][h]);
                   10778:          fprintf(ficrespijb,"\n");
                   10779:        }
                   10780:        free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   10781:        fprintf(ficrespijb,"\n");
                   10782:       } /* end age deb */
                   10783:     } /* end combination */
                   10784:   } /* end nres */
1.218     brouard  10785:   return 0;
                   10786:  } /*  hBijx */
1.217     brouard  10787: 
1.180     brouard  10788: 
1.136     brouard  10789: /***********************************************/
                   10790: /**************** Main Program *****************/
                   10791: /***********************************************/
                   10792: 
                   10793: int main(int argc, char *argv[])
                   10794: {
                   10795: #ifdef GSL
                   10796:   const gsl_multimin_fminimizer_type *T;
                   10797:   size_t iteri = 0, it;
                   10798:   int rval = GSL_CONTINUE;
                   10799:   int status = GSL_SUCCESS;
                   10800:   double ssval;
                   10801: #endif
                   10802:   int movingaverage(double ***probs, double bage,double fage, double ***mobaverage, int mobilav);
1.290     brouard  10803:   int i,j, k, iter=0,m,size=100, cptcod; /* Suppressing because nobs */
                   10804:   /* int i,j, k, n=MAXN,iter=0,m,size=100, cptcod; */
1.209     brouard  10805:   int ncvyear=0; /* Number of years needed for the period prevalence to converge */
1.164     brouard  10806:   int jj, ll, li, lj, lk;
1.136     brouard  10807:   int numlinepar=0; /* Current linenumber of parameter file */
1.197     brouard  10808:   int num_filled;
1.136     brouard  10809:   int itimes;
                   10810:   int NDIM=2;
                   10811:   int vpopbased=0;
1.235     brouard  10812:   int nres=0;
1.258     brouard  10813:   int endishere=0;
1.277     brouard  10814:   int noffset=0;
1.274     brouard  10815:   int ncurrv=0; /* Temporary variable */
                   10816:   
1.164     brouard  10817:   char ca[32], cb[32];
1.136     brouard  10818:   /*  FILE *fichtm; *//* Html File */
                   10819:   /* FILE *ficgp;*/ /*Gnuplot File */
                   10820:   struct stat info;
1.191     brouard  10821:   double agedeb=0.;
1.194     brouard  10822: 
                   10823:   double ageminpar=AGEOVERFLOW,agemin=AGEOVERFLOW, agemaxpar=-AGEOVERFLOW, agemax=-AGEOVERFLOW;
1.219     brouard  10824:   double ageminout=-AGEOVERFLOW,agemaxout=AGEOVERFLOW; /* Smaller Age range redefined after movingaverage */
1.136     brouard  10825: 
1.165     brouard  10826:   double fret;
1.191     brouard  10827:   double dum=0.; /* Dummy variable */
1.136     brouard  10828:   double ***p3mat;
1.218     brouard  10829:   /* double ***mobaverage; */
1.164     brouard  10830: 
                   10831:   char line[MAXLINE];
1.197     brouard  10832:   char path[MAXLINE],pathc[MAXLINE],pathcd[MAXLINE],pathtot[MAXLINE];
                   10833: 
1.234     brouard  10834:   char  modeltemp[MAXLINE];
1.230     brouard  10835:   char resultline[MAXLINE];
                   10836:   
1.136     brouard  10837:   char pathr[MAXLINE], pathimach[MAXLINE]; 
1.164     brouard  10838:   char *tok, *val; /* pathtot */
1.290     brouard  10839:   int firstobs=1, lastobs=10; /* nobs = lastobs-firstobs declared globally ;*/
1.195     brouard  10840:   int c,  h , cpt, c2;
1.191     brouard  10841:   int jl=0;
                   10842:   int i1, j1, jk, stepsize=0;
1.194     brouard  10843:   int count=0;
                   10844: 
1.164     brouard  10845:   int *tab; 
1.136     brouard  10846:   int mobilavproj=0 , prevfcast=0 ; /* moving average of prev, If prevfcast=1 prevalence projection */
1.296     brouard  10847:   /* double anprojd, mprojd, jprojd; /\* For eventual projections *\/ */
                   10848:   /* double anprojf, mprojf, jprojf; */
                   10849:   /* double jintmean,mintmean,aintmean;   */
                   10850:   int prvforecast = 0; /* Might be 1 (date of beginning of projection is a choice or 2 is the dateintmean */
                   10851:   int prvbackcast = 0; /* Might be 1 (date of beginning of projection is a choice or 2 is the dateintmean */
                   10852:   double yrfproj= 10.0; /* Number of years of forward projections */
                   10853:   double yrbproj= 10.0; /* Number of years of backward projections */
                   10854:   int prevbcast=0; /* defined as global for mlikeli and mle, replacing backcast */
1.136     brouard  10855:   int mobilav=0,popforecast=0;
1.191     brouard  10856:   int hstepm=0, nhstepm=0;
1.136     brouard  10857:   int agemortsup;
                   10858:   float  sumlpop=0.;
                   10859:   double jprev1=1, mprev1=1,anprev1=2000,jprev2=1, mprev2=1,anprev2=2000;
                   10860:   double jpyram=1, mpyram=1,anpyram=2000,jpyram1=1, mpyram1=1,anpyram1=2000;
                   10861: 
1.191     brouard  10862:   double bage=0, fage=110., age, agelim=0., agebase=0.;
1.136     brouard  10863:   double ftolpl=FTOL;
                   10864:   double **prlim;
1.217     brouard  10865:   double **bprlim;
1.136     brouard  10866:   double ***param; /* Matrix of parameters */
1.251     brouard  10867:   double ***paramstart; /* Matrix of starting parameter values */
                   10868:   double  *p, *pstart; /* p=param[1][1] pstart is for starting values guessed by freqsummary */
1.136     brouard  10869:   double **matcov; /* Matrix of covariance */
1.203     brouard  10870:   double **hess; /* Hessian matrix */
1.136     brouard  10871:   double ***delti3; /* Scale */
                   10872:   double *delti; /* Scale */
                   10873:   double ***eij, ***vareij;
                   10874:   double **varpl; /* Variances of prevalence limits by age */
1.269     brouard  10875: 
1.136     brouard  10876:   double *epj, vepp;
1.164     brouard  10877: 
1.273     brouard  10878:   double dateprev1, dateprev2;
1.296     brouard  10879:   double jproj1=1,mproj1=1,anproj1=2000,jproj2=1,mproj2=1,anproj2=2000, dateproj1=0, dateproj2=0, dateprojd=0, dateprojf=0;
                   10880:   double jback1=1,mback1=1,anback1=2000,jback2=1,mback2=1,anback2=2000, dateback1=0, dateback2=0, datebackd=0, datebackf=0;
                   10881: 
1.217     brouard  10882: 
1.136     brouard  10883:   double **ximort;
1.145     brouard  10884:   char *alph[]={"a","a","b","c","d","e"}, str[4]="1234";
1.136     brouard  10885:   int *dcwave;
                   10886: 
1.164     brouard  10887:   char z[1]="c";
1.136     brouard  10888: 
                   10889:   /*char  *strt;*/
                   10890:   char strtend[80];
1.126     brouard  10891: 
1.164     brouard  10892: 
1.126     brouard  10893: /*   setlocale (LC_ALL, ""); */
                   10894: /*   bindtextdomain (PACKAGE, LOCALEDIR); */
                   10895: /*   textdomain (PACKAGE); */
                   10896: /*   setlocale (LC_CTYPE, ""); */
                   10897: /*   setlocale (LC_MESSAGES, ""); */
                   10898: 
                   10899:   /*   gettimeofday(&start_time, (struct timezone*)0); */ /* at first time */
1.157     brouard  10900:   rstart_time = time(NULL);  
                   10901:   /*  (void) gettimeofday(&start_time,&tzp);*/
                   10902:   start_time = *localtime(&rstart_time);
1.126     brouard  10903:   curr_time=start_time;
1.157     brouard  10904:   /*tml = *localtime(&start_time.tm_sec);*/
                   10905:   /* strcpy(strstart,asctime(&tml)); */
                   10906:   strcpy(strstart,asctime(&start_time));
1.126     brouard  10907: 
                   10908: /*  printf("Localtime (at start)=%s",strstart); */
1.157     brouard  10909: /*  tp.tm_sec = tp.tm_sec +86400; */
                   10910: /*  tm = *localtime(&start_time.tm_sec); */
1.126     brouard  10911: /*   tmg.tm_year=tmg.tm_year +dsign*dyear; */
                   10912: /*   tmg.tm_mon=tmg.tm_mon +dsign*dmonth; */
                   10913: /*   tmg.tm_hour=tmg.tm_hour + 1; */
1.157     brouard  10914: /*   tp.tm_sec = mktime(&tmg); */
1.126     brouard  10915: /*   strt=asctime(&tmg); */
                   10916: /*   printf("Time(after) =%s",strstart);  */
                   10917: /*  (void) time (&time_value);
                   10918: *  printf("time=%d,t-=%d\n",time_value,time_value-86400);
                   10919: *  tm = *localtime(&time_value);
                   10920: *  strstart=asctime(&tm);
                   10921: *  printf("tim_value=%d,asctime=%s\n",time_value,strstart); 
                   10922: */
                   10923: 
                   10924:   nberr=0; /* Number of errors and warnings */
                   10925:   nbwarn=0;
1.184     brouard  10926: #ifdef WIN32
                   10927:   _getcwd(pathcd, size);
                   10928: #else
1.126     brouard  10929:   getcwd(pathcd, size);
1.184     brouard  10930: #endif
1.191     brouard  10931:   syscompilerinfo(0);
1.196     brouard  10932:   printf("\nIMaCh version %s, %s\n%s",version, copyright, fullversion);
1.126     brouard  10933:   if(argc <=1){
                   10934:     printf("\nEnter the parameter file name: ");
1.205     brouard  10935:     if(!fgets(pathr,FILENAMELENGTH,stdin)){
                   10936:       printf("ERROR Empty parameter file name\n");
                   10937:       goto end;
                   10938:     }
1.126     brouard  10939:     i=strlen(pathr);
                   10940:     if(pathr[i-1]=='\n')
                   10941:       pathr[i-1]='\0';
1.156     brouard  10942:     i=strlen(pathr);
1.205     brouard  10943:     if(i >= 1 && pathr[i-1]==' ') {/* This may happen when dragging on oS/X! */
1.156     brouard  10944:       pathr[i-1]='\0';
1.205     brouard  10945:     }
                   10946:     i=strlen(pathr);
                   10947:     if( i==0 ){
                   10948:       printf("ERROR Empty parameter file name\n");
                   10949:       goto end;
                   10950:     }
                   10951:     for (tok = pathr; tok != NULL; ){
1.126     brouard  10952:       printf("Pathr |%s|\n",pathr);
                   10953:       while ((val = strsep(&tok, "\"" )) != NULL && *val == '\0');
                   10954:       printf("val= |%s| pathr=%s\n",val,pathr);
                   10955:       strcpy (pathtot, val);
                   10956:       if(pathr[0] == '\0') break; /* Dirty */
                   10957:     }
                   10958:   }
1.281     brouard  10959:   else if (argc<=2){
                   10960:     strcpy(pathtot,argv[1]);
                   10961:   }
1.126     brouard  10962:   else{
                   10963:     strcpy(pathtot,argv[1]);
1.281     brouard  10964:     strcpy(z,argv[2]);
                   10965:     printf("\nargv[2]=%s z=%c\n",argv[2],z[0]);
1.126     brouard  10966:   }
                   10967:   /*if(getcwd(pathcd, MAXLINE)!= NULL)printf ("Error pathcd\n");*/
                   10968:   /*cygwin_split_path(pathtot,path,optionfile);
                   10969:     printf("pathtot=%s, path=%s, optionfile=%s\n",pathtot,path,optionfile);*/
                   10970:   /* cutv(path,optionfile,pathtot,'\\');*/
                   10971: 
                   10972:   /* Split argv[0], imach program to get pathimach */
                   10973:   printf("\nargv[0]=%s argv[1]=%s, \n",argv[0],argv[1]);
                   10974:   split(argv[0],pathimach,optionfile,optionfilext,optionfilefiname);
                   10975:   printf("\nargv[0]=%s pathimach=%s, \noptionfile=%s \noptionfilext=%s \noptionfilefiname=%s\n",argv[0],pathimach,optionfile,optionfilext,optionfilefiname);
                   10976:  /*   strcpy(pathimach,argv[0]); */
                   10977:   /* Split argv[1]=pathtot, parameter file name to get path, optionfile, extension and name */
                   10978:   split(pathtot,path,optionfile,optionfilext,optionfilefiname);
                   10979:   printf("\npathtot=%s,\npath=%s,\noptionfile=%s \noptionfilext=%s \noptionfilefiname=%s\n",pathtot,path,optionfile,optionfilext,optionfilefiname);
1.184     brouard  10980: #ifdef WIN32
                   10981:   _chdir(path); /* Can be a relative path */
                   10982:   if(_getcwd(pathcd,MAXLINE) > 0) /* So pathcd is the full path */
                   10983: #else
1.126     brouard  10984:   chdir(path); /* Can be a relative path */
1.184     brouard  10985:   if (getcwd(pathcd, MAXLINE) > 0) /* So pathcd is the full path */
                   10986: #endif
                   10987:   printf("Current directory %s!\n",pathcd);
1.126     brouard  10988:   strcpy(command,"mkdir ");
                   10989:   strcat(command,optionfilefiname);
                   10990:   if((outcmd=system(command)) != 0){
1.169     brouard  10991:     printf("Directory already exists (or can't create it) %s%s, err=%d\n",path,optionfilefiname,outcmd);
1.126     brouard  10992:     /* fprintf(ficlog,"Problem creating directory %s%s\n",path,optionfilefiname); */
                   10993:     /* fclose(ficlog); */
                   10994: /*     exit(1); */
                   10995:   }
                   10996: /*   if((imk=mkdir(optionfilefiname))<0){ */
                   10997: /*     perror("mkdir"); */
                   10998: /*   } */
                   10999: 
                   11000:   /*-------- arguments in the command line --------*/
                   11001: 
1.186     brouard  11002:   /* Main Log file */
1.126     brouard  11003:   strcat(filelog, optionfilefiname);
                   11004:   strcat(filelog,".log");    /* */
                   11005:   if((ficlog=fopen(filelog,"w"))==NULL)    {
                   11006:     printf("Problem with logfile %s\n",filelog);
                   11007:     goto end;
                   11008:   }
                   11009:   fprintf(ficlog,"Log filename:%s\n",filelog);
1.197     brouard  11010:   fprintf(ficlog,"Version %s %s",version,fullversion);
1.126     brouard  11011:   fprintf(ficlog,"\nEnter the parameter file name: \n");
                   11012:   fprintf(ficlog,"pathimach=%s\npathtot=%s\n\
                   11013:  path=%s \n\
                   11014:  optionfile=%s\n\
                   11015:  optionfilext=%s\n\
1.156     brouard  11016:  optionfilefiname='%s'\n",pathimach,pathtot,path,optionfile,optionfilext,optionfilefiname);
1.126     brouard  11017: 
1.197     brouard  11018:   syscompilerinfo(1);
1.167     brouard  11019: 
1.126     brouard  11020:   printf("Local time (at start):%s",strstart);
                   11021:   fprintf(ficlog,"Local time (at start): %s",strstart);
                   11022:   fflush(ficlog);
                   11023: /*   (void) gettimeofday(&curr_time,&tzp); */
1.157     brouard  11024: /*   printf("Elapsed time %d\n", asc_diff_time(curr_time.tm_sec-start_time.tm_sec,tmpout)); */
1.126     brouard  11025: 
                   11026:   /* */
                   11027:   strcpy(fileres,"r");
                   11028:   strcat(fileres, optionfilefiname);
1.201     brouard  11029:   strcat(fileresu, optionfilefiname); /* Without r in front */
1.126     brouard  11030:   strcat(fileres,".txt");    /* Other files have txt extension */
1.201     brouard  11031:   strcat(fileresu,".txt");    /* Other files have txt extension */
1.126     brouard  11032: 
1.186     brouard  11033:   /* Main ---------arguments file --------*/
1.126     brouard  11034: 
                   11035:   if((ficpar=fopen(optionfile,"r"))==NULL)    {
1.155     brouard  11036:     printf("Problem with optionfile '%s' with errno='%s'\n",optionfile,strerror(errno));
                   11037:     fprintf(ficlog,"Problem with optionfile '%s' with errno='%s'\n",optionfile,strerror(errno));
1.126     brouard  11038:     fflush(ficlog);
1.149     brouard  11039:     /* goto end; */
                   11040:     exit(70); 
1.126     brouard  11041:   }
                   11042: 
                   11043:   strcpy(filereso,"o");
1.201     brouard  11044:   strcat(filereso,fileresu);
1.126     brouard  11045:   if((ficparo=fopen(filereso,"w"))==NULL) { /* opened on subdirectory */
                   11046:     printf("Problem with Output resultfile: %s\n", filereso);
                   11047:     fprintf(ficlog,"Problem with Output resultfile: %s\n", filereso);
                   11048:     fflush(ficlog);
                   11049:     goto end;
                   11050:   }
1.278     brouard  11051:       /*-------- Rewriting parameter file ----------*/
                   11052:   strcpy(rfileres,"r");    /* "Rparameterfile */
                   11053:   strcat(rfileres,optionfilefiname);    /* Parameter file first name */
                   11054:   strcat(rfileres,".");    /* */
                   11055:   strcat(rfileres,optionfilext);    /* Other files have txt extension */
                   11056:   if((ficres =fopen(rfileres,"w"))==NULL) {
                   11057:     printf("Problem writing new parameter file: %s\n", rfileres);goto end;
                   11058:     fprintf(ficlog,"Problem writing new parameter file: %s\n", rfileres);goto end;
                   11059:     fflush(ficlog);
                   11060:     goto end;
                   11061:   }
                   11062:   fprintf(ficres,"#IMaCh %s\n",version);
1.126     brouard  11063: 
1.278     brouard  11064:                                      
1.126     brouard  11065:   /* Reads comments: lines beginning with '#' */
                   11066:   numlinepar=0;
1.277     brouard  11067:   /* Is it a BOM UTF-8 Windows file? */
                   11068:   /* First parameter line */
1.197     brouard  11069:   while(fgets(line, MAXLINE, ficpar)) {
1.277     brouard  11070:     noffset=0;
                   11071:     if( line[0] == (char)0xEF && line[1] == (char)0xBB) /* EF BB BF */
                   11072:     {
                   11073:       noffset=noffset+3;
                   11074:       printf("# File is an UTF8 Bom.\n"); // 0xBF
                   11075:     }
                   11076:     else if( line[0] == (char)0xFE && line[1] == (char)0xFF)
                   11077:     {
                   11078:       noffset=noffset+2;
                   11079:       printf("# File is an UTF16BE BOM file\n");
                   11080:     }
                   11081:     else if( line[0] == 0 && line[1] == 0)
                   11082:     {
                   11083:       if( line[2] == (char)0xFE && line[3] == (char)0xFF){
                   11084:        noffset=noffset+4;
                   11085:        printf("# File is an UTF16BE BOM file\n");
                   11086:       }
                   11087:     } else{
                   11088:       ;/*printf(" Not a BOM file\n");*/
                   11089:     }
                   11090:   
1.197     brouard  11091:     /* If line starts with a # it is a comment */
1.277     brouard  11092:     if (line[noffset] == '#') {
1.197     brouard  11093:       numlinepar++;
                   11094:       fputs(line,stdout);
                   11095:       fputs(line,ficparo);
1.278     brouard  11096:       fputs(line,ficres);
1.197     brouard  11097:       fputs(line,ficlog);
                   11098:       continue;
                   11099:     }else
                   11100:       break;
                   11101:   }
                   11102:   if((num_filled=sscanf(line,"title=%s datafile=%s lastobs=%d firstpass=%d lastpass=%d\n", \
                   11103:                        title, datafile, &lastobs, &firstpass,&lastpass)) !=EOF){
                   11104:     if (num_filled != 5) {
                   11105:       printf("Should be 5 parameters\n");
1.283     brouard  11106:       fprintf(ficlog,"Should be 5 parameters\n");
1.197     brouard  11107:     }
1.126     brouard  11108:     numlinepar++;
1.197     brouard  11109:     printf("title=%s datafile=%s lastobs=%d firstpass=%d lastpass=%d\n", title, datafile, lastobs, firstpass,lastpass);
1.283     brouard  11110:     fprintf(ficparo,"title=%s datafile=%s lastobs=%d firstpass=%d lastpass=%d\n", title, datafile, lastobs, firstpass,lastpass);
                   11111:     fprintf(ficres,"title=%s datafile=%s lastobs=%d firstpass=%d lastpass=%d\n", title, datafile, lastobs, firstpass,lastpass);
                   11112:     fprintf(ficlog,"title=%s datafile=%s lastobs=%d firstpass=%d lastpass=%d\n", title, datafile, lastobs, firstpass,lastpass);
1.197     brouard  11113:   }
                   11114:   /* Second parameter line */
                   11115:   while(fgets(line, MAXLINE, ficpar)) {
1.283     brouard  11116:     /* while(fscanf(ficpar,"%[^\n]", line)) { */
                   11117:     /* If line starts with a # it is a comment. Strangely fgets reads the EOL and fputs doesn't */
1.197     brouard  11118:     if (line[0] == '#') {
                   11119:       numlinepar++;
1.283     brouard  11120:       printf("%s",line);
                   11121:       fprintf(ficres,"%s",line);
                   11122:       fprintf(ficparo,"%s",line);
                   11123:       fprintf(ficlog,"%s",line);
1.197     brouard  11124:       continue;
                   11125:     }else
                   11126:       break;
                   11127:   }
1.223     brouard  11128:   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", \
                   11129:                        &ftol, &stepm, &ncovcol, &nqv, &ntv, &nqtv, &nlstate, &ndeath, &maxwav, &mle, &weightopt)) !=EOF){
                   11130:     if (num_filled != 11) {
                   11131:       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  11132:       printf("but line=%s\n",line);
1.283     brouard  11133:       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");
                   11134:       fprintf(ficlog,"but line=%s\n",line);
1.197     brouard  11135:     }
1.286     brouard  11136:     if( lastpass > maxwav){
                   11137:       printf("Error (lastpass = %d) > (maxwav = %d)\n",lastpass, maxwav);
                   11138:       fprintf(ficlog,"Error (lastpass = %d) > (maxwav = %d)\n",lastpass, maxwav);
                   11139:       fflush(ficlog);
                   11140:       goto end;
                   11141:     }
                   11142:       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  11143:     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  11144:     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  11145:     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  11146:   }
1.203     brouard  11147:   /* ftolpl=6*ftol*1.e5; /\* 6.e-3 make convergences in less than 80 loops for the prevalence limit *\/ */
1.209     brouard  11148:   /*ftolpl=6.e-4; *//* 6.e-3 make convergences in less than 80 loops for the prevalence limit */
1.197     brouard  11149:   /* Third parameter line */
                   11150:   while(fgets(line, MAXLINE, ficpar)) {
                   11151:     /* If line starts with a # it is a comment */
                   11152:     if (line[0] == '#') {
                   11153:       numlinepar++;
1.283     brouard  11154:       printf("%s",line);
                   11155:       fprintf(ficres,"%s",line);
                   11156:       fprintf(ficparo,"%s",line);
                   11157:       fprintf(ficlog,"%s",line);
1.197     brouard  11158:       continue;
                   11159:     }else
                   11160:       break;
                   11161:   }
1.201     brouard  11162:   if((num_filled=sscanf(line,"model=1+age%[^.\n]", model)) !=EOF){
1.279     brouard  11163:     if (num_filled != 1){
                   11164:       printf("ERROR %d: Model should be at minimum 'model=1+age' %s\n",num_filled, line);
                   11165:       fprintf(ficlog,"ERROR %d: Model should be at minimum 'model=1+age' %s\n",num_filled, line);
1.197     brouard  11166:       model[0]='\0';
                   11167:       goto end;
                   11168:     }
                   11169:     else{
                   11170:       if (model[0]=='+'){
                   11171:        for(i=1; i<=strlen(model);i++)
                   11172:          modeltemp[i-1]=model[i];
1.201     brouard  11173:        strcpy(model,modeltemp); 
1.197     brouard  11174:       }
                   11175:     }
1.199     brouard  11176:     /* printf(" model=1+age%s modeltemp= %s, model=%s\n",model, modeltemp, model);fflush(stdout); */
1.203     brouard  11177:     printf("model=1+age+%s\n",model);fflush(stdout);
1.283     brouard  11178:     fprintf(ficparo,"model=1+age+%s\n",model);fflush(stdout);
                   11179:     fprintf(ficres,"model=1+age+%s\n",model);fflush(stdout);
                   11180:     fprintf(ficlog,"model=1+age+%s\n",model);fflush(stdout);
1.197     brouard  11181:   }
                   11182:   /* 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); */
                   11183:   /* numlinepar=numlinepar+3; /\* In general *\/ */
                   11184:   /* 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  11185:   /* 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); */
                   11186:   /* 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  11187:   fflush(ficlog);
1.190     brouard  11188:   /* if(model[0]=='#'|| model[0]== '\0'){ */
                   11189:   if(model[0]=='#'){
1.279     brouard  11190:     printf("Error in 'model' line: model should start with 'model=1+age+' and end without space \n \
                   11191:  'model=1+age+' or 'model=1+age+V1.' or 'model=1+age+age*age+V1+V1*age' or \n \
                   11192:  'model=1+age+V1+V2' or 'model=1+age+V1+V2+V1*V2' etc. \n");           \
1.187     brouard  11193:     if(mle != -1){
1.279     brouard  11194:       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  11195:       exit(1);
                   11196:     }
                   11197:   }
1.126     brouard  11198:   while((c=getc(ficpar))=='#' && c!= EOF){
                   11199:     ungetc(c,ficpar);
                   11200:     fgets(line, MAXLINE, ficpar);
                   11201:     numlinepar++;
1.195     brouard  11202:     if(line[1]=='q'){ /* This #q will quit imach (the answer is q) */
                   11203:       z[0]=line[1];
                   11204:     }
                   11205:     /* printf("****line [1] = %c \n",line[1]); */
1.141     brouard  11206:     fputs(line, stdout);
                   11207:     //puts(line);
1.126     brouard  11208:     fputs(line,ficparo);
                   11209:     fputs(line,ficlog);
                   11210:   }
                   11211:   ungetc(c,ficpar);
                   11212: 
                   11213:    
1.290     brouard  11214:   covar=matrix(0,NCOVMAX,firstobs,lastobs);  /**< used in readdata */
                   11215:   if(nqv>=1)coqvar=matrix(1,nqv,firstobs,lastobs);  /**< Fixed quantitative covariate */
                   11216:   if(nqtv>=1)cotqvar=ma3x(1,maxwav,1,nqtv,firstobs,lastobs);  /**< Time varying quantitative covariate */
                   11217:   if(ntv+nqtv>=1)cotvar=ma3x(1,maxwav,1,ntv+nqtv,firstobs,lastobs);  /**< Time varying covariate (dummy and quantitative)*/
1.136     brouard  11218:   cptcovn=0; /*Number of covariates, i.e. number of '+' in model statement plus one, indepently of n in Vn*/
                   11219:   /* v1+v2+v3+v2*v4+v5*age makes cptcovn = 5
                   11220:      v1+v2*age+v2*v3 makes cptcovn = 3
                   11221:   */
                   11222:   if (strlen(model)>1) 
1.187     brouard  11223:     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  11224:   else
1.187     brouard  11225:     ncovmodel=2; /* Constant and age */
1.133     brouard  11226:   nforce= (nlstate+ndeath-1)*nlstate; /* Number of forces ij from state i to j */
                   11227:   npar= nforce*ncovmodel; /* Number of parameters like aij*/
1.131     brouard  11228:   if(npar >MAXPARM || nlstate >NLSTATEMAX || ndeath >NDEATHMAX || ncovmodel>NCOVMAX){
                   11229:     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);
                   11230:     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);
                   11231:     fflush(stdout);
                   11232:     fclose (ficlog);
                   11233:     goto end;
                   11234:   }
1.126     brouard  11235:   delti3= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
                   11236:   delti=delti3[1][1];
                   11237:   /*delti=vector(1,npar); *//* Scale of each paramater (output from hesscov)*/
                   11238:   if(mle==-1){ /* Print a wizard for help writing covariance matrix */
1.247     brouard  11239: /* We could also provide initial parameters values giving by simple logistic regression 
                   11240:  * only one way, that is without matrix product. We will have nlstate maximizations */
                   11241:       /* for(i=1;i<nlstate;i++){ */
                   11242:       /*       /\*reducing xi for 1 to npar to 1 to ncovmodel; *\/ */
                   11243:       /*    mlikeli(ficres,p, ncovmodel, ncovmodel, nlstate, ftol, funcnoprod); */
                   11244:       /* } */
1.126     brouard  11245:     prwizard(ncovmodel, nlstate, ndeath, model, ficparo);
1.191     brouard  11246:     printf(" You chose mle=-1, look at file %s for a template of covariance matrix \n",filereso);
                   11247:     fprintf(ficlog," You chose mle=-1, look at file %s for a template of covariance matrix \n",filereso);
1.126     brouard  11248:     free_ma3x(delti3,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel); 
                   11249:     fclose (ficparo);
                   11250:     fclose (ficlog);
                   11251:     goto end;
                   11252:     exit(0);
1.220     brouard  11253:   }  else if(mle==-5) { /* Main Wizard */
1.126     brouard  11254:     prwizard(ncovmodel, nlstate, ndeath, model, ficparo);
1.192     brouard  11255:     printf(" You chose mle=-3, look at file %s for a template of covariance matrix \n",filereso);
                   11256:     fprintf(ficlog," You chose mle=-3, look at file %s for a template of covariance matrix \n",filereso);
1.126     brouard  11257:     param= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
                   11258:     matcov=matrix(1,npar,1,npar);
1.203     brouard  11259:     hess=matrix(1,npar,1,npar);
1.220     brouard  11260:   }  else{ /* Begin of mle != -1 or -5 */
1.145     brouard  11261:     /* Read guessed parameters */
1.126     brouard  11262:     /* Reads comments: lines beginning with '#' */
                   11263:     while((c=getc(ficpar))=='#' && c!= EOF){
                   11264:       ungetc(c,ficpar);
                   11265:       fgets(line, MAXLINE, ficpar);
                   11266:       numlinepar++;
1.141     brouard  11267:       fputs(line,stdout);
1.126     brouard  11268:       fputs(line,ficparo);
                   11269:       fputs(line,ficlog);
                   11270:     }
                   11271:     ungetc(c,ficpar);
                   11272:     
                   11273:     param= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
1.251     brouard  11274:     paramstart= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
1.126     brouard  11275:     for(i=1; i <=nlstate; i++){
1.234     brouard  11276:       j=0;
1.126     brouard  11277:       for(jj=1; jj <=nlstate+ndeath; jj++){
1.234     brouard  11278:        if(jj==i) continue;
                   11279:        j++;
1.292     brouard  11280:        while((c=getc(ficpar))=='#' && c!= EOF){
                   11281:          ungetc(c,ficpar);
                   11282:          fgets(line, MAXLINE, ficpar);
                   11283:          numlinepar++;
                   11284:          fputs(line,stdout);
                   11285:          fputs(line,ficparo);
                   11286:          fputs(line,ficlog);
                   11287:        }
                   11288:        ungetc(c,ficpar);
1.234     brouard  11289:        fscanf(ficpar,"%1d%1d",&i1,&j1);
                   11290:        if ((i1 != i) || (j1 != jj)){
                   11291:          printf("Error in line parameters number %d, %1d%1d instead of %1d%1d \n \
1.126     brouard  11292: It might be a problem of design; if ncovcol and the model are correct\n \
                   11293: run imach with mle=-1 to get a correct template of the parameter file.\n",numlinepar, i,j, i1, j1);
1.234     brouard  11294:          exit(1);
                   11295:        }
                   11296:        fprintf(ficparo,"%1d%1d",i1,j1);
                   11297:        if(mle==1)
                   11298:          printf("%1d%1d",i,jj);
                   11299:        fprintf(ficlog,"%1d%1d",i,jj);
                   11300:        for(k=1; k<=ncovmodel;k++){
                   11301:          fscanf(ficpar," %lf",&param[i][j][k]);
                   11302:          if(mle==1){
                   11303:            printf(" %lf",param[i][j][k]);
                   11304:            fprintf(ficlog," %lf",param[i][j][k]);
                   11305:          }
                   11306:          else
                   11307:            fprintf(ficlog," %lf",param[i][j][k]);
                   11308:          fprintf(ficparo," %lf",param[i][j][k]);
                   11309:        }
                   11310:        fscanf(ficpar,"\n");
                   11311:        numlinepar++;
                   11312:        if(mle==1)
                   11313:          printf("\n");
                   11314:        fprintf(ficlog,"\n");
                   11315:        fprintf(ficparo,"\n");
1.126     brouard  11316:       }
                   11317:     }  
                   11318:     fflush(ficlog);
1.234     brouard  11319:     
1.251     brouard  11320:     /* Reads parameters values */
1.126     brouard  11321:     p=param[1][1];
1.251     brouard  11322:     pstart=paramstart[1][1];
1.126     brouard  11323:     
                   11324:     /* Reads comments: lines beginning with '#' */
                   11325:     while((c=getc(ficpar))=='#' && c!= EOF){
                   11326:       ungetc(c,ficpar);
                   11327:       fgets(line, MAXLINE, ficpar);
                   11328:       numlinepar++;
1.141     brouard  11329:       fputs(line,stdout);
1.126     brouard  11330:       fputs(line,ficparo);
                   11331:       fputs(line,ficlog);
                   11332:     }
                   11333:     ungetc(c,ficpar);
                   11334: 
                   11335:     for(i=1; i <=nlstate; i++){
                   11336:       for(j=1; j <=nlstate+ndeath-1; j++){
1.234     brouard  11337:        fscanf(ficpar,"%1d%1d",&i1,&j1);
                   11338:        if ( (i1-i) * (j1-j) != 0){
                   11339:          printf("Error in line parameters number %d, %1d%1d instead of %1d%1d \n",numlinepar, i,j, i1, j1);
                   11340:          exit(1);
                   11341:        }
                   11342:        printf("%1d%1d",i,j);
                   11343:        fprintf(ficparo,"%1d%1d",i1,j1);
                   11344:        fprintf(ficlog,"%1d%1d",i1,j1);
                   11345:        for(k=1; k<=ncovmodel;k++){
                   11346:          fscanf(ficpar,"%le",&delti3[i][j][k]);
                   11347:          printf(" %le",delti3[i][j][k]);
                   11348:          fprintf(ficparo," %le",delti3[i][j][k]);
                   11349:          fprintf(ficlog," %le",delti3[i][j][k]);
                   11350:        }
                   11351:        fscanf(ficpar,"\n");
                   11352:        numlinepar++;
                   11353:        printf("\n");
                   11354:        fprintf(ficparo,"\n");
                   11355:        fprintf(ficlog,"\n");
1.126     brouard  11356:       }
                   11357:     }
                   11358:     fflush(ficlog);
1.234     brouard  11359:     
1.145     brouard  11360:     /* Reads covariance matrix */
1.126     brouard  11361:     delti=delti3[1][1];
1.220     brouard  11362:                
                   11363:                
1.126     brouard  11364:     /* 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  11365:                
1.126     brouard  11366:     /* Reads comments: lines beginning with '#' */
                   11367:     while((c=getc(ficpar))=='#' && c!= EOF){
                   11368:       ungetc(c,ficpar);
                   11369:       fgets(line, MAXLINE, ficpar);
                   11370:       numlinepar++;
1.141     brouard  11371:       fputs(line,stdout);
1.126     brouard  11372:       fputs(line,ficparo);
                   11373:       fputs(line,ficlog);
                   11374:     }
                   11375:     ungetc(c,ficpar);
1.220     brouard  11376:                
1.126     brouard  11377:     matcov=matrix(1,npar,1,npar);
1.203     brouard  11378:     hess=matrix(1,npar,1,npar);
1.131     brouard  11379:     for(i=1; i <=npar; i++)
                   11380:       for(j=1; j <=npar; j++) matcov[i][j]=0.;
1.220     brouard  11381:                
1.194     brouard  11382:     /* Scans npar lines */
1.126     brouard  11383:     for(i=1; i <=npar; i++){
1.226     brouard  11384:       count=fscanf(ficpar,"%1d%1d%d",&i1,&j1,&jk);
1.194     brouard  11385:       if(count != 3){
1.226     brouard  11386:        printf("Error! Error in parameter file %s at line %d after line starting with %1d%1d%1d\n\
1.194     brouard  11387: This is probably because your covariance matrix doesn't \n  contain exactly %d lines corresponding to your model line '1+age+%s'.\n\
                   11388: Please run with mle=-1 to get a correct covariance matrix.\n",optionfile,numlinepar, i1,j1,jk, npar, model);
1.226     brouard  11389:        fprintf(ficlog,"Error! Error in parameter file %s at line %d after line starting with %1d%1d%1d\n\
1.194     brouard  11390: This is probably because your covariance matrix doesn't \n  contain exactly %d lines corresponding to your model line '1+age+%s'.\n\
                   11391: Please run with mle=-1 to get a correct covariance matrix.\n",optionfile,numlinepar, i1,j1,jk, npar, model);
1.226     brouard  11392:        exit(1);
1.220     brouard  11393:       }else{
1.226     brouard  11394:        if(mle==1)
                   11395:          printf("%1d%1d%d",i1,j1,jk);
                   11396:       }
                   11397:       fprintf(ficlog,"%1d%1d%d",i1,j1,jk);
                   11398:       fprintf(ficparo,"%1d%1d%d",i1,j1,jk);
1.126     brouard  11399:       for(j=1; j <=i; j++){
1.226     brouard  11400:        fscanf(ficpar," %le",&matcov[i][j]);
                   11401:        if(mle==1){
                   11402:          printf(" %.5le",matcov[i][j]);
                   11403:        }
                   11404:        fprintf(ficlog," %.5le",matcov[i][j]);
                   11405:        fprintf(ficparo," %.5le",matcov[i][j]);
1.126     brouard  11406:       }
                   11407:       fscanf(ficpar,"\n");
                   11408:       numlinepar++;
                   11409:       if(mle==1)
1.220     brouard  11410:                                printf("\n");
1.126     brouard  11411:       fprintf(ficlog,"\n");
                   11412:       fprintf(ficparo,"\n");
                   11413:     }
1.194     brouard  11414:     /* End of read covariance matrix npar lines */
1.126     brouard  11415:     for(i=1; i <=npar; i++)
                   11416:       for(j=i+1;j<=npar;j++)
1.226     brouard  11417:        matcov[i][j]=matcov[j][i];
1.126     brouard  11418:     
                   11419:     if(mle==1)
                   11420:       printf("\n");
                   11421:     fprintf(ficlog,"\n");
                   11422:     
                   11423:     fflush(ficlog);
                   11424:     
                   11425:   }    /* End of mle != -3 */
1.218     brouard  11426:   
1.186     brouard  11427:   /*  Main data
                   11428:    */
1.290     brouard  11429:   nobs=lastobs-firstobs+1; /* was = lastobs;*/
                   11430:   /* num=lvector(1,n); */
                   11431:   /* moisnais=vector(1,n); */
                   11432:   /* annais=vector(1,n); */
                   11433:   /* moisdc=vector(1,n); */
                   11434:   /* andc=vector(1,n); */
                   11435:   /* weight=vector(1,n); */
                   11436:   /* agedc=vector(1,n); */
                   11437:   /* cod=ivector(1,n); */
                   11438:   /* for(i=1;i<=n;i++){ */
                   11439:   num=lvector(firstobs,lastobs);
                   11440:   moisnais=vector(firstobs,lastobs);
                   11441:   annais=vector(firstobs,lastobs);
                   11442:   moisdc=vector(firstobs,lastobs);
                   11443:   andc=vector(firstobs,lastobs);
                   11444:   weight=vector(firstobs,lastobs);
                   11445:   agedc=vector(firstobs,lastobs);
                   11446:   cod=ivector(firstobs,lastobs);
                   11447:   for(i=firstobs;i<=lastobs;i++){
1.234     brouard  11448:     num[i]=0;
                   11449:     moisnais[i]=0;
                   11450:     annais[i]=0;
                   11451:     moisdc[i]=0;
                   11452:     andc[i]=0;
                   11453:     agedc[i]=0;
                   11454:     cod[i]=0;
                   11455:     weight[i]=1.0; /* Equal weights, 1 by default */
                   11456:   }
1.290     brouard  11457:   mint=matrix(1,maxwav,firstobs,lastobs);
                   11458:   anint=matrix(1,maxwav,firstobs,lastobs);
                   11459:   s=imatrix(1,maxwav+1,firstobs,lastobs); /* s[i][j] health state for wave i and individual j */ 
1.126     brouard  11460:   tab=ivector(1,NCOVMAX);
1.144     brouard  11461:   ncodemax=ivector(1,NCOVMAX); /* Number of code per covariate; if O and 1 only, 2**ncov; V1+V2+V3+V4=>16 */
1.192     brouard  11462:   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  11463: 
1.136     brouard  11464:   /* Reads data from file datafile */
                   11465:   if (readdata(datafile, firstobs, lastobs, &imx)==1)
                   11466:     goto end;
                   11467: 
                   11468:   /* Calculation of the number of parameters from char model */
1.234     brouard  11469:   /*    modelsav=V2+V1+V4+age*V3 strb=age*V3 stra=V2+V1+V4 
1.137     brouard  11470:        k=4 (age*V3) Tvar[k=4]= 3 (from V3) Tag[cptcovage=1]=4
                   11471:        k=3 V4 Tvar[k=3]= 4 (from V4)
                   11472:        k=2 V1 Tvar[k=2]= 1 (from V1)
                   11473:        k=1 Tvar[1]=2 (from V2)
1.234     brouard  11474:   */
                   11475:   
                   11476:   Tvar=ivector(1,NCOVMAX); /* Was 15 changed to NCOVMAX. */
                   11477:   TvarsDind=ivector(1,NCOVMAX); /*  */
                   11478:   TvarsD=ivector(1,NCOVMAX); /*  */
                   11479:   TvarsQind=ivector(1,NCOVMAX); /*  */
                   11480:   TvarsQ=ivector(1,NCOVMAX); /*  */
1.232     brouard  11481:   TvarF=ivector(1,NCOVMAX); /*  */
                   11482:   TvarFind=ivector(1,NCOVMAX); /*  */
                   11483:   TvarV=ivector(1,NCOVMAX); /*  */
                   11484:   TvarVind=ivector(1,NCOVMAX); /*  */
                   11485:   TvarA=ivector(1,NCOVMAX); /*  */
                   11486:   TvarAind=ivector(1,NCOVMAX); /*  */
1.231     brouard  11487:   TvarFD=ivector(1,NCOVMAX); /*  */
                   11488:   TvarFDind=ivector(1,NCOVMAX); /*  */
                   11489:   TvarFQ=ivector(1,NCOVMAX); /*  */
                   11490:   TvarFQind=ivector(1,NCOVMAX); /*  */
                   11491:   TvarVD=ivector(1,NCOVMAX); /*  */
                   11492:   TvarVDind=ivector(1,NCOVMAX); /*  */
                   11493:   TvarVQ=ivector(1,NCOVMAX); /*  */
                   11494:   TvarVQind=ivector(1,NCOVMAX); /*  */
                   11495: 
1.230     brouard  11496:   Tvalsel=vector(1,NCOVMAX); /*  */
1.233     brouard  11497:   Tvarsel=ivector(1,NCOVMAX); /*  */
1.226     brouard  11498:   Typevar=ivector(-1,NCOVMAX); /* -1 to 2 */
                   11499:   Fixed=ivector(-1,NCOVMAX); /* -1 to 3 */
                   11500:   Dummy=ivector(-1,NCOVMAX); /* -1 to 3 */
1.137     brouard  11501:   /*  V2+V1+V4+age*V3 is a model with 4 covariates (3 plus signs). 
                   11502:       For each model-covariate stores the data-covariate id. Tvar[1]=2, Tvar[2]=1, Tvar[3]=4, 
                   11503:       Tvar[4=age*V3] is 3 and 'age' is recorded in Tage.
                   11504:   */
                   11505:   /* For model-covariate k tells which data-covariate to use but
                   11506:     because this model-covariate is a construction we invent a new column
                   11507:     ncovcol + k1
                   11508:     If already ncovcol=4 and model=V2+V1+V1*V4+age*V3
                   11509:     Tvar[3=V1*V4]=4+1 etc */
1.227     brouard  11510:   Tprod=ivector(1,NCOVMAX); /* Gives the k position of the k1 product */
                   11511:   Tposprod=ivector(1,NCOVMAX); /* Gives the k1 product from the k position */
1.137     brouard  11512:   /* Tprod[k1=1]=3(=V1*V4) for V2+V1+V1*V4+age*V3
                   11513:      if  V2+V1+V1*V4+age*V3+V3*V2   TProd[k1=2]=5 (V3*V2)
1.227     brouard  11514:      Tposprod[k]=k1 , Tposprod[3]=1, Tposprod[5]=2 
1.137     brouard  11515:   */
1.145     brouard  11516:   Tvaraff=ivector(1,NCOVMAX); /* Unclear */
                   11517:   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  11518:                            * For V3*V2 (in V2+V1+V1*V4+age*V3+V3*V2), V3*V2 position is 2nd. 
                   11519:                            * Tvard[k1=2][1]=3 (V3) Tvard[k1=2][2]=2(V2) */
1.145     brouard  11520:   Tage=ivector(1,NCOVMAX); /* Gives the covariate id of covariates associated with age: V2 + V1 + age*V4 + V3*age
1.137     brouard  11521:                         4 covariates (3 plus signs)
                   11522:                         Tage[1=V3*age]= 4; Tage[2=age*V4] = 3
                   11523:                      */  
1.230     brouard  11524:   Tmodelind=ivector(1,NCOVMAX);/** gives the k model position of an
1.227     brouard  11525:                                * individual dummy, fixed or varying:
                   11526:                                * Tmodelind[Tvaraff[3]]=9,Tvaraff[1]@9={4,
                   11527:                                * 3, 1, 0, 0, 0, 0, 0, 0},
1.230     brouard  11528:                                * model=V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 , 
                   11529:                                * V1 df, V2 qf, V3 & V4 dv, V5 qv
                   11530:                                * Tmodelind[1]@9={9,0,3,2,}*/
                   11531:   TmodelInvind=ivector(1,NCOVMAX); /* TmodelInvind=Tvar[k]- ncovcol-nqv={5-2-1=2,*/
                   11532:   TmodelInvQind=ivector(1,NCOVMAX);/** gives the k model position of an
1.228     brouard  11533:                                * individual quantitative, fixed or varying:
                   11534:                                * Tmodelqind[1]=1,Tvaraff[1]@9={4,
                   11535:                                * 3, 1, 0, 0, 0, 0, 0, 0},
                   11536:                                * model=V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1*/
1.186     brouard  11537: /* Main decodemodel */
                   11538: 
1.187     brouard  11539: 
1.223     brouard  11540:   if(decodemodel(model, lastobs) == 1) /* In order to get Tvar[k] V4+V3+V5 p Tvar[1]@3  = {4, 3, 5}*/
1.136     brouard  11541:     goto end;
                   11542: 
1.137     brouard  11543:   if((double)(lastobs-imx)/(double)imx > 1.10){
                   11544:     nbwarn++;
                   11545:     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); 
                   11546:     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); 
                   11547:   }
1.136     brouard  11548:     /*  if(mle==1){*/
1.137     brouard  11549:   if (weightopt != 1) { /* Maximisation without weights. We can have weights different from 1 but want no weight*/
                   11550:     for(i=1;i<=imx;i++) weight[i]=1.0; /* changed to imx */
1.136     brouard  11551:   }
                   11552: 
                   11553:     /*-calculation of age at interview from date of interview and age at death -*/
                   11554:   agev=matrix(1,maxwav,1,imx);
                   11555: 
                   11556:   if(calandcheckages(imx, maxwav, &agemin, &agemax, &nberr, &nbwarn) == 1)
                   11557:     goto end;
                   11558: 
1.126     brouard  11559: 
1.136     brouard  11560:   agegomp=(int)agemin;
1.290     brouard  11561:   free_vector(moisnais,firstobs,lastobs);
                   11562:   free_vector(annais,firstobs,lastobs);
1.126     brouard  11563:   /* free_matrix(mint,1,maxwav,1,n);
                   11564:      free_matrix(anint,1,maxwav,1,n);*/
1.215     brouard  11565:   /* free_vector(moisdc,1,n); */
                   11566:   /* free_vector(andc,1,n); */
1.145     brouard  11567:   /* */
                   11568:   
1.126     brouard  11569:   wav=ivector(1,imx);
1.214     brouard  11570:   /* dh=imatrix(1,lastpass-firstpass+1,1,imx); */
                   11571:   /* bh=imatrix(1,lastpass-firstpass+1,1,imx); */
                   11572:   /* mw=imatrix(1,lastpass-firstpass+1,1,imx); */
                   11573:   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.*/
                   11574:   bh=imatrix(1,lastpass-firstpass+2,1,imx);
                   11575:   mw=imatrix(1,lastpass-firstpass+2,1,imx);
1.126     brouard  11576:    
                   11577:   /* Concatenates waves */
1.214     brouard  11578:   /* Concatenates waves: wav[i] is the number of effective (useful waves) of individual i.
                   11579:      Death is a valid wave (if date is known).
                   11580:      mw[mi][i] is the number of (mi=1 to wav[i]) effective wave out of mi of individual i
                   11581:      dh[m][i] or dh[mw[mi][i]][i] is the delay between two effective waves m=mw[mi][i]
                   11582:      and mw[mi+1][i]. dh depends on stepm.
                   11583:   */
                   11584: 
1.126     brouard  11585:   concatwav(wav, dh, bh, mw, s, agedc, agev,  firstpass, lastpass, imx, nlstate, stepm);
1.248     brouard  11586:   /* Concatenates waves */
1.145     brouard  11587:  
1.290     brouard  11588:   free_vector(moisdc,firstobs,lastobs);
                   11589:   free_vector(andc,firstobs,lastobs);
1.215     brouard  11590: 
1.126     brouard  11591:   /* Routine tricode is to calculate cptcoveff (real number of unique covariates) and to associate covariable number and modality */
                   11592:   nbcode=imatrix(0,NCOVMAX,0,NCOVMAX); 
                   11593:   ncodemax[1]=1;
1.145     brouard  11594:   Ndum =ivector(-1,NCOVMAX);  
1.225     brouard  11595:   cptcoveff=0;
1.220     brouard  11596:   if (ncovmodel-nagesqr > 2 ){ /* That is if covariate other than cst, age and age*age */
                   11597:     tricode(&cptcoveff,Tvar,nbcode,imx, Ndum); /**< Fills nbcode[Tvar[j]][l]; */
1.227     brouard  11598:   }
                   11599:   
                   11600:   ncovcombmax=pow(2,cptcoveff);
                   11601:   invalidvarcomb=ivector(1, ncovcombmax); 
                   11602:   for(i=1;i<ncovcombmax;i++)
                   11603:     invalidvarcomb[i]=0;
                   11604:   
1.211     brouard  11605:   /* Nbcode gives the value of the lth modality (currently 1 to 2) of jth covariate, in
1.186     brouard  11606:      V2+V1*age, there are 3 covariates Tvar[2]=1 (V1).*/
1.211     brouard  11607:   /* 1 to ncodemax[j] which is the maximum value of this jth covariate */
1.227     brouard  11608:   
1.200     brouard  11609:   /*  codtab=imatrix(1,100,1,10);*/ /* codtab[h,k]=( (h-1) - mod(k-1,2**(k-1) )/2**(k-1) */
1.198     brouard  11610:   /*printf(" codtab[1,1],codtab[100,10]=%d,%d\n", codtab[1][1],codtabm(100,10));*/
1.186     brouard  11611:   /* codtab gives the value 1 or 2 of the hth combination of k covariates (1 or 2).*/
1.211     brouard  11612:   /* nbcode[Tvaraff[j]][codtabm(h,j)]) : if there are only 2 modalities for a covariate j, 
                   11613:    * codtabm(h,j) gives its value classified at position h and nbcode gives how it is coded 
                   11614:    * (currently 0 or 1) in the data.
                   11615:    * In a loop on h=1 to 2**k, and a loop on j (=1 to k), we get the value of 
                   11616:    * corresponding modality (h,j).
                   11617:    */
                   11618: 
1.145     brouard  11619:   h=0;
                   11620:   /*if (cptcovn > 0) */
1.126     brouard  11621:   m=pow(2,cptcoveff);
                   11622:  
1.144     brouard  11623:          /**< codtab(h,k)  k   = codtab[h,k]=( (h-1) - mod(k-1,2**(k-1) )/2**(k-1) + 1
1.211     brouard  11624:           * For k=4 covariates, h goes from 1 to m=2**k
                   11625:           * codtabm(h,k)=  (1 & (h-1) >> (k-1)) + 1;
                   11626:            * #define codtabm(h,k)  (1 & (h-1) >> (k-1))+1
1.186     brouard  11627:           *     h\k   1     2     3     4
1.143     brouard  11628:           *______________________________  
                   11629:           *     1 i=1 1 i=1 1 i=1 1 i=1 1
                   11630:           *     2     2     1     1     1
                   11631:           *     3 i=2 1     2     1     1
                   11632:           *     4     2     2     1     1
                   11633:           *     5 i=3 1 i=2 1     2     1
                   11634:           *     6     2     1     2     1
                   11635:           *     7 i=4 1     2     2     1
                   11636:           *     8     2     2     2     1
1.197     brouard  11637:           *     9 i=5 1 i=3 1 i=2 1     2
                   11638:           *    10     2     1     1     2
                   11639:           *    11 i=6 1     2     1     2
                   11640:           *    12     2     2     1     2
                   11641:           *    13 i=7 1 i=4 1     2     2    
                   11642:           *    14     2     1     2     2
                   11643:           *    15 i=8 1     2     2     2
                   11644:           *    16     2     2     2     2
1.143     brouard  11645:           */
1.212     brouard  11646:   /* How to do the opposite? From combination h (=1 to 2**k) how to get the value on the covariates? */
1.211     brouard  11647:      /* from h=5 and m, we get then number of covariates k=log(m)/log(2)=4
                   11648:      * and the value of each covariate?
                   11649:      * V1=1, V2=1, V3=2, V4=1 ?
                   11650:      * h-1=4 and 4 is 0100 or reverse 0010, and +1 is 1121 ok.
                   11651:      * h=6, 6-1=5, 5 is 0101, 1010, 2121, V1=2nd, V2=1st, V3=2nd, V4=1st.
                   11652:      * In order to get the real value in the data, we use nbcode
                   11653:      * nbcode[Tvar[3][2nd]]=1 and nbcode[Tvar[4][1]]=0
                   11654:      * We are keeping this crazy system in order to be able (in the future?) 
                   11655:      * to have more than 2 values (0 or 1) for a covariate.
                   11656:      * #define codtabm(h,k)  (1 & (h-1) >> (k-1))+1
                   11657:      * h=6, k=2? h-1=5=0101, reverse 1010, +1=2121, k=2nd position: value is 1: codtabm(6,2)=1
                   11658:      *              bbbbbbbb
                   11659:      *              76543210     
                   11660:      *   h-1        00000101 (6-1=5)
1.219     brouard  11661:      *(h-1)>>(k-1)= 00000010 >> (2-1) = 1 right shift
1.211     brouard  11662:      *           &
                   11663:      *     1        00000001 (1)
1.219     brouard  11664:      *              00000000        = 1 & ((h-1) >> (k-1))
                   11665:      *          +1= 00000001 =1 
1.211     brouard  11666:      *
                   11667:      * h=14, k=3 => h'=h-1=13, k'=k-1=2
                   11668:      *          h'      1101 =2^3+2^2+0x2^1+2^0
                   11669:      *    >>k'            11
                   11670:      *          &   00000001
                   11671:      *            = 00000001
                   11672:      *      +1    = 00000010=2    =  codtabm(14,3)   
                   11673:      * Reverse h=6 and m=16?
                   11674:      * cptcoveff=log(16)/log(2)=4 covariate: 6-1=5=0101 reversed=1010 +1=2121 =>V1=2, V2=1, V3=2, V4=1.
                   11675:      * for (j=1 to cptcoveff) Vj=decodtabm(j,h,cptcoveff)
                   11676:      * decodtabm(h,j,cptcoveff)= (((h-1) >> (j-1)) & 1) +1 
                   11677:      * decodtabm(h,j,cptcoveff)= (h <= (1<<cptcoveff)?(((h-1) >> (j-1)) & 1) +1 : -1)
                   11678:      * V3=decodtabm(14,3,2**4)=2
                   11679:      *          h'=13   1101 =2^3+2^2+0x2^1+2^0
                   11680:      *(h-1) >> (j-1)    0011 =13 >> 2
                   11681:      *          &1 000000001
                   11682:      *           = 000000001
                   11683:      *         +1= 000000010 =2
                   11684:      *                  2211
                   11685:      *                  V1=1+1, V2=0+1, V3=1+1, V4=1+1
                   11686:      *                  V3=2
1.220     brouard  11687:                 * codtabm and decodtabm are identical
1.211     brouard  11688:      */
                   11689: 
1.145     brouard  11690: 
                   11691:  free_ivector(Ndum,-1,NCOVMAX);
                   11692: 
                   11693: 
1.126     brouard  11694:     
1.186     brouard  11695:   /* Initialisation of ----------- gnuplot -------------*/
1.126     brouard  11696:   strcpy(optionfilegnuplot,optionfilefiname);
                   11697:   if(mle==-3)
1.201     brouard  11698:     strcat(optionfilegnuplot,"-MORT_");
1.126     brouard  11699:   strcat(optionfilegnuplot,".gp");
                   11700: 
                   11701:   if((ficgp=fopen(optionfilegnuplot,"w"))==NULL) {
                   11702:     printf("Problem with file %s",optionfilegnuplot);
                   11703:   }
                   11704:   else{
1.204     brouard  11705:     fprintf(ficgp,"\n# IMaCh-%s\n", version); 
1.126     brouard  11706:     fprintf(ficgp,"# %s\n", optionfilegnuplot); 
1.141     brouard  11707:     //fprintf(ficgp,"set missing 'NaNq'\n");
                   11708:     fprintf(ficgp,"set datafile missing 'NaNq'\n");
1.126     brouard  11709:   }
                   11710:   /*  fclose(ficgp);*/
1.186     brouard  11711: 
                   11712: 
                   11713:   /* Initialisation of --------- index.htm --------*/
1.126     brouard  11714: 
                   11715:   strcpy(optionfilehtm,optionfilefiname); /* Main html file */
                   11716:   if(mle==-3)
1.201     brouard  11717:     strcat(optionfilehtm,"-MORT_");
1.126     brouard  11718:   strcat(optionfilehtm,".htm");
                   11719:   if((fichtm=fopen(optionfilehtm,"w"))==NULL)    {
1.131     brouard  11720:     printf("Problem with %s \n",optionfilehtm);
                   11721:     exit(0);
1.126     brouard  11722:   }
                   11723: 
                   11724:   strcpy(optionfilehtmcov,optionfilefiname); /* Only for matrix of covariance */
                   11725:   strcat(optionfilehtmcov,"-cov.htm");
                   11726:   if((fichtmcov=fopen(optionfilehtmcov,"w"))==NULL)    {
                   11727:     printf("Problem with %s \n",optionfilehtmcov), exit(0);
                   11728:   }
                   11729:   else{
                   11730:   fprintf(fichtmcov,"<html><head>\n<title>IMaCh Cov %s</title></head>\n <body><font size=\"2\">%s <br> %s</font> \
                   11731: <hr size=\"2\" color=\"#EC5E5E\"> \n\
1.204     brouard  11732: Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=1+age+%s<br>\n",\
1.126     brouard  11733:          optionfilehtmcov,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model);
                   11734:   }
                   11735: 
1.213     brouard  11736:   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  11737: <hr size=\"2\" color=\"#EC5E5E\"> \n\
                   11738: <font size=\"2\">IMaCh-%s <br> %s</font> \
1.126     brouard  11739: <hr size=\"2\" color=\"#EC5E5E\"> \n\
1.204     brouard  11740: Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=1+age+%s<br>\n\
1.126     brouard  11741: \n\
                   11742: <hr  size=\"2\" color=\"#EC5E5E\">\
                   11743:  <ul><li><h4>Parameter files</h4>\n\
                   11744:  - Parameter file: <a href=\"%s.%s\">%s.%s</a><br>\n\
                   11745:  - Copy of the parameter file: <a href=\"o%s\">o%s</a><br>\n\
                   11746:  - Log file of the run: <a href=\"%s\">%s</a><br>\n\
                   11747:  - Gnuplot file name: <a href=\"%s\">%s</a><br>\n\
                   11748:  - Date and time at start: %s</ul>\n",\
                   11749:          optionfilehtm,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model,\
                   11750:          optionfilefiname,optionfilext,optionfilefiname,optionfilext,\
                   11751:          fileres,fileres,\
                   11752:          filelog,filelog,optionfilegnuplot,optionfilegnuplot,strstart);
                   11753:   fflush(fichtm);
                   11754: 
                   11755:   strcpy(pathr,path);
                   11756:   strcat(pathr,optionfilefiname);
1.184     brouard  11757: #ifdef WIN32
                   11758:   _chdir(optionfilefiname); /* Move to directory named optionfile */
                   11759: #else
1.126     brouard  11760:   chdir(optionfilefiname); /* Move to directory named optionfile */
1.184     brouard  11761: #endif
                   11762:          
1.126     brouard  11763:   
1.220     brouard  11764:   /* Calculates basic frequencies. Computes observed prevalence at single age 
                   11765:                 and for any valid combination of covariates
1.126     brouard  11766:      and prints on file fileres'p'. */
1.251     brouard  11767:   freqsummary(fileres, p, pstart, agemin, agemax, s, agev, nlstate, imx, Tvaraff, invalidvarcomb, nbcode, ncodemax,mint,anint,strstart, \
1.227     brouard  11768:              firstpass, lastpass,  stepm,  weightopt, model);
1.126     brouard  11769: 
                   11770:   fprintf(fichtm,"\n");
1.286     brouard  11771:   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  11772:          ftol, stepm);
                   11773:   fprintf(fichtm,"\n<li>Number of fixed dummy covariates: ncovcol=%d ", ncovcol);
                   11774:   ncurrv=1;
                   11775:   for(i=ncurrv; i <=ncovcol; i++) fprintf(fichtm,"V%d ", i);
                   11776:   fprintf(fichtm,"\n<li> Number of fixed quantitative variables: nqv=%d ", nqv); 
                   11777:   ncurrv=i;
                   11778:   for(i=ncurrv; i <=ncurrv-1+nqv; i++) fprintf(fichtm,"V%d ", i);
1.290     brouard  11779:   fprintf(fichtm,"\n<li> Number of time varying (wave varying) dummy covariates: ntv=%d ", ntv);
1.274     brouard  11780:   ncurrv=i;
                   11781:   for(i=ncurrv; i <=ncurrv-1+ntv; i++) fprintf(fichtm,"V%d ", i);
1.290     brouard  11782:   fprintf(fichtm,"\n<li>Number of time varying  quantitative covariates: nqtv=%d ", nqtv);
1.274     brouard  11783:   ncurrv=i;
                   11784:   for(i=ncurrv; i <=ncurrv-1+nqtv; i++) fprintf(fichtm,"V%d ", i);
                   11785:   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", \
                   11786:           nlstate, ndeath, maxwav, mle, weightopt);
                   11787: 
                   11788:   fprintf(fichtm,"<h4> Diagram of states <a href=\"%s_.svg\">%s_.svg</a></h4> \n\
                   11789: <img src=\"%s_.svg\">", subdirf2(optionfilefiname,"D_"),subdirf2(optionfilefiname,"D_"),subdirf2(optionfilefiname,"D_"));
                   11790: 
                   11791:   
                   11792:   fprintf(fichtm,"\n<h4>Some descriptive statistics </h4>\n<br>Total number of observations=%d <br>\n\
1.126     brouard  11793: Youngest age at first (selected) pass %.2f, oldest age %.2f<br>\n\
                   11794: Interval (in months) between two waves: Min=%d Max=%d Mean=%.2lf<br>\n",\
1.274     brouard  11795:   imx,agemin,agemax,jmin,jmax,jmean);
1.126     brouard  11796:   pmmij= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
1.268     brouard  11797:   oldms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
                   11798:   newms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
                   11799:   savms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
                   11800:   oldm=oldms; newm=newms; savm=savms; /* Keeps fixed addresses to free */
1.218     brouard  11801: 
1.126     brouard  11802:   /* For Powell, parameters are in a vector p[] starting at p[1]
                   11803:      so we point p on param[1][1] so that p[1] maps on param[1][1][1] */
                   11804:   p=param[1][1]; /* *(*(*(param +1)+1)+0) */
                   11805: 
                   11806:   globpr=0; /* To get the number ipmx of contributions and the sum of weights*/
1.186     brouard  11807:   /* For mortality only */
1.126     brouard  11808:   if (mle==-3){
1.136     brouard  11809:     ximort=matrix(1,NDIM,1,NDIM); 
1.248     brouard  11810:     for(i=1;i<=NDIM;i++)
                   11811:       for(j=1;j<=NDIM;j++)
                   11812:        ximort[i][j]=0.;
1.186     brouard  11813:     /*     ximort=gsl_matrix_alloc(1,NDIM,1,NDIM); */
1.290     brouard  11814:     cens=ivector(firstobs,lastobs);
                   11815:     ageexmed=vector(firstobs,lastobs);
                   11816:     agecens=vector(firstobs,lastobs);
                   11817:     dcwave=ivector(firstobs,lastobs);
1.223     brouard  11818:                
1.126     brouard  11819:     for (i=1; i<=imx; i++){
                   11820:       dcwave[i]=-1;
                   11821:       for (m=firstpass; m<=lastpass; m++)
1.226     brouard  11822:        if (s[m][i]>nlstate) {
                   11823:          dcwave[i]=m;
                   11824:          /*    printf("i=%d j=%d s=%d dcwave=%d\n",i,j, s[j][i],dcwave[i]);*/
                   11825:          break;
                   11826:        }
1.126     brouard  11827:     }
1.226     brouard  11828:     
1.126     brouard  11829:     for (i=1; i<=imx; i++) {
                   11830:       if (wav[i]>0){
1.226     brouard  11831:        ageexmed[i]=agev[mw[1][i]][i];
                   11832:        j=wav[i];
                   11833:        agecens[i]=1.; 
                   11834:        
                   11835:        if (ageexmed[i]> 1 && wav[i] > 0){
                   11836:          agecens[i]=agev[mw[j][i]][i];
                   11837:          cens[i]= 1;
                   11838:        }else if (ageexmed[i]< 1) 
                   11839:          cens[i]= -1;
                   11840:        if (agedc[i]< AGESUP && agedc[i]>1 && dcwave[i]>firstpass && dcwave[i]<=lastpass)
                   11841:          cens[i]=0 ;
1.126     brouard  11842:       }
                   11843:       else cens[i]=-1;
                   11844:     }
                   11845:     
                   11846:     for (i=1;i<=NDIM;i++) {
                   11847:       for (j=1;j<=NDIM;j++)
1.226     brouard  11848:        ximort[i][j]=(i == j ? 1.0 : 0.0);
1.126     brouard  11849:     }
                   11850:     
1.145     brouard  11851:     /*p[1]=0.0268; p[NDIM]=0.083;*/
1.126     brouard  11852:     /*printf("%lf %lf", p[1], p[2]);*/
                   11853:     
                   11854:     
1.136     brouard  11855: #ifdef GSL
                   11856:     printf("GSL optimization\n");  fprintf(ficlog,"Powell\n");
1.162     brouard  11857: #else
1.126     brouard  11858:     printf("Powell\n");  fprintf(ficlog,"Powell\n");
1.136     brouard  11859: #endif
1.201     brouard  11860:     strcpy(filerespow,"POW-MORT_"); 
                   11861:     strcat(filerespow,fileresu);
1.126     brouard  11862:     if((ficrespow=fopen(filerespow,"w"))==NULL) {
                   11863:       printf("Problem with resultfile: %s\n", filerespow);
                   11864:       fprintf(ficlog,"Problem with resultfile: %s\n", filerespow);
                   11865:     }
1.136     brouard  11866: #ifdef GSL
                   11867:     fprintf(ficrespow,"# GSL optimization\n# iter -2*LL");
1.162     brouard  11868: #else
1.126     brouard  11869:     fprintf(ficrespow,"# Powell\n# iter -2*LL");
1.136     brouard  11870: #endif
1.126     brouard  11871:     /*  for (i=1;i<=nlstate;i++)
                   11872:        for(j=1;j<=nlstate+ndeath;j++)
                   11873:        if(j!=i)fprintf(ficrespow," p%1d%1d",i,j);
                   11874:     */
                   11875:     fprintf(ficrespow,"\n");
1.136     brouard  11876: #ifdef GSL
                   11877:     /* gsl starts here */ 
                   11878:     T = gsl_multimin_fminimizer_nmsimplex;
                   11879:     gsl_multimin_fminimizer *sfm = NULL;
                   11880:     gsl_vector *ss, *x;
                   11881:     gsl_multimin_function minex_func;
                   11882: 
                   11883:     /* Initial vertex size vector */
                   11884:     ss = gsl_vector_alloc (NDIM);
                   11885:     
                   11886:     if (ss == NULL){
                   11887:       GSL_ERROR_VAL ("failed to allocate space for ss", GSL_ENOMEM, 0);
                   11888:     }
                   11889:     /* Set all step sizes to 1 */
                   11890:     gsl_vector_set_all (ss, 0.001);
                   11891: 
                   11892:     /* Starting point */
1.126     brouard  11893:     
1.136     brouard  11894:     x = gsl_vector_alloc (NDIM);
                   11895:     
                   11896:     if (x == NULL){
                   11897:       gsl_vector_free(ss);
                   11898:       GSL_ERROR_VAL ("failed to allocate space for x", GSL_ENOMEM, 0);
                   11899:     }
                   11900:   
                   11901:     /* Initialize method and iterate */
                   11902:     /*     p[1]=0.0268; p[NDIM]=0.083; */
1.186     brouard  11903:     /*     gsl_vector_set(x, 0, 0.0268); */
                   11904:     /*     gsl_vector_set(x, 1, 0.083); */
1.136     brouard  11905:     gsl_vector_set(x, 0, p[1]);
                   11906:     gsl_vector_set(x, 1, p[2]);
                   11907: 
                   11908:     minex_func.f = &gompertz_f;
                   11909:     minex_func.n = NDIM;
                   11910:     minex_func.params = (void *)&p; /* ??? */
                   11911:     
                   11912:     sfm = gsl_multimin_fminimizer_alloc (T, NDIM);
                   11913:     gsl_multimin_fminimizer_set (sfm, &minex_func, x, ss);
                   11914:     
                   11915:     printf("Iterations beginning .....\n\n");
                   11916:     printf("Iter. #    Intercept       Slope     -Log Likelihood     Simplex size\n");
                   11917: 
                   11918:     iteri=0;
                   11919:     while (rval == GSL_CONTINUE){
                   11920:       iteri++;
                   11921:       status = gsl_multimin_fminimizer_iterate(sfm);
                   11922:       
                   11923:       if (status) printf("error: %s\n", gsl_strerror (status));
                   11924:       fflush(0);
                   11925:       
                   11926:       if (status) 
                   11927:         break;
                   11928:       
                   11929:       rval = gsl_multimin_test_size (gsl_multimin_fminimizer_size (sfm), 1e-6);
                   11930:       ssval = gsl_multimin_fminimizer_size (sfm);
                   11931:       
                   11932:       if (rval == GSL_SUCCESS)
                   11933:         printf ("converged to a local maximum at\n");
                   11934:       
                   11935:       printf("%5d ", iteri);
                   11936:       for (it = 0; it < NDIM; it++){
                   11937:        printf ("%10.5f ", gsl_vector_get (sfm->x, it));
                   11938:       }
                   11939:       printf("f() = %-10.5f ssize = %.7f\n", sfm->fval, ssval);
                   11940:     }
                   11941:     
                   11942:     printf("\n\n Please note: Program should be run many times with varying starting points to detemine global maximum\n\n");
                   11943:     
                   11944:     gsl_vector_free(x); /* initial values */
                   11945:     gsl_vector_free(ss); /* inital step size */
                   11946:     for (it=0; it<NDIM; it++){
                   11947:       p[it+1]=gsl_vector_get(sfm->x,it);
                   11948:       fprintf(ficrespow," %.12lf", p[it]);
                   11949:     }
                   11950:     gsl_multimin_fminimizer_free (sfm); /* p *(sfm.x.data) et p *(sfm.x.data+1)  */
                   11951: #endif
                   11952: #ifdef POWELL
                   11953:      powell(p,ximort,NDIM,ftol,&iter,&fret,gompertz);
                   11954: #endif  
1.126     brouard  11955:     fclose(ficrespow);
                   11956:     
1.203     brouard  11957:     hesscov(matcov, hess, p, NDIM, delti, 1e-4, gompertz); 
1.126     brouard  11958: 
                   11959:     for(i=1; i <=NDIM; i++)
                   11960:       for(j=i+1;j<=NDIM;j++)
1.220     brouard  11961:                                matcov[i][j]=matcov[j][i];
1.126     brouard  11962:     
                   11963:     printf("\nCovariance matrix\n ");
1.203     brouard  11964:     fprintf(ficlog,"\nCovariance matrix\n ");
1.126     brouard  11965:     for(i=1; i <=NDIM; i++) {
                   11966:       for(j=1;j<=NDIM;j++){ 
1.220     brouard  11967:                                printf("%f ",matcov[i][j]);
                   11968:                                fprintf(ficlog,"%f ",matcov[i][j]);
1.126     brouard  11969:       }
1.203     brouard  11970:       printf("\n ");  fprintf(ficlog,"\n ");
1.126     brouard  11971:     }
                   11972:     
                   11973:     printf("iter=%d MLE=%f Eq=%lf*exp(%lf*(age-%d))\n",iter,-gompertz(p),p[1],p[2],agegomp);
1.193     brouard  11974:     for (i=1;i<=NDIM;i++) {
1.126     brouard  11975:       printf("%f [%f ; %f]\n",p[i],p[i]-2*sqrt(matcov[i][i]),p[i]+2*sqrt(matcov[i][i]));
1.193     brouard  11976:       fprintf(ficlog,"%f [%f ; %f]\n",p[i],p[i]-2*sqrt(matcov[i][i]),p[i]+2*sqrt(matcov[i][i]));
                   11977:     }
1.126     brouard  11978:     lsurv=vector(1,AGESUP);
                   11979:     lpop=vector(1,AGESUP);
                   11980:     tpop=vector(1,AGESUP);
                   11981:     lsurv[agegomp]=100000;
                   11982:     
                   11983:     for (k=agegomp;k<=AGESUP;k++) {
                   11984:       agemortsup=k;
                   11985:       if (p[1]*exp(p[2]*(k-agegomp))>1) break;
                   11986:     }
                   11987:     
                   11988:     for (k=agegomp;k<agemortsup;k++)
                   11989:       lsurv[k+1]=lsurv[k]-lsurv[k]*(p[1]*exp(p[2]*(k-agegomp)));
                   11990:     
                   11991:     for (k=agegomp;k<agemortsup;k++){
                   11992:       lpop[k]=(lsurv[k]+lsurv[k+1])/2.;
                   11993:       sumlpop=sumlpop+lpop[k];
                   11994:     }
                   11995:     
                   11996:     tpop[agegomp]=sumlpop;
                   11997:     for (k=agegomp;k<(agemortsup-3);k++){
                   11998:       /*  tpop[k+1]=2;*/
                   11999:       tpop[k+1]=tpop[k]-lpop[k];
                   12000:     }
                   12001:     
                   12002:     
                   12003:     printf("\nAge   lx     qx    dx    Lx     Tx     e(x)\n");
                   12004:     for (k=agegomp;k<(agemortsup-2);k++) 
                   12005:       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]);
                   12006:     
                   12007:     
                   12008:     replace_back_to_slash(pathc,pathcd); /* Even gnuplot wants a / */
1.220     brouard  12009:                ageminpar=50;
                   12010:                agemaxpar=100;
1.194     brouard  12011:     if(ageminpar == AGEOVERFLOW ||agemaxpar == AGEOVERFLOW){
                   12012:        printf("Warning! Error in gnuplot file with ageminpar %f or agemaxpar %f overflow\n\
                   12013: This is probably because your parameter file doesn't \n  contain the exact number of lines (or columns) corresponding to your model line.\n\
                   12014: Please run with mle=-1 to get a correct covariance matrix.\n",ageminpar,agemaxpar);
                   12015:        fprintf(ficlog,"Warning! Error in gnuplot file with ageminpar %f or agemaxpar %f overflow\n\
                   12016: This is probably because your parameter file doesn't \n  contain the exact number of lines (or columns) corresponding to your model line.\n\
                   12017: Please run with mle=-1 to get a correct covariance matrix.\n",ageminpar,agemaxpar);
1.220     brouard  12018:     }else{
                   12019:                        printf("Warning! ageminpar %f and agemaxpar %f have been fixed because for simplification until it is fixed...\n\n",ageminpar,agemaxpar);
                   12020:                        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  12021:       printinggnuplotmort(fileresu, optionfilefiname,ageminpar,agemaxpar,fage, pathc,p);
1.220     brouard  12022:                }
1.201     brouard  12023:     printinghtmlmort(fileresu,title,datafile, firstpass, lastpass, \
1.126     brouard  12024:                     stepm, weightopt,\
                   12025:                     model,imx,p,matcov,agemortsup);
                   12026:     
                   12027:     free_vector(lsurv,1,AGESUP);
                   12028:     free_vector(lpop,1,AGESUP);
                   12029:     free_vector(tpop,1,AGESUP);
1.220     brouard  12030:     free_matrix(ximort,1,NDIM,1,NDIM);
1.290     brouard  12031:     free_ivector(dcwave,firstobs,lastobs);
                   12032:     free_vector(agecens,firstobs,lastobs);
                   12033:     free_vector(ageexmed,firstobs,lastobs);
                   12034:     free_ivector(cens,firstobs,lastobs);
1.220     brouard  12035: #ifdef GSL
1.136     brouard  12036: #endif
1.186     brouard  12037:   } /* Endof if mle==-3 mortality only */
1.205     brouard  12038:   /* Standard  */
                   12039:   else{ /* For mle !=- 3, could be 0 or 1 or 4 etc. */
                   12040:     globpr=0;/* Computes sum of likelihood for globpr=1 and funcone */
                   12041:     /* Computes likelihood for initial parameters, uses funcone to compute gpimx and gsw */
1.132     brouard  12042:     likelione(ficres, p, npar, nlstate, &globpr, &ipmx, &sw, &fretone, funcone); /* Prints the contributions to the likelihood */
1.126     brouard  12043:     printf("First Likeli=%12.6f ipmx=%ld sw=%12.6f",fretone,ipmx,sw);
                   12044:     for (k=1; k<=npar;k++)
                   12045:       printf(" %d %8.5f",k,p[k]);
                   12046:     printf("\n");
1.205     brouard  12047:     if(mle>=1){ /* Could be 1 or 2, Real Maximization */
                   12048:       /* mlikeli uses func not funcone */
1.247     brouard  12049:       /* for(i=1;i<nlstate;i++){ */
                   12050:       /*       /\*reducing xi for 1 to npar to 1 to ncovmodel; *\/ */
                   12051:       /*    mlikeli(ficres,p, ncovmodel, ncovmodel, nlstate, ftol, funcnoprod); */
                   12052:       /* } */
1.205     brouard  12053:       mlikeli(ficres,p, npar, ncovmodel, nlstate, ftol, func);
                   12054:     }
                   12055:     if(mle==0) {/* No optimization, will print the likelihoods for the datafile */
                   12056:       globpr=0;/* Computes sum of likelihood for globpr=1 and funcone */
                   12057:       /* Computes likelihood for initial parameters, uses funcone to compute gpimx and gsw */
                   12058:       likelione(ficres, p, npar, nlstate, &globpr, &ipmx, &sw, &fretone, funcone); /* Prints the contributions to the likelihood */
                   12059:     }
                   12060:     globpr=1; /* again, to print the individual contributions using computed gpimx and gsw */
1.126     brouard  12061:     likelione(ficres, p, npar, nlstate, &globpr, &ipmx, &sw, &fretone, funcone); /* Prints the contributions to the likelihood */
                   12062:     printf("Second Likeli=%12.6f ipmx=%ld sw=%12.6f",fretone,ipmx,sw);
                   12063:     for (k=1; k<=npar;k++)
                   12064:       printf(" %d %8.5f",k,p[k]);
                   12065:     printf("\n");
                   12066:     
                   12067:     /*--------- results files --------------*/
1.283     brouard  12068:     /* 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  12069:     
                   12070:     
                   12071:     fprintf(ficres,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
                   12072:     printf("# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
                   12073:     fprintf(ficlog,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
                   12074:     for(i=1,jk=1; i <=nlstate; i++){
                   12075:       for(k=1; k <=(nlstate+ndeath); k++){
1.225     brouard  12076:        if (k != i) {
                   12077:          printf("%d%d ",i,k);
                   12078:          fprintf(ficlog,"%d%d ",i,k);
                   12079:          fprintf(ficres,"%1d%1d ",i,k);
                   12080:          for(j=1; j <=ncovmodel; j++){
                   12081:            printf("%12.7f ",p[jk]);
                   12082:            fprintf(ficlog,"%12.7f ",p[jk]);
                   12083:            fprintf(ficres,"%12.7f ",p[jk]);
                   12084:            jk++; 
                   12085:          }
                   12086:          printf("\n");
                   12087:          fprintf(ficlog,"\n");
                   12088:          fprintf(ficres,"\n");
                   12089:        }
1.126     brouard  12090:       }
                   12091:     }
1.203     brouard  12092:     if(mle != 0){
                   12093:       /* Computing hessian and covariance matrix only at a peak of the Likelihood, that is after optimization */
1.126     brouard  12094:       ftolhess=ftol; /* Usually correct */
1.203     brouard  12095:       hesscov(matcov, hess, p, npar, delti, ftolhess, func);
                   12096:       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");
                   12097:       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");
                   12098:       for(i=1,jk=1; i <=nlstate; i++){
1.225     brouard  12099:        for(k=1; k <=(nlstate+ndeath); k++){
                   12100:          if (k != i) {
                   12101:            printf("%d%d ",i,k);
                   12102:            fprintf(ficlog,"%d%d ",i,k);
                   12103:            for(j=1; j <=ncovmodel; j++){
                   12104:              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]));
                   12105:              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]));
                   12106:              jk++; 
                   12107:            }
                   12108:            printf("\n");
                   12109:            fprintf(ficlog,"\n");
                   12110:          }
                   12111:        }
1.193     brouard  12112:       }
1.203     brouard  12113:     } /* end of hesscov and Wald tests */
1.225     brouard  12114:     
1.203     brouard  12115:     /*  */
1.126     brouard  12116:     fprintf(ficres,"# Scales (for hessian or gradient estimation)\n");
                   12117:     printf("# Scales (for hessian or gradient estimation)\n");
                   12118:     fprintf(ficlog,"# Scales (for hessian or gradient estimation)\n");
                   12119:     for(i=1,jk=1; i <=nlstate; i++){
                   12120:       for(j=1; j <=nlstate+ndeath; j++){
1.225     brouard  12121:        if (j!=i) {
                   12122:          fprintf(ficres,"%1d%1d",i,j);
                   12123:          printf("%1d%1d",i,j);
                   12124:          fprintf(ficlog,"%1d%1d",i,j);
                   12125:          for(k=1; k<=ncovmodel;k++){
                   12126:            printf(" %.5e",delti[jk]);
                   12127:            fprintf(ficlog," %.5e",delti[jk]);
                   12128:            fprintf(ficres," %.5e",delti[jk]);
                   12129:            jk++;
                   12130:          }
                   12131:          printf("\n");
                   12132:          fprintf(ficlog,"\n");
                   12133:          fprintf(ficres,"\n");
                   12134:        }
1.126     brouard  12135:       }
                   12136:     }
                   12137:     
                   12138:     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  12139:     if(mle >= 1) /* To big for the screen */
1.126     brouard  12140:       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");
                   12141:     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");
                   12142:     /* # 121 Var(a12)\n\ */
                   12143:     /* # 122 Cov(b12,a12) Var(b12)\n\ */
                   12144:     /* # 131 Cov(a13,a12) Cov(a13,b12, Var(a13)\n\ */
                   12145:     /* # 132 Cov(b13,a12) Cov(b13,b12, Cov(b13,a13) Var(b13)\n\ */
                   12146:     /* # 212 Cov(a21,a12) Cov(a21,b12, Cov(a21,a13) Cov(a21,b13) Var(a21)\n\ */
                   12147:     /* # 212 Cov(b21,a12) Cov(b21,b12, Cov(b21,a13) Cov(b21,b13) Cov(b21,a21) Var(b21)\n\ */
                   12148:     /* # 232 Cov(a23,a12) Cov(a23,b12, Cov(a23,a13) Cov(a23,b13) Cov(a23,a21) Cov(a23,b21) Var(a23)\n\ */
                   12149:     /* # 232 Cov(b23,a12) Cov(b23,b12) ... Var (b23)\n" */
                   12150:     
                   12151:     
                   12152:     /* Just to have a covariance matrix which will be more understandable
                   12153:        even is we still don't want to manage dictionary of variables
                   12154:     */
                   12155:     for(itimes=1;itimes<=2;itimes++){
                   12156:       jj=0;
                   12157:       for(i=1; i <=nlstate; i++){
1.225     brouard  12158:        for(j=1; j <=nlstate+ndeath; j++){
                   12159:          if(j==i) continue;
                   12160:          for(k=1; k<=ncovmodel;k++){
                   12161:            jj++;
                   12162:            ca[0]= k+'a'-1;ca[1]='\0';
                   12163:            if(itimes==1){
                   12164:              if(mle>=1)
                   12165:                printf("#%1d%1d%d",i,j,k);
                   12166:              fprintf(ficlog,"#%1d%1d%d",i,j,k);
                   12167:              fprintf(ficres,"#%1d%1d%d",i,j,k);
                   12168:            }else{
                   12169:              if(mle>=1)
                   12170:                printf("%1d%1d%d",i,j,k);
                   12171:              fprintf(ficlog,"%1d%1d%d",i,j,k);
                   12172:              fprintf(ficres,"%1d%1d%d",i,j,k);
                   12173:            }
                   12174:            ll=0;
                   12175:            for(li=1;li <=nlstate; li++){
                   12176:              for(lj=1;lj <=nlstate+ndeath; lj++){
                   12177:                if(lj==li) continue;
                   12178:                for(lk=1;lk<=ncovmodel;lk++){
                   12179:                  ll++;
                   12180:                  if(ll<=jj){
                   12181:                    cb[0]= lk +'a'-1;cb[1]='\0';
                   12182:                    if(ll<jj){
                   12183:                      if(itimes==1){
                   12184:                        if(mle>=1)
                   12185:                          printf(" Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
                   12186:                        fprintf(ficlog," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
                   12187:                        fprintf(ficres," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
                   12188:                      }else{
                   12189:                        if(mle>=1)
                   12190:                          printf(" %.5e",matcov[jj][ll]); 
                   12191:                        fprintf(ficlog," %.5e",matcov[jj][ll]); 
                   12192:                        fprintf(ficres," %.5e",matcov[jj][ll]); 
                   12193:                      }
                   12194:                    }else{
                   12195:                      if(itimes==1){
                   12196:                        if(mle>=1)
                   12197:                          printf(" Var(%s%1d%1d)",ca,i,j);
                   12198:                        fprintf(ficlog," Var(%s%1d%1d)",ca,i,j);
                   12199:                        fprintf(ficres," Var(%s%1d%1d)",ca,i,j);
                   12200:                      }else{
                   12201:                        if(mle>=1)
                   12202:                          printf(" %.7e",matcov[jj][ll]); 
                   12203:                        fprintf(ficlog," %.7e",matcov[jj][ll]); 
                   12204:                        fprintf(ficres," %.7e",matcov[jj][ll]); 
                   12205:                      }
                   12206:                    }
                   12207:                  }
                   12208:                } /* end lk */
                   12209:              } /* end lj */
                   12210:            } /* end li */
                   12211:            if(mle>=1)
                   12212:              printf("\n");
                   12213:            fprintf(ficlog,"\n");
                   12214:            fprintf(ficres,"\n");
                   12215:            numlinepar++;
                   12216:          } /* end k*/
                   12217:        } /*end j */
1.126     brouard  12218:       } /* end i */
                   12219:     } /* end itimes */
                   12220:     
                   12221:     fflush(ficlog);
                   12222:     fflush(ficres);
1.225     brouard  12223:     while(fgets(line, MAXLINE, ficpar)) {
                   12224:       /* If line starts with a # it is a comment */
                   12225:       if (line[0] == '#') {
                   12226:        numlinepar++;
                   12227:        fputs(line,stdout);
                   12228:        fputs(line,ficparo);
                   12229:        fputs(line,ficlog);
                   12230:        continue;
                   12231:       }else
                   12232:        break;
                   12233:     }
                   12234:     
1.209     brouard  12235:     /* while((c=getc(ficpar))=='#' && c!= EOF){ */
                   12236:     /*   ungetc(c,ficpar); */
                   12237:     /*   fgets(line, MAXLINE, ficpar); */
                   12238:     /*   fputs(line,stdout); */
                   12239:     /*   fputs(line,ficparo); */
                   12240:     /* } */
                   12241:     /* ungetc(c,ficpar); */
1.126     brouard  12242:     
                   12243:     estepm=0;
1.209     brouard  12244:     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  12245:       
                   12246:       if (num_filled != 6) {
                   12247:        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);
                   12248:        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);
                   12249:        goto end;
                   12250:       }
                   12251:       printf("agemin=%lf agemax=%lf bage=%lf fage=%lf estepm=%d ftolpl=%lf\n",ageminpar,agemaxpar, bage, fage, estepm, ftolpl);
                   12252:     }
                   12253:     /* ftolpl=6*ftol*1.e5; /\* 6.e-3 make convergences in less than 80 loops for the prevalence limit *\/ */
                   12254:     /*ftolpl=6.e-4;*/ /* 6.e-3 make convergences in less than 80 loops for the prevalence limit */
                   12255:     
1.209     brouard  12256:     /* fscanf(ficpar,"agemin=%lf agemax=%lf bage=%lf fage=%lf estepm=%d ftolpl=%\n",&ageminpar,&agemaxpar, &bage, &fage, &estepm); */
1.126     brouard  12257:     if (estepm==0 || estepm < stepm) estepm=stepm;
                   12258:     if (fage <= 2) {
                   12259:       bage = ageminpar;
                   12260:       fage = agemaxpar;
                   12261:     }
                   12262:     
                   12263:     fprintf(ficres,"# agemin agemax for life expectancy, bage fage (if mle==0 ie no data nor Max likelihood).\n");
1.211     brouard  12264:     fprintf(ficres,"agemin=%.0f agemax=%.0f bage=%.0f fage=%.0f estepm=%d ftolpl=%e\n",ageminpar,agemaxpar,bage,fage, estepm, ftolpl);
                   12265:     fprintf(ficparo,"agemin=%.0f agemax=%.0f bage=%.0f fage=%.0f estepm=%d, ftolpl=%e\n",ageminpar,agemaxpar,bage,fage, estepm, ftolpl);
1.220     brouard  12266:                
1.186     brouard  12267:     /* Other stuffs, more or less useful */    
1.254     brouard  12268:     while(fgets(line, MAXLINE, ficpar)) {
                   12269:       /* If line starts with a # it is a comment */
                   12270:       if (line[0] == '#') {
                   12271:        numlinepar++;
                   12272:        fputs(line,stdout);
                   12273:        fputs(line,ficparo);
                   12274:        fputs(line,ficlog);
                   12275:        continue;
                   12276:       }else
                   12277:        break;
                   12278:     }
                   12279: 
                   12280:     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){
                   12281:       
                   12282:       if (num_filled != 7) {
                   12283:        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);
                   12284:        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);
                   12285:        goto end;
                   12286:       }
                   12287:       printf("begin-prev-date=%.lf/%.lf/%.lf end-prev-date=%.lf/%.lf/%.lf mov_average=%d\n",jprev1, mprev1,anprev1,jprev2, mprev2,anprev2,mobilav);
                   12288:       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);
                   12289:       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);
                   12290:       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  12291:     }
1.254     brouard  12292: 
                   12293:     while(fgets(line, MAXLINE, ficpar)) {
                   12294:       /* If line starts with a # it is a comment */
                   12295:       if (line[0] == '#') {
                   12296:        numlinepar++;
                   12297:        fputs(line,stdout);
                   12298:        fputs(line,ficparo);
                   12299:        fputs(line,ficlog);
                   12300:        continue;
                   12301:       }else
                   12302:        break;
1.126     brouard  12303:     }
                   12304:     
                   12305:     
                   12306:     dateprev1=anprev1+(mprev1-1)/12.+(jprev1-1)/365.;
                   12307:     dateprev2=anprev2+(mprev2-1)/12.+(jprev2-1)/365.;
                   12308:     
1.254     brouard  12309:     if((num_filled=sscanf(line,"pop_based=%d\n",&popbased)) !=EOF){
                   12310:       if (num_filled != 1) {
                   12311:        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);
                   12312:        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);
                   12313:        goto end;
                   12314:       }
                   12315:       printf("pop_based=%d\n",popbased);
                   12316:       fprintf(ficlog,"pop_based=%d\n",popbased);
                   12317:       fprintf(ficparo,"pop_based=%d\n",popbased);   
                   12318:       fprintf(ficres,"pop_based=%d\n",popbased);   
                   12319:     }
                   12320:      
1.258     brouard  12321:     /* Results */
                   12322:     nresult=0;
                   12323:     do{
                   12324:       if(!fgets(line, MAXLINE, ficpar)){
                   12325:        endishere=1;
                   12326:        parameterline=14;
                   12327:       }else if (line[0] == '#') {
                   12328:        /* If line starts with a # it is a comment */
1.254     brouard  12329:        numlinepar++;
                   12330:        fputs(line,stdout);
                   12331:        fputs(line,ficparo);
                   12332:        fputs(line,ficlog);
                   12333:        continue;
1.258     brouard  12334:       }else if(sscanf(line,"prevforecast=%[^\n]\n",modeltemp))
                   12335:        parameterline=11;
1.296     brouard  12336:       else if(sscanf(line,"prevbackcast=%[^\n]\n",modeltemp))
1.258     brouard  12337:        parameterline=12;
                   12338:       else if(sscanf(line,"result:%[^\n]\n",modeltemp))
                   12339:        parameterline=13;
                   12340:       else{
                   12341:        parameterline=14;
1.254     brouard  12342:       }
1.258     brouard  12343:       switch (parameterline){ 
                   12344:       case 11:
1.296     brouard  12345:        if((num_filled=sscanf(line,"prevforecast=%d starting-proj-date=%lf/%lf/%lf final-proj-date=%lf/%lf/%lf mobil_average=%d\n",&prevfcast,&jproj1,&mproj1,&anproj1,&jproj2,&mproj2,&anproj2,&mobilavproj)) !=EOF && (num_filled == 8)){
                   12346:                  fprintf(ficparo,"prevforecast=%d starting-proj-date=%.lf/%.lf/%.lf final-proj-date=%.lf/%.lf/%.lf mobil_average=%d\n",prevfcast,jproj1,mproj1,anproj1,jproj2,mproj2,anproj2,mobilavproj);
1.258     brouard  12347:          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);
                   12348:          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);
                   12349:          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);
                   12350:          /* day and month of proj2 are not used but only year anproj2.*/
1.273     brouard  12351:          dateproj1=anproj1+(mproj1-1)/12.+(jproj1-1)/365.;
                   12352:          dateproj2=anproj2+(mproj2-1)/12.+(jproj2-1)/365.;
1.296     brouard  12353:           prvforecast = 1;
                   12354:        } 
                   12355:        else if((num_filled=sscanf(line,"prevforecast=%d yearsfproj=%lf mobil_average=%d\n",&prevfcast,&yrfproj,&mobilavproj)) !=EOF){/* && (num_filled == 3))*/
                   12356:           printf(" Num_filled=%d, yearsfproj=%lf, mobil_average=%d\n",prevfcast,yrfproj,mobilavproj);
                   12357:           prvforecast = 2;
                   12358:        }
                   12359:        else {
                   12360:          printf("Error: Not 8 (data)parameters in line but %d, for example:prevforecast=1 starting-proj-date=1/1/1990 final-proj-date=1/1/2000 mobil_average=0\nnor 3 (data)parameters, for example:prevforecast=1 yearsfproj=10 mobil_average=0. Your line=%s . You are running probably an older format.\n, ",num_filled,line);
                   12361:          fprintf(ficlog,"Error: Not 8 (data)parameters in line but %d, for example:prevforecast=1 starting-proj-date=1/1/1990 final-proj-date=1/1/2000 mobil_average=0\nnor 3 (data)parameters, for example:prevforecast=1 yearproj=10 mobil_average=0. Your line=%s . You are running probably an older format.\n, ",num_filled,line);
                   12362:          goto end;
1.258     brouard  12363:        }
1.254     brouard  12364:        break;
1.258     brouard  12365:       case 12:
1.296     brouard  12366:        if((num_filled=sscanf(line,"prevbackcast=%d starting-back-date=%lf/%lf/%lf final-back-date=%lf/%lf/%lf mobil_average=%d\n",&prevbcast,&jback1,&mback1,&anback1,&jback2,&mback2,&anback2,&mobilavproj)) !=EOF && (num_filled == 8)){
                   12367:           fprintf(ficparo,"prevbackcast=%d starting-back-date=%.lf/%.lf/%.lf final-back-date=%.lf/%.lf/%.lf mobil_average=%d\n",prevbcast,jback1,mback1,anback1,jback2,mback2,anback2,mobilavproj);
                   12368:          printf("prevbackcast=%d starting-back-date=%.lf/%.lf/%.lf final-back-date=%.lf/%.lf/%.lf mobil_average=%d\n",prevbcast,jback1,mback1,anback1,jback2,mback2,anback2,mobilavproj);
                   12369:          fprintf(ficlog,"prevbackcast=%d starting-back-date=%.lf/%.lf/%.lf final-back-date=%.lf/%.lf/%.lf mobil_average=%d\n",prevbcast,jback1,mback1,anback1,jback2,mback2,anback2,mobilavproj);
                   12370:          fprintf(ficres,"prevbackcast=%d starting-back-date=%.lf/%.lf/%.lf final-back-date=%.lf/%.lf/%.lf mobil_average=%d\n",prevbcast,jback1,mback1,anback1,jback2,mback2,anback2,mobilavproj);
                   12371:          /* day and month of back2 are not used but only year anback2.*/
1.273     brouard  12372:          dateback1=anback1+(mback1-1)/12.+(jback1-1)/365.;
                   12373:          dateback2=anback2+(mback2-1)/12.+(jback2-1)/365.;
1.296     brouard  12374:           prvbackcast = 1;
                   12375:        } 
                   12376:        else if((num_filled=sscanf(line,"prevbackcast=%d yearsbproj=%lf mobil_average=%d\n",&prevbcast,&yrbproj,&mobilavproj)) ==3){/* && (num_filled == 3))*/
                   12377:           printf(" Num_filled=%d, yearsbproj=%lf, mobil_average=%d\n",prevbcast,yrbproj,mobilavproj);
                   12378:           prvbackcast = 2;
                   12379:        }
                   12380:        else {
                   12381:          printf("Error: Not 8 (data)parameters in line but %d, for example:prevbackcast=1 starting-back-date=1/1/1990 final-back-date=1/1/2000 mobil_average=0\nnor 3 (data)parameters, for example:prevbackcast=1 yearsbproj=10 mobil_average=0. Your line=%s . You are running probably an older format.\n, ",num_filled,line);
                   12382:          fprintf(ficlog,"Error: Not 8 (data)parameters in line but %d, for example:prevbackcast=1 starting-back-date=1/1/1990 final-back-date=1/1/2000 mobil_average=0\nnor 3 (data)parameters, for example:prevbackcast=1 yearbproj=10 mobil_average=0. Your line=%s . You are running probably an older format.\n, ",num_filled,line);
                   12383:          goto end;
1.258     brouard  12384:        }
1.230     brouard  12385:        break;
1.296     brouard  12386:        /* /\*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);*\/ */
                   12387:        /* 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){ */
                   12388:        /*   if (num_filled != 8) { */
                   12389:        /*     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); */
                   12390:        /*     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); */
                   12391:        /*     goto end; */
                   12392:        /*   } */
                   12393:        /*   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); */
                   12394:        /*   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); */
                   12395:        /*   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); */
                   12396:        /*   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); */
                   12397:        /*   /\* day and month of proj2 are not used but only year anproj2.*\/ */
                   12398:        /*   dateback1=anback1+(mback1-1)/12.+(jback1-1)/365.; */
                   12399:        /*   dateback2=anback2+(mback2-1)/12.+(jback2-1)/365.; */
                   12400:        /* } */
                   12401:        /* break; */
1.258     brouard  12402:       case 13:
                   12403:        if((num_filled=sscanf(line,"result:%[^\n]\n",resultline)) !=EOF){
                   12404:          if (num_filled == 0){
                   12405:            resultline[0]='\0';
                   12406:            printf("Warning %d: no result line! It should be at minimum 'result: V2=0 V1=1 or result:.\n%s\n", num_filled, line);
                   12407:            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);
                   12408:            break;
                   12409:          } else if (num_filled != 1){
                   12410:            printf("ERROR %d: result line! It should be at minimum 'result: V2=0 V1=1 or result:.' %s\n",num_filled, line);
                   12411:            fprintf(ficlog,"ERROR %d: result line! It should be at minimum 'result: V2=0 V1=1 or result:.' %s\n",num_filled, line);
                   12412:          }
                   12413:          nresult++; /* Sum of resultlines */
                   12414:          printf("Result %d: result=%s\n",nresult, resultline);
                   12415:          if(nresult > MAXRESULTLINES){
                   12416:            printf("ERROR: Current version of IMaCh limits the number of resultlines to %d, you used %d\n",MAXRESULTLINES,nresult);
                   12417:            fprintf(ficlog,"ERROR: Current version of IMaCh limits the number of resultlines to %d, you used %d\n",MAXRESULTLINES,nresult);
                   12418:            goto end;
                   12419:          }
                   12420:          decoderesult(resultline, nresult); /* Fills TKresult[nresult] combination and Tresult[nresult][k4+1] combination values */
                   12421:          fprintf(ficparo,"result: %s\n",resultline);
                   12422:          fprintf(ficres,"result: %s\n",resultline);
                   12423:          fprintf(ficlog,"result: %s\n",resultline);
1.230     brouard  12424:          break;
1.258     brouard  12425:        case 14: 
1.259     brouard  12426:          if(ncovmodel >2 && nresult==0 ){
                   12427:            printf("ERROR: no result lines! It should be at minimum 'result: V2=0 V1=1 or result:.' %s\n",line);
1.258     brouard  12428:            goto end;
                   12429:          }
1.259     brouard  12430:          break;
1.258     brouard  12431:        default:
                   12432:          nresult=1;
                   12433:          decoderesult(".",nresult ); /* No covariate */
                   12434:        }
                   12435:       } /* End switch parameterline */
                   12436:     }while(endishere==0); /* End do */
1.126     brouard  12437:     
1.230     brouard  12438:     /* freqsummary(fileres, agemin, agemax, s, agev, nlstate, imx,Tvaraff,nbcode, ncodemax,mint,anint); */
1.145     brouard  12439:     /* ,dateprev1,dateprev2,jprev1, mprev1,anprev1,jprev2, mprev2,anprev2); */
1.126     brouard  12440:     
                   12441:     replace_back_to_slash(pathc,pathcd); /* Even gnuplot wants a / */
1.194     brouard  12442:     if(ageminpar == AGEOVERFLOW ||agemaxpar == -AGEOVERFLOW){
1.230     brouard  12443:       printf("Warning! Error in gnuplot file with ageminpar %f or agemaxpar %f overflow\n\
1.194     brouard  12444: This is probably because your parameter file doesn't \n  contain the exact number of lines (or columns) corresponding to your model line.\n\
                   12445: Please run with mle=-1 to get a correct covariance matrix.\n",ageminpar,agemaxpar);
1.230     brouard  12446:       fprintf(ficlog,"Warning! Error in gnuplot file with ageminpar %f or agemaxpar %f overflow\n\
1.194     brouard  12447: This is probably because your parameter file doesn't \n  contain the exact number of lines (or columns) corresponding to your model line.\n\
                   12448: Please run with mle=-1 to get a correct covariance matrix.\n",ageminpar,agemaxpar);
1.220     brouard  12449:     }else{
1.270     brouard  12450:       /* printinggnuplot(fileresu, optionfilefiname,ageminpar,agemaxpar,fage, prevfcast, backcast, pathc,p, (int)anproj1-(int)agemin, (int)anback1-(int)agemax+1); */
1.296     brouard  12451:       /* It seems that anprojd which is computed from the mean year at interview which is known yet because of freqsummary */
                   12452:       /* date2dmy(dateintmean,&jintmean,&mintmean,&aintmean); */ /* Done in freqsummary */
                   12453:       if(prvforecast==1){
                   12454:         dateprojd=(jproj1+12*mproj1+365*anproj1)/365;
                   12455:         jprojd=jproj1;
                   12456:         mprojd=mproj1;
                   12457:         anprojd=anproj1;
                   12458:         dateprojf=(jproj2+12*mproj2+365*anproj2)/365;
                   12459:         jprojf=jproj2;
                   12460:         mprojf=mproj2;
                   12461:         anprojf=anproj2;
                   12462:       } else if(prvforecast == 2){
                   12463:         dateprojd=dateintmean;
                   12464:         date2dmy(dateprojd,&jprojd, &mprojd, &anprojd);
                   12465:         dateprojf=dateintmean+yrfproj;
                   12466:         date2dmy(dateprojf,&jprojf, &mprojf, &anprojf);
                   12467:       }
                   12468:       if(prvbackcast==1){
                   12469:         datebackd=(jback1+12*mback1+365*anback1)/365;
                   12470:         jbackd=jback1;
                   12471:         mbackd=mback1;
                   12472:         anbackd=anback1;
                   12473:         datebackf=(jback2+12*mback2+365*anback2)/365;
                   12474:         jbackf=jback2;
                   12475:         mbackf=mback2;
                   12476:         anbackf=anback2;
                   12477:       } else if(prvbackcast == 2){
                   12478:         datebackd=dateintmean;
                   12479:         date2dmy(datebackd,&jbackd, &mbackd, &anbackd);
                   12480:         datebackf=dateintmean-yrbproj;
                   12481:         date2dmy(datebackf,&jbackf, &mbackf, &anbackf);
                   12482:       }
                   12483:       
                   12484:       printinggnuplot(fileresu, optionfilefiname,ageminpar,agemaxpar,bage, fage, prevfcast, prevbcast, pathc,p, (int)anprojd-bage, (int)anbackd-fage);
1.220     brouard  12485:     }
                   12486:     printinghtml(fileresu,title,datafile, firstpass, lastpass, stepm, weightopt, \
1.296     brouard  12487:                 model,imx,jmin,jmax,jmean,rfileres,popforecast,mobilav,prevfcast,mobilavproj,prevbcast, estepm, \
                   12488:                 jprev1,mprev1,anprev1,dateprev1, dateprojd, datebackd,jprev2,mprev2,anprev2,dateprev2,dateprojf, datebackf);
1.220     brouard  12489:                
1.225     brouard  12490:     /*------------ free_vector  -------------*/
                   12491:     /*  chdir(path); */
1.220     brouard  12492:                
1.215     brouard  12493:     /* free_ivector(wav,1,imx); */  /* Moved after last prevalence call */
                   12494:     /* free_imatrix(dh,1,lastpass-firstpass+2,1,imx); */
                   12495:     /* free_imatrix(bh,1,lastpass-firstpass+2,1,imx); */
                   12496:     /* free_imatrix(mw,1,lastpass-firstpass+2,1,imx);    */
1.290     brouard  12497:     free_lvector(num,firstobs,lastobs);
                   12498:     free_vector(agedc,firstobs,lastobs);
1.126     brouard  12499:     /*free_matrix(covar,0,NCOVMAX,1,n);*/
                   12500:     /*free_matrix(covar,1,NCOVMAX,1,n);*/
                   12501:     fclose(ficparo);
                   12502:     fclose(ficres);
1.220     brouard  12503:                
                   12504:                
1.186     brouard  12505:     /* Other results (useful)*/
1.220     brouard  12506:                
                   12507:                
1.126     brouard  12508:     /*--------------- Prevalence limit  (period or stable prevalence) --------------*/
1.180     brouard  12509:     /*#include "prevlim.h"*/  /* Use ficrespl, ficlog */
                   12510:     prlim=matrix(1,nlstate,1,nlstate);
1.209     brouard  12511:     prevalence_limit(p, prlim,  ageminpar, agemaxpar, ftolpl, &ncvyear);
1.126     brouard  12512:     fclose(ficrespl);
                   12513: 
                   12514:     /*------------- h Pij x at various ages ------------*/
1.180     brouard  12515:     /*#include "hpijx.h"*/
                   12516:     hPijx(p, bage, fage);
1.145     brouard  12517:     fclose(ficrespij);
1.227     brouard  12518:     
1.220     brouard  12519:     /* ncovcombmax=  pow(2,cptcoveff); */
1.219     brouard  12520:     /*-------------- Variance of one-step probabilities---*/
1.145     brouard  12521:     k=1;
1.126     brouard  12522:     varprob(optionfilefiname, matcov, p, delti, nlstate, bage, fage,k,Tvar,nbcode, ncodemax,strstart);
1.227     brouard  12523:     
1.269     brouard  12524:     /* Prevalence for each covariate combination in probs[age][status][cov] */
                   12525:     probs= ma3x(AGEINF,AGESUP,1,nlstate+ndeath, 1,ncovcombmax);
                   12526:     for(i=AGEINF;i<=AGESUP;i++)
1.219     brouard  12527:       for(j=1;j<=nlstate+ndeath;j++) /* ndeath is useless but a necessity to be compared with mobaverages */
1.225     brouard  12528:        for(k=1;k<=ncovcombmax;k++)
                   12529:          probs[i][j][k]=0.;
1.269     brouard  12530:     prevalence(probs, ageminpar, agemaxpar, s, agev, nlstate, imx, Tvar, nbcode, 
                   12531:               ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass);
1.219     brouard  12532:     if (mobilav!=0 ||mobilavproj !=0 ) {
1.269     brouard  12533:       mobaverages= ma3x(AGEINF, AGESUP,1,nlstate+ndeath, 1,ncovcombmax);
                   12534:       for(i=AGEINF;i<=AGESUP;i++)
1.268     brouard  12535:        for(j=1;j<=nlstate+ndeath;j++)
1.227     brouard  12536:          for(k=1;k<=ncovcombmax;k++)
                   12537:            mobaverages[i][j][k]=0.;
1.219     brouard  12538:       mobaverage=mobaverages;
                   12539:       if (mobilav!=0) {
1.235     brouard  12540:        printf("Movingaveraging observed prevalence\n");
1.258     brouard  12541:        fprintf(ficlog,"Movingaveraging observed prevalence\n");
1.227     brouard  12542:        if (movingaverage(probs, ageminpar, agemaxpar, mobaverage, mobilav)!=0){
                   12543:          fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);
                   12544:          printf(" Error in movingaverage mobilav=%d\n",mobilav);
                   12545:        }
1.269     brouard  12546:       } else if (mobilavproj !=0) {
1.235     brouard  12547:        printf("Movingaveraging projected observed prevalence\n");
1.258     brouard  12548:        fprintf(ficlog,"Movingaveraging projected observed prevalence\n");
1.227     brouard  12549:        if (movingaverage(probs, ageminpar, agemaxpar, mobaverage, mobilavproj)!=0){
                   12550:          fprintf(ficlog," Error in movingaverage mobilavproj=%d\n",mobilavproj);
                   12551:          printf(" Error in movingaverage mobilavproj=%d\n",mobilavproj);
                   12552:        }
1.269     brouard  12553:       }else{
                   12554:        printf("Internal error moving average\n");
                   12555:        fflush(stdout);
                   12556:        exit(1);
1.219     brouard  12557:       }
                   12558:     }/* end if moving average */
1.227     brouard  12559:     
1.126     brouard  12560:     /*---------- Forecasting ------------------*/
1.296     brouard  12561:     if(prevfcast==1){ 
                   12562:       /*   /\*    if(stepm ==1){*\/ */
                   12563:       /*   /\*  anproj1, mproj1, jproj1 either read explicitly or yrfproj *\/ */
                   12564:       /*This done previously after freqsummary.*/
                   12565:       /*   dateprojd=(jproj1+12*mproj1+365*anproj1)/365; */
                   12566:       /*   dateprojf=(jproj2+12*mproj2+365*anproj2)/365; */
                   12567:       
                   12568:       /* } else if (prvforecast==2){ */
                   12569:       /*   /\*    if(stepm ==1){*\/ */
                   12570:       /*   /\*  anproj1, mproj1, jproj1 either read explicitly or yrfproj *\/ */
                   12571:       /* } */
                   12572:       /*prevforecast(fileresu, dateintmean, anproj1, mproj1, jproj1, agemin, agemax, dateprev1, dateprev2, mobilavproj, mobaverage, bage, fage, firstpass, lastpass, anproj2, p, cptcoveff);*/
                   12573:       prevforecast(fileresu,dateintmean, dateprojd, dateprojf, agemin, agemax, dateprev1, dateprev2, mobilavproj, mobaverage, bage, fage, firstpass, lastpass, p, cptcoveff);
1.126     brouard  12574:     }
1.269     brouard  12575: 
1.296     brouard  12576:     /* Prevbcasting */
                   12577:     if(prevbcast==1){
1.219     brouard  12578:       ddnewms=matrix(1,nlstate+ndeath,1,nlstate+ndeath);       
                   12579:       ddoldms=matrix(1,nlstate+ndeath,1,nlstate+ndeath);       
                   12580:       ddsavms=matrix(1,nlstate+ndeath,1,nlstate+ndeath);
                   12581: 
                   12582:       /*--------------- Back Prevalence limit  (period or stable prevalence) --------------*/
                   12583: 
                   12584:       bprlim=matrix(1,nlstate,1,nlstate);
1.269     brouard  12585: 
1.219     brouard  12586:       back_prevalence_limit(p, bprlim,  ageminpar, agemaxpar, ftolpl, &ncvyear, dateprev1, dateprev2, firstpass, lastpass, mobilavproj);
                   12587:       fclose(ficresplb);
                   12588: 
1.222     brouard  12589:       hBijx(p, bage, fage, mobaverage);
                   12590:       fclose(ficrespijb);
1.219     brouard  12591: 
1.296     brouard  12592:       /* /\* prevbackforecast(fileresu, mobaverage, anback1, mback1, jback1, agemin, agemax, dateprev1, dateprev2, *\/ */
                   12593:       /* /\*                  mobilavproj, bage, fage, firstpass, lastpass, anback2, p, cptcoveff); *\/ */
                   12594:       /* prevbackforecast(fileresu, mobaverage, anback1, mback1, jback1, agemin, agemax, dateprev1, dateprev2, */
                   12595:       /*                      mobilavproj, bage, fage, firstpass, lastpass, anback2, p, cptcoveff); */
                   12596:       prevbackforecast(fileresu, mobaverage, dateintmean, dateprojd, dateprojf, agemin, agemax, dateprev1, dateprev2,
                   12597:                       mobilavproj, bage, fage, firstpass, lastpass, p, cptcoveff);
                   12598: 
                   12599:       
1.269     brouard  12600:       varbprlim(fileresu, nresult, mobaverage, mobilavproj, bage, fage, bprlim, &ncvyear, ftolpl, p, matcov, delti, stepm, cptcoveff);
1.268     brouard  12601: 
                   12602:       
1.269     brouard  12603:       free_matrix(bprlim,1,nlstate,1,nlstate); /*here or after loop ? */
1.219     brouard  12604:       free_matrix(ddnewms, 1, nlstate+ndeath, 1, nlstate+ndeath);
                   12605:       free_matrix(ddsavms, 1, nlstate+ndeath, 1, nlstate+ndeath);
                   12606:       free_matrix(ddoldms, 1, nlstate+ndeath, 1, nlstate+ndeath);
1.296     brouard  12607:     }    /* end  Prevbcasting */
1.268     brouard  12608:  
1.186     brouard  12609:  
                   12610:     /* ------ Other prevalence ratios------------ */
1.126     brouard  12611: 
1.215     brouard  12612:     free_ivector(wav,1,imx);
                   12613:     free_imatrix(dh,1,lastpass-firstpass+2,1,imx);
                   12614:     free_imatrix(bh,1,lastpass-firstpass+2,1,imx);
                   12615:     free_imatrix(mw,1,lastpass-firstpass+2,1,imx);   
1.218     brouard  12616:                
                   12617:                
1.127     brouard  12618:     /*---------- Health expectancies, no variances ------------*/
1.218     brouard  12619:                
1.201     brouard  12620:     strcpy(filerese,"E_");
                   12621:     strcat(filerese,fileresu);
1.126     brouard  12622:     if((ficreseij=fopen(filerese,"w"))==NULL) {
                   12623:       printf("Problem with Health Exp. resultfile: %s\n", filerese); exit(0);
                   12624:       fprintf(ficlog,"Problem with Health Exp. resultfile: %s\n", filerese); exit(0);
                   12625:     }
1.208     brouard  12626:     printf("Computing Health Expectancies: result on file '%s' ...", filerese);fflush(stdout);
                   12627:     fprintf(ficlog,"Computing Health Expectancies: result on file '%s' ...", filerese);fflush(ficlog);
1.238     brouard  12628: 
                   12629:     pstamp(ficreseij);
1.219     brouard  12630:                
1.235     brouard  12631:     i1=pow(2,cptcoveff); /* Number of combination of dummy covariates */
                   12632:     if (cptcovn < 1){i1=1;}
                   12633:     
                   12634:     for(nres=1; nres <= nresult; nres++) /* For each resultline */
                   12635:     for(k=1; k<=i1;k++){ /* For any combination of dummy covariates, fixed and varying */
1.253     brouard  12636:       if(i1 != 1 && TKresult[nres]!= k)
1.235     brouard  12637:        continue;
1.219     brouard  12638:       fprintf(ficreseij,"\n#****** ");
1.235     brouard  12639:       printf("\n#****** ");
1.225     brouard  12640:       for(j=1;j<=cptcoveff;j++) {
1.227     brouard  12641:        fprintf(ficreseij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
1.235     brouard  12642:        printf("V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   12643:       }
                   12644:       for (j=1; j<= nsq; j++){ /* For each selected (single) quantitative value */
                   12645:        printf(" V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]);
                   12646:        fprintf(ficreseij," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]);
1.219     brouard  12647:       }
                   12648:       fprintf(ficreseij,"******\n");
1.235     brouard  12649:       printf("******\n");
1.219     brouard  12650:       
                   12651:       eij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
                   12652:       oldm=oldms;savm=savms;
1.235     brouard  12653:       evsij(eij, p, nlstate, stepm, (int) bage, (int)fage, oldm, savm, k, estepm, strstart, nres);  
1.127     brouard  12654:       
1.219     brouard  12655:       free_ma3x(eij,1,nlstate,1,nlstate,(int) bage, (int)fage);
1.127     brouard  12656:     }
                   12657:     fclose(ficreseij);
1.208     brouard  12658:     printf("done evsij\n");fflush(stdout);
                   12659:     fprintf(ficlog,"done evsij\n");fflush(ficlog);
1.269     brouard  12660: 
1.218     brouard  12661:                
1.227     brouard  12662:     /*---------- State-specific expectancies and variances ------------*/
1.218     brouard  12663:                
1.201     brouard  12664:     strcpy(filerest,"T_");
                   12665:     strcat(filerest,fileresu);
1.127     brouard  12666:     if((ficrest=fopen(filerest,"w"))==NULL) {
                   12667:       printf("Problem with total LE resultfile: %s\n", filerest);goto end;
                   12668:       fprintf(ficlog,"Problem with total LE resultfile: %s\n", filerest);goto end;
                   12669:     }
1.208     brouard  12670:     printf("Computing Total Life expectancies with their standard errors: file '%s' ...\n", filerest); fflush(stdout);
                   12671:     fprintf(ficlog,"Computing Total Life expectancies with their standard errors: file '%s' ...\n", filerest); fflush(ficlog);
1.201     brouard  12672:     strcpy(fileresstde,"STDE_");
                   12673:     strcat(fileresstde,fileresu);
1.126     brouard  12674:     if((ficresstdeij=fopen(fileresstde,"w"))==NULL) {
1.227     brouard  12675:       printf("Problem with State specific Exp. and std errors resultfile: %s\n", fileresstde); exit(0);
                   12676:       fprintf(ficlog,"Problem with State specific Exp. and std errors resultfile: %s\n", fileresstde); exit(0);
1.126     brouard  12677:     }
1.227     brouard  12678:     printf("  Computing State-specific Expectancies and standard errors: result on file '%s' \n", fileresstde);
                   12679:     fprintf(ficlog,"  Computing State-specific Expectancies and standard errors: result on file '%s' \n", fileresstde);
1.126     brouard  12680: 
1.201     brouard  12681:     strcpy(filerescve,"CVE_");
                   12682:     strcat(filerescve,fileresu);
1.126     brouard  12683:     if((ficrescveij=fopen(filerescve,"w"))==NULL) {
1.227     brouard  12684:       printf("Problem with Covar. State-specific Exp. resultfile: %s\n", filerescve); exit(0);
                   12685:       fprintf(ficlog,"Problem with Covar. State-specific Exp. resultfile: %s\n", filerescve); exit(0);
1.126     brouard  12686:     }
1.227     brouard  12687:     printf("    Computing Covar. of State-specific Expectancies: result on file '%s' \n", filerescve);
                   12688:     fprintf(ficlog,"    Computing Covar. of State-specific Expectancies: result on file '%s' \n", filerescve);
1.126     brouard  12689: 
1.201     brouard  12690:     strcpy(fileresv,"V_");
                   12691:     strcat(fileresv,fileresu);
1.126     brouard  12692:     if((ficresvij=fopen(fileresv,"w"))==NULL) {
                   12693:       printf("Problem with variance resultfile: %s\n", fileresv);exit(0);
                   12694:       fprintf(ficlog,"Problem with variance resultfile: %s\n", fileresv);exit(0);
                   12695:     }
1.227     brouard  12696:     printf("      Computing Variance-covariance of State-specific Expectancies: file '%s' ... ", fileresv);fflush(stdout);
                   12697:     fprintf(ficlog,"      Computing Variance-covariance of State-specific Expectancies: file '%s' ... ", fileresv);fflush(ficlog);
1.126     brouard  12698: 
1.235     brouard  12699:     i1=pow(2,cptcoveff); /* Number of combination of dummy covariates */
                   12700:     if (cptcovn < 1){i1=1;}
                   12701:     
                   12702:     for(nres=1; nres <= nresult; nres++) /* For each resultline */
                   12703:     for(k=1; k<=i1;k++){ /* For any combination of dummy covariates, fixed and varying */
1.253     brouard  12704:       if(i1 != 1 && TKresult[nres]!= k)
1.235     brouard  12705:        continue;
1.242     brouard  12706:       printf("\n#****** Result for:");
                   12707:       fprintf(ficrest,"\n#****** Result for:");
                   12708:       fprintf(ficlog,"\n#****** Result for:");
1.227     brouard  12709:       for(j=1;j<=cptcoveff;j++){ 
                   12710:        printf("V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   12711:        fprintf(ficrest,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   12712:        fprintf(ficlog,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   12713:       }
1.235     brouard  12714:       for (j=1; j<= nsq; j++){ /* For each selected (single) quantitative value */
                   12715:        printf(" V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]);
                   12716:        fprintf(ficrest," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]);
                   12717:        fprintf(ficlog," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]);
                   12718:       }        
1.208     brouard  12719:       fprintf(ficrest,"******\n");
1.227     brouard  12720:       fprintf(ficlog,"******\n");
                   12721:       printf("******\n");
1.208     brouard  12722:       
                   12723:       fprintf(ficresstdeij,"\n#****** ");
                   12724:       fprintf(ficrescveij,"\n#****** ");
1.225     brouard  12725:       for(j=1;j<=cptcoveff;j++) {
1.227     brouard  12726:        fprintf(ficresstdeij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   12727:        fprintf(ficrescveij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
1.208     brouard  12728:       }
1.235     brouard  12729:       for (j=1; j<= nsq; j++){ /* For each selected (single) quantitative value */
                   12730:        fprintf(ficresstdeij," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]);
                   12731:        fprintf(ficrescveij," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]);
                   12732:       }        
1.208     brouard  12733:       fprintf(ficresstdeij,"******\n");
                   12734:       fprintf(ficrescveij,"******\n");
                   12735:       
                   12736:       fprintf(ficresvij,"\n#****** ");
1.238     brouard  12737:       /* pstamp(ficresvij); */
1.225     brouard  12738:       for(j=1;j<=cptcoveff;j++) 
1.227     brouard  12739:        fprintf(ficresvij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
1.235     brouard  12740:       for (j=1; j<= nsq; j++){ /* For each selected (single) quantitative value */
                   12741:        fprintf(ficresvij," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]);
                   12742:       }        
1.208     brouard  12743:       fprintf(ficresvij,"******\n");
                   12744:       
                   12745:       eij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
                   12746:       oldm=oldms;savm=savms;
1.235     brouard  12747:       printf(" cvevsij ");
                   12748:       fprintf(ficlog, " cvevsij ");
                   12749:       cvevsij(eij, p, nlstate, stepm, (int) bage, (int)fage, oldm, savm, k, estepm, delti, matcov, strstart, nres);
1.208     brouard  12750:       printf(" end cvevsij \n ");
                   12751:       fprintf(ficlog, " end cvevsij \n ");
                   12752:       
                   12753:       /*
                   12754:        */
                   12755:       /* goto endfree; */
                   12756:       
                   12757:       vareij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
                   12758:       pstamp(ficrest);
                   12759:       
1.269     brouard  12760:       epj=vector(1,nlstate+1);
1.208     brouard  12761:       for(vpopbased=0; vpopbased <= popbased; vpopbased++){ /* Done for vpopbased=0 and vpopbased=1 if popbased==1*/
1.227     brouard  12762:        oldm=oldms;savm=savms; /* ZZ Segmentation fault */
                   12763:        cptcod= 0; /* To be deleted */
                   12764:        printf("varevsij vpopbased=%d \n",vpopbased);
                   12765:        fprintf(ficlog, "varevsij vpopbased=%d \n",vpopbased);
1.235     brouard  12766:        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  12767:        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 ");
                   12768:        if(vpopbased==1)
                   12769:          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);
                   12770:        else
1.288     brouard  12771:          fprintf(ficrest,"the age specific forward period (stable) prevalences in each health state \n");
1.227     brouard  12772:        fprintf(ficrest,"# Age popbased mobilav e.. (std) ");
                   12773:        for (i=1;i<=nlstate;i++) fprintf(ficrest,"e.%d (std) ",i);
                   12774:        fprintf(ficrest,"\n");
                   12775:        /* printf("Which p?\n"); for(i=1;i<=npar;i++)printf("p[i=%d]=%lf,",i,p[i]);printf("\n"); */
1.288     brouard  12776:        printf("Computing age specific forward period (stable) prevalences in each health state \n");
                   12777:        fprintf(ficlog,"Computing age specific forward period (stable) prevalences in each health state \n");
1.227     brouard  12778:        for(age=bage; age <=fage ;age++){
1.235     brouard  12779:          prevalim(prlim, nlstate, p, age, oldm, savm, ftolpl, &ncvyear, k, nres); /*ZZ Is it the correct prevalim */
1.227     brouard  12780:          if (vpopbased==1) {
                   12781:            if(mobilav ==0){
                   12782:              for(i=1; i<=nlstate;i++)
                   12783:                prlim[i][i]=probs[(int)age][i][k];
                   12784:            }else{ /* mobilav */ 
                   12785:              for(i=1; i<=nlstate;i++)
                   12786:                prlim[i][i]=mobaverage[(int)age][i][k];
                   12787:            }
                   12788:          }
1.219     brouard  12789:          
1.227     brouard  12790:          fprintf(ficrest," %4.0f %d %d",age, vpopbased, mobilav);
                   12791:          /* fprintf(ficrest," %4.0f %d %d %d %d",age, vpopbased, mobilav,Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]); */ /* to be done */
                   12792:          /* printf(" age %4.0f ",age); */
                   12793:          for(j=1, epj[nlstate+1]=0.;j <=nlstate;j++){
                   12794:            for(i=1, epj[j]=0.;i <=nlstate;i++) {
                   12795:              epj[j] += prlim[i][i]*eij[i][j][(int)age];
                   12796:              /*ZZZ  printf("%lf %lf ", prlim[i][i] ,eij[i][j][(int)age]);*/
                   12797:              /* printf("%lf %lf ", prlim[i][i] ,eij[i][j][(int)age]); */
                   12798:            }
                   12799:            epj[nlstate+1] +=epj[j];
                   12800:          }
                   12801:          /* printf(" age %4.0f \n",age); */
1.219     brouard  12802:          
1.227     brouard  12803:          for(i=1, vepp=0.;i <=nlstate;i++)
                   12804:            for(j=1;j <=nlstate;j++)
                   12805:              vepp += vareij[i][j][(int)age];
                   12806:          fprintf(ficrest," %7.3f (%7.3f)", epj[nlstate+1],sqrt(vepp));
                   12807:          for(j=1;j <=nlstate;j++){
                   12808:            fprintf(ficrest," %7.3f (%7.3f)", epj[j],sqrt(vareij[j][j][(int)age]));
                   12809:          }
                   12810:          fprintf(ficrest,"\n");
                   12811:        }
1.208     brouard  12812:       } /* End vpopbased */
1.269     brouard  12813:       free_vector(epj,1,nlstate+1);
1.208     brouard  12814:       free_ma3x(eij,1,nlstate,1,nlstate,(int) bage, (int)fage);
                   12815:       free_ma3x(vareij,1,nlstate,1,nlstate,(int) bage, (int)fage);
1.235     brouard  12816:       printf("done selection\n");fflush(stdout);
                   12817:       fprintf(ficlog,"done selection\n");fflush(ficlog);
1.208     brouard  12818:       
1.235     brouard  12819:     } /* End k selection */
1.227     brouard  12820: 
                   12821:     printf("done State-specific expectancies\n");fflush(stdout);
                   12822:     fprintf(ficlog,"done State-specific expectancies\n");fflush(ficlog);
                   12823: 
1.288     brouard  12824:     /* variance-covariance of forward period prevalence*/
1.269     brouard  12825:     varprlim(fileresu, nresult, mobaverage, mobilavproj, bage, fage, prlim, &ncvyear, ftolpl, p, matcov, delti, stepm, cptcoveff);
1.268     brouard  12826: 
1.227     brouard  12827:     
1.290     brouard  12828:     free_vector(weight,firstobs,lastobs);
1.227     brouard  12829:     free_imatrix(Tvard,1,NCOVMAX,1,2);
1.290     brouard  12830:     free_imatrix(s,1,maxwav+1,firstobs,lastobs);
                   12831:     free_matrix(anint,1,maxwav,firstobs,lastobs); 
                   12832:     free_matrix(mint,1,maxwav,firstobs,lastobs);
                   12833:     free_ivector(cod,firstobs,lastobs);
1.227     brouard  12834:     free_ivector(tab,1,NCOVMAX);
                   12835:     fclose(ficresstdeij);
                   12836:     fclose(ficrescveij);
                   12837:     fclose(ficresvij);
                   12838:     fclose(ficrest);
                   12839:     fclose(ficpar);
                   12840:     
                   12841:     
1.126     brouard  12842:     /*---------- End : free ----------------*/
1.219     brouard  12843:     if (mobilav!=0 ||mobilavproj !=0)
1.269     brouard  12844:       free_ma3x(mobaverages,AGEINF, AGESUP,1,nlstate+ndeath, 1,ncovcombmax); /* We need to have a squared matrix with prevalence of the dead! */
                   12845:     free_ma3x(probs,AGEINF,AGESUP,1,nlstate+ndeath, 1,ncovcombmax);
1.220     brouard  12846:     free_matrix(prlim,1,nlstate,1,nlstate); /*here or after loop ? */
                   12847:     free_matrix(pmmij,1,nlstate+ndeath,1,nlstate+ndeath);
1.126     brouard  12848:   }  /* mle==-3 arrives here for freeing */
1.227     brouard  12849:   /* endfree:*/
                   12850:   free_matrix(oldms, 1,nlstate+ndeath,1,nlstate+ndeath);
                   12851:   free_matrix(newms, 1,nlstate+ndeath,1,nlstate+ndeath);
                   12852:   free_matrix(savms, 1,nlstate+ndeath,1,nlstate+ndeath);
1.290     brouard  12853:   if(ntv+nqtv>=1)free_ma3x(cotvar,1,maxwav,1,ntv+nqtv,firstobs,lastobs);
                   12854:   if(nqtv>=1)free_ma3x(cotqvar,1,maxwav,1,nqtv,firstobs,lastobs);
                   12855:   if(nqv>=1)free_matrix(coqvar,1,nqv,firstobs,lastobs);
                   12856:   free_matrix(covar,0,NCOVMAX,firstobs,lastobs);
1.227     brouard  12857:   free_matrix(matcov,1,npar,1,npar);
                   12858:   free_matrix(hess,1,npar,1,npar);
                   12859:   /*free_vector(delti,1,npar);*/
                   12860:   free_ma3x(delti3,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel); 
                   12861:   free_matrix(agev,1,maxwav,1,imx);
1.269     brouard  12862:   free_ma3x(paramstart,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel);
1.227     brouard  12863:   free_ma3x(param,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel);
                   12864:   
                   12865:   free_ivector(ncodemax,1,NCOVMAX);
                   12866:   free_ivector(ncodemaxwundef,1,NCOVMAX);
                   12867:   free_ivector(Dummy,-1,NCOVMAX);
                   12868:   free_ivector(Fixed,-1,NCOVMAX);
1.238     brouard  12869:   free_ivector(DummyV,1,NCOVMAX);
                   12870:   free_ivector(FixedV,1,NCOVMAX);
1.227     brouard  12871:   free_ivector(Typevar,-1,NCOVMAX);
                   12872:   free_ivector(Tvar,1,NCOVMAX);
1.234     brouard  12873:   free_ivector(TvarsQ,1,NCOVMAX);
                   12874:   free_ivector(TvarsQind,1,NCOVMAX);
                   12875:   free_ivector(TvarsD,1,NCOVMAX);
                   12876:   free_ivector(TvarsDind,1,NCOVMAX);
1.231     brouard  12877:   free_ivector(TvarFD,1,NCOVMAX);
                   12878:   free_ivector(TvarFDind,1,NCOVMAX);
1.232     brouard  12879:   free_ivector(TvarF,1,NCOVMAX);
                   12880:   free_ivector(TvarFind,1,NCOVMAX);
                   12881:   free_ivector(TvarV,1,NCOVMAX);
                   12882:   free_ivector(TvarVind,1,NCOVMAX);
                   12883:   free_ivector(TvarA,1,NCOVMAX);
                   12884:   free_ivector(TvarAind,1,NCOVMAX);
1.231     brouard  12885:   free_ivector(TvarFQ,1,NCOVMAX);
                   12886:   free_ivector(TvarFQind,1,NCOVMAX);
                   12887:   free_ivector(TvarVD,1,NCOVMAX);
                   12888:   free_ivector(TvarVDind,1,NCOVMAX);
                   12889:   free_ivector(TvarVQ,1,NCOVMAX);
                   12890:   free_ivector(TvarVQind,1,NCOVMAX);
1.230     brouard  12891:   free_ivector(Tvarsel,1,NCOVMAX);
                   12892:   free_vector(Tvalsel,1,NCOVMAX);
1.227     brouard  12893:   free_ivector(Tposprod,1,NCOVMAX);
                   12894:   free_ivector(Tprod,1,NCOVMAX);
                   12895:   free_ivector(Tvaraff,1,NCOVMAX);
                   12896:   free_ivector(invalidvarcomb,1,ncovcombmax);
                   12897:   free_ivector(Tage,1,NCOVMAX);
                   12898:   free_ivector(Tmodelind,1,NCOVMAX);
1.228     brouard  12899:   free_ivector(TmodelInvind,1,NCOVMAX);
                   12900:   free_ivector(TmodelInvQind,1,NCOVMAX);
1.227     brouard  12901:   
                   12902:   free_imatrix(nbcode,0,NCOVMAX,0,NCOVMAX);
                   12903:   /* free_imatrix(codtab,1,100,1,10); */
1.126     brouard  12904:   fflush(fichtm);
                   12905:   fflush(ficgp);
                   12906:   
1.227     brouard  12907:   
1.126     brouard  12908:   if((nberr >0) || (nbwarn>0)){
1.216     brouard  12909:     printf("End of Imach with %d errors and/or %d warnings. Please look at the log file for details.\n",nberr,nbwarn);
                   12910:     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  12911:   }else{
                   12912:     printf("End of Imach\n");
                   12913:     fprintf(ficlog,"End of Imach\n");
                   12914:   }
                   12915:   printf("See log file on %s\n",filelog);
                   12916:   /*  gettimeofday(&end_time, (struct timezone*)0);*/  /* after time */
1.157     brouard  12917:   /*(void) gettimeofday(&end_time,&tzp);*/
                   12918:   rend_time = time(NULL);  
                   12919:   end_time = *localtime(&rend_time);
                   12920:   /* tml = *localtime(&end_time.tm_sec); */
                   12921:   strcpy(strtend,asctime(&end_time));
1.126     brouard  12922:   printf("Local time at start %s\nLocal time at end   %s",strstart, strtend); 
                   12923:   fprintf(ficlog,"Local time at start %s\nLocal time at end   %s\n",strstart, strtend); 
1.157     brouard  12924:   printf("Total time used %s\n", asc_diff_time(rend_time -rstart_time,tmpout));
1.227     brouard  12925:   
1.157     brouard  12926:   printf("Total time was %.0lf Sec.\n", difftime(rend_time,rstart_time));
                   12927:   fprintf(ficlog,"Total time used %s\n", asc_diff_time(rend_time -rstart_time,tmpout));
                   12928:   fprintf(ficlog,"Total time was %.0lf Sec.\n", difftime(rend_time,rstart_time));
1.126     brouard  12929:   /*  printf("Total time was %d uSec.\n", total_usecs);*/
                   12930: /*   if(fileappend(fichtm,optionfilehtm)){ */
                   12931:   fprintf(fichtm,"<br>Local time at start %s<br>Local time at end   %s<br>\n</body></html>",strstart, strtend);
                   12932:   fclose(fichtm);
                   12933:   fprintf(fichtmcov,"<br>Local time at start %s<br>Local time at end   %s<br>\n</body></html>",strstart, strtend);
                   12934:   fclose(fichtmcov);
                   12935:   fclose(ficgp);
                   12936:   fclose(ficlog);
                   12937:   /*------ End -----------*/
1.227     brouard  12938:   
1.281     brouard  12939: 
                   12940: /* Executes gnuplot */
1.227     brouard  12941:   
                   12942:   printf("Before Current directory %s!\n",pathcd);
1.184     brouard  12943: #ifdef WIN32
1.227     brouard  12944:   if (_chdir(pathcd) != 0)
                   12945:     printf("Can't move to directory %s!\n",path);
                   12946:   if(_getcwd(pathcd,MAXLINE) > 0)
1.184     brouard  12947: #else
1.227     brouard  12948:     if(chdir(pathcd) != 0)
                   12949:       printf("Can't move to directory %s!\n", path);
                   12950:   if (getcwd(pathcd, MAXLINE) > 0)
1.184     brouard  12951: #endif 
1.126     brouard  12952:     printf("Current directory %s!\n",pathcd);
                   12953:   /*strcat(plotcmd,CHARSEPARATOR);*/
                   12954:   sprintf(plotcmd,"gnuplot");
1.157     brouard  12955: #ifdef _WIN32
1.126     brouard  12956:   sprintf(plotcmd,"\"%sgnuplot.exe\"",pathimach);
                   12957: #endif
                   12958:   if(!stat(plotcmd,&info)){
1.158     brouard  12959:     printf("Error or gnuplot program not found: '%s'\n",plotcmd);fflush(stdout);
1.126     brouard  12960:     if(!stat(getenv("GNUPLOTBIN"),&info)){
1.158     brouard  12961:       printf("Error or gnuplot program not found: '%s' Environment GNUPLOTBIN not set.\n",plotcmd);fflush(stdout);
1.126     brouard  12962:     }else
                   12963:       strcpy(pplotcmd,plotcmd);
1.157     brouard  12964: #ifdef __unix
1.126     brouard  12965:     strcpy(plotcmd,GNUPLOTPROGRAM);
                   12966:     if(!stat(plotcmd,&info)){
1.158     brouard  12967:       printf("Error gnuplot program not found: '%s'\n",plotcmd);fflush(stdout);
1.126     brouard  12968:     }else
                   12969:       strcpy(pplotcmd,plotcmd);
                   12970: #endif
                   12971:   }else
                   12972:     strcpy(pplotcmd,plotcmd);
                   12973:   
                   12974:   sprintf(plotcmd,"%s %s",pplotcmd, optionfilegnuplot);
1.158     brouard  12975:   printf("Starting graphs with: '%s'\n",plotcmd);fflush(stdout);
1.292     brouard  12976:   strcpy(pplotcmd,plotcmd);
1.227     brouard  12977:   
1.126     brouard  12978:   if((outcmd=system(plotcmd)) != 0){
1.292     brouard  12979:     printf("Error in gnuplot, command might not be in your path: '%s', err=%d\n", plotcmd, outcmd);
1.154     brouard  12980:     printf("\n Trying if gnuplot resides on the same directory that IMaCh\n");
1.152     brouard  12981:     sprintf(plotcmd,"%sgnuplot %s", pathimach, optionfilegnuplot);
1.292     brouard  12982:     if((outcmd=system(plotcmd)) != 0){
1.153     brouard  12983:       printf("\n Still a problem with gnuplot command %s, err=%d\n", plotcmd, outcmd);
1.292     brouard  12984:       strcpy(plotcmd,pplotcmd);
                   12985:     }
1.126     brouard  12986:   }
1.158     brouard  12987:   printf(" Successful, please wait...");
1.126     brouard  12988:   while (z[0] != 'q') {
                   12989:     /* chdir(path); */
1.154     brouard  12990:     printf("\nType e to edit results with your browser, g to graph again and q for exit: ");
1.126     brouard  12991:     scanf("%s",z);
                   12992: /*     if (z[0] == 'c') system("./imach"); */
                   12993:     if (z[0] == 'e') {
1.158     brouard  12994: #ifdef __APPLE__
1.152     brouard  12995:       sprintf(pplotcmd, "open %s", optionfilehtm);
1.157     brouard  12996: #elif __linux
                   12997:       sprintf(pplotcmd, "xdg-open %s", optionfilehtm);
1.153     brouard  12998: #else
1.152     brouard  12999:       sprintf(pplotcmd, "%s", optionfilehtm);
1.153     brouard  13000: #endif
                   13001:       printf("Starting browser with: %s",pplotcmd);fflush(stdout);
                   13002:       system(pplotcmd);
1.126     brouard  13003:     }
                   13004:     else if (z[0] == 'g') system(plotcmd);
                   13005:     else if (z[0] == 'q') exit(0);
                   13006:   }
1.227     brouard  13007: end:
1.126     brouard  13008:   while (z[0] != 'q') {
1.195     brouard  13009:     printf("\nType  q for exiting: "); fflush(stdout);
1.126     brouard  13010:     scanf("%s",z);
                   13011:   }
1.283     brouard  13012:   printf("End\n");
1.282     brouard  13013:   exit(0);
1.126     brouard  13014: }

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