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

1.324   ! brouard     1: /* $Id: imach.c,v 1.323 2022/07/22 12:30:08 brouard Exp $
1.126     brouard     2:   $State: Exp $
1.163     brouard     3:   $Log: imach.c,v $
1.324   ! brouard     4:   Revision 1.323  2022/07/22 12:30:08  brouard
        !             5:   *  imach.c (Module): Output of Wald test in the htm file and not only in the log.
        !             6: 
1.323     brouard     7:   Revision 1.322  2022/07/22 12:27:48  brouard
                      8:   *  imach.c (Module): Output of Wald test in the htm file and not only in the log.
                      9: 
1.322     brouard    10:   Revision 1.321  2022/07/22 12:04:24  brouard
                     11:   Summary: r28
                     12: 
                     13:   *  imach.c (Module): Output of Wald test in the htm file and not only in the log.
                     14: 
1.321     brouard    15:   Revision 1.320  2022/06/02 05:10:11  brouard
                     16:   *** empty log message ***
                     17: 
1.320     brouard    18:   Revision 1.319  2022/06/02 04:45:11  brouard
                     19:   * imach.c (Module): Adding the Wald tests from the log to the main
                     20:   htm for better display of the maximum likelihood estimators.
                     21: 
1.319     brouard    22:   Revision 1.318  2022/05/24 08:10:59  brouard
                     23:   * imach.c (Module): Some attempts to find a bug of wrong estimates
                     24:   of confidencce intervals with product in the equation modelC
                     25: 
1.318     brouard    26:   Revision 1.317  2022/05/15 15:06:23  brouard
                     27:   * imach.c (Module):  Some minor improvements
                     28: 
1.317     brouard    29:   Revision 1.316  2022/05/11 15:11:31  brouard
                     30:   Summary: r27
                     31: 
1.316     brouard    32:   Revision 1.315  2022/05/11 15:06:32  brouard
                     33:   *** empty log message ***
                     34: 
1.315     brouard    35:   Revision 1.314  2022/04/13 17:43:09  brouard
                     36:   * imach.c (Module): Adding link to text data files
                     37: 
1.314     brouard    38:   Revision 1.313  2022/04/11 15:57:42  brouard
                     39:   * imach.c (Module): Error in rewriting the 'r' file with yearsfproj or yearsbproj fixed
                     40: 
1.313     brouard    41:   Revision 1.312  2022/04/05 21:24:39  brouard
                     42:   *** empty log message ***
                     43: 
1.312     brouard    44:   Revision 1.311  2022/04/05 21:03:51  brouard
                     45:   Summary: Fixed quantitative covariates
                     46: 
                     47:          Fixed covariates (dummy or quantitative)
                     48:        with missing values have never been allowed but are ERRORS and
                     49:        program quits. Standard deviations of fixed covariates were
                     50:        wrongly computed. Mean and standard deviations of time varying
                     51:        covariates are still not computed.
                     52: 
1.311     brouard    53:   Revision 1.310  2022/03/17 08:45:53  brouard
                     54:   Summary: 99r25
                     55: 
                     56:   Improving detection of errors: result lines should be compatible with
                     57:   the model.
                     58: 
1.310     brouard    59:   Revision 1.309  2021/05/20 12:39:14  brouard
                     60:   Summary: Version 0.99r24
                     61: 
1.309     brouard    62:   Revision 1.308  2021/03/31 13:11:57  brouard
                     63:   Summary: Version 0.99r23
                     64: 
                     65: 
                     66:   * imach.c (Module): Still bugs in the result loop. Thank to Holly Benett
                     67: 
1.308     brouard    68:   Revision 1.307  2021/03/08 18:11:32  brouard
                     69:   Summary: 0.99r22 fixed bug on result:
                     70: 
1.307     brouard    71:   Revision 1.306  2021/02/20 15:44:02  brouard
                     72:   Summary: Version 0.99r21
                     73: 
                     74:   * imach.c (Module): Fix bug on quitting after result lines!
                     75:   (Module): Version 0.99r21
                     76: 
1.306     brouard    77:   Revision 1.305  2021/02/20 15:28:30  brouard
                     78:   * imach.c (Module): Fix bug on quitting after result lines!
                     79: 
1.305     brouard    80:   Revision 1.304  2021/02/12 11:34:20  brouard
                     81:   * imach.c (Module): The use of a Windows BOM (huge) file is now an error
                     82: 
1.304     brouard    83:   Revision 1.303  2021/02/11 19:50:15  brouard
                     84:   *  (Module): imach.c Someone entered 'results:' instead of 'result:'. Now it is an error which is printed.
                     85: 
1.303     brouard    86:   Revision 1.302  2020/02/22 21:00:05  brouard
                     87:   *  (Module): imach.c Update mle=-3 (for computing Life expectancy
                     88:   and life table from the data without any state)
                     89: 
1.302     brouard    90:   Revision 1.301  2019/06/04 13:51:20  brouard
                     91:   Summary: Error in 'r'parameter file backcast yearsbproj instead of yearsfproj
                     92: 
1.301     brouard    93:   Revision 1.300  2019/05/22 19:09:45  brouard
                     94:   Summary: version 0.99r19 of May 2019
                     95: 
1.300     brouard    96:   Revision 1.299  2019/05/22 18:37:08  brouard
                     97:   Summary: Cleaned 0.99r19
                     98: 
1.299     brouard    99:   Revision 1.298  2019/05/22 18:19:56  brouard
                    100:   *** empty log message ***
                    101: 
1.298     brouard   102:   Revision 1.297  2019/05/22 17:56:10  brouard
                    103:   Summary: Fix bug by moving date2dmy and nhstepm which gaefin=-1
                    104: 
1.297     brouard   105:   Revision 1.296  2019/05/20 13:03:18  brouard
                    106:   Summary: Projection syntax simplified
                    107: 
                    108: 
                    109:   We can now start projections, forward or backward, from the mean date
                    110:   of inteviews up to or down to a number of years of projection:
                    111:   prevforecast=1 yearsfproj=15.3 mobil_average=0
                    112:   or
                    113:   prevforecast=1 starting-proj-date=1/1/2007 final-proj-date=12/31/2017 mobil_average=0
                    114:   or
                    115:   prevbackcast=1 yearsbproj=12.3 mobil_average=1
                    116:   or
                    117:   prevbackcast=1 starting-back-date=1/10/1999 final-back-date=1/1/1985 mobil_average=1
                    118: 
1.296     brouard   119:   Revision 1.295  2019/05/18 09:52:50  brouard
                    120:   Summary: doxygen tex bug
                    121: 
1.295     brouard   122:   Revision 1.294  2019/05/16 14:54:33  brouard
                    123:   Summary: There was some wrong lines added
                    124: 
1.294     brouard   125:   Revision 1.293  2019/05/09 15:17:34  brouard
                    126:   *** empty log message ***
                    127: 
1.293     brouard   128:   Revision 1.292  2019/05/09 14:17:20  brouard
                    129:   Summary: Some updates
                    130: 
1.292     brouard   131:   Revision 1.291  2019/05/09 13:44:18  brouard
                    132:   Summary: Before ncovmax
                    133: 
1.291     brouard   134:   Revision 1.290  2019/05/09 13:39:37  brouard
                    135:   Summary: 0.99r18 unlimited number of individuals
                    136: 
                    137:   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.
                    138: 
1.290     brouard   139:   Revision 1.289  2018/12/13 09:16:26  brouard
                    140:   Summary: Bug for young ages (<-30) will be in r17
                    141: 
1.289     brouard   142:   Revision 1.288  2018/05/02 20:58:27  brouard
                    143:   Summary: Some bugs fixed
                    144: 
1.288     brouard   145:   Revision 1.287  2018/05/01 17:57:25  brouard
                    146:   Summary: Bug fixed by providing frequencies only for non missing covariates
                    147: 
1.287     brouard   148:   Revision 1.286  2018/04/27 14:27:04  brouard
                    149:   Summary: some minor bugs
                    150: 
1.286     brouard   151:   Revision 1.285  2018/04/21 21:02:16  brouard
                    152:   Summary: Some bugs fixed, valgrind tested
                    153: 
1.285     brouard   154:   Revision 1.284  2018/04/20 05:22:13  brouard
                    155:   Summary: Computing mean and stdeviation of fixed quantitative variables
                    156: 
1.284     brouard   157:   Revision 1.283  2018/04/19 14:49:16  brouard
                    158:   Summary: Some minor bugs fixed
                    159: 
1.283     brouard   160:   Revision 1.282  2018/02/27 22:50:02  brouard
                    161:   *** empty log message ***
                    162: 
1.282     brouard   163:   Revision 1.281  2018/02/27 19:25:23  brouard
                    164:   Summary: Adding second argument for quitting
                    165: 
1.281     brouard   166:   Revision 1.280  2018/02/21 07:58:13  brouard
                    167:   Summary: 0.99r15
                    168: 
                    169:   New Makefile with recent VirtualBox 5.26. Bug in sqrt negatve in imach.c
                    170: 
1.280     brouard   171:   Revision 1.279  2017/07/20 13:35:01  brouard
                    172:   Summary: temporary working
                    173: 
1.279     brouard   174:   Revision 1.278  2017/07/19 14:09:02  brouard
                    175:   Summary: Bug for mobil_average=0 and prevforecast fixed(?)
                    176: 
1.278     brouard   177:   Revision 1.277  2017/07/17 08:53:49  brouard
                    178:   Summary: BOM files can be read now
                    179: 
1.277     brouard   180:   Revision 1.276  2017/06/30 15:48:31  brouard
                    181:   Summary: Graphs improvements
                    182: 
1.276     brouard   183:   Revision 1.275  2017/06/30 13:39:33  brouard
                    184:   Summary: Saito's color
                    185: 
1.275     brouard   186:   Revision 1.274  2017/06/29 09:47:08  brouard
                    187:   Summary: Version 0.99r14
                    188: 
1.274     brouard   189:   Revision 1.273  2017/06/27 11:06:02  brouard
                    190:   Summary: More documentation on projections
                    191: 
1.273     brouard   192:   Revision 1.272  2017/06/27 10:22:40  brouard
                    193:   Summary: Color of backprojection changed from 6 to 5(yellow)
                    194: 
1.272     brouard   195:   Revision 1.271  2017/06/27 10:17:50  brouard
                    196:   Summary: Some bug with rint
                    197: 
1.271     brouard   198:   Revision 1.270  2017/05/24 05:45:29  brouard
                    199:   *** empty log message ***
                    200: 
1.270     brouard   201:   Revision 1.269  2017/05/23 08:39:25  brouard
                    202:   Summary: Code into subroutine, cleanings
                    203: 
1.269     brouard   204:   Revision 1.268  2017/05/18 20:09:32  brouard
                    205:   Summary: backprojection and confidence intervals of backprevalence
                    206: 
1.268     brouard   207:   Revision 1.267  2017/05/13 10:25:05  brouard
                    208:   Summary: temporary save for backprojection
                    209: 
1.267     brouard   210:   Revision 1.266  2017/05/13 07:26:12  brouard
                    211:   Summary: Version 0.99r13 (improvements and bugs fixed)
                    212: 
1.266     brouard   213:   Revision 1.265  2017/04/26 16:22:11  brouard
                    214:   Summary: imach 0.99r13 Some bugs fixed
                    215: 
1.265     brouard   216:   Revision 1.264  2017/04/26 06:01:29  brouard
                    217:   Summary: Labels in graphs
                    218: 
1.264     brouard   219:   Revision 1.263  2017/04/24 15:23:15  brouard
                    220:   Summary: to save
                    221: 
1.263     brouard   222:   Revision 1.262  2017/04/18 16:48:12  brouard
                    223:   *** empty log message ***
                    224: 
1.262     brouard   225:   Revision 1.261  2017/04/05 10:14:09  brouard
                    226:   Summary: Bug in E_ as well as in T_ fixed nres-1 vs k1-1
                    227: 
1.261     brouard   228:   Revision 1.260  2017/04/04 17:46:59  brouard
                    229:   Summary: Gnuplot indexations fixed (humm)
                    230: 
1.260     brouard   231:   Revision 1.259  2017/04/04 13:01:16  brouard
                    232:   Summary: Some errors to warnings only if date of death is unknown but status is death we could set to pi3
                    233: 
1.259     brouard   234:   Revision 1.258  2017/04/03 10:17:47  brouard
                    235:   Summary: Version 0.99r12
                    236: 
                    237:   Some cleanings, conformed with updated documentation.
                    238: 
1.258     brouard   239:   Revision 1.257  2017/03/29 16:53:30  brouard
                    240:   Summary: Temp
                    241: 
1.257     brouard   242:   Revision 1.256  2017/03/27 05:50:23  brouard
                    243:   Summary: Temporary
                    244: 
1.256     brouard   245:   Revision 1.255  2017/03/08 16:02:28  brouard
                    246:   Summary: IMaCh version 0.99r10 bugs in gnuplot fixed
                    247: 
1.255     brouard   248:   Revision 1.254  2017/03/08 07:13:00  brouard
                    249:   Summary: Fixing data parameter line
                    250: 
1.254     brouard   251:   Revision 1.253  2016/12/15 11:59:41  brouard
                    252:   Summary: 0.99 in progress
                    253: 
1.253     brouard   254:   Revision 1.252  2016/09/15 21:15:37  brouard
                    255:   *** empty log message ***
                    256: 
1.252     brouard   257:   Revision 1.251  2016/09/15 15:01:13  brouard
                    258:   Summary: not working
                    259: 
1.251     brouard   260:   Revision 1.250  2016/09/08 16:07:27  brouard
                    261:   Summary: continue
                    262: 
1.250     brouard   263:   Revision 1.249  2016/09/07 17:14:18  brouard
                    264:   Summary: Starting values from frequencies
                    265: 
1.249     brouard   266:   Revision 1.248  2016/09/07 14:10:18  brouard
                    267:   *** empty log message ***
                    268: 
1.248     brouard   269:   Revision 1.247  2016/09/02 11:11:21  brouard
                    270:   *** empty log message ***
                    271: 
1.247     brouard   272:   Revision 1.246  2016/09/02 08:49:22  brouard
                    273:   *** empty log message ***
                    274: 
1.246     brouard   275:   Revision 1.245  2016/09/02 07:25:01  brouard
                    276:   *** empty log message ***
                    277: 
1.245     brouard   278:   Revision 1.244  2016/09/02 07:17:34  brouard
                    279:   *** empty log message ***
                    280: 
1.244     brouard   281:   Revision 1.243  2016/09/02 06:45:35  brouard
                    282:   *** empty log message ***
                    283: 
1.243     brouard   284:   Revision 1.242  2016/08/30 15:01:20  brouard
                    285:   Summary: Fixing a lots
                    286: 
1.242     brouard   287:   Revision 1.241  2016/08/29 17:17:25  brouard
                    288:   Summary: gnuplot problem in Back projection to fix
                    289: 
1.241     brouard   290:   Revision 1.240  2016/08/29 07:53:18  brouard
                    291:   Summary: Better
                    292: 
1.240     brouard   293:   Revision 1.239  2016/08/26 15:51:03  brouard
                    294:   Summary: Improvement in Powell output in order to copy and paste
                    295: 
                    296:   Author:
                    297: 
1.239     brouard   298:   Revision 1.238  2016/08/26 14:23:35  brouard
                    299:   Summary: Starting tests of 0.99
                    300: 
1.238     brouard   301:   Revision 1.237  2016/08/26 09:20:19  brouard
                    302:   Summary: to valgrind
                    303: 
1.237     brouard   304:   Revision 1.236  2016/08/25 10:50:18  brouard
                    305:   *** empty log message ***
                    306: 
1.236     brouard   307:   Revision 1.235  2016/08/25 06:59:23  brouard
                    308:   *** empty log message ***
                    309: 
1.235     brouard   310:   Revision 1.234  2016/08/23 16:51:20  brouard
                    311:   *** empty log message ***
                    312: 
1.234     brouard   313:   Revision 1.233  2016/08/23 07:40:50  brouard
                    314:   Summary: not working
                    315: 
1.233     brouard   316:   Revision 1.232  2016/08/22 14:20:21  brouard
                    317:   Summary: not working
                    318: 
1.232     brouard   319:   Revision 1.231  2016/08/22 07:17:15  brouard
                    320:   Summary: not working
                    321: 
1.231     brouard   322:   Revision 1.230  2016/08/22 06:55:53  brouard
                    323:   Summary: Not working
                    324: 
1.230     brouard   325:   Revision 1.229  2016/07/23 09:45:53  brouard
                    326:   Summary: Completing for func too
                    327: 
1.229     brouard   328:   Revision 1.228  2016/07/22 17:45:30  brouard
                    329:   Summary: Fixing some arrays, still debugging
                    330: 
1.227     brouard   331:   Revision 1.226  2016/07/12 18:42:34  brouard
                    332:   Summary: temp
                    333: 
1.226     brouard   334:   Revision 1.225  2016/07/12 08:40:03  brouard
                    335:   Summary: saving but not running
                    336: 
1.225     brouard   337:   Revision 1.224  2016/07/01 13:16:01  brouard
                    338:   Summary: Fixes
                    339: 
1.224     brouard   340:   Revision 1.223  2016/02/19 09:23:35  brouard
                    341:   Summary: temporary
                    342: 
1.223     brouard   343:   Revision 1.222  2016/02/17 08:14:50  brouard
                    344:   Summary: Probably last 0.98 stable version 0.98r6
                    345: 
1.222     brouard   346:   Revision 1.221  2016/02/15 23:35:36  brouard
                    347:   Summary: minor bug
                    348: 
1.220     brouard   349:   Revision 1.219  2016/02/15 00:48:12  brouard
                    350:   *** empty log message ***
                    351: 
1.219     brouard   352:   Revision 1.218  2016/02/12 11:29:23  brouard
                    353:   Summary: 0.99 Back projections
                    354: 
1.218     brouard   355:   Revision 1.217  2015/12/23 17:18:31  brouard
                    356:   Summary: Experimental backcast
                    357: 
1.217     brouard   358:   Revision 1.216  2015/12/18 17:32:11  brouard
                    359:   Summary: 0.98r4 Warning and status=-2
                    360: 
                    361:   Version 0.98r4 is now:
                    362:    - displaying an error when status is -1, date of interview unknown and date of death known;
                    363:    - permitting a status -2 when the vital status is unknown at a known date of right truncation.
                    364:   Older changes concerning s=-2, dating from 2005 have been supersed.
                    365: 
1.216     brouard   366:   Revision 1.215  2015/12/16 08:52:24  brouard
                    367:   Summary: 0.98r4 working
                    368: 
1.215     brouard   369:   Revision 1.214  2015/12/16 06:57:54  brouard
                    370:   Summary: temporary not working
                    371: 
1.214     brouard   372:   Revision 1.213  2015/12/11 18:22:17  brouard
                    373:   Summary: 0.98r4
                    374: 
1.213     brouard   375:   Revision 1.212  2015/11/21 12:47:24  brouard
                    376:   Summary: minor typo
                    377: 
1.212     brouard   378:   Revision 1.211  2015/11/21 12:41:11  brouard
                    379:   Summary: 0.98r3 with some graph of projected cross-sectional
                    380: 
                    381:   Author: Nicolas Brouard
                    382: 
1.211     brouard   383:   Revision 1.210  2015/11/18 17:41:20  brouard
1.252     brouard   384:   Summary: Start working on projected prevalences  Revision 1.209  2015/11/17 22:12:03  brouard
1.210     brouard   385:   Summary: Adding ftolpl parameter
                    386:   Author: N Brouard
                    387: 
                    388:   We had difficulties to get smoothed confidence intervals. It was due
                    389:   to the period prevalence which wasn't computed accurately. The inner
                    390:   parameter ftolpl is now an outer parameter of the .imach parameter
                    391:   file after estepm. If ftolpl is small 1.e-4 and estepm too,
                    392:   computation are long.
                    393: 
1.209     brouard   394:   Revision 1.208  2015/11/17 14:31:57  brouard
                    395:   Summary: temporary
                    396: 
1.208     brouard   397:   Revision 1.207  2015/10/27 17:36:57  brouard
                    398:   *** empty log message ***
                    399: 
1.207     brouard   400:   Revision 1.206  2015/10/24 07:14:11  brouard
                    401:   *** empty log message ***
                    402: 
1.206     brouard   403:   Revision 1.205  2015/10/23 15:50:53  brouard
                    404:   Summary: 0.98r3 some clarification for graphs on likelihood contributions
                    405: 
1.205     brouard   406:   Revision 1.204  2015/10/01 16:20:26  brouard
                    407:   Summary: Some new graphs of contribution to likelihood
                    408: 
1.204     brouard   409:   Revision 1.203  2015/09/30 17:45:14  brouard
                    410:   Summary: looking at better estimation of the hessian
                    411: 
                    412:   Also a better criteria for convergence to the period prevalence And
                    413:   therefore adding the number of years needed to converge. (The
                    414:   prevalence in any alive state shold sum to one
                    415: 
1.203     brouard   416:   Revision 1.202  2015/09/22 19:45:16  brouard
                    417:   Summary: Adding some overall graph on contribution to likelihood. Might change
                    418: 
1.202     brouard   419:   Revision 1.201  2015/09/15 17:34:58  brouard
                    420:   Summary: 0.98r0
                    421: 
                    422:   - Some new graphs like suvival functions
                    423:   - Some bugs fixed like model=1+age+V2.
                    424: 
1.201     brouard   425:   Revision 1.200  2015/09/09 16:53:55  brouard
                    426:   Summary: Big bug thanks to Flavia
                    427: 
                    428:   Even model=1+age+V2. did not work anymore
                    429: 
1.200     brouard   430:   Revision 1.199  2015/09/07 14:09:23  brouard
                    431:   Summary: 0.98q6 changing default small png format for graph to vectorized svg.
                    432: 
1.199     brouard   433:   Revision 1.198  2015/09/03 07:14:39  brouard
                    434:   Summary: 0.98q5 Flavia
                    435: 
1.198     brouard   436:   Revision 1.197  2015/09/01 18:24:39  brouard
                    437:   *** empty log message ***
                    438: 
1.197     brouard   439:   Revision 1.196  2015/08/18 23:17:52  brouard
                    440:   Summary: 0.98q5
                    441: 
1.196     brouard   442:   Revision 1.195  2015/08/18 16:28:39  brouard
                    443:   Summary: Adding a hack for testing purpose
                    444: 
                    445:   After reading the title, ftol and model lines, if the comment line has
                    446:   a q, starting with #q, the answer at the end of the run is quit. It
                    447:   permits to run test files in batch with ctest. The former workaround was
                    448:   $ echo q | imach foo.imach
                    449: 
1.195     brouard   450:   Revision 1.194  2015/08/18 13:32:00  brouard
                    451:   Summary:  Adding error when the covariance matrix doesn't contain the exact number of lines required by the model line.
                    452: 
1.194     brouard   453:   Revision 1.193  2015/08/04 07:17:42  brouard
                    454:   Summary: 0.98q4
                    455: 
1.193     brouard   456:   Revision 1.192  2015/07/16 16:49:02  brouard
                    457:   Summary: Fixing some outputs
                    458: 
1.192     brouard   459:   Revision 1.191  2015/07/14 10:00:33  brouard
                    460:   Summary: Some fixes
                    461: 
1.191     brouard   462:   Revision 1.190  2015/05/05 08:51:13  brouard
                    463:   Summary: Adding digits in output parameters (7 digits instead of 6)
                    464: 
                    465:   Fix 1+age+.
                    466: 
1.190     brouard   467:   Revision 1.189  2015/04/30 14:45:16  brouard
                    468:   Summary: 0.98q2
                    469: 
1.189     brouard   470:   Revision 1.188  2015/04/30 08:27:53  brouard
                    471:   *** empty log message ***
                    472: 
1.188     brouard   473:   Revision 1.187  2015/04/29 09:11:15  brouard
                    474:   *** empty log message ***
                    475: 
1.187     brouard   476:   Revision 1.186  2015/04/23 12:01:52  brouard
                    477:   Summary: V1*age is working now, version 0.98q1
                    478: 
                    479:   Some codes had been disabled in order to simplify and Vn*age was
                    480:   working in the optimization phase, ie, giving correct MLE parameters,
                    481:   but, as usual, outputs were not correct and program core dumped.
                    482: 
1.186     brouard   483:   Revision 1.185  2015/03/11 13:26:42  brouard
                    484:   Summary: Inclusion of compile and links command line for Intel Compiler
                    485: 
1.185     brouard   486:   Revision 1.184  2015/03/11 11:52:39  brouard
                    487:   Summary: Back from Windows 8. Intel Compiler
                    488: 
1.184     brouard   489:   Revision 1.183  2015/03/10 20:34:32  brouard
                    490:   Summary: 0.98q0, trying with directest, mnbrak fixed
                    491: 
                    492:   We use directest instead of original Powell test; probably no
                    493:   incidence on the results, but better justifications;
                    494:   We fixed Numerical Recipes mnbrak routine which was wrong and gave
                    495:   wrong results.
                    496: 
1.183     brouard   497:   Revision 1.182  2015/02/12 08:19:57  brouard
                    498:   Summary: Trying to keep directest which seems simpler and more general
                    499:   Author: Nicolas Brouard
                    500: 
1.182     brouard   501:   Revision 1.181  2015/02/11 23:22:24  brouard
                    502:   Summary: Comments on Powell added
                    503: 
                    504:   Author:
                    505: 
1.181     brouard   506:   Revision 1.180  2015/02/11 17:33:45  brouard
                    507:   Summary: Finishing move from main to function (hpijx and prevalence_limit)
                    508: 
1.180     brouard   509:   Revision 1.179  2015/01/04 09:57:06  brouard
                    510:   Summary: back to OS/X
                    511: 
1.179     brouard   512:   Revision 1.178  2015/01/04 09:35:48  brouard
                    513:   *** empty log message ***
                    514: 
1.178     brouard   515:   Revision 1.177  2015/01/03 18:40:56  brouard
                    516:   Summary: Still testing ilc32 on OSX
                    517: 
1.177     brouard   518:   Revision 1.176  2015/01/03 16:45:04  brouard
                    519:   *** empty log message ***
                    520: 
1.176     brouard   521:   Revision 1.175  2015/01/03 16:33:42  brouard
                    522:   *** empty log message ***
                    523: 
1.175     brouard   524:   Revision 1.174  2015/01/03 16:15:49  brouard
                    525:   Summary: Still in cross-compilation
                    526: 
1.174     brouard   527:   Revision 1.173  2015/01/03 12:06:26  brouard
                    528:   Summary: trying to detect cross-compilation
                    529: 
1.173     brouard   530:   Revision 1.172  2014/12/27 12:07:47  brouard
                    531:   Summary: Back from Visual Studio and Intel, options for compiling for Windows XP
                    532: 
1.172     brouard   533:   Revision 1.171  2014/12/23 13:26:59  brouard
                    534:   Summary: Back from Visual C
                    535: 
                    536:   Still problem with utsname.h on Windows
                    537: 
1.171     brouard   538:   Revision 1.170  2014/12/23 11:17:12  brouard
                    539:   Summary: Cleaning some \%% back to %%
                    540: 
                    541:   The escape was mandatory for a specific compiler (which one?), but too many warnings.
                    542: 
1.170     brouard   543:   Revision 1.169  2014/12/22 23:08:31  brouard
                    544:   Summary: 0.98p
                    545: 
                    546:   Outputs some informations on compiler used, OS etc. Testing on different platforms.
                    547: 
1.169     brouard   548:   Revision 1.168  2014/12/22 15:17:42  brouard
1.170     brouard   549:   Summary: update
1.169     brouard   550: 
1.168     brouard   551:   Revision 1.167  2014/12/22 13:50:56  brouard
                    552:   Summary: Testing uname and compiler version and if compiled 32 or 64
                    553: 
                    554:   Testing on Linux 64
                    555: 
1.167     brouard   556:   Revision 1.166  2014/12/22 11:40:47  brouard
                    557:   *** empty log message ***
                    558: 
1.166     brouard   559:   Revision 1.165  2014/12/16 11:20:36  brouard
                    560:   Summary: After compiling on Visual C
                    561: 
                    562:   * imach.c (Module): Merging 1.61 to 1.162
                    563: 
1.165     brouard   564:   Revision 1.164  2014/12/16 10:52:11  brouard
                    565:   Summary: Merging with Visual C after suppressing some warnings for unused variables. Also fixing Saito's bug 0.98Xn
                    566: 
                    567:   * imach.c (Module): Merging 1.61 to 1.162
                    568: 
1.164     brouard   569:   Revision 1.163  2014/12/16 10:30:11  brouard
                    570:   * imach.c (Module): Merging 1.61 to 1.162
                    571: 
1.163     brouard   572:   Revision 1.162  2014/09/25 11:43:39  brouard
                    573:   Summary: temporary backup 0.99!
                    574: 
1.162     brouard   575:   Revision 1.1  2014/09/16 11:06:58  brouard
                    576:   Summary: With some code (wrong) for nlopt
                    577: 
                    578:   Author:
                    579: 
                    580:   Revision 1.161  2014/09/15 20:41:41  brouard
                    581:   Summary: Problem with macro SQR on Intel compiler
                    582: 
1.161     brouard   583:   Revision 1.160  2014/09/02 09:24:05  brouard
                    584:   *** empty log message ***
                    585: 
1.160     brouard   586:   Revision 1.159  2014/09/01 10:34:10  brouard
                    587:   Summary: WIN32
                    588:   Author: Brouard
                    589: 
1.159     brouard   590:   Revision 1.158  2014/08/27 17:11:51  brouard
                    591:   *** empty log message ***
                    592: 
1.158     brouard   593:   Revision 1.157  2014/08/27 16:26:55  brouard
                    594:   Summary: Preparing windows Visual studio version
                    595:   Author: Brouard
                    596: 
                    597:   In order to compile on Visual studio, time.h is now correct and time_t
                    598:   and tm struct should be used. difftime should be used but sometimes I
                    599:   just make the differences in raw time format (time(&now).
                    600:   Trying to suppress #ifdef LINUX
                    601:   Add xdg-open for __linux in order to open default browser.
                    602: 
1.157     brouard   603:   Revision 1.156  2014/08/25 20:10:10  brouard
                    604:   *** empty log message ***
                    605: 
1.156     brouard   606:   Revision 1.155  2014/08/25 18:32:34  brouard
                    607:   Summary: New compile, minor changes
                    608:   Author: Brouard
                    609: 
1.155     brouard   610:   Revision 1.154  2014/06/20 17:32:08  brouard
                    611:   Summary: Outputs now all graphs of convergence to period prevalence
                    612: 
1.154     brouard   613:   Revision 1.153  2014/06/20 16:45:46  brouard
                    614:   Summary: If 3 live state, convergence to period prevalence on same graph
                    615:   Author: Brouard
                    616: 
1.153     brouard   617:   Revision 1.152  2014/06/18 17:54:09  brouard
                    618:   Summary: open browser, use gnuplot on same dir than imach if not found in the path
                    619: 
1.152     brouard   620:   Revision 1.151  2014/06/18 16:43:30  brouard
                    621:   *** empty log message ***
                    622: 
1.151     brouard   623:   Revision 1.150  2014/06/18 16:42:35  brouard
                    624:   Summary: If gnuplot is not in the path try on same directory than imach binary (OSX)
                    625:   Author: brouard
                    626: 
1.150     brouard   627:   Revision 1.149  2014/06/18 15:51:14  brouard
                    628:   Summary: Some fixes in parameter files errors
                    629:   Author: Nicolas Brouard
                    630: 
1.149     brouard   631:   Revision 1.148  2014/06/17 17:38:48  brouard
                    632:   Summary: Nothing new
                    633:   Author: Brouard
                    634: 
                    635:   Just a new packaging for OS/X version 0.98nS
                    636: 
1.148     brouard   637:   Revision 1.147  2014/06/16 10:33:11  brouard
                    638:   *** empty log message ***
                    639: 
1.147     brouard   640:   Revision 1.146  2014/06/16 10:20:28  brouard
                    641:   Summary: Merge
                    642:   Author: Brouard
                    643: 
                    644:   Merge, before building revised version.
                    645: 
1.146     brouard   646:   Revision 1.145  2014/06/10 21:23:15  brouard
                    647:   Summary: Debugging with valgrind
                    648:   Author: Nicolas Brouard
                    649: 
                    650:   Lot of changes in order to output the results with some covariates
                    651:   After the Edimburgh REVES conference 2014, it seems mandatory to
                    652:   improve the code.
                    653:   No more memory valgrind error but a lot has to be done in order to
                    654:   continue the work of splitting the code into subroutines.
                    655:   Also, decodemodel has been improved. Tricode is still not
                    656:   optimal. nbcode should be improved. Documentation has been added in
                    657:   the source code.
                    658: 
1.144     brouard   659:   Revision 1.143  2014/01/26 09:45:38  brouard
                    660:   Summary: Version 0.98nR (to be improved, but gives same optimization results as 0.98k. Nice, promising
                    661: 
                    662:   * imach.c (Module): Trying to merge old staffs together while being at Tokyo. Not tested...
                    663:   (Module): Version 0.98nR Running ok, but output format still only works for three covariates.
                    664: 
1.143     brouard   665:   Revision 1.142  2014/01/26 03:57:36  brouard
                    666:   Summary: gnuplot changed plot w l 1 has to be changed to plot w l lt 2
                    667: 
                    668:   * imach.c (Module): Trying to merge old staffs together while being at Tokyo. Not tested...
                    669: 
1.142     brouard   670:   Revision 1.141  2014/01/26 02:42:01  brouard
                    671:   * imach.c (Module): Trying to merge old staffs together while being at Tokyo. Not tested...
                    672: 
1.141     brouard   673:   Revision 1.140  2011/09/02 10:37:54  brouard
                    674:   Summary: times.h is ok with mingw32 now.
                    675: 
1.140     brouard   676:   Revision 1.139  2010/06/14 07:50:17  brouard
                    677:   After the theft of my laptop, I probably lost some lines of codes which were not uploaded to the CVS tree.
                    678:   I remember having already fixed agemin agemax which are pointers now but not cvs saved.
                    679: 
1.139     brouard   680:   Revision 1.138  2010/04/30 18:19:40  brouard
                    681:   *** empty log message ***
                    682: 
1.138     brouard   683:   Revision 1.137  2010/04/29 18:11:38  brouard
                    684:   (Module): Checking covariates for more complex models
                    685:   than V1+V2. A lot of change to be done. Unstable.
                    686: 
1.137     brouard   687:   Revision 1.136  2010/04/26 20:30:53  brouard
                    688:   (Module): merging some libgsl code. Fixing computation
                    689:   of likelione (using inter/intrapolation if mle = 0) in order to
                    690:   get same likelihood as if mle=1.
                    691:   Some cleaning of code and comments added.
                    692: 
1.136     brouard   693:   Revision 1.135  2009/10/29 15:33:14  brouard
                    694:   (Module): Now imach stops if date of birth, at least year of birth, is not given. Some cleaning of the code.
                    695: 
1.135     brouard   696:   Revision 1.134  2009/10/29 13:18:53  brouard
                    697:   (Module): Now imach stops if date of birth, at least year of birth, is not given. Some cleaning of the code.
                    698: 
1.134     brouard   699:   Revision 1.133  2009/07/06 10:21:25  brouard
                    700:   just nforces
                    701: 
1.133     brouard   702:   Revision 1.132  2009/07/06 08:22:05  brouard
                    703:   Many tings
                    704: 
1.132     brouard   705:   Revision 1.131  2009/06/20 16:22:47  brouard
                    706:   Some dimensions resccaled
                    707: 
1.131     brouard   708:   Revision 1.130  2009/05/26 06:44:34  brouard
                    709:   (Module): Max Covariate is now set to 20 instead of 8. A
                    710:   lot of cleaning with variables initialized to 0. Trying to make
                    711:   V2+V3*age+V1+V4 strb=V3*age+V1+V4 working better.
                    712: 
1.130     brouard   713:   Revision 1.129  2007/08/31 13:49:27  lievre
                    714:   Modification of the way of exiting when the covariate is not binary in order to see on the window the error message before exiting
                    715: 
1.129     lievre    716:   Revision 1.128  2006/06/30 13:02:05  brouard
                    717:   (Module): Clarifications on computing e.j
                    718: 
1.128     brouard   719:   Revision 1.127  2006/04/28 18:11:50  brouard
                    720:   (Module): Yes the sum of survivors was wrong since
                    721:   imach-114 because nhstepm was no more computed in the age
                    722:   loop. Now we define nhstepma in the age loop.
                    723:   (Module): In order to speed up (in case of numerous covariates) we
                    724:   compute health expectancies (without variances) in a first step
                    725:   and then all the health expectancies with variances or standard
                    726:   deviation (needs data from the Hessian matrices) which slows the
                    727:   computation.
                    728:   In the future we should be able to stop the program is only health
                    729:   expectancies and graph are needed without standard deviations.
                    730: 
1.127     brouard   731:   Revision 1.126  2006/04/28 17:23:28  brouard
                    732:   (Module): Yes the sum of survivors was wrong since
                    733:   imach-114 because nhstepm was no more computed in the age
                    734:   loop. Now we define nhstepma in the age loop.
                    735:   Version 0.98h
                    736: 
1.126     brouard   737:   Revision 1.125  2006/04/04 15:20:31  lievre
                    738:   Errors in calculation of health expectancies. Age was not initialized.
                    739:   Forecasting file added.
                    740: 
                    741:   Revision 1.124  2006/03/22 17:13:53  lievre
                    742:   Parameters are printed with %lf instead of %f (more numbers after the comma).
                    743:   The log-likelihood is printed in the log file
                    744: 
                    745:   Revision 1.123  2006/03/20 10:52:43  brouard
                    746:   * imach.c (Module): <title> changed, corresponds to .htm file
                    747:   name. <head> headers where missing.
                    748: 
                    749:   * imach.c (Module): Weights can have a decimal point as for
                    750:   English (a comma might work with a correct LC_NUMERIC environment,
                    751:   otherwise the weight is truncated).
                    752:   Modification of warning when the covariates values are not 0 or
                    753:   1.
                    754:   Version 0.98g
                    755: 
                    756:   Revision 1.122  2006/03/20 09:45:41  brouard
                    757:   (Module): Weights can have a decimal point as for
                    758:   English (a comma might work with a correct LC_NUMERIC environment,
                    759:   otherwise the weight is truncated).
                    760:   Modification of warning when the covariates values are not 0 or
                    761:   1.
                    762:   Version 0.98g
                    763: 
                    764:   Revision 1.121  2006/03/16 17:45:01  lievre
                    765:   * imach.c (Module): Comments concerning covariates added
                    766: 
                    767:   * imach.c (Module): refinements in the computation of lli if
                    768:   status=-2 in order to have more reliable computation if stepm is
                    769:   not 1 month. Version 0.98f
                    770: 
                    771:   Revision 1.120  2006/03/16 15:10:38  lievre
                    772:   (Module): refinements in the computation of lli if
                    773:   status=-2 in order to have more reliable computation if stepm is
                    774:   not 1 month. Version 0.98f
                    775: 
                    776:   Revision 1.119  2006/03/15 17:42:26  brouard
                    777:   (Module): Bug if status = -2, the loglikelihood was
                    778:   computed as likelihood omitting the logarithm. Version O.98e
                    779: 
                    780:   Revision 1.118  2006/03/14 18:20:07  brouard
                    781:   (Module): varevsij Comments added explaining the second
                    782:   table of variances if popbased=1 .
                    783:   (Module): Covariances of eij, ekl added, graphs fixed, new html link.
                    784:   (Module): Function pstamp added
                    785:   (Module): Version 0.98d
                    786: 
                    787:   Revision 1.117  2006/03/14 17:16:22  brouard
                    788:   (Module): varevsij Comments added explaining the second
                    789:   table of variances if popbased=1 .
                    790:   (Module): Covariances of eij, ekl added, graphs fixed, new html link.
                    791:   (Module): Function pstamp added
                    792:   (Module): Version 0.98d
                    793: 
                    794:   Revision 1.116  2006/03/06 10:29:27  brouard
                    795:   (Module): Variance-covariance wrong links and
                    796:   varian-covariance of ej. is needed (Saito).
                    797: 
                    798:   Revision 1.115  2006/02/27 12:17:45  brouard
                    799:   (Module): One freematrix added in mlikeli! 0.98c
                    800: 
                    801:   Revision 1.114  2006/02/26 12:57:58  brouard
                    802:   (Module): Some improvements in processing parameter
                    803:   filename with strsep.
                    804: 
                    805:   Revision 1.113  2006/02/24 14:20:24  brouard
                    806:   (Module): Memory leaks checks with valgrind and:
                    807:   datafile was not closed, some imatrix were not freed and on matrix
                    808:   allocation too.
                    809: 
                    810:   Revision 1.112  2006/01/30 09:55:26  brouard
                    811:   (Module): Back to gnuplot.exe instead of wgnuplot.exe
                    812: 
                    813:   Revision 1.111  2006/01/25 20:38:18  brouard
                    814:   (Module): Lots of cleaning and bugs added (Gompertz)
                    815:   (Module): Comments can be added in data file. Missing date values
                    816:   can be a simple dot '.'.
                    817: 
                    818:   Revision 1.110  2006/01/25 00:51:50  brouard
                    819:   (Module): Lots of cleaning and bugs added (Gompertz)
                    820: 
                    821:   Revision 1.109  2006/01/24 19:37:15  brouard
                    822:   (Module): Comments (lines starting with a #) are allowed in data.
                    823: 
                    824:   Revision 1.108  2006/01/19 18:05:42  lievre
                    825:   Gnuplot problem appeared...
                    826:   To be fixed
                    827: 
                    828:   Revision 1.107  2006/01/19 16:20:37  brouard
                    829:   Test existence of gnuplot in imach path
                    830: 
                    831:   Revision 1.106  2006/01/19 13:24:36  brouard
                    832:   Some cleaning and links added in html output
                    833: 
                    834:   Revision 1.105  2006/01/05 20:23:19  lievre
                    835:   *** empty log message ***
                    836: 
                    837:   Revision 1.104  2005/09/30 16:11:43  lievre
                    838:   (Module): sump fixed, loop imx fixed, and simplifications.
                    839:   (Module): If the status is missing at the last wave but we know
                    840:   that the person is alive, then we can code his/her status as -2
                    841:   (instead of missing=-1 in earlier versions) and his/her
                    842:   contributions to the likelihood is 1 - Prob of dying from last
                    843:   health status (= 1-p13= p11+p12 in the easiest case of somebody in
                    844:   the healthy state at last known wave). Version is 0.98
                    845: 
                    846:   Revision 1.103  2005/09/30 15:54:49  lievre
                    847:   (Module): sump fixed, loop imx fixed, and simplifications.
                    848: 
                    849:   Revision 1.102  2004/09/15 17:31:30  brouard
                    850:   Add the possibility to read data file including tab characters.
                    851: 
                    852:   Revision 1.101  2004/09/15 10:38:38  brouard
                    853:   Fix on curr_time
                    854: 
                    855:   Revision 1.100  2004/07/12 18:29:06  brouard
                    856:   Add version for Mac OS X. Just define UNIX in Makefile
                    857: 
                    858:   Revision 1.99  2004/06/05 08:57:40  brouard
                    859:   *** empty log message ***
                    860: 
                    861:   Revision 1.98  2004/05/16 15:05:56  brouard
                    862:   New version 0.97 . First attempt to estimate force of mortality
                    863:   directly from the data i.e. without the need of knowing the health
                    864:   state at each age, but using a Gompertz model: log u =a + b*age .
                    865:   This is the basic analysis of mortality and should be done before any
                    866:   other analysis, in order to test if the mortality estimated from the
                    867:   cross-longitudinal survey is different from the mortality estimated
                    868:   from other sources like vital statistic data.
                    869: 
                    870:   The same imach parameter file can be used but the option for mle should be -3.
                    871: 
1.324   ! brouard   872:   Agnès, who wrote this part of the code, tried to keep most of the
1.126     brouard   873:   former routines in order to include the new code within the former code.
                    874: 
                    875:   The output is very simple: only an estimate of the intercept and of
                    876:   the slope with 95% confident intervals.
                    877: 
                    878:   Current limitations:
                    879:   A) Even if you enter covariates, i.e. with the
                    880:   model= V1+V2 equation for example, the programm does only estimate a unique global model without covariates.
                    881:   B) There is no computation of Life Expectancy nor Life Table.
                    882: 
                    883:   Revision 1.97  2004/02/20 13:25:42  lievre
                    884:   Version 0.96d. Population forecasting command line is (temporarily)
                    885:   suppressed.
                    886: 
                    887:   Revision 1.96  2003/07/15 15:38:55  brouard
                    888:   * imach.c (Repository): Errors in subdirf, 2, 3 while printing tmpout is
                    889:   rewritten within the same printf. Workaround: many printfs.
                    890: 
                    891:   Revision 1.95  2003/07/08 07:54:34  brouard
                    892:   * imach.c (Repository):
                    893:   (Repository): Using imachwizard code to output a more meaningful covariance
                    894:   matrix (cov(a12,c31) instead of numbers.
                    895: 
                    896:   Revision 1.94  2003/06/27 13:00:02  brouard
                    897:   Just cleaning
                    898: 
                    899:   Revision 1.93  2003/06/25 16:33:55  brouard
                    900:   (Module): On windows (cygwin) function asctime_r doesn't
                    901:   exist so I changed back to asctime which exists.
                    902:   (Module): Version 0.96b
                    903: 
                    904:   Revision 1.92  2003/06/25 16:30:45  brouard
                    905:   (Module): On windows (cygwin) function asctime_r doesn't
                    906:   exist so I changed back to asctime which exists.
                    907: 
                    908:   Revision 1.91  2003/06/25 15:30:29  brouard
                    909:   * imach.c (Repository): Duplicated warning errors corrected.
                    910:   (Repository): Elapsed time after each iteration is now output. It
                    911:   helps to forecast when convergence will be reached. Elapsed time
                    912:   is stamped in powell.  We created a new html file for the graphs
                    913:   concerning matrix of covariance. It has extension -cov.htm.
                    914: 
                    915:   Revision 1.90  2003/06/24 12:34:15  brouard
                    916:   (Module): Some bugs corrected for windows. Also, when
                    917:   mle=-1 a template is output in file "or"mypar.txt with the design
                    918:   of the covariance matrix to be input.
                    919: 
                    920:   Revision 1.89  2003/06/24 12:30:52  brouard
                    921:   (Module): Some bugs corrected for windows. Also, when
                    922:   mle=-1 a template is output in file "or"mypar.txt with the design
                    923:   of the covariance matrix to be input.
                    924: 
                    925:   Revision 1.88  2003/06/23 17:54:56  brouard
                    926:   * 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.
                    927: 
                    928:   Revision 1.87  2003/06/18 12:26:01  brouard
                    929:   Version 0.96
                    930: 
                    931:   Revision 1.86  2003/06/17 20:04:08  brouard
                    932:   (Module): Change position of html and gnuplot routines and added
                    933:   routine fileappend.
                    934: 
                    935:   Revision 1.85  2003/06/17 13:12:43  brouard
                    936:   * imach.c (Repository): Check when date of death was earlier that
                    937:   current date of interview. It may happen when the death was just
                    938:   prior to the death. In this case, dh was negative and likelihood
                    939:   was wrong (infinity). We still send an "Error" but patch by
                    940:   assuming that the date of death was just one stepm after the
                    941:   interview.
                    942:   (Repository): Because some people have very long ID (first column)
                    943:   we changed int to long in num[] and we added a new lvector for
                    944:   memory allocation. But we also truncated to 8 characters (left
                    945:   truncation)
                    946:   (Repository): No more line truncation errors.
                    947: 
                    948:   Revision 1.84  2003/06/13 21:44:43  brouard
                    949:   * imach.c (Repository): Replace "freqsummary" at a correct
                    950:   place. It differs from routine "prevalence" which may be called
                    951:   many times. Probs is memory consuming and must be used with
                    952:   parcimony.
                    953:   Version 0.95a3 (should output exactly the same maximization than 0.8a2)
                    954: 
                    955:   Revision 1.83  2003/06/10 13:39:11  lievre
                    956:   *** empty log message ***
                    957: 
                    958:   Revision 1.82  2003/06/05 15:57:20  brouard
                    959:   Add log in  imach.c and  fullversion number is now printed.
                    960: 
                    961: */
                    962: /*
                    963:    Interpolated Markov Chain
                    964: 
                    965:   Short summary of the programme:
                    966:   
1.227     brouard   967:   This program computes Healthy Life Expectancies or State-specific
                    968:   (if states aren't health statuses) Expectancies from
                    969:   cross-longitudinal data. Cross-longitudinal data consist in: 
                    970: 
                    971:   -1- a first survey ("cross") where individuals from different ages
                    972:   are interviewed on their health status or degree of disability (in
                    973:   the case of a health survey which is our main interest)
                    974: 
                    975:   -2- at least a second wave of interviews ("longitudinal") which
                    976:   measure each change (if any) in individual health status.  Health
                    977:   expectancies are computed from the time spent in each health state
                    978:   according to a model. More health states you consider, more time is
                    979:   necessary to reach the Maximum Likelihood of the parameters involved
                    980:   in the model.  The simplest model is the multinomial logistic model
                    981:   where pij is the probability to be observed in state j at the second
                    982:   wave conditional to be observed in state i at the first
                    983:   wave. Therefore the model is: log(pij/pii)= aij + bij*age+ cij*sex +
                    984:   etc , where 'age' is age and 'sex' is a covariate. If you want to
                    985:   have a more complex model than "constant and age", you should modify
                    986:   the program where the markup *Covariates have to be included here
                    987:   again* invites you to do it.  More covariates you add, slower the
1.126     brouard   988:   convergence.
                    989: 
                    990:   The advantage of this computer programme, compared to a simple
                    991:   multinomial logistic model, is clear when the delay between waves is not
                    992:   identical for each individual. Also, if a individual missed an
                    993:   intermediate interview, the information is lost, but taken into
                    994:   account using an interpolation or extrapolation.  
                    995: 
                    996:   hPijx is the probability to be observed in state i at age x+h
                    997:   conditional to the observed state i at age x. The delay 'h' can be
                    998:   split into an exact number (nh*stepm) of unobserved intermediate
                    999:   states. This elementary transition (by month, quarter,
                   1000:   semester or year) is modelled as a multinomial logistic.  The hPx
                   1001:   matrix is simply the matrix product of nh*stepm elementary matrices
                   1002:   and the contribution of each individual to the likelihood is simply
                   1003:   hPijx.
                   1004: 
                   1005:   Also this programme outputs the covariance matrix of the parameters but also
1.218     brouard  1006:   of the life expectancies. It also computes the period (stable) prevalence.
                   1007: 
                   1008: Back prevalence and projections:
1.227     brouard  1009: 
                   1010:  - back_prevalence_limit(double *p, double **bprlim, double ageminpar,
                   1011:    double agemaxpar, double ftolpl, int *ncvyearp, double
                   1012:    dateprev1,double dateprev2, int firstpass, int lastpass, int
                   1013:    mobilavproj)
                   1014: 
                   1015:     Computes the back prevalence limit for any combination of
                   1016:     covariate values k at any age between ageminpar and agemaxpar and
                   1017:     returns it in **bprlim. In the loops,
                   1018: 
                   1019:    - **bprevalim(**bprlim, ***mobaverage, nlstate, *p, age, **oldm,
                   1020:        **savm, **dnewm, **doldm, **dsavm, ftolpl, ncvyearp, k);
                   1021: 
                   1022:    - hBijx Back Probability to be in state i at age x-h being in j at x
1.218     brouard  1023:    Computes for any combination of covariates k and any age between bage and fage 
                   1024:    p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   1025:                        oldm=oldms;savm=savms;
1.227     brouard  1026: 
1.267     brouard  1027:    - hbxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k, nres);
1.218     brouard  1028:      Computes the transition matrix starting at age 'age' over
                   1029:      'nhstepm*hstepm*stepm' months (i.e. until
                   1030:      age (in years)  age+nhstepm*hstepm*stepm/12) by multiplying
1.227     brouard  1031:      nhstepm*hstepm matrices. 
                   1032: 
                   1033:      Returns p3mat[i][j][h] after calling
                   1034:      p3mat[i][j][h]=matprod2(newm,
                   1035:      bmij(pmmij,cov,ncovmodel,x,nlstate,prevacurrent, dnewm, doldm,
                   1036:      dsavm,ij),\ 1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath,
                   1037:      oldm);
1.226     brouard  1038: 
                   1039: Important routines
                   1040: 
                   1041: - func (or funcone), computes logit (pij) distinguishing
                   1042:   o fixed variables (single or product dummies or quantitative);
                   1043:   o varying variables by:
                   1044:    (1) wave (single, product dummies, quantitative), 
                   1045:    (2) by age (can be month) age (done), age*age (done), age*Vn where Vn can be:
                   1046:        % fixed dummy (treated) or quantitative (not done because time-consuming);
                   1047:        % varying dummy (not done) or quantitative (not done);
                   1048: - Tricode which tests the modality of dummy variables (in order to warn with wrong or empty modalities)
                   1049:   and returns the number of efficient covariates cptcoveff and modalities nbcode[Tvar[k]][1]= 0 and nbcode[Tvar[k]][2]= 1 usually.
                   1050: - printinghtml which outputs results like life expectancy in and from a state for a combination of modalities of dummy variables
1.324   ! brouard  1051:   o There are 2*cptcoveff combinations of (0,1) for cptcoveff variables. Outputting only combinations with people, éliminating 1 1 if
1.226     brouard  1052:     race White (0 0), Black vs White (1 0), Hispanic (0 1) and 1 1 being meaningless.
1.218     brouard  1053: 
1.226     brouard  1054: 
                   1055:   
1.324   ! brouard  1056:   Authors: Nicolas Brouard (brouard@ined.fr) and Agnès Lièvre (lievre@ined.fr).
        !          1057:            Institut national d'études démographiques, Paris.
1.126     brouard  1058:   This software have been partly granted by Euro-REVES, a concerted action
                   1059:   from the European Union.
                   1060:   It is copyrighted identically to a GNU software product, ie programme and
                   1061:   software can be distributed freely for non commercial use. Latest version
                   1062:   can be accessed at http://euroreves.ined.fr/imach .
                   1063: 
                   1064:   Help to debug: LD_PRELOAD=/usr/local/lib/libnjamd.so ./imach foo.imach
                   1065:   or better on gdb : set env LD_PRELOAD=/usr/local/lib/libnjamd.so
                   1066:   
                   1067:   **********************************************************************/
                   1068: /*
                   1069:   main
                   1070:   read parameterfile
                   1071:   read datafile
                   1072:   concatwav
                   1073:   freqsummary
                   1074:   if (mle >= 1)
                   1075:     mlikeli
                   1076:   print results files
                   1077:   if mle==1 
                   1078:      computes hessian
                   1079:   read end of parameter file: agemin, agemax, bage, fage, estepm
                   1080:       begin-prev-date,...
                   1081:   open gnuplot file
                   1082:   open html file
1.145     brouard  1083:   period (stable) prevalence      | pl_nom    1-1 2-2 etc by covariate
                   1084:    for age prevalim()             | #****** V1=0  V2=1  V3=1  V4=0 ******
                   1085:                                   | 65 1 0 2 1 3 1 4 0  0.96326 0.03674
                   1086:     freexexit2 possible for memory heap.
                   1087: 
                   1088:   h Pij x                         | pij_nom  ficrestpij
                   1089:    # Cov Agex agex+h hpijx with i,j= 1-1 1-2     1-3     2-1     2-2     2-3
                   1090:        1  85   85    1.00000             0.00000 0.00000 0.00000 1.00000 0.00000
                   1091:        1  85   86    0.68299             0.22291 0.09410 0.71093 0.00000 0.28907
                   1092: 
                   1093:        1  65   99    0.00364             0.00322 0.99314 0.00350 0.00310 0.99340
                   1094:        1  65  100    0.00214             0.00204 0.99581 0.00206 0.00196 0.99597
                   1095:   variance of p one-step probabilities varprob  | prob_nom   ficresprob #One-step probabilities and stand. devi in ()
                   1096:    Standard deviation of one-step probabilities | probcor_nom   ficresprobcor #One-step probabilities and correlation matrix
                   1097:    Matrix of variance covariance of one-step probabilities |  probcov_nom ficresprobcov #One-step probabilities and covariance matrix
                   1098: 
1.126     brouard  1099:   forecasting if prevfcast==1 prevforecast call prevalence()
                   1100:   health expectancies
                   1101:   Variance-covariance of DFLE
                   1102:   prevalence()
                   1103:    movingaverage()
                   1104:   varevsij() 
                   1105:   if popbased==1 varevsij(,popbased)
                   1106:   total life expectancies
                   1107:   Variance of period (stable) prevalence
                   1108:  end
                   1109: */
                   1110: 
1.187     brouard  1111: /* #define DEBUG */
                   1112: /* #define DEBUGBRENT */
1.203     brouard  1113: /* #define DEBUGLINMIN */
                   1114: /* #define DEBUGHESS */
                   1115: #define DEBUGHESSIJ
1.224     brouard  1116: /* #define LINMINORIGINAL  /\* Don't use loop on scale in linmin (accepting nan) *\/ */
1.165     brouard  1117: #define POWELL /* Instead of NLOPT */
1.224     brouard  1118: #define POWELLNOF3INFF1TEST /* Skip test */
1.186     brouard  1119: /* #define POWELLORIGINAL /\* Don't use Directest to decide new direction but original Powell test *\/ */
                   1120: /* #define MNBRAKORIGINAL /\* Don't use mnbrak fix *\/ */
1.319     brouard  1121: /* #define FLATSUP  *//* Suppresses directions where likelihood is flat */
1.126     brouard  1122: 
                   1123: #include <math.h>
                   1124: #include <stdio.h>
                   1125: #include <stdlib.h>
                   1126: #include <string.h>
1.226     brouard  1127: #include <ctype.h>
1.159     brouard  1128: 
                   1129: #ifdef _WIN32
                   1130: #include <io.h>
1.172     brouard  1131: #include <windows.h>
                   1132: #include <tchar.h>
1.159     brouard  1133: #else
1.126     brouard  1134: #include <unistd.h>
1.159     brouard  1135: #endif
1.126     brouard  1136: 
                   1137: #include <limits.h>
                   1138: #include <sys/types.h>
1.171     brouard  1139: 
                   1140: #if defined(__GNUC__)
                   1141: #include <sys/utsname.h> /* Doesn't work on Windows */
                   1142: #endif
                   1143: 
1.126     brouard  1144: #include <sys/stat.h>
                   1145: #include <errno.h>
1.159     brouard  1146: /* extern int errno; */
1.126     brouard  1147: 
1.157     brouard  1148: /* #ifdef LINUX */
                   1149: /* #include <time.h> */
                   1150: /* #include "timeval.h" */
                   1151: /* #else */
                   1152: /* #include <sys/time.h> */
                   1153: /* #endif */
                   1154: 
1.126     brouard  1155: #include <time.h>
                   1156: 
1.136     brouard  1157: #ifdef GSL
                   1158: #include <gsl/gsl_errno.h>
                   1159: #include <gsl/gsl_multimin.h>
                   1160: #endif
                   1161: 
1.167     brouard  1162: 
1.162     brouard  1163: #ifdef NLOPT
                   1164: #include <nlopt.h>
                   1165: typedef struct {
                   1166:   double (* function)(double [] );
                   1167: } myfunc_data ;
                   1168: #endif
                   1169: 
1.126     brouard  1170: /* #include <libintl.h> */
                   1171: /* #define _(String) gettext (String) */
                   1172: 
1.251     brouard  1173: #define MAXLINE 2048 /* Was 256 and 1024. Overflow with 312 with 2 states and 4 covariates. Should be ok */
1.126     brouard  1174: 
                   1175: #define GNUPLOTPROGRAM "gnuplot"
                   1176: /*#define GNUPLOTPROGRAM "..\\gp37mgw\\wgnuplot"*/
                   1177: #define FILENAMELENGTH 132
                   1178: 
                   1179: #define        GLOCK_ERROR_NOPATH              -1      /* empty path */
                   1180: #define        GLOCK_ERROR_GETCWD              -2      /* cannot get cwd */
                   1181: 
1.144     brouard  1182: #define MAXPARM 128 /**< Maximum number of parameters for the optimization */
                   1183: #define NPARMAX 64 /**< (nlstate+ndeath-1)*nlstate*ncovmodel */
1.126     brouard  1184: 
                   1185: #define NINTERVMAX 8
1.144     brouard  1186: #define NLSTATEMAX 8 /**< Maximum number of live states (for func) */
                   1187: #define NDEATHMAX 8 /**< Maximum number of dead states (for func) */
1.318     brouard  1188: #define NCOVMAX 30  /**< Maximum number of covariates, including generated covariates V1*V2 */
1.197     brouard  1189: #define codtabm(h,k)  (1 & (h-1) >> (k-1))+1
1.211     brouard  1190: /*#define decodtabm(h,k,cptcoveff)= (h <= (1<<cptcoveff)?(((h-1) >> (k-1)) & 1) +1 : -1)*/
                   1191: #define decodtabm(h,k,cptcoveff) (((h-1) >> (k-1)) & 1) +1 
1.290     brouard  1192: /*#define MAXN 20000 */ /* Should by replaced by nobs, real number of observations and unlimited */
1.144     brouard  1193: #define YEARM 12. /**< Number of months per year */
1.218     brouard  1194: /* #define AGESUP 130 */
1.288     brouard  1195: /* #define AGESUP 150 */
                   1196: #define AGESUP 200
1.268     brouard  1197: #define AGEINF 0
1.218     brouard  1198: #define AGEMARGE 25 /* Marge for agemin and agemax for(iage=agemin-AGEMARGE; iage <= agemax+3+AGEMARGE; iage++) */
1.126     brouard  1199: #define AGEBASE 40
1.194     brouard  1200: #define AGEOVERFLOW 1.e20
1.164     brouard  1201: #define AGEGOMP 10 /**< Minimal age for Gompertz adjustment */
1.157     brouard  1202: #ifdef _WIN32
                   1203: #define DIRSEPARATOR '\\'
                   1204: #define CHARSEPARATOR "\\"
                   1205: #define ODIRSEPARATOR '/'
                   1206: #else
1.126     brouard  1207: #define DIRSEPARATOR '/'
                   1208: #define CHARSEPARATOR "/"
                   1209: #define ODIRSEPARATOR '\\'
                   1210: #endif
                   1211: 
1.324   ! brouard  1212: /* $Id: imach.c,v 1.323 2022/07/22 12:30:08 brouard Exp $ */
1.126     brouard  1213: /* $State: Exp $ */
1.196     brouard  1214: #include "version.h"
                   1215: char version[]=__IMACH_VERSION__;
1.323     brouard  1216: char copyright[]="July 2022,INED-EUROREVES-Institut de longevite-Japan Society for the Promotion of Science (Grant-in-Aid for Scientific Research 25293121), Intel Software 2015-2020, Nihon University 2021-202, INED 2000-2022";
1.324   ! brouard  1217: char fullversion[]="$Revision: 1.323 $ $Date: 2022/07/22 12:30:08 $"; 
1.126     brouard  1218: char strstart[80];
                   1219: char optionfilext[10], optionfilefiname[FILENAMELENGTH];
1.130     brouard  1220: int erreur=0, nberr=0, nbwarn=0; /* Error number, number of errors number of warnings  */
1.187     brouard  1221: int nagesqr=0, nforce=0; /* nagesqr=1 if model is including age*age, number of forces */
1.145     brouard  1222: /* Number of covariates model=V2+V1+ V3*age+V2*V4 */
                   1223: int cptcovn=0; /**< cptcovn number of covariates added in the model (excepting constant and age and age*product) */
                   1224: int cptcovt=0; /**< cptcovt number of covariates added in the model (excepting constant and age) */
1.225     brouard  1225: int cptcovs=0; /**< cptcovs number of simple covariates in the model V2+V1 =2 */
                   1226: int cptcovsnq=0; /**< cptcovsnq number of simple covariates in the model but non quantitative V2+V1 =2 */
1.145     brouard  1227: int cptcovage=0; /**< Number of covariates with age: V3*age only =1 */
                   1228: int cptcovprodnoage=0; /**< Number of covariate products without age */   
                   1229: int cptcoveff=0; /* Total number of covariates to vary for printing results */
1.233     brouard  1230: int ncovf=0; /* Total number of effective fixed covariates (dummy or quantitative) in the model */
                   1231: int ncovv=0; /* Total number of effective (wave) varying covariates (dummy or quantitative) in the model */
1.232     brouard  1232: int ncova=0; /* Total number of effective (wave and stepm) varying with age covariates (dummy of quantitative) in the model */
1.234     brouard  1233: int nsd=0; /**< Total number of single dummy variables (output) */
                   1234: int nsq=0; /**< Total number of single quantitative variables (output) */
1.232     brouard  1235: int ncoveff=0; /* Total number of effective fixed dummy covariates in the model */
1.225     brouard  1236: int nqfveff=0; /**< nqfveff Number of Quantitative Fixed Variables Effective */
1.224     brouard  1237: int ntveff=0; /**< ntveff number of effective time varying variables */
                   1238: int nqtveff=0; /**< ntqveff number of effective time varying quantitative variables */
1.145     brouard  1239: int cptcov=0; /* Working variable */
1.290     brouard  1240: int nobs=10;  /* Number of observations in the data lastobs-firstobs */
1.218     brouard  1241: int ncovcombmax=NCOVMAX; /* Maximum calculated number of covariate combination = pow(2, cptcoveff) */
1.302     brouard  1242: int npar=NPARMAX; /* Number of parameters (nlstate+ndeath-1)*nlstate*ncovmodel; */
1.126     brouard  1243: int nlstate=2; /* Number of live states */
                   1244: int ndeath=1; /* Number of dead states */
1.130     brouard  1245: int ncovmodel=0, ncovcol=0;     /* Total number of covariables including constant a12*1 +b12*x ncovmodel=2 */
1.223     brouard  1246: int  nqv=0, ntv=0, nqtv=0;    /* Total number of quantitative variables, time variable (dummy), quantitative and time variable */ 
1.126     brouard  1247: int popbased=0;
                   1248: 
                   1249: int *wav; /* Number of waves for this individuual 0 is possible */
1.130     brouard  1250: int maxwav=0; /* Maxim number of waves */
                   1251: int jmin=0, jmax=0; /* min, max spacing between 2 waves */
                   1252: int ijmin=0, ijmax=0; /* Individuals having jmin and jmax */ 
                   1253: int gipmx=0, gsw=0; /* Global variables on the number of contributions 
1.126     brouard  1254:                   to the likelihood and the sum of weights (done by funcone)*/
1.130     brouard  1255: int mle=1, weightopt=0;
1.126     brouard  1256: int **mw; /* mw[mi][i] is number of the mi wave for this individual */
                   1257: int **dh; /* dh[mi][i] is number of steps between mi,mi+1 for this individual */
                   1258: int **bh; /* bh[mi][i] is the bias (+ or -) for this individual if the delay between
                   1259:           * wave mi and wave mi+1 is not an exact multiple of stepm. */
1.162     brouard  1260: int countcallfunc=0;  /* Count the number of calls to func */
1.230     brouard  1261: int selected(int kvar); /* Is covariate kvar selected for printing results */
                   1262: 
1.130     brouard  1263: double jmean=1; /* Mean space between 2 waves */
1.145     brouard  1264: double **matprod2(); /* test */
1.126     brouard  1265: double **oldm, **newm, **savm; /* Working pointers to matrices */
                   1266: double **oldms, **newms, **savms; /* Fixed working pointers to matrices */
1.218     brouard  1267: double  **ddnewms, **ddoldms, **ddsavms; /* for freeing later */
                   1268: 
1.136     brouard  1269: /*FILE *fic ; */ /* Used in readdata only */
1.217     brouard  1270: FILE *ficpar, *ficparo,*ficres, *ficresp, *ficresphtm, *ficresphtmfr, *ficrespl, *ficresplb,*ficrespij, *ficrespijb, *ficrest,*ficresf, *ficresfb,*ficrespop;
1.126     brouard  1271: FILE *ficlog, *ficrespow;
1.130     brouard  1272: int globpr=0; /* Global variable for printing or not */
1.126     brouard  1273: double fretone; /* Only one call to likelihood */
1.130     brouard  1274: long ipmx=0; /* Number of contributions */
1.126     brouard  1275: double sw; /* Sum of weights */
                   1276: char filerespow[FILENAMELENGTH];
                   1277: char fileresilk[FILENAMELENGTH]; /* File of individual contributions to the likelihood */
                   1278: FILE *ficresilk;
                   1279: FILE *ficgp,*ficresprob,*ficpop, *ficresprobcov, *ficresprobcor;
                   1280: FILE *ficresprobmorprev;
                   1281: FILE *fichtm, *fichtmcov; /* Html File */
                   1282: FILE *ficreseij;
                   1283: char filerese[FILENAMELENGTH];
                   1284: FILE *ficresstdeij;
                   1285: char fileresstde[FILENAMELENGTH];
                   1286: FILE *ficrescveij;
                   1287: char filerescve[FILENAMELENGTH];
                   1288: FILE  *ficresvij;
                   1289: char fileresv[FILENAMELENGTH];
1.269     brouard  1290: 
1.126     brouard  1291: char title[MAXLINE];
1.234     brouard  1292: char model[MAXLINE]; /**< The model line */
1.217     brouard  1293: char optionfile[FILENAMELENGTH], datafile[FILENAMELENGTH],  filerespl[FILENAMELENGTH],  fileresplb[FILENAMELENGTH];
1.126     brouard  1294: char plotcmd[FILENAMELENGTH], pplotcmd[FILENAMELENGTH];
                   1295: char tmpout[FILENAMELENGTH],  tmpout2[FILENAMELENGTH]; 
                   1296: char command[FILENAMELENGTH];
                   1297: int  outcmd=0;
                   1298: 
1.217     brouard  1299: char fileres[FILENAMELENGTH], filerespij[FILENAMELENGTH], filerespijb[FILENAMELENGTH], filereso[FILENAMELENGTH], rfileres[FILENAMELENGTH];
1.202     brouard  1300: char fileresu[FILENAMELENGTH]; /* fileres without r in front */
1.126     brouard  1301: char filelog[FILENAMELENGTH]; /* Log file */
                   1302: char filerest[FILENAMELENGTH];
                   1303: char fileregp[FILENAMELENGTH];
                   1304: char popfile[FILENAMELENGTH];
                   1305: 
                   1306: char optionfilegnuplot[FILENAMELENGTH], optionfilehtm[FILENAMELENGTH], optionfilehtmcov[FILENAMELENGTH] ;
                   1307: 
1.157     brouard  1308: /* struct timeval start_time, end_time, curr_time, last_time, forecast_time; */
                   1309: /* struct timezone tzp; */
                   1310: /* extern int gettimeofday(); */
                   1311: struct tm tml, *gmtime(), *localtime();
                   1312: 
                   1313: extern time_t time();
                   1314: 
                   1315: struct tm start_time, end_time, curr_time, last_time, forecast_time;
                   1316: time_t  rstart_time, rend_time, rcurr_time, rlast_time, rforecast_time; /* raw time */
                   1317: struct tm tm;
                   1318: 
1.126     brouard  1319: char strcurr[80], strfor[80];
                   1320: 
                   1321: char *endptr;
                   1322: long lval;
                   1323: double dval;
                   1324: 
                   1325: #define NR_END 1
                   1326: #define FREE_ARG char*
                   1327: #define FTOL 1.0e-10
                   1328: 
                   1329: #define NRANSI 
1.240     brouard  1330: #define ITMAX 200
                   1331: #define ITPOWMAX 20 /* This is now multiplied by the number of parameters */ 
1.126     brouard  1332: 
                   1333: #define TOL 2.0e-4 
                   1334: 
                   1335: #define CGOLD 0.3819660 
                   1336: #define ZEPS 1.0e-10 
                   1337: #define SHFT(a,b,c,d) (a)=(b);(b)=(c);(c)=(d); 
                   1338: 
                   1339: #define GOLD 1.618034 
                   1340: #define GLIMIT 100.0 
                   1341: #define TINY 1.0e-20 
                   1342: 
                   1343: static double maxarg1,maxarg2;
                   1344: #define FMAX(a,b) (maxarg1=(a),maxarg2=(b),(maxarg1)>(maxarg2)? (maxarg1):(maxarg2))
                   1345: #define FMIN(a,b) (maxarg1=(a),maxarg2=(b),(maxarg1)<(maxarg2)? (maxarg1):(maxarg2))
                   1346:   
                   1347: #define SIGN(a,b) ((b)>0.0 ? fabs(a) : -fabs(a))
                   1348: #define rint(a) floor(a+0.5)
1.166     brouard  1349: /* http://www.thphys.uni-heidelberg.de/~robbers/cmbeasy/doc/html/myutils_8h-source.html */
1.183     brouard  1350: #define mytinydouble 1.0e-16
1.166     brouard  1351: /* #define DEQUAL(a,b) (fabs((a)-(b))<mytinydouble) */
                   1352: /* http://www.thphys.uni-heidelberg.de/~robbers/cmbeasy/doc/html/mynrutils_8h-source.html */
                   1353: /* static double dsqrarg; */
                   1354: /* #define DSQR(a) (DEQUAL((dsqrarg=(a)),0.0) ? 0.0 : dsqrarg*dsqrarg) */
1.126     brouard  1355: static double sqrarg;
                   1356: #define SQR(a) ((sqrarg=(a)) == 0.0 ? 0.0 :sqrarg*sqrarg)
                   1357: #define SWAP(a,b) {temp=(a);(a)=(b);(b)=temp;} 
                   1358: int agegomp= AGEGOMP;
                   1359: 
                   1360: int imx; 
                   1361: int stepm=1;
                   1362: /* Stepm, step in month: minimum step interpolation*/
                   1363: 
                   1364: int estepm;
                   1365: /* Estepm, step in month to interpolate survival function in order to approximate Life Expectancy*/
                   1366: 
                   1367: int m,nb;
                   1368: long *num;
1.197     brouard  1369: int firstpass=0, lastpass=4,*cod, *cens;
1.192     brouard  1370: int *ncodemax;  /* ncodemax[j]= Number of modalities of the j th
                   1371:                   covariate for which somebody answered excluding 
                   1372:                   undefined. Usually 2: 0 and 1. */
                   1373: int *ncodemaxwundef;  /* ncodemax[j]= Number of modalities of the j th
                   1374:                             covariate for which somebody answered including 
                   1375:                             undefined. Usually 3: -1, 0 and 1. */
1.126     brouard  1376: double **agev,*moisnais, *annais, *moisdc, *andc,**mint, **anint;
1.218     brouard  1377: double **pmmij, ***probs; /* Global pointer */
1.219     brouard  1378: double ***mobaverage, ***mobaverages; /* New global variable */
1.126     brouard  1379: double *ageexmed,*agecens;
                   1380: double dateintmean=0;
1.296     brouard  1381:   double anprojd, mprojd, jprojd; /* For eventual projections */
                   1382:   double anprojf, mprojf, jprojf;
1.126     brouard  1383: 
1.296     brouard  1384:   double anbackd, mbackd, jbackd; /* For eventual backprojections */
                   1385:   double anbackf, mbackf, jbackf;
                   1386:   double jintmean,mintmean,aintmean;  
1.126     brouard  1387: double *weight;
                   1388: int **s; /* Status */
1.141     brouard  1389: double *agedc;
1.145     brouard  1390: double  **covar; /**< covar[j,i], value of jth covariate for individual i,
1.141     brouard  1391:                  * covar=matrix(0,NCOVMAX,1,n); 
1.187     brouard  1392:                  * cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*age; */
1.268     brouard  1393: double **coqvar; /* Fixed quantitative covariate nqv */
                   1394: double ***cotvar; /* Time varying covariate ntv */
1.225     brouard  1395: double ***cotqvar; /* Time varying quantitative covariate itqv */
1.141     brouard  1396: double  idx; 
                   1397: int **nbcode, *Tvar; /**< model=V2 => Tvar[1]= 2 */
1.319     brouard  1398: /* Some documentation */
                   1399:       /*   Design original data
                   1400:        *  V1   V2   V3   V4  V5  V6  V7  V8  Weight ddb ddth d1st s1 V9 V10 V11 V12 s2 V9 V10 V11 V12 
                   1401:        *  <          ncovcol=6   >   nqv=2 (V7 V8)                   dv dv  dv  qtv    dv dv  dvv qtv
                   1402:        *                                                             ntv=3     nqtv=1
                   1403:        *  cptcovn number of covariates (not including constant and age) = # of + plus 1 = 10+1=11
                   1404:        * For time varying covariate, quanti or dummies
                   1405:        *       cotqvar[wav][iv(1 to nqtv)][i]= [1][12][i]=(V12) quanti
                   1406:        *       cotvar[wav][ntv+iv][i]= [3+(1 to nqtv)][i]=(V12) quanti
                   1407:        *       cotvar[wav][iv(1 to ntv)][i]= [1][1][i]=(V9) dummies at wav 1
                   1408:        *       cotvar[wav][iv(1 to ntv)][i]= [1][2][i]=(V10) dummies at wav 1
                   1409:        *       covar[k,i], value of kth fixed covariate dummy or quanti :
                   1410:        *       covar[1][i]= (V1), covar[4][i]=(V4), covar[8][i]=(V8)
                   1411:        * Model V2 + V1 + V3*age + V3 + V5*V6 + V7*V8 + V8*age + V8 + V9 + V9*age + V10
                   1412:        *   k=  1    2      3       4     5       6      7        8   9     10       11 
                   1413:        */
                   1414: /* According to the model, more columns can be added to covar by the product of covariates */
1.318     brouard  1415: /* ncovcol=1(Males=0 Females=1) nqv=1(raedyrs) ntv=2(withoutiadl=0 withiadl=1, witoutadl=0 withoutadl=1) nqtv=1(bmi) nlstate=3 ndeath=1
                   1416:   # States 1=Coresidence, 2 Living alone, 3 Institution
                   1417:   # V1=sex, V2=raedyrs Quant Fixed, State=livarnb4..livarnb11, V3=iadl4..iald11, V4=adlw4..adlw11, V5=r4bmi..r11bmi
                   1418: */
1.319     brouard  1419: /*             V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
                   1420: /*    k        1  2   3   4     5    6    7     8    9 */
                   1421: /*Typevar[k]=  0  0   0   2     1    0    2     1    0 *//*0 for simple covariate (dummy, quantitative,*/
                   1422:                                                          /* fixed or varying), 1 for age product, 2 for*/
                   1423:                                                          /* product */
                   1424: /*Dummy[k]=    1  0   0   1     3    1    1     2    0 *//*Dummy[k] 0=dummy (0 1), 1 quantitative */
                   1425:                                                          /*(single or product without age), 2 dummy*/
                   1426:                                                          /* with age product, 3 quant with age product*/
                   1427: /*Tvar[k]=     5  4   3   6     5    2    7     1    1 */
                   1428: /*    nsd         1   2                              3 */ /* Counting single dummies covar fixed or tv */
                   1429: /*TvarsD[nsd]     4   3                              1 */ /* ID of single dummy cova fixed or timevary*/
                   1430: /*TvarsDind[k]    2   3                              9 */ /* position K of single dummy cova */
                   1431: /*    nsq      1                     2                 */ /* Counting single quantit tv */
                   1432: /* TvarsQ[k]   5                     2                 */ /* Number of single quantitative cova */
                   1433: /* TvarsQind   1                     6                 */ /* position K of single quantitative cova */
                   1434: /* Tprod[i]=k             1               2            */ /* Position in model of the ith prod without age */
                   1435: /* cptcovage                    1               2      */ /* Counting cov*age in the model equation */
                   1436: /* Tage[cptcovage]=k            5               8      */ /* Position in the model of ith cov*age */
                   1437: /* Tvard[1][1]@4={4,3,1,2}    V4*V3 V1*V2              */ /* Position in model of the ith prod without age */
                   1438: /* TvarF TvarF[1]=Tvar[6]=2,  TvarF[2]=Tvar[7]=7, TvarF[3]=Tvar[9]=1  ID of fixed covariates or product V2, V1*V2, V1 */
1.320     brouard  1439: /* TvarFind;  TvarFind[1]=6,  TvarFind[2]=7, TvarFind[3]=9 *//* Inverse V2(6) is first fixed (single or prod)  */
1.234     brouard  1440: /* Type                    */
                   1441: /* V         1  2  3  4  5 */
                   1442: /*           F  F  V  V  V */
                   1443: /*           D  Q  D  D  Q */
                   1444: /*                         */
                   1445: int *TvarsD;
                   1446: int *TvarsDind;
                   1447: int *TvarsQ;
                   1448: int *TvarsQind;
                   1449: 
1.318     brouard  1450: #define MAXRESULTLINESPONE 10+1
1.235     brouard  1451: int nresult=0;
1.258     brouard  1452: int parameterline=0; /* # of the parameter (type) line */
1.318     brouard  1453: int TKresult[MAXRESULTLINESPONE];
                   1454: int Tresult[MAXRESULTLINESPONE][NCOVMAX];/* For dummy variable , value (output) */
                   1455: int Tinvresult[MAXRESULTLINESPONE][NCOVMAX];/* For dummy variable , value (output) */
                   1456: int Tvresult[MAXRESULTLINESPONE][NCOVMAX]; /* For dummy variable , variable # (output) */
                   1457: double Tqresult[MAXRESULTLINESPONE][NCOVMAX]; /* For quantitative variable , value (output) */
                   1458: double Tqinvresult[MAXRESULTLINESPONE][NCOVMAX]; /* For quantitative variable , value (output) */
                   1459: int Tvqresult[MAXRESULTLINESPONE][NCOVMAX]; /* For quantitative variable , variable # (output) */
                   1460: 
                   1461: /* ncovcol=1(Males=0 Females=1) nqv=1(raedyrs) ntv=2(withoutiadl=0 withiadl=1, witoutadl=0 withoutadl=1) nqtv=1(bmi) nlstate=3 ndeath=1
                   1462:   # States 1=Coresidence, 2 Living alone, 3 Institution
                   1463:   # V1=sex, V2=raedyrs Quant Fixed, State=livarnb4..livarnb11, V3=iadl4..iald11, V4=adlw4..adlw11, V5=r4bmi..r11bmi
                   1464: */
1.234     brouard  1465: /* 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  1466: 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 */
                   1467: 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 */
                   1468: 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 */
                   1469: int *TvarVind; /**< TvarVind[1]=1, TvarVind[2]=2  in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
                   1470: 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 */
                   1471: 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  1472: int *TvarFD; /**< TvarFD[1]=V1 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
                   1473: int *TvarFDind; /* TvarFDind[1]=9 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
                   1474: int *TvarFQ; /* TvarFQ[1]=V2 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */ /* Only simple fixed quantitative variable */
                   1475: int *TvarFQind; /* TvarFQind[1]=6 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */ /* Only simple fixed quantitative variable */
                   1476: int *TvarVD; /* TvarVD[1]=V5 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */ /* Only simple fixed quantitative variable */
                   1477: int *TvarVDind; /* TvarVDind[1]=1 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */ /* Only simple fixed quantitative variable */
                   1478: 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 */
                   1479: 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 */
                   1480: 
1.230     brouard  1481: int *Tvarsel; /**< Selected covariates for output */
                   1482: double *Tvalsel; /**< Selected modality value of covariate for output */
1.226     brouard  1483: int *Typevar; /**< 0 for simple covariate (dummy, quantitative, fixed or varying), 1 for age product, 2 for  product */
1.227     brouard  1484: int *Fixed; /** Fixed[k] 0=fixed, 1 varying, 2 fixed with age product, 3 varying with age product */ 
                   1485: 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  1486: int *DummyV; /** Dummy[v] 0=dummy (0 1), 1 quantitative */
                   1487: int *FixedV; /** FixedV[v] 0 fixed, 1 varying */
1.197     brouard  1488: int *Tage;
1.227     brouard  1489: int anyvaryingduminmodel=0; /**< Any varying dummy in Model=1 yes, 0 no, to avoid a loop on waves in freq */ 
1.228     brouard  1490: 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  1491: 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*/ 
                   1492: 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  1493: int *Ndum; /** Freq of modality (tricode */
1.200     brouard  1494: /* int **codtab;*/ /**< codtab=imatrix(1,100,1,10); */
1.227     brouard  1495: int **Tvard;
                   1496: int *Tprod;/**< Gives the k position of the k1 product */
1.238     brouard  1497: /* Tprod[k1=1]=3(=V1*V4) for V2+V1+V1*V4+age*V3  */
1.227     brouard  1498: int *Tposprod; /**< Gives the k1 product from the k position */
1.238     brouard  1499:    /* if  V2+V1+V1*V4+age*V3+V3*V2   TProd[k1=2]=5 (V3*V2) */
                   1500:    /* Tposprod[k]=k1 , Tposprod[3]=1, Tposprod[5(V3*V2)]=2 (2nd product without age) */
1.227     brouard  1501: int cptcovprod, *Tvaraff, *invalidvarcomb;
1.126     brouard  1502: double *lsurv, *lpop, *tpop;
                   1503: 
1.231     brouard  1504: #define FD 1; /* Fixed dummy covariate */
                   1505: #define FQ 2; /* Fixed quantitative covariate */
                   1506: #define FP 3; /* Fixed product covariate */
                   1507: #define FPDD 7; /* Fixed product dummy*dummy covariate */
                   1508: #define FPDQ 8; /* Fixed product dummy*quantitative covariate */
                   1509: #define FPQQ 9; /* Fixed product quantitative*quantitative covariate */
                   1510: #define VD 10; /* Varying dummy covariate */
                   1511: #define VQ 11; /* Varying quantitative covariate */
                   1512: #define VP 12; /* Varying product covariate */
                   1513: #define VPDD 13; /* Varying product dummy*dummy covariate */
                   1514: #define VPDQ 14; /* Varying product dummy*quantitative covariate */
                   1515: #define VPQQ 15; /* Varying product quantitative*quantitative covariate */
                   1516: #define APFD 16; /* Age product * fixed dummy covariate */
                   1517: #define APFQ 17; /* Age product * fixed quantitative covariate */
                   1518: #define APVD 18; /* Age product * varying dummy covariate */
                   1519: #define APVQ 19; /* Age product * varying quantitative covariate */
                   1520: 
                   1521: #define FTYPE 1; /* Fixed covariate */
                   1522: #define VTYPE 2; /* Varying covariate (loop in wave) */
                   1523: #define ATYPE 2; /* Age product covariate (loop in dh within wave)*/
                   1524: 
                   1525: struct kmodel{
                   1526:        int maintype; /* main type */
                   1527:        int subtype; /* subtype */
                   1528: };
                   1529: struct kmodel modell[NCOVMAX];
                   1530: 
1.143     brouard  1531: double ftol=FTOL; /**< Tolerance for computing Max Likelihood */
                   1532: double ftolhess; /**< Tolerance for computing hessian */
1.126     brouard  1533: 
                   1534: /**************** split *************************/
                   1535: static int split( char *path, char *dirc, char *name, char *ext, char *finame )
                   1536: {
                   1537:   /* From a file name with (full) path (either Unix or Windows) we extract the directory (dirc)
                   1538:      the name of the file (name), its extension only (ext) and its first part of the name (finame)
                   1539:   */ 
                   1540:   char *ss;                            /* pointer */
1.186     brouard  1541:   int  l1=0, l2=0;                             /* length counters */
1.126     brouard  1542: 
                   1543:   l1 = strlen(path );                  /* length of path */
                   1544:   if ( l1 == 0 ) return( GLOCK_ERROR_NOPATH );
                   1545:   ss= strrchr( path, DIRSEPARATOR );           /* find last / */
                   1546:   if ( ss == NULL ) {                  /* no directory, so determine current directory */
                   1547:     strcpy( name, path );              /* we got the fullname name because no directory */
                   1548:     /*if(strrchr(path, ODIRSEPARATOR )==NULL)
                   1549:       printf("Warning you should use %s as a separator\n",DIRSEPARATOR);*/
                   1550:     /* get current working directory */
                   1551:     /*    extern  char* getcwd ( char *buf , int len);*/
1.184     brouard  1552: #ifdef WIN32
                   1553:     if (_getcwd( dirc, FILENAME_MAX ) == NULL ) {
                   1554: #else
                   1555:        if (getcwd(dirc, FILENAME_MAX) == NULL) {
                   1556: #endif
1.126     brouard  1557:       return( GLOCK_ERROR_GETCWD );
                   1558:     }
                   1559:     /* got dirc from getcwd*/
                   1560:     printf(" DIRC = %s \n",dirc);
1.205     brouard  1561:   } else {                             /* strip directory from path */
1.126     brouard  1562:     ss++;                              /* after this, the filename */
                   1563:     l2 = strlen( ss );                 /* length of filename */
                   1564:     if ( l2 == 0 ) return( GLOCK_ERROR_NOPATH );
                   1565:     strcpy( name, ss );                /* save file name */
                   1566:     strncpy( dirc, path, l1 - l2 );    /* now the directory */
1.186     brouard  1567:     dirc[l1-l2] = '\0';                        /* add zero */
1.126     brouard  1568:     printf(" DIRC2 = %s \n",dirc);
                   1569:   }
                   1570:   /* We add a separator at the end of dirc if not exists */
                   1571:   l1 = strlen( dirc );                 /* length of directory */
                   1572:   if( dirc[l1-1] != DIRSEPARATOR ){
                   1573:     dirc[l1] =  DIRSEPARATOR;
                   1574:     dirc[l1+1] = 0; 
                   1575:     printf(" DIRC3 = %s \n",dirc);
                   1576:   }
                   1577:   ss = strrchr( name, '.' );           /* find last / */
                   1578:   if (ss >0){
                   1579:     ss++;
                   1580:     strcpy(ext,ss);                    /* save extension */
                   1581:     l1= strlen( name);
                   1582:     l2= strlen(ss)+1;
                   1583:     strncpy( finame, name, l1-l2);
                   1584:     finame[l1-l2]= 0;
                   1585:   }
                   1586: 
                   1587:   return( 0 );                         /* we're done */
                   1588: }
                   1589: 
                   1590: 
                   1591: /******************************************/
                   1592: 
                   1593: void replace_back_to_slash(char *s, char*t)
                   1594: {
                   1595:   int i;
                   1596:   int lg=0;
                   1597:   i=0;
                   1598:   lg=strlen(t);
                   1599:   for(i=0; i<= lg; i++) {
                   1600:     (s[i] = t[i]);
                   1601:     if (t[i]== '\\') s[i]='/';
                   1602:   }
                   1603: }
                   1604: 
1.132     brouard  1605: char *trimbb(char *out, char *in)
1.137     brouard  1606: { /* Trim multiple blanks in line but keeps first blanks if line starts with blanks */
1.132     brouard  1607:   char *s;
                   1608:   s=out;
                   1609:   while (*in != '\0'){
1.137     brouard  1610:     while( *in == ' ' && *(in+1) == ' '){ /* && *(in+1) != '\0'){*/
1.132     brouard  1611:       in++;
                   1612:     }
                   1613:     *out++ = *in++;
                   1614:   }
                   1615:   *out='\0';
                   1616:   return s;
                   1617: }
                   1618: 
1.187     brouard  1619: /* char *substrchaine(char *out, char *in, char *chain) */
                   1620: /* { */
                   1621: /*   /\* Substract chain 'chain' from 'in', return and output 'out' *\/ */
                   1622: /*   char *s, *t; */
                   1623: /*   t=in;s=out; */
                   1624: /*   while ((*in != *chain) && (*in != '\0')){ */
                   1625: /*     *out++ = *in++; */
                   1626: /*   } */
                   1627: 
                   1628: /*   /\* *in matches *chain *\/ */
                   1629: /*   while ((*in++ == *chain++) && (*in != '\0')){ */
                   1630: /*     printf("*in = %c, *out= %c *chain= %c \n", *in, *out, *chain);  */
                   1631: /*   } */
                   1632: /*   in--; chain--; */
                   1633: /*   while ( (*in != '\0')){ */
                   1634: /*     printf("Bef *in = %c, *out= %c *chain= %c \n", *in, *out, *chain);  */
                   1635: /*     *out++ = *in++; */
                   1636: /*     printf("Aft *in = %c, *out= %c *chain= %c \n", *in, *out, *chain);  */
                   1637: /*   } */
                   1638: /*   *out='\0'; */
                   1639: /*   out=s; */
                   1640: /*   return out; */
                   1641: /* } */
                   1642: char *substrchaine(char *out, char *in, char *chain)
                   1643: {
                   1644:   /* Substract chain 'chain' from 'in', return and output 'out' */
                   1645:   /* in="V1+V1*age+age*age+V2", chain="age*age" */
                   1646: 
                   1647:   char *strloc;
                   1648: 
                   1649:   strcpy (out, in); 
                   1650:   strloc = strstr(out, chain); /* strloc points to out at age*age+V2 */
                   1651:   printf("Bef strloc=%s chain=%s out=%s \n", strloc, chain, out);
                   1652:   if(strloc != NULL){ 
                   1653:     /* will affect out */ /* strloc+strlenc(chain)=+V2 */ /* Will also work in Unicode */
                   1654:     memmove(strloc,strloc+strlen(chain), strlen(strloc+strlen(chain))+1);
                   1655:     /* strcpy (strloc, strloc +strlen(chain));*/
                   1656:   }
                   1657:   printf("Aft strloc=%s chain=%s in=%s out=%s \n", strloc, chain, in, out);
                   1658:   return out;
                   1659: }
                   1660: 
                   1661: 
1.145     brouard  1662: char *cutl(char *blocc, char *alocc, char *in, char occ)
                   1663: {
1.187     brouard  1664:   /* cuts string in into blocc and alocc where blocc ends before FIRST occurence of char 'occ' 
1.145     brouard  1665:      and alocc starts after first occurence of char 'occ' : ex cutv(blocc,alocc,"abcdef2ghi2j",'2')
1.310     brouard  1666:      gives alocc="abcdef" and blocc="ghi2j".
1.145     brouard  1667:      If occ is not found blocc is null and alocc is equal to in. Returns blocc
                   1668:   */
1.160     brouard  1669:   char *s, *t;
1.145     brouard  1670:   t=in;s=in;
                   1671:   while ((*in != occ) && (*in != '\0')){
                   1672:     *alocc++ = *in++;
                   1673:   }
                   1674:   if( *in == occ){
                   1675:     *(alocc)='\0';
                   1676:     s=++in;
                   1677:   }
                   1678:  
                   1679:   if (s == t) {/* occ not found */
                   1680:     *(alocc-(in-s))='\0';
                   1681:     in=s;
                   1682:   }
                   1683:   while ( *in != '\0'){
                   1684:     *blocc++ = *in++;
                   1685:   }
                   1686: 
                   1687:   *blocc='\0';
                   1688:   return t;
                   1689: }
1.137     brouard  1690: char *cutv(char *blocc, char *alocc, char *in, char occ)
                   1691: {
1.187     brouard  1692:   /* cuts string in into blocc and alocc where blocc ends before LAST occurence of char 'occ' 
1.137     brouard  1693:      and alocc starts after last occurence of char 'occ' : ex cutv(blocc,alocc,"abcdef2ghi2j",'2')
                   1694:      gives blocc="abcdef2ghi" and alocc="j".
                   1695:      If occ is not found blocc is null and alocc is equal to in. Returns alocc
                   1696:   */
                   1697:   char *s, *t;
                   1698:   t=in;s=in;
                   1699:   while (*in != '\0'){
                   1700:     while( *in == occ){
                   1701:       *blocc++ = *in++;
                   1702:       s=in;
                   1703:     }
                   1704:     *blocc++ = *in++;
                   1705:   }
                   1706:   if (s == t) /* occ not found */
                   1707:     *(blocc-(in-s))='\0';
                   1708:   else
                   1709:     *(blocc-(in-s)-1)='\0';
                   1710:   in=s;
                   1711:   while ( *in != '\0'){
                   1712:     *alocc++ = *in++;
                   1713:   }
                   1714: 
                   1715:   *alocc='\0';
                   1716:   return s;
                   1717: }
                   1718: 
1.126     brouard  1719: int nbocc(char *s, char occ)
                   1720: {
                   1721:   int i,j=0;
                   1722:   int lg=20;
                   1723:   i=0;
                   1724:   lg=strlen(s);
                   1725:   for(i=0; i<= lg; i++) {
1.234     brouard  1726:     if  (s[i] == occ ) j++;
1.126     brouard  1727:   }
                   1728:   return j;
                   1729: }
                   1730: 
1.137     brouard  1731: /* void cutv(char *u,char *v, char*t, char occ) */
                   1732: /* { */
                   1733: /*   /\* cuts string t into u and v where u ends before last occurence of char 'occ'  */
                   1734: /*      and v starts after last occurence of char 'occ' : ex cutv(u,v,"abcdef2ghi2j",'2') */
                   1735: /*      gives u="abcdef2ghi" and v="j" *\/ */
                   1736: /*   int i,lg,j,p=0; */
                   1737: /*   i=0; */
                   1738: /*   lg=strlen(t); */
                   1739: /*   for(j=0; j<=lg-1; j++) { */
                   1740: /*     if((t[j]!= occ) && (t[j+1]== occ)) p=j+1; */
                   1741: /*   } */
1.126     brouard  1742: 
1.137     brouard  1743: /*   for(j=0; j<p; j++) { */
                   1744: /*     (u[j] = t[j]); */
                   1745: /*   } */
                   1746: /*      u[p]='\0'; */
1.126     brouard  1747: 
1.137     brouard  1748: /*    for(j=0; j<= lg; j++) { */
                   1749: /*     if (j>=(p+1))(v[j-p-1] = t[j]); */
                   1750: /*   } */
                   1751: /* } */
1.126     brouard  1752: 
1.160     brouard  1753: #ifdef _WIN32
                   1754: char * strsep(char **pp, const char *delim)
                   1755: {
                   1756:   char *p, *q;
                   1757:          
                   1758:   if ((p = *pp) == NULL)
                   1759:     return 0;
                   1760:   if ((q = strpbrk (p, delim)) != NULL)
                   1761:   {
                   1762:     *pp = q + 1;
                   1763:     *q = '\0';
                   1764:   }
                   1765:   else
                   1766:     *pp = 0;
                   1767:   return p;
                   1768: }
                   1769: #endif
                   1770: 
1.126     brouard  1771: /********************** nrerror ********************/
                   1772: 
                   1773: void nrerror(char error_text[])
                   1774: {
                   1775:   fprintf(stderr,"ERREUR ...\n");
                   1776:   fprintf(stderr,"%s\n",error_text);
                   1777:   exit(EXIT_FAILURE);
                   1778: }
                   1779: /*********************** vector *******************/
                   1780: double *vector(int nl, int nh)
                   1781: {
                   1782:   double *v;
                   1783:   v=(double *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(double)));
                   1784:   if (!v) nrerror("allocation failure in vector");
                   1785:   return v-nl+NR_END;
                   1786: }
                   1787: 
                   1788: /************************ free vector ******************/
                   1789: void free_vector(double*v, int nl, int nh)
                   1790: {
                   1791:   free((FREE_ARG)(v+nl-NR_END));
                   1792: }
                   1793: 
                   1794: /************************ivector *******************************/
                   1795: int *ivector(long nl,long nh)
                   1796: {
                   1797:   int *v;
                   1798:   v=(int *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(int)));
                   1799:   if (!v) nrerror("allocation failure in ivector");
                   1800:   return v-nl+NR_END;
                   1801: }
                   1802: 
                   1803: /******************free ivector **************************/
                   1804: void free_ivector(int *v, long nl, long nh)
                   1805: {
                   1806:   free((FREE_ARG)(v+nl-NR_END));
                   1807: }
                   1808: 
                   1809: /************************lvector *******************************/
                   1810: long *lvector(long nl,long nh)
                   1811: {
                   1812:   long *v;
                   1813:   v=(long *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(long)));
                   1814:   if (!v) nrerror("allocation failure in ivector");
                   1815:   return v-nl+NR_END;
                   1816: }
                   1817: 
                   1818: /******************free lvector **************************/
                   1819: void free_lvector(long *v, long nl, long nh)
                   1820: {
                   1821:   free((FREE_ARG)(v+nl-NR_END));
                   1822: }
                   1823: 
                   1824: /******************* imatrix *******************************/
                   1825: int **imatrix(long nrl, long nrh, long ncl, long nch) 
                   1826:      /* allocate a int matrix with subscript range m[nrl..nrh][ncl..nch] */ 
                   1827: { 
                   1828:   long i, nrow=nrh-nrl+1,ncol=nch-ncl+1; 
                   1829:   int **m; 
                   1830:   
                   1831:   /* allocate pointers to rows */ 
                   1832:   m=(int **) malloc((size_t)((nrow+NR_END)*sizeof(int*))); 
                   1833:   if (!m) nrerror("allocation failure 1 in matrix()"); 
                   1834:   m += NR_END; 
                   1835:   m -= nrl; 
                   1836:   
                   1837:   
                   1838:   /* allocate rows and set pointers to them */ 
                   1839:   m[nrl]=(int *) malloc((size_t)((nrow*ncol+NR_END)*sizeof(int))); 
                   1840:   if (!m[nrl]) nrerror("allocation failure 2 in matrix()"); 
                   1841:   m[nrl] += NR_END; 
                   1842:   m[nrl] -= ncl; 
                   1843:   
                   1844:   for(i=nrl+1;i<=nrh;i++) m[i]=m[i-1]+ncol; 
                   1845:   
                   1846:   /* return pointer to array of pointers to rows */ 
                   1847:   return m; 
                   1848: } 
                   1849: 
                   1850: /****************** free_imatrix *************************/
                   1851: void free_imatrix(m,nrl,nrh,ncl,nch)
                   1852:       int **m;
                   1853:       long nch,ncl,nrh,nrl; 
                   1854:      /* free an int matrix allocated by imatrix() */ 
                   1855: { 
                   1856:   free((FREE_ARG) (m[nrl]+ncl-NR_END)); 
                   1857:   free((FREE_ARG) (m+nrl-NR_END)); 
                   1858: } 
                   1859: 
                   1860: /******************* matrix *******************************/
                   1861: double **matrix(long nrl, long nrh, long ncl, long nch)
                   1862: {
                   1863:   long i, nrow=nrh-nrl+1, ncol=nch-ncl+1;
                   1864:   double **m;
                   1865: 
                   1866:   m=(double **) malloc((size_t)((nrow+NR_END)*sizeof(double*)));
                   1867:   if (!m) nrerror("allocation failure 1 in matrix()");
                   1868:   m += NR_END;
                   1869:   m -= nrl;
                   1870: 
                   1871:   m[nrl]=(double *) malloc((size_t)((nrow*ncol+NR_END)*sizeof(double)));
                   1872:   if (!m[nrl]) nrerror("allocation failure 2 in matrix()");
                   1873:   m[nrl] += NR_END;
                   1874:   m[nrl] -= ncl;
                   1875: 
                   1876:   for (i=nrl+1; i<=nrh; i++) m[i]=m[i-1]+ncol;
                   1877:   return m;
1.145     brouard  1878:   /* print *(*(m+1)+70) or print m[1][70]; print m+1 or print &(m[1]) or &(m[1][0])
                   1879: m[i] = address of ith row of the table. &(m[i]) is its value which is another adress
                   1880: that of m[i][0]. In order to get the value p m[i][0] but it is unitialized.
1.126     brouard  1881:    */
                   1882: }
                   1883: 
                   1884: /*************************free matrix ************************/
                   1885: void free_matrix(double **m, long nrl, long nrh, long ncl, long nch)
                   1886: {
                   1887:   free((FREE_ARG)(m[nrl]+ncl-NR_END));
                   1888:   free((FREE_ARG)(m+nrl-NR_END));
                   1889: }
                   1890: 
                   1891: /******************* ma3x *******************************/
                   1892: double ***ma3x(long nrl, long nrh, long ncl, long nch, long nll, long nlh)
                   1893: {
                   1894:   long i, j, nrow=nrh-nrl+1, ncol=nch-ncl+1, nlay=nlh-nll+1;
                   1895:   double ***m;
                   1896: 
                   1897:   m=(double ***) malloc((size_t)((nrow+NR_END)*sizeof(double*)));
                   1898:   if (!m) nrerror("allocation failure 1 in matrix()");
                   1899:   m += NR_END;
                   1900:   m -= nrl;
                   1901: 
                   1902:   m[nrl]=(double **) malloc((size_t)((nrow*ncol+NR_END)*sizeof(double)));
                   1903:   if (!m[nrl]) nrerror("allocation failure 2 in matrix()");
                   1904:   m[nrl] += NR_END;
                   1905:   m[nrl] -= ncl;
                   1906: 
                   1907:   for (i=nrl+1; i<=nrh; i++) m[i]=m[i-1]+ncol;
                   1908: 
                   1909:   m[nrl][ncl]=(double *) malloc((size_t)((nrow*ncol*nlay+NR_END)*sizeof(double)));
                   1910:   if (!m[nrl][ncl]) nrerror("allocation failure 3 in matrix()");
                   1911:   m[nrl][ncl] += NR_END;
                   1912:   m[nrl][ncl] -= nll;
                   1913:   for (j=ncl+1; j<=nch; j++) 
                   1914:     m[nrl][j]=m[nrl][j-1]+nlay;
                   1915:   
                   1916:   for (i=nrl+1; i<=nrh; i++) {
                   1917:     m[i][ncl]=m[i-1l][ncl]+ncol*nlay;
                   1918:     for (j=ncl+1; j<=nch; j++) 
                   1919:       m[i][j]=m[i][j-1]+nlay;
                   1920:   }
                   1921:   return m; 
                   1922:   /*  gdb: p *(m+1) <=> p m[1] and p (m+1) <=> p (m+1) <=> p &(m[1])
                   1923:            &(m[i][j][k]) <=> *((*(m+i) + j)+k)
                   1924:   */
                   1925: }
                   1926: 
                   1927: /*************************free ma3x ************************/
                   1928: void free_ma3x(double ***m, long nrl, long nrh, long ncl, long nch,long nll, long nlh)
                   1929: {
                   1930:   free((FREE_ARG)(m[nrl][ncl]+ nll-NR_END));
                   1931:   free((FREE_ARG)(m[nrl]+ncl-NR_END));
                   1932:   free((FREE_ARG)(m+nrl-NR_END));
                   1933: }
                   1934: 
                   1935: /*************** function subdirf ***********/
                   1936: char *subdirf(char fileres[])
                   1937: {
                   1938:   /* Caution optionfilefiname is hidden */
                   1939:   strcpy(tmpout,optionfilefiname);
                   1940:   strcat(tmpout,"/"); /* Add to the right */
                   1941:   strcat(tmpout,fileres);
                   1942:   return tmpout;
                   1943: }
                   1944: 
                   1945: /*************** function subdirf2 ***********/
                   1946: char *subdirf2(char fileres[], char *preop)
                   1947: {
1.314     brouard  1948:   /* Example subdirf2(optionfilefiname,"FB_") with optionfilefiname="texte", result="texte/FB_texte"
                   1949:  Errors in subdirf, 2, 3 while printing tmpout is
1.315     brouard  1950:  rewritten within the same printf. Workaround: many printfs */
1.126     brouard  1951:   /* Caution optionfilefiname is hidden */
                   1952:   strcpy(tmpout,optionfilefiname);
                   1953:   strcat(tmpout,"/");
                   1954:   strcat(tmpout,preop);
                   1955:   strcat(tmpout,fileres);
                   1956:   return tmpout;
                   1957: }
                   1958: 
                   1959: /*************** function subdirf3 ***********/
                   1960: char *subdirf3(char fileres[], char *preop, char *preop2)
                   1961: {
                   1962:   
                   1963:   /* Caution optionfilefiname is hidden */
                   1964:   strcpy(tmpout,optionfilefiname);
                   1965:   strcat(tmpout,"/");
                   1966:   strcat(tmpout,preop);
                   1967:   strcat(tmpout,preop2);
                   1968:   strcat(tmpout,fileres);
                   1969:   return tmpout;
                   1970: }
1.213     brouard  1971:  
                   1972: /*************** function subdirfext ***********/
                   1973: char *subdirfext(char fileres[], char *preop, char *postop)
                   1974: {
                   1975:   
                   1976:   strcpy(tmpout,preop);
                   1977:   strcat(tmpout,fileres);
                   1978:   strcat(tmpout,postop);
                   1979:   return tmpout;
                   1980: }
1.126     brouard  1981: 
1.213     brouard  1982: /*************** function subdirfext3 ***********/
                   1983: char *subdirfext3(char fileres[], char *preop, char *postop)
                   1984: {
                   1985:   
                   1986:   /* Caution optionfilefiname is hidden */
                   1987:   strcpy(tmpout,optionfilefiname);
                   1988:   strcat(tmpout,"/");
                   1989:   strcat(tmpout,preop);
                   1990:   strcat(tmpout,fileres);
                   1991:   strcat(tmpout,postop);
                   1992:   return tmpout;
                   1993: }
                   1994:  
1.162     brouard  1995: char *asc_diff_time(long time_sec, char ascdiff[])
                   1996: {
                   1997:   long sec_left, days, hours, minutes;
                   1998:   days = (time_sec) / (60*60*24);
                   1999:   sec_left = (time_sec) % (60*60*24);
                   2000:   hours = (sec_left) / (60*60) ;
                   2001:   sec_left = (sec_left) %(60*60);
                   2002:   minutes = (sec_left) /60;
                   2003:   sec_left = (sec_left) % (60);
                   2004:   sprintf(ascdiff,"%ld day(s) %ld hour(s) %ld minute(s) %ld second(s)",days, hours, minutes, sec_left);  
                   2005:   return ascdiff;
                   2006: }
                   2007: 
1.126     brouard  2008: /***************** f1dim *************************/
                   2009: extern int ncom; 
                   2010: extern double *pcom,*xicom;
                   2011: extern double (*nrfunc)(double []); 
                   2012:  
                   2013: double f1dim(double x) 
                   2014: { 
                   2015:   int j; 
                   2016:   double f;
                   2017:   double *xt; 
                   2018:  
                   2019:   xt=vector(1,ncom); 
                   2020:   for (j=1;j<=ncom;j++) xt[j]=pcom[j]+x*xicom[j]; 
                   2021:   f=(*nrfunc)(xt); 
                   2022:   free_vector(xt,1,ncom); 
                   2023:   return f; 
                   2024: } 
                   2025: 
                   2026: /*****************brent *************************/
                   2027: double brent(double ax, double bx, double cx, double (*f)(double), double tol,         double *xmin) 
1.187     brouard  2028: {
                   2029:   /* Given a function f, and given a bracketing triplet of abscissas ax, bx, cx (such that bx is
                   2030:    * between ax and cx, and f(bx) is less than both f(ax) and f(cx) ), this routine isolates
                   2031:    * the minimum to a fractional precision of about tol using Brent’s method. The abscissa of
                   2032:    * the minimum is returned as xmin, and the minimum function value is returned as brent , the
                   2033:    * returned function value. 
                   2034:   */
1.126     brouard  2035:   int iter; 
                   2036:   double a,b,d,etemp;
1.159     brouard  2037:   double fu=0,fv,fw,fx;
1.164     brouard  2038:   double ftemp=0.;
1.126     brouard  2039:   double p,q,r,tol1,tol2,u,v,w,x,xm; 
                   2040:   double e=0.0; 
                   2041:  
                   2042:   a=(ax < cx ? ax : cx); 
                   2043:   b=(ax > cx ? ax : cx); 
                   2044:   x=w=v=bx; 
                   2045:   fw=fv=fx=(*f)(x); 
                   2046:   for (iter=1;iter<=ITMAX;iter++) { 
                   2047:     xm=0.5*(a+b); 
                   2048:     tol2=2.0*(tol1=tol*fabs(x)+ZEPS); 
                   2049:     /*         if (2.0*fabs(fp-(*fret)) <= ftol*(fabs(fp)+fabs(*fret)))*/
                   2050:     printf(".");fflush(stdout);
                   2051:     fprintf(ficlog,".");fflush(ficlog);
1.162     brouard  2052: #ifdef DEBUGBRENT
1.126     brouard  2053:     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);
                   2054:     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);
                   2055:     /*         if ((fabs(x-xm) <= (tol2-0.5*(b-a)))||(2.0*fabs(fu-ftemp) <= ftol*1.e-2*(fabs(fu)+fabs(ftemp)))) { */
                   2056: #endif
                   2057:     if (fabs(x-xm) <= (tol2-0.5*(b-a))){ 
                   2058:       *xmin=x; 
                   2059:       return fx; 
                   2060:     } 
                   2061:     ftemp=fu;
                   2062:     if (fabs(e) > tol1) { 
                   2063:       r=(x-w)*(fx-fv); 
                   2064:       q=(x-v)*(fx-fw); 
                   2065:       p=(x-v)*q-(x-w)*r; 
                   2066:       q=2.0*(q-r); 
                   2067:       if (q > 0.0) p = -p; 
                   2068:       q=fabs(q); 
                   2069:       etemp=e; 
                   2070:       e=d; 
                   2071:       if (fabs(p) >= fabs(0.5*q*etemp) || p <= q*(a-x) || p >= q*(b-x)) 
1.224     brouard  2072:                                d=CGOLD*(e=(x >= xm ? a-x : b-x)); 
1.126     brouard  2073:       else { 
1.224     brouard  2074:                                d=p/q; 
                   2075:                                u=x+d; 
                   2076:                                if (u-a < tol2 || b-u < tol2) 
                   2077:                                        d=SIGN(tol1,xm-x); 
1.126     brouard  2078:       } 
                   2079:     } else { 
                   2080:       d=CGOLD*(e=(x >= xm ? a-x : b-x)); 
                   2081:     } 
                   2082:     u=(fabs(d) >= tol1 ? x+d : x+SIGN(tol1,d)); 
                   2083:     fu=(*f)(u); 
                   2084:     if (fu <= fx) { 
                   2085:       if (u >= x) a=x; else b=x; 
                   2086:       SHFT(v,w,x,u) 
1.183     brouard  2087:       SHFT(fv,fw,fx,fu) 
                   2088:     } else { 
                   2089:       if (u < x) a=u; else b=u; 
                   2090:       if (fu <= fw || w == x) { 
1.224     brouard  2091:                                v=w; 
                   2092:                                w=u; 
                   2093:                                fv=fw; 
                   2094:                                fw=fu; 
1.183     brouard  2095:       } else if (fu <= fv || v == x || v == w) { 
1.224     brouard  2096:                                v=u; 
                   2097:                                fv=fu; 
1.183     brouard  2098:       } 
                   2099:     } 
1.126     brouard  2100:   } 
                   2101:   nrerror("Too many iterations in brent"); 
                   2102:   *xmin=x; 
                   2103:   return fx; 
                   2104: } 
                   2105: 
                   2106: /****************** mnbrak ***********************/
                   2107: 
                   2108: void mnbrak(double *ax, double *bx, double *cx, double *fa, double *fb, double *fc, 
                   2109:            double (*func)(double)) 
1.183     brouard  2110: { /* Given a function func , and given distinct initial points ax and bx , this routine searches in
                   2111: the downhill direction (defined by the function as evaluated at the initial points) and returns
                   2112: new points ax , bx , cx that bracket a minimum of the function. Also returned are the function
                   2113: values at the three points, fa, fb , and fc such that fa > fb and fb < fc.
                   2114:    */
1.126     brouard  2115:   double ulim,u,r,q, dum;
                   2116:   double fu; 
1.187     brouard  2117: 
                   2118:   double scale=10.;
                   2119:   int iterscale=0;
                   2120: 
                   2121:   *fa=(*func)(*ax); /*  xta[j]=pcom[j]+(*ax)*xicom[j]; fa=f(xta[j])*/
                   2122:   *fb=(*func)(*bx); /*  xtb[j]=pcom[j]+(*bx)*xicom[j]; fb=f(xtb[j]) */
                   2123: 
                   2124: 
                   2125:   /* while(*fb != *fb){ /\* *ax should be ok, reducing distance to *ax *\/ */
                   2126:   /*   printf("Warning mnbrak *fb = %lf, *bx=%lf *ax=%lf *fa==%lf iter=%d\n",*fb, *bx, *ax, *fa, iterscale++); */
                   2127:   /*   *bx = *ax - (*ax - *bx)/scale; */
                   2128:   /*   *fb=(*func)(*bx);  /\*  xtb[j]=pcom[j]+(*bx)*xicom[j]; fb=f(xtb[j]) *\/ */
                   2129:   /* } */
                   2130: 
1.126     brouard  2131:   if (*fb > *fa) { 
                   2132:     SHFT(dum,*ax,*bx,dum) 
1.183     brouard  2133:     SHFT(dum,*fb,*fa,dum) 
                   2134:   } 
1.126     brouard  2135:   *cx=(*bx)+GOLD*(*bx-*ax); 
                   2136:   *fc=(*func)(*cx); 
1.183     brouard  2137: #ifdef DEBUG
1.224     brouard  2138:   printf("mnbrak0 a=%lf *fa=%lf, b=%lf *fb=%lf, c=%lf *fc=%lf\n",*ax,*fa,*bx,*fb,*cx, *fc);
                   2139:   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  2140: #endif
1.224     brouard  2141:   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  2142:     r=(*bx-*ax)*(*fb-*fc); 
1.224     brouard  2143:     q=(*bx-*cx)*(*fb-*fa); /* What if fa=inf */
1.126     brouard  2144:     u=(*bx)-((*bx-*cx)*q-(*bx-*ax)*r)/ 
1.183     brouard  2145:       (2.0*SIGN(FMAX(fabs(q-r),TINY),q-r)); /* Minimum abscissa of a parabolic estimated from (a,fa), (b,fb) and (c,fc). */
                   2146:     ulim=(*bx)+GLIMIT*(*cx-*bx); /* Maximum abscissa where function should be evaluated */
                   2147:     if ((*bx-u)*(u-*cx) > 0.0) { /* if u_p is between b and c */
1.126     brouard  2148:       fu=(*func)(u); 
1.163     brouard  2149: #ifdef DEBUG
                   2150:       /* f(x)=A(x-u)**2+f(u) */
                   2151:       double A, fparabu; 
                   2152:       A= (*fb - *fa)/(*bx-*ax)/(*bx+*ax-2*u);
                   2153:       fparabu= *fa - A*(*ax-u)*(*ax-u);
1.224     brouard  2154:       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);
                   2155:       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  2156:       /* And thus,it can be that fu > *fc even if fparabu < *fc */
                   2157:       /* mnbrak (*ax=7.666299858533, *fa=299039.693133272231), (*bx=8.595447774979, *fb=298976.598289369489),
                   2158:         (*cx=10.098840694817, *fc=298946.631474258087),  (*u=9.852501168332, fu=298948.773013752128, fparabu=298945.434711494134) */
                   2159:       /* In that case, there is no bracket in the output! Routine is wrong with many consequences.*/
1.163     brouard  2160: #endif 
1.184     brouard  2161: #ifdef MNBRAKORIGINAL
1.183     brouard  2162: #else
1.191     brouard  2163: /*       if (fu > *fc) { */
                   2164: /* #ifdef DEBUG */
                   2165: /*       printf("mnbrak4  fu > fc \n"); */
                   2166: /*       fprintf(ficlog, "mnbrak4 fu > fc\n"); */
                   2167: /* #endif */
                   2168: /*     /\* 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 *\\/  *\/ */
                   2169: /*     /\* SHFT(*fa,*fc,fu,*fc) /\\* (b, u, c) is a bracket while test fb > fc will be fu > fc  will exit *\\/ *\/ */
                   2170: /*     dum=u; /\* Shifting c and u *\/ */
                   2171: /*     u = *cx; */
                   2172: /*     *cx = dum; */
                   2173: /*     dum = fu; */
                   2174: /*     fu = *fc; */
                   2175: /*     *fc =dum; */
                   2176: /*       } else { /\* end *\/ */
                   2177: /* #ifdef DEBUG */
                   2178: /*       printf("mnbrak3  fu < fc \n"); */
                   2179: /*       fprintf(ficlog, "mnbrak3 fu < fc\n"); */
                   2180: /* #endif */
                   2181: /*     dum=u; /\* Shifting c and u *\/ */
                   2182: /*     u = *cx; */
                   2183: /*     *cx = dum; */
                   2184: /*     dum = fu; */
                   2185: /*     fu = *fc; */
                   2186: /*     *fc =dum; */
                   2187: /*       } */
1.224     brouard  2188: #ifdef DEBUGMNBRAK
                   2189:                 double A, fparabu; 
                   2190:      A= (*fb - *fa)/(*bx-*ax)/(*bx+*ax-2*u);
                   2191:      fparabu= *fa - A*(*ax-u)*(*ax-u);
                   2192:      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);
                   2193:      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  2194: #endif
1.191     brouard  2195:       dum=u; /* Shifting c and u */
                   2196:       u = *cx;
                   2197:       *cx = dum;
                   2198:       dum = fu;
                   2199:       fu = *fc;
                   2200:       *fc =dum;
1.183     brouard  2201: #endif
1.162     brouard  2202:     } else if ((*cx-u)*(u-ulim) > 0.0) { /* u is after c but before ulim */
1.183     brouard  2203: #ifdef DEBUG
1.224     brouard  2204:       printf("\nmnbrak2  u=%lf after c=%lf but before ulim\n",u,*cx);
                   2205:       fprintf(ficlog,"\nmnbrak2  u=%lf after c=%lf but before ulim\n",u,*cx);
1.183     brouard  2206: #endif
1.126     brouard  2207:       fu=(*func)(u); 
                   2208:       if (fu < *fc) { 
1.183     brouard  2209: #ifdef DEBUG
1.224     brouard  2210:                                printf("\nmnbrak2  u=%lf after c=%lf but before ulim=%lf AND fu=%lf < %lf=fc\n",u,*cx,ulim,fu, *fc);
                   2211:                          fprintf(ficlog,"\nmnbrak2  u=%lf after c=%lf but before ulim=%lf AND fu=%lf < %lf=fc\n",u,*cx,ulim,fu, *fc);
                   2212: #endif
                   2213:                          SHFT(*bx,*cx,u,*cx+GOLD*(*cx-*bx)) 
                   2214:                                SHFT(*fb,*fc,fu,(*func)(u)) 
                   2215: #ifdef DEBUG
                   2216:                                        printf("\nmnbrak2 shift GOLD c=%lf",*cx+GOLD*(*cx-*bx));
1.183     brouard  2217: #endif
                   2218:       } 
1.162     brouard  2219:     } else if ((u-ulim)*(ulim-*cx) >= 0.0) { /* u outside ulim (verifying that ulim is beyond c) */
1.183     brouard  2220: #ifdef DEBUG
1.224     brouard  2221:       printf("\nmnbrak2  u=%lf outside ulim=%lf (verifying that ulim is beyond c=%lf)\n",u,ulim,*cx);
                   2222:       fprintf(ficlog,"\nmnbrak2  u=%lf outside ulim=%lf (verifying that ulim is beyond c=%lf)\n",u,ulim,*cx);
1.183     brouard  2223: #endif
1.126     brouard  2224:       u=ulim; 
                   2225:       fu=(*func)(u); 
1.183     brouard  2226:     } else { /* u could be left to b (if r > q parabola has a maximum) */
                   2227: #ifdef DEBUG
1.224     brouard  2228:       printf("\nmnbrak2  u=%lf could be left to b=%lf (if r=%lf > q=%lf parabola has a maximum)\n",u,*bx,r,q);
                   2229:       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  2230: #endif
1.126     brouard  2231:       u=(*cx)+GOLD*(*cx-*bx); 
                   2232:       fu=(*func)(u); 
1.224     brouard  2233: #ifdef DEBUG
                   2234:       printf("\nmnbrak2 new u=%lf fu=%lf shifted gold left from c=%lf and b=%lf \n",u,fu,*cx,*bx);
                   2235:       fprintf(ficlog,"\nmnbrak2 new u=%lf fu=%lf shifted gold left from c=%lf and b=%lf \n",u,fu,*cx,*bx);
                   2236: #endif
1.183     brouard  2237:     } /* end tests */
1.126     brouard  2238:     SHFT(*ax,*bx,*cx,u) 
1.183     brouard  2239:     SHFT(*fa,*fb,*fc,fu) 
                   2240: #ifdef DEBUG
1.224     brouard  2241:       printf("\nmnbrak2 shift (*ax=%.12f, *fa=%.12lf), (*bx=%.12f, *fb=%.12lf), (*cx=%.12f, *fc=%.12lf)\n",*ax,*fa,*bx,*fb,*cx,*fc);
                   2242:       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  2243: #endif
                   2244:   } /* 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  2245: } 
                   2246: 
                   2247: /*************** linmin ************************/
1.162     brouard  2248: /* Given an n -dimensional point p[1..n] and an n -dimensional direction xi[1..n] , moves and
                   2249: resets p to where the function func(p) takes on a minimum along the direction xi from p ,
                   2250: and replaces xi by the actual vector displacement that p was moved. Also returns as fret
                   2251: the value of func at the returned location p . This is actually all accomplished by calling the
                   2252: routines mnbrak and brent .*/
1.126     brouard  2253: int ncom; 
                   2254: double *pcom,*xicom;
                   2255: double (*nrfunc)(double []); 
                   2256:  
1.224     brouard  2257: #ifdef LINMINORIGINAL
1.126     brouard  2258: void linmin(double p[], double xi[], int n, double *fret,double (*func)(double [])) 
1.224     brouard  2259: #else
                   2260: void linmin(double p[], double xi[], int n, double *fret,double (*func)(double []), int *flat) 
                   2261: #endif
1.126     brouard  2262: { 
                   2263:   double brent(double ax, double bx, double cx, 
                   2264:               double (*f)(double), double tol, double *xmin); 
                   2265:   double f1dim(double x); 
                   2266:   void mnbrak(double *ax, double *bx, double *cx, double *fa, double *fb, 
                   2267:              double *fc, double (*func)(double)); 
                   2268:   int j; 
                   2269:   double xx,xmin,bx,ax; 
                   2270:   double fx,fb,fa;
1.187     brouard  2271: 
1.203     brouard  2272: #ifdef LINMINORIGINAL
                   2273: #else
                   2274:   double scale=10., axs, xxs; /* Scale added for infinity */
                   2275: #endif
                   2276:   
1.126     brouard  2277:   ncom=n; 
                   2278:   pcom=vector(1,n); 
                   2279:   xicom=vector(1,n); 
                   2280:   nrfunc=func; 
                   2281:   for (j=1;j<=n;j++) { 
                   2282:     pcom[j]=p[j]; 
1.202     brouard  2283:     xicom[j]=xi[j]; /* Former scale xi[j] of currrent direction i */
1.126     brouard  2284:   } 
1.187     brouard  2285: 
1.203     brouard  2286: #ifdef LINMINORIGINAL
                   2287:   xx=1.;
                   2288: #else
                   2289:   axs=0.0;
                   2290:   xxs=1.;
                   2291:   do{
                   2292:     xx= xxs;
                   2293: #endif
1.187     brouard  2294:     ax=0.;
                   2295:     mnbrak(&ax,&xx,&bx,&fa,&fx,&fb,f1dim);  /* Outputs: xtx[j]=pcom[j]+(*xx)*xicom[j]; fx=f(xtx[j]) */
                   2296:     /* brackets with inputs ax=0 and xx=1, but points, pcom=p, and directions values, xicom=xi, are sent via f1dim(x) */
                   2297:     /* 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))   */
                   2298:     /* Outputs: fa=f(p(j)) and fx=f(p(j) + xxs * xi(j) ) and f(bx)= f(p(j)+ bx* xi(j)) */
                   2299:     /* Given input ax=axs and xx=xxs, xx might be too far from ax to get a finite f(xx) */
                   2300:     /* Searches on line, outputs (ax, xx, bx) such that fx < min(fa and fb) */
                   2301:     /* 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  2302: #ifdef LINMINORIGINAL
                   2303: #else
                   2304:     if (fx != fx){
1.224     brouard  2305:                        xxs=xxs/scale; /* Trying a smaller xx, closer to initial ax=0 */
                   2306:                        printf("|");
                   2307:                        fprintf(ficlog,"|");
1.203     brouard  2308: #ifdef DEBUGLINMIN
1.224     brouard  2309:                        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  2310: #endif
                   2311:     }
1.224     brouard  2312:   }while(fx != fx && xxs > 1.e-5);
1.203     brouard  2313: #endif
                   2314:   
1.191     brouard  2315: #ifdef DEBUGLINMIN
                   2316:   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  2317:   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  2318: #endif
1.224     brouard  2319: #ifdef LINMINORIGINAL
                   2320: #else
1.317     brouard  2321:   if(fb == fx){ /* Flat function in the direction */
                   2322:     xmin=xx;
1.224     brouard  2323:     *flat=1;
1.317     brouard  2324:   }else{
1.224     brouard  2325:     *flat=0;
                   2326: #endif
                   2327:                /*Flat mnbrak2 shift (*ax=0.000000000000, *fa=51626.272983130431), (*bx=-1.618034000000, *fb=51590.149499362531), (*cx=-4.236068025156, *fc=51590.149499362531) */
1.187     brouard  2328:   *fret=brent(ax,xx,bx,f1dim,TOL,&xmin); /* Giving a bracketting triplet (ax, xx, bx), find a minimum, xmin, according to f1dim, *fret(xmin),*/
                   2329:   /* fa = f(p[j] + ax * xi[j]), fx = f(p[j] + xx * xi[j]), fb = f(p[j] + bx * xi[j]) */
                   2330:   /* fmin = f(p[j] + xmin * xi[j]) */
                   2331:   /* P+lambda n in that direction (lambdamin), with TOL between abscisses */
                   2332:   /* f1dim(xmin): for (j=1;j<=ncom;j++) xt[j]=pcom[j]+xmin*xicom[j]; */
1.126     brouard  2333: #ifdef DEBUG
1.224     brouard  2334:   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);
                   2335:   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);
                   2336: #endif
                   2337: #ifdef LINMINORIGINAL
                   2338: #else
                   2339:                        }
1.126     brouard  2340: #endif
1.191     brouard  2341: #ifdef DEBUGLINMIN
                   2342:   printf("linmin end ");
1.202     brouard  2343:   fprintf(ficlog,"linmin end ");
1.191     brouard  2344: #endif
1.126     brouard  2345:   for (j=1;j<=n;j++) { 
1.203     brouard  2346: #ifdef LINMINORIGINAL
                   2347:     xi[j] *= xmin; 
                   2348: #else
                   2349: #ifdef DEBUGLINMIN
                   2350:     if(xxs <1.0)
                   2351:       printf(" before xi[%d]=%12.8f", j,xi[j]);
                   2352: #endif
                   2353:     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) */
                   2354: #ifdef DEBUGLINMIN
                   2355:     if(xxs <1.0)
                   2356:       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 );
                   2357: #endif
                   2358: #endif
1.187     brouard  2359:     p[j] += xi[j]; /* Parameters values are updated accordingly */
1.126     brouard  2360:   } 
1.191     brouard  2361: #ifdef DEBUGLINMIN
1.203     brouard  2362:   printf("\n");
1.191     brouard  2363:   printf("Comparing last *frec(xmin=%12.8f)=%12.8f from Brent and frec(0.)=%12.8f \n", xmin, *fret, (*func)(p));
1.202     brouard  2364:   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  2365:   for (j=1;j<=n;j++) { 
1.202     brouard  2366:     printf(" xi[%d]= %14.10f p[%d]= %12.7f",j,xi[j],j,p[j]);
                   2367:     fprintf(ficlog," xi[%d]= %14.10f p[%d]= %12.7f",j,xi[j],j,p[j]);
                   2368:     if(j % ncovmodel == 0){
1.191     brouard  2369:       printf("\n");
1.202     brouard  2370:       fprintf(ficlog,"\n");
                   2371:     }
1.191     brouard  2372:   }
1.203     brouard  2373: #else
1.191     brouard  2374: #endif
1.126     brouard  2375:   free_vector(xicom,1,n); 
                   2376:   free_vector(pcom,1,n); 
                   2377: } 
                   2378: 
                   2379: 
                   2380: /*************** powell ************************/
1.162     brouard  2381: /*
1.317     brouard  2382: Minimization of a function func of n variables. Input consists in an initial starting point
                   2383: p[1..n] ; an initial matrix xi[1..n][1..n]  whose columns contain the initial set of di-
                   2384: rections (usually the n unit vectors); and ftol, the fractional tolerance in the function value
                   2385: such that failure to decrease by more than this amount in one iteration signals doneness. On
1.162     brouard  2386: output, p is set to the best point found, xi is the then-current direction set, fret is the returned
                   2387: function value at p , and iter is the number of iterations taken. The routine linmin is used.
                   2388:  */
1.224     brouard  2389: #ifdef LINMINORIGINAL
                   2390: #else
                   2391:        int *flatdir; /* Function is vanishing in that direction */
1.225     brouard  2392:        int flat=0, flatd=0; /* Function is vanishing in that direction */
1.224     brouard  2393: #endif
1.126     brouard  2394: void powell(double p[], double **xi, int n, double ftol, int *iter, double *fret, 
                   2395:            double (*func)(double [])) 
                   2396: { 
1.224     brouard  2397: #ifdef LINMINORIGINAL
                   2398:  void linmin(double p[], double xi[], int n, double *fret, 
1.126     brouard  2399:              double (*func)(double [])); 
1.224     brouard  2400: #else 
1.241     brouard  2401:  void linmin(double p[], double xi[], int n, double *fret,
                   2402:             double (*func)(double []),int *flat); 
1.224     brouard  2403: #endif
1.239     brouard  2404:  int i,ibig,j,jk,k; 
1.126     brouard  2405:   double del,t,*pt,*ptt,*xit;
1.181     brouard  2406:   double directest;
1.126     brouard  2407:   double fp,fptt;
                   2408:   double *xits;
                   2409:   int niterf, itmp;
                   2410: 
                   2411:   pt=vector(1,n); 
                   2412:   ptt=vector(1,n); 
                   2413:   xit=vector(1,n); 
                   2414:   xits=vector(1,n); 
                   2415:   *fret=(*func)(p); 
                   2416:   for (j=1;j<=n;j++) pt[j]=p[j]; 
1.202     brouard  2417:   rcurr_time = time(NULL);  
1.126     brouard  2418:   for (*iter=1;;++(*iter)) { 
                   2419:     ibig=0; 
                   2420:     del=0.0; 
1.157     brouard  2421:     rlast_time=rcurr_time;
                   2422:     /* (void) gettimeofday(&curr_time,&tzp); */
                   2423:     rcurr_time = time(NULL);  
                   2424:     curr_time = *localtime(&rcurr_time);
1.324   ! brouard  2425:     printf("\nPowell iter=%d -2*LL=%.12f gain=%.12f=%.3g %ld sec. %ld sec.",*iter,*fret, fp-*fret,fp-*fret, rcurr_time-rlast_time, rcurr_time-rstart_time);fflush(stdout);
        !          2426:     fprintf(ficlog,"\nPowell iter=%d -2*LL=%.12f gain=%.12f=%.3g %ld sec. %ld sec.",*iter,*fret, fp-*fret,fp-*fret,rcurr_time-rlast_time, rcurr_time-rstart_time); fflush(ficlog);
1.157     brouard  2427: /*     fprintf(ficrespow,"%d %.12f %ld",*iter,*fret,curr_time.tm_sec-start_time.tm_sec); */
1.324   ! brouard  2428:     fp=(*fret); /* From former iteration or initial value */
1.192     brouard  2429:     for (i=1;i<=n;i++) {
1.126     brouard  2430:       fprintf(ficrespow," %.12lf", p[i]);
                   2431:     }
1.239     brouard  2432:     fprintf(ficrespow,"\n");fflush(ficrespow);
                   2433:     printf("\n#model=  1      +     age ");
                   2434:     fprintf(ficlog,"\n#model=  1      +     age ");
                   2435:     if(nagesqr==1){
1.241     brouard  2436:        printf("  + age*age  ");
                   2437:        fprintf(ficlog,"  + age*age  ");
1.239     brouard  2438:     }
                   2439:     for(j=1;j <=ncovmodel-2;j++){
                   2440:       if(Typevar[j]==0) {
                   2441:        printf("  +      V%d  ",Tvar[j]);
                   2442:        fprintf(ficlog,"  +      V%d  ",Tvar[j]);
                   2443:       }else if(Typevar[j]==1) {
                   2444:        printf("  +    V%d*age ",Tvar[j]);
                   2445:        fprintf(ficlog,"  +    V%d*age ",Tvar[j]);
                   2446:       }else if(Typevar[j]==2) {
                   2447:        printf("  +    V%d*V%d ",Tvard[Tposprod[j]][1],Tvard[Tposprod[j]][2]);
                   2448:        fprintf(ficlog,"  +    V%d*V%d ",Tvard[Tposprod[j]][1],Tvard[Tposprod[j]][2]);
                   2449:       }
                   2450:     }
1.126     brouard  2451:     printf("\n");
1.239     brouard  2452: /*     printf("12   47.0114589    0.0154322   33.2424412    0.3279905    2.3731903  */
                   2453: /* 13  -21.5392400    0.1118147    1.2680506    1.2973408   -1.0663662  */
1.126     brouard  2454:     fprintf(ficlog,"\n");
1.239     brouard  2455:     for(i=1,jk=1; i <=nlstate; i++){
                   2456:       for(k=1; k <=(nlstate+ndeath); k++){
                   2457:        if (k != i) {
                   2458:          printf("%d%d ",i,k);
                   2459:          fprintf(ficlog,"%d%d ",i,k);
                   2460:          for(j=1; j <=ncovmodel; j++){
                   2461:            printf("%12.7f ",p[jk]);
                   2462:            fprintf(ficlog,"%12.7f ",p[jk]);
                   2463:            jk++; 
                   2464:          }
                   2465:          printf("\n");
                   2466:          fprintf(ficlog,"\n");
                   2467:        }
                   2468:       }
                   2469:     }
1.241     brouard  2470:     if(*iter <=3 && *iter >1){
1.157     brouard  2471:       tml = *localtime(&rcurr_time);
                   2472:       strcpy(strcurr,asctime(&tml));
                   2473:       rforecast_time=rcurr_time; 
1.126     brouard  2474:       itmp = strlen(strcurr);
                   2475:       if(strcurr[itmp-1]=='\n')  /* Windows outputs with a new line */
1.241     brouard  2476:        strcurr[itmp-1]='\0';
1.162     brouard  2477:       printf("\nConsidering the time needed for the last iteration #%d: %ld seconds,\n",*iter,rcurr_time-rlast_time);
1.157     brouard  2478:       fprintf(ficlog,"\nConsidering the time needed for this last iteration #%d: %ld seconds,\n",*iter,rcurr_time-rlast_time);
1.126     brouard  2479:       for(niterf=10;niterf<=30;niterf+=10){
1.241     brouard  2480:        rforecast_time=rcurr_time+(niterf-*iter)*(rcurr_time-rlast_time);
                   2481:        forecast_time = *localtime(&rforecast_time);
                   2482:        strcpy(strfor,asctime(&forecast_time));
                   2483:        itmp = strlen(strfor);
                   2484:        if(strfor[itmp-1]=='\n')
                   2485:          strfor[itmp-1]='\0';
                   2486:        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);
                   2487:        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  2488:       }
                   2489:     }
1.187     brouard  2490:     for (i=1;i<=n;i++) { /* For each direction i */
                   2491:       for (j=1;j<=n;j++) xit[j]=xi[j][i]; /* Directions stored from previous iteration with previous scales */
1.126     brouard  2492:       fptt=(*fret); 
                   2493: #ifdef DEBUG
1.203     brouard  2494:       printf("fret=%lf, %lf, %lf \n", *fret, *fret, *fret);
                   2495:       fprintf(ficlog, "fret=%lf, %lf, %lf \n", *fret, *fret, *fret);
1.126     brouard  2496: #endif
1.203     brouard  2497:       printf("%d",i);fflush(stdout); /* print direction (parameter) i */
1.126     brouard  2498:       fprintf(ficlog,"%d",i);fflush(ficlog);
1.224     brouard  2499: #ifdef LINMINORIGINAL
1.188     brouard  2500:       linmin(p,xit,n,fret,func); /* Point p[n]. xit[n] has been loaded for direction i as input.*/
1.224     brouard  2501: #else
                   2502:       linmin(p,xit,n,fret,func,&flat); /* Point p[n]. xit[n] has been loaded for direction i as input.*/
                   2503:                        flatdir[i]=flat; /* Function is vanishing in that direction i */
                   2504: #endif
                   2505:                        /* Outputs are fret(new point p) p is updated and xit rescaled */
1.188     brouard  2506:       if (fabs(fptt-(*fret)) > del) { /* We are keeping the max gain on each of the n directions */
1.224     brouard  2507:                                /* because that direction will be replaced unless the gain del is small */
                   2508:                                /* in comparison with the 'probable' gain, mu^2, with the last average direction. */
                   2509:                                /* Unless the n directions are conjugate some gain in the determinant may be obtained */
                   2510:                                /* with the new direction. */
                   2511:                                del=fabs(fptt-(*fret)); 
                   2512:                                ibig=i; 
1.126     brouard  2513:       } 
                   2514: #ifdef DEBUG
                   2515:       printf("%d %.12e",i,(*fret));
                   2516:       fprintf(ficlog,"%d %.12e",i,(*fret));
                   2517:       for (j=1;j<=n;j++) {
1.224     brouard  2518:                                xits[j]=FMAX(fabs(p[j]-pt[j]),1.e-5);
                   2519:                                printf(" x(%d)=%.12e",j,xit[j]);
                   2520:                                fprintf(ficlog," x(%d)=%.12e",j,xit[j]);
1.126     brouard  2521:       }
                   2522:       for(j=1;j<=n;j++) {
1.225     brouard  2523:                                printf(" p(%d)=%.12e",j,p[j]);
                   2524:                                fprintf(ficlog," p(%d)=%.12e",j,p[j]);
1.126     brouard  2525:       }
                   2526:       printf("\n");
                   2527:       fprintf(ficlog,"\n");
                   2528: #endif
1.187     brouard  2529:     } /* end loop on each direction i */
                   2530:     /* Convergence test will use last linmin estimation (fret) and compare former iteration (fp) */ 
1.188     brouard  2531:     /* But p and xit have been updated at the end of linmin, *fret corresponds to new p, xit  */
1.187     brouard  2532:     /* New value of last point Pn is not computed, P(n-1) */
1.319     brouard  2533:     for(j=1;j<=n;j++) {
                   2534:       if(flatdir[j] >0){
                   2535:         printf(" p(%d)=%lf flat=%d ",j,p[j],flatdir[j]);
                   2536:         fprintf(ficlog," p(%d)=%lf flat=%d ",j,p[j],flatdir[j]);
1.302     brouard  2537:       }
1.319     brouard  2538:       /* printf("\n"); */
                   2539:       /* fprintf(ficlog,"\n"); */
                   2540:     }
1.243     brouard  2541:     /* if (2.0*fabs(fp-(*fret)) <= ftol*(fabs(fp)+fabs(*fret))) { /\* Did we reach enough precision? *\/ */
                   2542:     if (2.0*fabs(fp-(*fret)) <= ftol) { /* Did we reach enough precision? */
1.188     brouard  2543:       /* We could compare with a chi^2. chisquare(0.95,ddl=1)=3.84 */
                   2544:       /* By adding age*age in a model, the new -2LL should be lower and the difference follows a */
                   2545:       /* a chisquare statistics with 1 degree. To be significant at the 95% level, it should have */
                   2546:       /* decreased of more than 3.84  */
                   2547:       /* By adding age*age and V1*age the gain (-2LL) should be more than 5.99 (ddl=2) */
                   2548:       /* By using V1+V2+V3, the gain should be  7.82, compared with basic 1+age. */
                   2549:       /* By adding 10 parameters more the gain should be 18.31 */
1.224     brouard  2550:                        
1.188     brouard  2551:       /* Starting the program with initial values given by a former maximization will simply change */
                   2552:       /* the scales of the directions and the directions, because the are reset to canonical directions */
                   2553:       /* Thus the first calls to linmin will give new points and better maximizations until fp-(*fret) is */
                   2554:       /* under the tolerance value. If the tolerance is very small 1.e-9, it could last long.  */
1.126     brouard  2555: #ifdef DEBUG
                   2556:       int k[2],l;
                   2557:       k[0]=1;
                   2558:       k[1]=-1;
                   2559:       printf("Max: %.12e",(*func)(p));
                   2560:       fprintf(ficlog,"Max: %.12e",(*func)(p));
                   2561:       for (j=1;j<=n;j++) {
                   2562:        printf(" %.12e",p[j]);
                   2563:        fprintf(ficlog," %.12e",p[j]);
                   2564:       }
                   2565:       printf("\n");
                   2566:       fprintf(ficlog,"\n");
                   2567:       for(l=0;l<=1;l++) {
                   2568:        for (j=1;j<=n;j++) {
                   2569:          ptt[j]=p[j]+(p[j]-pt[j])*k[l];
                   2570:          printf("l=%d j=%d ptt=%.12e, xits=%.12e, p=%.12e, xit=%.12e", l,j,ptt[j],xits[j],p[j],xit[j]);
                   2571:          fprintf(ficlog,"l=%d j=%d ptt=%.12e, xits=%.12e, p=%.12e, xit=%.12e", l,j,ptt[j],xits[j],p[j],xit[j]);
                   2572:        }
                   2573:        printf("func(ptt)=%.12e, deriv=%.12e\n",(*func)(ptt),(ptt[j]-p[j])/((*func)(ptt)-(*func)(p)));
                   2574:        fprintf(ficlog,"func(ptt)=%.12e, deriv=%.12e\n",(*func)(ptt),(ptt[j]-p[j])/((*func)(ptt)-(*func)(p)));
                   2575:       }
                   2576: #endif
                   2577: 
                   2578:       free_vector(xit,1,n); 
                   2579:       free_vector(xits,1,n); 
                   2580:       free_vector(ptt,1,n); 
                   2581:       free_vector(pt,1,n); 
                   2582:       return; 
1.192     brouard  2583:     } /* enough precision */ 
1.240     brouard  2584:     if (*iter == ITMAX*n) nrerror("powell exceeding maximum iterations."); 
1.181     brouard  2585:     for (j=1;j<=n;j++) { /* Computes the extrapolated point P_0 + 2 (P_n-P_0) */
1.126     brouard  2586:       ptt[j]=2.0*p[j]-pt[j]; 
                   2587:       xit[j]=p[j]-pt[j]; 
                   2588:       pt[j]=p[j]; 
                   2589:     } 
1.181     brouard  2590:     fptt=(*func)(ptt); /* f_3 */
1.224     brouard  2591: #ifdef NODIRECTIONCHANGEDUNTILNITER  /* No change in drections until some iterations are done */
                   2592:                if (*iter <=4) {
1.225     brouard  2593: #else
                   2594: #endif
1.224     brouard  2595: #ifdef POWELLNOF3INFF1TEST    /* skips test F3 <F1 */
1.192     brouard  2596: #else
1.161     brouard  2597:     if (fptt < fp) { /* If extrapolated point is better, decide if we keep that new direction or not */
1.192     brouard  2598: #endif
1.162     brouard  2599:       /* (x1 f1=fp), (x2 f2=*fret), (x3 f3=fptt), (xm fm) */
1.161     brouard  2600:       /* From x1 (P0) distance of x2 is at h and x3 is 2h */
1.162     brouard  2601:       /* Let f"(x2) be the 2nd derivative equal everywhere.  */
                   2602:       /* Then the parabolic through (x1,f1), (x2,f2) and (x3,f3) */
                   2603:       /* will reach at f3 = fm + h^2/2 f"m  ; f" = (f1 -2f2 +f3 ) / h**2 */
1.224     brouard  2604:       /* Conditional for using this new direction is that mu^2 = (f1-2f2+f3)^2 /2 < del or directest <0 */
                   2605:       /* also  lamda^2=(f1-f2)^2/mu² is a parasite solution of powell */
                   2606:       /* For powell, inclusion of this average direction is only if t(del)<0 or del inbetween mu^2 and lambda^2 */
1.161     brouard  2607:       /* t=2.0*(fp-2.0*(*fret)+fptt)*SQR(fp-(*fret)-del)-del*SQR(fp-fptt); */
1.224     brouard  2608:       /*  Even if f3 <f1, directest can be negative and t >0 */
                   2609:       /* mu² and del² are equal when f3=f1 */
                   2610:                        /* f3 < f1 : mu² < del <= lambda^2 both test are equivalent */
                   2611:                        /* f3 < f1 : mu² < lambda^2 < del then directtest is negative and powell t is positive */
                   2612:                        /* f3 > f1 : lambda² < mu^2 < del then t is negative and directest >0  */
                   2613:                        /* f3 > f1 : lambda² < del < mu^2 then t is positive and directest >0  */
1.183     brouard  2614: #ifdef NRCORIGINAL
                   2615:       t=2.0*(fp-2.0*(*fret)+fptt)*SQR(fp-(*fret)-del)- del*SQR(fp-fptt); /* Original Numerical Recipes in C*/
                   2616: #else
                   2617:       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  2618:       t= t- del*SQR(fp-fptt);
1.183     brouard  2619: #endif
1.202     brouard  2620:       directest = fp-2.0*(*fret)+fptt - 2.0 * del; /* If delta was big enough we change it for a new direction */
1.161     brouard  2621: #ifdef DEBUG
1.181     brouard  2622:       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);
                   2623:       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  2624:       printf("t3= %.12lf, t4= %.12lf, t3*= %.12lf, t4*= %.12lf\n",SQR(fp-(*fret)-del),SQR(fp-fptt),
                   2625:             (fp-(*fret)-del)*(fp-(*fret)-del),(fp-fptt)*(fp-fptt));
                   2626:       fprintf(ficlog,"t3= %.12lf, t4= %.12lf, t3*= %.12lf, t4*= %.12lf\n",SQR(fp-(*fret)-del),SQR(fp-fptt),
                   2627:             (fp-(*fret)-del)*(fp-(*fret)-del),(fp-fptt)*(fp-fptt));
                   2628:       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);
                   2629:       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);
                   2630: #endif
1.183     brouard  2631: #ifdef POWELLORIGINAL
                   2632:       if (t < 0.0) { /* Then we use it for new direction */
                   2633: #else
1.182     brouard  2634:       if (directest*t < 0.0) { /* Contradiction between both tests */
1.224     brouard  2635:                                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  2636:         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  2637:         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  2638:         fprintf(ficlog,"f1-2f2+f3= %.12lf, f1-f2-del= %.12lf, f1-f3= %.12lf\n",fp-2.0*(*fret)+fptt, fp -(*fret) -del, fp-fptt);
                   2639:       } 
1.181     brouard  2640:       if (directest < 0.0) { /* Then we use it for new direction */
                   2641: #endif
1.191     brouard  2642: #ifdef DEBUGLINMIN
1.234     brouard  2643:        printf("Before linmin in direction P%d-P0\n",n);
                   2644:        for (j=1;j<=n;j++) {
                   2645:          printf(" Before xit[%d]= %12.7f p[%d]= %12.7f",j,xit[j],j,p[j]);
                   2646:          fprintf(ficlog," Before xit[%d]= %12.7f p[%d]= %12.7f",j,xit[j],j,p[j]);
                   2647:          if(j % ncovmodel == 0){
                   2648:            printf("\n");
                   2649:            fprintf(ficlog,"\n");
                   2650:          }
                   2651:        }
1.224     brouard  2652: #endif
                   2653: #ifdef LINMINORIGINAL
1.234     brouard  2654:        linmin(p,xit,n,fret,func); /* computes minimum on the extrapolated direction: changes p and rescales xit.*/
1.224     brouard  2655: #else
1.234     brouard  2656:        linmin(p,xit,n,fret,func,&flat); /* computes minimum on the extrapolated direction: changes p and rescales xit.*/
                   2657:        flatdir[i]=flat; /* Function is vanishing in that direction i */
1.191     brouard  2658: #endif
1.234     brouard  2659:        
1.191     brouard  2660: #ifdef DEBUGLINMIN
1.234     brouard  2661:        for (j=1;j<=n;j++) { 
                   2662:          printf("After xit[%d]= %12.7f p[%d]= %12.7f",j,xit[j],j,p[j]);
                   2663:          fprintf(ficlog,"After xit[%d]= %12.7f p[%d]= %12.7f",j,xit[j],j,p[j]);
                   2664:          if(j % ncovmodel == 0){
                   2665:            printf("\n");
                   2666:            fprintf(ficlog,"\n");
                   2667:          }
                   2668:        }
1.224     brouard  2669: #endif
1.234     brouard  2670:        for (j=1;j<=n;j++) { 
                   2671:          xi[j][ibig]=xi[j][n]; /* Replace direction with biggest decrease by last direction n */
                   2672:          xi[j][n]=xit[j];      /* and this nth direction by the by the average p_0 p_n */
                   2673:        }
1.224     brouard  2674: #ifdef LINMINORIGINAL
                   2675: #else
1.234     brouard  2676:        for (j=1, flatd=0;j<=n;j++) {
                   2677:          if(flatdir[j]>0)
                   2678:            flatd++;
                   2679:        }
                   2680:        if(flatd >0){
1.255     brouard  2681:          printf("%d flat directions: ",flatd);
                   2682:          fprintf(ficlog,"%d flat directions :",flatd);
1.234     brouard  2683:          for (j=1;j<=n;j++) { 
                   2684:            if(flatdir[j]>0){
                   2685:              printf("%d ",j);
                   2686:              fprintf(ficlog,"%d ",j);
                   2687:            }
                   2688:          }
                   2689:          printf("\n");
                   2690:          fprintf(ficlog,"\n");
1.319     brouard  2691: #ifdef FLATSUP
                   2692:           free_vector(xit,1,n); 
                   2693:           free_vector(xits,1,n); 
                   2694:           free_vector(ptt,1,n); 
                   2695:           free_vector(pt,1,n); 
                   2696:           return;
                   2697: #endif
1.234     brouard  2698:        }
1.191     brouard  2699: #endif
1.234     brouard  2700:        printf("Gaining to use new average direction of P0 P%d instead of biggest increase direction %d :\n",n,ibig);
                   2701:        fprintf(ficlog,"Gaining to use new average direction of P0 P%d instead of biggest increase direction %d :\n",n,ibig);
                   2702:        
1.126     brouard  2703: #ifdef DEBUG
1.234     brouard  2704:        printf("Direction changed  last moved %d in place of ibig=%d, new last is the average:\n",n,ibig);
                   2705:        fprintf(ficlog,"Direction changed  last moved %d in place of ibig=%d, new last is the average:\n",n,ibig);
                   2706:        for(j=1;j<=n;j++){
                   2707:          printf(" %lf",xit[j]);
                   2708:          fprintf(ficlog," %lf",xit[j]);
                   2709:        }
                   2710:        printf("\n");
                   2711:        fprintf(ficlog,"\n");
1.126     brouard  2712: #endif
1.192     brouard  2713:       } /* end of t or directest negative */
1.224     brouard  2714: #ifdef POWELLNOF3INFF1TEST
1.192     brouard  2715: #else
1.234     brouard  2716:       } /* end if (fptt < fp)  */
1.192     brouard  2717: #endif
1.225     brouard  2718: #ifdef NODIRECTIONCHANGEDUNTILNITER  /* No change in drections until some iterations are done */
1.234     brouard  2719:     } /*NODIRECTIONCHANGEDUNTILNITER  No change in drections until some iterations are done */
1.225     brouard  2720: #else
1.224     brouard  2721: #endif
1.234     brouard  2722:                } /* loop iteration */ 
1.126     brouard  2723: } 
1.234     brouard  2724:   
1.126     brouard  2725: /**** Prevalence limit (stable or period prevalence)  ****************/
1.234     brouard  2726:   
1.235     brouard  2727:   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  2728:   {
1.279     brouard  2729:     /**< Computes the prevalence limit in each live state at age x and for covariate combination ij 
                   2730:      *   (and selected quantitative values in nres)
                   2731:      *  by left multiplying the unit
                   2732:      *  matrix by transitions matrix until convergence is reached with precision ftolpl 
                   2733:      * Wx= Wx-1 Px-1= Wx-2 Px-2 Px-1  = Wx-n Px-n ... Px-2 Px-1 I
                   2734:      * Wx is row vector: population in state 1, population in state 2, population dead
                   2735:      * or prevalence in state 1, prevalence in state 2, 0
                   2736:      * newm is the matrix after multiplications, its rows are identical at a factor.
                   2737:      * Inputs are the parameter, age, a tolerance for the prevalence limit ftolpl.
                   2738:      * Output is prlim.
                   2739:      * Initial matrix pimij 
                   2740:      */
1.206     brouard  2741:   /* {0.85204250825084937, 0.13044499163996345, 0.017512500109187184, */
                   2742:   /* 0.090851990222114765, 0.88271245433047185, 0.026435555447413338, */
                   2743:   /*  0,                   0                  , 1} */
                   2744:   /*
                   2745:    * and after some iteration: */
                   2746:   /* {0.45504275246439968, 0.42731458730878791, 0.11764266022681241, */
                   2747:   /*  0.45201005341706885, 0.42865420071559901, 0.11933574586733192, */
                   2748:   /*  0,                   0                  , 1} */
                   2749:   /* And prevalence by suppressing the deaths are close to identical rows in prlim: */
                   2750:   /* {0.51571254859325999, 0.4842874514067399, */
                   2751:   /*  0.51326036147820708, 0.48673963852179264} */
                   2752:   /* If we start from prlim again, prlim tends to a constant matrix */
1.234     brouard  2753:     
1.126     brouard  2754:   int i, ii,j,k;
1.209     brouard  2755:   double *min, *max, *meandiff, maxmax,sumnew=0.;
1.145     brouard  2756:   /* double **matprod2(); */ /* test */
1.218     brouard  2757:   double **out, cov[NCOVMAX+1], **pmij(); /* **pmmij is a global variable feeded with oldms etc */
1.126     brouard  2758:   double **newm;
1.209     brouard  2759:   double agefin, delaymax=200. ; /* 100 Max number of years to converge */
1.203     brouard  2760:   int ncvloop=0;
1.288     brouard  2761:   int first=0;
1.169     brouard  2762:   
1.209     brouard  2763:   min=vector(1,nlstate);
                   2764:   max=vector(1,nlstate);
                   2765:   meandiff=vector(1,nlstate);
                   2766: 
1.218     brouard  2767:        /* Starting with matrix unity */
1.126     brouard  2768:   for (ii=1;ii<=nlstate+ndeath;ii++)
                   2769:     for (j=1;j<=nlstate+ndeath;j++){
                   2770:       oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   2771:     }
1.169     brouard  2772:   
                   2773:   cov[1]=1.;
                   2774:   
                   2775:   /* Even if hstepm = 1, at least one multiplication by the unit matrix */
1.202     brouard  2776:   /* Start at agefin= age, computes the matrix of passage and loops decreasing agefin until convergence is reached */
1.126     brouard  2777:   for(agefin=age-stepm/YEARM; agefin>=age-delaymax; agefin=agefin-stepm/YEARM){
1.202     brouard  2778:     ncvloop++;
1.126     brouard  2779:     newm=savm;
                   2780:     /* Covariates have to be included here again */
1.138     brouard  2781:     cov[2]=agefin;
1.319     brouard  2782:      if(nagesqr==1){
                   2783:       cov[3]= agefin*agefin;
                   2784:      }
1.234     brouard  2785:     for (k=1; k<=nsd;k++) { /* For single dummy covariates only */
                   2786:                        /* Here comes the value of the covariate 'ij' after renumbering k with single dummy covariates */
                   2787:       cov[2+nagesqr+TvarsDind[k]]=nbcode[TvarsD[k]][codtabm(ij,k)];
1.319     brouard  2788:       /* cov[++k1]=nbcode[TvarsD[k]][codtabm(ij,k)]; */
1.235     brouard  2789:       /* 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  2790:     }
                   2791:     for (k=1; k<=nsq;k++) { /* For single varying covariates only */
                   2792:                        /* Here comes the value of quantitative after renumbering k with single quantitative covariates */
1.319     brouard  2793:       cov[2+nagesqr+TvarsQind[k]]=Tqresult[nres][k];
                   2794:       /* cov[++k1]=Tqresult[nres][k];  */
1.235     brouard  2795:       /* 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  2796:     }
1.237     brouard  2797:     for (k=1; k<=cptcovage;k++){  /* For product with age */
1.319     brouard  2798:       if(Dummy[Tage[k]]==2){ /* dummy with age */
1.234     brouard  2799:        cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,k)]*cov[2];
1.319     brouard  2800:        /* cov[++k1]=nbcode[Tvar[Tage[k]]][codtabm(ij,k)]*cov[2]; */
                   2801:       } else if(Dummy[Tage[k]]==3){ /* quantitative with age */
                   2802:        cov[2+nagesqr+Tage[k]]=Tqresult[nres][k];
                   2803:        /* cov[++k1]=Tqresult[nres][k];  */
1.234     brouard  2804:       }
1.235     brouard  2805:       /* 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  2806:     }
1.237     brouard  2807:     for (k=1; k<=cptcovprod;k++){ /* For product without age */
1.235     brouard  2808:       /* 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  2809:       if(Dummy[Tvard[k][1]==0]){
                   2810:        if(Dummy[Tvard[k][2]==0]){
                   2811:          cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)] * nbcode[Tvard[k][2]][codtabm(ij,k)];
1.319     brouard  2812:          /* cov[++k1]=nbcode[Tvard[k][1]][codtabm(ij,k)] * nbcode[Tvard[k][2]][codtabm(ij,k)]; */
1.237     brouard  2813:        }else{
                   2814:          cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)] * Tqresult[nres][k];
1.319     brouard  2815:          /* cov[++k1]=nbcode[Tvard[k][1]][codtabm(ij,k)] * Tqresult[nres][k]; */
1.237     brouard  2816:        }
                   2817:       }else{
                   2818:        if(Dummy[Tvard[k][2]==0]){
                   2819:          cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][2]][codtabm(ij,k)] * Tqinvresult[nres][Tvard[k][1]];
1.319     brouard  2820:          /* cov[++k1]=nbcode[Tvard[k][2]][codtabm(ij,k)] * Tqinvresult[nres][Tvard[k][1]]; */
1.237     brouard  2821:        }else{
                   2822:          cov[2+nagesqr+Tprod[k]]=Tqinvresult[nres][Tvard[k][1]]*  Tqinvresult[nres][Tvard[k][2]];
1.319     brouard  2823:          /* cov[++k1]=Tqinvresult[nres][Tvard[k][1]]*  Tqinvresult[nres][Tvard[k][2]]; */
1.237     brouard  2824:        }
                   2825:       }
1.234     brouard  2826:     }
1.138     brouard  2827:     /*printf("ij=%d cptcovprod=%d tvar=%d ", ij, cptcovprod, Tvar[1]);*/
                   2828:     /*printf("ij=%d cov[3]=%lf cov[4]=%lf \n",ij, cov[3],cov[4]);*/
                   2829:     /*printf("ij=%d cov[3]=%lf \n",ij, cov[3]);*/
1.145     brouard  2830:     /* savm=pmij(pmmij,cov,ncovmodel,x,nlstate); */
                   2831:     /* out=matprod2(newm, pmij(pmmij,cov,ncovmodel,x,nlstate),1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm); /\* Bug Valgrind *\/ */
1.319     brouard  2832:     /* age and covariate values of ij are in 'cov' */
1.142     brouard  2833:     out=matprod2(newm, pmij(pmmij,cov,ncovmodel,x,nlstate),1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm); /* Bug Valgrind */
1.138     brouard  2834:     
1.126     brouard  2835:     savm=oldm;
                   2836:     oldm=newm;
1.209     brouard  2837: 
                   2838:     for(j=1; j<=nlstate; j++){
                   2839:       max[j]=0.;
                   2840:       min[j]=1.;
                   2841:     }
                   2842:     for(i=1;i<=nlstate;i++){
                   2843:       sumnew=0;
                   2844:       for(k=1; k<=ndeath; k++) sumnew+=newm[i][nlstate+k];
                   2845:       for(j=1; j<=nlstate; j++){ 
                   2846:        prlim[i][j]= newm[i][j]/(1-sumnew);
                   2847:        max[j]=FMAX(max[j],prlim[i][j]);
                   2848:        min[j]=FMIN(min[j],prlim[i][j]);
                   2849:       }
                   2850:     }
                   2851: 
1.126     brouard  2852:     maxmax=0.;
1.209     brouard  2853:     for(j=1; j<=nlstate; j++){
                   2854:       meandiff[j]=(max[j]-min[j])/(max[j]+min[j])*2.; /* mean difference for each column */
                   2855:       maxmax=FMAX(maxmax,meandiff[j]);
                   2856:       /* 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  2857:     } /* j loop */
1.203     brouard  2858:     *ncvyear= (int)age- (int)agefin;
1.208     brouard  2859:     /* 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  2860:     if(maxmax < ftolpl){
1.209     brouard  2861:       /* printf("maxmax=%lf ncvloop=%ld, age=%d, agefin=%d ncvyear=%d \n", maxmax, ncvloop, (int)age, (int)agefin, *ncvyear); */
                   2862:       free_vector(min,1,nlstate);
                   2863:       free_vector(max,1,nlstate);
                   2864:       free_vector(meandiff,1,nlstate);
1.126     brouard  2865:       return prlim;
                   2866:     }
1.288     brouard  2867:   } /* agefin loop */
1.208     brouard  2868:     /* After some age loop it doesn't converge */
1.288     brouard  2869:   if(!first){
                   2870:     first=1;
                   2871:     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);
1.317     brouard  2872:     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);
                   2873:   }else if (first >=1 && first <10){
                   2874:     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);
                   2875:     first++;
                   2876:   }else if (first ==10){
                   2877:     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);
                   2878:     printf("Warning: the stable prevalence dit not converge. This warning came too often, IMaCh will stop notifying, even in its log file. Look at the graphs to appreciate the non convergence.\n");
                   2879:     fprintf(ficlog,"Warning: the stable prevalence no convergence; too many cases, giving up noticing, even in log file\n");
                   2880:     first++;
1.288     brouard  2881:   }
                   2882: 
1.209     brouard  2883:   /* 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); */
                   2884:   free_vector(min,1,nlstate);
                   2885:   free_vector(max,1,nlstate);
                   2886:   free_vector(meandiff,1,nlstate);
1.208     brouard  2887:   
1.169     brouard  2888:   return prlim; /* should not reach here */
1.126     brouard  2889: }
                   2890: 
1.217     brouard  2891: 
                   2892:  /**** Back Prevalence limit (stable or period prevalence)  ****************/
                   2893: 
1.218     brouard  2894:  /* 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) */
                   2895:  /* 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  2896:   double **bprevalim(double **bprlim, double ***prevacurrent, int nlstate, double x[], double age, double ftolpl, int *ncvyear, int ij, int nres)
1.217     brouard  2897: {
1.264     brouard  2898:   /* 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  2899:      matrix by transitions matrix until convergence is reached with precision ftolpl */
                   2900:   /* Wx= Wx-1 Px-1= Wx-2 Px-2 Px-1  = Wx-n Px-n ... Px-2 Px-1 I */
                   2901:   /* Wx is row vector: population in state 1, population in state 2, population dead */
                   2902:   /* or prevalence in state 1, prevalence in state 2, 0 */
                   2903:   /* newm is the matrix after multiplications, its rows are identical at a factor */
                   2904:   /* Initial matrix pimij */
                   2905:   /* {0.85204250825084937, 0.13044499163996345, 0.017512500109187184, */
                   2906:   /* 0.090851990222114765, 0.88271245433047185, 0.026435555447413338, */
                   2907:   /*  0,                   0                  , 1} */
                   2908:   /*
                   2909:    * and after some iteration: */
                   2910:   /* {0.45504275246439968, 0.42731458730878791, 0.11764266022681241, */
                   2911:   /*  0.45201005341706885, 0.42865420071559901, 0.11933574586733192, */
                   2912:   /*  0,                   0                  , 1} */
                   2913:   /* And prevalence by suppressing the deaths are close to identical rows in prlim: */
                   2914:   /* {0.51571254859325999, 0.4842874514067399, */
                   2915:   /*  0.51326036147820708, 0.48673963852179264} */
                   2916:   /* If we start from prlim again, prlim tends to a constant matrix */
                   2917: 
                   2918:   int i, ii,j,k;
1.247     brouard  2919:   int first=0;
1.217     brouard  2920:   double *min, *max, *meandiff, maxmax,sumnew=0.;
                   2921:   /* double **matprod2(); */ /* test */
                   2922:   double **out, cov[NCOVMAX+1], **bmij();
                   2923:   double **newm;
1.218     brouard  2924:   double        **dnewm, **doldm, **dsavm;  /* for use */
                   2925:   double        **oldm, **savm;  /* for use */
                   2926: 
1.217     brouard  2927:   double agefin, delaymax=200. ; /* 100 Max number of years to converge */
                   2928:   int ncvloop=0;
                   2929:   
                   2930:   min=vector(1,nlstate);
                   2931:   max=vector(1,nlstate);
                   2932:   meandiff=vector(1,nlstate);
                   2933: 
1.266     brouard  2934:   dnewm=ddnewms; doldm=ddoldms; dsavm=ddsavms;
                   2935:   oldm=oldms; savm=savms;
                   2936:   
                   2937:   /* Starting with matrix unity */
                   2938:   for (ii=1;ii<=nlstate+ndeath;ii++)
                   2939:     for (j=1;j<=nlstate+ndeath;j++){
1.217     brouard  2940:       oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   2941:     }
                   2942:   
                   2943:   cov[1]=1.;
                   2944:   
                   2945:   /* Even if hstepm = 1, at least one multiplication by the unit matrix */
                   2946:   /* Start at agefin= age, computes the matrix of passage and loops decreasing agefin until convergence is reached */
1.218     brouard  2947:   /* for(agefin=age+stepm/YEARM; agefin<=age+delaymax; agefin=agefin+stepm/YEARM){ /\* A changer en age *\/ */
1.288     brouard  2948:   /* for(agefin=age; agefin<AGESUP; agefin=agefin+stepm/YEARM){ /\* A changer en age *\/ */
                   2949:   for(agefin=age; agefin<FMIN(AGESUP,age+delaymax); agefin=agefin+stepm/YEARM){ /* A changer en age */
1.217     brouard  2950:     ncvloop++;
1.218     brouard  2951:     newm=savm; /* oldm should be kept from previous iteration or unity at start */
                   2952:                /* newm points to the allocated table savm passed by the function it can be written, savm could be reallocated */
1.217     brouard  2953:     /* Covariates have to be included here again */
                   2954:     cov[2]=agefin;
1.319     brouard  2955:     if(nagesqr==1){
1.217     brouard  2956:       cov[3]= agefin*agefin;;
1.319     brouard  2957:     }
1.242     brouard  2958:     for (k=1; k<=nsd;k++) { /* For single dummy covariates only */
                   2959:                        /* Here comes the value of the covariate 'ij' after renumbering k with single dummy covariates */
                   2960:       cov[2+nagesqr+TvarsDind[k]]=nbcode[TvarsD[k]][codtabm(ij,k)];
1.264     brouard  2961:       /* 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  2962:     }
                   2963:     /* for (k=1; k<=cptcovn;k++) { */
                   2964:     /*   /\* cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,Tvar[k])]; *\/ */
                   2965:     /*   cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,k)]; */
                   2966:     /*   /\* 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])]); *\/ */
                   2967:     /* } */
                   2968:     for (k=1; k<=nsq;k++) { /* For single varying covariates only */
                   2969:                        /* Here comes the value of quantitative after renumbering k with single quantitative covariates */
                   2970:       cov[2+nagesqr+TvarsQind[k]]=Tqresult[nres][k]; 
                   2971:       /* 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]); */
                   2972:     }
                   2973:     /* for (k=1; k<=cptcovage;k++) cov[2+nagesqr+Tage[k]]=nbcode[Tvar[k]][codtabm(ij,k)]*cov[2]; */
                   2974:     /* for (k=1; k<=cptcovprod;k++) /\* Useless *\/ */
                   2975:     /*   /\* cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,Tvard[k][1])] * nbcode[Tvard[k][2]][codtabm(ij,Tvard[k][2])]; *\/ */
                   2976:     /*   cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)] * nbcode[Tvard[k][2]][codtabm(ij,k)]; */
                   2977:     for (k=1; k<=cptcovage;k++){  /* For product with age */
1.319     brouard  2978:       /* if(Dummy[Tvar[Tage[k]]]== 2){ /\* dummy with age *\/ ERROR ???*/
                   2979:       if(Dummy[Tage[k]]== 2){ /* dummy with age */
1.242     brouard  2980:        cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,k)]*cov[2];
1.319     brouard  2981:       } else if(Dummy[Tage[k]]== 3){ /* quantitative with age */
                   2982:        cov[2+nagesqr+Tage[k]]=Tqresult[nres][k];
1.242     brouard  2983:       }
                   2984:       /* 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]); */
                   2985:     }
                   2986:     for (k=1; k<=cptcovprod;k++){ /* For product without age */
                   2987:       /* 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]); */
                   2988:       if(Dummy[Tvard[k][1]==0]){
                   2989:        if(Dummy[Tvard[k][2]==0]){
                   2990:          cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)] * nbcode[Tvard[k][2]][codtabm(ij,k)];
                   2991:        }else{
                   2992:          cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)] * Tqresult[nres][k];
                   2993:        }
                   2994:       }else{
                   2995:        if(Dummy[Tvard[k][2]==0]){
                   2996:          cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][2]][codtabm(ij,k)] * Tqinvresult[nres][Tvard[k][1]];
                   2997:        }else{
                   2998:          cov[2+nagesqr+Tprod[k]]=Tqinvresult[nres][Tvard[k][1]]*  Tqinvresult[nres][Tvard[k][2]];
                   2999:        }
                   3000:       }
1.217     brouard  3001:     }
                   3002:     
                   3003:     /*printf("ij=%d cptcovprod=%d tvar=%d ", ij, cptcovprod, Tvar[1]);*/
                   3004:     /*printf("ij=%d cov[3]=%lf cov[4]=%lf \n",ij, cov[3],cov[4]);*/
                   3005:     /*printf("ij=%d cov[3]=%lf \n",ij, cov[3]);*/
                   3006:     /* savm=pmij(pmmij,cov,ncovmodel,x,nlstate); */
                   3007:     /* out=matprod2(newm, pmij(pmmij,cov,ncovmodel,x,nlstate),1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm); /\* Bug Valgrind *\/ */
1.218     brouard  3008:                /* ij should be linked to the correct index of cov */
                   3009:                /* age and covariate values ij are in 'cov', but we need to pass
                   3010:                 * ij for the observed prevalence at age and status and covariate
                   3011:                 * number:  prevacurrent[(int)agefin][ii][ij]
                   3012:                 */
                   3013:     /* 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 *\/ */
                   3014:     /* 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 *\/ */
                   3015:     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  3016:     /* if((int)age == 86 || (int)age == 87){ */
1.266     brouard  3017:     /*   printf(" Backward prevalim age=%d agefin=%d \n", (int) age, (int) agefin); */
                   3018:     /*   for(i=1; i<=nlstate+ndeath; i++) { */
                   3019:     /*         printf("%d newm= ",i); */
                   3020:     /*         for(j=1;j<=nlstate+ndeath;j++) { */
                   3021:     /*           printf("%f ",newm[i][j]); */
                   3022:     /*         } */
                   3023:     /*         printf("oldm * "); */
                   3024:     /*         for(j=1;j<=nlstate+ndeath;j++) { */
                   3025:     /*           printf("%f ",oldm[i][j]); */
                   3026:     /*         } */
1.268     brouard  3027:     /*         printf(" bmmij "); */
1.266     brouard  3028:     /*         for(j=1;j<=nlstate+ndeath;j++) { */
                   3029:     /*           printf("%f ",pmmij[i][j]); */
                   3030:     /*         } */
                   3031:     /*         printf("\n"); */
                   3032:     /*   } */
                   3033:     /* } */
1.217     brouard  3034:     savm=oldm;
                   3035:     oldm=newm;
1.266     brouard  3036: 
1.217     brouard  3037:     for(j=1; j<=nlstate; j++){
                   3038:       max[j]=0.;
                   3039:       min[j]=1.;
                   3040:     }
                   3041:     for(j=1; j<=nlstate; j++){ 
                   3042:       for(i=1;i<=nlstate;i++){
1.234     brouard  3043:        /* bprlim[i][j]= newm[i][j]/(1-sumnew); */
                   3044:        bprlim[i][j]= newm[i][j];
                   3045:        max[i]=FMAX(max[i],bprlim[i][j]); /* Max in line */
                   3046:        min[i]=FMIN(min[i],bprlim[i][j]);
1.217     brouard  3047:       }
                   3048:     }
1.218     brouard  3049:                
1.217     brouard  3050:     maxmax=0.;
                   3051:     for(i=1; i<=nlstate; i++){
1.318     brouard  3052:       meandiff[i]=(max[i]-min[i])/(max[i]+min[i])*2.; /* mean difference for each column, could be nan! */
1.217     brouard  3053:       maxmax=FMAX(maxmax,meandiff[i]);
                   3054:       /* 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  3055:     } /* i loop */
1.217     brouard  3056:     *ncvyear= -( (int)age- (int)agefin);
1.268     brouard  3057:     /* printf("Back maxmax=%lf ncvloop=%d, age=%d, agefin=%d ncvyear=%d \n", maxmax, ncvloop, (int)age, (int)agefin, *ncvyear); */
1.217     brouard  3058:     if(maxmax < ftolpl){
1.220     brouard  3059:       /* printf("OK Back maxmax=%lf ncvloop=%d, age=%d, agefin=%d ncvyear=%d \n", maxmax, ncvloop, (int)age, (int)agefin, *ncvyear); */
1.217     brouard  3060:       free_vector(min,1,nlstate);
                   3061:       free_vector(max,1,nlstate);
                   3062:       free_vector(meandiff,1,nlstate);
                   3063:       return bprlim;
                   3064:     }
1.288     brouard  3065:   } /* agefin loop */
1.217     brouard  3066:     /* After some age loop it doesn't converge */
1.288     brouard  3067:   if(!first){
1.247     brouard  3068:     first=1;
                   3069:     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\
                   3070: 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);
                   3071:   }
                   3072:   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  3073: 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);
                   3074:   /* 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); */
                   3075:   free_vector(min,1,nlstate);
                   3076:   free_vector(max,1,nlstate);
                   3077:   free_vector(meandiff,1,nlstate);
                   3078:   
                   3079:   return bprlim; /* should not reach here */
                   3080: }
                   3081: 
1.126     brouard  3082: /*************** transition probabilities ***************/ 
                   3083: 
                   3084: double **pmij(double **ps, double *cov, int ncovmodel, double *x, int nlstate )
                   3085: {
1.138     brouard  3086:   /* According to parameters values stored in x and the covariate's values stored in cov,
1.266     brouard  3087:      computes the probability to be observed in state j (after stepm years) being in state i by appying the
1.138     brouard  3088:      model to the ncovmodel covariates (including constant and age).
                   3089:      lnpijopii=ln(pij/pii)= aij+bij*age+cij*v1+dij*v2+... = sum_nc=1^ncovmodel xij(nc)*cov[nc]
                   3090:      and, according on how parameters are entered, the position of the coefficient xij(nc) of the
                   3091:      ncth covariate in the global vector x is given by the formula:
                   3092:      j<i nc+((i-1)*(nlstate+ndeath-1)+j-1)*ncovmodel
                   3093:      j>=i nc + ((i-1)*(nlstate+ndeath-1)+(j-2))*ncovmodel
                   3094:      Computes ln(pij/pii) (lnpijopii), deduces pij/pii by exponentiation,
                   3095:      sums on j different of i to get 1-pii/pii, deduces pii, and then all pij.
1.266     brouard  3096:      Outputs ps[i][j] or probability to be observed in j being in i according to
1.138     brouard  3097:      the values of the covariates cov[nc] and corresponding parameter values x[nc+shiftij]
1.266     brouard  3098:      Sum on j ps[i][j] should equal to 1.
1.138     brouard  3099:   */
                   3100:   double s1, lnpijopii;
1.126     brouard  3101:   /*double t34;*/
1.164     brouard  3102:   int i,j, nc, ii, jj;
1.126     brouard  3103: 
1.223     brouard  3104:   for(i=1; i<= nlstate; i++){
                   3105:     for(j=1; j<i;j++){
                   3106:       for (nc=1, lnpijopii=0.;nc <=ncovmodel; nc++){
                   3107:        /*lnpijopii += param[i][j][nc]*cov[nc];*/
                   3108:        lnpijopii += x[nc+((i-1)*(nlstate+ndeath-1)+j-1)*ncovmodel]*cov[nc];
                   3109:        /*       printf("Int j<i s1=%.17e, lnpijopii=%.17e\n",s1,lnpijopii); */
                   3110:       }
                   3111:       ps[i][j]=lnpijopii; /* In fact ln(pij/pii) */
                   3112:       /*       printf("s1=%.17e, lnpijopii=%.17e\n",s1,lnpijopii); */
                   3113:     }
                   3114:     for(j=i+1; j<=nlstate+ndeath;j++){
                   3115:       for (nc=1, lnpijopii=0.;nc <=ncovmodel; nc++){
                   3116:        /*lnpijopii += x[(i-1)*nlstate*ncovmodel+(j-2)*ncovmodel+nc+(i-1)*(ndeath-1)*ncovmodel]*cov[nc];*/
                   3117:        lnpijopii += x[nc + ((i-1)*(nlstate+ndeath-1)+(j-2))*ncovmodel]*cov[nc];
                   3118:        /*        printf("Int j>i s1=%.17e, lnpijopii=%.17e %lx %lx\n",s1,lnpijopii,s1,lnpijopii); */
                   3119:       }
                   3120:       ps[i][j]=lnpijopii; /* In fact ln(pij/pii) */
                   3121:     }
                   3122:   }
1.218     brouard  3123:   
1.223     brouard  3124:   for(i=1; i<= nlstate; i++){
                   3125:     s1=0;
                   3126:     for(j=1; j<i; j++){
                   3127:       s1+=exp(ps[i][j]); /* In fact sums pij/pii */
                   3128:       /*printf("debug1 %d %d ps=%lf exp(ps)=%lf s1+=%lf\n",i,j,ps[i][j],exp(ps[i][j]),s1); */
                   3129:     }
                   3130:     for(j=i+1; j<=nlstate+ndeath; j++){
                   3131:       s1+=exp(ps[i][j]); /* In fact sums pij/pii */
                   3132:       /*printf("debug2 %d %d ps=%lf exp(ps)=%lf s1+=%lf\n",i,j,ps[i][j],exp(ps[i][j]),s1); */
                   3133:     }
                   3134:     /* s1= sum_{j<>i} pij/pii=(1-pii)/pii and thus pii is known from s1 */
                   3135:     ps[i][i]=1./(s1+1.);
                   3136:     /* Computing other pijs */
                   3137:     for(j=1; j<i; j++)
                   3138:       ps[i][j]= exp(ps[i][j])*ps[i][i];
                   3139:     for(j=i+1; j<=nlstate+ndeath; j++)
                   3140:       ps[i][j]= exp(ps[i][j])*ps[i][i];
                   3141:     /* ps[i][nlstate+1]=1.-s1- ps[i][i];*/ /* Sum should be 1 */
                   3142:   } /* end i */
1.218     brouard  3143:   
1.223     brouard  3144:   for(ii=nlstate+1; ii<= nlstate+ndeath; ii++){
                   3145:     for(jj=1; jj<= nlstate+ndeath; jj++){
                   3146:       ps[ii][jj]=0;
                   3147:       ps[ii][ii]=1;
                   3148:     }
                   3149:   }
1.294     brouard  3150: 
                   3151: 
1.223     brouard  3152:   /* for(ii=1; ii<= nlstate+ndeath; ii++){ */
                   3153:   /*   for(jj=1; jj<= nlstate+ndeath; jj++){ */
                   3154:   /*   printf(" pmij  ps[%d][%d]=%lf ",ii,jj,ps[ii][jj]); */
                   3155:   /*   } */
                   3156:   /*   printf("\n "); */
                   3157:   /* } */
                   3158:   /* printf("\n ");printf("%lf ",cov[2]);*/
                   3159:   /*
                   3160:     for(i=1; i<= npar; i++) printf("%f ",x[i]);
1.218     brouard  3161:                goto end;*/
1.266     brouard  3162:   return ps; /* Pointer is unchanged since its call */
1.126     brouard  3163: }
                   3164: 
1.218     brouard  3165: /*************** backward transition probabilities ***************/ 
                   3166: 
                   3167:  /* 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 ) */
                   3168: /* double **bmij(double **ps, double *cov, int ncovmodel, double *x, int nlstate,  double ***prevacurrent, double ***dnewm, double **doldm, double **dsavm, int ij ) */
                   3169:  double **bmij(double **ps, double *cov, int ncovmodel, double *x, int nlstate,  double ***prevacurrent, int ij )
                   3170: {
1.302     brouard  3171:   /* Computes the backward probability at age agefin, cov[2], and covariate combination 'ij'. In fact cov is already filled and x too.
1.266     brouard  3172:    * 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  3173:    */
1.218     brouard  3174:   int i, ii, j,k;
1.222     brouard  3175:   
                   3176:   double **out, **pmij();
                   3177:   double sumnew=0.;
1.218     brouard  3178:   double agefin;
1.292     brouard  3179:   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  3180:   double **dnewm, **dsavm, **doldm;
                   3181:   double **bbmij;
                   3182:   
1.218     brouard  3183:   doldm=ddoldms; /* global pointers */
1.222     brouard  3184:   dnewm=ddnewms;
                   3185:   dsavm=ddsavms;
1.318     brouard  3186: 
                   3187:   /* Debug */
                   3188:   /* printf("Bmij ij=%d, cov[2}=%f\n", ij, cov[2]); */
1.222     brouard  3189:   agefin=cov[2];
1.268     brouard  3190:   /* Bx = Diag(w_x) P_x Diag(Sum_i w^i_x p^ij_x */
1.222     brouard  3191:   /* bmij *//* age is cov[2], ij is included in cov, but we need for
1.266     brouard  3192:      the observed prevalence (with this covariate ij) at beginning of transition */
                   3193:   /* dsavm=pmij(pmmij,cov,ncovmodel,x,nlstate); */
1.268     brouard  3194: 
                   3195:   /* P_x */
1.266     brouard  3196:   pmmij=pmij(pmmij,cov,ncovmodel,x,nlstate); /*This is forward probability from agefin to agefin + stepm */
1.268     brouard  3197:   /* outputs pmmij which is a stochastic matrix in row */
                   3198: 
                   3199:   /* Diag(w_x) */
1.292     brouard  3200:   /* Rescaling the cross-sectional prevalence: Problem with prevacurrent which can be zero */
1.268     brouard  3201:   sumnew=0.;
1.269     brouard  3202:   /*for (ii=1;ii<=nlstate+ndeath;ii++){*/
1.268     brouard  3203:   for (ii=1;ii<=nlstate;ii++){ /* Only on live states */
1.297     brouard  3204:     /* printf(" agefin=%d, ii=%d, ij=%d, prev=%f\n",(int)agefin,ii, ij, prevacurrent[(int)agefin][ii][ij]); */
1.268     brouard  3205:     sumnew+=prevacurrent[(int)agefin][ii][ij];
                   3206:   }
                   3207:   if(sumnew >0.01){  /* At least some value in the prevalence */
                   3208:     for (ii=1;ii<=nlstate+ndeath;ii++){
                   3209:       for (j=1;j<=nlstate+ndeath;j++)
1.269     brouard  3210:        doldm[ii][j]=(ii==j ? prevacurrent[(int)agefin][ii][ij]/sumnew : 0.0);
1.268     brouard  3211:     }
                   3212:   }else{
                   3213:     for (ii=1;ii<=nlstate+ndeath;ii++){
                   3214:       for (j=1;j<=nlstate+ndeath;j++)
                   3215:       doldm[ii][j]=(ii==j ? 1./nlstate : 0.0);
                   3216:     }
                   3217:     /* if(sumnew <0.9){ */
                   3218:     /*   printf("Problem internal bmij B: sum on i wi <0.9: j=%d, sum_i wi=%lf,agefin=%d\n",j,sumnew, (int)agefin); */
                   3219:     /* } */
                   3220:   }
                   3221:   k3=0.0;  /* We put the last diagonal to 0 */
                   3222:   for (ii=nlstate+1;ii<=nlstate+ndeath;ii++){
                   3223:       doldm[ii][ii]= k3;
                   3224:   }
                   3225:   /* End doldm, At the end doldm is diag[(w_i)] */
                   3226:   
1.292     brouard  3227:   /* Left product of this diag matrix by pmmij=Px (dnewm=dsavm*doldm): diag[(w_i)*Px */
                   3228:   bbmij=matprod2(dnewm, doldm,1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, pmmij); /* was a Bug Valgrind */
1.268     brouard  3229: 
1.292     brouard  3230:   /* Diag(Sum_i w^i_x p^ij_x, should be the prevalence at age x+stepm */
1.268     brouard  3231:   /* 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  3232:   for (j=1;j<=nlstate+ndeath;j++){
1.268     brouard  3233:     sumnew=0.;
1.222     brouard  3234:     for (ii=1;ii<=nlstate;ii++){
1.266     brouard  3235:       /* sumnew+=dsavm[ii][j]*prevacurrent[(int)agefin][ii][ij]; */
1.268     brouard  3236:       sumnew+=pmmij[ii][j]*doldm[ii][ii]; /* Yes prevalence at beginning of transition */
1.222     brouard  3237:     } /* sumnew is (N11+N21)/N..= N.1/N.. = sum on i of w_i pij */
1.268     brouard  3238:     for (ii=1;ii<=nlstate+ndeath;ii++){
1.222     brouard  3239:        /* if(agefin >= agemaxpar && agefin <= agemaxpar+stepm/YEARM){ */
1.268     brouard  3240:        /*      dsavm[ii][j]=(ii==j ? 1./sumnew : 0.0); */
1.222     brouard  3241:        /* }else if(agefin >= agemaxpar+stepm/YEARM){ */
1.268     brouard  3242:        /*      dsavm[ii][j]=(ii==j ? 1./sumnew : 0.0); */
1.222     brouard  3243:        /* }else */
1.268     brouard  3244:       dsavm[ii][j]=(ii==j ? 1./sumnew : 0.0);
                   3245:     } /*End ii */
                   3246:   } /* 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 */
                   3247: 
1.292     brouard  3248:   ps=matprod2(ps, dnewm,1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, dsavm); /* was a Bug Valgrind */
1.268     brouard  3249:   /* ps is now diag[w_i] * Px * diag [1/(w_1p1i+w_2 p2i)] */
1.222     brouard  3250:   /* end bmij */
1.266     brouard  3251:   return ps; /*pointer is unchanged */
1.218     brouard  3252: }
1.217     brouard  3253: /*************** transition probabilities ***************/ 
                   3254: 
1.218     brouard  3255: double **bpmij(double **ps, double *cov, int ncovmodel, double *x, int nlstate )
1.217     brouard  3256: {
                   3257:   /* According to parameters values stored in x and the covariate's values stored in cov,
                   3258:      computes the probability to be observed in state j being in state i by appying the
                   3259:      model to the ncovmodel covariates (including constant and age).
                   3260:      lnpijopii=ln(pij/pii)= aij+bij*age+cij*v1+dij*v2+... = sum_nc=1^ncovmodel xij(nc)*cov[nc]
                   3261:      and, according on how parameters are entered, the position of the coefficient xij(nc) of the
                   3262:      ncth covariate in the global vector x is given by the formula:
                   3263:      j<i nc+((i-1)*(nlstate+ndeath-1)+j-1)*ncovmodel
                   3264:      j>=i nc + ((i-1)*(nlstate+ndeath-1)+(j-2))*ncovmodel
                   3265:      Computes ln(pij/pii) (lnpijopii), deduces pij/pii by exponentiation,
                   3266:      sums on j different of i to get 1-pii/pii, deduces pii, and then all pij.
                   3267:      Outputs ps[i][j] the probability to be observed in j being in j according to
                   3268:      the values of the covariates cov[nc] and corresponding parameter values x[nc+shiftij]
                   3269:   */
                   3270:   double s1, lnpijopii;
                   3271:   /*double t34;*/
                   3272:   int i,j, nc, ii, jj;
                   3273: 
1.234     brouard  3274:   for(i=1; i<= nlstate; i++){
                   3275:     for(j=1; j<i;j++){
                   3276:       for (nc=1, lnpijopii=0.;nc <=ncovmodel; nc++){
                   3277:        /*lnpijopii += param[i][j][nc]*cov[nc];*/
                   3278:        lnpijopii += x[nc+((i-1)*(nlstate+ndeath-1)+j-1)*ncovmodel]*cov[nc];
                   3279:        /*       printf("Int j<i s1=%.17e, lnpijopii=%.17e\n",s1,lnpijopii); */
                   3280:       }
                   3281:       ps[i][j]=lnpijopii; /* In fact ln(pij/pii) */
                   3282:       /*       printf("s1=%.17e, lnpijopii=%.17e\n",s1,lnpijopii); */
                   3283:     }
                   3284:     for(j=i+1; j<=nlstate+ndeath;j++){
                   3285:       for (nc=1, lnpijopii=0.;nc <=ncovmodel; nc++){
                   3286:        /*lnpijopii += x[(i-1)*nlstate*ncovmodel+(j-2)*ncovmodel+nc+(i-1)*(ndeath-1)*ncovmodel]*cov[nc];*/
                   3287:        lnpijopii += x[nc + ((i-1)*(nlstate+ndeath-1)+(j-2))*ncovmodel]*cov[nc];
                   3288:        /*        printf("Int j>i s1=%.17e, lnpijopii=%.17e %lx %lx\n",s1,lnpijopii,s1,lnpijopii); */
                   3289:       }
                   3290:       ps[i][j]=lnpijopii; /* In fact ln(pij/pii) */
                   3291:     }
                   3292:   }
                   3293:   
                   3294:   for(i=1; i<= nlstate; i++){
                   3295:     s1=0;
                   3296:     for(j=1; j<i; j++){
                   3297:       s1+=exp(ps[i][j]); /* In fact sums pij/pii */
                   3298:       /*printf("debug1 %d %d ps=%lf exp(ps)=%lf s1+=%lf\n",i,j,ps[i][j],exp(ps[i][j]),s1); */
                   3299:     }
                   3300:     for(j=i+1; j<=nlstate+ndeath; j++){
                   3301:       s1+=exp(ps[i][j]); /* In fact sums pij/pii */
                   3302:       /*printf("debug2 %d %d ps=%lf exp(ps)=%lf s1+=%lf\n",i,j,ps[i][j],exp(ps[i][j]),s1); */
                   3303:     }
                   3304:     /* s1= sum_{j<>i} pij/pii=(1-pii)/pii and thus pii is known from s1 */
                   3305:     ps[i][i]=1./(s1+1.);
                   3306:     /* Computing other pijs */
                   3307:     for(j=1; j<i; j++)
                   3308:       ps[i][j]= exp(ps[i][j])*ps[i][i];
                   3309:     for(j=i+1; j<=nlstate+ndeath; j++)
                   3310:       ps[i][j]= exp(ps[i][j])*ps[i][i];
                   3311:     /* ps[i][nlstate+1]=1.-s1- ps[i][i];*/ /* Sum should be 1 */
                   3312:   } /* end i */
                   3313:   
                   3314:   for(ii=nlstate+1; ii<= nlstate+ndeath; ii++){
                   3315:     for(jj=1; jj<= nlstate+ndeath; jj++){
                   3316:       ps[ii][jj]=0;
                   3317:       ps[ii][ii]=1;
                   3318:     }
                   3319:   }
1.296     brouard  3320:   /* Added for prevbcast */ /* Transposed matrix too */
1.234     brouard  3321:   for(jj=1; jj<= nlstate+ndeath; jj++){
                   3322:     s1=0.;
                   3323:     for(ii=1; ii<= nlstate+ndeath; ii++){
                   3324:       s1+=ps[ii][jj];
                   3325:     }
                   3326:     for(ii=1; ii<= nlstate; ii++){
                   3327:       ps[ii][jj]=ps[ii][jj]/s1;
                   3328:     }
                   3329:   }
                   3330:   /* Transposition */
                   3331:   for(jj=1; jj<= nlstate+ndeath; jj++){
                   3332:     for(ii=jj; ii<= nlstate+ndeath; ii++){
                   3333:       s1=ps[ii][jj];
                   3334:       ps[ii][jj]=ps[jj][ii];
                   3335:       ps[jj][ii]=s1;
                   3336:     }
                   3337:   }
                   3338:   /* for(ii=1; ii<= nlstate+ndeath; ii++){ */
                   3339:   /*   for(jj=1; jj<= nlstate+ndeath; jj++){ */
                   3340:   /*   printf(" pmij  ps[%d][%d]=%lf ",ii,jj,ps[ii][jj]); */
                   3341:   /*   } */
                   3342:   /*   printf("\n "); */
                   3343:   /* } */
                   3344:   /* printf("\n ");printf("%lf ",cov[2]);*/
                   3345:   /*
                   3346:     for(i=1; i<= npar; i++) printf("%f ",x[i]);
                   3347:     goto end;*/
                   3348:   return ps;
1.217     brouard  3349: }
                   3350: 
                   3351: 
1.126     brouard  3352: /**************** Product of 2 matrices ******************/
                   3353: 
1.145     brouard  3354: double **matprod2(double **out, double **in,int nrl, int nrh, int ncl, int nch, int ncolol, int ncoloh, double **b)
1.126     brouard  3355: {
                   3356:   /* Computes the matrix product of in(1,nrh-nrl+1)(1,nch-ncl+1) times
                   3357:      b(1,nch-ncl+1)(1,ncoloh-ncolol+1) into out(...) */
                   3358:   /* in, b, out are matrice of pointers which should have been initialized 
                   3359:      before: only the contents of out is modified. The function returns
                   3360:      a pointer to pointers identical to out */
1.145     brouard  3361:   int i, j, k;
1.126     brouard  3362:   for(i=nrl; i<= nrh; i++)
1.145     brouard  3363:     for(k=ncolol; k<=ncoloh; k++){
                   3364:       out[i][k]=0.;
                   3365:       for(j=ncl; j<=nch; j++)
                   3366:        out[i][k] +=in[i][j]*b[j][k];
                   3367:     }
1.126     brouard  3368:   return out;
                   3369: }
                   3370: 
                   3371: 
                   3372: /************* Higher Matrix Product ***************/
                   3373: 
1.235     brouard  3374: 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  3375: {
1.218     brouard  3376:   /* Computes the transition matrix starting at age 'age' and combination of covariate values corresponding to ij over 
1.126     brouard  3377:      'nhstepm*hstepm*stepm' months (i.e. until
                   3378:      age (in years)  age+nhstepm*hstepm*stepm/12) by multiplying 
                   3379:      nhstepm*hstepm matrices. 
                   3380:      Output is stored in matrix po[i][j][h] for h every 'hstepm' step 
                   3381:      (typically every 2 years instead of every month which is too big 
                   3382:      for the memory).
                   3383:      Model is determined by parameters x and covariates have to be 
                   3384:      included manually here. 
                   3385: 
                   3386:      */
                   3387: 
                   3388:   int i, j, d, h, k;
1.131     brouard  3389:   double **out, cov[NCOVMAX+1];
1.126     brouard  3390:   double **newm;
1.187     brouard  3391:   double agexact;
1.214     brouard  3392:   double agebegin, ageend;
1.126     brouard  3393: 
                   3394:   /* Hstepm could be zero and should return the unit matrix */
                   3395:   for (i=1;i<=nlstate+ndeath;i++)
                   3396:     for (j=1;j<=nlstate+ndeath;j++){
                   3397:       oldm[i][j]=(i==j ? 1.0 : 0.0);
                   3398:       po[i][j][0]=(i==j ? 1.0 : 0.0);
                   3399:     }
                   3400:   /* Even if hstepm = 1, at least one multiplication by the unit matrix */
                   3401:   for(h=1; h <=nhstepm; h++){
                   3402:     for(d=1; d <=hstepm; d++){
                   3403:       newm=savm;
                   3404:       /* Covariates have to be included here again */
                   3405:       cov[1]=1.;
1.214     brouard  3406:       agexact=age+((h-1)*hstepm + (d-1))*stepm/YEARM; /* age just before transition */
1.187     brouard  3407:       cov[2]=agexact;
1.319     brouard  3408:       if(nagesqr==1){
1.227     brouard  3409:        cov[3]= agexact*agexact;
1.319     brouard  3410:       }
1.235     brouard  3411:       for (k=1; k<=nsd;k++) { /* For single dummy covariates only */
1.319     brouard  3412: /* Here comes the value of the covariate 'ij' after renumbering k with single dummy covariates */
                   3413:        /* codtabm(ij,k)  (1 & (ij-1) >> (k-1))+1 */
                   3414: /*             V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
                   3415: /*    k        1  2   3   4     5    6    7     8    9 */
                   3416: /*Tvar[k]=     5  4   3   6     5    2    7     1    1 */
                   3417: /*    nsd         1   2                              3 */ /* Counting single dummies covar fixed or tv */
                   3418: /*TvarsD[nsd]     4   3                              1 */ /* ID of single dummy cova fixed or timevary*/
                   3419: /*TvarsDind[k]    2   3                              9 */ /* position K of single dummy cova */
1.235     brouard  3420:        cov[2+nagesqr+TvarsDind[k]]=nbcode[TvarsD[k]][codtabm(ij,k)];
                   3421:        /* 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)); */
                   3422:       }
                   3423:       for (k=1; k<=nsq;k++) { /* For single varying covariates only */
                   3424:        /* Here comes the value of quantitative after renumbering k with single quantitative covariates */
1.319     brouard  3425:        cov[2+nagesqr+TvarsQind[k]]=Tqresult[nres][k];
1.235     brouard  3426:        /* 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]); */
                   3427:       }
1.319     brouard  3428:       for (k=1; k<=cptcovage;k++){ /* For product with age V1+V1*age +V4 +age*V3 */
                   3429:        /* 1+2 Tage[1]=2 TVar[2]=1 Dummy[2]=2, Tage[2]=4 TVar[4]=3 Dummy[4]=3 quant*/
                   3430:        /* */
                   3431:        if(Dummy[Tage[k]]== 2){ /* dummy with age */
                   3432:        /* if(Dummy[Tvar[Tage[k]]]== 2){ /\* dummy with age *\/ */
1.235     brouard  3433:          cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,k)]*cov[2];
1.319     brouard  3434:        } else if(Dummy[Tage[k]]== 3){ /* quantitative with age */
                   3435:          cov[2+nagesqr+Tage[k]]=Tqresult[nres][k];
1.235     brouard  3436:        }
                   3437:        /* 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]); */
                   3438:       }
1.319     brouard  3439:       for (k=1; k<=cptcovprod;k++){ /*  For product without age */
1.235     brouard  3440:        /* 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]); */
1.319     brouard  3441:        /* cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)] * nbcode[Tvard[k][2]][codtabm(ij,k)]; */
                   3442:        if(Dummy[Tvard[k][1]==0]){
                   3443:          if(Dummy[Tvard[k][2]==0]){
                   3444:            cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)] * nbcode[Tvard[k][2]][codtabm(ij,k)];
                   3445:          }else{
                   3446:            cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)] * Tqresult[nres][k];
                   3447:          }
                   3448:        }else{
                   3449:          if(Dummy[Tvard[k][2]==0]){
                   3450:            cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][2]][codtabm(ij,k)] * Tqinvresult[nres][Tvard[k][1]];
                   3451:          }else{
                   3452:            cov[2+nagesqr+Tprod[k]]=Tqinvresult[nres][Tvard[k][1]]*  Tqinvresult[nres][Tvard[k][2]];
                   3453:          }
                   3454:        }
1.235     brouard  3455:       }
                   3456:       /* for (k=1; k<=cptcovn;k++)  */
                   3457:       /*       cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,k)]; */
                   3458:       /* for (k=1; k<=cptcovage;k++) /\* Should start at cptcovn+1 *\/ */
                   3459:       /*       cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,k)]*cov[2]; */
                   3460:       /* for (k=1; k<=cptcovprod;k++) /\* Useless because included in cptcovn *\/ */
                   3461:       /*       cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)]*nbcode[Tvard[k][2]][codtabm(ij,k)]; */
1.227     brouard  3462:       
                   3463:       
1.126     brouard  3464:       /*printf("hxi cptcov=%d cptcode=%d\n",cptcov,cptcode);*/
                   3465:       /*printf("h=%d d=%d age=%f cov=%f\n",h,d,age,cov[2]);*/
1.319     brouard  3466:       /* right multiplication of oldm by the current matrix */
1.126     brouard  3467:       out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, 
                   3468:                   pmij(pmmij,cov,ncovmodel,x,nlstate));
1.217     brouard  3469:       /* if((int)age == 70){ */
                   3470:       /*       printf(" Forward hpxij age=%d agexact=%f d=%d nhstepm=%d hstepm=%d\n", (int) age, agexact, d, nhstepm, hstepm); */
                   3471:       /*       for(i=1; i<=nlstate+ndeath; i++) { */
                   3472:       /*         printf("%d pmmij ",i); */
                   3473:       /*         for(j=1;j<=nlstate+ndeath;j++) { */
                   3474:       /*           printf("%f ",pmmij[i][j]); */
                   3475:       /*         } */
                   3476:       /*         printf(" oldm "); */
                   3477:       /*         for(j=1;j<=nlstate+ndeath;j++) { */
                   3478:       /*           printf("%f ",oldm[i][j]); */
                   3479:       /*         } */
                   3480:       /*         printf("\n"); */
                   3481:       /*       } */
                   3482:       /* } */
1.126     brouard  3483:       savm=oldm;
                   3484:       oldm=newm;
                   3485:     }
                   3486:     for(i=1; i<=nlstate+ndeath; i++)
                   3487:       for(j=1;j<=nlstate+ndeath;j++) {
1.267     brouard  3488:        po[i][j][h]=newm[i][j];
                   3489:        /*if(h==nhstepm) printf("po[%d][%d][%d]=%f ",i,j,h,po[i][j][h]);*/
1.126     brouard  3490:       }
1.128     brouard  3491:     /*printf("h=%d ",h);*/
1.126     brouard  3492:   } /* end h */
1.267     brouard  3493:   /*     printf("\n H=%d \n",h); */
1.126     brouard  3494:   return po;
                   3495: }
                   3496: 
1.217     brouard  3497: /************* Higher Back Matrix Product ***************/
1.218     brouard  3498: /* 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  3499: 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  3500: {
1.266     brouard  3501:   /* For a combination of dummy covariate ij, computes the transition matrix starting at age 'age' over
1.217     brouard  3502:      'nhstepm*hstepm*stepm' months (i.e. until
1.218     brouard  3503:      age (in years)  age+nhstepm*hstepm*stepm/12) by multiplying
                   3504:      nhstepm*hstepm matrices.
                   3505:      Output is stored in matrix po[i][j][h] for h every 'hstepm' step
                   3506:      (typically every 2 years instead of every month which is too big
1.217     brouard  3507:      for the memory).
1.218     brouard  3508:      Model is determined by parameters x and covariates have to be
1.266     brouard  3509:      included manually here. Then we use a call to bmij(x and cov)
                   3510:      The addresss of po (p3mat allocated to the dimension of nhstepm) should be stored for output
1.222     brouard  3511:   */
1.217     brouard  3512: 
                   3513:   int i, j, d, h, k;
1.266     brouard  3514:   double **out, cov[NCOVMAX+1], **bmij();
                   3515:   double **newm, ***newmm;
1.217     brouard  3516:   double agexact;
                   3517:   double agebegin, ageend;
1.222     brouard  3518:   double **oldm, **savm;
1.217     brouard  3519: 
1.266     brouard  3520:   newmm=po; /* To be saved */
                   3521:   oldm=oldms;savm=savms; /* Global pointers */
1.217     brouard  3522:   /* Hstepm could be zero and should return the unit matrix */
                   3523:   for (i=1;i<=nlstate+ndeath;i++)
                   3524:     for (j=1;j<=nlstate+ndeath;j++){
                   3525:       oldm[i][j]=(i==j ? 1.0 : 0.0);
                   3526:       po[i][j][0]=(i==j ? 1.0 : 0.0);
                   3527:     }
                   3528:   /* Even if hstepm = 1, at least one multiplication by the unit matrix */
                   3529:   for(h=1; h <=nhstepm; h++){
                   3530:     for(d=1; d <=hstepm; d++){
                   3531:       newm=savm;
                   3532:       /* Covariates have to be included here again */
                   3533:       cov[1]=1.;
1.271     brouard  3534:       agexact=age-( (h-1)*hstepm + (d)  )*stepm/YEARM; /* age just before transition, d or d-1? */
1.217     brouard  3535:       /* agexact=age+((h-1)*hstepm + (d-1))*stepm/YEARM; /\* age just before transition *\/ */
1.318     brouard  3536:         /* Debug */
                   3537:       /* printf("hBxij age=%lf, agexact=%lf\n", age, agexact); */
1.217     brouard  3538:       cov[2]=agexact;
                   3539:       if(nagesqr==1)
1.222     brouard  3540:        cov[3]= agexact*agexact;
1.266     brouard  3541:       for (k=1; k<=cptcovn;k++){
                   3542:       /*       cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,k)]; */
                   3543:       /* /\* cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,Tvar[k])]; *\/ */
                   3544:        cov[2+nagesqr+TvarsDind[k]]=nbcode[TvarsD[k]][codtabm(ij,k)];
                   3545:         /* 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)); */
                   3546:       }
1.267     brouard  3547:       for (k=1; k<=nsq;k++) { /* For single varying covariates only */
                   3548:        /* Here comes the value of quantitative after renumbering k with single quantitative covariates */
                   3549:        cov[2+nagesqr+TvarsQind[k]]=Tqresult[nres][k]; 
                   3550:        /* 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]); */
                   3551:       }
1.319     brouard  3552:       for (k=1; k<=cptcovage;k++){ /* Should start at cptcovn+1 *//* For product with age */
                   3553:        /* if(Dummy[Tvar[Tage[k]]]== 2){ /\* dummy with age error!!!*\/ */
                   3554:        if(Dummy[Tage[k]]== 2){ /* dummy with age */
1.267     brouard  3555:          cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,k)]*cov[2];
1.319     brouard  3556:        } else if(Dummy[Tage[k]]== 3){ /* quantitative with age */
1.267     brouard  3557:          cov[2+nagesqr+Tage[k]]=Tqresult[nres][k]; 
                   3558:        }
                   3559:        /* 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]); */
                   3560:       }
                   3561:       for (k=1; k<=cptcovprod;k++){ /* Useless because included in cptcovn */
1.222     brouard  3562:        cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)]*nbcode[Tvard[k][2]][codtabm(ij,k)];
1.267     brouard  3563:       }                        
1.217     brouard  3564:       /*printf("hxi cptcov=%d cptcode=%d\n",cptcov,cptcode);*/
                   3565:       /*printf("h=%d d=%d age=%f cov=%f\n",h,d,age,cov[2]);*/
1.267     brouard  3566: 
1.218     brouard  3567:       /* Careful transposed matrix */
1.266     brouard  3568:       /* age is in cov[2], prevacurrent at beginning of transition. */
1.218     brouard  3569:       /* out=matprod2(newm, bmij(pmmij,cov,ncovmodel,x,nlstate,prevacurrent, dnewm, doldm, dsavm,ij),\ */
1.222     brouard  3570:       /*                                                1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm); */
1.218     brouard  3571:       out=matprod2(newm, bmij(pmmij,cov,ncovmodel,x,nlstate,prevacurrent,ij),\
1.222     brouard  3572:                   1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm);
1.217     brouard  3573:       /* if((int)age == 70){ */
                   3574:       /*       printf(" Backward hbxij age=%d agexact=%f d=%d nhstepm=%d hstepm=%d\n", (int) age, agexact, d, nhstepm, hstepm); */
                   3575:       /*       for(i=1; i<=nlstate+ndeath; i++) { */
                   3576:       /*         printf("%d pmmij ",i); */
                   3577:       /*         for(j=1;j<=nlstate+ndeath;j++) { */
                   3578:       /*           printf("%f ",pmmij[i][j]); */
                   3579:       /*         } */
                   3580:       /*         printf(" oldm "); */
                   3581:       /*         for(j=1;j<=nlstate+ndeath;j++) { */
                   3582:       /*           printf("%f ",oldm[i][j]); */
                   3583:       /*         } */
                   3584:       /*         printf("\n"); */
                   3585:       /*       } */
                   3586:       /* } */
                   3587:       savm=oldm;
                   3588:       oldm=newm;
                   3589:     }
                   3590:     for(i=1; i<=nlstate+ndeath; i++)
                   3591:       for(j=1;j<=nlstate+ndeath;j++) {
1.222     brouard  3592:        po[i][j][h]=newm[i][j];
1.268     brouard  3593:        /* if(h==nhstepm) */
                   3594:        /*   printf("po[%d][%d][%d]=%f ",i,j,h,po[i][j][h]); */
1.217     brouard  3595:       }
1.268     brouard  3596:     /* printf("h=%d %.1f ",h, agexact); */
1.217     brouard  3597:   } /* end h */
1.268     brouard  3598:   /* printf("\n H=%d nhs=%d \n",h, nhstepm); */
1.217     brouard  3599:   return po;
                   3600: }
                   3601: 
                   3602: 
1.162     brouard  3603: #ifdef NLOPT
                   3604:   double  myfunc(unsigned n, const double *p1, double *grad, void *pd){
                   3605:   double fret;
                   3606:   double *xt;
                   3607:   int j;
                   3608:   myfunc_data *d2 = (myfunc_data *) pd;
                   3609: /* xt = (p1-1); */
                   3610:   xt=vector(1,n); 
                   3611:   for (j=1;j<=n;j++)   xt[j]=p1[j-1]; /* xt[1]=p1[0] */
                   3612: 
                   3613:   fret=(d2->function)(xt); /*  p xt[1]@8 is fine */
                   3614:   /* fret=(*func)(xt); /\*  p xt[1]@8 is fine *\/ */
                   3615:   printf("Function = %.12lf ",fret);
                   3616:   for (j=1;j<=n;j++) printf(" %d %.8lf", j, xt[j]); 
                   3617:   printf("\n");
                   3618:  free_vector(xt,1,n);
                   3619:   return fret;
                   3620: }
                   3621: #endif
1.126     brouard  3622: 
                   3623: /*************** log-likelihood *************/
                   3624: double func( double *x)
                   3625: {
1.226     brouard  3626:   int i, ii, j, k, mi, d, kk;
                   3627:   int ioffset=0;
                   3628:   double l, ll[NLSTATEMAX+1], cov[NCOVMAX+1];
                   3629:   double **out;
                   3630:   double lli; /* Individual log likelihood */
                   3631:   int s1, s2;
1.228     brouard  3632:   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  3633:   double bbh, survp;
                   3634:   long ipmx;
                   3635:   double agexact;
                   3636:   /*extern weight */
                   3637:   /* We are differentiating ll according to initial status */
                   3638:   /*  for (i=1;i<=npar;i++) printf("%f ", x[i]);*/
                   3639:   /*for(i=1;i<imx;i++) 
                   3640:     printf(" %d\n",s[4][i]);
                   3641:   */
1.162     brouard  3642: 
1.226     brouard  3643:   ++countcallfunc;
1.162     brouard  3644: 
1.226     brouard  3645:   cov[1]=1.;
1.126     brouard  3646: 
1.226     brouard  3647:   for(k=1; k<=nlstate; k++) ll[k]=0.;
1.224     brouard  3648:   ioffset=0;
1.226     brouard  3649:   if(mle==1){
                   3650:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
                   3651:       /* Computes the values of the ncovmodel covariates of the model
                   3652:         depending if the covariates are fixed or varying (age dependent) and stores them in cov[]
                   3653:         Then computes with function pmij which return a matrix p[i][j] giving the elementary probability
                   3654:         to be observed in j being in i according to the model.
                   3655:       */
1.243     brouard  3656:       ioffset=2+nagesqr ;
1.233     brouard  3657:    /* Fixed */
1.319     brouard  3658:       for (k=1; k<=ncovf;k++){ /* For each fixed covariate dummu or quant or prod */
                   3659:        /* # V1=sex, V2=raedyrs Quant Fixed, State=livarnb4..livarnb11, V3=iadl4..iald11, V4=adlw4..adlw11, V5=r4bmi..r11bmi */
                   3660:         /*             V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
                   3661:        /*  TvarF[1]=Tvar[6]=2,  TvarF[2]=Tvar[7]=7, TvarF[3]=Tvar[9]=1  ID of fixed covariates or product V2, V1*V2, V1 */
1.320     brouard  3662:         /* TvarFind;  TvarFind[1]=6,  TvarFind[2]=7, TvarFind[3]=9 *//* Inverse V2(6) is first fixed (single or prod)  */
1.319     brouard  3663:        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 (TvarFind[1]=6)*/
                   3664:        /* V1*V2 (7)  TvarFind[2]=7, TvarFind[3]=9 */
1.234     brouard  3665:       }
1.226     brouard  3666:       /* In model V2+V1*V4+age*V3+V3*V2 Tvar[1] is V2, Tvar[2=V1*V4] 
1.319     brouard  3667:         is 5, Tvar[3=age*V3] should not be computed because of age Tvar[4=V3*V2]=6 
1.226     brouard  3668:         has been calculated etc */
                   3669:       /* For an individual i, wav[i] gives the number of effective waves */
                   3670:       /* We compute the contribution to Likelihood of each effective transition
                   3671:         mw[mi][i] is real wave of the mi th effectve wave */
                   3672:       /* Then statuses are computed at each begin and end of an effective wave s1=s[ mw[mi][i] ][i];
                   3673:         s2=s[mw[mi+1][i]][i];
                   3674:         And the iv th varying covariate is the cotvar[mw[mi+1][i]][iv][i]
                   3675:         But if the variable is not in the model TTvar[iv] is the real variable effective in the model:
                   3676:         meaning that decodemodel should be used cotvar[mw[mi+1][i]][TTvar[iv]][i]
                   3677:       */
                   3678:       for(mi=1; mi<= wav[i]-1; mi++){
1.319     brouard  3679:        for(k=1; k <= ncovv ; k++){ /* Varying  covariates in the model (single and product but no age )"V5+V4+V3+V4*V3+V5*age+V1*age+V1" +TvarVind 1,2,3,4(V4*V3)  Tvar[1]@7{5, 4, 3, 6, 5, 1, 1 ; 6 because the created covar is after V5 and is 6, minus 1+1, 3,2,1,4 positions in cotvar*/
                   3680:          /* cov[ioffset+TvarVind[k]]=cotvar[mw[mi][i]][Tvar[TvarVind[k]]][i]; but where is the crossproduct? */
1.242     brouard  3681:          cov[ioffset+TvarVind[k]]=cotvar[mw[mi][i]][Tvar[TvarVind[k]]-ncovcol-nqv][i];
1.234     brouard  3682:        }
                   3683:        for (ii=1;ii<=nlstate+ndeath;ii++)
                   3684:          for (j=1;j<=nlstate+ndeath;j++){
                   3685:            oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   3686:            savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   3687:          }
                   3688:        for(d=0; d<dh[mi][i]; d++){
                   3689:          newm=savm;
                   3690:          agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
                   3691:          cov[2]=agexact;
                   3692:          if(nagesqr==1)
                   3693:            cov[3]= agexact*agexact;  /* Should be changed here */
                   3694:          for (kk=1; kk<=cptcovage;kk++) {
1.318     brouard  3695:            if(!FixedV[Tvar[Tage[kk]]])
                   3696:              cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact; /* Tage[kk] gives the data-covariate associated with age */
                   3697:            else
                   3698:              cov[Tage[kk]+2+nagesqr]=cotvar[mw[mi][i]][Tvar[Tage[kk]]-ncovcol-nqv][i]*agexact;
1.234     brouard  3699:          }
                   3700:          out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   3701:                       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   3702:          savm=oldm;
                   3703:          oldm=newm;
                   3704:        } /* end mult */
                   3705:        
                   3706:        /*lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]);*/ /* Original formula */
                   3707:        /* But now since version 0.9 we anticipate for bias at large stepm.
                   3708:         * If stepm is larger than one month (smallest stepm) and if the exact delay 
                   3709:         * (in months) between two waves is not a multiple of stepm, we rounded to 
                   3710:         * the nearest (and in case of equal distance, to the lowest) interval but now
                   3711:         * we keep into memory the bias bh[mi][i] and also the previous matrix product
                   3712:         * (i.e to dh[mi][i]-1) saved in 'savm'. Then we inter(extra)polate the
                   3713:         * probability in order to take into account the bias as a fraction of the way
1.231     brouard  3714:                                 * from savm to out if bh is negative or even beyond if bh is positive. bh varies
                   3715:                                 * -stepm/2 to stepm/2 .
                   3716:                                 * For stepm=1 the results are the same as for previous versions of Imach.
                   3717:                                 * For stepm > 1 the results are less biased than in previous versions. 
                   3718:                                 */
1.234     brouard  3719:        s1=s[mw[mi][i]][i];
                   3720:        s2=s[mw[mi+1][i]][i];
                   3721:        bbh=(double)bh[mi][i]/(double)stepm; 
                   3722:        /* bias bh is positive if real duration
                   3723:         * is higher than the multiple of stepm and negative otherwise.
                   3724:         */
                   3725:        /* lli= (savm[s1][s2]>1.e-8 ?(1.+bbh)*log(out[s1][s2])- bbh*log(savm[s1][s2]):log((1.+bbh)*out[s1][s2]));*/
                   3726:        if( s2 > nlstate){ 
                   3727:          /* i.e. if s2 is a death state and if the date of death is known 
                   3728:             then the contribution to the likelihood is the probability to 
                   3729:             die between last step unit time and current  step unit time, 
                   3730:             which is also equal to probability to die before dh 
                   3731:             minus probability to die before dh-stepm . 
                   3732:             In version up to 0.92 likelihood was computed
                   3733:             as if date of death was unknown. Death was treated as any other
                   3734:             health state: the date of the interview describes the actual state
                   3735:             and not the date of a change in health state. The former idea was
                   3736:             to consider that at each interview the state was recorded
                   3737:             (healthy, disable or death) and IMaCh was corrected; but when we
                   3738:             introduced the exact date of death then we should have modified
                   3739:             the contribution of an exact death to the likelihood. This new
                   3740:             contribution is smaller and very dependent of the step unit
                   3741:             stepm. It is no more the probability to die between last interview
                   3742:             and month of death but the probability to survive from last
                   3743:             interview up to one month before death multiplied by the
                   3744:             probability to die within a month. Thanks to Chris
                   3745:             Jackson for correcting this bug.  Former versions increased
                   3746:             mortality artificially. The bad side is that we add another loop
                   3747:             which slows down the processing. The difference can be up to 10%
                   3748:             lower mortality.
                   3749:          */
                   3750:          /* If, at the beginning of the maximization mostly, the
                   3751:             cumulative probability or probability to be dead is
                   3752:             constant (ie = 1) over time d, the difference is equal to
                   3753:             0.  out[s1][3] = savm[s1][3]: probability, being at state
                   3754:             s1 at precedent wave, to be dead a month before current
                   3755:             wave is equal to probability, being at state s1 at
                   3756:             precedent wave, to be dead at mont of the current
                   3757:             wave. Then the observed probability (that this person died)
                   3758:             is null according to current estimated parameter. In fact,
                   3759:             it should be very low but not zero otherwise the log go to
                   3760:             infinity.
                   3761:          */
1.183     brouard  3762: /* #ifdef INFINITYORIGINAL */
                   3763: /*         lli=log(out[s1][s2] - savm[s1][s2]); */
                   3764: /* #else */
                   3765: /*       if ((out[s1][s2] - savm[s1][s2]) < mytinydouble)  */
                   3766: /*         lli=log(mytinydouble); */
                   3767: /*       else */
                   3768: /*         lli=log(out[s1][s2] - savm[s1][s2]); */
                   3769: /* #endif */
1.226     brouard  3770:          lli=log(out[s1][s2] - savm[s1][s2]);
1.216     brouard  3771:          
1.226     brouard  3772:        } else if  ( s2==-1 ) { /* alive */
                   3773:          for (j=1,survp=0. ; j<=nlstate; j++) 
                   3774:            survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
                   3775:          /*survp += out[s1][j]; */
                   3776:          lli= log(survp);
                   3777:        }
                   3778:        else if  (s2==-4) { 
                   3779:          for (j=3,survp=0. ; j<=nlstate; j++)  
                   3780:            survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
                   3781:          lli= log(survp); 
                   3782:        } 
                   3783:        else if  (s2==-5) { 
                   3784:          for (j=1,survp=0. ; j<=2; j++)  
                   3785:            survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
                   3786:          lli= log(survp); 
                   3787:        } 
                   3788:        else{
                   3789:          lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */
                   3790:          /*  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 */
                   3791:        } 
                   3792:        /*lli=(1.+bbh)*log(out[s1][s2])- bbh*log(savm[s1][s2]);*/
                   3793:        /*if(lli ==000.0)*/
                   3794:        /*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); */
                   3795:        ipmx +=1;
                   3796:        sw += weight[i];
                   3797:        ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
                   3798:        /* if (lli < log(mytinydouble)){ */
                   3799:        /*   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); */
                   3800:        /*   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]); */
                   3801:        /* } */
                   3802:       } /* end of wave */
                   3803:     } /* end of individual */
                   3804:   }  else if(mle==2){
                   3805:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
1.319     brouard  3806:       ioffset=2+nagesqr ;
                   3807:       for (k=1; k<=ncovf;k++)
                   3808:        cov[ioffset+TvarFind[k]]=covar[Tvar[TvarFind[k]]][i];
1.226     brouard  3809:       for(mi=1; mi<= wav[i]-1; mi++){
1.319     brouard  3810:        for(k=1; k <= ncovv ; k++){
                   3811:          cov[ioffset+TvarVind[k]]=cotvar[mw[mi][i]][Tvar[TvarVind[k]]-ncovcol-nqv][i];
                   3812:        }
1.226     brouard  3813:        for (ii=1;ii<=nlstate+ndeath;ii++)
                   3814:          for (j=1;j<=nlstate+ndeath;j++){
                   3815:            oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   3816:            savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   3817:          }
                   3818:        for(d=0; d<=dh[mi][i]; d++){
                   3819:          newm=savm;
                   3820:          agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
                   3821:          cov[2]=agexact;
                   3822:          if(nagesqr==1)
                   3823:            cov[3]= agexact*agexact;
                   3824:          for (kk=1; kk<=cptcovage;kk++) {
                   3825:            cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact;
                   3826:          }
                   3827:          out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   3828:                       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   3829:          savm=oldm;
                   3830:          oldm=newm;
                   3831:        } /* end mult */
                   3832:       
                   3833:        s1=s[mw[mi][i]][i];
                   3834:        s2=s[mw[mi+1][i]][i];
                   3835:        bbh=(double)bh[mi][i]/(double)stepm; 
                   3836:        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 */
                   3837:        ipmx +=1;
                   3838:        sw += weight[i];
                   3839:        ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
                   3840:       } /* end of wave */
                   3841:     } /* end of individual */
                   3842:   }  else if(mle==3){  /* exponential inter-extrapolation */
                   3843:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
                   3844:       for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i];
                   3845:       for(mi=1; mi<= wav[i]-1; mi++){
                   3846:        for (ii=1;ii<=nlstate+ndeath;ii++)
                   3847:          for (j=1;j<=nlstate+ndeath;j++){
                   3848:            oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   3849:            savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   3850:          }
                   3851:        for(d=0; d<dh[mi][i]; d++){
                   3852:          newm=savm;
                   3853:          agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
                   3854:          cov[2]=agexact;
                   3855:          if(nagesqr==1)
                   3856:            cov[3]= agexact*agexact;
                   3857:          for (kk=1; kk<=cptcovage;kk++) {
                   3858:            cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact;
                   3859:          }
                   3860:          out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   3861:                       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   3862:          savm=oldm;
                   3863:          oldm=newm;
                   3864:        } /* end mult */
                   3865:       
                   3866:        s1=s[mw[mi][i]][i];
                   3867:        s2=s[mw[mi+1][i]][i];
                   3868:        bbh=(double)bh[mi][i]/(double)stepm; 
                   3869:        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 */
                   3870:        ipmx +=1;
                   3871:        sw += weight[i];
                   3872:        ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
                   3873:       } /* end of wave */
                   3874:     } /* end of individual */
                   3875:   }else if (mle==4){  /* ml=4 no inter-extrapolation */
                   3876:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
                   3877:       for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i];
                   3878:       for(mi=1; mi<= wav[i]-1; mi++){
                   3879:        for (ii=1;ii<=nlstate+ndeath;ii++)
                   3880:          for (j=1;j<=nlstate+ndeath;j++){
                   3881:            oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   3882:            savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   3883:          }
                   3884:        for(d=0; d<dh[mi][i]; d++){
                   3885:          newm=savm;
                   3886:          agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
                   3887:          cov[2]=agexact;
                   3888:          if(nagesqr==1)
                   3889:            cov[3]= agexact*agexact;
                   3890:          for (kk=1; kk<=cptcovage;kk++) {
                   3891:            cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact;
                   3892:          }
1.126     brouard  3893:        
1.226     brouard  3894:          out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   3895:                       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   3896:          savm=oldm;
                   3897:          oldm=newm;
                   3898:        } /* end mult */
                   3899:       
                   3900:        s1=s[mw[mi][i]][i];
                   3901:        s2=s[mw[mi+1][i]][i];
                   3902:        if( s2 > nlstate){ 
                   3903:          lli=log(out[s1][s2] - savm[s1][s2]);
                   3904:        } else if  ( s2==-1 ) { /* alive */
                   3905:          for (j=1,survp=0. ; j<=nlstate; j++) 
                   3906:            survp += out[s1][j];
                   3907:          lli= log(survp);
                   3908:        }else{
                   3909:          lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]); /* Original formula */
                   3910:        }
                   3911:        ipmx +=1;
                   3912:        sw += weight[i];
                   3913:        ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
1.126     brouard  3914: /*     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  3915:       } /* end of wave */
                   3916:     } /* end of individual */
                   3917:   }else{  /* ml=5 no inter-extrapolation no jackson =0.8a */
                   3918:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
                   3919:       for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i];
                   3920:       for(mi=1; mi<= wav[i]-1; mi++){
                   3921:        for (ii=1;ii<=nlstate+ndeath;ii++)
                   3922:          for (j=1;j<=nlstate+ndeath;j++){
                   3923:            oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   3924:            savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   3925:          }
                   3926:        for(d=0; d<dh[mi][i]; d++){
                   3927:          newm=savm;
                   3928:          agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
                   3929:          cov[2]=agexact;
                   3930:          if(nagesqr==1)
                   3931:            cov[3]= agexact*agexact;
                   3932:          for (kk=1; kk<=cptcovage;kk++) {
                   3933:            cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact;
                   3934:          }
1.126     brouard  3935:        
1.226     brouard  3936:          out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   3937:                       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   3938:          savm=oldm;
                   3939:          oldm=newm;
                   3940:        } /* end mult */
                   3941:       
                   3942:        s1=s[mw[mi][i]][i];
                   3943:        s2=s[mw[mi+1][i]][i];
                   3944:        lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]); /* Original formula */
                   3945:        ipmx +=1;
                   3946:        sw += weight[i];
                   3947:        ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
                   3948:        /*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]);*/
                   3949:       } /* end of wave */
                   3950:     } /* end of individual */
                   3951:   } /* End of if */
                   3952:   for(k=1,l=0.; k<=nlstate; k++) l += ll[k];
                   3953:   /* printf("l1=%f l2=%f ",ll[1],ll[2]); */
                   3954:   l= l*ipmx/sw; /* To get the same order of magnitude as if weight=1 for every body */
                   3955:   return -l;
1.126     brouard  3956: }
                   3957: 
                   3958: /*************** log-likelihood *************/
                   3959: double funcone( double *x)
                   3960: {
1.228     brouard  3961:   /* Same as func but slower because of a lot of printf and if */
1.126     brouard  3962:   int i, ii, j, k, mi, d, kk;
1.228     brouard  3963:   int ioffset=0;
1.131     brouard  3964:   double l, ll[NLSTATEMAX+1], cov[NCOVMAX+1];
1.126     brouard  3965:   double **out;
                   3966:   double lli; /* Individual log likelihood */
                   3967:   double llt;
                   3968:   int s1, s2;
1.228     brouard  3969:   int iv=0, iqv=0, itv=0, iqtv=0 ; /* Index of varying covariate, fixed quantitative cov, time varying covariate, quantitative time varying covariate */
                   3970: 
1.126     brouard  3971:   double bbh, survp;
1.187     brouard  3972:   double agexact;
1.214     brouard  3973:   double agebegin, ageend;
1.126     brouard  3974:   /*extern weight */
                   3975:   /* We are differentiating ll according to initial status */
                   3976:   /*  for (i=1;i<=npar;i++) printf("%f ", x[i]);*/
                   3977:   /*for(i=1;i<imx;i++) 
                   3978:     printf(" %d\n",s[4][i]);
                   3979:   */
                   3980:   cov[1]=1.;
                   3981: 
                   3982:   for(k=1; k<=nlstate; k++) ll[k]=0.;
1.224     brouard  3983:   ioffset=0;
                   3984:   for (i=1,ipmx=0, sw=0.; i<=imx; i++){
1.243     brouard  3985:     /* ioffset=2+nagesqr+cptcovage; */
                   3986:     ioffset=2+nagesqr;
1.232     brouard  3987:     /* Fixed */
1.224     brouard  3988:     /* for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i]; */
1.232     brouard  3989:     /* for (k=1; k<=ncoveff;k++){ /\* Simple and product fixed Dummy covariates without age* products *\/ */
1.311     brouard  3990:     for (k=1; k<=ncovf;k++){ /* Simple and product fixed covariates without age* products *//* Missing values are set to -1 but should be dropped */
1.232     brouard  3991:       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)*/
                   3992: /*    cov[ioffset+TvarFind[1]]=covar[Tvar[TvarFind[1]]][i];  */
                   3993: /*    cov[2+6]=covar[Tvar[6]][i];  */
                   3994: /*    cov[2+6]=covar[2][i]; V2  */
                   3995: /*    cov[TvarFind[2]]=covar[Tvar[TvarFind[2]]][i];  */
                   3996: /*    cov[2+7]=covar[Tvar[7]][i];  */
                   3997: /*    cov[2+7]=covar[7][i]; V7=V1*V2  */
                   3998: /*    cov[TvarFind[3]]=covar[Tvar[TvarFind[3]]][i];  */
                   3999: /*    cov[2+9]=covar[Tvar[9]][i];  */
                   4000: /*    cov[2+9]=covar[1][i]; V1  */
1.225     brouard  4001:     }
1.232     brouard  4002:     /* for (k=1; k<=nqfveff;k++){ /\* Simple and product fixed Quantitative covariates without age* products *\/ */
                   4003:     /*   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?)*\/ */
                   4004:     /* } */
1.231     brouard  4005:     /* for(iqv=1; iqv <= nqfveff; iqv++){ /\* Quantitative fixed covariates *\/ */
                   4006:     /*   cov[++ioffset]=coqvar[Tvar[iqv]][i]; /\* Only V2 k=6 and V1*V2 7 *\/ */
                   4007:     /* } */
1.225     brouard  4008:     
1.233     brouard  4009: 
                   4010:     for(mi=1; mi<= wav[i]-1; mi++){  /* Varying with waves */
1.232     brouard  4011:     /* Wave varying (but not age varying) */
                   4012:       for(k=1; k <= ncovv ; k++){ /* Varying  covariates (single and product but no age )*/
1.242     brouard  4013:        /* cov[ioffset+TvarVind[k]]=cotvar[mw[mi][i]][Tvar[TvarVind[k]]][i]; */
                   4014:        cov[ioffset+TvarVind[k]]=cotvar[mw[mi][i]][Tvar[TvarVind[k]]-ncovcol-nqv][i];
                   4015:       }
1.232     brouard  4016:       /* for(itv=1; itv <= ntveff; itv++){ /\* Varying dummy covariates (single??)*\/ */
1.242     brouard  4017:       /* iv= Tvar[Tmodelind[ioffset-2-nagesqr-cptcovage+itv]]-ncovcol-nqv; /\* Counting the # varying covariate from 1 to ntveff *\/ */
                   4018:       /* cov[ioffset+iv]=cotvar[mw[mi][i]][iv][i]; */
                   4019:       /* k=ioffset-2-nagesqr-cptcovage+itv; /\* position in simple model *\/ */
                   4020:       /* cov[ioffset+itv]=cotvar[mw[mi][i]][TmodelInvind[itv]][i]; */
                   4021:       /* 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  4022:       /* for(iqtv=1; iqtv <= nqtveff; iqtv++){ /\* Varying quantitatives covariates *\/ */
1.242     brouard  4023:       /*       iv=TmodelInvQind[iqtv]; /\* Counting the # varying covariate from 1 to ntveff *\/ */
                   4024:       /*       /\* 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]); *\/ */
                   4025:       /*       cov[ioffset+ntveff+iqtv]=cotqvar[mw[mi][i]][TmodelInvQind[iqtv]][i]; */
1.232     brouard  4026:       /* } */
1.126     brouard  4027:       for (ii=1;ii<=nlstate+ndeath;ii++)
1.242     brouard  4028:        for (j=1;j<=nlstate+ndeath;j++){
                   4029:          oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   4030:          savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   4031:        }
1.214     brouard  4032:       
                   4033:       agebegin=agev[mw[mi][i]][i]; /* Age at beginning of effective wave */
                   4034:       ageend=agev[mw[mi][i]][i] + (dh[mi][i])*stepm/YEARM; /* Age at end of effective wave and at the end of transition */
                   4035:       for(d=0; d<dh[mi][i]; d++){  /* Delay between two effective waves */
1.247     brouard  4036:       /* for(d=0; d<=0; d++){  /\* Delay between two effective waves Only one matrix to speed up*\/ */
1.242     brouard  4037:        /*dh[m][i] or dh[mw[mi][i]][i] is the delay between two effective waves m=mw[mi][i]
                   4038:          and mw[mi+1][i]. dh depends on stepm.*/
                   4039:        newm=savm;
1.247     brouard  4040:        agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;  /* Here d is needed */
1.242     brouard  4041:        cov[2]=agexact;
                   4042:        if(nagesqr==1)
                   4043:          cov[3]= agexact*agexact;
                   4044:        for (kk=1; kk<=cptcovage;kk++) {
                   4045:          if(!FixedV[Tvar[Tage[kk]]])
                   4046:            cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact;
                   4047:          else
                   4048:            cov[Tage[kk]+2+nagesqr]=cotvar[mw[mi][i]][Tvar[Tage[kk]]-ncovcol-nqv][i]*agexact;
                   4049:        }
                   4050:        /* printf("i=%d,mi=%d,d=%d,mw[mi][i]=%d\n",i, mi,d,mw[mi][i]); */
                   4051:        /* savm=pmij(pmmij,cov,ncovmodel,x,nlstate); */
                   4052:        out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   4053:                     1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   4054:        /* out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath, */
                   4055:        /*           1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate)); */
                   4056:        savm=oldm;
                   4057:        oldm=newm;
1.126     brouard  4058:       } /* end mult */
                   4059:       
                   4060:       s1=s[mw[mi][i]][i];
                   4061:       s2=s[mw[mi+1][i]][i];
1.217     brouard  4062:       /* if(s2==-1){ */
1.268     brouard  4063:       /*       printf(" ERROR s1=%d, s2=%d i=%d \n", s1, s2, i); */
1.217     brouard  4064:       /*       /\* exit(1); *\/ */
                   4065:       /* } */
1.126     brouard  4066:       bbh=(double)bh[mi][i]/(double)stepm; 
                   4067:       /* bias is positive if real duration
                   4068:        * is higher than the multiple of stepm and negative otherwise.
                   4069:        */
                   4070:       if( s2 > nlstate && (mle <5) ){  /* Jackson */
1.242     brouard  4071:        lli=log(out[s1][s2] - savm[s1][s2]);
1.216     brouard  4072:       } else if  ( s2==-1 ) { /* alive */
1.242     brouard  4073:        for (j=1,survp=0. ; j<=nlstate; j++) 
                   4074:          survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
                   4075:        lli= log(survp);
1.126     brouard  4076:       }else if (mle==1){
1.242     brouard  4077:        lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */
1.126     brouard  4078:       } else if(mle==2){
1.242     brouard  4079:        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  4080:       } else if(mle==3){  /* exponential inter-extrapolation */
1.242     brouard  4081:        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  4082:       } else if (mle==4){  /* mle=4 no inter-extrapolation */
1.242     brouard  4083:        lli=log(out[s1][s2]); /* Original formula */
1.136     brouard  4084:       } else{  /* mle=0 back to 1 */
1.242     brouard  4085:        lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */
                   4086:        /*lli=log(out[s1][s2]); */ /* Original formula */
1.126     brouard  4087:       } /* End of if */
                   4088:       ipmx +=1;
                   4089:       sw += weight[i];
                   4090:       ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
1.132     brouard  4091:       /*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  4092:       if(globpr){
1.246     brouard  4093:        fprintf(ficresilk,"%09ld %6.1f %6.1f %6d %2d %2d %2d %2d %3d %15.6f %8.4f %8.3f\
1.126     brouard  4094:  %11.6f %11.6f %11.6f ", \
1.242     brouard  4095:                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  4096:                2*weight[i]*lli,(s2==-1? -1: out[s1][s2]),(s2==-1? -1: savm[s1][s2]));
1.242     brouard  4097:        for(k=1,llt=0.,l=0.; k<=nlstate; k++){
                   4098:          llt +=ll[k]*gipmx/gsw;
                   4099:          fprintf(ficresilk," %10.6f",-ll[k]*gipmx/gsw);
                   4100:        }
                   4101:        fprintf(ficresilk," %10.6f\n", -llt);
1.126     brouard  4102:       }
1.232     brouard  4103:        } /* end of wave */
                   4104: } /* end of individual */
                   4105: for(k=1,l=0.; k<=nlstate; k++) l += ll[k];
                   4106: /* printf("l1=%f l2=%f ",ll[1],ll[2]); */
                   4107: l= l*ipmx/sw; /* To get the same order of magnitude as if weight=1 for every body */
                   4108: if(globpr==0){ /* First time we count the contributions and weights */
                   4109:        gipmx=ipmx;
                   4110:        gsw=sw;
                   4111: }
                   4112: return -l;
1.126     brouard  4113: }
                   4114: 
                   4115: 
                   4116: /*************** function likelione ***********/
1.292     brouard  4117: void likelione(FILE *ficres,double p[], int npar, int nlstate, int *globpri, long *ipmx, double *sw, double *fretone, double (*func)(double []))
1.126     brouard  4118: {
                   4119:   /* This routine should help understanding what is done with 
                   4120:      the selection of individuals/waves and
                   4121:      to check the exact contribution to the likelihood.
                   4122:      Plotting could be done.
                   4123:    */
                   4124:   int k;
                   4125: 
                   4126:   if(*globpri !=0){ /* Just counts and sums, no printings */
1.201     brouard  4127:     strcpy(fileresilk,"ILK_"); 
1.202     brouard  4128:     strcat(fileresilk,fileresu);
1.126     brouard  4129:     if((ficresilk=fopen(fileresilk,"w"))==NULL) {
                   4130:       printf("Problem with resultfile: %s\n", fileresilk);
                   4131:       fprintf(ficlog,"Problem with resultfile: %s\n", fileresilk);
                   4132:     }
1.214     brouard  4133:     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");
                   4134:     fprintf(ficresilk, "#num_i ageb agend i s1 s2 mi mw dh likeli weight %%weight 2wlli out sav ");
1.126     brouard  4135:     /*         i,s1,s2,mi,mw[mi][i],dh[mi][i],exp(lli),weight[i],2*weight[i]*lli,out[s1][s2],savm[s1][s2]); */
                   4136:     for(k=1; k<=nlstate; k++) 
                   4137:       fprintf(ficresilk," -2*gipw/gsw*weight*ll[%d]++",k);
                   4138:     fprintf(ficresilk," -2*gipw/gsw*weight*ll(total)\n");
                   4139:   }
                   4140: 
1.292     brouard  4141:   *fretone=(*func)(p);
1.126     brouard  4142:   if(*globpri !=0){
                   4143:     fclose(ficresilk);
1.205     brouard  4144:     if (mle ==0)
                   4145:       fprintf(fichtm,"\n<br>File of contributions to the likelihood computed with initial parameters and mle = %d.",mle);
                   4146:     else if(mle >=1)
                   4147:       fprintf(fichtm,"\n<br>File of contributions to the likelihood computed with optimized parameters mle = %d.",mle);
                   4148:     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  4149:     fprintf(fichtm,"\n<br>Equation of the model: <b>model=1+age+%s</b><br>\n",model); 
1.208     brouard  4150:       
                   4151:     for (k=1; k<= nlstate ; k++) {
1.211     brouard  4152:       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  4153: <img src=\"%s-p%dj.png\">",k,k,subdirf2(optionfilefiname,"ILK_"),k,subdirf2(optionfilefiname,"ILK_"),k,subdirf2(optionfilefiname,"ILK_"),k);
                   4154:     }
1.207     brouard  4155:     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  4156: <img src=\"%s-ori.png\">",subdirf2(optionfilefiname,"ILK_"),subdirf2(optionfilefiname,"ILK_"),subdirf2(optionfilefiname,"ILK_"));
1.207     brouard  4157:     fprintf(fichtm,"<br>- and by state of destination <a href=\"%s-dest.png\">%s-dest.png</a><br> \
1.204     brouard  4158: <img src=\"%s-dest.png\">",subdirf2(optionfilefiname,"ILK_"),subdirf2(optionfilefiname,"ILK_"),subdirf2(optionfilefiname,"ILK_"));
1.207     brouard  4159:     fflush(fichtm);
1.205     brouard  4160:   }
1.126     brouard  4161:   return;
                   4162: }
                   4163: 
                   4164: 
                   4165: /*********** Maximum Likelihood Estimation ***************/
                   4166: 
                   4167: void mlikeli(FILE *ficres,double p[], int npar, int ncovmodel, int nlstate, double ftol, double (*func)(double []))
                   4168: {
1.319     brouard  4169:   int i,j,k, jk, jkk=0, iter=0;
1.126     brouard  4170:   double **xi;
                   4171:   double fret;
                   4172:   double fretone; /* Only one call to likelihood */
                   4173:   /*  char filerespow[FILENAMELENGTH];*/
1.162     brouard  4174: 
                   4175: #ifdef NLOPT
                   4176:   int creturn;
                   4177:   nlopt_opt opt;
                   4178:   /* double lb[9] = { -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL }; /\* lower bounds *\/ */
                   4179:   double *lb;
                   4180:   double minf; /* the minimum objective value, upon return */
                   4181:   double * p1; /* Shifted parameters from 0 instead of 1 */
                   4182:   myfunc_data dinst, *d = &dinst;
                   4183: #endif
                   4184: 
                   4185: 
1.126     brouard  4186:   xi=matrix(1,npar,1,npar);
                   4187:   for (i=1;i<=npar;i++)
                   4188:     for (j=1;j<=npar;j++)
                   4189:       xi[i][j]=(i==j ? 1.0 : 0.0);
                   4190:   printf("Powell\n");  fprintf(ficlog,"Powell\n");
1.201     brouard  4191:   strcpy(filerespow,"POW_"); 
1.126     brouard  4192:   strcat(filerespow,fileres);
                   4193:   if((ficrespow=fopen(filerespow,"w"))==NULL) {
                   4194:     printf("Problem with resultfile: %s\n", filerespow);
                   4195:     fprintf(ficlog,"Problem with resultfile: %s\n", filerespow);
                   4196:   }
                   4197:   fprintf(ficrespow,"# Powell\n# iter -2*LL");
                   4198:   for (i=1;i<=nlstate;i++)
                   4199:     for(j=1;j<=nlstate+ndeath;j++)
                   4200:       if(j!=i)fprintf(ficrespow," p%1d%1d",i,j);
                   4201:   fprintf(ficrespow,"\n");
1.162     brouard  4202: #ifdef POWELL
1.319     brouard  4203: #ifdef LINMINORIGINAL
                   4204: #else /* LINMINORIGINAL */
                   4205:   
                   4206:   flatdir=ivector(1,npar); 
                   4207:   for (j=1;j<=npar;j++) flatdir[j]=0; 
                   4208: #endif /*LINMINORIGINAL */
                   4209: 
                   4210: #ifdef FLATSUP
                   4211:   powell(p,xi,npar,ftol,&iter,&fret,flatdir,func);
                   4212:   /* reorganizing p by suppressing flat directions */
                   4213:   for(i=1, jk=1; i <=nlstate; i++){
                   4214:     for(k=1; k <=(nlstate+ndeath); k++){
                   4215:       if (k != i) {
                   4216:         printf("%d%d flatdir[%d]=%d",i,k,jk, flatdir[jk]);
                   4217:         if(flatdir[jk]==1){
                   4218:           printf(" To be skipped %d%d flatdir[%d]=%d ",i,k,jk, flatdir[jk]);
                   4219:         }
                   4220:         for(j=1; j <=ncovmodel; j++){
                   4221:           printf("%12.7f ",p[jk]);
                   4222:           jk++; 
                   4223:         }
                   4224:         printf("\n");
                   4225:       }
                   4226:     }
                   4227:   }
                   4228: /* skipping */
                   4229:   /* for(i=1, jk=1, jkk=1;(flatdir[jk]==0)&& (i <=nlstate); i++){ */
                   4230:   for(i=1, jk=1, jkk=1;i <=nlstate; i++){
                   4231:     for(k=1; k <=(nlstate+ndeath); k++){
                   4232:       if (k != i) {
                   4233:         printf("%d%d flatdir[%d]=%d",i,k,jk, flatdir[jk]);
                   4234:         if(flatdir[jk]==1){
                   4235:           printf(" To be skipped %d%d flatdir[%d]=%d jk=%d p[%d] ",i,k,jk, flatdir[jk],jk, jk);
                   4236:           for(j=1; j <=ncovmodel;  jk++,j++){
                   4237:             printf(" p[%d]=%12.7f",jk, p[jk]);
                   4238:             /*q[jjk]=p[jk];*/
                   4239:           }
                   4240:         }else{
                   4241:           printf(" To be kept %d%d flatdir[%d]=%d jk=%d q[%d]=p[%d] ",i,k,jk, flatdir[jk],jk, jkk, jk);
                   4242:           for(j=1; j <=ncovmodel;  jk++,jkk++,j++){
                   4243:             printf(" p[%d]=%12.7f=q[%d]",jk, p[jk],jkk);
                   4244:             /*q[jjk]=p[jk];*/
                   4245:           }
                   4246:         }
                   4247:         printf("\n");
                   4248:       }
                   4249:       fflush(stdout);
                   4250:     }
                   4251:   }
                   4252:   powell(p,xi,npar,ftol,&iter,&fret,flatdir,func);
                   4253: #else  /* FLATSUP */
1.126     brouard  4254:   powell(p,xi,npar,ftol,&iter,&fret,func);
1.319     brouard  4255: #endif  /* FLATSUP */
                   4256: 
                   4257: #ifdef LINMINORIGINAL
                   4258: #else
                   4259:       free_ivector(flatdir,1,npar); 
                   4260: #endif  /* LINMINORIGINAL*/
                   4261: #endif /* POWELL */
1.126     brouard  4262: 
1.162     brouard  4263: #ifdef NLOPT
                   4264: #ifdef NEWUOA
                   4265:   opt = nlopt_create(NLOPT_LN_NEWUOA,npar);
                   4266: #else
                   4267:   opt = nlopt_create(NLOPT_LN_BOBYQA,npar);
                   4268: #endif
                   4269:   lb=vector(0,npar-1);
                   4270:   for (i=0;i<npar;i++) lb[i]= -HUGE_VAL;
                   4271:   nlopt_set_lower_bounds(opt, lb);
                   4272:   nlopt_set_initial_step1(opt, 0.1);
                   4273:   
                   4274:   p1= (p+1); /*  p *(p+1)@8 and p *(p1)@8 are equal p1[0]=p[1] */
                   4275:   d->function = func;
                   4276:   printf(" Func %.12lf \n",myfunc(npar,p1,NULL,d));
                   4277:   nlopt_set_min_objective(opt, myfunc, d);
                   4278:   nlopt_set_xtol_rel(opt, ftol);
                   4279:   if ((creturn=nlopt_optimize(opt, p1, &minf)) < 0) {
                   4280:     printf("nlopt failed! %d\n",creturn); 
                   4281:   }
                   4282:   else {
                   4283:     printf("found minimum after %d evaluations (NLOPT=%d)\n", countcallfunc ,NLOPT);
                   4284:     printf("found minimum at f(%g,%g) = %0.10g\n", p[0], p[1], minf);
                   4285:     iter=1; /* not equal */
                   4286:   }
                   4287:   nlopt_destroy(opt);
                   4288: #endif
1.319     brouard  4289: #ifdef FLATSUP
                   4290:   /* npared = npar -flatd/ncovmodel; */
                   4291:   /* xired= matrix(1,npared,1,npared); */
                   4292:   /* paramred= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel); */
                   4293:   /* powell(pred,xired,npared,ftol,&iter,&fret,flatdir,func); */
                   4294:   /* free_matrix(xire,1,npared,1,npared); */
                   4295: #else  /* FLATSUP */
                   4296: #endif /* FLATSUP */
1.126     brouard  4297:   free_matrix(xi,1,npar,1,npar);
                   4298:   fclose(ficrespow);
1.203     brouard  4299:   printf("\n#Number of iterations & function calls = %d & %d, -2 Log likelihood = %.12f\n",iter, countcallfunc,func(p));
                   4300:   fprintf(ficlog,"\n#Number of iterations & function calls = %d & %d, -2 Log likelihood = %.12f\n",iter, countcallfunc,func(p));
1.180     brouard  4301:   fprintf(ficres,"#Number of iterations & function calls = %d & %d, -2 Log likelihood = %.12f\n",iter, countcallfunc,func(p));
1.126     brouard  4302: 
                   4303: }
                   4304: 
                   4305: /**** Computes Hessian and covariance matrix ***/
1.203     brouard  4306: void hesscov(double **matcov, double **hess, double p[], int npar, double delti[], double ftolhess, double (*func)(double []))
1.126     brouard  4307: {
                   4308:   double  **a,**y,*x,pd;
1.203     brouard  4309:   /* double **hess; */
1.164     brouard  4310:   int i, j;
1.126     brouard  4311:   int *indx;
                   4312: 
                   4313:   double hessii(double p[], double delta, int theta, double delti[],double (*func)(double []),int npar);
1.203     brouard  4314:   double hessij(double p[], double **hess, double delti[], int i, int j,double (*func)(double []),int npar);
1.126     brouard  4315:   void lubksb(double **a, int npar, int *indx, double b[]) ;
                   4316:   void ludcmp(double **a, int npar, int *indx, double *d) ;
                   4317:   double gompertz(double p[]);
1.203     brouard  4318:   /* hess=matrix(1,npar,1,npar); */
1.126     brouard  4319: 
                   4320:   printf("\nCalculation of the hessian matrix. Wait...\n");
                   4321:   fprintf(ficlog,"\nCalculation of the hessian matrix. Wait...\n");
                   4322:   for (i=1;i<=npar;i++){
1.203     brouard  4323:     printf("%d-",i);fflush(stdout);
                   4324:     fprintf(ficlog,"%d-",i);fflush(ficlog);
1.126     brouard  4325:    
                   4326:      hess[i][i]=hessii(p,ftolhess,i,delti,func,npar);
                   4327:     
                   4328:     /*  printf(" %f ",p[i]);
                   4329:        printf(" %lf %lf %lf",hess[i][i],ftolhess,delti[i]);*/
                   4330:   }
                   4331:   
                   4332:   for (i=1;i<=npar;i++) {
                   4333:     for (j=1;j<=npar;j++)  {
                   4334:       if (j>i) { 
1.203     brouard  4335:        printf(".%d-%d",i,j);fflush(stdout);
                   4336:        fprintf(ficlog,".%d-%d",i,j);fflush(ficlog);
                   4337:        hess[i][j]=hessij(p,hess, delti,i,j,func,npar);
1.126     brouard  4338:        
                   4339:        hess[j][i]=hess[i][j];    
                   4340:        /*printf(" %lf ",hess[i][j]);*/
                   4341:       }
                   4342:     }
                   4343:   }
                   4344:   printf("\n");
                   4345:   fprintf(ficlog,"\n");
                   4346: 
                   4347:   printf("\nInverting the hessian to get the covariance matrix. Wait...\n");
                   4348:   fprintf(ficlog,"\nInverting the hessian to get the covariance matrix. Wait...\n");
                   4349:   
                   4350:   a=matrix(1,npar,1,npar);
                   4351:   y=matrix(1,npar,1,npar);
                   4352:   x=vector(1,npar);
                   4353:   indx=ivector(1,npar);
                   4354:   for (i=1;i<=npar;i++)
                   4355:     for (j=1;j<=npar;j++) a[i][j]=hess[i][j];
                   4356:   ludcmp(a,npar,indx,&pd);
                   4357: 
                   4358:   for (j=1;j<=npar;j++) {
                   4359:     for (i=1;i<=npar;i++) x[i]=0;
                   4360:     x[j]=1;
                   4361:     lubksb(a,npar,indx,x);
                   4362:     for (i=1;i<=npar;i++){ 
                   4363:       matcov[i][j]=x[i];
                   4364:     }
                   4365:   }
                   4366: 
                   4367:   printf("\n#Hessian matrix#\n");
                   4368:   fprintf(ficlog,"\n#Hessian matrix#\n");
                   4369:   for (i=1;i<=npar;i++) { 
                   4370:     for (j=1;j<=npar;j++) { 
1.203     brouard  4371:       printf("%.6e ",hess[i][j]);
                   4372:       fprintf(ficlog,"%.6e ",hess[i][j]);
1.126     brouard  4373:     }
                   4374:     printf("\n");
                   4375:     fprintf(ficlog,"\n");
                   4376:   }
                   4377: 
1.203     brouard  4378:   /* printf("\n#Covariance matrix#\n"); */
                   4379:   /* fprintf(ficlog,"\n#Covariance matrix#\n"); */
                   4380:   /* for (i=1;i<=npar;i++) {  */
                   4381:   /*   for (j=1;j<=npar;j++) {  */
                   4382:   /*     printf("%.6e ",matcov[i][j]); */
                   4383:   /*     fprintf(ficlog,"%.6e ",matcov[i][j]); */
                   4384:   /*   } */
                   4385:   /*   printf("\n"); */
                   4386:   /*   fprintf(ficlog,"\n"); */
                   4387:   /* } */
                   4388: 
1.126     brouard  4389:   /* Recompute Inverse */
1.203     brouard  4390:   /* for (i=1;i<=npar;i++) */
                   4391:   /*   for (j=1;j<=npar;j++) a[i][j]=matcov[i][j]; */
                   4392:   /* ludcmp(a,npar,indx,&pd); */
                   4393: 
                   4394:   /*  printf("\n#Hessian matrix recomputed#\n"); */
                   4395: 
                   4396:   /* for (j=1;j<=npar;j++) { */
                   4397:   /*   for (i=1;i<=npar;i++) x[i]=0; */
                   4398:   /*   x[j]=1; */
                   4399:   /*   lubksb(a,npar,indx,x); */
                   4400:   /*   for (i=1;i<=npar;i++){  */
                   4401:   /*     y[i][j]=x[i]; */
                   4402:   /*     printf("%.3e ",y[i][j]); */
                   4403:   /*     fprintf(ficlog,"%.3e ",y[i][j]); */
                   4404:   /*   } */
                   4405:   /*   printf("\n"); */
                   4406:   /*   fprintf(ficlog,"\n"); */
                   4407:   /* } */
                   4408: 
                   4409:   /* Verifying the inverse matrix */
                   4410: #ifdef DEBUGHESS
                   4411:   y=matprod2(y,hess,1,npar,1,npar,1,npar,matcov);
1.126     brouard  4412: 
1.203     brouard  4413:    printf("\n#Verification: multiplying the matrix of covariance by the Hessian matrix, should be unity:#\n");
                   4414:    fprintf(ficlog,"\n#Verification: multiplying the matrix of covariance by the Hessian matrix. Should be unity:#\n");
1.126     brouard  4415: 
                   4416:   for (j=1;j<=npar;j++) {
                   4417:     for (i=1;i<=npar;i++){ 
1.203     brouard  4418:       printf("%.2f ",y[i][j]);
                   4419:       fprintf(ficlog,"%.2f ",y[i][j]);
1.126     brouard  4420:     }
                   4421:     printf("\n");
                   4422:     fprintf(ficlog,"\n");
                   4423:   }
1.203     brouard  4424: #endif
1.126     brouard  4425: 
                   4426:   free_matrix(a,1,npar,1,npar);
                   4427:   free_matrix(y,1,npar,1,npar);
                   4428:   free_vector(x,1,npar);
                   4429:   free_ivector(indx,1,npar);
1.203     brouard  4430:   /* free_matrix(hess,1,npar,1,npar); */
1.126     brouard  4431: 
                   4432: 
                   4433: }
                   4434: 
                   4435: /*************** hessian matrix ****************/
                   4436: double hessii(double x[], double delta, int theta, double delti[], double (*func)(double []), int npar)
1.203     brouard  4437: { /* Around values of x, computes the function func and returns the scales delti and hessian */
1.126     brouard  4438:   int i;
                   4439:   int l=1, lmax=20;
1.203     brouard  4440:   double k1,k2, res, fx;
1.132     brouard  4441:   double p2[MAXPARM+1]; /* identical to x */
1.126     brouard  4442:   double delt=0.0001, delts, nkhi=10.,nkhif=1., khi=1.e-4;
                   4443:   int k=0,kmax=10;
                   4444:   double l1;
                   4445: 
                   4446:   fx=func(x);
                   4447:   for (i=1;i<=npar;i++) p2[i]=x[i];
1.145     brouard  4448:   for(l=0 ; l <=lmax; l++){  /* Enlarging the zone around the Maximum */
1.126     brouard  4449:     l1=pow(10,l);
                   4450:     delts=delt;
                   4451:     for(k=1 ; k <kmax; k=k+1){
                   4452:       delt = delta*(l1*k);
                   4453:       p2[theta]=x[theta] +delt;
1.145     brouard  4454:       k1=func(p2)-fx;   /* Might be negative if too close to the theoretical maximum */
1.126     brouard  4455:       p2[theta]=x[theta]-delt;
                   4456:       k2=func(p2)-fx;
                   4457:       /*res= (k1-2.0*fx+k2)/delt/delt; */
1.203     brouard  4458:       res= (k1+k2)/delt/delt/2.; /* Divided by 2 because L and not 2*L */
1.126     brouard  4459:       
1.203     brouard  4460: #ifdef DEBUGHESSII
1.126     brouard  4461:       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);
                   4462:       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);
                   4463: #endif
                   4464:       /*if(fabs(k1-2.0*fx+k2) <1.e-13){ */
                   4465:       if((k1 <khi/nkhi/2.) || (k2 <khi/nkhi/2.)){
                   4466:        k=kmax;
                   4467:       }
                   4468:       else if((k1 >khi/nkhif) || (k2 >khi/nkhif)){ /* Keeps lastvalue before 3.84/2 KHI2 5% 1d.f. */
1.164     brouard  4469:        k=kmax; l=lmax*10;
1.126     brouard  4470:       }
                   4471:       else if((k1 >khi/nkhi) || (k2 >khi/nkhi)){ 
                   4472:        delts=delt;
                   4473:       }
1.203     brouard  4474:     } /* End loop k */
1.126     brouard  4475:   }
                   4476:   delti[theta]=delts;
                   4477:   return res; 
                   4478:   
                   4479: }
                   4480: 
1.203     brouard  4481: double hessij( double x[], double **hess, double delti[], int thetai,int thetaj,double (*func)(double []),int npar)
1.126     brouard  4482: {
                   4483:   int i;
1.164     brouard  4484:   int l=1, lmax=20;
1.126     brouard  4485:   double k1,k2,k3,k4,res,fx;
1.132     brouard  4486:   double p2[MAXPARM+1];
1.203     brouard  4487:   int k, kmax=1;
                   4488:   double v1, v2, cv12, lc1, lc2;
1.208     brouard  4489: 
                   4490:   int firstime=0;
1.203     brouard  4491:   
1.126     brouard  4492:   fx=func(x);
1.203     brouard  4493:   for (k=1; k<=kmax; k=k+10) {
1.126     brouard  4494:     for (i=1;i<=npar;i++) p2[i]=x[i];
1.203     brouard  4495:     p2[thetai]=x[thetai]+delti[thetai]*k;
                   4496:     p2[thetaj]=x[thetaj]+delti[thetaj]*k;
1.126     brouard  4497:     k1=func(p2)-fx;
                   4498:   
1.203     brouard  4499:     p2[thetai]=x[thetai]+delti[thetai]*k;
                   4500:     p2[thetaj]=x[thetaj]-delti[thetaj]*k;
1.126     brouard  4501:     k2=func(p2)-fx;
                   4502:   
1.203     brouard  4503:     p2[thetai]=x[thetai]-delti[thetai]*k;
                   4504:     p2[thetaj]=x[thetaj]+delti[thetaj]*k;
1.126     brouard  4505:     k3=func(p2)-fx;
                   4506:   
1.203     brouard  4507:     p2[thetai]=x[thetai]-delti[thetai]*k;
                   4508:     p2[thetaj]=x[thetaj]-delti[thetaj]*k;
1.126     brouard  4509:     k4=func(p2)-fx;
1.203     brouard  4510:     res=(k1-k2-k3+k4)/4.0/delti[thetai]/k/delti[thetaj]/k/2.; /* Because of L not 2*L */
                   4511:     if(k1*k2*k3*k4 <0.){
1.208     brouard  4512:       firstime=1;
1.203     brouard  4513:       kmax=kmax+10;
1.208     brouard  4514:     }
                   4515:     if(kmax >=10 || firstime ==1){
1.246     brouard  4516:       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);
                   4517:       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  4518:       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);
                   4519:       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);
                   4520:     }
                   4521: #ifdef DEBUGHESSIJ
                   4522:     v1=hess[thetai][thetai];
                   4523:     v2=hess[thetaj][thetaj];
                   4524:     cv12=res;
                   4525:     /* Computing eigen value of Hessian matrix */
                   4526:     lc1=((v1+v2)+sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
                   4527:     lc2=((v1+v2)-sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
                   4528:     if ((lc2 <0) || (lc1 <0) ){
                   4529:       printf("Warning: sub Hessian matrix '%d%d' does not have positive eigen values \n",thetai,thetaj);
                   4530:       fprintf(ficlog, "Warning: sub Hessian matrix '%d%d' does not have positive eigen values \n",thetai,thetaj);
                   4531:       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);
                   4532:       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);
                   4533:     }
1.126     brouard  4534: #endif
                   4535:   }
                   4536:   return res;
                   4537: }
                   4538: 
1.203     brouard  4539:     /* Not done yet: Was supposed to fix if not exactly at the maximum */
                   4540: /* double hessij( double x[], double delti[], int thetai,int thetaj,double (*func)(double []),int npar) */
                   4541: /* { */
                   4542: /*   int i; */
                   4543: /*   int l=1, lmax=20; */
                   4544: /*   double k1,k2,k3,k4,res,fx; */
                   4545: /*   double p2[MAXPARM+1]; */
                   4546: /*   double delt=0.0001, delts, nkhi=10.,nkhif=1., khi=1.e-4; */
                   4547: /*   int k=0,kmax=10; */
                   4548: /*   double l1; */
                   4549:   
                   4550: /*   fx=func(x); */
                   4551: /*   for(l=0 ; l <=lmax; l++){  /\* Enlarging the zone around the Maximum *\/ */
                   4552: /*     l1=pow(10,l); */
                   4553: /*     delts=delt; */
                   4554: /*     for(k=1 ; k <kmax; k=k+1){ */
                   4555: /*       delt = delti*(l1*k); */
                   4556: /*       for (i=1;i<=npar;i++) p2[i]=x[i]; */
                   4557: /*       p2[thetai]=x[thetai]+delti[thetai]/k; */
                   4558: /*       p2[thetaj]=x[thetaj]+delti[thetaj]/k; */
                   4559: /*       k1=func(p2)-fx; */
                   4560:       
                   4561: /*       p2[thetai]=x[thetai]+delti[thetai]/k; */
                   4562: /*       p2[thetaj]=x[thetaj]-delti[thetaj]/k; */
                   4563: /*       k2=func(p2)-fx; */
                   4564:       
                   4565: /*       p2[thetai]=x[thetai]-delti[thetai]/k; */
                   4566: /*       p2[thetaj]=x[thetaj]+delti[thetaj]/k; */
                   4567: /*       k3=func(p2)-fx; */
                   4568:       
                   4569: /*       p2[thetai]=x[thetai]-delti[thetai]/k; */
                   4570: /*       p2[thetaj]=x[thetaj]-delti[thetaj]/k; */
                   4571: /*       k4=func(p2)-fx; */
                   4572: /*       res=(k1-k2-k3+k4)/4.0/delti[thetai]*k/delti[thetaj]*k/2.; /\* Because of L not 2*L *\/ */
                   4573: /* #ifdef DEBUGHESSIJ */
                   4574: /*       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); */
                   4575: /*       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); */
                   4576: /* #endif */
                   4577: /*       if((k1 <khi/nkhi/2.) || (k2 <khi/nkhi/2.)|| (k4 <khi/nkhi/2.)|| (k4 <khi/nkhi/2.)){ */
                   4578: /*     k=kmax; */
                   4579: /*       } */
                   4580: /*       else if((k1 >khi/nkhif) || (k2 >khi/nkhif) || (k4 >khi/nkhif) || (k4 >khi/nkhif)){ /\* Keeps lastvalue before 3.84/2 KHI2 5% 1d.f. *\/ */
                   4581: /*     k=kmax; l=lmax*10; */
                   4582: /*       } */
                   4583: /*       else if((k1 >khi/nkhi) || (k2 >khi/nkhi)){  */
                   4584: /*     delts=delt; */
                   4585: /*       } */
                   4586: /*     } /\* End loop k *\/ */
                   4587: /*   } */
                   4588: /*   delti[theta]=delts; */
                   4589: /*   return res;  */
                   4590: /* } */
                   4591: 
                   4592: 
1.126     brouard  4593: /************** Inverse of matrix **************/
                   4594: void ludcmp(double **a, int n, int *indx, double *d) 
                   4595: { 
                   4596:   int i,imax,j,k; 
                   4597:   double big,dum,sum,temp; 
                   4598:   double *vv; 
                   4599:  
                   4600:   vv=vector(1,n); 
                   4601:   *d=1.0; 
                   4602:   for (i=1;i<=n;i++) { 
                   4603:     big=0.0; 
                   4604:     for (j=1;j<=n;j++) 
                   4605:       if ((temp=fabs(a[i][j])) > big) big=temp; 
1.256     brouard  4606:     if (big == 0.0){
                   4607:       printf(" Singular Hessian matrix at row %d:\n",i);
                   4608:       for (j=1;j<=n;j++) {
                   4609:        printf(" a[%d][%d]=%f,",i,j,a[i][j]);
                   4610:        fprintf(ficlog," a[%d][%d]=%f,",i,j,a[i][j]);
                   4611:       }
                   4612:       fflush(ficlog);
                   4613:       fclose(ficlog);
                   4614:       nrerror("Singular matrix in routine ludcmp"); 
                   4615:     }
1.126     brouard  4616:     vv[i]=1.0/big; 
                   4617:   } 
                   4618:   for (j=1;j<=n;j++) { 
                   4619:     for (i=1;i<j;i++) { 
                   4620:       sum=a[i][j]; 
                   4621:       for (k=1;k<i;k++) sum -= a[i][k]*a[k][j]; 
                   4622:       a[i][j]=sum; 
                   4623:     } 
                   4624:     big=0.0; 
                   4625:     for (i=j;i<=n;i++) { 
                   4626:       sum=a[i][j]; 
                   4627:       for (k=1;k<j;k++) 
                   4628:        sum -= a[i][k]*a[k][j]; 
                   4629:       a[i][j]=sum; 
                   4630:       if ( (dum=vv[i]*fabs(sum)) >= big) { 
                   4631:        big=dum; 
                   4632:        imax=i; 
                   4633:       } 
                   4634:     } 
                   4635:     if (j != imax) { 
                   4636:       for (k=1;k<=n;k++) { 
                   4637:        dum=a[imax][k]; 
                   4638:        a[imax][k]=a[j][k]; 
                   4639:        a[j][k]=dum; 
                   4640:       } 
                   4641:       *d = -(*d); 
                   4642:       vv[imax]=vv[j]; 
                   4643:     } 
                   4644:     indx[j]=imax; 
                   4645:     if (a[j][j] == 0.0) a[j][j]=TINY; 
                   4646:     if (j != n) { 
                   4647:       dum=1.0/(a[j][j]); 
                   4648:       for (i=j+1;i<=n;i++) a[i][j] *= dum; 
                   4649:     } 
                   4650:   } 
                   4651:   free_vector(vv,1,n);  /* Doesn't work */
                   4652: ;
                   4653: } 
                   4654: 
                   4655: void lubksb(double **a, int n, int *indx, double b[]) 
                   4656: { 
                   4657:   int i,ii=0,ip,j; 
                   4658:   double sum; 
                   4659:  
                   4660:   for (i=1;i<=n;i++) { 
                   4661:     ip=indx[i]; 
                   4662:     sum=b[ip]; 
                   4663:     b[ip]=b[i]; 
                   4664:     if (ii) 
                   4665:       for (j=ii;j<=i-1;j++) sum -= a[i][j]*b[j]; 
                   4666:     else if (sum) ii=i; 
                   4667:     b[i]=sum; 
                   4668:   } 
                   4669:   for (i=n;i>=1;i--) { 
                   4670:     sum=b[i]; 
                   4671:     for (j=i+1;j<=n;j++) sum -= a[i][j]*b[j]; 
                   4672:     b[i]=sum/a[i][i]; 
                   4673:   } 
                   4674: } 
                   4675: 
                   4676: void pstamp(FILE *fichier)
                   4677: {
1.196     brouard  4678:   fprintf(fichier,"# %s.%s\n#IMaCh version %s, %s\n#%s\n# %s", optionfilefiname,optionfilext,version,copyright, fullversion, strstart);
1.126     brouard  4679: }
                   4680: 
1.297     brouard  4681: void date2dmy(double date,double *day, double *month, double *year){
                   4682:   double yp=0., yp1=0., yp2=0.;
                   4683:   
                   4684:   yp1=modf(date,&yp);/* extracts integral of date in yp  and
                   4685:                        fractional in yp1 */
                   4686:   *year=yp;
                   4687:   yp2=modf((yp1*12),&yp);
                   4688:   *month=yp;
                   4689:   yp1=modf((yp2*30.5),&yp);
                   4690:   *day=yp;
                   4691:   if(*day==0) *day=1;
                   4692:   if(*month==0) *month=1;
                   4693: }
                   4694: 
1.253     brouard  4695: 
                   4696: 
1.126     brouard  4697: /************ Frequencies ********************/
1.251     brouard  4698: void  freqsummary(char fileres[], double p[], double pstart[], int iagemin, int iagemax, int **s, double **agev, int nlstate, int imx, \
1.226     brouard  4699:                  int *Tvaraff, int *invalidvarcomb, int **nbcode, int *ncodemax,double **mint,double **anint, char strstart[], \
                   4700:                  int firstpass,  int lastpass, int stepm, int weightopt, char model[])
1.250     brouard  4701: {  /* Some frequencies as well as proposing some starting values */
1.226     brouard  4702:   
1.265     brouard  4703:   int i, m, jk, j1, bool, z1,j, nj, nl, k, iv, jj=0, s1=1, s2=1;
1.226     brouard  4704:   int iind=0, iage=0;
                   4705:   int mi; /* Effective wave */
                   4706:   int first;
                   4707:   double ***freq; /* Frequencies */
1.268     brouard  4708:   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 */
                   4709:   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  4710:   double *meanq, *stdq, *idq;
1.226     brouard  4711:   double **meanqt;
                   4712:   double *pp, **prop, *posprop, *pospropt;
                   4713:   double pos=0., posproptt=0., pospropta=0., k2, dateintsum=0,k2cpt=0;
                   4714:   char fileresp[FILENAMELENGTH], fileresphtm[FILENAMELENGTH], fileresphtmfr[FILENAMELENGTH];
                   4715:   double agebegin, ageend;
                   4716:     
                   4717:   pp=vector(1,nlstate);
1.251     brouard  4718:   prop=matrix(1,nlstate,iagemin-AGEMARGE,iagemax+4+AGEMARGE); 
1.226     brouard  4719:   posprop=vector(1,nlstate); /* Counting the number of transition starting from a live state per age */ 
                   4720:   pospropt=vector(1,nlstate); /* Counting the number of transition starting from a live state */ 
                   4721:   /* prop=matrix(1,nlstate,iagemin,iagemax+3); */
                   4722:   meanq=vector(1,nqfveff); /* Number of Quantitative Fixed Variables Effective */
1.284     brouard  4723:   stdq=vector(1,nqfveff); /* Number of Quantitative Fixed Variables Effective */
1.283     brouard  4724:   idq=vector(1,nqfveff); /* Number of Quantitative Fixed Variables Effective */
1.226     brouard  4725:   meanqt=matrix(1,lastpass,1,nqtveff);
                   4726:   strcpy(fileresp,"P_");
                   4727:   strcat(fileresp,fileresu);
                   4728:   /*strcat(fileresphtm,fileresu);*/
                   4729:   if((ficresp=fopen(fileresp,"w"))==NULL) {
                   4730:     printf("Problem with prevalence resultfile: %s\n", fileresp);
                   4731:     fprintf(ficlog,"Problem with prevalence resultfile: %s\n", fileresp);
                   4732:     exit(0);
                   4733:   }
1.240     brouard  4734:   
1.226     brouard  4735:   strcpy(fileresphtm,subdirfext(optionfilefiname,"PHTM_",".htm"));
                   4736:   if((ficresphtm=fopen(fileresphtm,"w"))==NULL) {
                   4737:     printf("Problem with prevalence HTM resultfile '%s' with errno='%s'\n",fileresphtm,strerror(errno));
                   4738:     fprintf(ficlog,"Problem with prevalence HTM resultfile '%s' with errno='%s'\n",fileresphtm,strerror(errno));
                   4739:     fflush(ficlog);
                   4740:     exit(70); 
                   4741:   }
                   4742:   else{
                   4743:     fprintf(ficresphtm,"<html><head>\n<title>IMaCh PHTM_ %s</title></head>\n <body><font size=\"2\">%s <br> %s</font> \
1.240     brouard  4744: <hr size=\"2\" color=\"#EC5E5E\"> \n                                   \
1.214     brouard  4745: Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=1+age+%s<br>\n",\
1.226     brouard  4746:            fileresphtm,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model);
                   4747:   }
1.319     brouard  4748:   fprintf(ficresphtm,"Current page is file <a href=\"%s\">%s</a><br>\n\n<h4>Frequencies (weight=%d) and prevalence by age at begin of transition and dummy covariate value at beginning of transition</h4>\n",fileresphtm, fileresphtm, weightopt);
1.240     brouard  4749:   
1.226     brouard  4750:   strcpy(fileresphtmfr,subdirfext(optionfilefiname,"PHTMFR_",".htm"));
                   4751:   if((ficresphtmfr=fopen(fileresphtmfr,"w"))==NULL) {
                   4752:     printf("Problem with frequency table HTM resultfile '%s' with errno='%s'\n",fileresphtmfr,strerror(errno));
                   4753:     fprintf(ficlog,"Problem with frequency table HTM resultfile '%s' with errno='%s'\n",fileresphtmfr,strerror(errno));
                   4754:     fflush(ficlog);
                   4755:     exit(70); 
1.240     brouard  4756:   } else{
1.226     brouard  4757:     fprintf(ficresphtmfr,"<html><head>\n<title>IMaCh PHTM_Frequency table %s</title></head>\n <body><font size=\"2\">%s <br> %s</font> \
1.319     brouard  4758: ,<hr size=\"2\" color=\"#EC5E5E\"> \n                                  \
1.214     brouard  4759: Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=1+age+%s<br>\n",\
1.226     brouard  4760:            fileresphtmfr,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model);
                   4761:   }
1.319     brouard  4762:   fprintf(ficresphtmfr,"Current page is file <a href=\"%s\">%s</a><br>\n\n<h4>(weight=%d) 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,weightopt);
1.240     brouard  4763:   
1.253     brouard  4764:   y= vector(iagemin-AGEMARGE,iagemax+4+AGEMARGE);
                   4765:   x= vector(iagemin-AGEMARGE,iagemax+4+AGEMARGE);
1.251     brouard  4766:   freq= ma3x(-5,nlstate+ndeath,-5,nlstate+ndeath,iagemin-AGEMARGE,iagemax+4+AGEMARGE);
1.226     brouard  4767:   j1=0;
1.126     brouard  4768:   
1.227     brouard  4769:   /* j=ncoveff;  /\* Only fixed dummy covariates *\/ */
                   4770:   j=cptcoveff;  /* Only dummy covariates of the model */
1.226     brouard  4771:   if (cptcovn<1) {j=1;ncodemax[1]=1;}
1.240     brouard  4772:   
                   4773:   
1.226     brouard  4774:   /* Detects if a combination j1 is empty: for a multinomial variable like 3 education levels:
                   4775:      reference=low_education V1=0,V2=0
                   4776:      med_educ                V1=1 V2=0, 
                   4777:      high_educ               V1=0 V2=1
                   4778:      Then V1=1 and V2=1 is a noisy combination that we want to exclude for the list 2**cptcoveff 
                   4779:   */
1.249     brouard  4780:   dateintsum=0;
                   4781:   k2cpt=0;
                   4782: 
1.253     brouard  4783:   if(cptcoveff == 0 )
1.265     brouard  4784:     nl=1;  /* Constant and age model only */
1.253     brouard  4785:   else
                   4786:     nl=2;
1.265     brouard  4787: 
                   4788:   /* if a constant only model, one pass to compute frequency tables and to write it on ficresp */
                   4789:   /* Loop on nj=1 or 2 if dummy covariates j!=0
                   4790:    *   Loop on j1(1 to 2**cptcoveff) covariate combination
                   4791:    *     freq[s1][s2][iage] =0.
                   4792:    *     Loop on iind
                   4793:    *       ++freq[s1][s2][iage] weighted
                   4794:    *     end iind
                   4795:    *     if covariate and j!0
                   4796:    *       headers Variable on one line
                   4797:    *     endif cov j!=0
                   4798:    *     header of frequency table by age
                   4799:    *     Loop on age
                   4800:    *       pp[s1]+=freq[s1][s2][iage] weighted
                   4801:    *       pos+=freq[s1][s2][iage] weighted
                   4802:    *       Loop on s1 initial state
                   4803:    *         fprintf(ficresp
                   4804:    *       end s1
                   4805:    *     end age
                   4806:    *     if j!=0 computes starting values
                   4807:    *     end compute starting values
                   4808:    *   end j1
                   4809:    * end nl 
                   4810:    */
1.253     brouard  4811:   for (nj = 1; nj <= nl; nj++){   /* nj= 1 constant model, nl number of loops. */
                   4812:     if(nj==1)
                   4813:       j=0;  /* First pass for the constant */
1.265     brouard  4814:     else{
1.253     brouard  4815:       j=cptcoveff; /* Other passes for the covariate values */
1.265     brouard  4816:     }
1.251     brouard  4817:     first=1;
1.265     brouard  4818:     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  4819:       posproptt=0.;
                   4820:       /*printf("cptcoveff=%d Tvaraff=%d", cptcoveff,Tvaraff[1]);
                   4821:        scanf("%d", i);*/
                   4822:       for (i=-5; i<=nlstate+ndeath; i++)  
1.265     brouard  4823:        for (s2=-5; s2<=nlstate+ndeath; s2++)  
1.251     brouard  4824:          for(m=iagemin; m <= iagemax+3; m++)
1.265     brouard  4825:            freq[i][s2][m]=0;
1.251     brouard  4826:       
                   4827:       for (i=1; i<=nlstate; i++)  {
1.240     brouard  4828:        for(m=iagemin; m <= iagemax+3; m++)
1.251     brouard  4829:          prop[i][m]=0;
                   4830:        posprop[i]=0;
                   4831:        pospropt[i]=0;
                   4832:       }
1.283     brouard  4833:       for (z1=1; z1<= nqfveff; z1++) { /* zeroing for each combination j1 as well as for the total */
1.284     brouard  4834:         idq[z1]=0.;
                   4835:         meanq[z1]=0.;
                   4836:         stdq[z1]=0.;
1.283     brouard  4837:       }
                   4838:       /* for (z1=1; z1<= nqtveff; z1++) { */
1.251     brouard  4839:       /*   for(m=1;m<=lastpass;m++){ */
1.283     brouard  4840:       /*         meanqt[m][z1]=0.; */
                   4841:       /*       } */
                   4842:       /* }       */
1.251     brouard  4843:       /* dateintsum=0; */
                   4844:       /* k2cpt=0; */
                   4845:       
1.265     brouard  4846:       /* For that combination of covariates j1 (V4=1 V3=0 for example), we count and print the frequencies in one pass */
1.251     brouard  4847:       for (iind=1; iind<=imx; iind++) { /* For each individual iind */
                   4848:        bool=1;
                   4849:        if(j !=0){
                   4850:          if(anyvaryingduminmodel==0){ /* If All fixed covariates */
                   4851:            if (cptcoveff >0) { /* Filter is here: Must be looked at for model=V1+V2+V3+V4 */
                   4852:              for (z1=1; z1<=cptcoveff; z1++) { /* loops on covariates in the model */
                   4853:                /* if(Tvaraff[z1] ==-20){ */
                   4854:                /*       /\* sumnew+=cotvar[mw[mi][iind]][z1][iind]; *\/ */
                   4855:                /* }else  if(Tvaraff[z1] ==-10){ */
                   4856:                /*       /\* sumnew+=coqvar[z1][iind]; *\/ */
                   4857:                /* }else  */
                   4858:                if (covar[Tvaraff[z1]][iind]!= nbcode[Tvaraff[z1]][codtabm(j1,z1)]){ /* for combination j1 of covariates */
1.265     brouard  4859:                  /* Tests if the value of the covariate z1 for this individual iind responded to combination j1 (V4=1 V3=0) */
1.251     brouard  4860:                  bool=0; /* bool should be equal to 1 to be selected, one covariate value failed */
                   4861:                  /* 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", 
                   4862:                     bool,i,z1, z1, Tvaraff[z1],i,covar[Tvaraff[z1]][i],j1,z1,codtabm(j1,z1),
                   4863:                     j1,z1,nbcode[Tvaraff[z1]][codtabm(j1,z1)],j1);*/
                   4864:                  /* For j1=7 in V1+V2+V3+V4 = 0 1 1 0 and codtabm(7,3)=1 and nbcde[3][?]=1*/
                   4865:                } /* Onlyf fixed */
                   4866:              } /* end z1 */
                   4867:            } /* cptcovn > 0 */
                   4868:          } /* end any */
                   4869:        }/* end j==0 */
1.265     brouard  4870:        if (bool==1){ /* We selected an individual iind satisfying combination j1 (V4=1 V3=0) or all fixed covariates */
1.251     brouard  4871:          /* for(m=firstpass; m<=lastpass; m++){ */
1.284     brouard  4872:          for(mi=1; mi<wav[iind];mi++){ /* For each wave */
1.251     brouard  4873:            m=mw[mi][iind];
                   4874:            if(j!=0){
                   4875:              if(anyvaryingduminmodel==1){ /* Some are varying covariates */
                   4876:                for (z1=1; z1<=cptcoveff; z1++) {
                   4877:                  if( Fixed[Tmodelind[z1]]==1){
                   4878:                    iv= Tvar[Tmodelind[z1]]-ncovcol-nqv;
                   4879:                    if (cotvar[m][iv][iind]!= nbcode[Tvaraff[z1]][codtabm(j1,z1)]) /* iv=1 to ntv, right modality. If covariate's 
                   4880:                                                                                      value is -1, we don't select. It differs from the 
                   4881:                                                                                      constant and age model which counts them. */
                   4882:                      bool=0; /* not selected */
                   4883:                  }else if( Fixed[Tmodelind[z1]]== 0) { /* fixed */
                   4884:                    if (covar[Tvaraff[z1]][iind]!= nbcode[Tvaraff[z1]][codtabm(j1,z1)]) {
                   4885:                      bool=0;
                   4886:                    }
                   4887:                  }
                   4888:                }
                   4889:              }/* Some are varying covariates, we tried to speed up if all fixed covariates in the model, avoiding waves loop  */
                   4890:            } /* end j==0 */
                   4891:            /* bool =0 we keep that guy which corresponds to the combination of dummy values */
1.284     brouard  4892:            if(bool==1){ /*Selected */
1.251     brouard  4893:              /* dh[m][iind] or dh[mw[mi][iind]][iind] is the delay between two effective (mi) waves m=mw[mi][iind]
                   4894:                 and mw[mi+1][iind]. dh depends on stepm. */
                   4895:              agebegin=agev[m][iind]; /* Age at beginning of wave before transition*/
                   4896:              ageend=agev[m][iind]+(dh[m][iind])*stepm/YEARM; /* Age at end of wave and transition */
                   4897:              if(m >=firstpass && m <=lastpass){
                   4898:                k2=anint[m][iind]+(mint[m][iind]/12.);
                   4899:                /*if ((k2>=dateprev1) && (k2<=dateprev2)) {*/
                   4900:                if(agev[m][iind]==0) agev[m][iind]=iagemax+1;  /* All ages equal to 0 are in iagemax+1 */
                   4901:                if(agev[m][iind]==1) agev[m][iind]=iagemax+2;  /* All ages equal to 1 are in iagemax+2 */
                   4902:                if (s[m][iind]>0 && s[m][iind]<=nlstate)  /* If status at wave m is known and a live state */
                   4903:                  prop[s[m][iind]][(int)agev[m][iind]] += weight[iind];  /* At age of beginning of transition, where status is known */
                   4904:                if (m<lastpass) {
                   4905:                  /* if(s[m][iind]==4 && s[m+1][iind]==4) */
                   4906:                  /*   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]); */
                   4907:                  if(s[m][iind]==-1)
                   4908:                    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.));
                   4909:                  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.311     brouard  4910:                  for (z1=1; z1<= nqfveff; z1++) { /* Quantitative variables, calculating mean on known values only */
                   4911:                    if(!isnan(covar[ncovcol+z1][iind])){
                   4912:                        idq[z1]=idq[z1]+weight[iind];
                   4913:                        meanq[z1]+=covar[ncovcol+z1][iind]*weight[iind];  /* Computes mean of quantitative with selected filter */
                   4914:                        /* stdq[z1]+=covar[ncovcol+z1][iind]*covar[ncovcol+z1][iind]*weight[iind]*weight[iind]; *//*error*/
                   4915:                        stdq[z1]+=covar[ncovcol+z1][iind]*covar[ncovcol+z1][iind]*weight[iind]; /* *weight[iind];*/  /* Computes mean of quantitative with selected filter */
                   4916:                    }
1.284     brouard  4917:                  }
1.251     brouard  4918:                  /* if((int)agev[m][iind] == 55) */
                   4919:                  /*   printf("j=%d, j1=%d Age %d, iind=%d, num=%09ld m=%d\n",j,j1,(int)agev[m][iind],iind, num[iind],m); */
                   4920:                  /* freq[s[m][iind]][s[m+1][iind]][(int)((agebegin+ageend)/2.)] += weight[iind]; */
                   4921:                  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  4922:                }
1.251     brouard  4923:              } /* end if between passes */  
                   4924:              if ((agev[m][iind]>1) && (agev[m][iind]< (iagemax+3)) && (anint[m][iind]!=9999) && (mint[m][iind]!=99) && (j==0)) {
                   4925:                dateintsum=dateintsum+k2; /* on all covariates ?*/
                   4926:                k2cpt++;
                   4927:                /* printf("iind=%ld dateintmean = %lf dateintsum=%lf k2cpt=%lf k2=%lf\n",iind, dateintsum/k2cpt, dateintsum,k2cpt, k2); */
1.234     brouard  4928:              }
1.251     brouard  4929:            }else{
                   4930:              bool=1;
                   4931:            }/* end bool 2 */
                   4932:          } /* end m */
1.284     brouard  4933:          /* for (z1=1; z1<= nqfveff; z1++) { /\* Quantitative variables, calculating mean *\/ */
                   4934:          /*   idq[z1]=idq[z1]+weight[iind]; */
                   4935:          /*   meanq[z1]+=covar[ncovcol+z1][iind]*weight[iind];  /\* Computes mean of quantitative with selected filter *\/ */
                   4936:          /*   stdq[z1]+=covar[ncovcol+z1][iind]*covar[ncovcol+z1][iind]*weight[iind]*weight[iind]; /\* *weight[iind];*\/  /\* Computes mean of quantitative with selected filter *\/ */
                   4937:          /* } */
1.251     brouard  4938:        } /* end bool */
                   4939:       } /* end iind = 1 to imx */
1.319     brouard  4940:       /* prop[s][age] is fed for any initial and valid live state as well as
1.251     brouard  4941:         freq[s1][s2][age] at single age of beginning the transition, for a combination j1 */
                   4942:       
                   4943:       
                   4944:       /*      fprintf(ficresp, "#Count between %.lf/%.lf/%.lf and %.lf/%.lf/%.lf\n",jprev1, mprev1,anprev1,jprev2, mprev2,anprev2);*/
1.265     brouard  4945:       if(cptcoveff==0 && nj==1) /* no covariate and first pass */
                   4946:         pstamp(ficresp);
1.251     brouard  4947:       if  (cptcoveff>0 && j!=0){
1.265     brouard  4948:         pstamp(ficresp);
1.251     brouard  4949:        printf( "\n#********** Variable "); 
                   4950:        fprintf(ficresp, "\n#********** Variable "); 
                   4951:        fprintf(ficresphtm, "\n<br/><br/><h3>********** Variable "); 
                   4952:        fprintf(ficresphtmfr, "\n<br/><br/><h3>********** Variable "); 
                   4953:        fprintf(ficlog, "\n#********** Variable "); 
                   4954:        for (z1=1; z1<=cptcoveff; z1++){
                   4955:          if(!FixedV[Tvaraff[z1]]){
                   4956:            printf( "V%d(fixed)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
                   4957:            fprintf(ficresp, "V%d(fixed)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
                   4958:            fprintf(ficresphtm, "V%d(fixed)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
                   4959:            fprintf(ficresphtmfr, "V%d(fixed)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
                   4960:            fprintf(ficlog, "V%d(fixed)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
1.250     brouard  4961:          }else{
1.251     brouard  4962:            printf( "V%d(varying)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
                   4963:            fprintf(ficresp, "V%d(varying)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
                   4964:            fprintf(ficresphtm, "V%d(varying)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
                   4965:            fprintf(ficresphtmfr, "V%d(varying)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
                   4966:            fprintf(ficlog, "V%d(varying)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
                   4967:          }
                   4968:        }
                   4969:        printf( "**********\n#");
                   4970:        fprintf(ficresp, "**********\n#");
                   4971:        fprintf(ficresphtm, "**********</h3>\n");
                   4972:        fprintf(ficresphtmfr, "**********</h3>\n");
                   4973:        fprintf(ficlog, "**********\n");
                   4974:       }
1.284     brouard  4975:       /*
                   4976:        Printing means of quantitative variables if any
                   4977:       */
                   4978:       for (z1=1; z1<= nqfveff; z1++) {
1.311     brouard  4979:        fprintf(ficlog,"Mean of fixed quantitative variable V%d on %.3g (weighted) individuals sum=%f", ncovcol+z1, idq[z1], meanq[z1]);
1.312     brouard  4980:        fprintf(ficlog,", mean=%.3g\n",meanq[z1]/idq[z1]);
1.284     brouard  4981:        if(weightopt==1){
                   4982:          printf(" Weighted mean and standard deviation of");
                   4983:          fprintf(ficlog," Weighted mean and standard deviation of");
                   4984:          fprintf(ficresphtmfr," Weighted mean and standard deviation of");
                   4985:        }
1.311     brouard  4986:        /* mu = \frac{w x}{\sum w}
                   4987:            var = \frac{\sum w (x-mu)^2}{\sum w} = \frac{w x^2}{\sum w} - mu^2 
                   4988:        */
                   4989:        printf(" fixed quantitative variable V%d on  %.3g (weighted) representatives of the population : %8.5g (%8.5g)\n", ncovcol+z1, idq[z1],meanq[z1]/idq[z1], sqrt(stdq[z1]/idq[z1]-meanq[z1]*meanq[z1]/idq[z1]/idq[z1]));
                   4990:        fprintf(ficlog," fixed quantitative variable V%d on  %.3g (weighted) representatives of the population : %8.5g (%8.5g)\n", ncovcol+z1, idq[z1],meanq[z1]/idq[z1], sqrt(stdq[z1]/idq[z1]-meanq[z1]*meanq[z1]/idq[z1]/idq[z1]));
                   4991:        fprintf(ficresphtmfr," fixed quantitative variable V%d on %.3g (weighted) representatives of the population : %8.5g (%8.5g)<p>\n", ncovcol+z1, idq[z1],meanq[z1]/idq[z1], sqrt(stdq[z1]/idq[z1]-meanq[z1]*meanq[z1]/idq[z1]/idq[z1]));
1.284     brouard  4992:       }
                   4993:       /* for (z1=1; z1<= nqtveff; z1++) { */
                   4994:       /*       for(m=1;m<=lastpass;m++){ */
                   4995:       /*         fprintf(ficresphtmfr,"V quantitative id %d, pass id=%d, mean=%f<p>\n", z1, m, meanqt[m][z1]); */
                   4996:       /*   } */
                   4997:       /* } */
1.283     brouard  4998: 
1.251     brouard  4999:       fprintf(ficresphtm,"<table style=\"text-align:center; border: 1px solid\">");
1.265     brouard  5000:       if((cptcoveff==0 && nj==1)|| nj==2 ) /* no covariate and first pass */
                   5001:         fprintf(ficresp, " Age");
                   5002:       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  5003:       for(i=1; i<=nlstate;i++) {
1.265     brouard  5004:        if((cptcoveff==0 && nj==1)|| nj==2 ) fprintf(ficresp," Prev(%d)  N(%d)  N  ",i,i);
1.251     brouard  5005:        fprintf(ficresphtm, "<th>Age</th><th>Prev(%d)</th><th>N(%d)</th><th>N</th>",i,i);
                   5006:       }
1.265     brouard  5007:       if((cptcoveff==0 && nj==1)|| nj==2 ) fprintf(ficresp, "\n");
1.251     brouard  5008:       fprintf(ficresphtm, "\n");
                   5009:       
                   5010:       /* Header of frequency table by age */
                   5011:       fprintf(ficresphtmfr,"<table style=\"text-align:center; border: 1px solid\">");
                   5012:       fprintf(ficresphtmfr,"<th>Age</th> ");
1.265     brouard  5013:       for(s2=-1; s2 <=nlstate+ndeath; s2++){
1.251     brouard  5014:        for(m=-1; m <=nlstate+ndeath; m++){
1.265     brouard  5015:          if(s2!=0 && m!=0)
                   5016:            fprintf(ficresphtmfr,"<th>%d%d</th> ",s2,m);
1.240     brouard  5017:        }
1.226     brouard  5018:       }
1.251     brouard  5019:       fprintf(ficresphtmfr, "\n");
                   5020:     
                   5021:       /* For each age */
                   5022:       for(iage=iagemin; iage <= iagemax+3; iage++){
                   5023:        fprintf(ficresphtm,"<tr>");
                   5024:        if(iage==iagemax+1){
                   5025:          fprintf(ficlog,"1");
                   5026:          fprintf(ficresphtmfr,"<tr><th>0</th> ");
                   5027:        }else if(iage==iagemax+2){
                   5028:          fprintf(ficlog,"0");
                   5029:          fprintf(ficresphtmfr,"<tr><th>Unknown</th> ");
                   5030:        }else if(iage==iagemax+3){
                   5031:          fprintf(ficlog,"Total");
                   5032:          fprintf(ficresphtmfr,"<tr><th>Total</th> ");
                   5033:        }else{
1.240     brouard  5034:          if(first==1){
1.251     brouard  5035:            first=0;
                   5036:            printf("See log file for details...\n");
                   5037:          }
                   5038:          fprintf(ficresphtmfr,"<tr><th>%d</th> ",iage);
                   5039:          fprintf(ficlog,"Age %d", iage);
                   5040:        }
1.265     brouard  5041:        for(s1=1; s1 <=nlstate ; s1++){
                   5042:          for(m=-1, pp[s1]=0; m <=nlstate+ndeath ; m++)
                   5043:            pp[s1] += freq[s1][m][iage]; 
1.251     brouard  5044:        }
1.265     brouard  5045:        for(s1=1; s1 <=nlstate ; s1++){
1.251     brouard  5046:          for(m=-1, pos=0; m <=0 ; m++)
1.265     brouard  5047:            pos += freq[s1][m][iage];
                   5048:          if(pp[s1]>=1.e-10){
1.251     brouard  5049:            if(first==1){
1.265     brouard  5050:              printf(" %d.=%.0f loss[%d]=%.1f%%",s1,pp[s1],s1,100*pos/pp[s1]);
1.251     brouard  5051:            }
1.265     brouard  5052:            fprintf(ficlog," %d.=%.0f loss[%d]=%.1f%%",s1,pp[s1],s1,100*pos/pp[s1]);
1.251     brouard  5053:          }else{
                   5054:            if(first==1)
1.265     brouard  5055:              printf(" %d.=%.0f loss[%d]=NaNQ%%",s1,pp[s1],s1);
                   5056:            fprintf(ficlog," %d.=%.0f loss[%d]=NaNQ%%",s1,pp[s1],s1);
1.240     brouard  5057:          }
                   5058:        }
                   5059:       
1.265     brouard  5060:        for(s1=1; s1 <=nlstate ; s1++){ 
                   5061:          /* posprop[s1]=0; */
                   5062:          for(m=0, pp[s1]=0; m <=nlstate+ndeath; m++)/* Summing on all ages */
                   5063:            pp[s1] += freq[s1][m][iage];
                   5064:        }       /* pp[s1] is the total number of transitions starting from state s1 and any ending status until this age */
                   5065:       
                   5066:        for(s1=1,pos=0, pospropta=0.; s1 <=nlstate ; s1++){
                   5067:          pos += pp[s1]; /* pos is the total number of transitions until this age */
                   5068:          posprop[s1] += prop[s1][iage]; /* prop is the number of transitions from a live state
                   5069:                                            from s1 at age iage prop[s[m][iind]][(int)agev[m][iind]] += weight[iind] */
                   5070:          pospropta += prop[s1][iage]; /* prop is the number of transitions from a live state
                   5071:                                          from s1 at age iage prop[s[m][iind]][(int)agev[m][iind]] += weight[iind] */
                   5072:        }
                   5073:        
                   5074:        /* Writing ficresp */
                   5075:        if(cptcoveff==0 && nj==1){ /* no covariate and first pass */
                   5076:           if( iage <= iagemax){
                   5077:            fprintf(ficresp," %d",iage);
                   5078:           }
                   5079:         }else if( nj==2){
                   5080:           if( iage <= iagemax){
                   5081:            fprintf(ficresp," %d",iage);
                   5082:             for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresp, " %d %d",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
                   5083:           }
1.240     brouard  5084:        }
1.265     brouard  5085:        for(s1=1; s1 <=nlstate ; s1++){
1.240     brouard  5086:          if(pos>=1.e-5){
1.251     brouard  5087:            if(first==1)
1.265     brouard  5088:              printf(" %d.=%.0f prev[%d]=%.1f%%",s1,pp[s1],s1,100*pp[s1]/pos);
                   5089:            fprintf(ficlog," %d.=%.0f prev[%d]=%.1f%%",s1,pp[s1],s1,100*pp[s1]/pos);
1.251     brouard  5090:          }else{
                   5091:            if(first==1)
1.265     brouard  5092:              printf(" %d.=%.0f prev[%d]=NaNQ%%",s1,pp[s1],s1);
                   5093:            fprintf(ficlog," %d.=%.0f prev[%d]=NaNQ%%",s1,pp[s1],s1);
1.251     brouard  5094:          }
                   5095:          if( iage <= iagemax){
                   5096:            if(pos>=1.e-5){
1.265     brouard  5097:              if(cptcoveff==0 && nj==1){ /* no covariate and first pass */
                   5098:                fprintf(ficresp," %.5f %.0f %.0f",prop[s1][iage]/pospropta, prop[s1][iage],pospropta);
                   5099:               }else if( nj==2){
                   5100:                fprintf(ficresp," %.5f %.0f %.0f",prop[s1][iage]/pospropta, prop[s1][iage],pospropta);
                   5101:               }
                   5102:              fprintf(ficresphtm,"<th>%d</th><td>%.5f</td><td>%.0f</td><td>%.0f</td>",iage,prop[s1][iage]/pospropta, prop[s1][iage],pospropta);
                   5103:              /*probs[iage][s1][j1]= pp[s1]/pos;*/
                   5104:              /*printf("\niage=%d s1=%d j1=%d %.5f %.0f %.0f %f",iage,s1,j1,pp[s1]/pos, pp[s1],pos,probs[iage][s1][j1]);*/
                   5105:            } else{
                   5106:              if((cptcoveff==0 && nj==1)|| nj==2 ) fprintf(ficresp," NaNq %.0f %.0f",prop[s1][iage],pospropta);
                   5107:              fprintf(ficresphtm,"<th>%d</th><td>NaNq</td><td>%.0f</td><td>%.0f</td>",iage, prop[s1][iage],pospropta);
1.251     brouard  5108:            }
1.240     brouard  5109:          }
1.265     brouard  5110:          pospropt[s1] +=posprop[s1];
                   5111:        } /* end loop s1 */
1.251     brouard  5112:        /* pospropt=0.; */
1.265     brouard  5113:        for(s1=-1; s1 <=nlstate+ndeath; s1++){
1.251     brouard  5114:          for(m=-1; m <=nlstate+ndeath; m++){
1.265     brouard  5115:            if(freq[s1][m][iage] !=0 ) { /* minimizing output */
1.251     brouard  5116:              if(first==1){
1.265     brouard  5117:                printf(" %d%d=%.0f",s1,m,freq[s1][m][iage]);
1.251     brouard  5118:              }
1.265     brouard  5119:              /* printf(" %d%d=%.0f",s1,m,freq[s1][m][iage]); */
                   5120:              fprintf(ficlog," %d%d=%.0f",s1,m,freq[s1][m][iage]);
1.251     brouard  5121:            }
1.265     brouard  5122:            if(s1!=0 && m!=0)
                   5123:              fprintf(ficresphtmfr,"<td>%.0f</td> ",freq[s1][m][iage]);
1.240     brouard  5124:          }
1.265     brouard  5125:        } /* end loop s1 */
1.251     brouard  5126:        posproptt=0.; 
1.265     brouard  5127:        for(s1=1; s1 <=nlstate; s1++){
                   5128:          posproptt += pospropt[s1];
1.251     brouard  5129:        }
                   5130:        fprintf(ficresphtmfr,"</tr>\n ");
1.265     brouard  5131:        fprintf(ficresphtm,"</tr>\n");
                   5132:        if((cptcoveff==0 && nj==1)|| nj==2 ) {
                   5133:          if(iage <= iagemax)
                   5134:            fprintf(ficresp,"\n");
1.240     brouard  5135:        }
1.251     brouard  5136:        if(first==1)
                   5137:          printf("Others in log...\n");
                   5138:        fprintf(ficlog,"\n");
                   5139:       } /* end loop age iage */
1.265     brouard  5140:       
1.251     brouard  5141:       fprintf(ficresphtm,"<tr><th>Tot</th>");
1.265     brouard  5142:       for(s1=1; s1 <=nlstate ; s1++){
1.251     brouard  5143:        if(posproptt < 1.e-5){
1.265     brouard  5144:          fprintf(ficresphtm,"<td>Nanq</td><td>%.0f</td><td>%.0f</td>",pospropt[s1],posproptt); 
1.251     brouard  5145:        }else{
1.265     brouard  5146:          fprintf(ficresphtm,"<td>%.5f</td><td>%.0f</td><td>%.0f</td>",pospropt[s1]/posproptt,pospropt[s1],posproptt);  
1.240     brouard  5147:        }
1.226     brouard  5148:       }
1.251     brouard  5149:       fprintf(ficresphtm,"</tr>\n");
                   5150:       fprintf(ficresphtm,"</table>\n");
                   5151:       fprintf(ficresphtmfr,"</table>\n");
1.226     brouard  5152:       if(posproptt < 1.e-5){
1.251     brouard  5153:        fprintf(ficresphtm,"\n <p><b> This combination (%d) is not valid and no result will be produced</b></p>",j1);
                   5154:        fprintf(ficresphtmfr,"\n <p><b> This combination (%d) is not valid and no result will be produced</b></p>",j1);
1.260     brouard  5155:        fprintf(ficlog,"#  This combination (%d) is not valid and no result will be produced\n",j1);
                   5156:        printf("#  This combination (%d) is not valid and no result will be produced\n",j1);
1.251     brouard  5157:        invalidvarcomb[j1]=1;
1.226     brouard  5158:       }else{
1.251     brouard  5159:        fprintf(ficresphtm,"\n <p> This combination (%d) is valid and result will be produced.</p>",j1);
                   5160:        invalidvarcomb[j1]=0;
1.226     brouard  5161:       }
1.251     brouard  5162:       fprintf(ficresphtmfr,"</table>\n");
                   5163:       fprintf(ficlog,"\n");
                   5164:       if(j!=0){
                   5165:        printf("#Freqsummary: Starting values for combination j1=%d:\n", j1);
1.265     brouard  5166:        for(i=1,s1=1; i <=nlstate; i++){
1.251     brouard  5167:          for(k=1; k <=(nlstate+ndeath); k++){
                   5168:            if (k != i) {
1.265     brouard  5169:              for(jj=1; jj <=ncovmodel; jj++){ /* For counting s1 */
1.253     brouard  5170:                if(jj==1){  /* Constant case (in fact cste + age) */
1.251     brouard  5171:                  if(j1==1){ /* All dummy covariates to zero */
                   5172:                    freq[i][k][iagemax+4]=freq[i][k][iagemax+3]; /* Stores case 0 0 0 */
                   5173:                    freq[i][i][iagemax+4]=freq[i][i][iagemax+3]; /* Stores case 0 0 0 */
1.252     brouard  5174:                    printf("%d%d ",i,k);
                   5175:                    fprintf(ficlog,"%d%d ",i,k);
1.265     brouard  5176:                    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]));
                   5177:                    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]));
                   5178:                    pstart[s1]= log(freq[i][k][iagemax+3]/freq[i][i][iagemax+3]);
1.251     brouard  5179:                  }
1.253     brouard  5180:                }else if((j1==1) && (jj==2 || nagesqr==1)){ /* age or age*age parameter without covariate V4*age (to be done later) */
                   5181:                  for(iage=iagemin; iage <= iagemax+3; iage++){
                   5182:                    x[iage]= (double)iage;
                   5183:                    y[iage]= log(freq[i][k][iage]/freq[i][i][iage]);
1.265     brouard  5184:                    /* 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  5185:                  }
1.268     brouard  5186:                  /* Some are not finite, but linreg will ignore these ages */
                   5187:                  no=0;
1.253     brouard  5188:                  linreg(iagemin,iagemax,&no,x,y,&a,&b,&r, &sa, &sb ); /* y= a+b*x with standard errors */
1.265     brouard  5189:                  pstart[s1]=b;
                   5190:                  pstart[s1-1]=a;
1.252     brouard  5191:                }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 */ 
                   5192:                  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]);
                   5193:                  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  5194:                  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  5195:                  printf("%d%d ",i,k);
                   5196:                  fprintf(ficlog,"%d%d ",i,k);
1.265     brouard  5197:                  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  5198:                }else{ /* Other cases, like quantitative fixed or varying covariates */
                   5199:                  ;
                   5200:                }
                   5201:                /* printf("%12.7f )", param[i][jj][k]); */
                   5202:                /* fprintf(ficlog,"%12.7f )", param[i][jj][k]); */
1.265     brouard  5203:                s1++; 
1.251     brouard  5204:              } /* end jj */
                   5205:            } /* end k!= i */
                   5206:          } /* end k */
1.265     brouard  5207:        } /* end i, s1 */
1.251     brouard  5208:       } /* end j !=0 */
                   5209:     } /* end selected combination of covariate j1 */
                   5210:     if(j==0){ /* We can estimate starting values from the occurences in each case */
                   5211:       printf("#Freqsummary: Starting values for the constants:\n");
                   5212:       fprintf(ficlog,"\n");
1.265     brouard  5213:       for(i=1,s1=1; i <=nlstate; i++){
1.251     brouard  5214:        for(k=1; k <=(nlstate+ndeath); k++){
                   5215:          if (k != i) {
                   5216:            printf("%d%d ",i,k);
                   5217:            fprintf(ficlog,"%d%d ",i,k);
                   5218:            for(jj=1; jj <=ncovmodel; jj++){
1.265     brouard  5219:              pstart[s1]=p[s1]; /* Setting pstart to p values by default */
1.253     brouard  5220:              if(jj==1){ /* Age has to be done */
1.265     brouard  5221:                pstart[s1]= log(freq[i][k][iagemax+3]/freq[i][i][iagemax+3]);
                   5222:                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]));
                   5223:                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  5224:              }
                   5225:              /* printf("%12.7f )", param[i][jj][k]); */
                   5226:              /* fprintf(ficlog,"%12.7f )", param[i][jj][k]); */
1.265     brouard  5227:              s1++; 
1.250     brouard  5228:            }
1.251     brouard  5229:            printf("\n");
                   5230:            fprintf(ficlog,"\n");
1.250     brouard  5231:          }
                   5232:        }
1.284     brouard  5233:       } /* end of state i */
1.251     brouard  5234:       printf("#Freqsummary\n");
                   5235:       fprintf(ficlog,"\n");
1.265     brouard  5236:       for(s1=-1; s1 <=nlstate+ndeath; s1++){
                   5237:        for(s2=-1; s2 <=nlstate+ndeath; s2++){
                   5238:          /* param[i]|j][k]= freq[s1][s2][iagemax+3] */
                   5239:          printf(" %d%d=%.0f",s1,s2,freq[s1][s2][iagemax+3]);
                   5240:          fprintf(ficlog," %d%d=%.0f",s1,s2,freq[s1][s2][iagemax+3]);
                   5241:          /* if(freq[s1][s2][iage] !=0 ) { /\* minimizing output *\/ */
                   5242:          /*   printf(" %d%d=%.0f",s1,s2,freq[s1][s2][iagemax+3]); */
                   5243:          /*   fprintf(ficlog," %d%d=%.0f",s1,s2,freq[s1][s2][iagemax+3]); */
1.251     brouard  5244:          /* } */
                   5245:        }
1.265     brouard  5246:       } /* end loop s1 */
1.251     brouard  5247:       
                   5248:       printf("\n");
                   5249:       fprintf(ficlog,"\n");
                   5250:     } /* end j=0 */
1.249     brouard  5251:   } /* end j */
1.252     brouard  5252: 
1.253     brouard  5253:   if(mle == -2){  /* We want to use these values as starting values */
1.252     brouard  5254:     for(i=1, jk=1; i <=nlstate; i++){
                   5255:       for(j=1; j <=nlstate+ndeath; j++){
                   5256:        if(j!=i){
                   5257:          /*ca[0]= k+'a'-1;ca[1]='\0';*/
                   5258:          printf("%1d%1d",i,j);
                   5259:          fprintf(ficparo,"%1d%1d",i,j);
                   5260:          for(k=1; k<=ncovmodel;k++){
                   5261:            /*    printf(" %lf",param[i][j][k]); */
                   5262:            /*    fprintf(ficparo," %lf",param[i][j][k]); */
                   5263:            p[jk]=pstart[jk];
                   5264:            printf(" %f ",pstart[jk]);
                   5265:            fprintf(ficparo," %f ",pstart[jk]);
                   5266:            jk++;
                   5267:          }
                   5268:          printf("\n");
                   5269:          fprintf(ficparo,"\n");
                   5270:        }
                   5271:       }
                   5272:     }
                   5273:   } /* end mle=-2 */
1.226     brouard  5274:   dateintmean=dateintsum/k2cpt; 
1.296     brouard  5275:   date2dmy(dateintmean,&jintmean,&mintmean,&aintmean);
1.240     brouard  5276:   
1.226     brouard  5277:   fclose(ficresp);
                   5278:   fclose(ficresphtm);
                   5279:   fclose(ficresphtmfr);
1.283     brouard  5280:   free_vector(idq,1,nqfveff);
1.226     brouard  5281:   free_vector(meanq,1,nqfveff);
1.284     brouard  5282:   free_vector(stdq,1,nqfveff);
1.226     brouard  5283:   free_matrix(meanqt,1,lastpass,1,nqtveff);
1.253     brouard  5284:   free_vector(x, iagemin-AGEMARGE, iagemax+4+AGEMARGE);
                   5285:   free_vector(y, iagemin-AGEMARGE, iagemax+4+AGEMARGE);
1.251     brouard  5286:   free_ma3x(freq,-5,nlstate+ndeath,-5,nlstate+ndeath, iagemin-AGEMARGE, iagemax+4+AGEMARGE);
1.226     brouard  5287:   free_vector(pospropt,1,nlstate);
                   5288:   free_vector(posprop,1,nlstate);
1.251     brouard  5289:   free_matrix(prop,1,nlstate,iagemin-AGEMARGE, iagemax+4+AGEMARGE);
1.226     brouard  5290:   free_vector(pp,1,nlstate);
                   5291:   /* End of freqsummary */
                   5292: }
1.126     brouard  5293: 
1.268     brouard  5294: /* Simple linear regression */
                   5295: int linreg(int ifi, int ila, int *no, const double x[], const double y[], double* a, double* b, double* r, double* sa, double * sb) {
                   5296: 
                   5297:   /* y=a+bx regression */
                   5298:   double   sumx = 0.0;                        /* sum of x                      */
                   5299:   double   sumx2 = 0.0;                       /* sum of x**2                   */
                   5300:   double   sumxy = 0.0;                       /* sum of x * y                  */
                   5301:   double   sumy = 0.0;                        /* sum of y                      */
                   5302:   double   sumy2 = 0.0;                       /* sum of y**2                   */
                   5303:   double   sume2 = 0.0;                       /* sum of square or residuals */
                   5304:   double yhat;
                   5305:   
                   5306:   double denom=0;
                   5307:   int i;
                   5308:   int ne=*no;
                   5309:   
                   5310:   for ( i=ifi, ne=0;i<=ila;i++) {
                   5311:     if(!isfinite(x[i]) || !isfinite(y[i])){
                   5312:       /* printf(" x[%d]=%f, y[%d]=%f\n",i,x[i],i,y[i]); */
                   5313:       continue;
                   5314:     }
                   5315:     ne=ne+1;
                   5316:     sumx  += x[i];       
                   5317:     sumx2 += x[i]*x[i];  
                   5318:     sumxy += x[i] * y[i];
                   5319:     sumy  += y[i];      
                   5320:     sumy2 += y[i]*y[i]; 
                   5321:     denom = (ne * sumx2 - sumx*sumx);
                   5322:     /* 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); */
                   5323:   } 
                   5324:   
                   5325:   denom = (ne * sumx2 - sumx*sumx);
                   5326:   if (denom == 0) {
                   5327:     // vertical, slope m is infinity
                   5328:     *b = INFINITY;
                   5329:     *a = 0;
                   5330:     if (r) *r = 0;
                   5331:     return 1;
                   5332:   }
                   5333:   
                   5334:   *b = (ne * sumxy  -  sumx * sumy) / denom;
                   5335:   *a = (sumy * sumx2  -  sumx * sumxy) / denom;
                   5336:   if (r!=NULL) {
                   5337:     *r = (sumxy - sumx * sumy / ne) /          /* compute correlation coeff     */
                   5338:       sqrt((sumx2 - sumx*sumx/ne) *
                   5339:           (sumy2 - sumy*sumy/ne));
                   5340:   }
                   5341:   *no=ne;
                   5342:   for ( i=ifi, ne=0;i<=ila;i++) {
                   5343:     if(!isfinite(x[i]) || !isfinite(y[i])){
                   5344:       /* printf(" x[%d]=%f, y[%d]=%f\n",i,x[i],i,y[i]); */
                   5345:       continue;
                   5346:     }
                   5347:     ne=ne+1;
                   5348:     yhat = y[i] - *a -*b* x[i];
                   5349:     sume2  += yhat * yhat ;       
                   5350:     
                   5351:     denom = (ne * sumx2 - sumx*sumx);
                   5352:     /* 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); */
                   5353:   } 
                   5354:   *sb = sqrt(sume2/(double)(ne-2)/(sumx2 - sumx * sumx /(double)ne));
                   5355:   *sa= *sb * sqrt(sumx2/ne);
                   5356:   
                   5357:   return 0; 
                   5358: }
                   5359: 
1.126     brouard  5360: /************ Prevalence ********************/
1.227     brouard  5361: 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)
                   5362: {  
                   5363:   /* Compute observed prevalence between dateprev1 and dateprev2 by counting the number of people
                   5364:      in each health status at the date of interview (if between dateprev1 and dateprev2).
                   5365:      We still use firstpass and lastpass as another selection.
                   5366:   */
1.126     brouard  5367:  
1.227     brouard  5368:   int i, m, jk, j1, bool, z1,j, iv;
                   5369:   int mi; /* Effective wave */
                   5370:   int iage;
                   5371:   double agebegin, ageend;
                   5372: 
                   5373:   double **prop;
                   5374:   double posprop; 
                   5375:   double  y2; /* in fractional years */
                   5376:   int iagemin, iagemax;
                   5377:   int first; /** to stop verbosity which is redirected to log file */
                   5378: 
                   5379:   iagemin= (int) agemin;
                   5380:   iagemax= (int) agemax;
                   5381:   /*pp=vector(1,nlstate);*/
1.251     brouard  5382:   prop=matrix(1,nlstate,iagemin-AGEMARGE,iagemax+4+AGEMARGE); 
1.227     brouard  5383:   /*  freq=ma3x(-1,nlstate+ndeath,-1,nlstate+ndeath,iagemin,iagemax+3);*/
                   5384:   j1=0;
1.222     brouard  5385:   
1.227     brouard  5386:   /*j=cptcoveff;*/
                   5387:   if (cptcovn<1) {j=1;ncodemax[1]=1;}
1.222     brouard  5388:   
1.288     brouard  5389:   first=0;
1.227     brouard  5390:   for(j1=1; j1<= (int) pow(2,cptcoveff);j1++){ /* For each combination of covariate */
                   5391:     for (i=1; i<=nlstate; i++)  
1.251     brouard  5392:       for(iage=iagemin-AGEMARGE; iage <= iagemax+4+AGEMARGE; iage++)
1.227     brouard  5393:        prop[i][iage]=0.0;
                   5394:     printf("Prevalence combination of varying and fixed dummies %d\n",j1);
                   5395:     /* fprintf(ficlog," V%d=%d ",Tvaraff[j1],nbcode[Tvaraff[j1]][codtabm(k,j1)]); */
                   5396:     fprintf(ficlog,"Prevalence combination of varying and fixed dummies %d\n",j1);
                   5397:     
                   5398:     for (i=1; i<=imx; i++) { /* Each individual */
                   5399:       bool=1;
                   5400:       /* for(m=firstpass; m<=lastpass; m++){/\* Other selection (we can limit to certain interviews*\/ */
                   5401:       for(mi=1; mi<wav[i];mi++){ /* For this wave too look where individual can be counted V4=0 V3=0 */
                   5402:        m=mw[mi][i];
                   5403:        /* Tmodelind[z1]=k is the position of the varying covariate in the model, but which # within 1 to ntv? */
                   5404:        /* Tvar[Tmodelind[z1]] is the n of Vn; n-ncovcol-nqv is the first time varying covariate or iv */
                   5405:        for (z1=1; z1<=cptcoveff; z1++){
                   5406:          if( Fixed[Tmodelind[z1]]==1){
                   5407:            iv= Tvar[Tmodelind[z1]]-ncovcol-nqv;
                   5408:            if (cotvar[m][iv][i]!= nbcode[Tvaraff[z1]][codtabm(j1,z1)]) /* iv=1 to ntv, right modality */
                   5409:              bool=0;
                   5410:          }else if( Fixed[Tmodelind[z1]]== 0)  /* fixed */
                   5411:            if (covar[Tvaraff[z1]][i]!= nbcode[Tvaraff[z1]][codtabm(j1,z1)]) {
                   5412:              bool=0;
                   5413:            }
                   5414:        }
                   5415:        if(bool==1){ /* Otherwise we skip that wave/person */
                   5416:          agebegin=agev[m][i]; /* Age at beginning of wave before transition*/
                   5417:          /* ageend=agev[m][i]+(dh[m][i])*stepm/YEARM; /\* Age at end of wave and transition *\/ */
                   5418:          if(m >=firstpass && m <=lastpass){
                   5419:            y2=anint[m][i]+(mint[m][i]/12.); /* Fractional date in year */
                   5420:            if ((y2>=dateprev1) && (y2<=dateprev2)) { /* Here is the main selection (fractional years) */
                   5421:              if(agev[m][i]==0) agev[m][i]=iagemax+1;
                   5422:              if(agev[m][i]==1) agev[m][i]=iagemax+2;
1.251     brouard  5423:              if((int)agev[m][i] <iagemin-AGEMARGE || (int)agev[m][i] >iagemax+4+AGEMARGE){
1.227     brouard  5424:                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); 
                   5425:                exit(1);
                   5426:              }
                   5427:              if (s[m][i]>0 && s[m][i]<=nlstate) { 
                   5428:                /*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]]);*/
                   5429:                prop[s[m][i]][(int)agev[m][i]] += weight[i];/* At age of beginning of transition, where status is known */
                   5430:                prop[s[m][i]][iagemax+3] += weight[i]; 
                   5431:              } /* end valid statuses */ 
                   5432:            } /* end selection of dates */
                   5433:          } /* end selection of waves */
                   5434:        } /* end bool */
                   5435:       } /* end wave */
                   5436:     } /* end individual */
                   5437:     for(i=iagemin; i <= iagemax+3; i++){  
                   5438:       for(jk=1,posprop=0; jk <=nlstate ; jk++) { 
                   5439:        posprop += prop[jk][i]; 
                   5440:       } 
                   5441:       
                   5442:       for(jk=1; jk <=nlstate ; jk++){      
                   5443:        if( i <=  iagemax){ 
                   5444:          if(posprop>=1.e-5){ 
                   5445:            probs[i][jk][j1]= prop[jk][i]/posprop;
                   5446:          } else{
1.288     brouard  5447:            if(!first){
                   5448:              first=1;
1.266     brouard  5449:              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]);
                   5450:            }else{
1.288     brouard  5451:              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  5452:            }
                   5453:          }
                   5454:        } 
                   5455:       }/* end jk */ 
                   5456:     }/* end i */ 
1.222     brouard  5457:      /*} *//* end i1 */
1.227     brouard  5458:   } /* end j1 */
1.222     brouard  5459:   
1.227     brouard  5460:   /*  free_ma3x(freq,-1,nlstate+ndeath,-1,nlstate+ndeath, iagemin, iagemax+3);*/
                   5461:   /*free_vector(pp,1,nlstate);*/
1.251     brouard  5462:   free_matrix(prop,1,nlstate, iagemin-AGEMARGE,iagemax+4+AGEMARGE);
1.227     brouard  5463: }  /* End of prevalence */
1.126     brouard  5464: 
                   5465: /************* Waves Concatenation ***************/
                   5466: 
                   5467: 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)
                   5468: {
1.298     brouard  5469:   /* 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  5470:      Death is a valid wave (if date is known).
                   5471:      mw[mi][i] is the mi (mi=1 to wav[i])  effective wave of individual i
                   5472:      dh[m][i] or dh[mw[mi][i]][i] is the delay between two effective waves m=mw[mi][i]
1.298     brouard  5473:      and mw[mi+1][i]. dh depends on stepm. s[m][i] exists for any wave from firstpass to lastpass
1.227     brouard  5474:   */
1.126     brouard  5475: 
1.224     brouard  5476:   int i=0, mi=0, m=0, mli=0;
1.126     brouard  5477:   /* int j, k=0,jk, ju, jl,jmin=1e+5, jmax=-1;
                   5478:      double sum=0., jmean=0.;*/
1.224     brouard  5479:   int first=0, firstwo=0, firsthree=0, firstfour=0, firstfiv=0;
1.126     brouard  5480:   int j, k=0,jk, ju, jl;
                   5481:   double sum=0.;
                   5482:   first=0;
1.214     brouard  5483:   firstwo=0;
1.217     brouard  5484:   firsthree=0;
1.218     brouard  5485:   firstfour=0;
1.164     brouard  5486:   jmin=100000;
1.126     brouard  5487:   jmax=-1;
                   5488:   jmean=0.;
1.224     brouard  5489: 
                   5490: /* Treating live states */
1.214     brouard  5491:   for(i=1; i<=imx; i++){  /* For simple cases and if state is death */
1.224     brouard  5492:     mi=0;  /* First valid wave */
1.227     brouard  5493:     mli=0; /* Last valid wave */
1.309     brouard  5494:     m=firstpass;  /* Loop on waves */
                   5495:     while(s[m][i] <= nlstate){  /* a live state or unknown state  */
1.227     brouard  5496:       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 */
                   5497:        mli=m-1;/* mw[++mi][i]=m-1; */
                   5498:       }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 */
1.309     brouard  5499:        mw[++mi][i]=m; /* Valid wave: incrementing mi and updating mi; mw[mi] is the wave number of mi_th valid transition   */
1.227     brouard  5500:        mli=m;
1.224     brouard  5501:       } /* else might be a useless wave  -1 and mi is not incremented and mw[mi] not updated */
                   5502:       if(m < lastpass){ /* m < lastpass, standard case */
1.227     brouard  5503:        m++; /* mi gives the "effective" current wave, m the current wave, go to next wave by incrementing m */
1.216     brouard  5504:       }
1.309     brouard  5505:       else{ /* m = lastpass, eventual special issue with warning */
1.224     brouard  5506: #ifdef UNKNOWNSTATUSNOTCONTRIBUTING
1.227     brouard  5507:        break;
1.224     brouard  5508: #else
1.317     brouard  5509:        if(s[m][i]==-1 && (int) andc[i] == 9999 && (int)anint[m][i] != 9999){ /* no death date and known date of interview, case -2 (vital status unknown is warned later */
1.227     brouard  5510:          if(firsthree == 0){
1.302     brouard  5511:            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  5512:            firsthree=1;
1.317     brouard  5513:          }else if(firsthree >=1 && firsthree < 10){
                   5514:            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);
                   5515:            firsthree++;
                   5516:          }else if(firsthree == 10){
                   5517:            printf("Information, too many Information flags: no more reported to log either\n");
                   5518:            fprintf(ficlog,"Information, too many Information flags: no more reported to log either\n");
                   5519:            firsthree++;
                   5520:          }else{
                   5521:            firsthree++;
1.227     brouard  5522:          }
1.309     brouard  5523:          mw[++mi][i]=m; /* Valid transition with unknown status */
1.227     brouard  5524:          mli=m;
                   5525:        }
                   5526:        if(s[m][i]==-2){ /* Vital status is really unknown */
                   5527:          nbwarn++;
1.309     brouard  5528:          if((int)anint[m][i] == 9999){  /*  Has the vital status really been verified?not a transition */
1.227     brouard  5529:            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);
                   5530:            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);
                   5531:          }
                   5532:          break;
                   5533:        }
                   5534:        break;
1.224     brouard  5535: #endif
1.227     brouard  5536:       }/* End m >= lastpass */
1.126     brouard  5537:     }/* end while */
1.224     brouard  5538: 
1.227     brouard  5539:     /* 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  5540:     /* After last pass */
1.224     brouard  5541: /* Treating death states */
1.214     brouard  5542:     if (s[m][i] > nlstate){  /* In a death state */
1.227     brouard  5543:       /* if( mint[m][i]==mdc[m][i] && anint[m][i]==andc[m][i]){ /\* same date of death and date of interview *\/ */
                   5544:       /* } */
1.126     brouard  5545:       mi++;    /* Death is another wave */
                   5546:       /* if(mi==0)  never been interviewed correctly before death */
1.227     brouard  5547:       /* Only death is a correct wave */
1.126     brouard  5548:       mw[mi][i]=m;
1.257     brouard  5549:     } /* else not in a death state */
1.224     brouard  5550: #ifndef DISPATCHINGKNOWNDEATHAFTERLASTWAVE
1.257     brouard  5551:     else if ((int) andc[i] != 9999) {  /* Date of death is known */
1.218     brouard  5552:       if ((int)anint[m][i]!= 9999) { /* date of last interview is known */
1.309     brouard  5553:        if((andc[i]+moisdc[i]/12.) <=(anint[m][i]+mint[m][i]/12.)){ /* month of death occured before last wave month and status should have been death instead of -1 */
1.227     brouard  5554:          nbwarn++;
                   5555:          if(firstfiv==0){
1.309     brouard  5556:            printf("Warning! Death for individual %ld line=%d occurred at %d/%d before last wave %d, interviewed on %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 );
1.227     brouard  5557:            firstfiv=1;
                   5558:          }else{
1.309     brouard  5559:            fprintf(ficlog,"Warning! Death for individual %ld line=%d occurred at %d/%d before last wave %d, interviewed on %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 );
1.227     brouard  5560:          }
1.309     brouard  5561:            s[m][i]=nlstate+1; /* Fixing the status as death. Be careful if multiple death states */
                   5562:        }else{ /* Month of Death occured afer last wave month, potential bias */
1.227     brouard  5563:          nberr++;
                   5564:          if(firstwo==0){
1.309     brouard  5565:            printf("Error! Death for individual %ld line=%d occurred at %d/%d after last wave %d interviewed at %d/%d with status %d. Potential bias if other individuals are still alive on this date but ignored. This case (%d)/wave (%d) is skipped, no contribution to likelihood. Please add a new fictitious wave at the date of last vital status scan, with a dead status. 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], s[m][i], i,m );
1.227     brouard  5566:            firstwo=1;
                   5567:          }
1.309     brouard  5568:          fprintf(ficlog,"Error! Death for individual %ld line=%d occurred at %d/%d after last wave %d interviewed at %d/%d with status %d. Potential bias if other individuals are still alive on this date but ignored. This case (%d)/wave (%d) is skipped, no contribution to likelihood. Please add a new fictitious wave at the date of last vital status scan, with a dead status. See documentation\n\n",num[i],i,(int) moisdc[i], (int) andc[i], lastpass,(int)mint[m][i],(int)anint[m][i], s[m][i], i,m );
1.227     brouard  5569:        }
1.257     brouard  5570:       }else{ /* if date of interview is unknown */
1.227     brouard  5571:        /* death is known but not confirmed by death status at any wave */
                   5572:        if(firstfour==0){
1.309     brouard  5573:          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 with status %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], s[m][i], i,m );
1.227     brouard  5574:          firstfour=1;
                   5575:        }
1.309     brouard  5576:        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  with status %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], s[m][i], i,m );
1.214     brouard  5577:       }
1.224     brouard  5578:     } /* end if date of death is known */
                   5579: #endif
1.309     brouard  5580:     wav[i]=mi; /* mi should be the last effective wave (or mli),  */
                   5581:     /* wav[i]=mw[mi][i];   */
1.126     brouard  5582:     if(mi==0){
                   5583:       nbwarn++;
                   5584:       if(first==0){
1.227     brouard  5585:        printf("Warning! No valid information for individual %ld line=%d (skipped) and may be others, see log file\n",num[i],i);
                   5586:        first=1;
1.126     brouard  5587:       }
                   5588:       if(first==1){
1.227     brouard  5589:        fprintf(ficlog,"Warning! No valid information for individual %ld line=%d (skipped)\n",num[i],i);
1.126     brouard  5590:       }
                   5591:     } /* end mi==0 */
                   5592:   } /* End individuals */
1.214     brouard  5593:   /* wav and mw are no more changed */
1.223     brouard  5594:        
1.317     brouard  5595:   printf("Information, you have to check %d informations which haven't been logged!\n",firsthree);
                   5596:   fprintf(ficlog,"Information, you have to check %d informations which haven't been logged!\n",firsthree);
                   5597: 
                   5598: 
1.126     brouard  5599:   for(i=1; i<=imx; i++){
                   5600:     for(mi=1; mi<wav[i];mi++){
                   5601:       if (stepm <=0)
1.227     brouard  5602:        dh[mi][i]=1;
1.126     brouard  5603:       else{
1.260     brouard  5604:        if (s[mw[mi+1][i]][i] > nlstate) { /* A death, but what if date is unknown? */
1.227     brouard  5605:          if (agedc[i] < 2*AGESUP) {
                   5606:            j= rint(agedc[i]*12-agev[mw[mi][i]][i]*12); 
                   5607:            if(j==0) j=1;  /* Survives at least one month after exam */
                   5608:            else if(j<0){
                   5609:              nberr++;
                   5610:              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]);
                   5611:              j=1; /* Temporary Dangerous patch */
                   5612:              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);
                   5613:              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]);
                   5614:              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);
                   5615:            }
                   5616:            k=k+1;
                   5617:            if (j >= jmax){
                   5618:              jmax=j;
                   5619:              ijmax=i;
                   5620:            }
                   5621:            if (j <= jmin){
                   5622:              jmin=j;
                   5623:              ijmin=i;
                   5624:            }
                   5625:            sum=sum+j;
                   5626:            /*if (j<0) printf("j=%d num=%d \n",j,i);*/
                   5627:            /*    printf("%d %d %d %d\n", s[mw[mi][i]][i] ,s[mw[mi+1][i]][i],j,i);*/
                   5628:          }
                   5629:        }
                   5630:        else{
                   5631:          j= rint( (agev[mw[mi+1][i]][i]*12 - agev[mw[mi][i]][i]*12));
1.126     brouard  5632: /*       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  5633:                                        
1.227     brouard  5634:          k=k+1;
                   5635:          if (j >= jmax) {
                   5636:            jmax=j;
                   5637:            ijmax=i;
                   5638:          }
                   5639:          else if (j <= jmin){
                   5640:            jmin=j;
                   5641:            ijmin=i;
                   5642:          }
                   5643:          /*        if (j<10) printf("j=%d jmin=%d num=%d ",j,jmin,i); */
                   5644:          /*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]);*/
                   5645:          if(j<0){
                   5646:            nberr++;
                   5647:            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]);
                   5648:            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]);
                   5649:          }
                   5650:          sum=sum+j;
                   5651:        }
                   5652:        jk= j/stepm;
                   5653:        jl= j -jk*stepm;
                   5654:        ju= j -(jk+1)*stepm;
                   5655:        if(mle <=1){ /* only if we use a the linear-interpoloation pseudo-likelihood */
                   5656:          if(jl==0){
                   5657:            dh[mi][i]=jk;
                   5658:            bh[mi][i]=0;
                   5659:          }else{ /* We want a negative bias in order to only have interpolation ie
                   5660:                  * to avoid the price of an extra matrix product in likelihood */
                   5661:            dh[mi][i]=jk+1;
                   5662:            bh[mi][i]=ju;
                   5663:          }
                   5664:        }else{
                   5665:          if(jl <= -ju){
                   5666:            dh[mi][i]=jk;
                   5667:            bh[mi][i]=jl;       /* bias is positive if real duration
                   5668:                                 * is higher than the multiple of stepm and negative otherwise.
                   5669:                                 */
                   5670:          }
                   5671:          else{
                   5672:            dh[mi][i]=jk+1;
                   5673:            bh[mi][i]=ju;
                   5674:          }
                   5675:          if(dh[mi][i]==0){
                   5676:            dh[mi][i]=1; /* At least one step */
                   5677:            bh[mi][i]=ju; /* At least one step */
                   5678:            /*  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);*/
                   5679:          }
                   5680:        } /* end if mle */
1.126     brouard  5681:       }
                   5682:     } /* end wave */
                   5683:   }
                   5684:   jmean=sum/k;
                   5685:   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  5686:   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  5687: }
1.126     brouard  5688: 
                   5689: /*********** Tricode ****************************/
1.220     brouard  5690:  void tricode(int *cptcov, int *Tvar, int **nbcode, int imx, int *Ndum)
1.242     brouard  5691:  {
                   5692:    /**< Uses cptcovn+2*cptcovprod as the number of covariates */
                   5693:    /*    Tvar[i]=atoi(stre);  find 'n' in Vn and stores in Tvar. If model=V2+V1 Tvar[1]=2 and Tvar[2]=1 
                   5694:     * Boring subroutine which should only output nbcode[Tvar[j]][k]
                   5695:     * Tvar[5] in V2+V1+V3*age+V2*V4 is 4 (V4) even it is a time varying or quantitative variable
                   5696:     * nbcode[Tvar[5]][1]= nbcode[4][1]=0, nbcode[4][2]=1 (usually);
                   5697:     */
1.130     brouard  5698: 
1.242     brouard  5699:    int ij=1, k=0, j=0, i=0, maxncov=NCOVMAX;
                   5700:    int modmaxcovj=0; /* Modality max of covariates j */
                   5701:    int cptcode=0; /* Modality max of covariates j */
                   5702:    int modmincovj=0; /* Modality min of covariates j */
1.145     brouard  5703: 
                   5704: 
1.242     brouard  5705:    /* cptcoveff=0;  */
                   5706:    /* *cptcov=0; */
1.126     brouard  5707:  
1.242     brouard  5708:    for (k=1; k <= maxncov; k++) ncodemax[k]=0; /* Horrible constant again replaced by NCOVMAX */
1.285     brouard  5709:    for (k=1; k <= maxncov; k++)
                   5710:      for(j=1; j<=2; j++)
                   5711:        nbcode[k][j]=0; /* Valgrind */
1.126     brouard  5712: 
1.242     brouard  5713:    /* Loop on covariates without age and products and no quantitative variable */
                   5714:    for (k=1; k<=cptcovt; k++) { /* From model V1 + V2*age + V3 + V3*V4 keeps V1 + V3 = 2 only */
                   5715:      for (j=-1; (j < maxncov); j++) Ndum[j]=0;
                   5716:      if(Dummy[k]==0 && Typevar[k] !=1){ /* Dummy covariate and not age product */ 
                   5717:        switch(Fixed[k]) {
                   5718:        case 0: /* Testing on fixed dummy covariate, simple or product of fixed */
1.311     brouard  5719:         modmaxcovj=0;
                   5720:         modmincovj=0;
1.242     brouard  5721:         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*/
                   5722:           ij=(int)(covar[Tvar[k]][i]);
                   5723:           /* ij=0 or 1 or -1. Value of the covariate Tvar[j] for individual i
                   5724:            * If product of Vn*Vm, still boolean *:
                   5725:            * If it was coded 1, 2, 3, 4 should be splitted into 3 boolean variables
                   5726:            * 1 => 0 0 0, 2 => 0 0 1, 3 => 0 1 1, 4=1 0 0   */
                   5727:           /* Finds for covariate j, n=Tvar[j] of Vn . ij is the
                   5728:              modality of the nth covariate of individual i. */
                   5729:           if (ij > modmaxcovj)
                   5730:             modmaxcovj=ij; 
                   5731:           else if (ij < modmincovj) 
                   5732:             modmincovj=ij; 
1.287     brouard  5733:           if (ij <0 || ij >1 ){
1.311     brouard  5734:             printf("ERROR, IMaCh doesn't treat covariate with missing values V%d=-1, individual %d will be skipped.\n",Tvar[k],i);
                   5735:             fprintf(ficlog,"ERROR, currently IMaCh doesn't treat covariate with missing values V%d=-1, individual %d will be skipped.\n",Tvar[k],i);
                   5736:             fflush(ficlog);
                   5737:             exit(1);
1.287     brouard  5738:           }
                   5739:           if ((ij < -1) || (ij > NCOVMAX)){
1.242     brouard  5740:             printf( "Error: minimal is less than -1 or maximal is bigger than %d. Exiting. \n", NCOVMAX );
                   5741:             exit(1);
                   5742:           }else
                   5743:             Ndum[ij]++; /*counts and stores the occurence of this modality 0, 1, -1*/
                   5744:           /*  If coded 1, 2, 3 , counts the number of 1 Ndum[1], number of 2, Ndum[2], etc */
                   5745:           /*printf("i=%d ij=%d Ndum[ij]=%d imx=%d",i,ij,Ndum[ij],imx);*/
                   5746:           /* getting the maximum value of the modality of the covariate
                   5747:              (should be 0 or 1 now) Tvar[j]. If V=sex and male is coded 0 and
                   5748:              female ies 1, then modmaxcovj=1.
                   5749:           */
                   5750:         } /* end for loop on individuals i */
                   5751:         printf(" Minimal and maximal values of %d th (fixed) covariate V%d: min=%d max=%d \n", k, Tvar[k], modmincovj, modmaxcovj);
                   5752:         fprintf(ficlog," Minimal and maximal values of %d th (fixed) covariate V%d: min=%d max=%d \n", k, Tvar[k], modmincovj, modmaxcovj);
                   5753:         cptcode=modmaxcovj;
                   5754:         /* Ndum[0] = frequency of 0 for model-covariate j, Ndum[1] frequency of 1 etc. */
                   5755:         /*for (i=0; i<=cptcode; i++) {*/
                   5756:         for (j=modmincovj;  j<=modmaxcovj; j++) { /* j=-1 ? 0 and 1*//* For each value j of the modality of model-cov k */
                   5757:           printf("Frequencies of (fixed) covariate %d ie V%d with value %d: %d\n", k, Tvar[k], j, Ndum[j]);
                   5758:           fprintf(ficlog, "Frequencies of (fixed) covariate %d ie V%d with value %d: %d\n", k, Tvar[k], j, Ndum[j]);
                   5759:           if( Ndum[j] != 0 ){ /* Counts if nobody answered modality j ie empty modality, we skip it and reorder */
                   5760:             if( j != -1){
                   5761:               ncodemax[k]++;  /* ncodemax[k]= Number of modalities of the k th
                   5762:                                  covariate for which somebody answered excluding 
                   5763:                                  undefined. Usually 2: 0 and 1. */
                   5764:             }
                   5765:             ncodemaxwundef[k]++; /* ncodemax[j]= Number of modalities of the k th
                   5766:                                     covariate for which somebody answered including 
                   5767:                                     undefined. Usually 3: -1, 0 and 1. */
                   5768:           }    /* In fact  ncodemax[k]=2 (dichotom. variables only) but it could be more for
                   5769:                 * historical reasons: 3 if coded 1, 2, 3 and 4 and Ndum[2]=0 */
                   5770:         } /* Ndum[-1] number of undefined modalities */
1.231     brouard  5771:                        
1.242     brouard  5772:         /* j is a covariate, n=Tvar[j] of Vn; Fills nbcode */
                   5773:         /* For covariate j, modalities could be 1, 2, 3, 4, 5, 6, 7. */
                   5774:         /* If Ndum[1]=0, Ndum[2]=0, Ndum[3]= 635, Ndum[4]=0, Ndum[5]=0, Ndum[6]=27, Ndum[7]=125; */
                   5775:         /* modmincovj=3; modmaxcovj = 7; */
                   5776:         /* There are only 3 modalities non empty 3, 6, 7 (or 2 if 27 is too few) : ncodemax[j]=3; */
                   5777:         /* which will be coded 0, 1, 2 which in binary on 2=3-1 digits are 0=00 1=01, 2=10; */
                   5778:         /*              defining two dummy variables: variables V1_1 and V1_2.*/
                   5779:         /* nbcode[Tvar[j]][ij]=k; */
                   5780:         /* nbcode[Tvar[j]][1]=0; */
                   5781:         /* nbcode[Tvar[j]][2]=1; */
                   5782:         /* nbcode[Tvar[j]][3]=2; */
                   5783:         /* To be continued (not working yet). */
                   5784:         ij=0; /* ij is similar to i but can jump over null modalities */
1.287     brouard  5785: 
                   5786:         /* 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*/
                   5787:         /* Skipping the case of missing values by reducing nbcode to 0 and 1 and not -1, 0, 1 */
                   5788:         /* model=V1+V2+V3, if V2=-1, 0 or 1, then nbcode[2][1]=0 and nbcode[2][2]=1 instead of
                   5789:          * nbcode[2][1]=-1, nbcode[2][2]=0 and nbcode[2][3]=1 */
                   5790:         /*, could be restored in the future */
                   5791:         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  5792:           if (Ndum[i] == 0) { /* If nobody responded to this modality k */
                   5793:             break;
                   5794:           }
                   5795:           ij++;
1.287     brouard  5796:           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  5797:           cptcode = ij; /* New max modality for covar j */
                   5798:         } /* end of loop on modality i=-1 to 1 or more */
                   5799:         break;
                   5800:        case 1: /* Testing on varying covariate, could be simple and
                   5801:                * should look at waves or product of fixed *
                   5802:                * varying. No time to test -1, assuming 0 and 1 only */
                   5803:         ij=0;
                   5804:         for(i=0; i<=1;i++){
                   5805:           nbcode[Tvar[k]][++ij]=i;
                   5806:         }
                   5807:         break;
                   5808:        default:
                   5809:         break;
                   5810:        } /* end switch */
                   5811:      } /* end dummy test */
1.311     brouard  5812:      if(Dummy[k]==1 && Typevar[k] !=1){ /* Dummy covariate and not age product */ 
                   5813:        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*/
                   5814:         if(isnan(covar[Tvar[k]][i])){
                   5815:           printf("ERROR, IMaCh doesn't treat fixed quantitative covariate with missing values V%d=., individual %d will be skipped.\n",Tvar[k],i);
                   5816:           fprintf(ficlog,"ERROR, currently IMaCh doesn't treat covariate with missing values V%d=., individual %d will be skipped.\n",Tvar[k],i);
                   5817:           fflush(ficlog);
                   5818:           exit(1);
                   5819:          }
                   5820:        }
                   5821:      }
1.287     brouard  5822:    } /* 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  5823:   
                   5824:    for (k=-1; k< maxncov; k++) Ndum[k]=0; 
                   5825:    /* Look at fixed dummy (single or product) covariates to check empty modalities */
                   5826:    for (i=1; i<=ncovmodel-2-nagesqr; i++) { /* -2, cste and age and eventually age*age */ 
                   5827:      /* Listing of all covariables in statement model to see if some covariates appear twice. For example, V1 appears twice in V1+V1*V2.*/ 
                   5828:      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 */ 
                   5829:      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 */
                   5830:      /* V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1,  {2, 1, 1, 1, 2, 1, 1, 0, 0} */
                   5831:    } /* V4+V3+V5, Ndum[1]@5={0, 0, 1, 1, 1} */
                   5832:   
                   5833:    ij=0;
                   5834:    /* for (i=0; i<=  maxncov-1; i++) { /\* modmaxcovj is unknown here. Only Ndum[2(V2),3(age*V3), 5(V3*V2) 6(V1*V4) *\/ */
                   5835:    for (k=1; k<=  cptcovt; k++) { /* modmaxcovj is unknown here. Only Ndum[2(V2),3(age*V3), 5(V3*V2) 6(V1*V4) */
                   5836:      /*printf("Ndum[%d]=%d\n",i, Ndum[i]);*/
                   5837:      /* if((Ndum[i]!=0) && (i<=ncovcol)){  /\* Tvar[i] <= ncovmodel ? *\/ */
                   5838:      if(Ndum[Tvar[k]]!=0 && Dummy[k] == 0 && Typevar[k]==0){  /* Only Dummy and non empty in the model */
                   5839:        /* If product not in single variable we don't print results */
                   5840:        /*printf("diff Ndum[%d]=%d\n",i, Ndum[i]);*/
                   5841:        ++ij;/* V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1, */
                   5842:        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*/
                   5843:        Tmodelind[ij]=k; /* Tmodelind: index in model of dummies Tmodelind[1]=2 V4: pos=2; V3: pos=3, V1=9 {2, 3, 9, ?, ?,} */
                   5844:        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 */
                   5845:        if(Fixed[k]!=0)
                   5846:         anyvaryingduminmodel=1;
                   5847:        /* }else if((Ndum[i]!=0) && (i<=ncovcol+nqv)){ */
                   5848:        /*   Tvaraff[++ij]=-10; /\* Dont'n know how to treat quantitative variables yet *\/ */
                   5849:        /* }else if((Ndum[i]!=0) && (i<=ncovcol+nqv+ntv)){ */
                   5850:        /*   Tvaraff[++ij]=i; /\*For printing (unclear) *\/ */
                   5851:        /* }else if((Ndum[i]!=0) && (i<=ncovcol+nqv+ntv+nqtv)){ */
                   5852:        /*   Tvaraff[++ij]=-20; /\* Dont'n know how to treat quantitative variables yet *\/ */
                   5853:      } 
                   5854:    } /* Tvaraff[1]@5 {3, 4, -20, 0, 0} Very strange */
                   5855:    /* ij--; */
                   5856:    /* cptcoveff=ij; /\*Number of total covariates*\/ */
                   5857:    *cptcov=ij; /*Number of total real effective covariates: effective
                   5858:                * because they can be excluded from the model and real
                   5859:                * if in the model but excluded because missing values, but how to get k from ij?*/
                   5860:    for(j=ij+1; j<= cptcovt; j++){
                   5861:      Tvaraff[j]=0;
                   5862:      Tmodelind[j]=0;
                   5863:    }
                   5864:    for(j=ntveff+1; j<= cptcovt; j++){
                   5865:      TmodelInvind[j]=0;
                   5866:    }
                   5867:    /* To be sorted */
                   5868:    ;
                   5869:  }
1.126     brouard  5870: 
1.145     brouard  5871: 
1.126     brouard  5872: /*********** Health Expectancies ****************/
                   5873: 
1.235     brouard  5874:  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  5875: 
                   5876: {
                   5877:   /* Health expectancies, no variances */
1.164     brouard  5878:   int i, j, nhstepm, hstepm, h, nstepm;
1.126     brouard  5879:   int nhstepma, nstepma; /* Decreasing with age */
                   5880:   double age, agelim, hf;
                   5881:   double ***p3mat;
                   5882:   double eip;
                   5883: 
1.238     brouard  5884:   /* pstamp(ficreseij); */
1.126     brouard  5885:   fprintf(ficreseij,"# (a) Life expectancies by health status at initial age and (b) health expectancies by health status at initial age\n");
                   5886:   fprintf(ficreseij,"# Age");
                   5887:   for(i=1; i<=nlstate;i++){
                   5888:     for(j=1; j<=nlstate;j++){
                   5889:       fprintf(ficreseij," e%1d%1d ",i,j);
                   5890:     }
                   5891:     fprintf(ficreseij," e%1d. ",i);
                   5892:   }
                   5893:   fprintf(ficreseij,"\n");
                   5894: 
                   5895:   
                   5896:   if(estepm < stepm){
                   5897:     printf ("Problem %d lower than %d\n",estepm, stepm);
                   5898:   }
                   5899:   else  hstepm=estepm;   
                   5900:   /* We compute the life expectancy from trapezoids spaced every estepm months
                   5901:    * This is mainly to measure the difference between two models: for example
                   5902:    * if stepm=24 months pijx are given only every 2 years and by summing them
                   5903:    * we are calculating an estimate of the Life Expectancy assuming a linear 
                   5904:    * progression in between and thus overestimating or underestimating according
                   5905:    * to the curvature of the survival function. If, for the same date, we 
                   5906:    * estimate the model with stepm=1 month, we can keep estepm to 24 months
                   5907:    * to compare the new estimate of Life expectancy with the same linear 
                   5908:    * hypothesis. A more precise result, taking into account a more precise
                   5909:    * curvature will be obtained if estepm is as small as stepm. */
                   5910: 
                   5911:   /* For example we decided to compute the life expectancy with the smallest unit */
                   5912:   /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm. 
                   5913:      nhstepm is the number of hstepm from age to agelim 
                   5914:      nstepm is the number of stepm from age to agelin. 
1.270     brouard  5915:      Look at hpijx to understand the reason which relies in memory size consideration
1.126     brouard  5916:      and note for a fixed period like estepm months */
                   5917:   /* We decided (b) to get a life expectancy respecting the most precise curvature of the
                   5918:      survival function given by stepm (the optimization length). Unfortunately it
                   5919:      means that if the survival funtion is printed only each two years of age and if
                   5920:      you sum them up and add 1 year (area under the trapezoids) you won't get the same 
                   5921:      results. So we changed our mind and took the option of the best precision.
                   5922:   */
                   5923:   hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */ 
                   5924: 
                   5925:   agelim=AGESUP;
                   5926:   /* If stepm=6 months */
                   5927:     /* Computed by stepm unit matrices, product of hstepm matrices, stored
                   5928:        in an array of nhstepm length: nhstepm=10, hstepm=4, stepm=6 months */
                   5929:     
                   5930: /* nhstepm age range expressed in number of stepm */
                   5931:   nstepm=(int) rint((agelim-bage)*YEARM/stepm); /* Biggest nstepm */
                   5932:   /* Typically if 20 years nstepm = 20*12/6=40 stepm */ 
                   5933:   /* if (stepm >= YEARM) hstepm=1;*/
                   5934:   nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
                   5935:   p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   5936: 
                   5937:   for (age=bage; age<=fage; age ++){ 
                   5938:     nstepma=(int) rint((agelim-bage)*YEARM/stepm); /* Biggest nstepm */
                   5939:     /* Typically if 20 years nstepm = 20*12/6=40 stepm */ 
                   5940:     /* if (stepm >= YEARM) hstepm=1;*/
                   5941:     nhstepma = nstepma/hstepm;/* Expressed in hstepm, typically nhstepma=40/4=10 */
                   5942: 
                   5943:     /* If stepm=6 months */
                   5944:     /* Computed by stepm unit matrices, product of hstepma matrices, stored
                   5945:        in an array of nhstepma length: nhstepma=10, hstepm=4, stepm=6 months */
                   5946:     
1.235     brouard  5947:     hpxij(p3mat,nhstepma,age,hstepm,x,nlstate,stepm,oldm, savm, cij, nres);  
1.126     brouard  5948:     
                   5949:     hf=hstepm*stepm/YEARM;  /* Duration of hstepm expressed in year unit. */
                   5950:     
                   5951:     printf("%d|",(int)age);fflush(stdout);
                   5952:     fprintf(ficlog,"%d|",(int)age);fflush(ficlog);
                   5953:     
                   5954:     /* Computing expectancies */
                   5955:     for(i=1; i<=nlstate;i++)
                   5956:       for(j=1; j<=nlstate;j++)
                   5957:        for (h=0, eij[i][j][(int)age]=0; h<=nhstepm-1; h++){
                   5958:          eij[i][j][(int)age] += (p3mat[i][j][h]+p3mat[i][j][h+1])/2.0*hf;
                   5959:          
                   5960:          /* 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]);*/
                   5961: 
                   5962:        }
                   5963: 
                   5964:     fprintf(ficreseij,"%3.0f",age );
                   5965:     for(i=1; i<=nlstate;i++){
                   5966:       eip=0;
                   5967:       for(j=1; j<=nlstate;j++){
                   5968:        eip +=eij[i][j][(int)age];
                   5969:        fprintf(ficreseij,"%9.4f", eij[i][j][(int)age] );
                   5970:       }
                   5971:       fprintf(ficreseij,"%9.4f", eip );
                   5972:     }
                   5973:     fprintf(ficreseij,"\n");
                   5974:     
                   5975:   }
                   5976:   free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   5977:   printf("\n");
                   5978:   fprintf(ficlog,"\n");
                   5979:   
                   5980: }
                   5981: 
1.235     brouard  5982:  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  5983: 
                   5984: {
                   5985:   /* Covariances of health expectancies eij and of total life expectancies according
1.222     brouard  5986:      to initial status i, ei. .
1.126     brouard  5987:   */
                   5988:   int i, j, nhstepm, hstepm, h, nstepm, k, cptj, cptj2, i2, j2, ij, ji;
                   5989:   int nhstepma, nstepma; /* Decreasing with age */
                   5990:   double age, agelim, hf;
                   5991:   double ***p3matp, ***p3matm, ***varhe;
                   5992:   double **dnewm,**doldm;
                   5993:   double *xp, *xm;
                   5994:   double **gp, **gm;
                   5995:   double ***gradg, ***trgradg;
                   5996:   int theta;
                   5997: 
                   5998:   double eip, vip;
                   5999: 
                   6000:   varhe=ma3x(1,nlstate*nlstate,1,nlstate*nlstate,(int) bage, (int) fage);
                   6001:   xp=vector(1,npar);
                   6002:   xm=vector(1,npar);
                   6003:   dnewm=matrix(1,nlstate*nlstate,1,npar);
                   6004:   doldm=matrix(1,nlstate*nlstate,1,nlstate*nlstate);
                   6005:   
                   6006:   pstamp(ficresstdeij);
                   6007:   fprintf(ficresstdeij,"# Health expectancies with standard errors\n");
                   6008:   fprintf(ficresstdeij,"# Age");
                   6009:   for(i=1; i<=nlstate;i++){
                   6010:     for(j=1; j<=nlstate;j++)
                   6011:       fprintf(ficresstdeij," e%1d%1d (SE)",i,j);
                   6012:     fprintf(ficresstdeij," e%1d. ",i);
                   6013:   }
                   6014:   fprintf(ficresstdeij,"\n");
                   6015: 
                   6016:   pstamp(ficrescveij);
                   6017:   fprintf(ficrescveij,"# Subdiagonal matrix of covariances of health expectancies by age: cov(eij,ekl)\n");
                   6018:   fprintf(ficrescveij,"# Age");
                   6019:   for(i=1; i<=nlstate;i++)
                   6020:     for(j=1; j<=nlstate;j++){
                   6021:       cptj= (j-1)*nlstate+i;
                   6022:       for(i2=1; i2<=nlstate;i2++)
                   6023:        for(j2=1; j2<=nlstate;j2++){
                   6024:          cptj2= (j2-1)*nlstate+i2;
                   6025:          if(cptj2 <= cptj)
                   6026:            fprintf(ficrescveij,"  %1d%1d,%1d%1d",i,j,i2,j2);
                   6027:        }
                   6028:     }
                   6029:   fprintf(ficrescveij,"\n");
                   6030:   
                   6031:   if(estepm < stepm){
                   6032:     printf ("Problem %d lower than %d\n",estepm, stepm);
                   6033:   }
                   6034:   else  hstepm=estepm;   
                   6035:   /* We compute the life expectancy from trapezoids spaced every estepm months
                   6036:    * This is mainly to measure the difference between two models: for example
                   6037:    * if stepm=24 months pijx are given only every 2 years and by summing them
                   6038:    * we are calculating an estimate of the Life Expectancy assuming a linear 
                   6039:    * progression in between and thus overestimating or underestimating according
                   6040:    * to the curvature of the survival function. If, for the same date, we 
                   6041:    * estimate the model with stepm=1 month, we can keep estepm to 24 months
                   6042:    * to compare the new estimate of Life expectancy with the same linear 
                   6043:    * hypothesis. A more precise result, taking into account a more precise
                   6044:    * curvature will be obtained if estepm is as small as stepm. */
                   6045: 
                   6046:   /* For example we decided to compute the life expectancy with the smallest unit */
                   6047:   /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm. 
                   6048:      nhstepm is the number of hstepm from age to agelim 
                   6049:      nstepm is the number of stepm from age to agelin. 
                   6050:      Look at hpijx to understand the reason of that which relies in memory size
                   6051:      and note for a fixed period like estepm months */
                   6052:   /* We decided (b) to get a life expectancy respecting the most precise curvature of the
                   6053:      survival function given by stepm (the optimization length). Unfortunately it
                   6054:      means that if the survival funtion is printed only each two years of age and if
                   6055:      you sum them up and add 1 year (area under the trapezoids) you won't get the same 
                   6056:      results. So we changed our mind and took the option of the best precision.
                   6057:   */
                   6058:   hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */ 
                   6059: 
                   6060:   /* If stepm=6 months */
                   6061:   /* nhstepm age range expressed in number of stepm */
                   6062:   agelim=AGESUP;
                   6063:   nstepm=(int) rint((agelim-bage)*YEARM/stepm); 
                   6064:   /* Typically if 20 years nstepm = 20*12/6=40 stepm */ 
                   6065:   /* if (stepm >= YEARM) hstepm=1;*/
                   6066:   nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
                   6067:   
                   6068:   p3matp=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   6069:   p3matm=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   6070:   gradg=ma3x(0,nhstepm,1,npar,1,nlstate*nlstate);
                   6071:   trgradg =ma3x(0,nhstepm,1,nlstate*nlstate,1,npar);
                   6072:   gp=matrix(0,nhstepm,1,nlstate*nlstate);
                   6073:   gm=matrix(0,nhstepm,1,nlstate*nlstate);
                   6074: 
                   6075:   for (age=bage; age<=fage; age ++){ 
                   6076:     nstepma=(int) rint((agelim-bage)*YEARM/stepm); /* Biggest nstepm */
                   6077:     /* Typically if 20 years nstepm = 20*12/6=40 stepm */ 
                   6078:     /* if (stepm >= YEARM) hstepm=1;*/
                   6079:     nhstepma = nstepma/hstepm;/* Expressed in hstepm, typically nhstepma=40/4=10 */
1.218     brouard  6080:                
1.126     brouard  6081:     /* If stepm=6 months */
                   6082:     /* Computed by stepm unit matrices, product of hstepma matrices, stored
                   6083:        in an array of nhstepma length: nhstepma=10, hstepm=4, stepm=6 months */
                   6084:     
                   6085:     hf=hstepm*stepm/YEARM;  /* Duration of hstepm expressed in year unit. */
1.218     brouard  6086:                
1.126     brouard  6087:     /* Computing  Variances of health expectancies */
                   6088:     /* Gradient is computed with plus gp and minus gm. Code is duplicated in order to
                   6089:        decrease memory allocation */
                   6090:     for(theta=1; theta <=npar; theta++){
                   6091:       for(i=1; i<=npar; i++){ 
1.222     brouard  6092:        xp[i] = x[i] + (i==theta ?delti[theta]:0);
                   6093:        xm[i] = x[i] - (i==theta ?delti[theta]:0);
1.126     brouard  6094:       }
1.235     brouard  6095:       hpxij(p3matp,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, cij, nres);  
                   6096:       hpxij(p3matm,nhstepm,age,hstepm,xm,nlstate,stepm,oldm,savm, cij, nres);  
1.218     brouard  6097:                        
1.126     brouard  6098:       for(j=1; j<= nlstate; j++){
1.222     brouard  6099:        for(i=1; i<=nlstate; i++){
                   6100:          for(h=0; h<=nhstepm-1; h++){
                   6101:            gp[h][(j-1)*nlstate + i] = (p3matp[i][j][h]+p3matp[i][j][h+1])/2.;
                   6102:            gm[h][(j-1)*nlstate + i] = (p3matm[i][j][h]+p3matm[i][j][h+1])/2.;
                   6103:          }
                   6104:        }
1.126     brouard  6105:       }
1.218     brouard  6106:                        
1.126     brouard  6107:       for(ij=1; ij<= nlstate*nlstate; ij++)
1.222     brouard  6108:        for(h=0; h<=nhstepm-1; h++){
                   6109:          gradg[h][theta][ij]= (gp[h][ij]-gm[h][ij])/2./delti[theta];
                   6110:        }
1.126     brouard  6111:     }/* End theta */
                   6112:     
                   6113:     
                   6114:     for(h=0; h<=nhstepm-1; h++)
                   6115:       for(j=1; j<=nlstate*nlstate;j++)
1.222     brouard  6116:        for(theta=1; theta <=npar; theta++)
                   6117:          trgradg[h][j][theta]=gradg[h][theta][j];
1.126     brouard  6118:     
1.218     brouard  6119:                
1.222     brouard  6120:     for(ij=1;ij<=nlstate*nlstate;ij++)
1.126     brouard  6121:       for(ji=1;ji<=nlstate*nlstate;ji++)
1.222     brouard  6122:        varhe[ij][ji][(int)age] =0.;
1.218     brouard  6123:                
1.222     brouard  6124:     printf("%d|",(int)age);fflush(stdout);
                   6125:     fprintf(ficlog,"%d|",(int)age);fflush(ficlog);
                   6126:     for(h=0;h<=nhstepm-1;h++){
1.126     brouard  6127:       for(k=0;k<=nhstepm-1;k++){
1.222     brouard  6128:        matprod2(dnewm,trgradg[h],1,nlstate*nlstate,1,npar,1,npar,matcov);
                   6129:        matprod2(doldm,dnewm,1,nlstate*nlstate,1,npar,1,nlstate*nlstate,gradg[k]);
                   6130:        for(ij=1;ij<=nlstate*nlstate;ij++)
                   6131:          for(ji=1;ji<=nlstate*nlstate;ji++)
                   6132:            varhe[ij][ji][(int)age] += doldm[ij][ji]*hf*hf;
1.126     brouard  6133:       }
                   6134:     }
1.320     brouard  6135:     /* if((int)age ==50){ */
                   6136:     /*   printf(" age=%d cij=%d nres=%d varhe[%d][%d]=%f ",(int)age, cij, nres, 1,2,varhe[1][2]); */
                   6137:     /* } */
1.126     brouard  6138:     /* Computing expectancies */
1.235     brouard  6139:     hpxij(p3matm,nhstepm,age,hstepm,x,nlstate,stepm,oldm, savm, cij,nres);  
1.126     brouard  6140:     for(i=1; i<=nlstate;i++)
                   6141:       for(j=1; j<=nlstate;j++)
1.222     brouard  6142:        for (h=0, eij[i][j][(int)age]=0; h<=nhstepm-1; h++){
                   6143:          eij[i][j][(int)age] += (p3matm[i][j][h]+p3matm[i][j][h+1])/2.0*hf;
1.218     brouard  6144:                                        
1.222     brouard  6145:          /* 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  6146:                                        
1.222     brouard  6147:        }
1.269     brouard  6148: 
                   6149:     /* Standard deviation of expectancies ij */                
1.126     brouard  6150:     fprintf(ficresstdeij,"%3.0f",age );
                   6151:     for(i=1; i<=nlstate;i++){
                   6152:       eip=0.;
                   6153:       vip=0.;
                   6154:       for(j=1; j<=nlstate;j++){
1.222     brouard  6155:        eip += eij[i][j][(int)age];
                   6156:        for(k=1; k<=nlstate;k++) /* Sum on j and k of cov(eij,eik) */
                   6157:          vip += varhe[(j-1)*nlstate+i][(k-1)*nlstate+i][(int)age];
                   6158:        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  6159:       }
                   6160:       fprintf(ficresstdeij," %9.4f (%.4f)", eip, sqrt(vip));
                   6161:     }
                   6162:     fprintf(ficresstdeij,"\n");
1.218     brouard  6163:                
1.269     brouard  6164:     /* Variance of expectancies ij */          
1.126     brouard  6165:     fprintf(ficrescveij,"%3.0f",age );
                   6166:     for(i=1; i<=nlstate;i++)
                   6167:       for(j=1; j<=nlstate;j++){
1.222     brouard  6168:        cptj= (j-1)*nlstate+i;
                   6169:        for(i2=1; i2<=nlstate;i2++)
                   6170:          for(j2=1; j2<=nlstate;j2++){
                   6171:            cptj2= (j2-1)*nlstate+i2;
                   6172:            if(cptj2 <= cptj)
                   6173:              fprintf(ficrescveij," %.4f", varhe[cptj][cptj2][(int)age]);
                   6174:          }
1.126     brouard  6175:       }
                   6176:     fprintf(ficrescveij,"\n");
1.218     brouard  6177:                
1.126     brouard  6178:   }
                   6179:   free_matrix(gm,0,nhstepm,1,nlstate*nlstate);
                   6180:   free_matrix(gp,0,nhstepm,1,nlstate*nlstate);
                   6181:   free_ma3x(gradg,0,nhstepm,1,npar,1,nlstate*nlstate);
                   6182:   free_ma3x(trgradg,0,nhstepm,1,nlstate*nlstate,1,npar);
                   6183:   free_ma3x(p3matm,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   6184:   free_ma3x(p3matp,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   6185:   printf("\n");
                   6186:   fprintf(ficlog,"\n");
1.218     brouard  6187:        
1.126     brouard  6188:   free_vector(xm,1,npar);
                   6189:   free_vector(xp,1,npar);
                   6190:   free_matrix(dnewm,1,nlstate*nlstate,1,npar);
                   6191:   free_matrix(doldm,1,nlstate*nlstate,1,nlstate*nlstate);
                   6192:   free_ma3x(varhe,1,nlstate*nlstate,1,nlstate*nlstate,(int) bage, (int)fage);
                   6193: }
1.218     brouard  6194:  
1.126     brouard  6195: /************ Variance ******************/
1.235     brouard  6196:  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  6197:  {
1.279     brouard  6198:    /** Variance of health expectancies 
                   6199:     *  double **prevalim(double **prlim, int nlstate, double *xp, double age, double **oldm, double ** savm,double ftolpl);
                   6200:     * double **newm;
                   6201:     * int movingaverage(double ***probs, double bage,double fage, double ***mobaverage, int mobilav) 
                   6202:     */
1.218     brouard  6203:   
                   6204:    /* int movingaverage(); */
                   6205:    double **dnewm,**doldm;
                   6206:    double **dnewmp,**doldmp;
                   6207:    int i, j, nhstepm, hstepm, h, nstepm ;
1.288     brouard  6208:    int first=0;
1.218     brouard  6209:    int k;
                   6210:    double *xp;
1.279     brouard  6211:    double **gp, **gm;  /**< for var eij */
                   6212:    double ***gradg, ***trgradg; /**< for var eij */
                   6213:    double **gradgp, **trgradgp; /**< for var p point j */
                   6214:    double *gpp, *gmp; /**< for var p point j */
                   6215:    double **varppt; /**< for var p point j nlstate to nlstate+ndeath */
1.218     brouard  6216:    double ***p3mat;
                   6217:    double age,agelim, hf;
                   6218:    /* double ***mobaverage; */
                   6219:    int theta;
                   6220:    char digit[4];
                   6221:    char digitp[25];
                   6222: 
                   6223:    char fileresprobmorprev[FILENAMELENGTH];
                   6224: 
                   6225:    if(popbased==1){
                   6226:      if(mobilav!=0)
                   6227:        strcpy(digitp,"-POPULBASED-MOBILAV_");
                   6228:      else strcpy(digitp,"-POPULBASED-NOMOBIL_");
                   6229:    }
                   6230:    else 
                   6231:      strcpy(digitp,"-STABLBASED_");
1.126     brouard  6232: 
1.218     brouard  6233:    /* if (mobilav!=0) { */
                   6234:    /*   mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX); */
                   6235:    /*   if (movingaverage(probs, bage, fage, mobaverage,mobilav)!=0){ */
                   6236:    /*     fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav); */
                   6237:    /*     printf(" Error in movingaverage mobilav=%d\n",mobilav); */
                   6238:    /*   } */
                   6239:    /* } */
                   6240: 
                   6241:    strcpy(fileresprobmorprev,"PRMORPREV-"); 
                   6242:    sprintf(digit,"%-d",ij);
                   6243:    /*printf("DIGIT=%s, ij=%d ijr=%-d|\n",digit, ij,ij);*/
                   6244:    strcat(fileresprobmorprev,digit); /* Tvar to be done */
                   6245:    strcat(fileresprobmorprev,digitp); /* Popbased or not, mobilav or not */
                   6246:    strcat(fileresprobmorprev,fileresu);
                   6247:    if((ficresprobmorprev=fopen(fileresprobmorprev,"w"))==NULL) {
                   6248:      printf("Problem with resultfile: %s\n", fileresprobmorprev);
                   6249:      fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobmorprev);
                   6250:    }
                   6251:    printf("Computing total mortality p.j=w1*p1j+w2*p2j+..: result on file '%s' \n",fileresprobmorprev);
                   6252:    fprintf(ficlog,"Computing total mortality p.j=w1*p1j+w2*p2j+..: result on file '%s' \n",fileresprobmorprev);
                   6253:    pstamp(ficresprobmorprev);
                   6254:    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  6255:    fprintf(ficresprobmorprev,"# Selected quantitative variables and dummies");
                   6256:    for (j=1; j<= nsq; j++){ /* For each selected (single) quantitative value */
                   6257:      fprintf(ficresprobmorprev," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]);
                   6258:    }
                   6259:    for(j=1;j<=cptcoveff;j++) 
                   6260:      fprintf(ficresprobmorprev,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(ij,j)]);
                   6261:    fprintf(ficresprobmorprev,"\n");
                   6262: 
1.218     brouard  6263:    fprintf(ficresprobmorprev,"# Age cov=%-d",ij);
                   6264:    for(j=nlstate+1; j<=(nlstate+ndeath);j++){
                   6265:      fprintf(ficresprobmorprev," p.%-d SE",j);
                   6266:      for(i=1; i<=nlstate;i++)
                   6267:        fprintf(ficresprobmorprev," w%1d p%-d%-d",i,i,j);
                   6268:    }  
                   6269:    fprintf(ficresprobmorprev,"\n");
                   6270:   
                   6271:    fprintf(ficgp,"\n# Routine varevsij");
                   6272:    fprintf(ficgp,"\nunset title \n");
                   6273:    /* fprintf(fichtm, "#Local time at start: %s", strstart);*/
                   6274:    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");
                   6275:    fprintf(fichtm,"\n<br>%s  <br>\n",digitp);
1.279     brouard  6276: 
1.218     brouard  6277:    varppt = matrix(nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
                   6278:    pstamp(ficresvij);
                   6279:    fprintf(ficresvij,"# Variance and covariance of health expectancies e.j \n#  (weighted average of eij where weights are ");
                   6280:    if(popbased==1)
                   6281:      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);
                   6282:    else
                   6283:      fprintf(ficresvij,"the age specific period (stable) prevalences in each health state \n");
                   6284:    fprintf(ficresvij,"# Age");
                   6285:    for(i=1; i<=nlstate;i++)
                   6286:      for(j=1; j<=nlstate;j++)
                   6287:        fprintf(ficresvij," Cov(e.%1d, e.%1d)",i,j);
                   6288:    fprintf(ficresvij,"\n");
                   6289: 
                   6290:    xp=vector(1,npar);
                   6291:    dnewm=matrix(1,nlstate,1,npar);
                   6292:    doldm=matrix(1,nlstate,1,nlstate);
                   6293:    dnewmp= matrix(nlstate+1,nlstate+ndeath,1,npar);
                   6294:    doldmp= matrix(nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
                   6295: 
                   6296:    gradgp=matrix(1,npar,nlstate+1,nlstate+ndeath);
                   6297:    gpp=vector(nlstate+1,nlstate+ndeath);
                   6298:    gmp=vector(nlstate+1,nlstate+ndeath);
                   6299:    trgradgp =matrix(nlstate+1,nlstate+ndeath,1,npar); /* mu or p point j*/
1.126     brouard  6300:   
1.218     brouard  6301:    if(estepm < stepm){
                   6302:      printf ("Problem %d lower than %d\n",estepm, stepm);
                   6303:    }
                   6304:    else  hstepm=estepm;   
                   6305:    /* For example we decided to compute the life expectancy with the smallest unit */
                   6306:    /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm. 
                   6307:       nhstepm is the number of hstepm from age to agelim 
                   6308:       nstepm is the number of stepm from age to agelim. 
                   6309:       Look at function hpijx to understand why because of memory size limitations, 
                   6310:       we decided (b) to get a life expectancy respecting the most precise curvature of the
                   6311:       survival function given by stepm (the optimization length). Unfortunately it
                   6312:       means that if the survival funtion is printed every two years of age and if
                   6313:       you sum them up and add 1 year (area under the trapezoids) you won't get the same 
                   6314:       results. So we changed our mind and took the option of the best precision.
                   6315:    */
                   6316:    hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */ 
                   6317:    agelim = AGESUP;
                   6318:    for (age=bage; age<=fage; age ++){ /* If stepm=6 months */
                   6319:      nstepm=(int) rint((agelim-age)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */ 
                   6320:      nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
                   6321:      p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   6322:      gradg=ma3x(0,nhstepm,1,npar,1,nlstate);
                   6323:      gp=matrix(0,nhstepm,1,nlstate);
                   6324:      gm=matrix(0,nhstepm,1,nlstate);
                   6325:                
                   6326:                
                   6327:      for(theta=1; theta <=npar; theta++){
                   6328:        for(i=1; i<=npar; i++){ /* Computes gradient x + delta*/
                   6329:         xp[i] = x[i] + (i==theta ?delti[theta]:0);
                   6330:        }
1.279     brouard  6331:        /**< Computes the prevalence limit with parameter theta shifted of delta up to ftolpl precision and 
                   6332:        * returns into prlim .
1.288     brouard  6333:        */
1.242     brouard  6334:        prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp,ij, nres);
1.279     brouard  6335: 
                   6336:        /* If popbased = 1 we use crossection prevalences. Previous step is useless but prlim is created */
1.218     brouard  6337:        if (popbased==1) {
                   6338:         if(mobilav ==0){
                   6339:           for(i=1; i<=nlstate;i++)
                   6340:             prlim[i][i]=probs[(int)age][i][ij];
                   6341:         }else{ /* mobilav */ 
                   6342:           for(i=1; i<=nlstate;i++)
                   6343:             prlim[i][i]=mobaverage[(int)age][i][ij];
                   6344:         }
                   6345:        }
1.295     brouard  6346:        /**< Computes the shifted transition matrix \f$ {}{h}_p^{ij}x\f$ at horizon h.
1.279     brouard  6347:        */                      
                   6348:        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  6349:        /**< 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  6350:        * at horizon h in state j including mortality.
                   6351:        */
1.218     brouard  6352:        for(j=1; j<= nlstate; j++){
                   6353:         for(h=0; h<=nhstepm; h++){
                   6354:           for(i=1, gp[h][j]=0.;i<=nlstate;i++)
                   6355:             gp[h][j] += prlim[i][i]*p3mat[i][j][h];
                   6356:         }
                   6357:        }
1.279     brouard  6358:        /* Next for computing shifted+ probability of death (h=1 means
1.218     brouard  6359:          computed over hstepm matrices product = hstepm*stepm months) 
1.279     brouard  6360:          as a weighted average of prlim(i) * p(i,j) p.3=w1*p13 + w2*p23 .
1.218     brouard  6361:        */
                   6362:        for(j=nlstate+1;j<=nlstate+ndeath;j++){
                   6363:         for(i=1,gpp[j]=0.; i<= nlstate; i++)
                   6364:           gpp[j] += prlim[i][i]*p3mat[i][j][1];
1.279     brouard  6365:        }
                   6366:        
                   6367:        /* Again with minus shift */
1.218     brouard  6368:                        
                   6369:        for(i=1; i<=npar; i++) /* Computes gradient x - delta */
                   6370:         xp[i] = x[i] - (i==theta ?delti[theta]:0);
1.288     brouard  6371: 
1.242     brouard  6372:        prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp, ij, nres);
1.218     brouard  6373:                        
                   6374:        if (popbased==1) {
                   6375:         if(mobilav ==0){
                   6376:           for(i=1; i<=nlstate;i++)
                   6377:             prlim[i][i]=probs[(int)age][i][ij];
                   6378:         }else{ /* mobilav */ 
                   6379:           for(i=1; i<=nlstate;i++)
                   6380:             prlim[i][i]=mobaverage[(int)age][i][ij];
                   6381:         }
                   6382:        }
                   6383:                        
1.235     brouard  6384:        hpxij(p3mat,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, ij,nres);  
1.218     brouard  6385:                        
                   6386:        for(j=1; j<= nlstate; j++){  /* Sum of wi * eij = e.j */
                   6387:         for(h=0; h<=nhstepm; h++){
                   6388:           for(i=1, gm[h][j]=0.;i<=nlstate;i++)
                   6389:             gm[h][j] += prlim[i][i]*p3mat[i][j][h];
                   6390:         }
                   6391:        }
                   6392:        /* This for computing probability of death (h=1 means
                   6393:          computed over hstepm matrices product = hstepm*stepm months) 
                   6394:          as a weighted average of prlim.
                   6395:        */
                   6396:        for(j=nlstate+1;j<=nlstate+ndeath;j++){
                   6397:         for(i=1,gmp[j]=0.; i<= nlstate; i++)
                   6398:           gmp[j] += prlim[i][i]*p3mat[i][j][1];
                   6399:        }    
1.279     brouard  6400:        /* end shifting computations */
                   6401: 
                   6402:        /**< Computing gradient matrix at horizon h 
                   6403:        */
1.218     brouard  6404:        for(j=1; j<= nlstate; j++) /* vareij */
                   6405:         for(h=0; h<=nhstepm; h++){
                   6406:           gradg[h][theta][j]= (gp[h][j]-gm[h][j])/2./delti[theta];
                   6407:         }
1.279     brouard  6408:        /**< Gradient of overall mortality p.3 (or p.j) 
                   6409:        */
                   6410:        for(j=nlstate+1; j<= nlstate+ndeath; j++){ /* var mu mortality from j */
1.218     brouard  6411:         gradgp[theta][j]= (gpp[j]-gmp[j])/2./delti[theta];
                   6412:        }
                   6413:                        
                   6414:      } /* End theta */
1.279     brouard  6415:      
                   6416:      /* We got the gradient matrix for each theta and state j */               
1.218     brouard  6417:      trgradg =ma3x(0,nhstepm,1,nlstate,1,npar); /* veij */
                   6418:                
                   6419:      for(h=0; h<=nhstepm; h++) /* veij */
                   6420:        for(j=1; j<=nlstate;j++)
                   6421:         for(theta=1; theta <=npar; theta++)
                   6422:           trgradg[h][j][theta]=gradg[h][theta][j];
                   6423:                
                   6424:      for(j=nlstate+1; j<=nlstate+ndeath;j++) /* mu */
                   6425:        for(theta=1; theta <=npar; theta++)
                   6426:         trgradgp[j][theta]=gradgp[theta][j];
1.279     brouard  6427:      /**< as well as its transposed matrix 
                   6428:       */               
1.218     brouard  6429:                
                   6430:      hf=hstepm*stepm/YEARM;  /* Duration of hstepm expressed in year unit. */
                   6431:      for(i=1;i<=nlstate;i++)
                   6432:        for(j=1;j<=nlstate;j++)
                   6433:         vareij[i][j][(int)age] =0.;
1.279     brouard  6434: 
                   6435:      /* Computing trgradg by matcov by gradg at age and summing over h
                   6436:       * and k (nhstepm) formula 15 of article
                   6437:       * Lievre-Brouard-Heathcote
                   6438:       */
                   6439:      
1.218     brouard  6440:      for(h=0;h<=nhstepm;h++){
                   6441:        for(k=0;k<=nhstepm;k++){
                   6442:         matprod2(dnewm,trgradg[h],1,nlstate,1,npar,1,npar,matcov);
                   6443:         matprod2(doldm,dnewm,1,nlstate,1,npar,1,nlstate,gradg[k]);
                   6444:         for(i=1;i<=nlstate;i++)
                   6445:           for(j=1;j<=nlstate;j++)
                   6446:             vareij[i][j][(int)age] += doldm[i][j]*hf*hf;
                   6447:        }
                   6448:      }
                   6449:                
1.279     brouard  6450:      /* pptj is p.3 or p.j = trgradgp by cov by gradgp, variance of
                   6451:       * p.j overall mortality formula 49 but computed directly because
                   6452:       * we compute the grad (wix pijx) instead of grad (pijx),even if
                   6453:       * wix is independent of theta.
                   6454:       */
1.218     brouard  6455:      matprod2(dnewmp,trgradgp,nlstate+1,nlstate+ndeath,1,npar,1,npar,matcov);
                   6456:      matprod2(doldmp,dnewmp,nlstate+1,nlstate+ndeath,1,npar,nlstate+1,nlstate+ndeath,gradgp);
                   6457:      for(j=nlstate+1;j<=nlstate+ndeath;j++)
                   6458:        for(i=nlstate+1;i<=nlstate+ndeath;i++)
                   6459:         varppt[j][i]=doldmp[j][i];
                   6460:      /* end ppptj */
                   6461:      /*  x centered again */
                   6462:                
1.242     brouard  6463:      prevalim(prlim,nlstate,x,age,oldm,savm,ftolpl,ncvyearp,ij, nres);
1.218     brouard  6464:                
                   6465:      if (popbased==1) {
                   6466:        if(mobilav ==0){
                   6467:         for(i=1; i<=nlstate;i++)
                   6468:           prlim[i][i]=probs[(int)age][i][ij];
                   6469:        }else{ /* mobilav */ 
                   6470:         for(i=1; i<=nlstate;i++)
                   6471:           prlim[i][i]=mobaverage[(int)age][i][ij];
                   6472:        }
                   6473:      }
                   6474:                
                   6475:      /* This for computing probability of death (h=1 means
                   6476:        computed over hstepm (estepm) matrices product = hstepm*stepm months) 
                   6477:        as a weighted average of prlim.
                   6478:      */
1.235     brouard  6479:      hpxij(p3mat,nhstepm,age,hstepm,x,nlstate,stepm,oldm,savm, ij, nres);  
1.218     brouard  6480:      for(j=nlstate+1;j<=nlstate+ndeath;j++){
                   6481:        for(i=1,gmp[j]=0.;i<= nlstate; i++) 
                   6482:         gmp[j] += prlim[i][i]*p3mat[i][j][1]; 
                   6483:      }    
                   6484:      /* end probability of death */
                   6485:                
                   6486:      fprintf(ficresprobmorprev,"%3d %d ",(int) age, ij);
                   6487:      for(j=nlstate+1; j<=(nlstate+ndeath);j++){
                   6488:        fprintf(ficresprobmorprev," %11.3e %11.3e",gmp[j], sqrt(varppt[j][j]));
                   6489:        for(i=1; i<=nlstate;i++){
                   6490:         fprintf(ficresprobmorprev," %11.3e %11.3e ",prlim[i][i],p3mat[i][j][1]);
                   6491:        }
                   6492:      } 
                   6493:      fprintf(ficresprobmorprev,"\n");
                   6494:                
                   6495:      fprintf(ficresvij,"%.0f ",age );
                   6496:      for(i=1; i<=nlstate;i++)
                   6497:        for(j=1; j<=nlstate;j++){
                   6498:         fprintf(ficresvij," %.4f", vareij[i][j][(int)age]);
                   6499:        }
                   6500:      fprintf(ficresvij,"\n");
                   6501:      free_matrix(gp,0,nhstepm,1,nlstate);
                   6502:      free_matrix(gm,0,nhstepm,1,nlstate);
                   6503:      free_ma3x(gradg,0,nhstepm,1,npar,1,nlstate);
                   6504:      free_ma3x(trgradg,0,nhstepm,1,nlstate,1,npar);
                   6505:      free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   6506:    } /* End age */
                   6507:    free_vector(gpp,nlstate+1,nlstate+ndeath);
                   6508:    free_vector(gmp,nlstate+1,nlstate+ndeath);
                   6509:    free_matrix(gradgp,1,npar,nlstate+1,nlstate+ndeath);
                   6510:    free_matrix(trgradgp,nlstate+1,nlstate+ndeath,1,npar); /* mu or p point j*/
                   6511:    /* fprintf(ficgp,"\nunset parametric;unset label; set ter png small size 320, 240"); */
                   6512:    fprintf(ficgp,"\nunset parametric;unset label; set ter svg size 640, 480");
                   6513:    /* for(j=nlstate+1; j<= nlstate+ndeath; j++){ *//* Only the first actually */
                   6514:    fprintf(ficgp,"\n set log y; unset log x;set xlabel \"Age\"; set ylabel \"Force of mortality (year-1)\";");
                   6515:    fprintf(ficgp,"\nset out \"%s%s.svg\";",subdirf3(optionfilefiname,"VARMUPTJGR-",digitp),digit);
                   6516:    /*   fprintf(ficgp,"\n plot \"%s\"  u 1:($3*%6.3f) not w l 1 ",fileresprobmorprev,YEARM/estepm); */
                   6517:    /*   fprintf(ficgp,"\n replot \"%s\"  u 1:(($3+1.96*$4)*%6.3f) t \"95\%% interval\" w l 2 ",fileresprobmorprev,YEARM/estepm); */
                   6518:    /*   fprintf(ficgp,"\n replot \"%s\"  u 1:(($3-1.96*$4)*%6.3f) not w l 2 ",fileresprobmorprev,YEARM/estepm); */
                   6519:    fprintf(ficgp,"\n plot \"%s\"  u 1:($3) not w l lt 1 ",subdirf(fileresprobmorprev));
                   6520:    fprintf(ficgp,"\n replot \"%s\"  u 1:(($3+1.96*$4)) t \"95%% interval\" w l lt 2 ",subdirf(fileresprobmorprev));
                   6521:    fprintf(ficgp,"\n replot \"%s\"  u 1:(($3-1.96*$4)) not w l lt 2 ",subdirf(fileresprobmorprev));
                   6522:    fprintf(fichtm,"\n<br> File (multiple files are possible if covariates are present): <A href=\"%s\">%s</a>\n",subdirf(fileresprobmorprev),subdirf(fileresprobmorprev));
                   6523:    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);
                   6524:    /*  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  6525:     */
1.218     brouard  6526:    /*   fprintf(ficgp,"\nset out \"varmuptjgr%s%s%s.svg\";replot;",digitp,optionfilefiname,digit); */
                   6527:    fprintf(ficgp,"\nset out;\nset out \"%s%s.svg\";replot;set out;\n",subdirf3(optionfilefiname,"VARMUPTJGR-",digitp),digit);
1.126     brouard  6528: 
1.218     brouard  6529:    free_vector(xp,1,npar);
                   6530:    free_matrix(doldm,1,nlstate,1,nlstate);
                   6531:    free_matrix(dnewm,1,nlstate,1,npar);
                   6532:    free_matrix(doldmp,nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
                   6533:    free_matrix(dnewmp,nlstate+1,nlstate+ndeath,1,npar);
                   6534:    free_matrix(varppt,nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
                   6535:    /* if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX); */
                   6536:    fclose(ficresprobmorprev);
                   6537:    fflush(ficgp);
                   6538:    fflush(fichtm); 
                   6539:  }  /* end varevsij */
1.126     brouard  6540: 
                   6541: /************ Variance of prevlim ******************/
1.269     brouard  6542:  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  6543: {
1.205     brouard  6544:   /* Variance of prevalence limit  for each state ij using current parameters x[] and estimates of neighbourhood give by delti*/
1.126     brouard  6545:   /*  double **prevalim(double **prlim, int nlstate, double *xp, double age, double **oldm, double **savm,double ftolpl);*/
1.164     brouard  6546: 
1.268     brouard  6547:   double **dnewmpar,**doldm;
1.126     brouard  6548:   int i, j, nhstepm, hstepm;
                   6549:   double *xp;
                   6550:   double *gp, *gm;
                   6551:   double **gradg, **trgradg;
1.208     brouard  6552:   double **mgm, **mgp;
1.126     brouard  6553:   double age,agelim;
                   6554:   int theta;
                   6555:   
                   6556:   pstamp(ficresvpl);
1.288     brouard  6557:   fprintf(ficresvpl,"# Standard deviation of period (forward stable) prevalences \n");
1.241     brouard  6558:   fprintf(ficresvpl,"# Age ");
                   6559:   if(nresult >=1)
                   6560:     fprintf(ficresvpl," Result# ");
1.126     brouard  6561:   for(i=1; i<=nlstate;i++)
                   6562:       fprintf(ficresvpl," %1d-%1d",i,i);
                   6563:   fprintf(ficresvpl,"\n");
                   6564: 
                   6565:   xp=vector(1,npar);
1.268     brouard  6566:   dnewmpar=matrix(1,nlstate,1,npar);
1.126     brouard  6567:   doldm=matrix(1,nlstate,1,nlstate);
                   6568:   
                   6569:   hstepm=1*YEARM; /* Every year of age */
                   6570:   hstepm=hstepm/stepm; /* Typically in stepm units, if j= 2 years, = 2/6 months = 4 */ 
                   6571:   agelim = AGESUP;
                   6572:   for (age=bage; age<=fage; age ++){ /* If stepm=6 months */
                   6573:     nhstepm=(int) rint((agelim-age)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */ 
                   6574:     if (stepm >= YEARM) hstepm=1;
                   6575:     nhstepm = nhstepm/hstepm; /* Typically 40/4=10 */
                   6576:     gradg=matrix(1,npar,1,nlstate);
1.208     brouard  6577:     mgp=matrix(1,npar,1,nlstate);
                   6578:     mgm=matrix(1,npar,1,nlstate);
1.126     brouard  6579:     gp=vector(1,nlstate);
                   6580:     gm=vector(1,nlstate);
                   6581: 
                   6582:     for(theta=1; theta <=npar; theta++){
                   6583:       for(i=1; i<=npar; i++){ /* Computes gradient */
                   6584:        xp[i] = x[i] + (i==theta ?delti[theta]:0);
                   6585:       }
1.288     brouard  6586:       /* if((int)age==79 ||(int)age== 80 ||(int)age== 81 ) */
                   6587:       /*       prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp,ij,nres); */
                   6588:       /* else */
                   6589:       prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp,ij,nres);
1.208     brouard  6590:       for(i=1;i<=nlstate;i++){
1.126     brouard  6591:        gp[i] = prlim[i][i];
1.208     brouard  6592:        mgp[theta][i] = prlim[i][i];
                   6593:       }
1.126     brouard  6594:       for(i=1; i<=npar; i++) /* Computes gradient */
                   6595:        xp[i] = x[i] - (i==theta ?delti[theta]:0);
1.288     brouard  6596:       /* if((int)age==79 ||(int)age== 80 ||(int)age== 81 ) */
                   6597:       /*       prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp,ij,nres); */
                   6598:       /* else */
                   6599:       prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp,ij,nres);
1.208     brouard  6600:       for(i=1;i<=nlstate;i++){
1.126     brouard  6601:        gm[i] = prlim[i][i];
1.208     brouard  6602:        mgm[theta][i] = prlim[i][i];
                   6603:       }
1.126     brouard  6604:       for(i=1;i<=nlstate;i++)
                   6605:        gradg[theta][i]= (gp[i]-gm[i])/2./delti[theta];
1.209     brouard  6606:       /* gradg[theta][2]= -gradg[theta][1]; */ /* For testing if nlstate=2 */
1.126     brouard  6607:     } /* End theta */
                   6608: 
                   6609:     trgradg =matrix(1,nlstate,1,npar);
                   6610: 
                   6611:     for(j=1; j<=nlstate;j++)
                   6612:       for(theta=1; theta <=npar; theta++)
                   6613:        trgradg[j][theta]=gradg[theta][j];
1.209     brouard  6614:     /* if((int)age==79 ||(int)age== 80 ||(int)age== 81 ){ */
                   6615:     /*   printf("\nmgm mgp %d ",(int)age); */
                   6616:     /*   for(j=1; j<=nlstate;j++){ */
                   6617:     /*         printf(" %d ",j); */
                   6618:     /*         for(theta=1; theta <=npar; theta++) */
                   6619:     /*           printf(" %d %lf %lf",theta,mgm[theta][j],mgp[theta][j]); */
                   6620:     /*         printf("\n "); */
                   6621:     /*   } */
                   6622:     /* } */
                   6623:     /* if((int)age==79 ||(int)age== 80 ||(int)age== 81 ){ */
                   6624:     /*   printf("\n gradg %d ",(int)age); */
                   6625:     /*   for(j=1; j<=nlstate;j++){ */
                   6626:     /*         printf("%d ",j); */
                   6627:     /*         for(theta=1; theta <=npar; theta++) */
                   6628:     /*           printf("%d %lf ",theta,gradg[theta][j]); */
                   6629:     /*         printf("\n "); */
                   6630:     /*   } */
                   6631:     /* } */
1.126     brouard  6632: 
                   6633:     for(i=1;i<=nlstate;i++)
                   6634:       varpl[i][(int)age] =0.;
1.209     brouard  6635:     if((int)age==79 ||(int)age== 80  ||(int)age== 81){
1.268     brouard  6636:     matprod2(dnewmpar,trgradg,1,nlstate,1,npar,1,npar,matcov);
                   6637:     matprod2(doldm,dnewmpar,1,nlstate,1,npar,1,nlstate,gradg);
1.205     brouard  6638:     }else{
1.268     brouard  6639:     matprod2(dnewmpar,trgradg,1,nlstate,1,npar,1,npar,matcov);
                   6640:     matprod2(doldm,dnewmpar,1,nlstate,1,npar,1,nlstate,gradg);
1.205     brouard  6641:     }
1.126     brouard  6642:     for(i=1;i<=nlstate;i++)
                   6643:       varpl[i][(int)age] = doldm[i][i]; /* Covariances are useless */
                   6644: 
                   6645:     fprintf(ficresvpl,"%.0f ",age );
1.241     brouard  6646:     if(nresult >=1)
                   6647:       fprintf(ficresvpl,"%d ",nres );
1.288     brouard  6648:     for(i=1; i<=nlstate;i++){
1.126     brouard  6649:       fprintf(ficresvpl," %.5f (%.5f)",prlim[i][i],sqrt(varpl[i][(int)age]));
1.288     brouard  6650:       /* for(j=1;j<=nlstate;j++) */
                   6651:       /*       fprintf(ficresvpl," %d %.5f ",j,prlim[j][i]); */
                   6652:     }
1.126     brouard  6653:     fprintf(ficresvpl,"\n");
                   6654:     free_vector(gp,1,nlstate);
                   6655:     free_vector(gm,1,nlstate);
1.208     brouard  6656:     free_matrix(mgm,1,npar,1,nlstate);
                   6657:     free_matrix(mgp,1,npar,1,nlstate);
1.126     brouard  6658:     free_matrix(gradg,1,npar,1,nlstate);
                   6659:     free_matrix(trgradg,1,nlstate,1,npar);
                   6660:   } /* End age */
                   6661: 
                   6662:   free_vector(xp,1,npar);
                   6663:   free_matrix(doldm,1,nlstate,1,npar);
1.268     brouard  6664:   free_matrix(dnewmpar,1,nlstate,1,nlstate);
                   6665: 
                   6666: }
                   6667: 
                   6668: 
                   6669: /************ Variance of backprevalence limit ******************/
1.269     brouard  6670:  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  6671: {
                   6672:   /* Variance of backward prevalence limit  for each state ij using current parameters x[] and estimates of neighbourhood give by delti*/
                   6673:   /*  double **prevalim(double **prlim, int nlstate, double *xp, double age, double **oldm, double **savm,double ftolpl);*/
                   6674: 
                   6675:   double **dnewmpar,**doldm;
                   6676:   int i, j, nhstepm, hstepm;
                   6677:   double *xp;
                   6678:   double *gp, *gm;
                   6679:   double **gradg, **trgradg;
                   6680:   double **mgm, **mgp;
                   6681:   double age,agelim;
                   6682:   int theta;
                   6683:   
                   6684:   pstamp(ficresvbl);
                   6685:   fprintf(ficresvbl,"# Standard deviation of back (stable) prevalences \n");
                   6686:   fprintf(ficresvbl,"# Age ");
                   6687:   if(nresult >=1)
                   6688:     fprintf(ficresvbl," Result# ");
                   6689:   for(i=1; i<=nlstate;i++)
                   6690:       fprintf(ficresvbl," %1d-%1d",i,i);
                   6691:   fprintf(ficresvbl,"\n");
                   6692: 
                   6693:   xp=vector(1,npar);
                   6694:   dnewmpar=matrix(1,nlstate,1,npar);
                   6695:   doldm=matrix(1,nlstate,1,nlstate);
                   6696:   
                   6697:   hstepm=1*YEARM; /* Every year of age */
                   6698:   hstepm=hstepm/stepm; /* Typically in stepm units, if j= 2 years, = 2/6 months = 4 */ 
                   6699:   agelim = AGEINF;
                   6700:   for (age=fage; age>=bage; age --){ /* If stepm=6 months */
                   6701:     nhstepm=(int) rint((age-agelim)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */ 
                   6702:     if (stepm >= YEARM) hstepm=1;
                   6703:     nhstepm = nhstepm/hstepm; /* Typically 40/4=10 */
                   6704:     gradg=matrix(1,npar,1,nlstate);
                   6705:     mgp=matrix(1,npar,1,nlstate);
                   6706:     mgm=matrix(1,npar,1,nlstate);
                   6707:     gp=vector(1,nlstate);
                   6708:     gm=vector(1,nlstate);
                   6709: 
                   6710:     for(theta=1; theta <=npar; theta++){
                   6711:       for(i=1; i<=npar; i++){ /* Computes gradient */
                   6712:        xp[i] = x[i] + (i==theta ?delti[theta]:0);
                   6713:       }
                   6714:       if(mobilavproj > 0 )
                   6715:        bprevalim(bprlim, mobaverage,nlstate,xp,age,ftolpl,ncvyearp,ij,nres);
                   6716:       else
                   6717:        bprevalim(bprlim, mobaverage,nlstate,xp,age,ftolpl,ncvyearp,ij,nres);
                   6718:       for(i=1;i<=nlstate;i++){
                   6719:        gp[i] = bprlim[i][i];
                   6720:        mgp[theta][i] = bprlim[i][i];
                   6721:       }
                   6722:      for(i=1; i<=npar; i++) /* Computes gradient */
                   6723:        xp[i] = x[i] - (i==theta ?delti[theta]:0);
                   6724:        if(mobilavproj > 0 )
                   6725:        bprevalim(bprlim, mobaverage,nlstate,xp,age,ftolpl,ncvyearp,ij,nres);
                   6726:        else
                   6727:        bprevalim(bprlim, mobaverage,nlstate,xp,age,ftolpl,ncvyearp,ij,nres);
                   6728:       for(i=1;i<=nlstate;i++){
                   6729:        gm[i] = bprlim[i][i];
                   6730:        mgm[theta][i] = bprlim[i][i];
                   6731:       }
                   6732:       for(i=1;i<=nlstate;i++)
                   6733:        gradg[theta][i]= (gp[i]-gm[i])/2./delti[theta];
                   6734:       /* gradg[theta][2]= -gradg[theta][1]; */ /* For testing if nlstate=2 */
                   6735:     } /* End theta */
                   6736: 
                   6737:     trgradg =matrix(1,nlstate,1,npar);
                   6738: 
                   6739:     for(j=1; j<=nlstate;j++)
                   6740:       for(theta=1; theta <=npar; theta++)
                   6741:        trgradg[j][theta]=gradg[theta][j];
                   6742:     /* if((int)age==79 ||(int)age== 80 ||(int)age== 81 ){ */
                   6743:     /*   printf("\nmgm mgp %d ",(int)age); */
                   6744:     /*   for(j=1; j<=nlstate;j++){ */
                   6745:     /*         printf(" %d ",j); */
                   6746:     /*         for(theta=1; theta <=npar; theta++) */
                   6747:     /*           printf(" %d %lf %lf",theta,mgm[theta][j],mgp[theta][j]); */
                   6748:     /*         printf("\n "); */
                   6749:     /*   } */
                   6750:     /* } */
                   6751:     /* if((int)age==79 ||(int)age== 80 ||(int)age== 81 ){ */
                   6752:     /*   printf("\n gradg %d ",(int)age); */
                   6753:     /*   for(j=1; j<=nlstate;j++){ */
                   6754:     /*         printf("%d ",j); */
                   6755:     /*         for(theta=1; theta <=npar; theta++) */
                   6756:     /*           printf("%d %lf ",theta,gradg[theta][j]); */
                   6757:     /*         printf("\n "); */
                   6758:     /*   } */
                   6759:     /* } */
                   6760: 
                   6761:     for(i=1;i<=nlstate;i++)
                   6762:       varbpl[i][(int)age] =0.;
                   6763:     if((int)age==79 ||(int)age== 80  ||(int)age== 81){
                   6764:     matprod2(dnewmpar,trgradg,1,nlstate,1,npar,1,npar,matcov);
                   6765:     matprod2(doldm,dnewmpar,1,nlstate,1,npar,1,nlstate,gradg);
                   6766:     }else{
                   6767:     matprod2(dnewmpar,trgradg,1,nlstate,1,npar,1,npar,matcov);
                   6768:     matprod2(doldm,dnewmpar,1,nlstate,1,npar,1,nlstate,gradg);
                   6769:     }
                   6770:     for(i=1;i<=nlstate;i++)
                   6771:       varbpl[i][(int)age] = doldm[i][i]; /* Covariances are useless */
                   6772: 
                   6773:     fprintf(ficresvbl,"%.0f ",age );
                   6774:     if(nresult >=1)
                   6775:       fprintf(ficresvbl,"%d ",nres );
                   6776:     for(i=1; i<=nlstate;i++)
                   6777:       fprintf(ficresvbl," %.5f (%.5f)",bprlim[i][i],sqrt(varbpl[i][(int)age]));
                   6778:     fprintf(ficresvbl,"\n");
                   6779:     free_vector(gp,1,nlstate);
                   6780:     free_vector(gm,1,nlstate);
                   6781:     free_matrix(mgm,1,npar,1,nlstate);
                   6782:     free_matrix(mgp,1,npar,1,nlstate);
                   6783:     free_matrix(gradg,1,npar,1,nlstate);
                   6784:     free_matrix(trgradg,1,nlstate,1,npar);
                   6785:   } /* End age */
                   6786: 
                   6787:   free_vector(xp,1,npar);
                   6788:   free_matrix(doldm,1,nlstate,1,npar);
                   6789:   free_matrix(dnewmpar,1,nlstate,1,nlstate);
1.126     brouard  6790: 
                   6791: }
                   6792: 
                   6793: /************ Variance of one-step probabilities  ******************/
                   6794: 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  6795:  {
                   6796:    int i, j=0,  k1, l1, tj;
                   6797:    int k2, l2, j1,  z1;
                   6798:    int k=0, l;
                   6799:    int first=1, first1, first2;
                   6800:    double cv12, mu1, mu2, lc1, lc2, v12, v21, v11, v22,v1,v2, c12, tnalp;
                   6801:    double **dnewm,**doldm;
                   6802:    double *xp;
                   6803:    double *gp, *gm;
                   6804:    double **gradg, **trgradg;
                   6805:    double **mu;
                   6806:    double age, cov[NCOVMAX+1];
                   6807:    double std=2.0; /* Number of standard deviation wide of confidence ellipsoids */
                   6808:    int theta;
                   6809:    char fileresprob[FILENAMELENGTH];
                   6810:    char fileresprobcov[FILENAMELENGTH];
                   6811:    char fileresprobcor[FILENAMELENGTH];
                   6812:    double ***varpij;
                   6813: 
                   6814:    strcpy(fileresprob,"PROB_"); 
                   6815:    strcat(fileresprob,fileres);
                   6816:    if((ficresprob=fopen(fileresprob,"w"))==NULL) {
                   6817:      printf("Problem with resultfile: %s\n", fileresprob);
                   6818:      fprintf(ficlog,"Problem with resultfile: %s\n", fileresprob);
                   6819:    }
                   6820:    strcpy(fileresprobcov,"PROBCOV_"); 
                   6821:    strcat(fileresprobcov,fileresu);
                   6822:    if((ficresprobcov=fopen(fileresprobcov,"w"))==NULL) {
                   6823:      printf("Problem with resultfile: %s\n", fileresprobcov);
                   6824:      fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobcov);
                   6825:    }
                   6826:    strcpy(fileresprobcor,"PROBCOR_"); 
                   6827:    strcat(fileresprobcor,fileresu);
                   6828:    if((ficresprobcor=fopen(fileresprobcor,"w"))==NULL) {
                   6829:      printf("Problem with resultfile: %s\n", fileresprobcor);
                   6830:      fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobcor);
                   6831:    }
                   6832:    printf("Computing standard deviation of one-step probabilities: result on file '%s' \n",fileresprob);
                   6833:    fprintf(ficlog,"Computing standard deviation of one-step probabilities: result on file '%s' \n",fileresprob);
                   6834:    printf("Computing matrix of variance covariance of one-step probabilities: result on file '%s' \n",fileresprobcov);
                   6835:    fprintf(ficlog,"Computing matrix of variance covariance of one-step probabilities: result on file '%s' \n",fileresprobcov);
                   6836:    printf("and correlation matrix of one-step probabilities: result on file '%s' \n",fileresprobcor);
                   6837:    fprintf(ficlog,"and correlation matrix of one-step probabilities: result on file '%s' \n",fileresprobcor);
                   6838:    pstamp(ficresprob);
                   6839:    fprintf(ficresprob,"#One-step probabilities and stand. devi in ()\n");
                   6840:    fprintf(ficresprob,"# Age");
                   6841:    pstamp(ficresprobcov);
                   6842:    fprintf(ficresprobcov,"#One-step probabilities and covariance matrix\n");
                   6843:    fprintf(ficresprobcov,"# Age");
                   6844:    pstamp(ficresprobcor);
                   6845:    fprintf(ficresprobcor,"#One-step probabilities and correlation matrix\n");
                   6846:    fprintf(ficresprobcor,"# Age");
1.126     brouard  6847: 
                   6848: 
1.222     brouard  6849:    for(i=1; i<=nlstate;i++)
                   6850:      for(j=1; j<=(nlstate+ndeath);j++){
                   6851:        fprintf(ficresprob," p%1d-%1d (SE)",i,j);
                   6852:        fprintf(ficresprobcov," p%1d-%1d ",i,j);
                   6853:        fprintf(ficresprobcor," p%1d-%1d ",i,j);
                   6854:      }  
                   6855:    /* fprintf(ficresprob,"\n");
                   6856:       fprintf(ficresprobcov,"\n");
                   6857:       fprintf(ficresprobcor,"\n");
                   6858:    */
                   6859:    xp=vector(1,npar);
                   6860:    dnewm=matrix(1,(nlstate)*(nlstate+ndeath),1,npar);
                   6861:    doldm=matrix(1,(nlstate)*(nlstate+ndeath),1,(nlstate)*(nlstate+ndeath));
                   6862:    mu=matrix(1,(nlstate)*(nlstate+ndeath), (int) bage, (int)fage);
                   6863:    varpij=ma3x(1,nlstate*(nlstate+ndeath),1,nlstate*(nlstate+ndeath),(int) bage, (int) fage);
                   6864:    first=1;
                   6865:    fprintf(ficgp,"\n# Routine varprob");
                   6866:    fprintf(fichtm,"\n<li><h4> Computing and drawing one step probabilities with their confidence intervals</h4></li>\n");
                   6867:    fprintf(fichtm,"\n");
                   6868: 
1.288     brouard  6869:    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  6870:    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);
                   6871:    fprintf(fichtmcov,"\nEllipsoids of confidence centered on point (p<inf>ij</inf>, p<inf>kl</inf>) are estimated \
1.126     brouard  6872: and drawn. It helps understanding how is the covariance between two incidences.\
                   6873:  They are expressed in year<sup>-1</sup> in order to be less dependent of stepm.<br>\n");
1.222     brouard  6874:    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  6875: It can be understood this way: if pij and pkl where uncorrelated the (2x2) matrix of covariance \
                   6876: would have been (1/(var pij), 0 , 0, 1/(var pkl)), and the confidence interval would be 2 \
                   6877: standard deviations wide on each axis. <br>\
                   6878:  Now, if both incidences are correlated (usual case) we diagonalised the inverse of the covariance matrix\
                   6879:  and made the appropriate rotation to look at the uncorrelated principal directions.<br>\
                   6880: To be simple, these graphs help to understand the significativity of each parameter in relation to a second other one.<br> \n");
                   6881: 
1.222     brouard  6882:    cov[1]=1;
                   6883:    /* tj=cptcoveff; */
1.225     brouard  6884:    tj = (int) pow(2,cptcoveff);
1.222     brouard  6885:    if (cptcovn<1) {tj=1;ncodemax[1]=1;}
                   6886:    j1=0;
1.224     brouard  6887:    for(j1=1; j1<=tj;j1++){  /* For each valid combination of covariates or only once*/
1.222     brouard  6888:      if  (cptcovn>0) {
                   6889:        fprintf(ficresprob, "\n#********** Variable "); 
1.225     brouard  6890:        for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresprob, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
1.222     brouard  6891:        fprintf(ficresprob, "**********\n#\n");
                   6892:        fprintf(ficresprobcov, "\n#********** Variable "); 
1.225     brouard  6893:        for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresprobcov, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
1.222     brouard  6894:        fprintf(ficresprobcov, "**********\n#\n");
1.220     brouard  6895:                        
1.222     brouard  6896:        fprintf(ficgp, "\n#********** Variable "); 
1.225     brouard  6897:        for (z1=1; z1<=cptcoveff; z1++) fprintf(ficgp, " V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
1.222     brouard  6898:        fprintf(ficgp, "**********\n#\n");
1.220     brouard  6899:                        
                   6900:                        
1.222     brouard  6901:        fprintf(fichtmcov, "\n<hr  size=\"2\" color=\"#EC5E5E\">********** Variable "); 
1.319     brouard  6902:        /* for (z1=1; z1<=cptcoveff; z1++) fprintf(fichtm, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]); */
                   6903:        for (z1=1; z1<=cptcoveff; z1++) fprintf(fichtmcov, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
1.222     brouard  6904:        fprintf(fichtmcov, "**********\n<hr size=\"2\" color=\"#EC5E5E\">");
1.220     brouard  6905:                        
1.222     brouard  6906:        fprintf(ficresprobcor, "\n#********** Variable ");    
1.225     brouard  6907:        for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresprobcor, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
1.222     brouard  6908:        fprintf(ficresprobcor, "**********\n#");    
                   6909:        if(invalidvarcomb[j1]){
                   6910:         fprintf(ficgp,"\n#Combination (%d) ignored because no cases \n",j1); 
                   6911:         fprintf(fichtmcov,"\n<h3>Combination (%d) ignored because no cases </h3>\n",j1); 
                   6912:         continue;
                   6913:        }
                   6914:      }
                   6915:      gradg=matrix(1,npar,1,(nlstate)*(nlstate+ndeath));
                   6916:      trgradg=matrix(1,(nlstate)*(nlstate+ndeath),1,npar);
                   6917:      gp=vector(1,(nlstate)*(nlstate+ndeath));
                   6918:      gm=vector(1,(nlstate)*(nlstate+ndeath));
                   6919:      for (age=bage; age<=fage; age ++){ 
                   6920:        cov[2]=age;
                   6921:        if(nagesqr==1)
                   6922:         cov[3]= age*age;
                   6923:        for (k=1; k<=cptcovn;k++) {
                   6924:         cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(j1,k)];
                   6925:         /*cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(j1,Tvar[k])];*//* j1 1 2 3 4
                   6926:                                                                    * 1  1 1 1 1
                   6927:                                                                    * 2  2 1 1 1
                   6928:                                                                    * 3  1 2 1 1
                   6929:                                                                    */
                   6930:         /* nbcode[1][1]=0 nbcode[1][2]=1;*/
                   6931:        }
1.319     brouard  6932:        /* V2+V1+V4+V3*age Tvar[4]=3 ; V1+V2*age Tvar[2]=2; V1+V1*age Tvar[2]=1, Tage[1]=2 */
                   6933:        /* ) p nbcode[Tvar[Tage[k]]][(1 & (ij-1) >> (k-1))+1] */
                   6934:        /*for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2]; */
                   6935:        for (k=1; k<=cptcovage;k++)
                   6936:         cov[2+Tage[k]+nagesqr]=nbcode[Tvar[Tage[k]]][codtabm(ij,k)]*cov[2];
1.222     brouard  6937:        for (k=1; k<=cptcovprod;k++)
                   6938:         cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)]*nbcode[Tvard[k][2]][codtabm(ij,k)];
1.220     brouard  6939:                        
                   6940:                        
1.222     brouard  6941:        for(theta=1; theta <=npar; theta++){
                   6942:         for(i=1; i<=npar; i++)
                   6943:           xp[i] = x[i] + (i==theta ?delti[theta]:(double)0);
1.220     brouard  6944:                                
1.222     brouard  6945:         pmij(pmmij,cov,ncovmodel,xp,nlstate);
1.220     brouard  6946:                                
1.222     brouard  6947:         k=0;
                   6948:         for(i=1; i<= (nlstate); i++){
                   6949:           for(j=1; j<=(nlstate+ndeath);j++){
                   6950:             k=k+1;
                   6951:             gp[k]=pmmij[i][j];
                   6952:           }
                   6953:         }
1.220     brouard  6954:                                
1.222     brouard  6955:         for(i=1; i<=npar; i++)
                   6956:           xp[i] = x[i] - (i==theta ?delti[theta]:(double)0);
1.220     brouard  6957:                                
1.222     brouard  6958:         pmij(pmmij,cov,ncovmodel,xp,nlstate);
                   6959:         k=0;
                   6960:         for(i=1; i<=(nlstate); i++){
                   6961:           for(j=1; j<=(nlstate+ndeath);j++){
                   6962:             k=k+1;
                   6963:             gm[k]=pmmij[i][j];
                   6964:           }
                   6965:         }
1.220     brouard  6966:                                
1.222     brouard  6967:         for(i=1; i<= (nlstate)*(nlstate+ndeath); i++) 
                   6968:           gradg[theta][i]=(gp[i]-gm[i])/(double)2./delti[theta];  
                   6969:        }
1.126     brouard  6970: 
1.222     brouard  6971:        for(j=1; j<=(nlstate)*(nlstate+ndeath);j++)
                   6972:         for(theta=1; theta <=npar; theta++)
                   6973:           trgradg[j][theta]=gradg[theta][j];
1.220     brouard  6974:                        
1.222     brouard  6975:        matprod2(dnewm,trgradg,1,(nlstate)*(nlstate+ndeath),1,npar,1,npar,matcov); 
                   6976:        matprod2(doldm,dnewm,1,(nlstate)*(nlstate+ndeath),1,npar,1,(nlstate)*(nlstate+ndeath),gradg);
1.220     brouard  6977:                        
1.222     brouard  6978:        pmij(pmmij,cov,ncovmodel,x,nlstate);
1.220     brouard  6979:                        
1.222     brouard  6980:        k=0;
                   6981:        for(i=1; i<=(nlstate); i++){
                   6982:         for(j=1; j<=(nlstate+ndeath);j++){
                   6983:           k=k+1;
                   6984:           mu[k][(int) age]=pmmij[i][j];
                   6985:         }
                   6986:        }
                   6987:        for(i=1;i<=(nlstate)*(nlstate+ndeath);i++)
                   6988:         for(j=1;j<=(nlstate)*(nlstate+ndeath);j++)
                   6989:           varpij[i][j][(int)age] = doldm[i][j];
1.220     brouard  6990:                        
1.222     brouard  6991:        /*printf("\n%d ",(int)age);
                   6992:         for (i=1; i<=(nlstate)*(nlstate+ndeath);i++){
                   6993:         printf("%e [%e ;%e] ",gm[i],gm[i]-2*sqrt(doldm[i][i]),gm[i]+2*sqrt(doldm[i][i]));
                   6994:         fprintf(ficlog,"%e [%e ;%e] ",gm[i],gm[i]-2*sqrt(doldm[i][i]),gm[i]+2*sqrt(doldm[i][i]));
                   6995:         }*/
1.220     brouard  6996:                        
1.222     brouard  6997:        fprintf(ficresprob,"\n%d ",(int)age);
                   6998:        fprintf(ficresprobcov,"\n%d ",(int)age);
                   6999:        fprintf(ficresprobcor,"\n%d ",(int)age);
1.220     brouard  7000:                        
1.222     brouard  7001:        for (i=1; i<=(nlstate)*(nlstate+ndeath);i++)
                   7002:         fprintf(ficresprob,"%11.3e (%11.3e) ",mu[i][(int) age],sqrt(varpij[i][i][(int)age]));
                   7003:        for (i=1; i<=(nlstate)*(nlstate+ndeath);i++){
                   7004:         fprintf(ficresprobcov,"%11.3e ",mu[i][(int) age]);
                   7005:         fprintf(ficresprobcor,"%11.3e ",mu[i][(int) age]);
                   7006:        }
                   7007:        i=0;
                   7008:        for (k=1; k<=(nlstate);k++){
                   7009:         for (l=1; l<=(nlstate+ndeath);l++){ 
                   7010:           i++;
                   7011:           fprintf(ficresprobcov,"\n%d %d-%d",(int)age,k,l);
                   7012:           fprintf(ficresprobcor,"\n%d %d-%d",(int)age,k,l);
                   7013:           for (j=1; j<=i;j++){
                   7014:             /* printf(" k=%d l=%d i=%d j=%d\n",k,l,i,j);fflush(stdout); */
                   7015:             fprintf(ficresprobcov," %11.3e",varpij[i][j][(int)age]);
                   7016:             fprintf(ficresprobcor," %11.3e",varpij[i][j][(int) age]/sqrt(varpij[i][i][(int) age])/sqrt(varpij[j][j][(int)age]));
                   7017:           }
                   7018:         }
                   7019:        }/* end of loop for state */
                   7020:      } /* end of loop for age */
                   7021:      free_vector(gp,1,(nlstate+ndeath)*(nlstate+ndeath));
                   7022:      free_vector(gm,1,(nlstate+ndeath)*(nlstate+ndeath));
                   7023:      free_matrix(trgradg,1,(nlstate+ndeath)*(nlstate+ndeath),1,npar);
                   7024:      free_matrix(gradg,1,(nlstate+ndeath)*(nlstate+ndeath),1,npar);
                   7025:     
                   7026:      /* Confidence intervalle of pij  */
                   7027:      /*
                   7028:        fprintf(ficgp,"\nunset parametric;unset label");
                   7029:        fprintf(ficgp,"\nset log y;unset log x; set xlabel \"Age\";set ylabel \"probability (year-1)\"");
                   7030:        fprintf(ficgp,"\nset ter png small\nset size 0.65,0.65");
                   7031:        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);
                   7032:        fprintf(fichtm,"\n<br><img src=\"pijgr%s.png\"> ",optionfilefiname);
                   7033:        fprintf(ficgp,"\nset out \"pijgr%s.png\"",optionfilefiname);
                   7034:        fprintf(ficgp,"\nplot \"%s\" every :::%d::%d u 1:2 \"\%%lf",k1,k2,xfilevarprob);
                   7035:      */
                   7036:                
                   7037:      /* Drawing ellipsoids of confidence of two variables p(k1-l1,k2-l2)*/
                   7038:      first1=1;first2=2;
                   7039:      for (k2=1; k2<=(nlstate);k2++){
                   7040:        for (l2=1; l2<=(nlstate+ndeath);l2++){ 
                   7041:         if(l2==k2) continue;
                   7042:         j=(k2-1)*(nlstate+ndeath)+l2;
                   7043:         for (k1=1; k1<=(nlstate);k1++){
                   7044:           for (l1=1; l1<=(nlstate+ndeath);l1++){ 
                   7045:             if(l1==k1) continue;
                   7046:             i=(k1-1)*(nlstate+ndeath)+l1;
                   7047:             if(i<=j) continue;
                   7048:             for (age=bage; age<=fage; age ++){ 
                   7049:               if ((int)age %5==0){
                   7050:                 v1=varpij[i][i][(int)age]/stepm*YEARM/stepm*YEARM;
                   7051:                 v2=varpij[j][j][(int)age]/stepm*YEARM/stepm*YEARM;
                   7052:                 cv12=varpij[i][j][(int)age]/stepm*YEARM/stepm*YEARM;
                   7053:                 mu1=mu[i][(int) age]/stepm*YEARM ;
                   7054:                 mu2=mu[j][(int) age]/stepm*YEARM;
                   7055:                 c12=cv12/sqrt(v1*v2);
                   7056:                 /* Computing eigen value of matrix of covariance */
                   7057:                 lc1=((v1+v2)+sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
                   7058:                 lc2=((v1+v2)-sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
                   7059:                 if ((lc2 <0) || (lc1 <0) ){
                   7060:                   if(first2==1){
                   7061:                     first1=0;
                   7062:                     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);
                   7063:                   }
                   7064:                   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);
                   7065:                   /* lc1=fabs(lc1); */ /* If we want to have them positive */
                   7066:                   /* lc2=fabs(lc2); */
                   7067:                 }
1.220     brouard  7068:                                                                
1.222     brouard  7069:                 /* Eigen vectors */
1.280     brouard  7070:                 if(1+(v1-lc1)*(v1-lc1)/cv12/cv12 <1.e-5){
                   7071:                   printf(" Error sqrt of a negative number: %lf\n",1+(v1-lc1)*(v1-lc1)/cv12/cv12);
                   7072:                   fprintf(ficlog," Error sqrt of a negative number: %lf\n",1+(v1-lc1)*(v1-lc1)/cv12/cv12);
                   7073:                   v11=(1./sqrt(fabs(1+(v1-lc1)*(v1-lc1)/cv12/cv12)));
                   7074:                 }else
                   7075:                   v11=(1./sqrt(1+(v1-lc1)*(v1-lc1)/cv12/cv12));
1.222     brouard  7076:                 /*v21=sqrt(1.-v11*v11); *//* error */
                   7077:                 v21=(lc1-v1)/cv12*v11;
                   7078:                 v12=-v21;
                   7079:                 v22=v11;
                   7080:                 tnalp=v21/v11;
                   7081:                 if(first1==1){
                   7082:                   first1=0;
                   7083:                   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);
                   7084:                 }
                   7085:                 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);
                   7086:                 /*printf(fignu*/
                   7087:                 /* mu1+ v11*lc1*cost + v12*lc2*sin(t) */
                   7088:                 /* mu2+ v21*lc1*cost + v22*lc2*sin(t) */
                   7089:                 if(first==1){
                   7090:                   first=0;
                   7091:                   fprintf(ficgp,"\n# Ellipsoids of confidence\n#\n");
                   7092:                   fprintf(ficgp,"\nset parametric;unset label");
                   7093:                   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);
                   7094:                   fprintf(ficgp,"\nset ter svg size 640, 480");
1.266     brouard  7095:                   fprintf(fichtmcov,"\n<p><br>Ellipsoids of confidence cov(p%1d%1d,p%1d%1d) expressed in year<sup>-1</sup>\
1.220     brouard  7096:  :<a href=\"%s_%d%1d%1d-%1d%1d.svg\">                                                                                                                                          \
1.201     brouard  7097: %s_%d%1d%1d-%1d%1d.svg</A>, ",k1,l1,k2,l2,\
1.222     brouard  7098:                           subdirf2(optionfilefiname,"VARPIJGR_"), j1,k1,l1,k2,l2,      \
                   7099:                           subdirf2(optionfilefiname,"VARPIJGR_"), j1,k1,l1,k2,l2);
                   7100:                   fprintf(fichtmcov,"\n<br><img src=\"%s_%d%1d%1d-%1d%1d.svg\"> ",subdirf2(optionfilefiname,"VARPIJGR_"), j1,k1,l1,k2,l2);
                   7101:                   fprintf(fichtmcov,"\n<br> Correlation at age %d (%.3f),",(int) age, c12);
                   7102:                   fprintf(ficgp,"\nset out \"%s_%d%1d%1d-%1d%1d.svg\"",subdirf2(optionfilefiname,"VARPIJGR_"), j1,k1,l1,k2,l2);
                   7103:                   fprintf(ficgp,"\nset label \"%d\" at %11.3e,%11.3e center",(int) age, mu1,mu2);
                   7104:                   fprintf(ficgp,"\n# Age %d, p%1d%1d - p%1d%1d",(int) age, k1,l1,k2,l2);
                   7105:                   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  7106:                           mu1,std,v11,sqrt(fabs(lc1)),v12,sqrt(fabs(lc2)), \
                   7107:                           mu2,std,v21,sqrt(fabs(lc1)),v22,sqrt(fabs(lc2))); /* For gnuplot only */
1.222     brouard  7108:                 }else{
                   7109:                   first=0;
                   7110:                   fprintf(fichtmcov," %d (%.3f),",(int) age, c12);
                   7111:                   fprintf(ficgp,"\n# Age %d, p%1d%1d - p%1d%1d",(int) age, k1,l1,k2,l2);
                   7112:                   fprintf(ficgp,"\nset label \"%d\" at %11.3e,%11.3e center",(int) age, mu1,mu2);
                   7113:                   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  7114:                           mu1,std,v11,sqrt(lc1),v12,sqrt(fabs(lc2)),   \
                   7115:                           mu2,std,v21,sqrt(lc1),v22,sqrt(fabs(lc2)));
1.222     brouard  7116:                 }/* if first */
                   7117:               } /* age mod 5 */
                   7118:             } /* end loop age */
                   7119:             fprintf(ficgp,"\nset out;\nset out \"%s_%d%1d%1d-%1d%1d.svg\";replot;set out;",subdirf2(optionfilefiname,"VARPIJGR_"), j1,k1,l1,k2,l2);
                   7120:             first=1;
                   7121:           } /*l12 */
                   7122:         } /* k12 */
                   7123:        } /*l1 */
                   7124:      }/* k1 */
                   7125:    }  /* loop on combination of covariates j1 */
                   7126:    free_ma3x(varpij,1,nlstate,1,nlstate+ndeath,(int) bage, (int)fage);
                   7127:    free_matrix(mu,1,(nlstate+ndeath)*(nlstate+ndeath),(int) bage, (int)fage);
                   7128:    free_matrix(doldm,1,(nlstate)*(nlstate+ndeath),1,(nlstate)*(nlstate+ndeath));
                   7129:    free_matrix(dnewm,1,(nlstate)*(nlstate+ndeath),1,npar);
                   7130:    free_vector(xp,1,npar);
                   7131:    fclose(ficresprob);
                   7132:    fclose(ficresprobcov);
                   7133:    fclose(ficresprobcor);
                   7134:    fflush(ficgp);
                   7135:    fflush(fichtmcov);
                   7136:  }
1.126     brouard  7137: 
                   7138: 
                   7139: /******************* Printing html file ***********/
1.201     brouard  7140: void printinghtml(char fileresu[], char title[], char datafile[], int firstpass, \
1.126     brouard  7141:                  int lastpass, int stepm, int weightopt, char model[],\
                   7142:                  int imx,int jmin, int jmax, double jmeanint,char rfileres[],\
1.296     brouard  7143:                  int popforecast, int mobilav, int prevfcast, int mobilavproj, int prevbcast, int estepm , \
                   7144:                  double jprev1, double mprev1,double anprev1, double dateprev1, double dateprojd, double dateback1, \
                   7145:                  double jprev2, double mprev2,double anprev2, double dateprev2, double dateprojf, double dateback2){
1.237     brouard  7146:   int jj1, k1, i1, cpt, k4, nres;
1.319     brouard  7147:   /* In fact some results are already printed in fichtm which is open */
1.126     brouard  7148:    fprintf(fichtm,"<ul><li><a href='#firstorder'>Result files (first order: no variance)</a>\n \
                   7149:    <li><a href='#secondorder'>Result files (second order (variance)</a>\n \
                   7150: </ul>");
1.319     brouard  7151: /*    fprintf(fichtm,"<ul><li> model=1+age+%s\n \ */
                   7152: /* </ul>", model); */
1.214     brouard  7153:    fprintf(fichtm,"<ul><li><h4><a name='firstorder'>Result files (first order: no variance)</a></h4>\n");
                   7154:    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",
                   7155:           jprev1, mprev1,anprev1,jprev2, mprev2,anprev2,subdirfext3(optionfilefiname,"PHTMFR_",".htm"),subdirfext3(optionfilefiname,"PHTMFR_",".htm"));
                   7156:    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  7157:           jprev1, mprev1,anprev1,jprev2, mprev2,anprev2,subdirfext3(optionfilefiname,"PHTM_",".htm"),subdirfext3(optionfilefiname,"PHTM_",".htm"));
                   7158:    fprintf(fichtm,",  <a href=\"%s\">%s</a> (text file) <br>\n",subdirf2(fileresu,"P_"),subdirf2(fileresu,"P_"));
1.126     brouard  7159:    fprintf(fichtm,"\
                   7160:  - Estimated transition probabilities over %d (stepm) months: <a href=\"%s\">%s</a><br>\n ",
1.201     brouard  7161:           stepm,subdirf2(fileresu,"PIJ_"),subdirf2(fileresu,"PIJ_"));
1.126     brouard  7162:    fprintf(fichtm,"\
1.217     brouard  7163:  - Estimated back transition probabilities over %d (stepm) months: <a href=\"%s\">%s</a><br>\n ",
                   7164:           stepm,subdirf2(fileresu,"PIJB_"),subdirf2(fileresu,"PIJB_"));
                   7165:    fprintf(fichtm,"\
1.288     brouard  7166:  - Period (forward) prevalence in each health state: <a href=\"%s\">%s</a> <br>\n",
1.201     brouard  7167:           subdirf2(fileresu,"PL_"),subdirf2(fileresu,"PL_"));
1.126     brouard  7168:    fprintf(fichtm,"\
1.288     brouard  7169:  - Backward prevalence in each health state: <a href=\"%s\">%s</a> <br>\n",
1.217     brouard  7170:           subdirf2(fileresu,"PLB_"),subdirf2(fileresu,"PLB_"));
                   7171:    fprintf(fichtm,"\
1.211     brouard  7172:  - (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  7173:    <a href=\"%s\">%s</a> <br>\n",
1.201     brouard  7174:           estepm,subdirf2(fileresu,"E_"),subdirf2(fileresu,"E_"));
1.211     brouard  7175:    if(prevfcast==1){
                   7176:      fprintf(fichtm,"\
                   7177:  - Prevalence projections by age and states:                           \
1.201     brouard  7178:    <a href=\"%s\">%s</a> <br>\n</li>", subdirf2(fileresu,"F_"),subdirf2(fileresu,"F_"));
1.211     brouard  7179:    }
1.126     brouard  7180: 
                   7181: 
1.225     brouard  7182:    m=pow(2,cptcoveff);
1.222     brouard  7183:    if (cptcovn < 1) {m=1;ncodemax[1]=1;}
1.126     brouard  7184: 
1.317     brouard  7185:    fprintf(fichtm," \n<ul><li><b>Graphs (first order)</b></li><p>");
1.264     brouard  7186: 
                   7187:    jj1=0;
                   7188: 
                   7189:    fprintf(fichtm," \n<ul>");
                   7190:    for(nres=1; nres <= nresult; nres++) /* For each resultline */
                   7191:    for(k1=1; k1<=m;k1++){ /* For each combination of covariate */
                   7192:      if(m != 1 && TKresult[nres]!= k1)
                   7193:        continue;
                   7194:      jj1++;
                   7195:      if (cptcovn > 0) {
                   7196:        fprintf(fichtm,"\n<li><a  size=\"1\" color=\"#EC5E5E\" href=\"#rescov");
                   7197:        for (cpt=1; cpt<=cptcoveff;cpt++){ 
                   7198:         fprintf(fichtm,"_V%d=%d_",Tvresult[nres][cpt],(int)Tresult[nres][cpt]);
                   7199:        }
                   7200:        for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
                   7201:         fprintf(fichtm,"_V%d=%f_",Tvqresult[nres][k4],Tqresult[nres][k4]);
                   7202:        }
                   7203:        fprintf(fichtm,"\">");
                   7204:        
                   7205:        /* if(nqfveff+nqtveff 0) */ /* Test to be done */
                   7206:        fprintf(fichtm,"************ Results for covariates");
                   7207:        for (cpt=1; cpt<=cptcoveff;cpt++){ 
                   7208:         fprintf(fichtm," V%d=%d ",Tvresult[nres][cpt],(int)Tresult[nres][cpt]);
                   7209:        }
                   7210:        for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
                   7211:         fprintf(fichtm," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
                   7212:        }
                   7213:        if(invalidvarcomb[k1]){
                   7214:         fprintf(fichtm," Warning Combination (%d) ignored because no cases ",k1); 
                   7215:         continue;
                   7216:        }
                   7217:        fprintf(fichtm,"</a></li>");
                   7218:      } /* cptcovn >0 */
                   7219:    }
1.317     brouard  7220:    fprintf(fichtm," \n</ul>");
1.264     brouard  7221: 
1.222     brouard  7222:    jj1=0;
1.237     brouard  7223: 
                   7224:    for(nres=1; nres <= nresult; nres++) /* For each resultline */
1.241     brouard  7225:    for(k1=1; k1<=m;k1++){ /* For each combination of covariate */
1.253     brouard  7226:      if(m != 1 && TKresult[nres]!= k1)
1.237     brouard  7227:        continue;
1.220     brouard  7228: 
1.222     brouard  7229:      /* for(i1=1; i1<=ncodemax[k1];i1++){ */
                   7230:      jj1++;
                   7231:      if (cptcovn > 0) {
1.264     brouard  7232:        fprintf(fichtm,"\n<p><a name=\"rescov");
                   7233:        for (cpt=1; cpt<=cptcoveff;cpt++){ 
                   7234:         fprintf(fichtm,"_V%d=%d_",Tvresult[nres][cpt],(int)Tresult[nres][cpt]);
                   7235:        }
                   7236:        for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
                   7237:         fprintf(fichtm,"_V%d=%f_",Tvqresult[nres][k4],Tqresult[nres][k4]);
                   7238:        }
                   7239:        fprintf(fichtm,"\"</a>");
                   7240:  
1.222     brouard  7241:        fprintf(fichtm,"<hr  size=\"2\" color=\"#EC5E5E\">************ Results for covariates");
1.225     brouard  7242:        for (cpt=1; cpt<=cptcoveff;cpt++){ 
1.237     brouard  7243:         fprintf(fichtm," V%d=%d ",Tvresult[nres][cpt],(int)Tresult[nres][cpt]);
                   7244:         printf(" V%d=%d ",Tvresult[nres][cpt],Tresult[nres][cpt]);fflush(stdout);
                   7245:         /* fprintf(fichtm," V%d=%d ",Tvaraff[cpt],nbcode[Tvaraff[cpt]][codtabm(jj1,cpt)]); */
                   7246:         /* printf(" V%d=%d ",Tvaraff[cpt],nbcode[Tvaraff[cpt]][codtabm(jj1,cpt)]);fflush(stdout); */
1.222     brouard  7247:        }
1.237     brouard  7248:        for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
                   7249:        fprintf(fichtm," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
                   7250:        printf(" V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);fflush(stdout);
                   7251:       }
                   7252:        
1.230     brouard  7253:        /* if(nqfveff+nqtveff 0) */ /* Test to be done */
1.321     brouard  7254:        fprintf(fichtm," (model=%s) ************\n<hr size=\"2\" color=\"#EC5E5E\">",model);
1.222     brouard  7255:        if(invalidvarcomb[k1]){
                   7256:         fprintf(fichtm,"\n<h3>Combination (%d) ignored because no cases </h3>\n",k1); 
                   7257:         printf("\nCombination (%d) ignored because no cases \n",k1); 
                   7258:         continue;
                   7259:        }
                   7260:      }
                   7261:      /* aij, bij */
1.259     brouard  7262:      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  7263: <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  7264:      /* Pij */
1.241     brouard  7265:      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> \
                   7266: <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  7267:      /* Quasi-incidences */
                   7268:      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  7269:  before but expressed in per year i.e. quasi incidences if stepm is small and probabilities too, \
1.211     brouard  7270:  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  7271: 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> \
                   7272: <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  7273:      /* Survival functions (period) in state j */
                   7274:      for(cpt=1; cpt<=nlstate;cpt++){
1.292     brouard  7275:        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  7276: <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  7277:      }
                   7278:      /* State specific survival functions (period) */
                   7279:      for(cpt=1; cpt<=nlstate;cpt++){
1.292     brouard  7280:        fprintf(fichtm,"<br>\n- Survival functions in state %d and in any other live state (total).\
                   7281:  And probability to be observed in various states (up to %d) being in state %d at different ages.      \
1.283     brouard  7282:  <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  7283:      }
1.288     brouard  7284:      /* Period (forward stable) prevalence in each health state */
1.222     brouard  7285:      for(cpt=1; cpt<=nlstate;cpt++){
1.264     brouard  7286:        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> \
                   7287: <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  7288:      }
1.296     brouard  7289:      if(prevbcast==1){
1.288     brouard  7290:        /* Backward prevalence in each health state */
1.222     brouard  7291:        for(cpt=1; cpt<=nlstate;cpt++){
1.264     brouard  7292:         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  7293: <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  7294:        }
1.217     brouard  7295:      }
1.222     brouard  7296:      if(prevfcast==1){
1.288     brouard  7297:        /* Projection of prevalence up to period (forward stable) prevalence in each health state */
1.222     brouard  7298:        for(cpt=1; cpt<=nlstate;cpt++){
1.314     brouard  7299:         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>", dateprev1, dateprev2, mobilavproj, dateprojd, dateprojf, cpt, cpt, nlstate, subdirf2(optionfilefiname,"PROJ_"),cpt,k1,nres,subdirf2(optionfilefiname,"PROJ_"),cpt,k1,nres);
                   7300:         fprintf(fichtm," (data from text file  <a href=\"%s.txt\">%s.txt</a>)\n<br>",subdirf2(optionfilefiname,"F_"),subdirf2(optionfilefiname,"F_"));
                   7301:         fprintf(fichtm,"<img src=\"%s_%d-%d-%d.svg\">",
                   7302:                 subdirf2(optionfilefiname,"PROJ_"),cpt,k1,nres);
1.222     brouard  7303:        }
                   7304:      }
1.296     brouard  7305:      if(prevbcast==1){
1.268     brouard  7306:       /* Back projection of prevalence up to stable (mixed) back-prevalence in each health state */
                   7307:        for(cpt=1; cpt<=nlstate;cpt++){
1.273     brouard  7308:         fprintf(fichtm,"<br>\n- Back projection of cross-sectional prevalence (estimated with cases observed from %.1f to %.1f and mobil_average=%d), \
                   7309:  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 \
                   7310:  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) \
1.314     brouard  7311: with weights corresponding to observed prevalence at different ages. <a href=\"%s_%d-%d-%d.svg\">%s_%d-%d-%d.svg</a>", dateprev1, dateprev2, mobilavproj, dateback1, dateback2, cpt, cpt, nlstate, subdirf2(optionfilefiname,"PROJB_"),cpt,k1,nres,subdirf2(optionfilefiname,"PROJB_"),cpt,k1,nres);
                   7312:         fprintf(fichtm," (data from text file  <a href=\"%s.txt\">%s.txt</a>)\n<br>",subdirf2(optionfilefiname,"FB_"),subdirf2(optionfilefiname,"FB_"));
                   7313:         fprintf(fichtm," <img src=\"%s_%d-%d-%d.svg\">", subdirf2(optionfilefiname,"PROJB_"),cpt,k1,nres);
1.268     brouard  7314:        }
                   7315:      }
1.220     brouard  7316:         
1.222     brouard  7317:      for(cpt=1; cpt<=nlstate;cpt++) {
1.314     brouard  7318:        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>",cpt,nlstate,subdirf2(optionfilefiname,"EXP_"),cpt,k1,nres,subdirf2(optionfilefiname,"EXP_"),cpt,k1,nres);
                   7319:        fprintf(fichtm," (data from text file  <a href=\"%s.txt\"> %s.txt</a>)\n<br>",subdirf2(optionfilefiname,"E_"),subdirf2(optionfilefiname,"E_"));
                   7320:        fprintf(fichtm,"<img src=\"%s_%d-%d-%d.svg\">", subdirf2(optionfilefiname,"EXP_"),cpt,k1,nres );
1.222     brouard  7321:      }
                   7322:      /* } /\* end i1 *\/ */
                   7323:    }/* End k1 */
                   7324:    fprintf(fichtm,"</ul>");
1.126     brouard  7325: 
1.222     brouard  7326:    fprintf(fichtm,"\
1.126     brouard  7327: \n<br><li><h4> <a name='secondorder'>Result files (second order: variances)</a></h4>\n\
1.193     brouard  7328:  - Parameter file with estimated parameters and covariance matrix: <a href=\"%s\">%s</a> <br> \
1.203     brouard  7329:  - 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  7330: But because parameters are usually highly correlated (a higher incidence of disability \
                   7331: and a higher incidence of recovery can give very close observed transition) it might \
                   7332: be very useful to look not only at linear confidence intervals estimated from the \
                   7333: variances but at the covariance matrix. And instead of looking at the estimated coefficients \
                   7334: (parameters) of the logistic regression, it might be more meaningful to visualize the \
                   7335: covariance matrix of the one-step probabilities. \
                   7336: See page 'Matrix of variance-covariance of one-step probabilities' below. \n", rfileres,rfileres);
1.126     brouard  7337: 
1.222     brouard  7338:    fprintf(fichtm," - Standard deviation of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
                   7339:           subdirf2(fileresu,"PROB_"),subdirf2(fileresu,"PROB_"));
                   7340:    fprintf(fichtm,"\
1.126     brouard  7341:  - Variance-covariance of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
1.222     brouard  7342:           subdirf2(fileresu,"PROBCOV_"),subdirf2(fileresu,"PROBCOV_"));
1.126     brouard  7343: 
1.222     brouard  7344:    fprintf(fichtm,"\
1.126     brouard  7345:  - Correlation matrix of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
1.222     brouard  7346:           subdirf2(fileresu,"PROBCOR_"),subdirf2(fileresu,"PROBCOR_"));
                   7347:    fprintf(fichtm,"\
1.126     brouard  7348:  - 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): \
                   7349:    <a href=\"%s\">%s</a> <br>\n</li>",
1.201     brouard  7350:           estepm,subdirf2(fileresu,"CVE_"),subdirf2(fileresu,"CVE_"));
1.222     brouard  7351:    fprintf(fichtm,"\
1.126     brouard  7352:  - (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): \
                   7353:    <a href=\"%s\">%s</a> <br>\n</li>",
1.201     brouard  7354:           estepm,subdirf2(fileresu,"STDE_"),subdirf2(fileresu,"STDE_"));
1.222     brouard  7355:    fprintf(fichtm,"\
1.288     brouard  7356:  - 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  7357:           estepm, subdirf2(fileresu,"V_"),subdirf2(fileresu,"V_"));
                   7358:    fprintf(fichtm,"\
1.128     brouard  7359:  - 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  7360:           estepm, subdirf2(fileresu,"T_"),subdirf2(fileresu,"T_"));
                   7361:    fprintf(fichtm,"\
1.288     brouard  7362:  - Standard deviation of forward (period) prevalences: <a href=\"%s\">%s</a> <br>\n",\
1.222     brouard  7363:           subdirf2(fileresu,"VPL_"),subdirf2(fileresu,"VPL_"));
1.126     brouard  7364: 
                   7365: /*  if(popforecast==1) fprintf(fichtm,"\n */
                   7366: /*  - Prevalences forecasting: <a href=\"f%s\">f%s</a> <br>\n */
                   7367: /*  - Population forecasting (if popforecast=1): <a href=\"pop%s\">pop%s</a> <br>\n */
                   7368: /*     <br>",fileres,fileres,fileres,fileres); */
                   7369: /*  else  */
                   7370: /*    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  7371:    fflush(fichtm);
1.126     brouard  7372: 
1.225     brouard  7373:    m=pow(2,cptcoveff);
1.222     brouard  7374:    if (cptcovn < 1) {m=1;ncodemax[1]=1;}
1.126     brouard  7375: 
1.317     brouard  7376:    fprintf(fichtm," <ul><li><b>Graphs (second order)</b></li><p>");
                   7377: 
                   7378:   jj1=0;
                   7379: 
                   7380:    fprintf(fichtm," \n<ul>");
                   7381:    for(nres=1; nres <= nresult; nres++) /* For each resultline */
                   7382:    for(k1=1; k1<=m;k1++){ /* For each combination of covariate */
                   7383:      if(m != 1 && TKresult[nres]!= k1)
                   7384:        continue;
                   7385:      jj1++;
                   7386:      if (cptcovn > 0) {
                   7387:        fprintf(fichtm,"\n<li><a  size=\"1\" color=\"#EC5E5E\" href=\"#rescovsecond");
                   7388:        for (cpt=1; cpt<=cptcoveff;cpt++){ 
                   7389:         fprintf(fichtm,"_V%d=%d_",Tvresult[nres][cpt],(int)Tresult[nres][cpt]);
                   7390:        }
                   7391:        for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
                   7392:         fprintf(fichtm,"_V%d=%f_",Tvqresult[nres][k4],Tqresult[nres][k4]);
                   7393:        }
                   7394:        fprintf(fichtm,"\">");
                   7395:        
                   7396:        /* if(nqfveff+nqtveff 0) */ /* Test to be done */
                   7397:        fprintf(fichtm,"************ Results for covariates");
                   7398:        for (cpt=1; cpt<=cptcoveff;cpt++){ 
                   7399:         fprintf(fichtm," V%d=%d ",Tvresult[nres][cpt],(int)Tresult[nres][cpt]);
                   7400:        }
                   7401:        for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
                   7402:         fprintf(fichtm," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
                   7403:        }
                   7404:        if(invalidvarcomb[k1]){
                   7405:         fprintf(fichtm," Warning Combination (%d) ignored because no cases ",k1); 
                   7406:         continue;
                   7407:        }
                   7408:        fprintf(fichtm,"</a></li>");
                   7409:      } /* cptcovn >0 */
                   7410:    }
                   7411:    fprintf(fichtm," \n</ul>");
                   7412: 
1.222     brouard  7413:    jj1=0;
1.237     brouard  7414: 
1.241     brouard  7415:    for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.222     brouard  7416:    for(k1=1; k1<=m;k1++){
1.253     brouard  7417:      if(m != 1 && TKresult[nres]!= k1)
1.237     brouard  7418:        continue;
1.222     brouard  7419:      /* for(i1=1; i1<=ncodemax[k1];i1++){ */
                   7420:      jj1++;
1.126     brouard  7421:      if (cptcovn > 0) {
1.317     brouard  7422:        fprintf(fichtm,"\n<p><a name=\"rescovsecond");
                   7423:        for (cpt=1; cpt<=cptcoveff;cpt++){ 
                   7424:         fprintf(fichtm,"_V%d=%d_",Tvresult[nres][cpt],(int)Tresult[nres][cpt]);
                   7425:        }
                   7426:        for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
                   7427:         fprintf(fichtm,"_V%d=%f_",Tvqresult[nres][k4],Tqresult[nres][k4]);
                   7428:        }
                   7429:        fprintf(fichtm,"\"</a>");
                   7430:        
1.126     brouard  7431:        fprintf(fichtm,"<hr  size=\"2\" color=\"#EC5E5E\">************ Results for covariates");
1.317     brouard  7432:        for (cpt=1; cpt<=cptcoveff;cpt++){  /**< cptcoveff number of variables */
1.237     brouard  7433:         fprintf(fichtm," V%d=%d ",Tvresult[nres][cpt],Tresult[nres][cpt]);
1.317     brouard  7434:         printf(" V%d=%d ",Tvresult[nres][cpt],Tresult[nres][cpt]);fflush(stdout);
1.237     brouard  7435:         /* fprintf(fichtm," V%d=%d ",Tvaraff[cpt],nbcode[Tvaraff[cpt]][codtabm(jj1,cpt)]); */
1.317     brouard  7436:        }
1.237     brouard  7437:        for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
                   7438:        fprintf(fichtm," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
                   7439:       }
                   7440: 
1.321     brouard  7441:        fprintf(fichtm," (model=%s) ************\n<hr size=\"2\" color=\"#EC5E5E\">",model);
1.220     brouard  7442: 
1.222     brouard  7443:        if(invalidvarcomb[k1]){
                   7444:         fprintf(fichtm,"\n<h4>Combination (%d) ignored because no cases </h4>\n",k1); 
                   7445:         continue;
                   7446:        }
1.126     brouard  7447:      }
                   7448:      for(cpt=1; cpt<=nlstate;cpt++) {
1.258     brouard  7449:        fprintf(fichtm,"\n<br>- Observed (cross-sectional with mov_average=%d) and period (incidence based) \
1.314     brouard  7450: prevalence (with 95%% confidence interval) in state (%d): <a href=\"%s_%d-%d-%d.svg\"> %s_%d-%d-%d.svg</a>",mobilav,cpt,subdirf2(optionfilefiname,"V_"),cpt,k1,nres,subdirf2(optionfilefiname,"V_"),cpt,k1,nres);
                   7451:        fprintf(fichtm," (data from text file  <a href=\"%s\">%s</a>)\n <br>",subdirf2(fileresu,"VPL_"),subdirf2(fileresu,"VPL_"));
                   7452:        fprintf(fichtm,"<img src=\"%s_%d-%d-%d.svg\">",subdirf2(optionfilefiname,"V_"), cpt,k1,nres);
1.126     brouard  7453:      }
                   7454:      fprintf(fichtm,"\n<br>- Total life expectancy by age and \
1.314     brouard  7455: health expectancies in each live states (1 to %d). If popbased=1 the smooth (due to the model) \
1.128     brouard  7456: true period expectancies (those weighted with period prevalences are also\
                   7457:  drawn in addition to the population based expectancies computed using\
1.314     brouard  7458:  observed and cahotic prevalences:  <a href=\"%s_%d-%d.svg\">%s_%d-%d.svg</a>",nlstate, subdirf2(optionfilefiname,"E_"),k1,nres,subdirf2(optionfilefiname,"E_"),k1,nres);
                   7459:      fprintf(fichtm," (data from text file <a href=\"%s.txt\">%s.txt</a>) \n<br>",subdirf2(optionfilefiname,"T_"),subdirf2(optionfilefiname,"T_"));
                   7460:      fprintf(fichtm,"<img src=\"%s_%d-%d.svg\">",subdirf2(optionfilefiname,"E_"),k1,nres);
1.222     brouard  7461:      /* } /\* end i1 *\/ */
                   7462:    }/* End k1 */
1.241     brouard  7463:   }/* End nres */
1.222     brouard  7464:    fprintf(fichtm,"</ul>");
                   7465:    fflush(fichtm);
1.126     brouard  7466: }
                   7467: 
                   7468: /******************* Gnuplot file **************/
1.296     brouard  7469: 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  7470: 
                   7471:   char dirfileres[132],optfileres[132];
1.264     brouard  7472:   char gplotcondition[132], gplotlabel[132];
1.237     brouard  7473:   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  7474:   int lv=0, vlv=0, kl=0;
1.130     brouard  7475:   int ng=0;
1.201     brouard  7476:   int vpopbased;
1.223     brouard  7477:   int ioffset; /* variable offset for columns */
1.270     brouard  7478:   int iyearc=1; /* variable column for year of projection  */
                   7479:   int iagec=1; /* variable column for age of projection  */
1.235     brouard  7480:   int nres=0; /* Index of resultline */
1.266     brouard  7481:   int istart=1; /* For starting graphs in projections */
1.219     brouard  7482: 
1.126     brouard  7483: /*   if((ficgp=fopen(optionfilegnuplot,"a"))==NULL) { */
                   7484: /*     printf("Problem with file %s",optionfilegnuplot); */
                   7485: /*     fprintf(ficlog,"Problem with file %s",optionfilegnuplot); */
                   7486: /*   } */
                   7487: 
                   7488:   /*#ifdef windows */
                   7489:   fprintf(ficgp,"cd \"%s\" \n",pathc);
1.223     brouard  7490:   /*#endif */
1.225     brouard  7491:   m=pow(2,cptcoveff);
1.126     brouard  7492: 
1.274     brouard  7493:   /* diagram of the model */
                   7494:   fprintf(ficgp,"\n#Diagram of the model \n");
                   7495:   fprintf(ficgp,"\ndelta=0.03;delta2=0.07;unset arrow;\n");
                   7496:   fprintf(ficgp,"yoff=(%d > 2? 0:1);\n",nlstate);
                   7497:   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);
                   7498: 
                   7499:   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);
                   7500:   fprintf(ficgp,"\n#show arrow\nunset label\n");
                   7501:   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);
                   7502:   fprintf(ficgp,"\nset label %d+1 sprintf(\"State %%d\",%d+1) center at 0.,0.  font \"helvetica, 16\" tc rgbcolor \"red\"\n",nlstate,nlstate);
                   7503:   fprintf(ficgp,"\n#show label\nunset border;unset xtics; unset ytics;\n");
                   7504:   fprintf(ficgp,"\n\nset ter svg size 640, 480;set out \"%s_.svg\" \n",subdirf2(optionfilefiname,"D_"));
                   7505:   fprintf(ficgp,"unset log y; plot [-1.2:1.2][yoff-1.2:1.2] 1/0 not; set out;reset;\n");
                   7506: 
1.202     brouard  7507:   /* Contribution to likelihood */
                   7508:   /* Plot the probability implied in the likelihood */
1.223     brouard  7509:   fprintf(ficgp,"\n# Contributions to the Likelihood, mle >=1. For mle=4 no interpolation, pure matrix products.\n#\n");
                   7510:   fprintf(ficgp,"\n set log y; unset log x;set xlabel \"Age\"; set ylabel \"Likelihood (-2Log(L))\";");
                   7511:   /* fprintf(ficgp,"\nset ter svg size 640, 480"); */ /* Too big for svg */
                   7512:   fprintf(ficgp,"\nset ter pngcairo size 640, 480");
1.204     brouard  7513: /* nice for mle=4 plot by number of matrix products.
1.202     brouard  7514:    replot  "rrtest1/toto.txt" u 2:($4 == 1 && $5==2 ? $9 : 1/0):5 t "p12" with point lc 1 */
                   7515: /* replot exp(p1+p2*x)/(1+exp(p1+p2*x)+exp(p3+p4*x)+exp(p5+p6*x)) t "p12(x)"  */
1.223     brouard  7516:   /* fprintf(ficgp,"\nset out \"%s.svg\";",subdirf2(optionfilefiname,"ILK_")); */
                   7517:   fprintf(ficgp,"\nset out \"%s-dest.png\";",subdirf2(optionfilefiname,"ILK_"));
                   7518:   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));
                   7519:   fprintf(ficgp,"\nset out \"%s-ori.png\";",subdirf2(optionfilefiname,"ILK_"));
                   7520:   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));
                   7521:   for (i=1; i<= nlstate ; i ++) {
                   7522:     fprintf(ficgp,"\nset out \"%s-p%dj.png\";set ylabel \"Probability for each individual/wave\";",subdirf2(optionfilefiname,"ILK_"),i);
                   7523:     fprintf(ficgp,"unset log;\n# plot weighted, mean weight should have point size of 0.5\n plot  \"%s\"",subdirf(fileresilk));
                   7524:     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);
                   7525:     for (j=2; j<= nlstate+ndeath ; j ++) {
                   7526:       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);
                   7527:     }
                   7528:     fprintf(ficgp,";\nset out; unset ylabel;\n"); 
                   7529:   }
                   7530:   /* 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 */               
                   7531:   /* fprintf(ficgp,"\nset log y;plot  \"%s\" u 2:(-$11):3 t \"All sample, all transitions\" with dots lc variable",subdirf(fileresilk)); */
                   7532:   /* fprintf(ficgp,"\nreplot  \"%s\" u 2:($3 <= 3 ? -$11 : 1/0):3 t \"First 3 individuals\" with line lc variable", subdirf(fileresilk)); */
                   7533:   fprintf(ficgp,"\nset out;unset log\n");
                   7534:   /* fprintf(ficgp,"\nset out \"%s.svg\"; replot; set out; # bug gnuplot",subdirf2(optionfilefiname,"ILK_")); */
1.202     brouard  7535: 
1.126     brouard  7536:   strcpy(dirfileres,optionfilefiname);
                   7537:   strcpy(optfileres,"vpl");
1.223     brouard  7538:   /* 1eme*/
1.238     brouard  7539:   for (cpt=1; cpt<= nlstate ; cpt ++){ /* For each live state */
                   7540:     for (k1=1; k1<= m ; k1 ++){ /* For each valid combination of covariate */
1.236     brouard  7541:       for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.238     brouard  7542:        /* plot [100000000000000000000:-100000000000000000000] "mysbiaspar/vplrmysbiaspar.txt to check */
1.253     brouard  7543:        if(m != 1 && TKresult[nres]!= k1)
1.238     brouard  7544:          continue;
                   7545:        /* We are interested in selected combination by the resultline */
1.246     brouard  7546:        /* printf("\n# 1st: Period (stable) prevalence with CI: 'VPL_' files and live state =%d ", cpt); */
1.288     brouard  7547:        fprintf(ficgp,"\n# 1st: Forward (stable period) prevalence with CI: 'VPL_' files  and live state =%d ", cpt);
1.264     brouard  7548:        strcpy(gplotlabel,"(");
1.238     brouard  7549:        for (k=1; k<=cptcoveff; k++){    /* For each covariate k get corresponding value lv for combination k1 */
                   7550:          lv= decodtabm(k1,k,cptcoveff); /* Should be the value of the covariate corresponding to k1 combination */
                   7551:          /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   7552:          /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   7553:          /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
                   7554:          vlv= nbcode[Tvaraff[k]][lv]; /* vlv is the value of the covariate lv, 0 or 1 */
                   7555:          /* For each combination of covariate k1 (V1=1, V3=0), we printed the current covariate k and its value vlv */
1.246     brouard  7556:          /* printf(" V%d=%d ",Tvaraff[k],vlv); */
1.238     brouard  7557:          fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv);
1.264     brouard  7558:          sprintf(gplotlabel+strlen(gplotlabel)," V%d=%d ",Tvaraff[k],vlv);
1.238     brouard  7559:        }
                   7560:        for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
1.246     brouard  7561:          /* printf(" V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]); */
1.238     brouard  7562:          fprintf(ficgp," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
1.264     brouard  7563:          sprintf(gplotlabel+strlen(gplotlabel)," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
                   7564:        }
                   7565:        strcpy(gplotlabel+strlen(gplotlabel),")");
1.246     brouard  7566:        /* printf("\n#\n"); */
1.238     brouard  7567:        fprintf(ficgp,"\n#\n");
                   7568:        if(invalidvarcomb[k1]){
1.260     brouard  7569:           /*k1=k1-1;*/ /* To be checked */
1.238     brouard  7570:          fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   7571:          continue;
                   7572:        }
1.235     brouard  7573:       
1.241     brouard  7574:        fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" \n",subdirf2(optionfilefiname,"V_"),cpt,k1,nres);
                   7575:        fprintf(ficgp,"\n#set out \"V_%s_%d-%d-%d.svg\" \n",optionfilefiname,cpt,k1,nres);
1.276     brouard  7576:        /* fprintf(ficgp,"set label \"Alive state %d %s\" at graph 0.98,0.5 center rotate font \"Helvetica,12\"\n",cpt,gplotlabel); */
1.321     brouard  7577:        fprintf(ficgp,"set title \"Alive state %d %s model=%s\" font \"Helvetica,12\"\n",cpt,gplotlabel,model);
1.260     brouard  7578:        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);
                   7579:        /* 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); */
                   7580:       /* k1-1 error should be nres-1*/
1.238     brouard  7581:        for (i=1; i<= nlstate ; i ++) {
                   7582:          if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
                   7583:          else        fprintf(ficgp," %%*lf (%%*lf)");
                   7584:        }
1.288     brouard  7585:        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  7586:        for (i=1; i<= nlstate ; i ++) {
                   7587:          if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
                   7588:          else fprintf(ficgp," %%*lf (%%*lf)");
                   7589:        } 
1.260     brouard  7590:        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  7591:        for (i=1; i<= nlstate ; i ++) {
                   7592:          if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
                   7593:          else fprintf(ficgp," %%*lf (%%*lf)");
                   7594:        }  
1.265     brouard  7595:        /* 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)); */
                   7596:        
                   7597:        fprintf(ficgp,"\" t\"\" w l lt 1,\"%s\" u 1:((",subdirf2(fileresu,"P_"));
                   7598:         if(cptcoveff ==0){
1.271     brouard  7599:          fprintf(ficgp,"$%d)) t 'Observed prevalence in state %d' with line lt 3",      2+3*(cpt-1),  cpt );
1.265     brouard  7600:        }else{
                   7601:          kl=0;
                   7602:          for (k=1; k<=cptcoveff; k++){    /* For each combination of covariate  */
                   7603:            lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate value corresponding to k1 combination and kth covariate */
                   7604:            /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   7605:            /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   7606:            /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
                   7607:            vlv= nbcode[Tvaraff[k]][lv];
                   7608:            kl++;
                   7609:            /* 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 *\/ */
                   7610:            /*6+(cpt-1)*(nlstate+1)+1+(i-1)+(nlstate+1)*nlstate; 6+(1-1)*(2+1)+1+(1-1) +(2+1)*2=13 */ 
                   7611:            /*6+1+(i-1)+(nlstate+1)*nlstate; 6+1+(1-1) +(2+1)*2=13 */ 
                   7612:            /* ''  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*/
                   7613:            if(k==cptcoveff){
                   7614:              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], \
                   7615:                      2+cptcoveff*2+3*(cpt-1),  cpt );  /* 4 or 6 ?*/
                   7616:            }else{
                   7617:              fprintf(ficgp,"$%d==%d && $%d==%d && ",kl+1, Tvaraff[k],kl+1+1,nbcode[Tvaraff[k]][lv]);
                   7618:              kl++;
                   7619:            }
                   7620:          } /* end covariate */
                   7621:        } /* end if no covariate */
                   7622: 
1.296     brouard  7623:        if(prevbcast==1){ /* We need to get the corresponding values of the covariates involved in this combination k1 */
1.238     brouard  7624:          /* 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  7625:          fprintf(ficgp,",\"%s\" u 1:((",subdirf2(fileresu,"PLB_")); /* Age is in 1, nres in 2 to be fixed */
1.238     brouard  7626:          if(cptcoveff ==0){
1.245     brouard  7627:            fprintf(ficgp,"$%d)) t 'Backward prevalence in state %d' with line lt 3",    2+(cpt-1),  cpt );
1.238     brouard  7628:          }else{
                   7629:            kl=0;
                   7630:            for (k=1; k<=cptcoveff; k++){    /* For each combination of covariate  */
                   7631:              lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate value corresponding to k1 combination and kth covariate */
                   7632:              /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   7633:              /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   7634:              /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
                   7635:              vlv= nbcode[Tvaraff[k]][lv];
1.223     brouard  7636:              kl++;
1.238     brouard  7637:              /* 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 *\/ */
                   7638:              /*6+(cpt-1)*(nlstate+1)+1+(i-1)+(nlstate+1)*nlstate; 6+(1-1)*(2+1)+1+(1-1) +(2+1)*2=13 */ 
                   7639:              /*6+1+(i-1)+(nlstate+1)*nlstate; 6+1+(1-1) +(2+1)*2=13 */ 
                   7640:              /* ''  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*/
                   7641:              if(k==cptcoveff){
1.245     brouard  7642:                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  7643:                        2+cptcoveff*2+(cpt-1),  cpt );  /* 4 or 6 ?*/
1.238     brouard  7644:              }else{
                   7645:                fprintf(ficgp,"$%d==%d && $%d==%d && ",kl+1, Tvaraff[k],kl+1+1,nbcode[Tvaraff[k]][lv]);
                   7646:                kl++;
                   7647:              }
                   7648:            } /* end covariate */
                   7649:          } /* end if no covariate */
1.296     brouard  7650:          if(prevbcast == 1){
1.268     brouard  7651:            fprintf(ficgp,", \"%s\" every :::%d::%d u 1:($2==%d ? $3:1/0) \"%%lf %%lf",subdirf2(fileresu,"VBL_"),nres-1,nres-1,nres);
                   7652:            /* k1-1 error should be nres-1*/
                   7653:            for (i=1; i<= nlstate ; i ++) {
                   7654:              if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
                   7655:              else        fprintf(ficgp," %%*lf (%%*lf)");
                   7656:            }
1.271     brouard  7657:            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  7658:            for (i=1; i<= nlstate ; i ++) {
                   7659:              if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
                   7660:              else fprintf(ficgp," %%*lf (%%*lf)");
                   7661:            } 
1.276     brouard  7662:            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  7663:            for (i=1; i<= nlstate ; i ++) {
                   7664:              if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
                   7665:              else fprintf(ficgp," %%*lf (%%*lf)");
                   7666:            } 
1.274     brouard  7667:            fprintf(ficgp,"\" t\"\" w l lt 4");
1.268     brouard  7668:          } /* end if backprojcast */
1.296     brouard  7669:        } /* end if prevbcast */
1.276     brouard  7670:        /* fprintf(ficgp,"\nset out ;unset label;\n"); */
                   7671:        fprintf(ficgp,"\nset out ;unset title;\n");
1.238     brouard  7672:       } /* nres */
1.201     brouard  7673:     } /* k1 */
                   7674:   } /* cpt */
1.235     brouard  7675: 
                   7676:   
1.126     brouard  7677:   /*2 eme*/
1.238     brouard  7678:   for (k1=1; k1<= m ; k1 ++){  
                   7679:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.253     brouard  7680:       if(m != 1 && TKresult[nres]!= k1)
1.238     brouard  7681:        continue;
                   7682:       fprintf(ficgp,"\n# 2nd: Total life expectancy with CI: 't' files ");
1.264     brouard  7683:       strcpy(gplotlabel,"(");
1.238     brouard  7684:       for (k=1; k<=cptcoveff; k++){    /* For each covariate and each value */
1.225     brouard  7685:        lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate number corresponding to k1 combination */
1.223     brouard  7686:        /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   7687:        /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   7688:        /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
                   7689:        vlv= nbcode[Tvaraff[k]][lv];
                   7690:        fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv);
1.264     brouard  7691:        sprintf(gplotlabel+strlen(gplotlabel)," V%d=%d ",Tvaraff[k],vlv);
1.211     brouard  7692:       }
1.237     brouard  7693:       /* for(k=1; k <= ncovds; k++){ */
1.236     brouard  7694:       for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
1.238     brouard  7695:        printf(" V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
1.236     brouard  7696:        fprintf(ficgp," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
1.264     brouard  7697:        sprintf(gplotlabel+strlen(gplotlabel)," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
1.238     brouard  7698:       }
1.264     brouard  7699:       strcpy(gplotlabel+strlen(gplotlabel),")");
1.211     brouard  7700:       fprintf(ficgp,"\n#\n");
1.223     brouard  7701:       if(invalidvarcomb[k1]){
                   7702:        fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   7703:        continue;
                   7704:       }
1.219     brouard  7705:                        
1.241     brouard  7706:       fprintf(ficgp,"\nset out \"%s_%d-%d.svg\" \n",subdirf2(optionfilefiname,"E_"),k1,nres);
1.238     brouard  7707:       for(vpopbased=0; vpopbased <= popbased; vpopbased++){ /* Done for vpopbased=0 and vpopbased=1 if popbased==1*/
1.264     brouard  7708:        fprintf(ficgp,"\nset label \"popbased %d %s\" at graph 0.98,0.5 center rotate font \"Helvetica,12\"\n",vpopbased,gplotlabel);
                   7709:        if(vpopbased==0){
1.238     brouard  7710:          fprintf(ficgp,"set ylabel \"Years\" \nset ter svg size 640, 480\nplot [%.f:%.f] ",ageminpar,fage);
1.264     brouard  7711:        }else
1.238     brouard  7712:          fprintf(ficgp,"\nreplot ");
                   7713:        for (i=1; i<= nlstate+1 ; i ++) {
                   7714:          k=2*i;
1.261     brouard  7715:          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  7716:          for (j=1; j<= nlstate+1 ; j ++) {
                   7717:            if (j==i) fprintf(ficgp," %%lf (%%lf)");
                   7718:            else fprintf(ficgp," %%*lf (%%*lf)");
                   7719:          }   
                   7720:          if (i== 1) fprintf(ficgp,"\" t\"TLE\" w l lt %d, \\\n",i);
                   7721:          else fprintf(ficgp,"\" t\"LE in state (%d)\" w l lt %d, \\\n",i-1,i+1);
1.261     brouard  7722:          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  7723:          for (j=1; j<= nlstate+1 ; j ++) {
                   7724:            if (j==i) fprintf(ficgp," %%lf (%%lf)");
                   7725:            else fprintf(ficgp," %%*lf (%%*lf)");
                   7726:          }   
                   7727:          fprintf(ficgp,"\" t\"\" w l lt 0,");
1.261     brouard  7728:          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  7729:          for (j=1; j<= nlstate+1 ; j ++) {
                   7730:            if (j==i) fprintf(ficgp," %%lf (%%lf)");
                   7731:            else fprintf(ficgp," %%*lf (%%*lf)");
                   7732:          }   
                   7733:          if (i== (nlstate+1)) fprintf(ficgp,"\" t\"\" w l lt 0");
                   7734:          else fprintf(ficgp,"\" t\"\" w l lt 0,\\\n");
                   7735:        } /* state */
                   7736:       } /* vpopbased */
1.264     brouard  7737:       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  7738:     } /* end nres */
                   7739:   } /* k1 end 2 eme*/
                   7740:        
                   7741:        
                   7742:   /*3eme*/
                   7743:   for (k1=1; k1<= m ; k1 ++){
                   7744:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.253     brouard  7745:       if(m != 1 && TKresult[nres]!= k1)
1.238     brouard  7746:        continue;
                   7747: 
                   7748:       for (cpt=1; cpt<= nlstate ; cpt ++) {
1.261     brouard  7749:        fprintf(ficgp,"\n\n# 3d: Life expectancy with EXP_ files:  combination=%d state=%d",k1, cpt);
1.264     brouard  7750:        strcpy(gplotlabel,"(");
1.238     brouard  7751:        for (k=1; k<=cptcoveff; k++){    /* For each covariate and each value */
                   7752:          lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate number corresponding to k1 combination */
                   7753:          /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   7754:          /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   7755:          /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
                   7756:          vlv= nbcode[Tvaraff[k]][lv];
                   7757:          fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv);
1.264     brouard  7758:          sprintf(gplotlabel+strlen(gplotlabel)," V%d=%d ",Tvaraff[k],vlv);
1.238     brouard  7759:        }
                   7760:        for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
                   7761:          fprintf(ficgp," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
1.264     brouard  7762:          sprintf(gplotlabel+strlen(gplotlabel)," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
1.238     brouard  7763:        }       
1.264     brouard  7764:        strcpy(gplotlabel+strlen(gplotlabel),")");
1.238     brouard  7765:        fprintf(ficgp,"\n#\n");
                   7766:        if(invalidvarcomb[k1]){
                   7767:          fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   7768:          continue;
                   7769:        }
                   7770:                        
                   7771:        /*       k=2+nlstate*(2*cpt-2); */
                   7772:        k=2+(nlstate+1)*(cpt-1);
1.241     brouard  7773:        fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" \n",subdirf2(optionfilefiname,"EXP_"),cpt,k1,nres);
1.264     brouard  7774:        fprintf(ficgp,"set label \"%s\" at graph 0.98,0.5 center rotate font \"Helvetica,12\"\n",gplotlabel);
1.238     brouard  7775:        fprintf(ficgp,"set ter svg size 640, 480\n\
1.261     brouard  7776: 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  7777:        /*fprintf(ficgp,",\"e%s\" every :::%d::%d u 1:($%d-2*$%d) \"\%%lf ",fileres,k1-1,k1-1,k,k+1);
                   7778:          for (i=1; i<= nlstate*2 ; i ++) fprintf(ficgp,"\%%lf (\%%lf) ");
                   7779:          fprintf(ficgp,"\" t \"e%d1\" w l",cpt);
                   7780:          fprintf(ficgp,",\"e%s\" every :::%d::%d u 1:($%d+2*$%d) \"\%%lf ",fileres,k1-1,k1-1,k,k+1);
                   7781:          for (i=1; i<= nlstate*2 ; i ++) fprintf(ficgp,"\%%lf (\%%lf) ");
                   7782:          fprintf(ficgp,"\" t \"e%d1\" w l",cpt);
1.219     brouard  7783:                                
1.238     brouard  7784:        */
                   7785:        for (i=1; i< nlstate ; i ++) {
1.261     brouard  7786:          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  7787:          /*    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  7788:                                
1.238     brouard  7789:        } 
1.261     brouard  7790:        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  7791:       }
1.264     brouard  7792:       fprintf(ficgp,"\nunset label;\n");
1.238     brouard  7793:     } /* end nres */
                   7794:   } /* end kl 3eme */
1.126     brouard  7795:   
1.223     brouard  7796:   /* 4eme */
1.201     brouard  7797:   /* Survival functions (period) from state i in state j by initial state i */
1.238     brouard  7798:   for (k1=1; k1<=m; k1++){    /* For each covariate and each value */
                   7799:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.253     brouard  7800:       if(m != 1 && TKresult[nres]!= k1)
1.223     brouard  7801:        continue;
1.238     brouard  7802:       for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each life state cpt*/
1.264     brouard  7803:        strcpy(gplotlabel,"(");
1.238     brouard  7804:        fprintf(ficgp,"\n#\n#\n# Survival functions in state j : 'LIJ_' files, cov=%d state=%d",k1, cpt);
                   7805:        for (k=1; k<=cptcoveff; k++){    /* For each covariate and each value */
                   7806:          lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate number corresponding to k1 combination */
                   7807:          /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   7808:          /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   7809:          /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
                   7810:          vlv= nbcode[Tvaraff[k]][lv];
                   7811:          fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv);
1.264     brouard  7812:          sprintf(gplotlabel+strlen(gplotlabel)," V%d=%d ",Tvaraff[k],vlv);
1.238     brouard  7813:        }
                   7814:        for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
                   7815:          fprintf(ficgp," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
1.264     brouard  7816:          sprintf(gplotlabel+strlen(gplotlabel)," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
1.238     brouard  7817:        }       
1.264     brouard  7818:        strcpy(gplotlabel+strlen(gplotlabel),")");
1.238     brouard  7819:        fprintf(ficgp,"\n#\n");
                   7820:        if(invalidvarcomb[k1]){
                   7821:          fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   7822:          continue;
1.223     brouard  7823:        }
1.238     brouard  7824:       
1.241     brouard  7825:        fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" \n",subdirf2(optionfilefiname,"LIJ_"),cpt,k1,nres);
1.264     brouard  7826:        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  7827:        fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Probability to be alive\" \n\
                   7828: set ter svg size 640, 480\nunset log y\nplot [%.f:%.f]  ", ageminpar, agemaxpar);
                   7829:        k=3;
                   7830:        for (i=1; i<= nlstate ; i ++){
                   7831:          if(i==1){
                   7832:            fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"PIJ_"));
                   7833:          }else{
                   7834:            fprintf(ficgp,", '' ");
                   7835:          }
                   7836:          l=(nlstate+ndeath)*(i-1)+1;
                   7837:          fprintf(ficgp," u ($1==%d ? ($3):1/0):($%d/($%d",k1,k+l+(cpt-1),k+l);
                   7838:          for (j=2; j<= nlstate+ndeath ; j ++)
                   7839:            fprintf(ficgp,"+$%d",k+l+j-1);
                   7840:          fprintf(ficgp,")) t \"l(%d,%d)\" w l",i,cpt);
                   7841:        } /* nlstate */
1.264     brouard  7842:        fprintf(ficgp,"\nset out; unset label;\n");
1.238     brouard  7843:       } /* end cpt state*/ 
                   7844:     } /* end nres */
                   7845:   } /* end covariate k1 */  
                   7846: 
1.220     brouard  7847: /* 5eme */
1.201     brouard  7848:   /* Survival functions (period) from state i in state j by final state j */
1.238     brouard  7849:   for (k1=1; k1<= m ; k1++){ /* For each covariate combination if any */
                   7850:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.253     brouard  7851:       if(m != 1 && TKresult[nres]!= k1)
1.227     brouard  7852:        continue;
1.238     brouard  7853:       for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each inital state  */
1.264     brouard  7854:        strcpy(gplotlabel,"(");
1.238     brouard  7855:        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);
                   7856:        for (k=1; k<=cptcoveff; k++){    /* For each covariate and each value */
                   7857:          lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate number corresponding to k1 combination */
                   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];
                   7862:          fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv);
1.264     brouard  7863:          sprintf(gplotlabel+strlen(gplotlabel)," V%d=%d ",Tvaraff[k],vlv);
1.238     brouard  7864:        }
                   7865:        for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
                   7866:          fprintf(ficgp," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
1.264     brouard  7867:          sprintf(gplotlabel+strlen(gplotlabel)," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
1.238     brouard  7868:        }       
1.264     brouard  7869:        strcpy(gplotlabel+strlen(gplotlabel),")");
1.238     brouard  7870:        fprintf(ficgp,"\n#\n");
                   7871:        if(invalidvarcomb[k1]){
                   7872:          fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   7873:          continue;
                   7874:        }
1.227     brouard  7875:       
1.241     brouard  7876:        fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" \n",subdirf2(optionfilefiname,"LIJT_"),cpt,k1,nres);
1.264     brouard  7877:        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  7878:        fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Probability to be alive\" \n\
                   7879: set ter svg size 640, 480\nunset log y\nplot [%.f:%.f]  ", ageminpar, agemaxpar);
                   7880:        k=3;
                   7881:        for (j=1; j<= nlstate ; j ++){ /* Lived in state j */
                   7882:          if(j==1)
                   7883:            fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"PIJ_"));
                   7884:          else
                   7885:            fprintf(ficgp,", '' ");
                   7886:          l=(nlstate+ndeath)*(cpt-1) +j;
                   7887:          fprintf(ficgp," u (($1==%d && (floor($2)%%5 == 0)) ? ($3):1/0):($%d",k1,k+l);
                   7888:          /* for (i=2; i<= nlstate+ndeath ; i ++) */
                   7889:          /*   fprintf(ficgp,"+$%d",k+l+i-1); */
                   7890:          fprintf(ficgp,") t \"l(%d,%d)\" w l",cpt,j);
                   7891:        } /* nlstate */
                   7892:        fprintf(ficgp,", '' ");
                   7893:        fprintf(ficgp," u (($1==%d && (floor($2)%%5 == 0)) ? ($3):1/0):(",k1);
                   7894:        for (j=1; j<= nlstate ; j ++){ /* Lived in state j */
                   7895:          l=(nlstate+ndeath)*(cpt-1) +j;
                   7896:          if(j < nlstate)
                   7897:            fprintf(ficgp,"$%d +",k+l);
                   7898:          else
                   7899:            fprintf(ficgp,"$%d) t\"l(%d,.)\" w l",k+l,cpt);
                   7900:        }
1.264     brouard  7901:        fprintf(ficgp,"\nset out; unset label;\n");
1.238     brouard  7902:       } /* end cpt state*/ 
                   7903:     } /* end covariate */  
                   7904:   } /* end nres */
1.227     brouard  7905:   
1.220     brouard  7906: /* 6eme */
1.202     brouard  7907:   /* CV preval stable (period) for each covariate */
1.237     brouard  7908:   for (k1=1; k1<= m ; k1 ++) /* For each covariate combination if any */
                   7909:   for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.253     brouard  7910:     if(m != 1 && TKresult[nres]!= k1)
1.237     brouard  7911:       continue;
1.255     brouard  7912:     for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each life state of arrival */
1.264     brouard  7913:       strcpy(gplotlabel,"(");      
1.288     brouard  7914:       fprintf(ficgp,"\n#\n#\n#CV preval stable (forward): 'pij' files, covariatecombination#=%d state=%d",k1, cpt);
1.225     brouard  7915:       for (k=1; k<=cptcoveff; k++){    /* For each covariate and each value */
1.227     brouard  7916:        lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate number corresponding to k1 combination */
                   7917:        /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   7918:        /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   7919:        /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
                   7920:        vlv= nbcode[Tvaraff[k]][lv];
                   7921:        fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv);
1.264     brouard  7922:        sprintf(gplotlabel+strlen(gplotlabel)," V%d=%d ",Tvaraff[k],vlv);
1.211     brouard  7923:       }
1.237     brouard  7924:       for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
                   7925:        fprintf(ficgp," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
1.264     brouard  7926:        sprintf(gplotlabel+strlen(gplotlabel)," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
1.237     brouard  7927:       }        
1.264     brouard  7928:       strcpy(gplotlabel+strlen(gplotlabel),")");
1.211     brouard  7929:       fprintf(ficgp,"\n#\n");
1.223     brouard  7930:       if(invalidvarcomb[k1]){
1.227     brouard  7931:        fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   7932:        continue;
1.223     brouard  7933:       }
1.227     brouard  7934:       
1.241     brouard  7935:       fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" \n",subdirf2(optionfilefiname,"P_"),cpt,k1,nres);
1.264     brouard  7936:       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  7937:       fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Probability\" \n\
1.238     brouard  7938: set ter svg size 640, 480\nunset log y\nplot [%.f:%.f]  ", ageminpar, agemaxpar);
1.211     brouard  7939:       k=3; /* Offset */
1.255     brouard  7940:       for (i=1; i<= nlstate ; i ++){ /* State of origin */
1.227     brouard  7941:        if(i==1)
                   7942:          fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"PIJ_"));
                   7943:        else
                   7944:          fprintf(ficgp,", '' ");
1.255     brouard  7945:        l=(nlstate+ndeath)*(i-1)+1; /* 1, 1+ nlstate+ndeath, 1+2*(nlstate+ndeath) */
1.227     brouard  7946:        fprintf(ficgp," u ($1==%d ? ($3):1/0):($%d/($%d",k1,k+l+(cpt-1),k+l);
                   7947:        for (j=2; j<= nlstate ; j ++)
                   7948:          fprintf(ficgp,"+$%d",k+l+j-1);
                   7949:        fprintf(ficgp,")) t \"prev(%d,%d)\" w l",i,cpt);
1.153     brouard  7950:       } /* nlstate */
1.264     brouard  7951:       fprintf(ficgp,"\nset out; unset label;\n");
1.153     brouard  7952:     } /* end cpt state*/ 
                   7953:   } /* end covariate */  
1.227     brouard  7954:   
                   7955:   
1.220     brouard  7956: /* 7eme */
1.296     brouard  7957:   if(prevbcast == 1){
1.288     brouard  7958:     /* CV backward prevalence  for each covariate */
1.237     brouard  7959:     for (k1=1; k1<= m ; k1 ++) /* For each covariate combination if any */
                   7960:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.253     brouard  7961:       if(m != 1 && TKresult[nres]!= k1)
1.237     brouard  7962:        continue;
1.268     brouard  7963:       for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each life origin state */
1.264     brouard  7964:        strcpy(gplotlabel,"(");      
1.288     brouard  7965:        fprintf(ficgp,"\n#\n#\n#CV Backward stable prevalence: 'pijb' files, covariatecombination#=%d state=%d",k1, cpt);
1.227     brouard  7966:        for (k=1; k<=cptcoveff; k++){    /* For each covariate and each value */
                   7967:          lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate number corresponding to k1 combination */
                   7968:          /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   7969:          /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
1.223     brouard  7970:          /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
1.227     brouard  7971:          vlv= nbcode[Tvaraff[k]][lv];
                   7972:          fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv);
1.264     brouard  7973:          sprintf(gplotlabel+strlen(gplotlabel)," V%d=%d ",Tvaraff[k],vlv);
1.227     brouard  7974:        }
1.237     brouard  7975:        for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
                   7976:          fprintf(ficgp," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
1.264     brouard  7977:          sprintf(gplotlabel+strlen(gplotlabel)," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
1.237     brouard  7978:        }       
1.264     brouard  7979:        strcpy(gplotlabel+strlen(gplotlabel),")");
1.227     brouard  7980:        fprintf(ficgp,"\n#\n");
                   7981:        if(invalidvarcomb[k1]){
                   7982:          fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   7983:          continue;
                   7984:        }
                   7985:        
1.241     brouard  7986:        fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" \n",subdirf2(optionfilefiname,"PB_"),cpt,k1,nres);
1.268     brouard  7987:        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  7988:        fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Probability\" \n\
1.238     brouard  7989: set ter svg size 640, 480\nunset log y\nplot [%.f:%.f]  ", ageminpar, agemaxpar);
1.227     brouard  7990:        k=3; /* Offset */
1.268     brouard  7991:        for (i=1; i<= nlstate ; i ++){ /* State of arrival */
1.227     brouard  7992:          if(i==1)
                   7993:            fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"PIJB_"));
                   7994:          else
                   7995:            fprintf(ficgp,", '' ");
                   7996:          /* l=(nlstate+ndeath)*(i-1)+1; */
1.255     brouard  7997:          l=(nlstate+ndeath)*(cpt-1)+1; /* fixed for i; cpt=1 1, cpt=2 1+ nlstate+ndeath, 1+2*(nlstate+ndeath) */
1.324   ! brouard  7998:          /* fprintf(ficgp," u ($1==%d ? ($3):1/0):($%d/($%d",k1,k+l+(cpt-1),k+l); /\* a vérifier *\/ */
        !          7999:          /* 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  8000:          fprintf(ficgp," u ($1==%d ? ($3):1/0):($%d",k1,k+l+i-1); /* To be verified */
1.227     brouard  8001:          /* for (j=2; j<= nlstate ; j ++) */
                   8002:          /*    fprintf(ficgp,"+$%d",k+l+j-1); */
                   8003:          /*    /\* fprintf(ficgp,"+$%d",k+l+j-1); *\/ */
1.268     brouard  8004:          fprintf(ficgp,") t \"bprev(%d,%d)\" w l",cpt,i);
1.227     brouard  8005:        } /* nlstate */
1.264     brouard  8006:        fprintf(ficgp,"\nset out; unset label;\n");
1.218     brouard  8007:       } /* end cpt state*/ 
                   8008:     } /* end covariate */  
1.296     brouard  8009:   } /* End if prevbcast */
1.218     brouard  8010:   
1.223     brouard  8011:   /* 8eme */
1.218     brouard  8012:   if(prevfcast==1){
1.288     brouard  8013:     /* Projection from cross-sectional to forward stable (period) prevalence for each covariate */
1.218     brouard  8014:     
1.237     brouard  8015:     for (k1=1; k1<= m ; k1 ++) /* For each covariate combination if any */
                   8016:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.253     brouard  8017:       if(m != 1 && TKresult[nres]!= k1)
1.237     brouard  8018:        continue;
1.211     brouard  8019:       for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each life state */
1.264     brouard  8020:        strcpy(gplotlabel,"(");      
1.288     brouard  8021:        fprintf(ficgp,"\n#\n#\n#Projection of prevalence to forward stable prevalence (period): 'PROJ_' files, covariatecombination#=%d state=%d",k1, cpt);
1.227     brouard  8022:        for (k=1; k<=cptcoveff; k++){    /* For each correspondig covariate value  */
                   8023:          lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate value corresponding to k1 combination and kth covariate */
                   8024:          /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   8025:          /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   8026:          /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
                   8027:          vlv= nbcode[Tvaraff[k]][lv];
                   8028:          fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv);
1.264     brouard  8029:          sprintf(gplotlabel+strlen(gplotlabel)," V%d=%d ",Tvaraff[k],vlv);
1.227     brouard  8030:        }
1.237     brouard  8031:        for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
                   8032:          fprintf(ficgp," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
1.264     brouard  8033:          sprintf(gplotlabel+strlen(gplotlabel)," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
1.237     brouard  8034:        }       
1.264     brouard  8035:        strcpy(gplotlabel+strlen(gplotlabel),")");
1.227     brouard  8036:        fprintf(ficgp,"\n#\n");
                   8037:        if(invalidvarcomb[k1]){
                   8038:          fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   8039:          continue;
                   8040:        }
                   8041:        
                   8042:        fprintf(ficgp,"# hpijx=probability over h years, hp.jx is weighted by observed prev\n ");
1.241     brouard  8043:        fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" \n",subdirf2(optionfilefiname,"PROJ_"),cpt,k1,nres);
1.264     brouard  8044:        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  8045:        fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Prevalence\" \n\
1.238     brouard  8046: set ter svg size 640, 480\nunset log y\nplot [%.f:%.f]  ", ageminpar, agemaxpar);
1.266     brouard  8047: 
                   8048:        /* for (i=1; i<= nlstate+1 ; i ++){  /\* nlstate +1 p11 p21 p.1 *\/ */
                   8049:        istart=nlstate+1; /* Could be one if by state, but nlstate+1 is w.i projection only */
                   8050:        /*istart=1;*/ /* Could be one if by state, but nlstate+1 is w.i projection only */
                   8051:        for (i=istart; i<= nlstate+1 ; i ++){  /* nlstate +1 p11 p21 p.1 */
1.227     brouard  8052:          /*#  V1  = 1  V2 =  0 yearproj age p11 p21 p.1 p12 p22 p.2 p13 p23 p.3*/
                   8053:          /*#   1    2   3    4    5      6  7   8   9   10   11 12  13   14  15 */   
                   8054:          /*# yearproj age p11 p21 p.1 p12 p22 p.2 p13 p23 p.3*/
                   8055:          /*#   1       2   3    4    5      6  7   8   9   10   11 12  13   14  15 */   
1.266     brouard  8056:          if(i==istart){
1.227     brouard  8057:            fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"F_"));
                   8058:          }else{
                   8059:            fprintf(ficgp,",\\\n '' ");
                   8060:          }
                   8061:          if(cptcoveff ==0){ /* No covariate */
                   8062:            ioffset=2; /* Age is in 2 */
                   8063:            /*# yearproj age p11 p21 p31 p.1 p12 p22 p32 p.2 p13 p23 p33 p.3 p14 p24 p34 p.4*/
                   8064:            /*#   1       2   3   4   5  6    7  8   9   10  11  12  13  14  15  16  17  18 */
                   8065:            /*# V1  = 1 yearproj age p11 p21 p31 p.1 p12 p22 p32 p.2 p13 p23 p33 p.3 p14 p24 p34 p.4*/
                   8066:            /*#  1    2        3   4   5  6    7  8   9   10  11  12  13  14  15  16  17  18 */
                   8067:            fprintf(ficgp," u %d:(", ioffset); 
1.266     brouard  8068:            if(i==nlstate+1){
1.270     brouard  8069:              fprintf(ficgp," $%d/(1.-$%d)):1 t 'pw.%d' with line lc variable ",        \
1.266     brouard  8070:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1),  ioffset+1+(i-1)+(nlstate+1)*nlstate,cpt );
                   8071:              fprintf(ficgp,",\\\n '' ");
                   8072:              fprintf(ficgp," u %d:(",ioffset); 
1.270     brouard  8073:              fprintf(ficgp," (($1-$2) == %d ) ? $%d/(1.-$%d) : 1/0):1 with labels center not ", \
1.266     brouard  8074:                     offyear,                           \
1.268     brouard  8075:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1),  ioffset+1+(i-1)+(nlstate+1)*nlstate );
1.266     brouard  8076:            }else
1.227     brouard  8077:              fprintf(ficgp," $%d/(1.-$%d)) t 'p%d%d' with line ",      \
                   8078:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1),  ioffset+1+(i-1)+(nlstate+1)*nlstate,i,cpt );
                   8079:          }else{ /* more than 2 covariates */
1.270     brouard  8080:            ioffset=2*cptcoveff+2; /* Age is in 4 or 6 or etc.*/
                   8081:            /*#  V1  = 1  V2 =  0 yearproj age p11 p21 p.1 p12 p22 p.2 p13 p23 p.3*/
                   8082:            /*#   1    2   3    4    5      6  7   8   9   10   11 12  13   14  15 */
                   8083:            iyearc=ioffset-1;
                   8084:            iagec=ioffset;
1.227     brouard  8085:            fprintf(ficgp," u %d:(",ioffset); 
                   8086:            kl=0;
                   8087:            strcpy(gplotcondition,"(");
                   8088:            for (k=1; k<=cptcoveff; k++){    /* For each covariate writing the chain of conditions */
                   8089:              lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate value corresponding to combination k1 and covariate k */
                   8090:              /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   8091:              /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   8092:              /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
                   8093:              vlv= nbcode[Tvaraff[k]][lv]; /* Value of the modality of Tvaraff[k] */
                   8094:              kl++;
                   8095:              sprintf(gplotcondition+strlen(gplotcondition),"$%d==%d && $%d==%d " ,kl,Tvaraff[k], kl+1, nbcode[Tvaraff[k]][lv]);
                   8096:              kl++;
                   8097:              if(k <cptcoveff && cptcoveff>1)
                   8098:                sprintf(gplotcondition+strlen(gplotcondition)," && ");
                   8099:            }
                   8100:            strcpy(gplotcondition+strlen(gplotcondition),")");
                   8101:            /* 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 *\/ */
                   8102:            /*6+(cpt-1)*(nlstate+1)+1+(i-1)+(nlstate+1)*nlstate; 6+(1-1)*(2+1)+1+(1-1) +(2+1)*2=13 */ 
                   8103:            /*6+1+(i-1)+(nlstate+1)*nlstate; 6+1+(1-1) +(2+1)*2=13 */ 
                   8104:            /* ''  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*/
                   8105:            if(i==nlstate+1){
1.270     brouard  8106:              fprintf(ficgp,"%s ? $%d/(1.-$%d) : 1/0):%d t 'p.%d' with line lc variable", gplotcondition, \
                   8107:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1),  ioffset+1+(i-1)+(nlstate+1)*nlstate,iyearc, cpt );
1.266     brouard  8108:              fprintf(ficgp,",\\\n '' ");
1.270     brouard  8109:              fprintf(ficgp," u %d:(",iagec); 
                   8110:              fprintf(ficgp,"%s && (($%d-$%d) == %d ) ? $%d/(1.-$%d) : 1/0):%d with labels center not ", gplotcondition, \
                   8111:                      iyearc, iagec, offyear,                           \
                   8112:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1),  ioffset+1+(i-1)+(nlstate+1)*nlstate, iyearc );
1.266     brouard  8113: /*  '' 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  8114:            }else{
                   8115:              fprintf(ficgp,"%s ? $%d/(1.-$%d) : 1/0) t 'p%d%d' with line ", gplotcondition, \
                   8116:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1), ioffset +1+(i-1)+(nlstate+1)*nlstate,i,cpt );
                   8117:            }
                   8118:          } /* end if covariate */
                   8119:        } /* nlstate */
1.264     brouard  8120:        fprintf(ficgp,"\nset out; unset label;\n");
1.223     brouard  8121:       } /* end cpt state*/
                   8122:     } /* end covariate */
                   8123:   } /* End if prevfcast */
1.227     brouard  8124:   
1.296     brouard  8125:   if(prevbcast==1){
1.268     brouard  8126:     /* Back projection from cross-sectional to stable (mixed) for each covariate */
                   8127:     
                   8128:     for (k1=1; k1<= m ; k1 ++) /* For each covariate combination if any */
                   8129:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
                   8130:       if(m != 1 && TKresult[nres]!= k1)
                   8131:        continue;
                   8132:       for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each life state */
                   8133:        strcpy(gplotlabel,"(");      
                   8134:        fprintf(ficgp,"\n#\n#\n#Back projection of prevalence to stable (mixed) back prevalence: 'BPROJ_' files, covariatecombination#=%d originstate=%d",k1, cpt);
                   8135:        for (k=1; k<=cptcoveff; k++){    /* For each correspondig covariate value  */
                   8136:          lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate value corresponding to k1 combination and kth covariate */
                   8137:          /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   8138:          /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   8139:          /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
                   8140:          vlv= nbcode[Tvaraff[k]][lv];
                   8141:          fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv);
                   8142:          sprintf(gplotlabel+strlen(gplotlabel)," V%d=%d ",Tvaraff[k],vlv);
                   8143:        }
                   8144:        for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
                   8145:          fprintf(ficgp," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
                   8146:          sprintf(gplotlabel+strlen(gplotlabel)," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
                   8147:        }       
                   8148:        strcpy(gplotlabel+strlen(gplotlabel),")");
                   8149:        fprintf(ficgp,"\n#\n");
                   8150:        if(invalidvarcomb[k1]){
                   8151:          fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   8152:          continue;
                   8153:        }
                   8154:        
                   8155:        fprintf(ficgp,"# hbijx=backprobability over h years, hb.jx is weighted by observed prev at destination state\n ");
                   8156:        fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" \n",subdirf2(optionfilefiname,"PROJB_"),cpt,k1,nres);
                   8157:        fprintf(ficgp,"set label \"Origin alive state %d %s\" at graph 0.98,0.5 center rotate font \"Helvetica,12\"\n",cpt,gplotlabel);
                   8158:        fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Prevalence\" \n\
                   8159: set ter svg size 640, 480\nunset log y\nplot [%.f:%.f]  ", ageminpar, agemaxpar);
                   8160: 
                   8161:        /* for (i=1; i<= nlstate+1 ; i ++){  /\* nlstate +1 p11 p21 p.1 *\/ */
                   8162:        istart=nlstate+1; /* Could be one if by state, but nlstate+1 is w.i projection only */
                   8163:        /*istart=1;*/ /* Could be one if by state, but nlstate+1 is w.i projection only */
                   8164:        for (i=istart; i<= nlstate+1 ; i ++){  /* nlstate +1 p11 p21 p.1 */
                   8165:          /*#  V1  = 1  V2 =  0 yearproj age p11 p21 p.1 p12 p22 p.2 p13 p23 p.3*/
                   8166:          /*#   1    2   3    4    5      6  7   8   9   10   11 12  13   14  15 */   
                   8167:          /*# yearproj age p11 p21 p.1 p12 p22 p.2 p13 p23 p.3*/
                   8168:          /*#   1       2   3    4    5      6  7   8   9   10   11 12  13   14  15 */   
                   8169:          if(i==istart){
                   8170:            fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"FB_"));
                   8171:          }else{
                   8172:            fprintf(ficgp,",\\\n '' ");
                   8173:          }
                   8174:          if(cptcoveff ==0){ /* No covariate */
                   8175:            ioffset=2; /* Age is in 2 */
                   8176:            /*# yearproj age p11 p21 p31 p.1 p12 p22 p32 p.2 p13 p23 p33 p.3 p14 p24 p34 p.4*/
                   8177:            /*#   1       2   3   4   5  6    7  8   9   10  11  12  13  14  15  16  17  18 */
                   8178:            /*# V1  = 1 yearproj age p11 p21 p31 p.1 p12 p22 p32 p.2 p13 p23 p33 p.3 p14 p24 p34 p.4*/
                   8179:            /*#  1    2        3   4   5  6    7  8   9   10  11  12  13  14  15  16  17  18 */
                   8180:            fprintf(ficgp," u %d:(", ioffset); 
                   8181:            if(i==nlstate+1){
1.270     brouard  8182:              fprintf(ficgp," $%d/(1.-$%d)):1 t 'bw%d' with line lc variable ", \
1.268     brouard  8183:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1),  ioffset+1+(i-1)+(nlstate+1)*nlstate,cpt );
                   8184:              fprintf(ficgp,",\\\n '' ");
                   8185:              fprintf(ficgp," u %d:(",ioffset); 
1.270     brouard  8186:              fprintf(ficgp," (($1-$2) == %d ) ? $%d : 1/0):1 with labels center not ", \
1.268     brouard  8187:                     offbyear,                          \
                   8188:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1) );
                   8189:            }else
                   8190:              fprintf(ficgp," $%d/(1.-$%d)) t 'b%d%d' with line ",      \
                   8191:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1),  ioffset+1+(i-1)+(nlstate+1)*nlstate,cpt,i );
                   8192:          }else{ /* more than 2 covariates */
1.270     brouard  8193:            ioffset=2*cptcoveff+2; /* Age is in 4 or 6 or etc.*/
                   8194:            /*#  V1  = 1  V2 =  0 yearproj age p11 p21 p.1 p12 p22 p.2 p13 p23 p.3*/
                   8195:            /*#   1    2   3    4    5      6  7   8   9   10   11 12  13   14  15 */
                   8196:            iyearc=ioffset-1;
                   8197:            iagec=ioffset;
1.268     brouard  8198:            fprintf(ficgp," u %d:(",ioffset); 
                   8199:            kl=0;
                   8200:            strcpy(gplotcondition,"(");
                   8201:            for (k=1; k<=cptcoveff; k++){    /* For each covariate writing the chain of conditions */
                   8202:              lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate value corresponding to combination k1 and covariate k */
                   8203:              /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   8204:              /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   8205:              /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
                   8206:              vlv= nbcode[Tvaraff[k]][lv]; /* Value of the modality of Tvaraff[k] */
                   8207:              kl++;
                   8208:              sprintf(gplotcondition+strlen(gplotcondition),"$%d==%d && $%d==%d " ,kl,Tvaraff[k], kl+1, nbcode[Tvaraff[k]][lv]);
                   8209:              kl++;
                   8210:              if(k <cptcoveff && cptcoveff>1)
                   8211:                sprintf(gplotcondition+strlen(gplotcondition)," && ");
                   8212:            }
                   8213:            strcpy(gplotcondition+strlen(gplotcondition),")");
                   8214:            /* 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 *\/ */
                   8215:            /*6+(cpt-1)*(nlstate+1)+1+(i-1)+(nlstate+1)*nlstate; 6+(1-1)*(2+1)+1+(1-1) +(2+1)*2=13 */ 
                   8216:            /*6+1+(i-1)+(nlstate+1)*nlstate; 6+1+(1-1) +(2+1)*2=13 */ 
                   8217:            /* ''  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*/
                   8218:            if(i==nlstate+1){
1.270     brouard  8219:              fprintf(ficgp,"%s ? $%d : 1/0):%d t 'bw%d' with line lc variable", gplotcondition, \
                   8220:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1),iyearc,cpt );
1.268     brouard  8221:              fprintf(ficgp,",\\\n '' ");
1.270     brouard  8222:              fprintf(ficgp," u %d:(",iagec); 
1.268     brouard  8223:              /* fprintf(ficgp,"%s && (($5-$6) == %d ) ? $%d/(1.-$%d) : 1/0):5 with labels center not ", gplotcondition, \ */
1.270     brouard  8224:              fprintf(ficgp,"%s && (($%d-$%d) == %d ) ? $%d : 1/0):%d with labels center not ", gplotcondition, \
                   8225:                      iyearc,iagec,offbyear,                            \
                   8226:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1), iyearc );
1.268     brouard  8227: /*  '' u 6:(($1==1 && $2==0  && $3==2 && $4==0) && (($5-$6) == 1947) ? $10/(1.-$22) : 1/0):5 with labels center boxed not*/
                   8228:            }else{
                   8229:              /* fprintf(ficgp,"%s ? $%d/(1.-$%d) : 1/0) t 'p%d%d' with line ", gplotcondition, \ */
                   8230:              fprintf(ficgp,"%s ? $%d : 1/0) t 'b%d%d' with line ", gplotcondition, \
                   8231:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1), cpt,i );
                   8232:            }
                   8233:          } /* end if covariate */
                   8234:        } /* nlstate */
                   8235:        fprintf(ficgp,"\nset out; unset label;\n");
                   8236:       } /* end cpt state*/
                   8237:     } /* end covariate */
1.296     brouard  8238:   } /* End if prevbcast */
1.268     brouard  8239:   
1.227     brouard  8240:   
1.238     brouard  8241:   /* 9eme writing MLE parameters */
                   8242:   fprintf(ficgp,"\n##############\n#9eme MLE estimated parameters\n#############\n");
1.126     brouard  8243:   for(i=1,jk=1; i <=nlstate; i++){
1.187     brouard  8244:     fprintf(ficgp,"# initial state %d\n",i);
1.126     brouard  8245:     for(k=1; k <=(nlstate+ndeath); k++){
                   8246:       if (k != i) {
1.227     brouard  8247:        fprintf(ficgp,"#   current state %d\n",k);
                   8248:        for(j=1; j <=ncovmodel; j++){
                   8249:          fprintf(ficgp,"p%d=%f; ",jk,p[jk]);
                   8250:          jk++; 
                   8251:        }
                   8252:        fprintf(ficgp,"\n");
1.126     brouard  8253:       }
                   8254:     }
1.223     brouard  8255:   }
1.187     brouard  8256:   fprintf(ficgp,"##############\n#\n");
1.227     brouard  8257:   
1.145     brouard  8258:   /*goto avoid;*/
1.238     brouard  8259:   /* 10eme Graphics of probabilities or incidences using written MLE parameters */
                   8260:   fprintf(ficgp,"\n##############\n#10eme Graphics of probabilities or incidences\n#############\n");
1.187     brouard  8261:   fprintf(ficgp,"# logi(p12/p11)=a12+b12*age+c12age*age+d12*V1+e12*V1*age\n");
                   8262:   fprintf(ficgp,"# logi(p12/p11)=p1 +p2*age +p3*age*age+ p4*V1+ p5*V1*age\n");
                   8263:   fprintf(ficgp,"# logi(p13/p11)=a13+b13*age+c13age*age+d13*V1+e13*V1*age\n");
                   8264:   fprintf(ficgp,"# logi(p13/p11)=p6 +p7*age +p8*age*age+ p9*V1+ p10*V1*age\n");
                   8265:   fprintf(ficgp,"# p12+p13+p14+p11=1=p11(1+exp(a12+b12*age+c12age*age+d12*V1+e12*V1*age)\n");
                   8266:   fprintf(ficgp,"#                      +exp(a13+b13*age+c13age*age+d13*V1+e13*V1*age)+...)\n");
                   8267:   fprintf(ficgp,"# p11=1/(1+exp(a12+b12*age+c12age*age+d12*V1+e12*V1*age)\n");
                   8268:   fprintf(ficgp,"#                      +exp(a13+b13*age+c13age*age+d13*V1+e13*V1*age)+...)\n");
                   8269:   fprintf(ficgp,"# p12=exp(a12+b12*age+c12age*age+d12*V1+e12*V1*age)/\n");
                   8270:   fprintf(ficgp,"#     (1+exp(a12+b12*age+c12age*age+d12*V1+e12*V1*age)\n");
                   8271:   fprintf(ficgp,"#       +exp(a13+b13*age+c13age*age+d13*V1+e13*V1*age))\n");
                   8272:   fprintf(ficgp,"#       +exp(a14+b14*age+c14age*age+d14*V1+e14*V1*age)+...)\n");
                   8273:   fprintf(ficgp,"#\n");
1.223     brouard  8274:   for(ng=1; ng<=3;ng++){ /* Number of graphics: first is logit, 2nd is probabilities, third is incidences per year*/
1.238     brouard  8275:     fprintf(ficgp,"#Number of graphics: first is logit, 2nd is probabilities, third is incidences per year\n");
1.237     brouard  8276:     fprintf(ficgp,"#model=%s \n",model);
1.238     brouard  8277:     fprintf(ficgp,"# Type of graphic ng=%d\n",ng);
1.264     brouard  8278:     fprintf(ficgp,"#   k1=1 to 2^%d=%d\n",cptcoveff,m);/* to be checked */
                   8279:     for(k1=1; k1 <=m; k1++)  /* For each combination of covariate */
1.237     brouard  8280:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.264     brouard  8281:       if(m != 1 && TKresult[nres]!= k1)
1.237     brouard  8282:        continue;
1.264     brouard  8283:       fprintf(ficgp,"\n\n# Combination of dummy  k1=%d which is ",k1);
                   8284:       strcpy(gplotlabel,"(");
1.276     brouard  8285:       /*sprintf(gplotlabel+strlen(gplotlabel)," Dummy combination %d ",k1);*/
1.264     brouard  8286:       for (k=1; k<=cptcoveff; k++){    /* For each correspondig covariate value  */
                   8287:        lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate value corresponding to k1 combination and kth covariate */
                   8288:        /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   8289:        /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   8290:        /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
                   8291:        vlv= nbcode[Tvaraff[k]][lv];
                   8292:        fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv);
                   8293:        sprintf(gplotlabel+strlen(gplotlabel)," V%d=%d ",Tvaraff[k],vlv);
                   8294:       }
1.237     brouard  8295:       for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
                   8296:        fprintf(ficgp," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
1.264     brouard  8297:        sprintf(gplotlabel+strlen(gplotlabel)," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
1.237     brouard  8298:       }        
1.264     brouard  8299:       strcpy(gplotlabel+strlen(gplotlabel),")");
1.237     brouard  8300:       fprintf(ficgp,"\n#\n");
1.264     brouard  8301:       fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" ",subdirf2(optionfilefiname,"PE_"),k1,ng,nres);
1.276     brouard  8302:       fprintf(ficgp,"\nset key outside ");
                   8303:       /* fprintf(ficgp,"\nset label \"%s\" at graph 1.2,0.5 center rotate font \"Helvetica,12\"\n",gplotlabel); */
                   8304:       fprintf(ficgp,"\nset title \"%s\" font \"Helvetica,12\"\n",gplotlabel);
1.223     brouard  8305:       fprintf(ficgp,"\nset ter svg size 640, 480 ");
                   8306:       if (ng==1){
                   8307:        fprintf(ficgp,"\nset ylabel \"Value of the logit of the model\"\n"); /* exp(a12+b12*x) could be nice */
                   8308:        fprintf(ficgp,"\nunset log y");
                   8309:       }else if (ng==2){
                   8310:        fprintf(ficgp,"\nset ylabel \"Probability\"\n");
                   8311:        fprintf(ficgp,"\nset log y");
                   8312:       }else if (ng==3){
                   8313:        fprintf(ficgp,"\nset ylabel \"Quasi-incidence per year\"\n");
                   8314:        fprintf(ficgp,"\nset log y");
                   8315:       }else
                   8316:        fprintf(ficgp,"\nunset title ");
                   8317:       fprintf(ficgp,"\nplot  [%.f:%.f] ",ageminpar,agemaxpar);
                   8318:       i=1;
                   8319:       for(k2=1; k2<=nlstate; k2++) {
                   8320:        k3=i;
                   8321:        for(k=1; k<=(nlstate+ndeath); k++) {
                   8322:          if (k != k2){
                   8323:            switch( ng) {
                   8324:            case 1:
                   8325:              if(nagesqr==0)
                   8326:                fprintf(ficgp," p%d+p%d*x",i,i+1);
                   8327:              else /* nagesqr =1 */
                   8328:                fprintf(ficgp," p%d+p%d*x+p%d*x*x",i,i+1,i+1+nagesqr);
                   8329:              break;
                   8330:            case 2: /* ng=2 */
                   8331:              if(nagesqr==0)
                   8332:                fprintf(ficgp," exp(p%d+p%d*x",i,i+1);
                   8333:              else /* nagesqr =1 */
                   8334:                fprintf(ficgp," exp(p%d+p%d*x+p%d*x*x",i,i+1,i+1+nagesqr);
                   8335:              break;
                   8336:            case 3:
                   8337:              if(nagesqr==0)
                   8338:                fprintf(ficgp," %f*exp(p%d+p%d*x",YEARM/stepm,i,i+1);
                   8339:              else /* nagesqr =1 */
                   8340:                fprintf(ficgp," %f*exp(p%d+p%d*x+p%d*x*x",YEARM/stepm,i,i+1,i+1+nagesqr);
                   8341:              break;
                   8342:            }
                   8343:            ij=1;/* To be checked else nbcode[0][0] wrong */
1.237     brouard  8344:            ijp=1; /* product no age */
                   8345:            /* for(j=3; j <=ncovmodel-nagesqr; j++) { */
                   8346:            for(j=1; j <=cptcovt; j++) { /* For each covariate of the simplified model */
1.223     brouard  8347:              /* printf("Tage[%d]=%d, j=%d\n", ij, Tage[ij], j); */
1.268     brouard  8348:              if(cptcovage >0){ /* V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1, 2 V5 and V1 */
                   8349:                if(j==Tage[ij]) { /* Product by age  To be looked at!!*/
                   8350:                  if(ij <=cptcovage) { /* V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1, 2 V5 and V1 */
                   8351:                    if(DummyV[j]==0){
                   8352:                      fprintf(ficgp,"+p%d*%d*x",i+j+2+nagesqr-1,Tinvresult[nres][Tvar[j]]);;
                   8353:                    }else{ /* quantitative */
                   8354:                      fprintf(ficgp,"+p%d*%f*x",i+j+2+nagesqr-1,Tqinvresult[nres][Tvar[j]]); /* Tqinvresult in decoderesult */
                   8355:                      /* fprintf(ficgp,"+p%d*%d*x",i+j+nagesqr-1,nbcode[Tvar[j-2]][codtabm(k1,Tvar[j-2])]); */
                   8356:                    }
                   8357:                    ij++;
1.237     brouard  8358:                  }
1.268     brouard  8359:                } 
                   8360:              }else if(cptcovprod >0){
                   8361:                if(j==Tprod[ijp]) { /* */ 
                   8362:                  /* printf("Tprod[%d]=%d, j=%d\n", ij, Tprod[ijp], j); */
                   8363:                  if(ijp <=cptcovprod) { /* Product */
                   8364:                    if(DummyV[Tvard[ijp][1]]==0){/* Vn is dummy */
                   8365:                      if(DummyV[Tvard[ijp][2]]==0){/* Vn and Vm are dummy */
                   8366:                        /* 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)]); */
                   8367:                        fprintf(ficgp,"+p%d*%d*%d",i+j+2+nagesqr-1,Tinvresult[nres][Tvard[ijp][1]],Tinvresult[nres][Tvard[ijp][2]]);
                   8368:                      }else{ /* Vn is dummy and Vm is quanti */
                   8369:                        /* fprintf(ficgp,"+p%d*%d*%f",i+j+2+nagesqr-1,nbcode[Tvard[ijp][1]][codtabm(k1,j)],Tqinvresult[nres][Tvard[ijp][2]]); */
                   8370:                        fprintf(ficgp,"+p%d*%d*%f",i+j+2+nagesqr-1,Tinvresult[nres][Tvard[ijp][1]],Tqinvresult[nres][Tvard[ijp][2]]);
                   8371:                      }
                   8372:                    }else{ /* Vn*Vm Vn is quanti */
                   8373:                      if(DummyV[Tvard[ijp][2]]==0){
                   8374:                        fprintf(ficgp,"+p%d*%d*%f",i+j+2+nagesqr-1,Tinvresult[nres][Tvard[ijp][2]],Tqinvresult[nres][Tvard[ijp][1]]);
                   8375:                      }else{ /* Both quanti */
                   8376:                        fprintf(ficgp,"+p%d*%f*%f",i+j+2+nagesqr-1,Tqinvresult[nres][Tvard[ijp][1]],Tqinvresult[nres][Tvard[ijp][2]]);
                   8377:                      }
1.237     brouard  8378:                    }
1.268     brouard  8379:                    ijp++;
1.237     brouard  8380:                  }
1.268     brouard  8381:                } /* end Tprod */
1.237     brouard  8382:              } else{  /* simple covariate */
1.264     brouard  8383:                /* fprintf(ficgp,"+p%d*%d",i+j+2+nagesqr-1,nbcode[Tvar[j]][codtabm(k1,j)]); /\* Valgrind bug nbcode *\/ */
1.237     brouard  8384:                if(Dummy[j]==0){
                   8385:                  fprintf(ficgp,"+p%d*%d",i+j+2+nagesqr-1,Tinvresult[nres][Tvar[j]]); /*  */
                   8386:                }else{ /* quantitative */
                   8387:                  fprintf(ficgp,"+p%d*%f",i+j+2+nagesqr-1,Tqinvresult[nres][Tvar[j]]); /* */
1.264     brouard  8388:                  /* fprintf(ficgp,"+p%d*%d*x",i+j+nagesqr-1,nbcode[Tvar[j-2]][codtabm(k1,Tvar[j-2])]); */
1.223     brouard  8389:                }
1.237     brouard  8390:              } /* end simple */
                   8391:            } /* end j */
1.223     brouard  8392:          }else{
                   8393:            i=i-ncovmodel;
                   8394:            if(ng !=1 ) /* For logit formula of log p11 is more difficult to get */
                   8395:              fprintf(ficgp," (1.");
                   8396:          }
1.227     brouard  8397:          
1.223     brouard  8398:          if(ng != 1){
                   8399:            fprintf(ficgp,")/(1");
1.227     brouard  8400:            
1.264     brouard  8401:            for(cpt=1; cpt <=nlstate; cpt++){ 
1.223     brouard  8402:              if(nagesqr==0)
1.264     brouard  8403:                fprintf(ficgp,"+exp(p%d+p%d*x",k3+(cpt-1)*ncovmodel,k3+(cpt-1)*ncovmodel+1);
1.223     brouard  8404:              else /* nagesqr =1 */
1.264     brouard  8405:                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  8406:               
1.223     brouard  8407:              ij=1;
                   8408:              for(j=3; j <=ncovmodel-nagesqr; j++){
1.268     brouard  8409:                 if(cptcovage >0){ 
                   8410:                   if((j-2)==Tage[ij]) { /* Bug valgrind */
                   8411:                     if(ij <=cptcovage) { /* Bug valgrind */
                   8412:                       fprintf(ficgp,"+p%d*%d*x",k3+(cpt-1)*ncovmodel+1+j-2+nagesqr,nbcode[Tvar[j-2]][codtabm(k1,j-2)]);
                   8413:                       /* fprintf(ficgp,"+p%d*%d*x",k3+(cpt-1)*ncovmodel+1+j-2+nagesqr,nbcode[Tvar[j-2]][codtabm(k1,Tvar[j-2])]); */
                   8414:                       ij++;
                   8415:                     }
                   8416:                   }
                   8417:                 }else
                   8418:                   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  8419:              }
                   8420:              fprintf(ficgp,")");
                   8421:            }
                   8422:            fprintf(ficgp,")");
                   8423:            if(ng ==2)
1.276     brouard  8424:              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  8425:            else /* ng= 3 */
1.276     brouard  8426:              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  8427:          }else{ /* end ng <> 1 */
                   8428:            if( k !=k2) /* logit p11 is hard to draw */
1.276     brouard  8429:              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  8430:          }
                   8431:          if ((k+k2)!= (nlstate*2+ndeath) && ng != 1)
                   8432:            fprintf(ficgp,",");
                   8433:          if (ng == 1 && k!=k2 && (k+k2)!= (nlstate*2+ndeath))
                   8434:            fprintf(ficgp,",");
                   8435:          i=i+ncovmodel;
                   8436:        } /* end k */
                   8437:       } /* end k2 */
1.276     brouard  8438:       /* fprintf(ficgp,"\n set out; unset label;set key default;\n"); */
                   8439:       fprintf(ficgp,"\n set out; unset title;set key default;\n");
1.264     brouard  8440:     } /* end k1 */
1.223     brouard  8441:   } /* end ng */
                   8442:   /* avoid: */
                   8443:   fflush(ficgp); 
1.126     brouard  8444: }  /* end gnuplot */
                   8445: 
                   8446: 
                   8447: /*************** Moving average **************/
1.219     brouard  8448: /* int movingaverage(double ***probs, double bage, double fage, double ***mobaverage, int mobilav, double bageout, double fageout){ */
1.222     brouard  8449:  int movingaverage(double ***probs, double bage, double fage, double ***mobaverage, int mobilav){
1.218     brouard  8450:    
1.222     brouard  8451:    int i, cpt, cptcod;
                   8452:    int modcovmax =1;
                   8453:    int mobilavrange, mob;
                   8454:    int iage=0;
1.288     brouard  8455:    int firstA1=0, firstA2=0;
1.222     brouard  8456: 
1.266     brouard  8457:    double sum=0., sumr=0.;
1.222     brouard  8458:    double age;
1.266     brouard  8459:    double *sumnewp, *sumnewm, *sumnewmr;
                   8460:    double *agemingood, *agemaxgood; 
                   8461:    double *agemingoodr, *agemaxgoodr; 
1.222     brouard  8462:   
                   8463:   
1.278     brouard  8464:    /* modcovmax=2*cptcoveff;  Max number of modalities. We suppose  */
                   8465:    /*             a covariate has 2 modalities, should be equal to ncovcombmax   */
1.222     brouard  8466: 
                   8467:    sumnewp = vector(1,ncovcombmax);
                   8468:    sumnewm = vector(1,ncovcombmax);
1.266     brouard  8469:    sumnewmr = vector(1,ncovcombmax);
1.222     brouard  8470:    agemingood = vector(1,ncovcombmax); 
1.266     brouard  8471:    agemingoodr = vector(1,ncovcombmax);        
1.222     brouard  8472:    agemaxgood = vector(1,ncovcombmax);
1.266     brouard  8473:    agemaxgoodr = vector(1,ncovcombmax);
1.222     brouard  8474: 
                   8475:    for (cptcod=1;cptcod<=ncovcombmax;cptcod++){
1.266     brouard  8476:      sumnewm[cptcod]=0.; sumnewmr[cptcod]=0.;
1.222     brouard  8477:      sumnewp[cptcod]=0.;
1.266     brouard  8478:      agemingood[cptcod]=0, agemingoodr[cptcod]=0;
                   8479:      agemaxgood[cptcod]=0, agemaxgoodr[cptcod]=0;
1.222     brouard  8480:    }
                   8481:    if (cptcovn<1) ncovcombmax=1; /* At least 1 pass */
                   8482:   
1.266     brouard  8483:    if(mobilav==-1 || mobilav==1||mobilav ==3 ||mobilav==5 ||mobilav== 7){
                   8484:      if(mobilav==1 || mobilav==-1) mobilavrange=5; /* default */
1.222     brouard  8485:      else mobilavrange=mobilav;
                   8486:      for (age=bage; age<=fage; age++)
                   8487:        for (i=1; i<=nlstate;i++)
                   8488:         for (cptcod=1;cptcod<=ncovcombmax;cptcod++)
                   8489:           mobaverage[(int)age][i][cptcod]=probs[(int)age][i][cptcod];
                   8490:      /* We keep the original values on the extreme ages bage, fage and for 
                   8491:        fage+1 and bage-1 we use a 3 terms moving average; for fage+2 bage+2
                   8492:        we use a 5 terms etc. until the borders are no more concerned. 
                   8493:      */ 
                   8494:      for (mob=3;mob <=mobilavrange;mob=mob+2){
                   8495:        for (age=bage+(mob-1)/2; age<=fage-(mob-1)/2; age++){
1.266     brouard  8496:         for (cptcod=1;cptcod<=ncovcombmax;cptcod++){
                   8497:           sumnewm[cptcod]=0.;
                   8498:           for (i=1; i<=nlstate;i++){
1.222     brouard  8499:             mobaverage[(int)age][i][cptcod] =probs[(int)age][i][cptcod];
                   8500:             for (cpt=1;cpt<=(mob-1)/2;cpt++){
                   8501:               mobaverage[(int)age][i][cptcod] +=probs[(int)age-cpt][i][cptcod];
                   8502:               mobaverage[(int)age][i][cptcod] +=probs[(int)age+cpt][i][cptcod];
                   8503:             }
                   8504:             mobaverage[(int)age][i][cptcod]=mobaverage[(int)age][i][cptcod]/mob;
1.266     brouard  8505:             sumnewm[cptcod]+=mobaverage[(int)age][i][cptcod];
                   8506:           } /* end i */
                   8507:           if(sumnewm[cptcod] >1.e-3) mobaverage[(int)age][i][cptcod]=mobaverage[(int)age][i][cptcod]/sumnewm[cptcod]; /* Rescaling to sum one */
                   8508:         } /* end cptcod */
1.222     brouard  8509:        }/* end age */
                   8510:      }/* end mob */
1.266     brouard  8511:    }else{
                   8512:      printf("Error internal in movingaverage, mobilav=%d.\n",mobilav);
1.222     brouard  8513:      return -1;
1.266     brouard  8514:    }
                   8515: 
                   8516:    for (cptcod=1;cptcod<=ncovcombmax;cptcod++){ /* for each combination */
1.222     brouard  8517:      /* for (age=bage+(mob-1)/2; age<=fage-(mob-1)/2; age++){ */
                   8518:      if(invalidvarcomb[cptcod]){
                   8519:        printf("\nCombination (%d) ignored because no cases \n",cptcod); 
                   8520:        continue;
                   8521:      }
1.219     brouard  8522: 
1.266     brouard  8523:      for (age=fage-(mob-1)/2; age>=bage+(mob-1)/2; age--){ /*looking for the youngest and oldest good age */
                   8524:        sumnewm[cptcod]=0.;
                   8525:        sumnewmr[cptcod]=0.;
                   8526:        for (i=1; i<=nlstate;i++){
                   8527:         sumnewm[cptcod]+=mobaverage[(int)age][i][cptcod];
                   8528:         sumnewmr[cptcod]+=probs[(int)age][i][cptcod];
                   8529:        }
                   8530:        if(fabs(sumnewmr[cptcod] - 1.) <= 1.e-3) { /* good without smoothing */
                   8531:         agemingoodr[cptcod]=age;
                   8532:        }
                   8533:        if(fabs(sumnewm[cptcod] - 1.) <= 1.e-3) { /* good */
                   8534:           agemingood[cptcod]=age;
                   8535:        }
                   8536:      } /* age */
                   8537:      for (age=bage+(mob-1)/2; age<=fage-(mob-1)/2; age++){ /*looking for the youngest and oldest good age */
1.222     brouard  8538:        sumnewm[cptcod]=0.;
1.266     brouard  8539:        sumnewmr[cptcod]=0.;
1.222     brouard  8540:        for (i=1; i<=nlstate;i++){
                   8541:         sumnewm[cptcod]+=mobaverage[(int)age][i][cptcod];
1.266     brouard  8542:         sumnewmr[cptcod]+=probs[(int)age][i][cptcod];
                   8543:        }
                   8544:        if(fabs(sumnewmr[cptcod] - 1.) <= 1.e-3) { /* good without smoothing */
                   8545:         agemaxgoodr[cptcod]=age;
1.222     brouard  8546:        }
                   8547:        if(fabs(sumnewm[cptcod] - 1.) <= 1.e-3) { /* good */
1.266     brouard  8548:         agemaxgood[cptcod]=age;
                   8549:        }
                   8550:      } /* age */
                   8551:      /* Thus we have agemingood and agemaxgood as well as goodr for raw (preobs) */
                   8552:      /* but they will change */
1.288     brouard  8553:      firstA1=0;firstA2=0;
1.266     brouard  8554:      for (age=fage-(mob-1)/2; age>=bage; age--){/* From oldest to youngest, filling up to the youngest */
                   8555:        sumnewm[cptcod]=0.;
                   8556:        sumnewmr[cptcod]=0.;
                   8557:        for (i=1; i<=nlstate;i++){
                   8558:         sumnewm[cptcod]+=mobaverage[(int)age][i][cptcod];
                   8559:         sumnewmr[cptcod]+=probs[(int)age][i][cptcod];
                   8560:        }
                   8561:        if(mobilav==-1){ /* Forcing raw ages if good else agemingood */
                   8562:         if(fabs(sumnewmr[cptcod] - 1.) <= 1.e-3) { /* good without smoothing */
                   8563:           agemaxgoodr[cptcod]=age;  /* age min */
                   8564:           for (i=1; i<=nlstate;i++)
                   8565:             mobaverage[(int)age][i][cptcod]=probs[(int)age][i][cptcod];
                   8566:         }else{ /* bad we change the value with the values of good ages */
                   8567:           for (i=1; i<=nlstate;i++){
                   8568:             mobaverage[(int)age][i][cptcod]=mobaverage[(int)agemaxgoodr[cptcod]][i][cptcod];
                   8569:           } /* i */
                   8570:         } /* end bad */
                   8571:        }else{
                   8572:         if(fabs(sumnewm[cptcod] - 1.) <= 1.e-3) { /* good */
                   8573:           agemaxgood[cptcod]=age;
                   8574:         }else{ /* bad we change the value with the values of good ages */
                   8575:           for (i=1; i<=nlstate;i++){
                   8576:             mobaverage[(int)age][i][cptcod]=mobaverage[(int)agemaxgood[cptcod]][i][cptcod];
                   8577:           } /* i */
                   8578:         } /* end bad */
                   8579:        }/* end else */
                   8580:        sum=0.;sumr=0.;
                   8581:        for (i=1; i<=nlstate;i++){
                   8582:         sum+=mobaverage[(int)age][i][cptcod];
                   8583:         sumr+=probs[(int)age][i][cptcod];
                   8584:        }
                   8585:        if(fabs(sum - 1.) > 1.e-3) { /* bad */
1.288     brouard  8586:         if(!firstA1){
                   8587:           firstA1=1;
                   8588:           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);
                   8589:         }
                   8590:         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  8591:        } /* end bad */
                   8592:        /* else{ /\* We found some ages summing to one, we will smooth the oldest *\/ */
                   8593:        if(fabs(sumr - 1.) > 1.e-3) { /* bad */
1.288     brouard  8594:         if(!firstA2){
                   8595:           firstA2=1;
                   8596:           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);
                   8597:         }
                   8598:         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  8599:        } /* end bad */
                   8600:      }/* age */
1.266     brouard  8601: 
                   8602:      for (age=bage+(mob-1)/2; age<=fage; age++){/* From youngest, finding the oldest wrong */
1.222     brouard  8603:        sumnewm[cptcod]=0.;
1.266     brouard  8604:        sumnewmr[cptcod]=0.;
1.222     brouard  8605:        for (i=1; i<=nlstate;i++){
                   8606:         sumnewm[cptcod]+=mobaverage[(int)age][i][cptcod];
1.266     brouard  8607:         sumnewmr[cptcod]+=probs[(int)age][i][cptcod];
                   8608:        } 
                   8609:        if(mobilav==-1){ /* Forcing raw ages if good else agemingood */
                   8610:         if(fabs(sumnewmr[cptcod] - 1.) <= 1.e-3) { /* good */
                   8611:           agemingoodr[cptcod]=age;
                   8612:           for (i=1; i<=nlstate;i++)
                   8613:             mobaverage[(int)age][i][cptcod]=probs[(int)age][i][cptcod];
                   8614:         }else{ /* bad we change the value with the values of good ages */
                   8615:           for (i=1; i<=nlstate;i++){
                   8616:             mobaverage[(int)age][i][cptcod]=mobaverage[(int)agemingoodr[cptcod]][i][cptcod];
                   8617:           } /* i */
                   8618:         } /* end bad */
                   8619:        }else{
                   8620:         if(fabs(sumnewm[cptcod] - 1.) <= 1.e-3) { /* good */
                   8621:           agemingood[cptcod]=age;
                   8622:         }else{ /* bad */
                   8623:           for (i=1; i<=nlstate;i++){
                   8624:             mobaverage[(int)age][i][cptcod]=mobaverage[(int)agemingood[cptcod]][i][cptcod];
                   8625:           } /* i */
                   8626:         } /* end bad */
                   8627:        }/* end else */
                   8628:        sum=0.;sumr=0.;
                   8629:        for (i=1; i<=nlstate;i++){
                   8630:         sum+=mobaverage[(int)age][i][cptcod];
                   8631:         sumr+=mobaverage[(int)age][i][cptcod];
1.222     brouard  8632:        }
1.266     brouard  8633:        if(fabs(sum - 1.) > 1.e-3) { /* bad */
1.268     brouard  8634:         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  8635:        } /* end bad */
                   8636:        /* else{ /\* We found some ages summing to one, we will smooth the oldest *\/ */
                   8637:        if(fabs(sumr - 1.) > 1.e-3) { /* bad */
1.268     brouard  8638:         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  8639:        } /* end bad */
                   8640:      }/* age */
1.266     brouard  8641: 
1.222     brouard  8642:                
                   8643:      for (age=bage; age<=fage; age++){
1.235     brouard  8644:        /* printf("%d %d ", cptcod, (int)age); */
1.222     brouard  8645:        sumnewp[cptcod]=0.;
                   8646:        sumnewm[cptcod]=0.;
                   8647:        for (i=1; i<=nlstate;i++){
                   8648:         sumnewp[cptcod]+=probs[(int)age][i][cptcod];
                   8649:         sumnewm[cptcod]+=mobaverage[(int)age][i][cptcod];
                   8650:         /* printf("%.4f %.4f ",probs[(int)age][i][cptcod], mobaverage[(int)age][i][cptcod]); */
                   8651:        }
                   8652:        /* printf("%.4f %.4f \n",sumnewp[cptcod], sumnewm[cptcod]); */
                   8653:      }
                   8654:      /* printf("\n"); */
                   8655:      /* } */
1.266     brouard  8656: 
1.222     brouard  8657:      /* brutal averaging */
1.266     brouard  8658:      /* for (i=1; i<=nlstate;i++){ */
                   8659:      /*   for (age=1; age<=bage; age++){ */
                   8660:      /*         mobaverage[(int)age][i][cptcod]=mobaverage[(int)agemingood[cptcod]][i][cptcod]; */
                   8661:      /*         /\* printf("age=%d i=%d cptcod=%d mobaverage=%.4f \n",(int)age,i, cptcod, mobaverage[(int)age][i][cptcod]); *\/ */
                   8662:      /*   }     */
                   8663:      /*   for (age=fage; age<=AGESUP; age++){ */
                   8664:      /*         mobaverage[(int)age][i][cptcod]=mobaverage[(int)agemaxgood[cptcod]][i][cptcod]; */
                   8665:      /*         /\* printf("age=%d i=%d cptcod=%d mobaverage=%.4f \n",(int)age,i, cptcod, mobaverage[(int)age][i][cptcod]); *\/ */
                   8666:      /*   } */
                   8667:      /* } /\* end i status *\/ */
                   8668:      /* for (i=nlstate+1; i<=nlstate+ndeath;i++){ */
                   8669:      /*   for (age=1; age<=AGESUP; age++){ */
                   8670:      /*         /\*printf("i=%d, age=%d, cptcod=%d\n",i, (int)age, cptcod);*\/ */
                   8671:      /*         mobaverage[(int)age][i][cptcod]=0.; */
                   8672:      /*   } */
                   8673:      /* } */
1.222     brouard  8674:    }/* end cptcod */
1.266     brouard  8675:    free_vector(agemaxgoodr,1, ncovcombmax);
                   8676:    free_vector(agemaxgood,1, ncovcombmax);
                   8677:    free_vector(agemingood,1, ncovcombmax);
                   8678:    free_vector(agemingoodr,1, ncovcombmax);
                   8679:    free_vector(sumnewmr,1, ncovcombmax);
1.222     brouard  8680:    free_vector(sumnewm,1, ncovcombmax);
                   8681:    free_vector(sumnewp,1, ncovcombmax);
                   8682:    return 0;
                   8683:  }/* End movingaverage */
1.218     brouard  8684:  
1.126     brouard  8685: 
1.296     brouard  8686:  
1.126     brouard  8687: /************** Forecasting ******************/
1.296     brouard  8688: /* 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)*/
                   8689: 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){
                   8690:   /* dateintemean, mean date of interviews
                   8691:      dateprojd, year, month, day of starting projection 
                   8692:      dateprojf date of end of projection;year of end of projection (same day and month as proj1).
1.126     brouard  8693:      agemin, agemax range of age
                   8694:      dateprev1 dateprev2 range of dates during which prevalence is computed
                   8695:   */
1.296     brouard  8696:   /* double anprojd, mprojd, jprojd; */
                   8697:   /* double anprojf, mprojf, jprojf; */
1.267     brouard  8698:   int yearp, stepsize, hstepm, nhstepm, j, k, cptcod, i, h, i1, k4, nres=0;
1.126     brouard  8699:   double agec; /* generic age */
1.296     brouard  8700:   double agelim, ppij, yp,yp1,yp2;
1.126     brouard  8701:   double *popeffectif,*popcount;
                   8702:   double ***p3mat;
1.218     brouard  8703:   /* double ***mobaverage; */
1.126     brouard  8704:   char fileresf[FILENAMELENGTH];
                   8705: 
                   8706:   agelim=AGESUP;
1.211     brouard  8707:   /* Compute observed prevalence between dateprev1 and dateprev2 by counting the number of people
                   8708:      in each health status at the date of interview (if between dateprev1 and dateprev2).
                   8709:      We still use firstpass and lastpass as another selection.
                   8710:   */
1.214     brouard  8711:   /* freqsummary(fileres, agemin, agemax, s, agev, nlstate, imx,Tvaraff,nbcode, ncodemax,mint,anint,strstart,\ */
                   8712:   /*         firstpass, lastpass,  stepm,  weightopt, model); */
1.126     brouard  8713:  
1.201     brouard  8714:   strcpy(fileresf,"F_"); 
                   8715:   strcat(fileresf,fileresu);
1.126     brouard  8716:   if((ficresf=fopen(fileresf,"w"))==NULL) {
                   8717:     printf("Problem with forecast resultfile: %s\n", fileresf);
                   8718:     fprintf(ficlog,"Problem with forecast resultfile: %s\n", fileresf);
                   8719:   }
1.235     brouard  8720:   printf("\nComputing forecasting: result on file '%s', please wait... \n", fileresf);
                   8721:   fprintf(ficlog,"\nComputing forecasting: result on file '%s', please wait... \n", fileresf);
1.126     brouard  8722: 
1.225     brouard  8723:   if (cptcoveff==0) ncodemax[cptcoveff]=1;
1.126     brouard  8724: 
                   8725: 
                   8726:   stepsize=(int) (stepm+YEARM-1)/YEARM;
                   8727:   if (stepm<=12) stepsize=1;
                   8728:   if(estepm < stepm){
                   8729:     printf ("Problem %d lower than %d\n",estepm, stepm);
                   8730:   }
1.270     brouard  8731:   else{
                   8732:     hstepm=estepm;   
                   8733:   }
                   8734:   if(estepm > stepm){ /* Yes every two year */
                   8735:     stepsize=2;
                   8736:   }
1.296     brouard  8737:   hstepm=hstepm/stepm;
1.126     brouard  8738: 
1.296     brouard  8739:   
                   8740:   /* yp1=modf(dateintmean,&yp);/\* extracts integral of datemean in yp  and */
                   8741:   /*                              fractional in yp1 *\/ */
                   8742:   /* aintmean=yp; */
                   8743:   /* yp2=modf((yp1*12),&yp); */
                   8744:   /* mintmean=yp; */
                   8745:   /* yp1=modf((yp2*30.5),&yp); */
                   8746:   /* jintmean=yp; */
                   8747:   /* if(jintmean==0) jintmean=1; */
                   8748:   /* if(mintmean==0) mintmean=1; */
1.126     brouard  8749: 
1.296     brouard  8750: 
                   8751:   /* date2dmy(dateintmean,&jintmean,&mintmean,&aintmean); */
                   8752:   /* date2dmy(dateprojd,&jprojd, &mprojd, &anprojd); */
                   8753:   /* date2dmy(dateprojf,&jprojf, &mprojf, &anprojf); */
1.227     brouard  8754:   i1=pow(2,cptcoveff);
1.126     brouard  8755:   if (cptcovn < 1){i1=1;}
                   8756:   
1.296     brouard  8757:   fprintf(ficresf,"# Mean day of interviews %.lf/%.lf/%.lf (%.2f) between %.2f and %.2f \n",jintmean,mintmean,aintmean,dateintmean,dateprev1,dateprev2); 
1.126     brouard  8758:   
                   8759:   fprintf(ficresf,"#****** Routine prevforecast **\n");
1.227     brouard  8760:   
1.126     brouard  8761: /*           if (h==(int)(YEARM*yearp)){ */
1.235     brouard  8762:   for(nres=1; nres <= nresult; nres++) /* For each resultline */
                   8763:   for(k=1; k<=i1;k++){
1.253     brouard  8764:     if(i1 != 1 && TKresult[nres]!= k)
1.235     brouard  8765:       continue;
1.227     brouard  8766:     if(invalidvarcomb[k]){
                   8767:       printf("\nCombination (%d) projection ignored because no cases \n",k); 
                   8768:       continue;
                   8769:     }
                   8770:     fprintf(ficresf,"\n#****** hpijx=probability over h years, hp.jx is weighted by observed prev \n#");
                   8771:     for(j=1;j<=cptcoveff;j++) {
                   8772:       fprintf(ficresf," V%d (=) %d",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   8773:     }
1.235     brouard  8774:     for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
1.238     brouard  8775:       fprintf(ficresf," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
1.235     brouard  8776:     }
1.227     brouard  8777:     fprintf(ficresf," yearproj age");
                   8778:     for(j=1; j<=nlstate+ndeath;j++){ 
                   8779:       for(i=1; i<=nlstate;i++)               
                   8780:        fprintf(ficresf," p%d%d",i,j);
                   8781:       fprintf(ficresf," wp.%d",j);
                   8782:     }
1.296     brouard  8783:     for (yearp=0; yearp<=(anprojf-anprojd);yearp +=stepsize) {
1.227     brouard  8784:       fprintf(ficresf,"\n");
1.296     brouard  8785:       fprintf(ficresf,"\n# Forecasting at date %.lf/%.lf/%.lf ",jprojd,mprojd,anprojd+yearp);   
1.270     brouard  8786:       /* for (agec=fage; agec>=(ageminpar-1); agec--){  */
                   8787:       for (agec=fage; agec>=(bage); agec--){ 
1.227     brouard  8788:        nhstepm=(int) rint((agelim-agec)*YEARM/stepm); 
                   8789:        nhstepm = nhstepm/hstepm; 
                   8790:        p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   8791:        oldm=oldms;savm=savms;
1.268     brouard  8792:        /* We compute pii at age agec over nhstepm);*/
1.235     brouard  8793:        hpxij(p3mat,nhstepm,agec,hstepm,p,nlstate,stepm,oldm,savm, k,nres);
1.268     brouard  8794:        /* Then we print p3mat for h corresponding to the right agec+h*stepms=yearp */
1.227     brouard  8795:        for (h=0; h<=nhstepm; h++){
                   8796:          if (h*hstepm/YEARM*stepm ==yearp) {
1.268     brouard  8797:            break;
                   8798:          }
                   8799:        }
                   8800:        fprintf(ficresf,"\n");
                   8801:        for(j=1;j<=cptcoveff;j++) 
                   8802:          fprintf(ficresf,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
1.296     brouard  8803:        fprintf(ficresf,"%.f %.f ",anprojd+yearp,agec+h*hstepm/YEARM*stepm);
1.268     brouard  8804:        
                   8805:        for(j=1; j<=nlstate+ndeath;j++) {
                   8806:          ppij=0.;
                   8807:          for(i=1; i<=nlstate;i++) {
1.278     brouard  8808:            if (mobilav>=1)
                   8809:             ppij=ppij+p3mat[i][j][h]*prev[(int)agec][i][k];
                   8810:            else { /* even if mobilav==-1 we use mobaverage, probs may not sums to 1 */
                   8811:                ppij=ppij+p3mat[i][j][h]*probs[(int)(agec)][i][k];
                   8812:            }
1.268     brouard  8813:            fprintf(ficresf," %.3f", p3mat[i][j][h]);
                   8814:          } /* end i */
                   8815:          fprintf(ficresf," %.3f", ppij);
                   8816:        }/* end j */
1.227     brouard  8817:        free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   8818:       } /* end agec */
1.266     brouard  8819:       /* diffyear=(int) anproj1+yearp-ageminpar-1; */
                   8820:       /*printf("Prevforecast %d+%d-%d=diffyear=%d\n",(int) anproj1, (int)yearp,(int)ageminpar,(int) anproj1-(int)ageminpar);*/
1.227     brouard  8821:     } /* end yearp */
                   8822:   } /* end  k */
1.219     brouard  8823:        
1.126     brouard  8824:   fclose(ficresf);
1.215     brouard  8825:   printf("End of Computing forecasting \n");
                   8826:   fprintf(ficlog,"End of Computing forecasting\n");
                   8827: 
1.126     brouard  8828: }
                   8829: 
1.269     brouard  8830: /************** Back Forecasting ******************/
1.296     brouard  8831:  /* 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){ */
                   8832:  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){
                   8833:   /* back1, year, month, day of starting backprojection
1.267     brouard  8834:      agemin, agemax range of age
                   8835:      dateprev1 dateprev2 range of dates during which prevalence is computed
1.269     brouard  8836:      anback2 year of end of backprojection (same day and month as back1).
                   8837:      prevacurrent and prev are prevalences.
1.267     brouard  8838:   */
                   8839:   int yearp, stepsize, hstepm, nhstepm, j, k, cptcod, i, h, i1, k4, nres=0;
                   8840:   double agec; /* generic age */
1.302     brouard  8841:   double agelim, ppij, ppi, yp,yp1,yp2; /* ,jintmean,mintmean,aintmean;*/
1.267     brouard  8842:   double *popeffectif,*popcount;
                   8843:   double ***p3mat;
                   8844:   /* double ***mobaverage; */
                   8845:   char fileresfb[FILENAMELENGTH];
                   8846:  
1.268     brouard  8847:   agelim=AGEINF;
1.267     brouard  8848:   /* Compute observed prevalence between dateprev1 and dateprev2 by counting the number of people
                   8849:      in each health status at the date of interview (if between dateprev1 and dateprev2).
                   8850:      We still use firstpass and lastpass as another selection.
                   8851:   */
                   8852:   /* freqsummary(fileres, agemin, agemax, s, agev, nlstate, imx,Tvaraff,nbcode, ncodemax,mint,anint,strstart,\ */
                   8853:   /*         firstpass, lastpass,  stepm,  weightopt, model); */
                   8854: 
                   8855:   /*Do we need to compute prevalence again?*/
                   8856: 
                   8857:   /* prevalence(probs, ageminpar, agemax, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass); */
                   8858:   
                   8859:   strcpy(fileresfb,"FB_");
                   8860:   strcat(fileresfb,fileresu);
                   8861:   if((ficresfb=fopen(fileresfb,"w"))==NULL) {
                   8862:     printf("Problem with back forecast resultfile: %s\n", fileresfb);
                   8863:     fprintf(ficlog,"Problem with back forecast resultfile: %s\n", fileresfb);
                   8864:   }
                   8865:   printf("\nComputing back forecasting: result on file '%s', please wait... \n", fileresfb);
                   8866:   fprintf(ficlog,"\nComputing back forecasting: result on file '%s', please wait... \n", fileresfb);
                   8867:   
                   8868:   if (cptcoveff==0) ncodemax[cptcoveff]=1;
                   8869:   
                   8870:    
                   8871:   stepsize=(int) (stepm+YEARM-1)/YEARM;
                   8872:   if (stepm<=12) stepsize=1;
                   8873:   if(estepm < stepm){
                   8874:     printf ("Problem %d lower than %d\n",estepm, stepm);
                   8875:   }
1.270     brouard  8876:   else{
                   8877:     hstepm=estepm;   
                   8878:   }
                   8879:   if(estepm >= stepm){ /* Yes every two year */
                   8880:     stepsize=2;
                   8881:   }
1.267     brouard  8882:   
                   8883:   hstepm=hstepm/stepm;
1.296     brouard  8884:   /* yp1=modf(dateintmean,&yp);/\* extracts integral of datemean in yp  and */
                   8885:   /*                              fractional in yp1 *\/ */
                   8886:   /* aintmean=yp; */
                   8887:   /* yp2=modf((yp1*12),&yp); */
                   8888:   /* mintmean=yp; */
                   8889:   /* yp1=modf((yp2*30.5),&yp); */
                   8890:   /* jintmean=yp; */
                   8891:   /* if(jintmean==0) jintmean=1; */
                   8892:   /* if(mintmean==0) jintmean=1; */
1.267     brouard  8893:   
                   8894:   i1=pow(2,cptcoveff);
                   8895:   if (cptcovn < 1){i1=1;}
                   8896:   
1.296     brouard  8897:   fprintf(ficresfb,"# Mean day of interviews %.lf/%.lf/%.lf (%.2f) between %.2f and %.2f \n",jintmean,mintmean,aintmean,dateintmean,dateprev1,dateprev2);
                   8898:   printf("# Mean day of interviews %.lf/%.lf/%.lf (%.2f) between %.2f and %.2f \n",jintmean,mintmean,aintmean,dateintmean,dateprev1,dateprev2);
1.267     brouard  8899:   
                   8900:   fprintf(ficresfb,"#****** Routine prevbackforecast **\n");
                   8901:   
                   8902:   for(nres=1; nres <= nresult; nres++) /* For each resultline */
                   8903:   for(k=1; k<=i1;k++){
                   8904:     if(i1 != 1 && TKresult[nres]!= k)
                   8905:       continue;
                   8906:     if(invalidvarcomb[k]){
                   8907:       printf("\nCombination (%d) projection ignored because no cases \n",k); 
                   8908:       continue;
                   8909:     }
1.268     brouard  8910:     fprintf(ficresfb,"\n#****** hbijx=probability over h years, hb.jx is weighted by observed prev \n#");
1.267     brouard  8911:     for(j=1;j<=cptcoveff;j++) {
                   8912:       fprintf(ficresfb," V%d (=) %d",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   8913:     }
                   8914:     for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
                   8915:       fprintf(ficresf," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
                   8916:     }
                   8917:     fprintf(ficresfb," yearbproj age");
                   8918:     for(j=1; j<=nlstate+ndeath;j++){
                   8919:       for(i=1; i<=nlstate;i++)
1.268     brouard  8920:        fprintf(ficresfb," b%d%d",i,j);
                   8921:       fprintf(ficresfb," b.%d",j);
1.267     brouard  8922:     }
1.296     brouard  8923:     for (yearp=0; yearp>=(anbackf-anbackd);yearp -=stepsize) {
1.267     brouard  8924:       /* for (yearp=0; yearp<=(anproj2-anproj1);yearp +=stepsize) {  */
                   8925:       fprintf(ficresfb,"\n");
1.296     brouard  8926:       fprintf(ficresfb,"\n# Back Forecasting at date %.lf/%.lf/%.lf ",jbackd,mbackd,anbackd+yearp);
1.273     brouard  8927:       /* printf("\n# Back Forecasting at date %.lf/%.lf/%.lf ",jback1,mback1,anback1+yearp); */
1.270     brouard  8928:       /* for (agec=bage; agec<=agemax-1; agec++){  /\* testing *\/ */
                   8929:       for (agec=bage; agec<=fage; agec++){  /* testing */
1.268     brouard  8930:        /* We compute bij at age agec over nhstepm, nhstepm decreases when agec increases because of agemax;*/
1.271     brouard  8931:        nhstepm=(int) (agec-agelim) *YEARM/stepm;/*     nhstepm=(int) rint((agec-agelim)*YEARM/stepm);*/
1.267     brouard  8932:        nhstepm = nhstepm/hstepm;
                   8933:        p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   8934:        oldm=oldms;savm=savms;
1.268     brouard  8935:        /* computes hbxij at age agec over 1 to nhstepm */
1.271     brouard  8936:        /* printf("####prevbackforecast debug  agec=%.2f nhstepm=%d\n",agec, nhstepm);fflush(stdout); */
1.267     brouard  8937:        hbxij(p3mat,nhstepm,agec,hstepm,p,prevacurrent,nlstate,stepm, k, nres);
1.268     brouard  8938:        /* hpxij(p3mat,nhstepm,agec,hstepm,p,             nlstate,stepm,oldm,savm, k,nres); */
                   8939:        /* Then we print p3mat for h corresponding to the right agec+h*stepms=yearp */
                   8940:        /* printf(" agec=%.2f\n",agec);fflush(stdout); */
1.267     brouard  8941:        for (h=0; h<=nhstepm; h++){
1.268     brouard  8942:          if (h*hstepm/YEARM*stepm ==-yearp) {
                   8943:            break;
                   8944:          }
                   8945:        }
                   8946:        fprintf(ficresfb,"\n");
                   8947:        for(j=1;j<=cptcoveff;j++)
                   8948:          fprintf(ficresfb,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
1.296     brouard  8949:        fprintf(ficresfb,"%.f %.f ",anbackd+yearp,agec-h*hstepm/YEARM*stepm);
1.268     brouard  8950:        for(i=1; i<=nlstate+ndeath;i++) {
                   8951:          ppij=0.;ppi=0.;
                   8952:          for(j=1; j<=nlstate;j++) {
                   8953:            /* if (mobilav==1) */
1.269     brouard  8954:            ppij=ppij+p3mat[i][j][h]*prevacurrent[(int)agec][j][k];
                   8955:            ppi=ppi+prevacurrent[(int)agec][j][k];
                   8956:            /* ppij=ppij+p3mat[i][j][h]*mobaverage[(int)agec][j][k]; */
                   8957:            /* ppi=ppi+mobaverage[(int)agec][j][k]; */
1.267     brouard  8958:              /* else { */
                   8959:              /*        ppij=ppij+p3mat[i][j][h]*probs[(int)(agec)][i][k]; */
                   8960:              /* } */
1.268     brouard  8961:            fprintf(ficresfb," %.3f", p3mat[i][j][h]);
                   8962:          } /* end j */
                   8963:          if(ppi <0.99){
                   8964:            printf("Error in prevbackforecast, prevalence doesn't sum to 1 for state %d: %3f\n",i, ppi);
                   8965:            fprintf(ficlog,"Error in prevbackforecast, prevalence doesn't sum to 1 for state %d: %3f\n",i, ppi);
                   8966:          }
                   8967:          fprintf(ficresfb," %.3f", ppij);
                   8968:        }/* end j */
1.267     brouard  8969:        free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   8970:       } /* end agec */
                   8971:     } /* end yearp */
                   8972:   } /* end k */
1.217     brouard  8973:   
1.267     brouard  8974:   /* if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX); */
1.217     brouard  8975:   
1.267     brouard  8976:   fclose(ficresfb);
                   8977:   printf("End of Computing Back forecasting \n");
                   8978:   fprintf(ficlog,"End of Computing Back forecasting\n");
1.218     brouard  8979:        
1.267     brouard  8980: }
1.217     brouard  8981: 
1.269     brouard  8982: /* Variance of prevalence limit: varprlim */
                   8983:  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  8984:     /*------- Variance of forward period (stable) prevalence------*/   
1.269     brouard  8985:  
                   8986:    char fileresvpl[FILENAMELENGTH];  
                   8987:    FILE *ficresvpl;
                   8988:    double **oldm, **savm;
                   8989:    double **varpl; /* Variances of prevalence limits by age */   
                   8990:    int i1, k, nres, j ;
                   8991:    
                   8992:     strcpy(fileresvpl,"VPL_");
                   8993:     strcat(fileresvpl,fileresu);
                   8994:     if((ficresvpl=fopen(fileresvpl,"w"))==NULL) {
1.288     brouard  8995:       printf("Problem with variance of forward period (stable) prevalence  resultfile: %s\n", fileresvpl);
1.269     brouard  8996:       exit(0);
                   8997:     }
1.288     brouard  8998:     printf("Computing Variance-covariance of forward period (stable) prevalence: file '%s' ...", fileresvpl);fflush(stdout);
                   8999:     fprintf(ficlog, "Computing Variance-covariance of forward period (stable) prevalence: file '%s' ...", fileresvpl);fflush(ficlog);
1.269     brouard  9000:     
                   9001:     /*for(cptcov=1,k=0;cptcov<=i1;cptcov++){
                   9002:       for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*/
                   9003:     
                   9004:     i1=pow(2,cptcoveff);
                   9005:     if (cptcovn < 1){i1=1;}
                   9006: 
                   9007:     for(nres=1; nres <= nresult; nres++) /* For each resultline */
                   9008:     for(k=1; k<=i1;k++){
                   9009:       if(i1 != 1 && TKresult[nres]!= k)
                   9010:        continue;
                   9011:       fprintf(ficresvpl,"\n#****** ");
                   9012:       printf("\n#****** ");
                   9013:       fprintf(ficlog,"\n#****** ");
                   9014:       for(j=1;j<=cptcoveff;j++) {
                   9015:        fprintf(ficresvpl,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   9016:        fprintf(ficlog,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   9017:        printf("V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   9018:       }
                   9019:       for (j=1; j<= nsq; j++){ /* For each selected (single) quantitative value */
                   9020:        printf(" V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]);
                   9021:        fprintf(ficresvpl," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]);
                   9022:        fprintf(ficlog," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]);
                   9023:       }        
                   9024:       fprintf(ficresvpl,"******\n");
                   9025:       printf("******\n");
                   9026:       fprintf(ficlog,"******\n");
                   9027:       
                   9028:       varpl=matrix(1,nlstate,(int) bage, (int) fage);
                   9029:       oldm=oldms;savm=savms;
                   9030:       varprevlim(fileresvpl, ficresvpl, varpl, matcov, p, delti, nlstate, stepm, (int) bage, (int) fage, oldm, savm, prlim, ftolpl, ncvyearp, k, strstart, nres);
                   9031:       free_matrix(varpl,1,nlstate,(int) bage, (int)fage);
                   9032:       /*}*/
                   9033:     }
                   9034:     
                   9035:     fclose(ficresvpl);
1.288     brouard  9036:     printf("done variance-covariance of forward period prevalence\n");fflush(stdout);
                   9037:     fprintf(ficlog,"done variance-covariance of forward period prevalence\n");fflush(ficlog);
1.269     brouard  9038: 
                   9039:  }
                   9040: /* Variance of back prevalence: varbprlim */
                   9041:  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){
                   9042:       /*------- Variance of back (stable) prevalence------*/
                   9043: 
                   9044:    char fileresvbl[FILENAMELENGTH];  
                   9045:    FILE  *ficresvbl;
                   9046: 
                   9047:    double **oldm, **savm;
                   9048:    double **varbpl; /* Variances of back prevalence limits by age */   
                   9049:    int i1, k, nres, j ;
                   9050: 
                   9051:    strcpy(fileresvbl,"VBL_");
                   9052:    strcat(fileresvbl,fileresu);
                   9053:    if((ficresvbl=fopen(fileresvbl,"w"))==NULL) {
                   9054:      printf("Problem with variance of back (stable) prevalence  resultfile: %s\n", fileresvbl);
                   9055:      exit(0);
                   9056:    }
                   9057:    printf("Computing Variance-covariance of back (stable) prevalence: file '%s' ...", fileresvbl);fflush(stdout);
                   9058:    fprintf(ficlog, "Computing Variance-covariance of back (stable) prevalence: file '%s' ...", fileresvbl);fflush(ficlog);
                   9059:    
                   9060:    
                   9061:    i1=pow(2,cptcoveff);
                   9062:    if (cptcovn < 1){i1=1;}
                   9063:    
                   9064:    for(nres=1; nres <= nresult; nres++) /* For each resultline */
                   9065:      for(k=1; k<=i1;k++){
                   9066:        if(i1 != 1 && TKresult[nres]!= k)
                   9067:         continue;
                   9068:        fprintf(ficresvbl,"\n#****** ");
                   9069:        printf("\n#****** ");
                   9070:        fprintf(ficlog,"\n#****** ");
                   9071:        for(j=1;j<=cptcoveff;j++) {
                   9072:         fprintf(ficresvbl,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   9073:         fprintf(ficlog,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   9074:         printf("V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   9075:        }
                   9076:        for (j=1; j<= nsq; j++){ /* For each selected (single) quantitative value */
                   9077:         printf(" V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]);
                   9078:         fprintf(ficresvbl," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]);
                   9079:         fprintf(ficlog," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]);
                   9080:        }
                   9081:        fprintf(ficresvbl,"******\n");
                   9082:        printf("******\n");
                   9083:        fprintf(ficlog,"******\n");
                   9084:        
                   9085:        varbpl=matrix(1,nlstate,(int) bage, (int) fage);
                   9086:        oldm=oldms;savm=savms;
                   9087:        
                   9088:        varbrevlim(fileresvbl, ficresvbl, varbpl, matcov, p, delti, nlstate, stepm, (int) bage, (int) fage, oldm, savm, bprlim, ftolpl, mobilavproj, ncvyearp, k, strstart, nres);
                   9089:        free_matrix(varbpl,1,nlstate,(int) bage, (int)fage);
                   9090:        /*}*/
                   9091:      }
                   9092:    
                   9093:    fclose(ficresvbl);
                   9094:    printf("done variance-covariance of back prevalence\n");fflush(stdout);
                   9095:    fprintf(ficlog,"done variance-covariance of back prevalence\n");fflush(ficlog);
                   9096: 
                   9097:  } /* End of varbprlim */
                   9098: 
1.126     brouard  9099: /************** Forecasting *****not tested NB*************/
1.227     brouard  9100: /* 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  9101:   
1.227     brouard  9102: /*   int cpt, stepsize, hstepm, nhstepm, j,k,c, cptcod, i,h; */
                   9103: /*   int *popage; */
                   9104: /*   double calagedatem, agelim, kk1, kk2; */
                   9105: /*   double *popeffectif,*popcount; */
                   9106: /*   double ***p3mat,***tabpop,***tabpopprev; */
                   9107: /*   /\* double ***mobaverage; *\/ */
                   9108: /*   char filerespop[FILENAMELENGTH]; */
1.126     brouard  9109: 
1.227     brouard  9110: /*   tabpop= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX); */
                   9111: /*   tabpopprev= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX); */
                   9112: /*   agelim=AGESUP; */
                   9113: /*   calagedatem=(anpyram+mpyram/12.+jpyram/365.-dateintmean)*YEARM; */
1.126     brouard  9114:   
1.227     brouard  9115: /*   prevalence(probs, ageminpar, agemax, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass); */
1.126     brouard  9116:   
                   9117:   
1.227     brouard  9118: /*   strcpy(filerespop,"POP_");  */
                   9119: /*   strcat(filerespop,fileresu); */
                   9120: /*   if((ficrespop=fopen(filerespop,"w"))==NULL) { */
                   9121: /*     printf("Problem with forecast resultfile: %s\n", filerespop); */
                   9122: /*     fprintf(ficlog,"Problem with forecast resultfile: %s\n", filerespop); */
                   9123: /*   } */
                   9124: /*   printf("Computing forecasting: result on file '%s' \n", filerespop); */
                   9125: /*   fprintf(ficlog,"Computing forecasting: result on file '%s' \n", filerespop); */
1.126     brouard  9126: 
1.227     brouard  9127: /*   if (cptcoveff==0) ncodemax[cptcoveff]=1; */
1.126     brouard  9128: 
1.227     brouard  9129: /*   /\* if (mobilav!=0) { *\/ */
                   9130: /*   /\*   mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX); *\/ */
                   9131: /*   /\*   if (movingaverage(probs, ageminpar, fage, mobaverage,mobilav)!=0){ *\/ */
                   9132: /*   /\*     fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav); *\/ */
                   9133: /*   /\*     printf(" Error in movingaverage mobilav=%d\n",mobilav); *\/ */
                   9134: /*   /\*   } *\/ */
                   9135: /*   /\* } *\/ */
1.126     brouard  9136: 
1.227     brouard  9137: /*   stepsize=(int) (stepm+YEARM-1)/YEARM; */
                   9138: /*   if (stepm<=12) stepsize=1; */
1.126     brouard  9139:   
1.227     brouard  9140: /*   agelim=AGESUP; */
1.126     brouard  9141:   
1.227     brouard  9142: /*   hstepm=1; */
                   9143: /*   hstepm=hstepm/stepm;  */
1.218     brouard  9144:        
1.227     brouard  9145: /*   if (popforecast==1) { */
                   9146: /*     if((ficpop=fopen(popfile,"r"))==NULL) { */
                   9147: /*       printf("Problem with population file : %s\n",popfile);exit(0); */
                   9148: /*       fprintf(ficlog,"Problem with population file : %s\n",popfile);exit(0); */
                   9149: /*     }  */
                   9150: /*     popage=ivector(0,AGESUP); */
                   9151: /*     popeffectif=vector(0,AGESUP); */
                   9152: /*     popcount=vector(0,AGESUP); */
1.126     brouard  9153:     
1.227     brouard  9154: /*     i=1;    */
                   9155: /*     while ((c=fscanf(ficpop,"%d %lf\n",&popage[i],&popcount[i])) != EOF) i=i+1; */
1.218     brouard  9156:     
1.227     brouard  9157: /*     imx=i; */
                   9158: /*     for (i=1; i<imx;i++) popeffectif[popage[i]]=popcount[i]; */
                   9159: /*   } */
1.218     brouard  9160:   
1.227     brouard  9161: /*   for(cptcov=1,k=0;cptcov<=i2;cptcov++){ */
                   9162: /*     for(cptcod=1;cptcod<=ncodemax[cptcoveff];cptcod++){ */
                   9163: /*       k=k+1; */
                   9164: /*       fprintf(ficrespop,"\n#******"); */
                   9165: /*       for(j=1;j<=cptcoveff;j++) { */
                   9166: /*     fprintf(ficrespop," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]); */
                   9167: /*       } */
                   9168: /*       fprintf(ficrespop,"******\n"); */
                   9169: /*       fprintf(ficrespop,"# Age"); */
                   9170: /*       for(j=1; j<=nlstate+ndeath;j++) fprintf(ficrespop," P.%d",j); */
                   9171: /*       if (popforecast==1)  fprintf(ficrespop," [Population]"); */
1.126     brouard  9172:       
1.227     brouard  9173: /*       for (cpt=0; cpt<=0;cpt++) {  */
                   9174: /*     fprintf(ficrespop,"\n\n# Forecasting at date %.lf/%.lf/%.lf ",jpyram,mpyram,anpyram+cpt);    */
1.126     brouard  9175:        
1.227     brouard  9176: /*     for (agedeb=(fage-((int)calagedatem %12/12.)); agedeb>=(ageminpar-((int)calagedatem %12)/12.); agedeb--){  */
                   9177: /*       nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm);  */
                   9178: /*       nhstepm = nhstepm/hstepm;  */
1.126     brouard  9179:          
1.227     brouard  9180: /*       p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm); */
                   9181: /*       oldm=oldms;savm=savms; */
                   9182: /*       hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);   */
1.218     brouard  9183:          
1.227     brouard  9184: /*       for (h=0; h<=nhstepm; h++){ */
                   9185: /*         if (h==(int) (calagedatem+YEARM*cpt)) { */
                   9186: /*           fprintf(ficrespop,"\n %3.f ",agedeb+h*hstepm/YEARM*stepm); */
                   9187: /*         }  */
                   9188: /*         for(j=1; j<=nlstate+ndeath;j++) { */
                   9189: /*           kk1=0.;kk2=0; */
                   9190: /*           for(i=1; i<=nlstate;i++) {               */
                   9191: /*             if (mobilav==1)  */
                   9192: /*               kk1=kk1+p3mat[i][j][h]*mobaverage[(int)agedeb+1][i][cptcod]; */
                   9193: /*             else { */
                   9194: /*               kk1=kk1+p3mat[i][j][h]*probs[(int)(agedeb+1)][i][cptcod]; */
                   9195: /*             } */
                   9196: /*           } */
                   9197: /*           if (h==(int)(calagedatem+12*cpt)){ */
                   9198: /*             tabpop[(int)(agedeb)][j][cptcod]=kk1; */
                   9199: /*             /\*fprintf(ficrespop," %.3f", kk1); */
                   9200: /*               if (popforecast==1) fprintf(ficrespop," [%.f]", kk1*popeffectif[(int)agedeb+1]);*\/ */
                   9201: /*           } */
                   9202: /*         } */
                   9203: /*         for(i=1; i<=nlstate;i++){ */
                   9204: /*           kk1=0.; */
                   9205: /*           for(j=1; j<=nlstate;j++){ */
                   9206: /*             kk1= kk1+tabpop[(int)(agedeb)][j][cptcod];  */
                   9207: /*           } */
                   9208: /*           tabpopprev[(int)(agedeb)][i][cptcod]=tabpop[(int)(agedeb)][i][cptcod]/kk1*popeffectif[(int)(agedeb+(calagedatem+12*cpt)*hstepm/YEARM*stepm-1)]; */
                   9209: /*         } */
1.218     brouard  9210:            
1.227     brouard  9211: /*         if (h==(int)(calagedatem+12*cpt)) */
                   9212: /*           for(j=1; j<=nlstate;j++)  */
                   9213: /*             fprintf(ficrespop," %15.2f",tabpopprev[(int)(agedeb+1)][j][cptcod]); */
                   9214: /*       } */
                   9215: /*       free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm); */
                   9216: /*     } */
                   9217: /*       } */
1.218     brouard  9218:       
1.227     brouard  9219: /*       /\******\/ */
1.218     brouard  9220:       
1.227     brouard  9221: /*       for (cpt=1; cpt<=(anpyram1-anpyram);cpt++) {  */
                   9222: /*     fprintf(ficrespop,"\n\n# Forecasting at date %.lf/%.lf/%.lf ",jpyram,mpyram,anpyram+cpt);    */
                   9223: /*     for (agedeb=(fage-((int)calagedatem %12/12.)); agedeb>=(ageminpar-((int)calagedatem %12)/12.); agedeb--){  */
                   9224: /*       nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm);  */
                   9225: /*       nhstepm = nhstepm/hstepm;  */
1.126     brouard  9226:          
1.227     brouard  9227: /*       p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm); */
                   9228: /*       oldm=oldms;savm=savms; */
                   9229: /*       hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);   */
                   9230: /*       for (h=0; h<=nhstepm; h++){ */
                   9231: /*         if (h==(int) (calagedatem+YEARM*cpt)) { */
                   9232: /*           fprintf(ficresf,"\n %3.f ",agedeb+h*hstepm/YEARM*stepm); */
                   9233: /*         }  */
                   9234: /*         for(j=1; j<=nlstate+ndeath;j++) { */
                   9235: /*           kk1=0.;kk2=0; */
                   9236: /*           for(i=1; i<=nlstate;i++) {               */
                   9237: /*             kk1=kk1+p3mat[i][j][h]*tabpopprev[(int)agedeb+1][i][cptcod];     */
                   9238: /*           } */
                   9239: /*           if (h==(int)(calagedatem+12*cpt)) fprintf(ficresf," %15.2f", kk1);         */
                   9240: /*         } */
                   9241: /*       } */
                   9242: /*       free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm); */
                   9243: /*     } */
                   9244: /*       } */
                   9245: /*     }  */
                   9246: /*   } */
1.218     brouard  9247:   
1.227     brouard  9248: /*   /\* if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX); *\/ */
1.218     brouard  9249:   
1.227     brouard  9250: /*   if (popforecast==1) { */
                   9251: /*     free_ivector(popage,0,AGESUP); */
                   9252: /*     free_vector(popeffectif,0,AGESUP); */
                   9253: /*     free_vector(popcount,0,AGESUP); */
                   9254: /*   } */
                   9255: /*   free_ma3x(tabpop,1, AGESUP,1,NCOVMAX, 1,NCOVMAX); */
                   9256: /*   free_ma3x(tabpopprev,1, AGESUP,1,NCOVMAX, 1,NCOVMAX); */
                   9257: /*   fclose(ficrespop); */
                   9258: /* } /\* End of popforecast *\/ */
1.218     brouard  9259:  
1.126     brouard  9260: int fileappend(FILE *fichier, char *optionfich)
                   9261: {
                   9262:   if((fichier=fopen(optionfich,"a"))==NULL) {
                   9263:     printf("Problem with file: %s\n", optionfich);
                   9264:     fprintf(ficlog,"Problem with file: %s\n", optionfich);
                   9265:     return (0);
                   9266:   }
                   9267:   fflush(fichier);
                   9268:   return (1);
                   9269: }
                   9270: 
                   9271: 
                   9272: /**************** function prwizard **********************/
                   9273: void prwizard(int ncovmodel, int nlstate, int ndeath,  char model[], FILE *ficparo)
                   9274: {
                   9275: 
                   9276:   /* Wizard to print covariance matrix template */
                   9277: 
1.164     brouard  9278:   char ca[32], cb[32];
                   9279:   int i,j, k, li, lj, lk, ll, jj, npar, itimes;
1.126     brouard  9280:   int numlinepar;
                   9281: 
                   9282:   printf("# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
                   9283:   fprintf(ficparo,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
                   9284:   for(i=1; i <=nlstate; i++){
                   9285:     jj=0;
                   9286:     for(j=1; j <=nlstate+ndeath; j++){
                   9287:       if(j==i) continue;
                   9288:       jj++;
                   9289:       /*ca[0]= k+'a'-1;ca[1]='\0';*/
                   9290:       printf("%1d%1d",i,j);
                   9291:       fprintf(ficparo,"%1d%1d",i,j);
                   9292:       for(k=1; k<=ncovmodel;k++){
                   9293:        /*        printf(" %lf",param[i][j][k]); */
                   9294:        /*        fprintf(ficparo," %lf",param[i][j][k]); */
                   9295:        printf(" 0.");
                   9296:        fprintf(ficparo," 0.");
                   9297:       }
                   9298:       printf("\n");
                   9299:       fprintf(ficparo,"\n");
                   9300:     }
                   9301:   }
                   9302:   printf("# Scales (for hessian or gradient estimation)\n");
                   9303:   fprintf(ficparo,"# Scales (for hessian or gradient estimation)\n");
                   9304:   npar= (nlstate+ndeath-1)*nlstate*ncovmodel; /* Number of parameters*/ 
                   9305:   for(i=1; i <=nlstate; i++){
                   9306:     jj=0;
                   9307:     for(j=1; j <=nlstate+ndeath; j++){
                   9308:       if(j==i) continue;
                   9309:       jj++;
                   9310:       fprintf(ficparo,"%1d%1d",i,j);
                   9311:       printf("%1d%1d",i,j);
                   9312:       fflush(stdout);
                   9313:       for(k=1; k<=ncovmodel;k++){
                   9314:        /*      printf(" %le",delti3[i][j][k]); */
                   9315:        /*      fprintf(ficparo," %le",delti3[i][j][k]); */
                   9316:        printf(" 0.");
                   9317:        fprintf(ficparo," 0.");
                   9318:       }
                   9319:       numlinepar++;
                   9320:       printf("\n");
                   9321:       fprintf(ficparo,"\n");
                   9322:     }
                   9323:   }
                   9324:   printf("# Covariance matrix\n");
                   9325: /* # 121 Var(a12)\n\ */
                   9326: /* # 122 Cov(b12,a12) Var(b12)\n\ */
                   9327: /* # 131 Cov(a13,a12) Cov(a13,b12, Var(a13)\n\ */
                   9328: /* # 132 Cov(b13,a12) Cov(b13,b12, Cov(b13,a13) Var(b13)\n\ */
                   9329: /* # 212 Cov(a21,a12) Cov(a21,b12, Cov(a21,a13) Cov(a21,b13) Var(a21)\n\ */
                   9330: /* # 212 Cov(b21,a12) Cov(b21,b12, Cov(b21,a13) Cov(b21,b13) Cov(b21,a21) Var(b21)\n\ */
                   9331: /* # 232 Cov(a23,a12) Cov(a23,b12, Cov(a23,a13) Cov(a23,b13) Cov(a23,a21) Cov(a23,b21) Var(a23)\n\ */
                   9332: /* # 232 Cov(b23,a12) Cov(b23,b12) ... Var (b23)\n" */
                   9333:   fflush(stdout);
                   9334:   fprintf(ficparo,"# Covariance matrix\n");
                   9335:   /* # 121 Var(a12)\n\ */
                   9336:   /* # 122 Cov(b12,a12) Var(b12)\n\ */
                   9337:   /* #   ...\n\ */
                   9338:   /* # 232 Cov(b23,a12)  Cov(b23,b12) ... Var (b23)\n" */
                   9339:   
                   9340:   for(itimes=1;itimes<=2;itimes++){
                   9341:     jj=0;
                   9342:     for(i=1; i <=nlstate; i++){
                   9343:       for(j=1; j <=nlstate+ndeath; j++){
                   9344:        if(j==i) continue;
                   9345:        for(k=1; k<=ncovmodel;k++){
                   9346:          jj++;
                   9347:          ca[0]= k+'a'-1;ca[1]='\0';
                   9348:          if(itimes==1){
                   9349:            printf("#%1d%1d%d",i,j,k);
                   9350:            fprintf(ficparo,"#%1d%1d%d",i,j,k);
                   9351:          }else{
                   9352:            printf("%1d%1d%d",i,j,k);
                   9353:            fprintf(ficparo,"%1d%1d%d",i,j,k);
                   9354:            /*  printf(" %.5le",matcov[i][j]); */
                   9355:          }
                   9356:          ll=0;
                   9357:          for(li=1;li <=nlstate; li++){
                   9358:            for(lj=1;lj <=nlstate+ndeath; lj++){
                   9359:              if(lj==li) continue;
                   9360:              for(lk=1;lk<=ncovmodel;lk++){
                   9361:                ll++;
                   9362:                if(ll<=jj){
                   9363:                  cb[0]= lk +'a'-1;cb[1]='\0';
                   9364:                  if(ll<jj){
                   9365:                    if(itimes==1){
                   9366:                      printf(" Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
                   9367:                      fprintf(ficparo," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
                   9368:                    }else{
                   9369:                      printf(" 0.");
                   9370:                      fprintf(ficparo," 0.");
                   9371:                    }
                   9372:                  }else{
                   9373:                    if(itimes==1){
                   9374:                      printf(" Var(%s%1d%1d)",ca,i,j);
                   9375:                      fprintf(ficparo," Var(%s%1d%1d)",ca,i,j);
                   9376:                    }else{
                   9377:                      printf(" 0.");
                   9378:                      fprintf(ficparo," 0.");
                   9379:                    }
                   9380:                  }
                   9381:                }
                   9382:              } /* end lk */
                   9383:            } /* end lj */
                   9384:          } /* end li */
                   9385:          printf("\n");
                   9386:          fprintf(ficparo,"\n");
                   9387:          numlinepar++;
                   9388:        } /* end k*/
                   9389:       } /*end j */
                   9390:     } /* end i */
                   9391:   } /* end itimes */
                   9392: 
                   9393: } /* end of prwizard */
                   9394: /******************* Gompertz Likelihood ******************************/
                   9395: double gompertz(double x[])
                   9396: { 
1.302     brouard  9397:   double A=0.0,B=0.,L=0.0,sump=0.,num=0.;
1.126     brouard  9398:   int i,n=0; /* n is the size of the sample */
                   9399: 
1.220     brouard  9400:   for (i=1;i<=imx ; i++) {
1.126     brouard  9401:     sump=sump+weight[i];
                   9402:     /*    sump=sump+1;*/
                   9403:     num=num+1;
                   9404:   }
1.302     brouard  9405:   L=0.0;
                   9406:   /* agegomp=AGEGOMP; */
1.126     brouard  9407:   /* for (i=0; i<=imx; i++) 
                   9408:      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]);*/
                   9409: 
1.302     brouard  9410:   for (i=1;i<=imx ; i++) {
                   9411:     /* mu(a)=mu(agecomp)*exp(teta*(age-agegomp))
                   9412:        mu(a)=x[1]*exp(x[2]*(age-agegomp)); x[1] and x[2] are per year.
                   9413:      * L= Product mu(agedeces)exp(-\int_ageexam^agedc mu(u) du ) for a death between agedc (in month) 
                   9414:      *   and agedc +1 month, cens[i]=0: log(x[1]/YEARM)
                   9415:      * +
                   9416:      * exp(-\int_ageexam^agecens mu(u) du ) when censored, cens[i]=1
                   9417:      */
                   9418:      if (wav[i] > 1 || agedc[i] < AGESUP) {
                   9419:        if (cens[i] == 1){
                   9420:         A=-x[1]/(x[2])*(exp(x[2]*(agecens[i]-agegomp))-exp(x[2]*(ageexmed[i]-agegomp)));
                   9421:        } else if (cens[i] == 0){
1.126     brouard  9422:        A=-x[1]/(x[2])*(exp(x[2]*(agedc[i]-agegomp))-exp(x[2]*(ageexmed[i]-agegomp)))
1.302     brouard  9423:          +log(x[1]/YEARM) +x[2]*(agedc[i]-agegomp)+log(YEARM);
                   9424:       } else
                   9425:         printf("Gompertz cens[%d] neither 1 nor 0\n",i);
1.126     brouard  9426:       /*if (wav[i] > 1 && agecens[i] > 15) {*/ /* ??? */
1.302     brouard  9427:        L=L+A*weight[i];
1.126     brouard  9428:        /*      printf("\ni=%d A=%f L=%lf x[1]=%lf x[2]=%lf ageex=%lf agecens=%lf cens=%d agedc=%lf weight=%lf\n",i,A,L,x[1],x[2],ageexmed[i]*12,agecens[i]*12,cens[i],agedc[i]*12,weight[i]);*/
1.302     brouard  9429:      }
                   9430:   }
1.126     brouard  9431: 
1.302     brouard  9432:   /*printf("x1=%2.9f x2=%2.9f x3=%2.9f L=%f\n",x[1],x[2],x[3],L);*/
1.126     brouard  9433:  
                   9434:   return -2*L*num/sump;
                   9435: }
                   9436: 
1.136     brouard  9437: #ifdef GSL
                   9438: /******************* Gompertz_f Likelihood ******************************/
                   9439: double gompertz_f(const gsl_vector *v, void *params)
                   9440: { 
1.302     brouard  9441:   double A=0.,B=0.,LL=0.0,sump=0.,num=0.;
1.136     brouard  9442:   double *x= (double *) v->data;
                   9443:   int i,n=0; /* n is the size of the sample */
                   9444: 
                   9445:   for (i=0;i<=imx-1 ; i++) {
                   9446:     sump=sump+weight[i];
                   9447:     /*    sump=sump+1;*/
                   9448:     num=num+1;
                   9449:   }
                   9450:  
                   9451:  
                   9452:   /* for (i=0; i<=imx; i++) 
                   9453:      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]);*/
                   9454:   printf("x[0]=%lf x[1]=%lf\n",x[0],x[1]);
                   9455:   for (i=1;i<=imx ; i++)
                   9456:     {
                   9457:       if (cens[i] == 1 && wav[i]>1)
                   9458:        A=-x[0]/(x[1])*(exp(x[1]*(agecens[i]-agegomp))-exp(x[1]*(ageexmed[i]-agegomp)));
                   9459:       
                   9460:       if (cens[i] == 0 && wav[i]>1)
                   9461:        A=-x[0]/(x[1])*(exp(x[1]*(agedc[i]-agegomp))-exp(x[1]*(ageexmed[i]-agegomp)))
                   9462:             +log(x[0]/YEARM)+x[1]*(agedc[i]-agegomp)+log(YEARM);  
                   9463:       
                   9464:       /*if (wav[i] > 1 && agecens[i] > 15) {*/ /* ??? */
                   9465:       if (wav[i] > 1 ) { /* ??? */
                   9466:        LL=LL+A*weight[i];
                   9467:        /*      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]);*/
                   9468:       }
                   9469:     }
                   9470: 
                   9471:  /*printf("x1=%2.9f x2=%2.9f x3=%2.9f L=%f\n",x[1],x[2],x[3],L);*/
                   9472:   printf("x[0]=%lf x[1]=%lf -2*LL*num/sump=%lf\n",x[0],x[1],-2*LL*num/sump);
                   9473:  
                   9474:   return -2*LL*num/sump;
                   9475: }
                   9476: #endif
                   9477: 
1.126     brouard  9478: /******************* Printing html file ***********/
1.201     brouard  9479: void printinghtmlmort(char fileresu[], char title[], char datafile[], int firstpass, \
1.126     brouard  9480:                  int lastpass, int stepm, int weightopt, char model[],\
                   9481:                  int imx,  double p[],double **matcov,double agemortsup){
                   9482:   int i,k;
                   9483: 
                   9484:   fprintf(fichtm,"<ul><li><h4>Result files </h4>\n Force of mortality. Parameters of the Gompertz fit (with confidence interval in brackets):<br>");
                   9485:   fprintf(fichtm,"  mu(age) =%lf*exp(%lf*(age-%d)) per year<br><br>",p[1],p[2],agegomp);
                   9486:   for (i=1;i<=2;i++) 
                   9487:     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  9488:   fprintf(fichtm,"<br><br><img src=\"graphmort.svg\">");
1.126     brouard  9489:   fprintf(fichtm,"</ul>");
                   9490: 
                   9491: fprintf(fichtm,"<ul><li><h4>Life table</h4>\n <br>");
                   9492: 
                   9493:  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>");
                   9494: 
                   9495:  for (k=agegomp;k<(agemortsup-2);k++) 
                   9496:    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]);
                   9497: 
                   9498:  
                   9499:   fflush(fichtm);
                   9500: }
                   9501: 
                   9502: /******************* Gnuplot file **************/
1.201     brouard  9503: void printinggnuplotmort(char fileresu[], char optionfilefiname[], double ageminpar, double agemaxpar, double fage , char pathc[], double p[]){
1.126     brouard  9504: 
                   9505:   char dirfileres[132],optfileres[132];
1.164     brouard  9506: 
1.126     brouard  9507:   int ng;
                   9508: 
                   9509: 
                   9510:   /*#ifdef windows */
                   9511:   fprintf(ficgp,"cd \"%s\" \n",pathc);
                   9512:     /*#endif */
                   9513: 
                   9514: 
                   9515:   strcpy(dirfileres,optionfilefiname);
                   9516:   strcpy(optfileres,"vpl");
1.199     brouard  9517:   fprintf(ficgp,"set out \"graphmort.svg\"\n "); 
1.126     brouard  9518:   fprintf(ficgp,"set xlabel \"Age\"\n set ylabel \"Force of mortality (per year)\" \n "); 
1.199     brouard  9519:   fprintf(ficgp, "set ter svg size 640, 480\n set log y\n"); 
1.145     brouard  9520:   /* fprintf(ficgp, "set size 0.65,0.65\n"); */
1.126     brouard  9521:   fprintf(ficgp,"plot [%d:100] %lf*exp(%lf*(x-%d))",agegomp,p[1],p[2],agegomp);
                   9522: 
                   9523: } 
                   9524: 
1.136     brouard  9525: int readdata(char datafile[], int firstobs, int lastobs, int *imax)
                   9526: {
1.126     brouard  9527: 
1.136     brouard  9528:   /*-------- data file ----------*/
                   9529:   FILE *fic;
                   9530:   char dummy[]="                         ";
1.240     brouard  9531:   int i=0, j=0, n=0, iv=0, v;
1.223     brouard  9532:   int lstra;
1.136     brouard  9533:   int linei, month, year,iout;
1.302     brouard  9534:   int noffset=0; /* This is the offset if BOM data file */
1.136     brouard  9535:   char line[MAXLINE], linetmp[MAXLINE];
1.164     brouard  9536:   char stra[MAXLINE], strb[MAXLINE];
1.136     brouard  9537:   char *stratrunc;
1.223     brouard  9538: 
1.240     brouard  9539:   DummyV=ivector(1,NCOVMAX); /* 1 to 3 */
                   9540:   FixedV=ivector(1,NCOVMAX); /* 1 to 3 */
1.126     brouard  9541: 
1.240     brouard  9542:   for(v=1; v <=ncovcol;v++){
                   9543:     DummyV[v]=0;
                   9544:     FixedV[v]=0;
                   9545:   }
                   9546:   for(v=ncovcol+1; v <=ncovcol+nqv;v++){
                   9547:     DummyV[v]=1;
                   9548:     FixedV[v]=0;
                   9549:   }
                   9550:   for(v=ncovcol+nqv+1; v <=ncovcol+nqv+ntv;v++){
                   9551:     DummyV[v]=0;
                   9552:     FixedV[v]=1;
                   9553:   }
                   9554:   for(v=ncovcol+nqv+ntv+1; v <=ncovcol+nqv+ntv+nqtv;v++){
                   9555:     DummyV[v]=1;
                   9556:     FixedV[v]=1;
                   9557:   }
                   9558:   for(v=1; v <=ncovcol+nqv+ntv+nqtv;v++){
                   9559:     printf("Covariate type in the data: V%d, DummyV(V%d)=%d, FixedV(V%d)=%d\n",v,v,DummyV[v],v,FixedV[v]);
                   9560:     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]);
                   9561:   }
1.126     brouard  9562: 
1.136     brouard  9563:   if((fic=fopen(datafile,"r"))==NULL)    {
1.218     brouard  9564:     printf("Problem while opening datafile: %s with errno='%s'\n", datafile,strerror(errno));fflush(stdout);
                   9565:     fprintf(ficlog,"Problem while opening datafile: %s with errno='%s'\n", datafile,strerror(errno));fflush(ficlog);return 1;
1.136     brouard  9566:   }
1.126     brouard  9567: 
1.302     brouard  9568:     /* Is it a BOM UTF-8 Windows file? */
                   9569:   /* First data line */
                   9570:   linei=0;
                   9571:   while(fgets(line, MAXLINE, fic)) {
                   9572:     noffset=0;
                   9573:     if( line[0] == (char)0xEF && line[1] == (char)0xBB) /* EF BB BF */
                   9574:     {
                   9575:       noffset=noffset+3;
                   9576:       printf("# Data file '%s'  is an UTF8 BOM file, please convert to UTF8 or ascii file and rerun.\n",datafile);fflush(stdout);
                   9577:       fprintf(ficlog,"# Data file '%s'  is an UTF8 BOM file, please convert to UTF8 or ascii file and rerun.\n",datafile);
                   9578:       fflush(ficlog); return 1;
                   9579:     }
                   9580:     /*    else if( line[0] == (char)0xFE && line[1] == (char)0xFF)*/
                   9581:     else if( line[0] == (char)0xFF && line[1] == (char)0xFE)
                   9582:     {
                   9583:       noffset=noffset+2;
1.304     brouard  9584:       printf("# Error Data file '%s'  is a huge UTF16BE BOM file, please convert to UTF8 or ascii file (for example with dos2unix) and rerun.\n",datafile);fflush(stdout);
                   9585:       fprintf(ficlog,"# Error Data file '%s'  is a huge UTF16BE BOM file, please convert to UTF8 or ascii file (for example with dos2unix) and rerun.\n",datafile);
1.302     brouard  9586:       fflush(ficlog); return 1;
                   9587:     }
                   9588:     else if( line[0] == 0 && line[1] == 0)
                   9589:     {
                   9590:       if( line[2] == (char)0xFE && line[3] == (char)0xFF){
                   9591:        noffset=noffset+4;
1.304     brouard  9592:        printf("# Error Data file '%s'  is a huge UTF16BE BOM file, please convert to UTF8 or ascii file (for example with dos2unix) and rerun.\n",datafile);fflush(stdout);
                   9593:        fprintf(ficlog,"# Error Data file '%s'  is a huge UTF16BE BOM file, please convert to UTF8 or ascii file (for example with dos2unix) and rerun.\n",datafile);
1.302     brouard  9594:        fflush(ficlog); return 1;
                   9595:       }
                   9596:     } else{
                   9597:       ;/*printf(" Not a BOM file\n");*/
                   9598:     }
                   9599:         /* If line starts with a # it is a comment */
                   9600:     if (line[noffset] == '#') {
                   9601:       linei=linei+1;
                   9602:       break;
                   9603:     }else{
                   9604:       break;
                   9605:     }
                   9606:   }
                   9607:   fclose(fic);
                   9608:   if((fic=fopen(datafile,"r"))==NULL)    {
                   9609:     printf("Problem while opening datafile: %s with errno='%s'\n", datafile,strerror(errno));fflush(stdout);
                   9610:     fprintf(ficlog,"Problem while opening datafile: %s with errno='%s'\n", datafile,strerror(errno));fflush(ficlog);return 1;
                   9611:   }
                   9612:   /* Not a Bom file */
                   9613:   
1.136     brouard  9614:   i=1;
                   9615:   while ((fgets(line, MAXLINE, fic) != NULL) &&((i >= firstobs) && (i <=lastobs))) {
                   9616:     linei=linei+1;
                   9617:     for(j=strlen(line); j>=0;j--){  /* Untabifies line */
                   9618:       if(line[j] == '\t')
                   9619:        line[j] = ' ';
                   9620:     }
                   9621:     for(j=strlen(line)-1; (line[j]==' ')||(line[j]==10)||(line[j]==13);j--){
                   9622:       ;
                   9623:     };
                   9624:     line[j+1]=0;  /* Trims blanks at end of line */
                   9625:     if(line[0]=='#'){
                   9626:       fprintf(ficlog,"Comment line\n%s\n",line);
                   9627:       printf("Comment line\n%s\n",line);
                   9628:       continue;
                   9629:     }
                   9630:     trimbb(linetmp,line); /* Trims multiple blanks in line */
1.164     brouard  9631:     strcpy(line, linetmp);
1.223     brouard  9632:     
                   9633:     /* Loops on waves */
                   9634:     for (j=maxwav;j>=1;j--){
                   9635:       for (iv=nqtv;iv>=1;iv--){  /* Loop  on time varying quantitative variables */
1.238     brouard  9636:        cutv(stra, strb, line, ' '); 
                   9637:        if(strb[0]=='.') { /* Missing value */
                   9638:          lval=-1;
                   9639:          cotqvar[j][iv][i]=-1; /* 0.0/0.0 */
                   9640:          cotvar[j][ntv+iv][i]=-1; /* For performance reasons */
                   9641:          if(isalpha(strb[1])) { /* .m or .d Really Missing value */
                   9642:            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);
                   9643:            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);
                   9644:            return 1;
                   9645:          }
                   9646:        }else{
                   9647:          errno=0;
                   9648:          /* what_kind_of_number(strb); */
                   9649:          dval=strtod(strb,&endptr); 
                   9650:          /* if( strb[0]=='\0' || (*endptr != '\0')){ */
                   9651:          /* if(strb != endptr && *endptr == '\0') */
                   9652:          /*    dval=dlval; */
                   9653:          /* if (errno == ERANGE && (lval == LONG_MAX || lval == LONG_MIN)) */
                   9654:          if( strb[0]=='\0' || (*endptr != '\0')){
                   9655:            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);
                   9656:            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);
                   9657:            return 1;
                   9658:          }
                   9659:          cotqvar[j][iv][i]=dval; 
                   9660:          cotvar[j][ntv+iv][i]=dval; 
                   9661:        }
                   9662:        strcpy(line,stra);
1.223     brouard  9663:       }/* end loop ntqv */
1.225     brouard  9664:       
1.223     brouard  9665:       for (iv=ntv;iv>=1;iv--){  /* Loop  on time varying dummies */
1.238     brouard  9666:        cutv(stra, strb, line, ' '); 
                   9667:        if(strb[0]=='.') { /* Missing value */
                   9668:          lval=-1;
                   9669:        }else{
                   9670:          errno=0;
                   9671:          lval=strtol(strb,&endptr,10); 
                   9672:          /*    if (errno == ERANGE && (lval == LONG_MAX || lval == LONG_MIN))*/
                   9673:          if( strb[0]=='\0' || (*endptr != '\0')){
                   9674:            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);
                   9675:            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);
                   9676:            return 1;
                   9677:          }
                   9678:        }
                   9679:        if(lval <-1 || lval >1){
                   9680:          printf("Error reading data around '%ld' at line number %d for individual %d, '%s'\n \
1.319     brouard  9681:  Should be a value of %d(nth) covariate of wave %d (0 should be the value for the reference and 1\n \
1.223     brouard  9682:  for the alternative. IMaCh does not build design variables automatically, do it yourself.\n \
1.238     brouard  9683:  For example, for multinomial values like 1, 2 and 3,\n                        \
                   9684:  build V1=0 V2=0 for the reference value (1),\n                                \
                   9685:         V1=1 V2=0 for (2) \n                                           \
1.223     brouard  9686:  and V1=0 V2=1 for (3). V1=1 V2=1 should not exist and the corresponding\n \
1.238     brouard  9687:  output of IMaCh is often meaningless.\n                               \
1.319     brouard  9688:  Exiting.\n",lval,linei, i,line,iv,j);
1.238     brouard  9689:          fprintf(ficlog,"Error reading data around '%ld' at line number %d for individual %d, '%s'\n \
1.319     brouard  9690:  Should be a value of %d(nth) covariate of wave %d (0 should be the value for the reference and 1\n \
1.223     brouard  9691:  for the alternative. IMaCh does not build design variables automatically, do it yourself.\n \
1.238     brouard  9692:  For example, for multinomial values like 1, 2 and 3,\n                        \
                   9693:  build V1=0 V2=0 for the reference value (1),\n                                \
                   9694:         V1=1 V2=0 for (2) \n                                           \
1.223     brouard  9695:  and V1=0 V2=1 for (3). V1=1 V2=1 should not exist and the corresponding\n \
1.238     brouard  9696:  output of IMaCh is often meaningless.\n                               \
1.319     brouard  9697:  Exiting.\n",lval,linei, i,line,iv,j);fflush(ficlog);
1.238     brouard  9698:          return 1;
                   9699:        }
                   9700:        cotvar[j][iv][i]=(double)(lval);
                   9701:        strcpy(line,stra);
1.223     brouard  9702:       }/* end loop ntv */
1.225     brouard  9703:       
1.223     brouard  9704:       /* Statuses  at wave */
1.137     brouard  9705:       cutv(stra, strb, line, ' '); 
1.223     brouard  9706:       if(strb[0]=='.') { /* Missing value */
1.238     brouard  9707:        lval=-1;
1.136     brouard  9708:       }else{
1.238     brouard  9709:        errno=0;
                   9710:        lval=strtol(strb,&endptr,10); 
                   9711:        /*      if (errno == ERANGE && (lval == LONG_MAX || lval == LONG_MIN))*/
                   9712:        if( strb[0]=='\0' || (*endptr != '\0')){
                   9713:          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);
                   9714:          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);
                   9715:          return 1;
                   9716:        }
1.136     brouard  9717:       }
1.225     brouard  9718:       
1.136     brouard  9719:       s[j][i]=lval;
1.225     brouard  9720:       
1.223     brouard  9721:       /* Date of Interview */
1.136     brouard  9722:       strcpy(line,stra);
                   9723:       cutv(stra, strb,line,' ');
1.169     brouard  9724:       if( (iout=sscanf(strb,"%d/%d",&month, &year)) != 0){
1.136     brouard  9725:       }
1.169     brouard  9726:       else  if( (iout=sscanf(strb,"%s.",dummy)) != 0){
1.225     brouard  9727:        month=99;
                   9728:        year=9999;
1.136     brouard  9729:       }else{
1.225     brouard  9730:        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);
                   9731:        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);
                   9732:        return 1;
1.136     brouard  9733:       }
                   9734:       anint[j][i]= (double) year; 
1.302     brouard  9735:       mint[j][i]= (double)month;
                   9736:       /* if( (int)anint[j][i]+ (int)(mint[j][i])/12. < (int) (moisnais[i]/12.+annais[i])){ */
                   9737:       /*       printf("Warning reading data around '%s' at line number %d for individual %d, '%s'\nThe date of interview (%2d/%4d) at wave %d occurred before the date of birth (%2d/%4d).\n",strb, linei,i, line, mint[j][i],anint[j][i], moisnais[i],annais[i]); */
                   9738:       /*       fprintf(ficlog,"Warning reading data around '%s' at line number %d for individual %d, '%s'\nThe date of interview (%2d/%4d) at wave %d occurred before the date of birth (%2d/%4d).\n",strb, linei,i, line, mint[j][i],anint[j][i], moisnais[i],annais[i]); */
                   9739:       /* } */
1.136     brouard  9740:       strcpy(line,stra);
1.223     brouard  9741:     } /* End loop on waves */
1.225     brouard  9742:     
1.223     brouard  9743:     /* Date of death */
1.136     brouard  9744:     cutv(stra, strb,line,' '); 
1.169     brouard  9745:     if( (iout=sscanf(strb,"%d/%d",&month, &year)) != 0){
1.136     brouard  9746:     }
1.169     brouard  9747:     else  if( (iout=sscanf(strb,"%s.",dummy)) != 0){
1.136     brouard  9748:       month=99;
                   9749:       year=9999;
                   9750:     }else{
1.141     brouard  9751:       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  9752:       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);
                   9753:       return 1;
1.136     brouard  9754:     }
                   9755:     andc[i]=(double) year; 
                   9756:     moisdc[i]=(double) month; 
                   9757:     strcpy(line,stra);
                   9758:     
1.223     brouard  9759:     /* Date of birth */
1.136     brouard  9760:     cutv(stra, strb,line,' '); 
1.169     brouard  9761:     if( (iout=sscanf(strb,"%d/%d",&month, &year)) != 0){
1.136     brouard  9762:     }
1.169     brouard  9763:     else  if( (iout=sscanf(strb,"%s.", dummy)) != 0){
1.136     brouard  9764:       month=99;
                   9765:       year=9999;
                   9766:     }else{
1.141     brouard  9767:       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);
                   9768:       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  9769:       return 1;
1.136     brouard  9770:     }
                   9771:     if (year==9999) {
1.141     brouard  9772:       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);
                   9773:       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  9774:       return 1;
                   9775:       
1.136     brouard  9776:     }
                   9777:     annais[i]=(double)(year);
1.302     brouard  9778:     moisnais[i]=(double)(month);
                   9779:     for (j=1;j<=maxwav;j++){
                   9780:       if( (int)anint[j][i]+ (int)(mint[j][i])/12. < (int) (moisnais[i]/12.+annais[i])){
                   9781:        printf("Warning reading data around '%s' at line number %d for individual %d, '%s'\nThe date of interview (%2d/%4d) at wave %d occurred before the date of birth (%2d/%4d).\n",strb, linei,i, line, (int)mint[j][i],(int)anint[j][i], j,(int)moisnais[i],(int)annais[i]);
                   9782:        fprintf(ficlog,"Warning reading data around '%s' at line number %d for individual %d, '%s'\nThe date of interview (%2d/%4d) at wave %d occurred before the date of birth (%2d/%4d).\n",strb, linei,i, line, (int)mint[j][i],(int)anint[j][i], j, (int)moisnais[i],(int)annais[i]);
                   9783:       }
                   9784:     }
                   9785: 
1.136     brouard  9786:     strcpy(line,stra);
1.225     brouard  9787:     
1.223     brouard  9788:     /* Sample weight */
1.136     brouard  9789:     cutv(stra, strb,line,' '); 
                   9790:     errno=0;
                   9791:     dval=strtod(strb,&endptr); 
                   9792:     if( strb[0]=='\0' || (*endptr != '\0')){
1.141     brouard  9793:       printf("Error reading data around '%f' at line number %d, \"%s\" for individual %d\nShould be a weight.  Exiting.\n",dval, i,line,linei);
                   9794:       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  9795:       fflush(ficlog);
                   9796:       return 1;
                   9797:     }
                   9798:     weight[i]=dval; 
                   9799:     strcpy(line,stra);
1.225     brouard  9800:     
1.223     brouard  9801:     for (iv=nqv;iv>=1;iv--){  /* Loop  on fixed quantitative variables */
                   9802:       cutv(stra, strb, line, ' '); 
                   9803:       if(strb[0]=='.') { /* Missing value */
1.225     brouard  9804:        lval=-1;
1.311     brouard  9805:        coqvar[iv][i]=NAN; 
                   9806:        covar[ncovcol+iv][i]=NAN; /* including qvar in standard covar for performance reasons */ 
1.223     brouard  9807:       }else{
1.225     brouard  9808:        errno=0;
                   9809:        /* what_kind_of_number(strb); */
                   9810:        dval=strtod(strb,&endptr);
                   9811:        /* if(strb != endptr && *endptr == '\0') */
                   9812:        /*   dval=dlval; */
                   9813:        /* if (errno == ERANGE && (lval == LONG_MAX || lval == LONG_MIN)) */
                   9814:        if( strb[0]=='\0' || (*endptr != '\0')){
                   9815:          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);
                   9816:          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);
                   9817:          return 1;
                   9818:        }
                   9819:        coqvar[iv][i]=dval; 
1.226     brouard  9820:        covar[ncovcol+iv][i]=dval; /* including qvar in standard covar for performance reasons */ 
1.223     brouard  9821:       }
                   9822:       strcpy(line,stra);
                   9823:     }/* end loop nqv */
1.136     brouard  9824:     
1.223     brouard  9825:     /* Covariate values */
1.136     brouard  9826:     for (j=ncovcol;j>=1;j--){
                   9827:       cutv(stra, strb,line,' '); 
1.223     brouard  9828:       if(strb[0]=='.') { /* Missing covariate value */
1.225     brouard  9829:        lval=-1;
1.136     brouard  9830:       }else{
1.225     brouard  9831:        errno=0;
                   9832:        lval=strtol(strb,&endptr,10); 
                   9833:        if( strb[0]=='\0' || (*endptr != '\0')){
                   9834:          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);
                   9835:          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);
                   9836:          return 1;
                   9837:        }
1.136     brouard  9838:       }
                   9839:       if(lval <-1 || lval >1){
1.225     brouard  9840:        printf("Error reading data around '%ld' at line number %d for individual %d, '%s'\n \
1.136     brouard  9841:  Should be a value of %d(nth) covariate (0 should be the value for the reference and 1\n \
                   9842:  for the alternative. IMaCh does not build design variables automatically, do it yourself.\n \
1.225     brouard  9843:  For example, for multinomial values like 1, 2 and 3,\n                        \
                   9844:  build V1=0 V2=0 for the reference value (1),\n                                \
                   9845:         V1=1 V2=0 for (2) \n                                           \
1.136     brouard  9846:  and V1=0 V2=1 for (3). V1=1 V2=1 should not exist and the corresponding\n \
1.225     brouard  9847:  output of IMaCh is often meaningless.\n                               \
1.136     brouard  9848:  Exiting.\n",lval,linei, i,line,j);
1.225     brouard  9849:        fprintf(ficlog,"Error reading data around '%ld' at line number %d for individual %d, '%s'\n \
1.136     brouard  9850:  Should be a value of %d(nth) covariate (0 should be the value for the reference and 1\n \
                   9851:  for the alternative. IMaCh does not build design variables automatically, do it yourself.\n \
1.225     brouard  9852:  For example, for multinomial values like 1, 2 and 3,\n                        \
                   9853:  build V1=0 V2=0 for the reference value (1),\n                                \
                   9854:         V1=1 V2=0 for (2) \n                                           \
1.136     brouard  9855:  and V1=0 V2=1 for (3). V1=1 V2=1 should not exist and the corresponding\n \
1.225     brouard  9856:  output of IMaCh is often meaningless.\n                               \
1.136     brouard  9857:  Exiting.\n",lval,linei, i,line,j);fflush(ficlog);
1.225     brouard  9858:        return 1;
1.136     brouard  9859:       }
                   9860:       covar[j][i]=(double)(lval);
                   9861:       strcpy(line,stra);
                   9862:     }  
                   9863:     lstra=strlen(stra);
1.225     brouard  9864:     
1.136     brouard  9865:     if(lstra > 9){ /* More than 2**32 or max of what printf can write with %ld */
                   9866:       stratrunc = &(stra[lstra-9]);
                   9867:       num[i]=atol(stratrunc);
                   9868:     }
                   9869:     else
                   9870:       num[i]=atol(stra);
                   9871:     /*if((s[2][i]==2) && (s[3][i]==-1)&&(s[4][i]==9)){
                   9872:       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;}*/
                   9873:     
                   9874:     i=i+1;
                   9875:   } /* End loop reading  data */
1.225     brouard  9876:   
1.136     brouard  9877:   *imax=i-1; /* Number of individuals */
                   9878:   fclose(fic);
1.225     brouard  9879:   
1.136     brouard  9880:   return (0);
1.164     brouard  9881:   /* endread: */
1.225     brouard  9882:   printf("Exiting readdata: ");
                   9883:   fclose(fic);
                   9884:   return (1);
1.223     brouard  9885: }
1.126     brouard  9886: 
1.234     brouard  9887: void removefirstspace(char **stri){/*, char stro[]) {*/
1.230     brouard  9888:   char *p1 = *stri, *p2 = *stri;
1.235     brouard  9889:   while (*p2 == ' ')
1.234     brouard  9890:     p2++; 
                   9891:   /* while ((*p1++ = *p2++) !=0) */
                   9892:   /*   ; */
                   9893:   /* do */
                   9894:   /*   while (*p2 == ' ') */
                   9895:   /*     p2++; */
                   9896:   /* while (*p1++ == *p2++); */
                   9897:   *stri=p2; 
1.145     brouard  9898: }
                   9899: 
1.235     brouard  9900: int decoderesult ( char resultline[], int nres)
1.230     brouard  9901: /**< This routine decode one result line and returns the combination # of dummy covariates only **/
                   9902: {
1.235     brouard  9903:   int j=0, k=0, k1=0, k2=0, k3=0, k4=0, match=0, k2q=0, k3q=0, k4q=0;
1.230     brouard  9904:   char resultsav[MAXLINE];
1.234     brouard  9905:   int resultmodel[MAXLINE];
                   9906:   int modelresult[MAXLINE];
1.230     brouard  9907:   char stra[80], strb[80], strc[80], strd[80],stre[80];
                   9908: 
1.234     brouard  9909:   removefirstspace(&resultline);
1.230     brouard  9910: 
                   9911:   if (strstr(resultline,"v") !=0){
                   9912:     printf("Error. 'v' must be in upper case 'V' result: %s ",resultline);
                   9913:     fprintf(ficlog,"Error. 'v' must be in upper case result: %s ",resultline);fflush(ficlog);
                   9914:     return 1;
                   9915:   }
                   9916:   trimbb(resultsav, resultline);
                   9917:   if (strlen(resultsav) >1){
                   9918:     j=nbocc(resultsav,'='); /**< j=Number of covariate values'=' */
                   9919:   }
1.253     brouard  9920:   if(j == 0){ /* Resultline but no = */
                   9921:     TKresult[nres]=0; /* Combination for the nresult and the model */
                   9922:     return (0);
                   9923:   }
1.234     brouard  9924:   if( j != cptcovs ){ /* Be careful if a variable is in a product but not single */
1.318     brouard  9925:     printf("ERROR: the number of variables in this result line, %d, differs from the number of variables used in the model line, %d.\n",j, cptcovs);
1.310     brouard  9926:     fprintf(ficlog,"ERROR: the number of variables in the resultline, %d, differs from the number of variables used in the model line, %d.\n",j, cptcovs);
1.234     brouard  9927:   }
                   9928:   for(k=1; k<=j;k++){ /* Loop on any covariate of the result line */
                   9929:     if(nbocc(resultsav,'=') >1){
1.318     brouard  9930:       cutl(stra,strb,resultsav,' '); /* keeps in strb after the first ' ' (stra is the rest of the resultline to be analyzed in the next loop *//*     resultsav= "V4=1 V5=25.1 V3=0" stra= "V5=25.1 V3=0" strb= "V4=1" */
                   9931:       cutl(strc,strd,strb,'=');  /* strb:"V4=1" strc="1" strd="V4" */
1.234     brouard  9932:     }else
                   9933:       cutl(strc,strd,resultsav,'=');
1.318     brouard  9934:     Tvalsel[k]=atof(strc); /* 1 */ /* Tvalsel of k is the float value of the kth covariate appearing in this result line */
1.234     brouard  9935:     
1.230     brouard  9936:     cutl(strc,stre,strd,'V'); /* strd='V4' strc=4 stre='V' */;
1.318     brouard  9937:     Tvarsel[k]=atoi(strc);  /* 4 */ /* Tvarsel is the id of the kth covariate in the result line Tvarsel[1] in "V4=1.." is 4.*/
1.230     brouard  9938:     /* Typevarsel[k]=1;  /\* 1 for age product *\/ */
                   9939:     /* cptcovsel++;     */
                   9940:     if (nbocc(stra,'=') >0)
                   9941:       strcpy(resultsav,stra); /* and analyzes it */
                   9942:   }
1.235     brouard  9943:   /* Checking for missing or useless values in comparison of current model needs */
1.318     brouard  9944:   for(k1=1; k1<= cptcovt ;k1++){ /* Loop on model. model line V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
                   9945:     if(Typevar[k1]==0){ /* Single covariate in model *//*0 for simple covariate (dummy, quantitative, fixed or varying), 1 for age product, 2 for  product */
1.234     brouard  9946:       match=0;
1.318     brouard  9947:       for(k2=1; k2 <=j;k2++){/* Loop on resultline. In result line V4=1 V5=24.1 V3=1  V2=8 V1=0 */
                   9948:        if(Tvar[k1]==Tvarsel[k2]) {/* Tvar is coming from the model, Tvarsel from the result. Tvar[1]=5 == Tvarsel[2]=5   */
1.236     brouard  9949:          modelresult[k2]=k1;/* modelresult[2]=1 modelresult[1]=2  modelresult[3]=3  modelresult[6]=4 modelresult[9]=5 */
1.318     brouard  9950:          match=1; /* modelresult of k2 variable of resultline is identical to k1 variable of the model good */
1.234     brouard  9951:          break;
                   9952:        }
                   9953:       }
                   9954:       if(match == 0){
1.310     brouard  9955:        printf("Error in result line: V%d is missing in result: %s according to model=%s\n",k1, resultline, model);
                   9956:        fprintf(ficlog,"Error in result line: V%d is missing in result: %s according to model=%s\n",k1, resultline, model);
                   9957:        return 1;
1.234     brouard  9958:       }
                   9959:     }
                   9960:   }
1.235     brouard  9961:   /* Checking for missing or useless values in comparison of current model needs */
1.318     brouard  9962:   for(k2=1; k2 <=j;k2++){ /* Loop on resultline variables: result line V4=1 V5=24.1 V3=1  V2=8 V1=0 */
1.234     brouard  9963:     match=0;
1.318     brouard  9964:     for(k1=1; k1<= cptcovt ;k1++){ /* loop on model: model line V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
1.235     brouard  9965:       if(Typevar[k1]==0){ /* Single */
1.237     brouard  9966:        if(Tvar[k1]==Tvarsel[k2]) { /* Tvar[2]=4 == Tvarsel[1]=4   */
1.318     brouard  9967:          resultmodel[k1]=k2;  /* k2th variable of the model corresponds to k1 variable of the model. resultmodel[2]=1 resultmodel[1]=2  resultmodel[3]=3  resultmodel[6]=4 resultmodel[9]=5 */
1.234     brouard  9968:          ++match;
                   9969:        }
                   9970:       }
                   9971:     }
                   9972:     if(match == 0){
                   9973:       printf("Error in result line: %d value missing; result: %s, model=%s\n",k1, resultline, model);
1.310     brouard  9974:       fprintf(ficlog,"Error in result line: %d value missing; result: %s, model=%s\n",k1, resultline, model);
                   9975:       return 1;
1.234     brouard  9976:     }else if(match > 1){
                   9977:       printf("Error in result line: %d doubled; result: %s, model=%s\n",k2, resultline, model);
1.310     brouard  9978:       fprintf(ficlog,"Error in result line: %d doubled; result: %s, model=%s\n",k2, resultline, model);
                   9979:       return 1;
1.234     brouard  9980:     }
                   9981:   }
1.235     brouard  9982:       
1.234     brouard  9983:   /* We need to deduce which combination number is chosen and save quantitative values */
1.235     brouard  9984:   /* model line V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
                   9985:   /* result line V4=1 V5=25.1 V3=0  V2=8 V1=1 */
                   9986:   /* should give a combination of dummy V4=1, V3=0, V1=1 => V4*2**(0) + V3*2**(1) + V1*2**(2) = 5 + (1offset) = 6*/
                   9987:   /* result line V4=1 V5=24.1 V3=1  V2=8 V1=0 */
                   9988:   /* should give a combination of dummy V4=1, V3=1, V1=0 => V4*2**(0) + V3*2**(1) + V1*2**(2) = 3 + (1offset) = 4*/
                   9989:   /*    1 0 0 0 */
                   9990:   /*    2 1 0 0 */
                   9991:   /*    3 0 1 0 */ 
                   9992:   /*    4 1 1 0 */ /* V4=1, V3=1, V1=0 */
                   9993:   /*    5 0 0 1 */
                   9994:   /*    6 1 0 1 */ /* V4=1, V3=0, V1=1 */
                   9995:   /*    7 0 1 1 */
                   9996:   /*    8 1 1 1 */
1.237     brouard  9997:   /* V(Tvresult)=Tresult V4=1 V3=0 V1=1 Tresult[nres=1][2]=0 */
                   9998:   /* V(Tvqresult)=Tqresult V5=25.1 V2=8 Tqresult[nres=1][1]=25.1 */
                   9999:   /* V5*age V5 known which value for nres?  */
                   10000:   /* Tqinvresult[2]=8 Tqinvresult[1]=25.1  */
1.318     brouard  10001:   for(k1=1, k=0, k4=0, k4q=0; k1 <=cptcovt;k1++){ /* loop on model line */
1.235     brouard  10002:     if( Dummy[k1]==0 && Typevar[k1]==0 ){ /* Single dummy */
1.237     brouard  10003:       k3= resultmodel[k1]; /* resultmodel[2(V4)] = 1=k3 */
1.235     brouard  10004:       k2=(int)Tvarsel[k3]; /*  Tvarsel[resultmodel[2]]= Tvarsel[1] = 4=k2 */
                   10005:       k+=Tvalsel[k3]*pow(2,k4);  /*  Tvalsel[1]=1  */
1.237     brouard  10006:       Tresult[nres][k4+1]=Tvalsel[k3];/* Tresult[nres][1]=1(V4=1)  Tresult[nres][2]=0(V3=0) */
                   10007:       Tvresult[nres][k4+1]=(int)Tvarsel[k3];/* Tvresult[nres][1]=4 Tvresult[nres][3]=1 */
                   10008:       Tinvresult[nres][(int)Tvarsel[k3]]=Tvalsel[k3]; /* Tinvresult[nres][4]=1 */
1.235     brouard  10009:       printf("Decoderesult Dummy k=%d, V(k2=V%d)= Tvalsel[%d]=%d, 2**(%d)\n",k, k2, k3, (int)Tvalsel[k3], k4);
                   10010:       k4++;;
                   10011:     }  else if( Dummy[k1]==1 && Typevar[k1]==0 ){ /* Single quantitative */
1.318     brouard  10012:       k3q= resultmodel[k1]; /* resultmodel[1(V5)] = 25.1=k3q */
                   10013:       k2q=(int)Tvarsel[k3q]; /*  Tvarsel[resultmodel[1]]= Tvarsel[1] = 4=k2 */
1.237     brouard  10014:       Tqresult[nres][k4q+1]=Tvalsel[k3q]; /* Tqresult[nres][1]=25.1 */
                   10015:       Tvqresult[nres][k4q+1]=(int)Tvarsel[k3q]; /* Tvqresult[nres][1]=5 */
                   10016:       Tqinvresult[nres][(int)Tvarsel[k3q]]=Tvalsel[k3q]; /* Tqinvresult[nres][5]=25.1 */
1.235     brouard  10017:       printf("Decoderesult Quantitative nres=%d, V(k2q=V%d)= Tvalsel[%d]=%d, Tvarsel[%d]=%f\n",nres, k2q, k3q, Tvarsel[k3q], k3q, Tvalsel[k3q]);
                   10018:       k4q++;;
                   10019:     }
                   10020:   }
1.234     brouard  10021:   
1.235     brouard  10022:   TKresult[nres]=++k; /* Combination for the nresult and the model */
1.230     brouard  10023:   return (0);
                   10024: }
1.235     brouard  10025: 
1.230     brouard  10026: int decodemodel( char model[], int lastobs)
                   10027:  /**< This routine decodes the model and returns:
1.224     brouard  10028:        * Model  V1+V2+V3+V8+V7*V8+V5*V6+V8*age+V3*age+age*age
                   10029:        * - nagesqr = 1 if age*age in the model, otherwise 0.
                   10030:        * - cptcovt total number of covariates of the model nbocc(+)+1 = 8 excepting constant and age and age*age
                   10031:        * - cptcovn or number of covariates k of the models excluding age*products =6 and age*age
                   10032:        * - cptcovage number of covariates with age*products =2
                   10033:        * - cptcovs number of simple covariates
                   10034:        * - 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
                   10035:        *     which is a new column after the 9 (ncovcol) variables. 
1.319     brouard  10036:        * - if k is a product Vn*Vm, covar[k][i] is filled with correct values for each individual
1.224     brouard  10037:        * - Tprod[l] gives the kth covariates of the product Vn*Vm l=1 to cptcovprod-cptcovage
                   10038:        *    Tprod[1]@2 {5, 6}: position of first product V7*V8 is 5, and second V5*V6 is 6.
                   10039:        * - Tvard[k]  p Tvard[1][1]@4 {7, 8, 5, 6} for V7*V8 and V5*V6 .
                   10040:        */
1.319     brouard  10041: /* V2+V1+V4+V3*age Tvar[4]=3 ; V1+V2*age Tvar[2]=2; V1+V1*age Tvar[2]=1, Tage[1]=2 */
1.136     brouard  10042: {
1.238     brouard  10043:   int i, j, k, ks, v;
1.227     brouard  10044:   int  j1, k1, k2, k3, k4;
1.136     brouard  10045:   char modelsav[80];
1.145     brouard  10046:   char stra[80], strb[80], strc[80], strd[80],stre[80];
1.187     brouard  10047:   char *strpt;
1.136     brouard  10048: 
1.145     brouard  10049:   /*removespace(model);*/
1.136     brouard  10050:   if (strlen(model) >1){ /* If there is at least 1 covariate */
1.145     brouard  10051:     j=0, j1=0, k1=0, k2=-1, ks=0, cptcovn=0;
1.137     brouard  10052:     if (strstr(model,"AGE") !=0){
1.192     brouard  10053:       printf("Error. AGE must be in lower case 'age' model=1+age+%s. ",model);
                   10054:       fprintf(ficlog,"Error. AGE must be in lower case model=1+age+%s. ",model);fflush(ficlog);
1.136     brouard  10055:       return 1;
                   10056:     }
1.141     brouard  10057:     if (strstr(model,"v") !=0){
                   10058:       printf("Error. 'v' must be in upper case 'V' model=%s ",model);
                   10059:       fprintf(ficlog,"Error. 'v' must be in upper case model=%s ",model);fflush(ficlog);
                   10060:       return 1;
                   10061:     }
1.187     brouard  10062:     strcpy(modelsav,model); 
                   10063:     if ((strpt=strstr(model,"age*age")) !=0){
                   10064:       printf(" strpt=%s, model=%s\n",strpt, model);
                   10065:       if(strpt != model){
1.234     brouard  10066:        printf("Error in model: 'model=%s'; 'age*age' should in first place before other covariates\n \
1.192     brouard  10067:  'model=1+age+age*age+V1.' or 'model=1+age+age*age+V1+V1*age.', please swap as well as \n \
1.187     brouard  10068:  corresponding column of parameters.\n",model);
1.234     brouard  10069:        fprintf(ficlog,"Error in model: 'model=%s'; 'age*age' should in first place before other covariates\n \
1.192     brouard  10070:  'model=1+age+age*age+V1.' or 'model=1+age+age*age+V1+V1*age.', please swap as well as \n \
1.187     brouard  10071:  corresponding column of parameters.\n",model); fflush(ficlog);
1.234     brouard  10072:        return 1;
1.225     brouard  10073:       }
1.187     brouard  10074:       nagesqr=1;
                   10075:       if (strstr(model,"+age*age") !=0)
1.234     brouard  10076:        substrchaine(modelsav, model, "+age*age");
1.187     brouard  10077:       else if (strstr(model,"age*age+") !=0)
1.234     brouard  10078:        substrchaine(modelsav, model, "age*age+");
1.187     brouard  10079:       else 
1.234     brouard  10080:        substrchaine(modelsav, model, "age*age");
1.187     brouard  10081:     }else
                   10082:       nagesqr=0;
                   10083:     if (strlen(modelsav) >1){
                   10084:       j=nbocc(modelsav,'+'); /**< j=Number of '+' */
                   10085:       j1=nbocc(modelsav,'*'); /**< j1=Number of '*' */
1.224     brouard  10086:       cptcovs=j+1-j1; /**<  Number of simple covariates V1+V1*age+V3 +V3*V4+age*age=> V1 + V3 =5-3=2  */
1.187     brouard  10087:       cptcovt= j+1; /* Number of total covariates in the model, not including
1.225     brouard  10088:                     * cst, age and age*age 
                   10089:                     * V1+V1*age+ V3 + V3*V4+age*age=> 3+1=4*/
                   10090:       /* including age products which are counted in cptcovage.
                   10091:        * but the covariates which are products must be treated 
                   10092:        * separately: ncovn=4- 2=2 (V1+V3). */
1.187     brouard  10093:       cptcovprod=j1; /**< Number of products  V1*V2 +v3*age = 2 */
                   10094:       cptcovprodnoage=0; /**< Number of covariate products without age: V3*V4 =1  */
1.225     brouard  10095:       
                   10096:       
1.187     brouard  10097:       /*   Design
                   10098:        *  V1   V2   V3   V4  V5  V6  V7  V8  V9 Weight
                   10099:        *  <          ncovcol=8                >
                   10100:        * Model V2 + V1 + V3*age + V3 + V5*V6 + V7*V8 + V8*age + V8
                   10101:        *   k=  1    2      3       4     5       6      7        8
                   10102:        *  cptcovn number of covariates (not including constant and age ) = # of + plus 1 = 7+1=8
                   10103:        *  covar[k,i], value of kth covariate if not including age for individual i:
1.224     brouard  10104:        *       covar[1][i]= (V1), covar[4][i]=(V4), covar[8][i]=(V8)
                   10105:        *  Tvar[k] # of the kth covariate:  Tvar[1]=2  Tvar[2]=1 Tvar[4]=3 Tvar[8]=8
1.187     brouard  10106:        *       if multiplied by age: V3*age Tvar[3=V3*age]=3 (V3) Tvar[7]=8 and 
                   10107:        *  Tage[++cptcovage]=k
                   10108:        *       if products, new covar are created after ncovcol with k1
                   10109:        *  Tvar[k]=ncovcol+k1; # of the kth covariate product:  Tvar[5]=ncovcol+1=10  Tvar[6]=ncovcol+1=11
                   10110:        *  Tprod[k1]=k; Tprod[1]=5 Tprod[2]= 6; gives the position of the k1th product
                   10111:        *  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
                   10112:        *  Tvar[cptcovn+k2]=Tvard[k1][1];Tvar[cptcovn+k2+1]=Tvard[k1][2];
                   10113:        *  Tvar[8+1]=5;Tvar[8+2]=6;Tvar[8+3]=7;Tvar[8+4]=8 inverted
                   10114:        *  V1   V2   V3   V4  V5  V6  V7  V8  V9  V10  V11
                   10115:        *  <          ncovcol=8                >
                   10116:        *       Model V2 + V1 + V3*age + V3 + V5*V6 + V7*V8 + V8*age + V8    d1   d1   d2  d2
                   10117:        *          k=  1    2      3       4     5       6      7        8    9   10   11  12
                   10118:        *     Tvar[k]= 2    1      3       3    10      11      8        8    5    6    7   8
1.319     brouard  10119:        * p Tvar[1]@12={2,   1,     3,      3,  11,     10,     8,       8,   7,   8,   5,  6}
1.187     brouard  10120:        * p Tprod[1]@2={                         6, 5}
                   10121:        *p Tvard[1][1]@4= {7, 8, 5, 6}
                   10122:        * covar[k][i]= V2   V1      ?      V3    V5*V6?   V7*V8?  ?       V8   
                   10123:        *  cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];
1.319     brouard  10124:        *How to reorganize? Tvars(orted)
1.187     brouard  10125:        * Model V1 + V2 + V3 + V8 + V5*V6 + V7*V8 + V3*age + V8*age
                   10126:        * Tvars {2,   1,     3,      3,   11,     10,     8,       8,   7,   8,   5,  6}
                   10127:        *       {2,   1,     4,      8,    5,      6,     3,       7}
                   10128:        * Struct []
                   10129:        */
1.225     brouard  10130:       
1.187     brouard  10131:       /* This loop fills the array Tvar from the string 'model'.*/
                   10132:       /* j is the number of + signs in the model V1+V2+V3 j=2 i=3 to 1 */
                   10133:       /*   modelsav=V2+V1+V4+age*V3 strb=age*V3 stra=V2+V1+V4  */
                   10134:       /*       k=4 (age*V3) Tvar[k=4]= 3 (from V3) Tage[cptcovage=1]=4 */
                   10135:       /*       k=3 V4 Tvar[k=3]= 4 (from V4) */
                   10136:       /*       k=2 V1 Tvar[k=2]= 1 (from V1) */
                   10137:       /*       k=1 Tvar[1]=2 (from V2) */
                   10138:       /*       k=5 Tvar[5] */
                   10139:       /* for (k=1; k<=cptcovn;k++) { */
1.198     brouard  10140:       /*       cov[2+k]=nbcode[Tvar[k]][codtabm(ij,Tvar[k])]; */
1.187     brouard  10141:       /*       } */
1.198     brouard  10142:       /* for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,Tvar[Tage[k])]]*cov[2]; */
1.187     brouard  10143:       /*
                   10144:        * Treating invertedly V2+V1+V3*age+V2*V4 is as if written V2*V4 +V3*age + V1 + V2 */
1.227     brouard  10145:       for(k=cptcovt; k>=1;k--){ /**< Number of covariates not including constant and age, neither age*age*/
                   10146:         Tvar[k]=0; Tprod[k]=0; Tposprod[k]=0;
                   10147:       }
1.187     brouard  10148:       cptcovage=0;
1.319     brouard  10149:       for(k=1; k<=cptcovt;k++){ /* Loop on total covariates of the model line */
                   10150:        cutl(stra,strb,modelsav,'+'); /* keeps in strb after the first '+' cutl from left to right
                   10151:                                         modelsav==V2+V1+V5*age+V4+V3*age strb=V3*age stra=V2+V1V5*age+V4 */    /* <model> "V5+V4+V3+V4*V3+V5*age+V1*age+V1" strb="V5" stra="V4+V3+V4*V3+V5*age+V1*age+V1" */
                   10152:        if (nbocc(modelsav,'+')==0)
                   10153:          strcpy(strb,modelsav); /* and analyzes it */
1.234     brouard  10154:        /*      printf("i=%d a=%s b=%s sav=%s\n",i, stra,strb,modelsav);*/
                   10155:        /*scanf("%d",i);*/
1.319     brouard  10156:        if (strchr(strb,'*')) {  /**< Model includes a product V2+V1+V5*age+ V4+V3*age strb=V3*age */
                   10157:          cutl(strc,strd,strb,'*'); /**< k=1 strd*strc  Vm*Vn: strb=V3*age(input) strc=age strd=V3 ; V3*V2 strc=V2, strd=V3 */
1.234     brouard  10158:          if (strcmp(strc,"age")==0) { /**< Model includes age: Vn*age */
                   10159:            /* covar is not filled and then is empty */
                   10160:            cptcovprod--;
                   10161:            cutl(stre,strb,strd,'V'); /* strd=V3(input): stre="3" */
1.319     brouard  10162:            Tvar[k]=atoi(stre);  /* V2+V1+V5*age+V4+V3*age Tvar[5]=3 ; V1+V2*age Tvar[2]=2; V1+V1*age Tvar[2]=1 */
1.234     brouard  10163:            Typevar[k]=1;  /* 1 for age product */
1.319     brouard  10164:            cptcovage++; /* Counts the number of covariates which include age as a product */
                   10165:            Tage[cptcovage]=k;  /*  V2+V1+V4+V3*age Tvar[4]=3, Tage[1] = 4 or V1+V1*age Tvar[2]=1, Tage[1]=2 */
1.234     brouard  10166:            /*printf("stre=%s ", stre);*/
                   10167:          } else if (strcmp(strd,"age")==0) { /* or age*Vn */
                   10168:            cptcovprod--;
                   10169:            cutl(stre,strb,strc,'V');
                   10170:            Tvar[k]=atoi(stre);
                   10171:            Typevar[k]=1;  /* 1 for age product */
                   10172:            cptcovage++;
                   10173:            Tage[cptcovage]=k;
                   10174:          } else {  /* Age is not in the model product V2+V1+V1*V4+V3*age+V3*V2  strb=V3*V2*/
                   10175:            /* loops on k1=1 (V3*V2) and k1=2 V4*V3 */
                   10176:            cptcovn++;
                   10177:            cptcovprodnoage++;k1++;
                   10178:            cutl(stre,strb,strc,'V'); /* strc= Vn, stre is n; strb=V3*V2 stre=3 strc=*/
                   10179:            Tvar[k]=ncovcol+nqv+ntv+nqtv+k1; /* For model-covariate k tells which data-covariate to use but
                   10180:                                                because this model-covariate is a construction we invent a new column
                   10181:                                                which is after existing variables ncovcol+nqv+ntv+nqtv + k1
1.319     brouard  10182:                                                If already ncovcol=4 and model=V2 + V1 +V1*V4 +age*V3 +V3*V2
                   10183:                                                thus after V4 we invent V5 and V6 because age*V3 will be computed in 4
                   10184:                                                Tvar[3=V1*V4]=4+1=5 Tvar[5=V3*V2]=4 + 2= 6, Tvar[4=age*V3]=4 etc */
1.234     brouard  10185:            Typevar[k]=2;  /* 2 for double fixed dummy covariates */
                   10186:            cutl(strc,strb,strd,'V'); /* strd was Vm, strc is m */
                   10187:            Tprod[k1]=k;  /* Tprod[1]=3(=V1*V4) for V2+V1+V1*V4+age*V3+V3*V2  */
1.319     brouard  10188:            Tposprod[k]=k1; /* Tposprod[3]=1, Tposprod[2]=5 */
1.234     brouard  10189:            Tvard[k1][1] =atoi(strc); /* m 1 for V1*/
                   10190:            Tvard[k1][2] =atoi(stre); /* n 4 for V4*/
                   10191:            k2=k2+2;  /* k2 is initialize to -1, We want to store the n and m in Vn*Vm at the end of Tvar */
                   10192:            /* Tvar[cptcovt+k2]=Tvard[k1][1]; /\* Tvar[(cptcovt=4+k2=1)=5]= 1 (V1) *\/ */
                   10193:            /* Tvar[cptcovt+k2+1]=Tvard[k1][2];  /\* Tvar[(cptcovt=4+(k2=1)+1)=6]= 4 (V4) *\/ */
1.225     brouard  10194:             /*ncovcol=4 and model=V2+V1+V1*V4+age*V3+V3*V2, Tvar[3]=5, Tvar[4]=6, cptcovt=5 */
1.234     brouard  10195:            /*                     1  2   3      4     5 | Tvar[5+1)=1, Tvar[7]=2   */
                   10196:            for (i=1; i<=lastobs;i++){
                   10197:              /* Computes the new covariate which is a product of
                   10198:                 covar[n][i]* covar[m][i] and stores it at ncovol+k1 May not be defined */
                   10199:              covar[ncovcol+k1][i]=covar[atoi(stre)][i]*covar[atoi(strc)][i];
                   10200:            }
                   10201:          } /* End age is not in the model */
                   10202:        } /* End if model includes a product */
1.319     brouard  10203:        else { /* not a product */
1.234     brouard  10204:          /*printf("d=%s c=%s b=%s\n", strd,strc,strb);*/
                   10205:          /*  scanf("%d",i);*/
                   10206:          cutl(strd,strc,strb,'V');
                   10207:          ks++; /**< Number of simple covariates dummy or quantitative, fixe or varying */
                   10208:          cptcovn++; /** V4+V3+V5: V4 and V3 timevarying dummy covariates, V5 timevarying quantitative */
                   10209:          Tvar[k]=atoi(strd);
                   10210:          Typevar[k]=0;  /* 0 for simple covariates */
                   10211:        }
                   10212:        strcpy(modelsav,stra);  /* modelsav=V2+V1+V4 stra=V2+V1+V4 */ 
1.223     brouard  10213:                                /*printf("a=%s b=%s sav=%s\n", stra,strb,modelsav);
1.225     brouard  10214:                                  scanf("%d",i);*/
1.187     brouard  10215:       } /* end of loop + on total covariates */
                   10216:     } /* end if strlen(modelsave == 0) age*age might exist */
                   10217:   } /* end if strlen(model == 0) */
1.136     brouard  10218:   
                   10219:   /*The number n of Vn is stored in Tvar. cptcovage =number of age covariate. Tage gives the position of age. cptcovprod= number of products.
                   10220:     If model=V1+V1*age then Tvar[1]=1 Tvar[2]=1 cptcovage=1 Tage[1]=2 cptcovprod=0*/
1.225     brouard  10221:   
1.136     brouard  10222:   /* printf("tvar1=%d tvar2=%d tvar3=%d cptcovage=%d Tage=%d",Tvar[1],Tvar[2],Tvar[3],cptcovage,Tage[1]);
1.225     brouard  10223:      printf("cptcovprod=%d ", cptcovprod);
                   10224:      fprintf(ficlog,"cptcovprod=%d ", cptcovprod);
                   10225:      scanf("%d ",i);*/
                   10226: 
                   10227: 
1.230     brouard  10228: /* Until here, decodemodel knows only the grammar (simple, product, age*) of the model but not what kind
                   10229:    of variable (dummy vs quantitative, fixed vs time varying) is behind. But we know the # of each. */
1.226     brouard  10230: /* ncovcol= 1, nqv=1 | ntv=2, nqtv= 1  = 5 possible variables data: 2 fixed 3, varying
                   10231:    model=        V5 + V4 +V3 + V4*V3 + V5*age + V2 + V1*V2 + V1*age + V5*age, V1 is not used saving its place
                   10232:    k =           1    2   3     4       5       6      7      8        9
                   10233:    Tvar[k]=      5    4   3 1+1+2+1+1=6 5       2      7      1        5
1.319     brouard  10234:    Typevar[k]=   0    0   0     2       1       0      2      1        0
1.227     brouard  10235:    Fixed[k]      1    1   1     1       3       0    0 or 2   2        3
                   10236:    Dummy[k]      1    0   0     0       3       1      1      2        3
                   10237:          Tmodelind[combination of covar]=k;
1.225     brouard  10238: */  
                   10239: /* Dispatching between quantitative and time varying covariates */
1.226     brouard  10240:   /* If Tvar[k] >ncovcol it is a product */
1.225     brouard  10241:   /* 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  10242:        /* Computing effective variables, ie used by the model, that is from the cptcovt variables */
1.318     brouard  10243:   printf("Model=1+age+%s\n\
1.227     brouard  10244: Typevar: 0 for simple covariate (dummy, quantitative, fixed or varying), 1 for age product, 2 for  product \n\
                   10245: Fixed[k] 0=fixed (product or simple), 1 varying, 2 fixed with age product, 3 varying with age product \n\
                   10246: 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.318     brouard  10247:   fprintf(ficlog,"Model=1+age+%s\n\
1.227     brouard  10248: Typevar: 0 for simple covariate (dummy, quantitative, fixed or varying), 1 for age product, 2 for  product \n\
                   10249: Fixed[k] 0=fixed (product or simple), 1 varying, 2 fixed with age product, 3 varying with age product \n\
                   10250: 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  10251:   for(k=-1;k<=cptcovt; k++){ Fixed[k]=0; Dummy[k]=0;}
1.234     brouard  10252:   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 */
                   10253:     if (Tvar[k] <=ncovcol && Typevar[k]==0 ){ /* Simple fixed dummy (<=ncovcol) covariates */
1.227     brouard  10254:       Fixed[k]= 0;
                   10255:       Dummy[k]= 0;
1.225     brouard  10256:       ncoveff++;
1.232     brouard  10257:       ncovf++;
1.234     brouard  10258:       nsd++;
                   10259:       modell[k].maintype= FTYPE;
                   10260:       TvarsD[nsd]=Tvar[k];
                   10261:       TvarsDind[nsd]=k;
                   10262:       TvarF[ncovf]=Tvar[k];
                   10263:       TvarFind[ncovf]=k;
                   10264:       TvarFD[ncoveff]=Tvar[k]; /* TvarFD[1]=V1 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
                   10265:       TvarFDind[ncoveff]=k; /* TvarFDind[1]=9 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
                   10266:     }else if( Tvar[k] <=ncovcol &&  Typevar[k]==2){ /* Product of fixed dummy (<=ncovcol) covariates */
                   10267:       Fixed[k]= 0;
                   10268:       Dummy[k]= 0;
                   10269:       ncoveff++;
                   10270:       ncovf++;
                   10271:       modell[k].maintype= FTYPE;
                   10272:       TvarF[ncovf]=Tvar[k];
                   10273:       TvarFind[ncovf]=k;
1.230     brouard  10274:       TvarFD[ncoveff]=Tvar[k]; /* TvarFD[1]=V1 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
1.231     brouard  10275:       TvarFDind[ncoveff]=k; /* TvarFDind[1]=9 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
1.240     brouard  10276:     }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  10277:       Fixed[k]= 0;
                   10278:       Dummy[k]= 1;
1.230     brouard  10279:       nqfveff++;
1.234     brouard  10280:       modell[k].maintype= FTYPE;
                   10281:       modell[k].subtype= FQ;
                   10282:       nsq++;
                   10283:       TvarsQ[nsq]=Tvar[k];
                   10284:       TvarsQind[nsq]=k;
1.232     brouard  10285:       ncovf++;
1.234     brouard  10286:       TvarF[ncovf]=Tvar[k];
                   10287:       TvarFind[ncovf]=k;
1.231     brouard  10288:       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  10289:       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  10290:     }else if( Tvar[k] <=ncovcol+nqv+ntv && Typevar[k]==0){/* Only simple time varying dummy variables */
1.227     brouard  10291:       Fixed[k]= 1;
                   10292:       Dummy[k]= 0;
1.225     brouard  10293:       ntveff++; /* Only simple time varying dummy variable */
1.234     brouard  10294:       modell[k].maintype= VTYPE;
                   10295:       modell[k].subtype= VD;
                   10296:       nsd++;
                   10297:       TvarsD[nsd]=Tvar[k];
                   10298:       TvarsDind[nsd]=k;
                   10299:       ncovv++; /* Only simple time varying variables */
                   10300:       TvarV[ncovv]=Tvar[k];
1.242     brouard  10301:       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  10302:       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 */
                   10303:       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  10304:       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);
                   10305:       printf("Quasi TmodelInvind[%d]=%d\n",k,Tvar[k]- ncovcol-nqv);
1.231     brouard  10306:     }else if( Tvar[k] <=ncovcol+nqv+ntv+nqtv  && Typevar[k]==0){ /* Only simple time varying quantitative variable V5*/
1.234     brouard  10307:       Fixed[k]= 1;
                   10308:       Dummy[k]= 1;
                   10309:       nqtveff++;
                   10310:       modell[k].maintype= VTYPE;
                   10311:       modell[k].subtype= VQ;
                   10312:       ncovv++; /* Only simple time varying variables */
                   10313:       nsq++;
1.319     brouard  10314:       TvarsQ[nsq]=Tvar[k]; /* k=1 Tvar=5 nsq=1 TvarsQ[1]=5 */
1.234     brouard  10315:       TvarsQind[nsq]=k;
                   10316:       TvarV[ncovv]=Tvar[k];
1.242     brouard  10317:       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  10318:       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 */
                   10319:       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  10320:       TmodelInvQind[nqtveff]=Tvar[k]- ncovcol-nqv-ntv;/* Only simple time varying quantitative variable */
                   10321:       /* Tmodeliqind[k]=nqtveff;/\* Only simple time varying quantitative variable *\/ */
                   10322:       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  10323:       printf("Quasi TmodelInvQind[%d]=%d\n",k,Tvar[k]- ncovcol-nqv-ntv);
1.227     brouard  10324:     }else if (Typevar[k] == 1) {  /* product with age */
1.234     brouard  10325:       ncova++;
                   10326:       TvarA[ncova]=Tvar[k];
                   10327:       TvarAind[ncova]=k;
1.231     brouard  10328:       if (Tvar[k] <=ncovcol ){ /* Product age with fixed dummy covariatee */
1.240     brouard  10329:        Fixed[k]= 2;
                   10330:        Dummy[k]= 2;
                   10331:        modell[k].maintype= ATYPE;
                   10332:        modell[k].subtype= APFD;
                   10333:        /* ncoveff++; */
1.227     brouard  10334:       }else if( Tvar[k] <=ncovcol+nqv) { /* Remind that product Vn*Vm are added in k*/
1.240     brouard  10335:        Fixed[k]= 2;
                   10336:        Dummy[k]= 3;
                   10337:        modell[k].maintype= ATYPE;
                   10338:        modell[k].subtype= APFQ;                /*      Product age * fixed quantitative */
                   10339:        /* nqfveff++;  /\* Only simple fixed quantitative variable *\/ */
1.227     brouard  10340:       }else if( Tvar[k] <=ncovcol+nqv+ntv ){
1.240     brouard  10341:        Fixed[k]= 3;
                   10342:        Dummy[k]= 2;
                   10343:        modell[k].maintype= ATYPE;
                   10344:        modell[k].subtype= APVD;                /*      Product age * varying dummy */
                   10345:        /* ntveff++; /\* Only simple time varying dummy variable *\/ */
1.227     brouard  10346:       }else if( Tvar[k] <=ncovcol+nqv+ntv+nqtv){
1.240     brouard  10347:        Fixed[k]= 3;
                   10348:        Dummy[k]= 3;
                   10349:        modell[k].maintype= ATYPE;
                   10350:        modell[k].subtype= APVQ;                /*      Product age * varying quantitative */
                   10351:        /* nqtveff++;/\* Only simple time varying quantitative variable *\/ */
1.227     brouard  10352:       }
                   10353:     }else if (Typevar[k] == 2) {  /* product without age */
                   10354:       k1=Tposprod[k];
                   10355:       if(Tvard[k1][1] <=ncovcol){
1.240     brouard  10356:        if(Tvard[k1][2] <=ncovcol){
                   10357:          Fixed[k]= 1;
                   10358:          Dummy[k]= 0;
                   10359:          modell[k].maintype= FTYPE;
                   10360:          modell[k].subtype= FPDD;              /*      Product fixed dummy * fixed dummy */
                   10361:          ncovf++; /* Fixed variables without age */
                   10362:          TvarF[ncovf]=Tvar[k];
                   10363:          TvarFind[ncovf]=k;
                   10364:        }else if(Tvard[k1][2] <=ncovcol+nqv){
                   10365:          Fixed[k]= 0;  /* or 2 ?*/
                   10366:          Dummy[k]= 1;
                   10367:          modell[k].maintype= FTYPE;
                   10368:          modell[k].subtype= FPDQ;              /*      Product fixed dummy * fixed quantitative */
                   10369:          ncovf++; /* Varying variables without age */
                   10370:          TvarF[ncovf]=Tvar[k];
                   10371:          TvarFind[ncovf]=k;
                   10372:        }else if(Tvard[k1][2] <=ncovcol+nqv+ntv){
                   10373:          Fixed[k]= 1;
                   10374:          Dummy[k]= 0;
                   10375:          modell[k].maintype= VTYPE;
                   10376:          modell[k].subtype= VPDD;              /*      Product fixed dummy * varying dummy */
                   10377:          ncovv++; /* Varying variables without age */
                   10378:          TvarV[ncovv]=Tvar[k];
                   10379:          TvarVind[ncovv]=k;
                   10380:        }else if(Tvard[k1][2] <=ncovcol+nqv+ntv+nqtv){
                   10381:          Fixed[k]= 1;
                   10382:          Dummy[k]= 1;
                   10383:          modell[k].maintype= VTYPE;
                   10384:          modell[k].subtype= VPDQ;              /*      Product fixed dummy * varying quantitative */
                   10385:          ncovv++; /* Varying variables without age */
                   10386:          TvarV[ncovv]=Tvar[k];
                   10387:          TvarVind[ncovv]=k;
                   10388:        }
1.227     brouard  10389:       }else if(Tvard[k1][1] <=ncovcol+nqv){
1.240     brouard  10390:        if(Tvard[k1][2] <=ncovcol){
                   10391:          Fixed[k]= 0;  /* or 2 ?*/
                   10392:          Dummy[k]= 1;
                   10393:          modell[k].maintype= FTYPE;
                   10394:          modell[k].subtype= FPDQ;              /*      Product fixed quantitative * fixed dummy */
                   10395:          ncovf++; /* Fixed variables without age */
                   10396:          TvarF[ncovf]=Tvar[k];
                   10397:          TvarFind[ncovf]=k;
                   10398:        }else if(Tvard[k1][2] <=ncovcol+nqv+ntv){
                   10399:          Fixed[k]= 1;
                   10400:          Dummy[k]= 1;
                   10401:          modell[k].maintype= VTYPE;
                   10402:          modell[k].subtype= VPDQ;              /*      Product fixed quantitative * varying dummy */
                   10403:          ncovv++; /* Varying variables without age */
                   10404:          TvarV[ncovv]=Tvar[k];
                   10405:          TvarVind[ncovv]=k;
                   10406:        }else if(Tvard[k1][2] <=ncovcol+nqv+ntv+nqtv){
                   10407:          Fixed[k]= 1;
                   10408:          Dummy[k]= 1;
                   10409:          modell[k].maintype= VTYPE;
                   10410:          modell[k].subtype= VPQQ;              /*      Product fixed quantitative * varying quantitative */
                   10411:          ncovv++; /* Varying variables without age */
                   10412:          TvarV[ncovv]=Tvar[k];
                   10413:          TvarVind[ncovv]=k;
                   10414:          ncovv++; /* Varying variables without age */
                   10415:          TvarV[ncovv]=Tvar[k];
                   10416:          TvarVind[ncovv]=k;
                   10417:        }
1.227     brouard  10418:       }else if(Tvard[k1][1] <=ncovcol+nqv+ntv){
1.240     brouard  10419:        if(Tvard[k1][2] <=ncovcol){
                   10420:          Fixed[k]= 1;
                   10421:          Dummy[k]= 1;
                   10422:          modell[k].maintype= VTYPE;
                   10423:          modell[k].subtype= VPDD;              /*      Product time varying dummy * fixed dummy */
                   10424:          ncovv++; /* Varying variables without age */
                   10425:          TvarV[ncovv]=Tvar[k];
                   10426:          TvarVind[ncovv]=k;
                   10427:        }else if(Tvard[k1][2] <=ncovcol+nqv){
                   10428:          Fixed[k]= 1;
                   10429:          Dummy[k]= 1;
                   10430:          modell[k].maintype= VTYPE;
                   10431:          modell[k].subtype= VPDQ;              /*      Product time varying dummy * fixed quantitative */
                   10432:          ncovv++; /* Varying variables without age */
                   10433:          TvarV[ncovv]=Tvar[k];
                   10434:          TvarVind[ncovv]=k;
                   10435:        }else if(Tvard[k1][2] <=ncovcol+nqv+ntv){
                   10436:          Fixed[k]= 1;
                   10437:          Dummy[k]= 0;
                   10438:          modell[k].maintype= VTYPE;
                   10439:          modell[k].subtype= VPDD;              /*      Product time varying dummy * time varying dummy */
                   10440:          ncovv++; /* Varying variables without age */
                   10441:          TvarV[ncovv]=Tvar[k];
                   10442:          TvarVind[ncovv]=k;
                   10443:        }else if(Tvard[k1][2] <=ncovcol+nqv+ntv+nqtv){
                   10444:          Fixed[k]= 1;
                   10445:          Dummy[k]= 1;
                   10446:          modell[k].maintype= VTYPE;
                   10447:          modell[k].subtype= VPDQ;              /*      Product time varying dummy * time varying quantitative */
                   10448:          ncovv++; /* Varying variables without age */
                   10449:          TvarV[ncovv]=Tvar[k];
                   10450:          TvarVind[ncovv]=k;
                   10451:        }
1.227     brouard  10452:       }else if(Tvard[k1][1] <=ncovcol+nqv+ntv+nqtv){
1.240     brouard  10453:        if(Tvard[k1][2] <=ncovcol){
                   10454:          Fixed[k]= 1;
                   10455:          Dummy[k]= 1;
                   10456:          modell[k].maintype= VTYPE;
                   10457:          modell[k].subtype= VPDQ;              /*      Product time varying quantitative * fixed dummy */
                   10458:          ncovv++; /* Varying variables without age */
                   10459:          TvarV[ncovv]=Tvar[k];
                   10460:          TvarVind[ncovv]=k;
                   10461:        }else if(Tvard[k1][2] <=ncovcol+nqv){
                   10462:          Fixed[k]= 1;
                   10463:          Dummy[k]= 1;
                   10464:          modell[k].maintype= VTYPE;
                   10465:          modell[k].subtype= VPQQ;              /*      Product time varying quantitative * fixed quantitative */
                   10466:          ncovv++; /* Varying variables without age */
                   10467:          TvarV[ncovv]=Tvar[k];
                   10468:          TvarVind[ncovv]=k;
                   10469:        }else if(Tvard[k1][2] <=ncovcol+nqv+ntv){
                   10470:          Fixed[k]= 1;
                   10471:          Dummy[k]= 1;
                   10472:          modell[k].maintype= VTYPE;
                   10473:          modell[k].subtype= VPDQ;              /*      Product time varying quantitative * time varying dummy */
                   10474:          ncovv++; /* Varying variables without age */
                   10475:          TvarV[ncovv]=Tvar[k];
                   10476:          TvarVind[ncovv]=k;
                   10477:        }else if(Tvard[k1][2] <=ncovcol+nqv+ntv+nqtv){
                   10478:          Fixed[k]= 1;
                   10479:          Dummy[k]= 1;
                   10480:          modell[k].maintype= VTYPE;
                   10481:          modell[k].subtype= VPQQ;              /*      Product time varying quantitative * time varying quantitative */
                   10482:          ncovv++; /* Varying variables without age */
                   10483:          TvarV[ncovv]=Tvar[k];
                   10484:          TvarVind[ncovv]=k;
                   10485:        }
1.227     brouard  10486:       }else{
1.240     brouard  10487:        printf("Error unknown type of covariate: Tvard[%d][1]=%d,Tvard[%d][2]=%d\n",k1,Tvard[k1][1],k1,Tvard[k1][2]);
                   10488:        fprintf(ficlog,"Error unknown type of covariate: Tvard[%d][1]=%d,Tvard[%d][2]=%d\n",k1,Tvard[k1][1],k1,Tvard[k1][2]);
                   10489:       } /*end k1*/
1.225     brouard  10490:     }else{
1.226     brouard  10491:       printf("Error, current version can't treat for performance reasons, Tvar[%d]=%d, Typevar[%d]=%d\n", k, Tvar[k], k, Typevar[k]);
                   10492:       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  10493:     }
1.227     brouard  10494:     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  10495:     printf("           modell[%d].maintype=%d, modell[%d].subtype=%d\n",k,modell[k].maintype,k,modell[k].subtype);
1.227     brouard  10496:     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]);
                   10497:   }
                   10498:   /* Searching for doublons in the model */
                   10499:   for(k1=1; k1<= cptcovt;k1++){
                   10500:     for(k2=1; k2 <k1;k2++){
1.285     brouard  10501:       /* if((Typevar[k1]==Typevar[k2]) && (Fixed[Tvar[k1]]==Fixed[Tvar[k2]]) && (Dummy[Tvar[k1]]==Dummy[Tvar[k2]] )){ */
                   10502:       if((Typevar[k1]==Typevar[k2]) && (Fixed[k1]==Fixed[k2]) && (Dummy[k1]==Dummy[k2] )){
1.234     brouard  10503:        if((Typevar[k1] == 0 || Typevar[k1] == 1)){ /* Simple or age product */
                   10504:          if(Tvar[k1]==Tvar[k2]){
1.285     brouard  10505:            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]);
                   10506:            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  10507:            return(1);
                   10508:          }
                   10509:        }else if (Typevar[k1] ==2){
                   10510:          k3=Tposprod[k1];
                   10511:          k4=Tposprod[k2];
                   10512:          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])) ){
                   10513:            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]]);
                   10514:            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);
                   10515:            return(1);
                   10516:          }
                   10517:        }
1.227     brouard  10518:       }
                   10519:     }
1.225     brouard  10520:   }
                   10521:   printf("ncoveff=%d, nqfveff=%d, ntveff=%d, nqtveff=%d, cptcovn=%d\n",ncoveff,nqfveff,ntveff,nqtveff,cptcovn);
                   10522:   fprintf(ficlog,"ncoveff=%d, nqfveff=%d, ntveff=%d, nqtveff=%d, cptcovn=%d\n",ncoveff,nqfveff,ntveff,nqtveff,cptcovn);
1.234     brouard  10523:   printf("ncovf=%d, ncovv=%d, ncova=%d, nsd=%d, nsq=%d\n",ncovf,ncovv,ncova,nsd,nsq);
                   10524:   fprintf(ficlog,"ncovf=%d, ncovv=%d, ncova=%d, nsd=%d, nsq=%d\n",ncovf,ncovv,ncova,nsd, nsq);
1.137     brouard  10525:   return (0); /* with covar[new additional covariate if product] and Tage if age */ 
1.164     brouard  10526:   /*endread:*/
1.225     brouard  10527:   printf("Exiting decodemodel: ");
                   10528:   return (1);
1.136     brouard  10529: }
                   10530: 
1.169     brouard  10531: int calandcheckages(int imx, int maxwav, double *agemin, double *agemax, int *nberr, int *nbwarn )
1.248     brouard  10532: {/* Check ages at death */
1.136     brouard  10533:   int i, m;
1.218     brouard  10534:   int firstone=0;
                   10535:   
1.136     brouard  10536:   for (i=1; i<=imx; i++) {
                   10537:     for(m=2; (m<= maxwav); m++) {
                   10538:       if (((int)mint[m][i]== 99) && (s[m][i] <= nlstate)){
                   10539:        anint[m][i]=9999;
1.216     brouard  10540:        if (s[m][i] != -2) /* Keeping initial status of unknown vital status */
                   10541:          s[m][i]=-1;
1.136     brouard  10542:       }
                   10543:       if((int)moisdc[i]==99 && (int)andc[i]==9999 && s[m][i]>nlstate){
1.260     brouard  10544:        *nberr = *nberr + 1;
1.218     brouard  10545:        if(firstone == 0){
                   10546:          firstone=1;
1.260     brouard  10547:        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  10548:        }
1.262     brouard  10549:        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  10550:        s[m][i]=-1;  /* Droping the death status */
1.136     brouard  10551:       }
                   10552:       if((int)moisdc[i]==99 && (int)andc[i]!=9999 && s[m][i]>nlstate){
1.169     brouard  10553:        (*nberr)++;
1.259     brouard  10554:        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  10555:        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  10556:        s[m][i]=-2; /* We prefer to skip it (and to skip it in version 0.8a1 too */
1.136     brouard  10557:       }
                   10558:     }
                   10559:   }
                   10560: 
                   10561:   for (i=1; i<=imx; i++)  {
                   10562:     agedc[i]=(moisdc[i]/12.+andc[i])-(moisnais[i]/12.+annais[i]);
                   10563:     for(m=firstpass; (m<= lastpass); m++){
1.214     brouard  10564:       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  10565:        if (s[m][i] >= nlstate+1) {
1.169     brouard  10566:          if(agedc[i]>0){
                   10567:            if((int)moisdc[i]!=99 && (int)andc[i]!=9999){
1.136     brouard  10568:              agev[m][i]=agedc[i];
1.214     brouard  10569:              /*if(moisdc[i]==99 && andc[i]==9999) s[m][i]=-1;*/
1.169     brouard  10570:            }else {
1.136     brouard  10571:              if ((int)andc[i]!=9999){
                   10572:                nbwarn++;
                   10573:                printf("Warning negative age at death: %ld line:%d\n",num[i],i);
                   10574:                fprintf(ficlog,"Warning negative age at death: %ld line:%d\n",num[i],i);
                   10575:                agev[m][i]=-1;
                   10576:              }
                   10577:            }
1.169     brouard  10578:          } /* agedc > 0 */
1.214     brouard  10579:        } /* end if */
1.136     brouard  10580:        else if(s[m][i] !=9){ /* Standard case, age in fractional
                   10581:                                 years but with the precision of a month */
                   10582:          agev[m][i]=(mint[m][i]/12.+1./24.+anint[m][i])-(moisnais[i]/12.+1./24.+annais[i]);
                   10583:          if((int)mint[m][i]==99 || (int)anint[m][i]==9999)
                   10584:            agev[m][i]=1;
                   10585:          else if(agev[m][i] < *agemin){ 
                   10586:            *agemin=agev[m][i];
                   10587:            printf(" Min anint[%d][%d]=%.2f annais[%d]=%.2f, agemin=%.2f\n",m,i,anint[m][i], i,annais[i], *agemin);
                   10588:          }
                   10589:          else if(agev[m][i] >*agemax){
                   10590:            *agemax=agev[m][i];
1.156     brouard  10591:            /* printf(" Max anint[%d][%d]=%.0f annais[%d]=%.0f, agemax=%.2f\n",m,i,anint[m][i], i,annais[i], *agemax);*/
1.136     brouard  10592:          }
                   10593:          /*agev[m][i]=anint[m][i]-annais[i];*/
                   10594:          /*     agev[m][i] = age[i]+2*m;*/
1.214     brouard  10595:        } /* en if 9*/
1.136     brouard  10596:        else { /* =9 */
1.214     brouard  10597:          /* printf("Debug num[%d]=%ld s[%d][%d]=%d\n",i,num[i], m,i, s[m][i]); */
1.136     brouard  10598:          agev[m][i]=1;
                   10599:          s[m][i]=-1;
                   10600:        }
                   10601:       }
1.214     brouard  10602:       else if(s[m][i]==0) /*= 0 Unknown */
1.136     brouard  10603:        agev[m][i]=1;
1.214     brouard  10604:       else{
                   10605:        printf("Warning, num[%d]=%ld, s[%d][%d]=%d\n", i, num[i], m, i,s[m][i]); 
                   10606:        fprintf(ficlog, "Warning, num[%d]=%ld, s[%d][%d]=%d\n", i, num[i], m, i,s[m][i]); 
                   10607:        agev[m][i]=0;
                   10608:       }
                   10609:     } /* End for lastpass */
                   10610:   }
1.136     brouard  10611:     
                   10612:   for (i=1; i<=imx; i++)  {
                   10613:     for(m=firstpass; (m<=lastpass); m++){
                   10614:       if (s[m][i] > (nlstate+ndeath)) {
1.169     brouard  10615:        (*nberr)++;
1.136     brouard  10616:        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);     
                   10617:        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);     
                   10618:        return 1;
                   10619:       }
                   10620:     }
                   10621:   }
                   10622: 
                   10623:   /*for (i=1; i<=imx; i++){
                   10624:   for (m=firstpass; (m<lastpass); m++){
                   10625:      printf("%ld %d %.lf %d %d\n", num[i],(covar[1][i]),agev[m][i],s[m][i],s[m+1][i]);
                   10626: }
                   10627: 
                   10628: }*/
                   10629: 
                   10630: 
1.139     brouard  10631:   printf("Total number of individuals= %d, Agemin = %.2f, Agemax= %.2f\n\n", imx, *agemin, *agemax);
                   10632:   fprintf(ficlog,"Total number of individuals= %d, Agemin = %.2f, Agemax= %.2f\n\n", imx, *agemin, *agemax); 
1.136     brouard  10633: 
                   10634:   return (0);
1.164     brouard  10635:  /* endread:*/
1.136     brouard  10636:     printf("Exiting calandcheckages: ");
                   10637:     return (1);
                   10638: }
                   10639: 
1.172     brouard  10640: #if defined(_MSC_VER)
                   10641: /*printf("Visual C++ compiler: %s \n;", _MSC_FULL_VER);*/
                   10642: /*fprintf(ficlog, "Visual C++ compiler: %s \n;", _MSC_FULL_VER);*/
                   10643: //#include "stdafx.h"
                   10644: //#include <stdio.h>
                   10645: //#include <tchar.h>
                   10646: //#include <windows.h>
                   10647: //#include <iostream>
                   10648: typedef BOOL(WINAPI *LPFN_ISWOW64PROCESS) (HANDLE, PBOOL);
                   10649: 
                   10650: LPFN_ISWOW64PROCESS fnIsWow64Process;
                   10651: 
                   10652: BOOL IsWow64()
                   10653: {
                   10654:        BOOL bIsWow64 = FALSE;
                   10655: 
                   10656:        //typedef BOOL (APIENTRY *LPFN_ISWOW64PROCESS)
                   10657:        //  (HANDLE, PBOOL);
                   10658: 
                   10659:        //LPFN_ISWOW64PROCESS fnIsWow64Process;
                   10660: 
                   10661:        HMODULE module = GetModuleHandle(_T("kernel32"));
                   10662:        const char funcName[] = "IsWow64Process";
                   10663:        fnIsWow64Process = (LPFN_ISWOW64PROCESS)
                   10664:                GetProcAddress(module, funcName);
                   10665: 
                   10666:        if (NULL != fnIsWow64Process)
                   10667:        {
                   10668:                if (!fnIsWow64Process(GetCurrentProcess(),
                   10669:                        &bIsWow64))
                   10670:                        //throw std::exception("Unknown error");
                   10671:                        printf("Unknown error\n");
                   10672:        }
                   10673:        return bIsWow64 != FALSE;
                   10674: }
                   10675: #endif
1.177     brouard  10676: 
1.191     brouard  10677: void syscompilerinfo(int logged)
1.292     brouard  10678: {
                   10679: #include <stdint.h>
                   10680: 
                   10681:   /* #include "syscompilerinfo.h"*/
1.185     brouard  10682:    /* command line Intel compiler 32bit windows, XP compatible:*/
                   10683:    /* /GS /W3 /Gy
                   10684:       /Zc:wchar_t /Zi /O2 /Fd"Release\vc120.pdb" /D "WIN32" /D "NDEBUG" /D
                   10685:       "_CONSOLE" /D "_LIB" /D "_USING_V110_SDK71_" /D "_UNICODE" /D
                   10686:       "UNICODE" /Qipo /Zc:forScope /Gd /Oi /MT /Fa"Release\" /EHsc /nologo
1.186     brouard  10687:       /Fo"Release\" /Qprof-dir "Release\" /Fp"Release\IMaCh.pch"
                   10688:    */ 
                   10689:    /* 64 bits */
1.185     brouard  10690:    /*
                   10691:      /GS /W3 /Gy
                   10692:      /Zc:wchar_t /Zi /O2 /Fd"x64\Release\vc120.pdb" /D "WIN32" /D "NDEBUG"
                   10693:      /D "_CONSOLE" /D "_LIB" /D "_UNICODE" /D "UNICODE" /Qipo /Zc:forScope
                   10694:      /Oi /MD /Fa"x64\Release\" /EHsc /nologo /Fo"x64\Release\" /Qprof-dir
                   10695:      "x64\Release\" /Fp"x64\Release\IMaCh.pch" */
                   10696:    /* Optimization are useless and O3 is slower than O2 */
                   10697:    /*
                   10698:      /GS /W3 /Gy /Zc:wchar_t /Zi /O3 /Fd"x64\Release\vc120.pdb" /D "WIN32" 
                   10699:      /D "NDEBUG" /D "_CONSOLE" /D "_LIB" /D "_UNICODE" /D "UNICODE" /Qipo 
                   10700:      /Zc:forScope /Oi /MD /Fa"x64\Release\" /EHsc /nologo /Qparallel 
                   10701:      /Fo"x64\Release\" /Qprof-dir "x64\Release\" /Fp"x64\Release\IMaCh.pch" 
                   10702:    */
1.186     brouard  10703:    /* Link is */ /* /OUT:"visual studio
1.185     brouard  10704:       2013\Projects\IMaCh\Release\IMaCh.exe" /MANIFEST /NXCOMPAT
                   10705:       /PDB:"visual studio
                   10706:       2013\Projects\IMaCh\Release\IMaCh.pdb" /DYNAMICBASE
                   10707:       "kernel32.lib" "user32.lib" "gdi32.lib" "winspool.lib"
                   10708:       "comdlg32.lib" "advapi32.lib" "shell32.lib" "ole32.lib"
                   10709:       "oleaut32.lib" "uuid.lib" "odbc32.lib" "odbccp32.lib"
                   10710:       /MACHINE:X86 /OPT:REF /SAFESEH /INCREMENTAL:NO
                   10711:       /SUBSYSTEM:CONSOLE",5.01" /MANIFESTUAC:"level='asInvoker'
                   10712:       uiAccess='false'"
                   10713:       /ManifestFile:"Release\IMaCh.exe.intermediate.manifest" /OPT:ICF
                   10714:       /NOLOGO /TLBID:1
                   10715:    */
1.292     brouard  10716: 
                   10717: 
1.177     brouard  10718: #if defined __INTEL_COMPILER
1.178     brouard  10719: #if defined(__GNUC__)
                   10720:        struct utsname sysInfo;  /* For Intel on Linux and OS/X */
                   10721: #endif
1.177     brouard  10722: #elif defined(__GNUC__) 
1.179     brouard  10723: #ifndef  __APPLE__
1.174     brouard  10724: #include <gnu/libc-version.h>  /* Only on gnu */
1.179     brouard  10725: #endif
1.177     brouard  10726:    struct utsname sysInfo;
1.178     brouard  10727:    int cross = CROSS;
                   10728:    if (cross){
                   10729:           printf("Cross-");
1.191     brouard  10730:           if(logged) fprintf(ficlog, "Cross-");
1.178     brouard  10731:    }
1.174     brouard  10732: #endif
                   10733: 
1.191     brouard  10734:    printf("Compiled with:");if(logged)fprintf(ficlog,"Compiled with:");
1.169     brouard  10735: #if defined(__clang__)
1.191     brouard  10736:    printf(" Clang/LLVM");if(logged)fprintf(ficlog," Clang/LLVM");      /* Clang/LLVM. ---------------------------------------------- */
1.169     brouard  10737: #endif
                   10738: #if defined(__ICC) || defined(__INTEL_COMPILER)
1.191     brouard  10739:    printf(" Intel ICC/ICPC");if(logged)fprintf(ficlog," Intel ICC/ICPC");/* Intel ICC/ICPC. ------------------------------------------ */
1.169     brouard  10740: #endif
                   10741: #if defined(__GNUC__) || defined(__GNUG__)
1.191     brouard  10742:    printf(" GNU GCC/G++");if(logged)fprintf(ficlog," GNU GCC/G++");/* GNU GCC/G++. --------------------------------------------- */
1.169     brouard  10743: #endif
                   10744: #if defined(__HP_cc) || defined(__HP_aCC)
1.191     brouard  10745:    printf(" Hewlett-Packard C/aC++");if(logged)fprintf(fcilog," Hewlett-Packard C/aC++"); /* Hewlett-Packard C/aC++. ---------------------------------- */
1.169     brouard  10746: #endif
                   10747: #if defined(__IBMC__) || defined(__IBMCPP__)
1.191     brouard  10748:    printf(" IBM XL C/C++"); if(logged) fprintf(ficlog," IBM XL C/C++");/* IBM XL C/C++. -------------------------------------------- */
1.169     brouard  10749: #endif
                   10750: #if defined(_MSC_VER)
1.191     brouard  10751:    printf(" Microsoft Visual Studio");if(logged)fprintf(ficlog," Microsoft Visual Studio");/* Microsoft Visual Studio. --------------------------------- */
1.169     brouard  10752: #endif
                   10753: #if defined(__PGI)
1.191     brouard  10754:    printf(" Portland Group PGCC/PGCPP");if(logged) fprintf(ficlog," Portland Group PGCC/PGCPP");/* Portland Group PGCC/PGCPP. ------------------------------- */
1.169     brouard  10755: #endif
                   10756: #if defined(__SUNPRO_C) || defined(__SUNPRO_CC)
1.191     brouard  10757:    printf(" Oracle Solaris Studio");if(logged)fprintf(ficlog," Oracle Solaris Studio\n");/* Oracle Solaris Studio. ----------------------------------- */
1.167     brouard  10758: #endif
1.191     brouard  10759:    printf(" for "); if (logged) fprintf(ficlog, " for ");
1.169     brouard  10760:    
1.167     brouard  10761: // http://stackoverflow.com/questions/4605842/how-to-identify-platform-compiler-from-preprocessor-macros
                   10762: #ifdef _WIN32 // note the underscore: without it, it's not msdn official!
                   10763:     // Windows (x64 and x86)
1.191     brouard  10764:    printf("Windows (x64 and x86) ");if(logged) fprintf(ficlog,"Windows (x64 and x86) ");
1.167     brouard  10765: #elif __unix__ // all unices, not all compilers
                   10766:     // Unix
1.191     brouard  10767:    printf("Unix ");if(logged) fprintf(ficlog,"Unix ");
1.167     brouard  10768: #elif __linux__
                   10769:     // linux
1.191     brouard  10770:    printf("linux ");if(logged) fprintf(ficlog,"linux ");
1.167     brouard  10771: #elif __APPLE__
1.174     brouard  10772:     // Mac OS, not sure if this is covered by __posix__ and/or __unix__ though..
1.191     brouard  10773:    printf("Mac OS ");if(logged) fprintf(ficlog,"Mac OS ");
1.167     brouard  10774: #endif
                   10775: 
                   10776: /*  __MINGW32__          */
                   10777: /*  __CYGWIN__  */
                   10778: /* __MINGW64__  */
                   10779: // http://msdn.microsoft.com/en-us/library/b0084kay.aspx
                   10780: /* _MSC_VER  //the Visual C++ compiler is 17.00.51106.1, the _MSC_VER macro evaluates to 1700. Type cl /?  */
                   10781: /* _MSC_FULL_VER //the Visual C++ compiler is 15.00.20706.01, the _MSC_FULL_VER macro evaluates to 150020706 */
                   10782: /* _WIN64  // Defined for applications for Win64. */
                   10783: /* _M_X64 // Defined for compilations that target x64 processors. */
                   10784: /* _DEBUG // Defined when you compile with /LDd, /MDd, and /MTd. */
1.171     brouard  10785: 
1.167     brouard  10786: #if UINTPTR_MAX == 0xffffffff
1.191     brouard  10787:    printf(" 32-bit"); if(logged) fprintf(ficlog," 32-bit");/* 32-bit */
1.167     brouard  10788: #elif UINTPTR_MAX == 0xffffffffffffffff
1.191     brouard  10789:    printf(" 64-bit"); if(logged) fprintf(ficlog," 64-bit");/* 64-bit */
1.167     brouard  10790: #else
1.191     brouard  10791:    printf(" wtf-bit"); if(logged) fprintf(ficlog," wtf-bit");/* wtf */
1.167     brouard  10792: #endif
                   10793: 
1.169     brouard  10794: #if defined(__GNUC__)
                   10795: # if defined(__GNUC_PATCHLEVEL__)
                   10796: #  define __GNUC_VERSION__ (__GNUC__ * 10000 \
                   10797:                             + __GNUC_MINOR__ * 100 \
                   10798:                             + __GNUC_PATCHLEVEL__)
                   10799: # else
                   10800: #  define __GNUC_VERSION__ (__GNUC__ * 10000 \
                   10801:                             + __GNUC_MINOR__ * 100)
                   10802: # endif
1.174     brouard  10803:    printf(" using GNU C version %d.\n", __GNUC_VERSION__);
1.191     brouard  10804:    if(logged) fprintf(ficlog, " using GNU C version %d.\n", __GNUC_VERSION__);
1.176     brouard  10805: 
                   10806:    if (uname(&sysInfo) != -1) {
                   10807:      printf("Running on: %s %s %s %s %s\n",sysInfo.sysname, sysInfo.nodename, sysInfo.release, sysInfo.version, sysInfo.machine);
1.191     brouard  10808:         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  10809:    }
                   10810:    else
                   10811:       perror("uname() error");
1.179     brouard  10812:    //#ifndef __INTEL_COMPILER 
                   10813: #if !defined (__INTEL_COMPILER) && !defined(__APPLE__)
1.174     brouard  10814:    printf("GNU libc version: %s\n", gnu_get_libc_version()); 
1.191     brouard  10815:    if(logged) fprintf(ficlog,"GNU libc version: %s\n", gnu_get_libc_version());
1.177     brouard  10816: #endif
1.169     brouard  10817: #endif
1.172     brouard  10818: 
1.286     brouard  10819:    //   void main ()
1.172     brouard  10820:    //   {
1.169     brouard  10821: #if defined(_MSC_VER)
1.174     brouard  10822:    if (IsWow64()){
1.191     brouard  10823:           printf("\nThe program (probably compiled for 32bit) is running under WOW64 (64bit) emulation.\n");
                   10824:           if (logged) fprintf(ficlog, "\nThe program (probably compiled for 32bit) is running under WOW64 (64bit) emulation.\n");
1.174     brouard  10825:    }
                   10826:    else{
1.191     brouard  10827:           printf("\nThe program is not running under WOW64 (i.e probably on a 64bit Windows).\n");
                   10828:           if (logged) fprintf(ficlog, "\nThe programm is not running under WOW64 (i.e probably on a 64bit Windows).\n");
1.174     brouard  10829:    }
1.172     brouard  10830:    //     printf("\nPress Enter to continue...");
                   10831:    //     getchar();
                   10832:    //   }
                   10833: 
1.169     brouard  10834: #endif
                   10835:    
1.167     brouard  10836: 
1.219     brouard  10837: }
1.136     brouard  10838: 
1.219     brouard  10839: int prevalence_limit(double *p, double **prlim, double ageminpar, double agemaxpar, double ftolpl, int *ncvyearp){
1.288     brouard  10840:   /*--------------- Prevalence limit  (forward period or forward stable prevalence) --------------*/
1.235     brouard  10841:   int i, j, k, i1, k4=0, nres=0 ;
1.202     brouard  10842:   /* double ftolpl = 1.e-10; */
1.180     brouard  10843:   double age, agebase, agelim;
1.203     brouard  10844:   double tot;
1.180     brouard  10845: 
1.202     brouard  10846:   strcpy(filerespl,"PL_");
                   10847:   strcat(filerespl,fileresu);
                   10848:   if((ficrespl=fopen(filerespl,"w"))==NULL) {
1.288     brouard  10849:     printf("Problem with forward period (stable) prevalence resultfile: %s\n", filerespl);return 1;
                   10850:     fprintf(ficlog,"Problem with forward period (stable) prevalence resultfile: %s\n", filerespl);return 1;
1.202     brouard  10851:   }
1.288     brouard  10852:   printf("\nComputing forward period (stable) prevalence: result on file '%s' \n", filerespl);
                   10853:   fprintf(ficlog,"\nComputing forward period (stable) prevalence: result on file '%s' \n", filerespl);
1.202     brouard  10854:   pstamp(ficrespl);
1.288     brouard  10855:   fprintf(ficrespl,"# Forward period (stable) prevalence. Precision given by ftolpl=%g \n", ftolpl);
1.202     brouard  10856:   fprintf(ficrespl,"#Age ");
                   10857:   for(i=1; i<=nlstate;i++) fprintf(ficrespl,"%d-%d ",i,i);
                   10858:   fprintf(ficrespl,"\n");
1.180     brouard  10859:   
1.219     brouard  10860:   /* prlim=matrix(1,nlstate,1,nlstate);*/ /* back in main */
1.180     brouard  10861: 
1.219     brouard  10862:   agebase=ageminpar;
                   10863:   agelim=agemaxpar;
1.180     brouard  10864: 
1.227     brouard  10865:   /* i1=pow(2,ncoveff); */
1.234     brouard  10866:   i1=pow(2,cptcoveff); /* Number of combination of dummy covariates */
1.219     brouard  10867:   if (cptcovn < 1){i1=1;}
1.180     brouard  10868: 
1.238     brouard  10869:   for(k=1; k<=i1;k++){ /* For each combination k of dummy covariates in the model */
                   10870:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.253     brouard  10871:       if(i1 != 1 && TKresult[nres]!= k)
1.238     brouard  10872:        continue;
1.235     brouard  10873: 
1.238     brouard  10874:       /* for(cptcov=1,k=0;cptcov<=i1;cptcov++){ */
                   10875:       /* for(cptcov=1,k=0;cptcov<=1;cptcov++){ */
                   10876:       //for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){
                   10877:       /* k=k+1; */
                   10878:       /* to clean */
                   10879:       //printf("cptcov=%d cptcod=%d codtab=%d\n",cptcov, cptcod,codtabm(cptcod,cptcov));
                   10880:       fprintf(ficrespl,"#******");
                   10881:       printf("#******");
                   10882:       fprintf(ficlog,"#******");
                   10883:       for(j=1;j<=cptcoveff ;j++) {/* all covariates */
                   10884:        fprintf(ficrespl," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]); /* Here problem for varying dummy*/
                   10885:        printf(" V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   10886:        fprintf(ficlog," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   10887:       }
                   10888:       for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
                   10889:        printf(" V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
                   10890:        fprintf(ficrespl," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
                   10891:        fprintf(ficlog," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
                   10892:       }
                   10893:       fprintf(ficrespl,"******\n");
                   10894:       printf("******\n");
                   10895:       fprintf(ficlog,"******\n");
                   10896:       if(invalidvarcomb[k]){
                   10897:        printf("\nCombination (%d) ignored because no case \n",k); 
                   10898:        fprintf(ficrespl,"#Combination (%d) ignored because no case \n",k); 
                   10899:        fprintf(ficlog,"\nCombination (%d) ignored because no case \n",k); 
                   10900:        continue;
                   10901:       }
1.219     brouard  10902: 
1.238     brouard  10903:       fprintf(ficrespl,"#Age ");
                   10904:       for(j=1;j<=cptcoveff;j++) {
                   10905:        fprintf(ficrespl,"V%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   10906:       }
                   10907:       for(i=1; i<=nlstate;i++) fprintf(ficrespl,"  %d-%d   ",i,i);
                   10908:       fprintf(ficrespl,"Total Years_to_converge\n");
1.227     brouard  10909:     
1.238     brouard  10910:       for (age=agebase; age<=agelim; age++){
                   10911:        /* for (age=agebase; age<=agebase; age++){ */
                   10912:        prevalim(prlim, nlstate, p, age, oldm, savm, ftolpl, ncvyearp, k, nres);
                   10913:        fprintf(ficrespl,"%.0f ",age );
                   10914:        for(j=1;j<=cptcoveff;j++)
                   10915:          fprintf(ficrespl,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   10916:        tot=0.;
                   10917:        for(i=1; i<=nlstate;i++){
                   10918:          tot +=  prlim[i][i];
                   10919:          fprintf(ficrespl," %.5f", prlim[i][i]);
                   10920:        }
                   10921:        fprintf(ficrespl," %.3f %d\n", tot, *ncvyearp);
                   10922:       } /* Age */
                   10923:       /* was end of cptcod */
                   10924:     } /* cptcov */
                   10925:   } /* nres */
1.219     brouard  10926:   return 0;
1.180     brouard  10927: }
                   10928: 
1.218     brouard  10929: 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  10930:        /*--------------- Back Prevalence limit  (backward stable prevalence) --------------*/
1.218     brouard  10931:        
                   10932:        /* Computes the back prevalence limit  for any combination      of covariate values 
                   10933:    * at any age between ageminpar and agemaxpar
                   10934:         */
1.235     brouard  10935:   int i, j, k, i1, nres=0 ;
1.217     brouard  10936:   /* double ftolpl = 1.e-10; */
                   10937:   double age, agebase, agelim;
                   10938:   double tot;
1.218     brouard  10939:   /* double ***mobaverage; */
                   10940:   /* double     **dnewm, **doldm, **dsavm;  /\* for use *\/ */
1.217     brouard  10941: 
                   10942:   strcpy(fileresplb,"PLB_");
                   10943:   strcat(fileresplb,fileresu);
                   10944:   if((ficresplb=fopen(fileresplb,"w"))==NULL) {
1.288     brouard  10945:     printf("Problem with backward prevalence resultfile: %s\n", fileresplb);return 1;
                   10946:     fprintf(ficlog,"Problem with backward prevalence resultfile: %s\n", fileresplb);return 1;
1.217     brouard  10947:   }
1.288     brouard  10948:   printf("Computing backward prevalence: result on file '%s' \n", fileresplb);
                   10949:   fprintf(ficlog,"Computing backward prevalence: result on file '%s' \n", fileresplb);
1.217     brouard  10950:   pstamp(ficresplb);
1.288     brouard  10951:   fprintf(ficresplb,"# Backward prevalence. Precision given by ftolpl=%g \n", ftolpl);
1.217     brouard  10952:   fprintf(ficresplb,"#Age ");
                   10953:   for(i=1; i<=nlstate;i++) fprintf(ficresplb,"%d-%d ",i,i);
                   10954:   fprintf(ficresplb,"\n");
                   10955:   
1.218     brouard  10956:   
                   10957:   /* prlim=matrix(1,nlstate,1,nlstate);*/ /* back in main */
                   10958:   
                   10959:   agebase=ageminpar;
                   10960:   agelim=agemaxpar;
                   10961:   
                   10962:   
1.227     brouard  10963:   i1=pow(2,cptcoveff);
1.218     brouard  10964:   if (cptcovn < 1){i1=1;}
1.227     brouard  10965:   
1.238     brouard  10966:   for(nres=1; nres <= nresult; nres++){ /* For each resultline */
                   10967:     for(k=1; k<=i1;k++){ /* For any combination of dummy covariates, fixed and varying */
1.253     brouard  10968:      if(i1 != 1 && TKresult[nres]!= k)
1.238     brouard  10969:        continue;
                   10970:       //printf("cptcov=%d cptcod=%d codtab=%d\n",cptcov, cptcod,codtabm(cptcod,cptcov));
                   10971:       fprintf(ficresplb,"#******");
                   10972:       printf("#******");
                   10973:       fprintf(ficlog,"#******");
                   10974:       for(j=1;j<=cptcoveff ;j++) {/* all covariates */
                   10975:        fprintf(ficresplb," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   10976:        printf(" V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   10977:        fprintf(ficlog," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   10978:       }
                   10979:       for (j=1; j<= nsq; j++){ /* For each selected (single) quantitative value */
                   10980:        printf(" V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]);
                   10981:        fprintf(ficresplb," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]);
                   10982:        fprintf(ficlog," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]);
                   10983:       }
                   10984:       fprintf(ficresplb,"******\n");
                   10985:       printf("******\n");
                   10986:       fprintf(ficlog,"******\n");
                   10987:       if(invalidvarcomb[k]){
                   10988:        printf("\nCombination (%d) ignored because no cases \n",k); 
                   10989:        fprintf(ficresplb,"#Combination (%d) ignored because no cases \n",k); 
                   10990:        fprintf(ficlog,"\nCombination (%d) ignored because no cases \n",k); 
                   10991:        continue;
                   10992:       }
1.218     brouard  10993:     
1.238     brouard  10994:       fprintf(ficresplb,"#Age ");
                   10995:       for(j=1;j<=cptcoveff;j++) {
                   10996:        fprintf(ficresplb,"V%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   10997:       }
                   10998:       for(i=1; i<=nlstate;i++) fprintf(ficresplb,"  %d-%d   ",i,i);
                   10999:       fprintf(ficresplb,"Total Years_to_converge\n");
1.218     brouard  11000:     
                   11001:     
1.238     brouard  11002:       for (age=agebase; age<=agelim; age++){
                   11003:        /* for (age=agebase; age<=agebase; age++){ */
                   11004:        if(mobilavproj > 0){
                   11005:          /* bprevalim(bprlim, mobaverage, nlstate, p, age, ageminpar, agemaxpar, oldm, savm, doldm, dsavm, ftolpl, ncvyearp, k); */
                   11006:          /* bprevalim(bprlim, mobaverage, nlstate, p, age, oldm, savm, dnewm, doldm, dsavm, ftolpl, ncvyearp, k); */
1.242     brouard  11007:          bprevalim(bprlim, mobaverage, nlstate, p, age, ftolpl, ncvyearp, k, nres);
1.238     brouard  11008:        }else if (mobilavproj == 0){
                   11009:          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);
                   11010:          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);
                   11011:          exit(1);
                   11012:        }else{
                   11013:          /* bprevalim(bprlim, probs, nlstate, p, age, oldm, savm, dnewm, doldm, dsavm, ftolpl, ncvyearp, k); */
1.242     brouard  11014:          bprevalim(bprlim, probs, nlstate, p, age, ftolpl, ncvyearp, k,nres);
1.266     brouard  11015:          /* printf("TOTOT\n"); */
                   11016:           /* exit(1); */
1.238     brouard  11017:        }
                   11018:        fprintf(ficresplb,"%.0f ",age );
                   11019:        for(j=1;j<=cptcoveff;j++)
                   11020:          fprintf(ficresplb,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   11021:        tot=0.;
                   11022:        for(i=1; i<=nlstate;i++){
                   11023:          tot +=  bprlim[i][i];
                   11024:          fprintf(ficresplb," %.5f", bprlim[i][i]);
                   11025:        }
                   11026:        fprintf(ficresplb," %.3f %d\n", tot, *ncvyearp);
                   11027:       } /* Age */
                   11028:       /* was end of cptcod */
1.255     brouard  11029:       /*fprintf(ficresplb,"\n");*/ /* Seems to be necessary for gnuplot only if two result lines and no covariate. */
1.238     brouard  11030:     } /* end of any combination */
                   11031:   } /* end of nres */  
1.218     brouard  11032:   /* hBijx(p, bage, fage); */
                   11033:   /* fclose(ficrespijb); */
                   11034:   
                   11035:   return 0;
1.217     brouard  11036: }
1.218     brouard  11037:  
1.180     brouard  11038: int hPijx(double *p, int bage, int fage){
                   11039:     /*------------- h Pij x at various ages ------------*/
                   11040: 
                   11041:   int stepsize;
                   11042:   int agelim;
                   11043:   int hstepm;
                   11044:   int nhstepm;
1.235     brouard  11045:   int h, i, i1, j, k, k4, nres=0;
1.180     brouard  11046: 
                   11047:   double agedeb;
                   11048:   double ***p3mat;
                   11049: 
1.201     brouard  11050:     strcpy(filerespij,"PIJ_");  strcat(filerespij,fileresu);
1.180     brouard  11051:     if((ficrespij=fopen(filerespij,"w"))==NULL) {
                   11052:       printf("Problem with Pij resultfile: %s\n", filerespij); return 1;
                   11053:       fprintf(ficlog,"Problem with Pij resultfile: %s\n", filerespij); return 1;
                   11054:     }
                   11055:     printf("Computing pij: result on file '%s' \n", filerespij);
                   11056:     fprintf(ficlog,"Computing pij: result on file '%s' \n", filerespij);
                   11057:   
                   11058:     stepsize=(int) (stepm+YEARM-1)/YEARM;
                   11059:     /*if (stepm<=24) stepsize=2;*/
                   11060: 
                   11061:     agelim=AGESUP;
                   11062:     hstepm=stepsize*YEARM; /* Every year of age */
                   11063:     hstepm=hstepm/stepm; /* Typically 2 years, = 2/6 months = 4 */ 
1.218     brouard  11064:                
1.180     brouard  11065:     /* hstepm=1;   aff par mois*/
                   11066:     pstamp(ficrespij);
                   11067:     fprintf(ficrespij,"#****** h Pij x Probability to be in state j at age x+h being in i at x ");
1.227     brouard  11068:     i1= pow(2,cptcoveff);
1.218     brouard  11069:                /* for(cptcov=1,k=0;cptcov<=i1;cptcov++){ */
                   11070:                /*    /\*for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*\/ */
                   11071:                /*      k=k+1;  */
1.235     brouard  11072:     for(nres=1; nres <= nresult; nres++) /* For each resultline */
                   11073:     for(k=1; k<=i1;k++){
1.253     brouard  11074:       if(i1 != 1 && TKresult[nres]!= k)
1.235     brouard  11075:        continue;
1.183     brouard  11076:       fprintf(ficrespij,"\n#****** ");
1.227     brouard  11077:       for(j=1;j<=cptcoveff;j++) 
1.198     brouard  11078:        fprintf(ficrespij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
1.235     brouard  11079:       for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
                   11080:        printf(" V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
                   11081:        fprintf(ficrespij," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
                   11082:       }
1.183     brouard  11083:       fprintf(ficrespij,"******\n");
                   11084:       
                   11085:       for (agedeb=fage; agedeb>=bage; agedeb--){ /* If stepm=6 months */
                   11086:        nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */ 
                   11087:        nhstepm = nhstepm/hstepm; /* Typically 40/4=10 */
                   11088:        
                   11089:        /*        nhstepm=nhstepm*YEARM; aff par mois*/
1.180     brouard  11090:        
1.183     brouard  11091:        p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   11092:        oldm=oldms;savm=savms;
1.235     brouard  11093:        hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k, nres);  
1.183     brouard  11094:        fprintf(ficrespij,"# Cov Agex agex+h hpijx with i,j=");
                   11095:        for(i=1; i<=nlstate;i++)
                   11096:          for(j=1; j<=nlstate+ndeath;j++)
                   11097:            fprintf(ficrespij," %1d-%1d",i,j);
                   11098:        fprintf(ficrespij,"\n");
                   11099:        for (h=0; h<=nhstepm; h++){
                   11100:          /*agedebphstep = agedeb + h*hstepm/YEARM*stepm;*/
                   11101:          fprintf(ficrespij,"%d %3.f %3.f",k, agedeb, agedeb + h*hstepm/YEARM*stepm );
1.180     brouard  11102:          for(i=1; i<=nlstate;i++)
                   11103:            for(j=1; j<=nlstate+ndeath;j++)
1.183     brouard  11104:              fprintf(ficrespij," %.5f", p3mat[i][j][h]);
1.180     brouard  11105:          fprintf(ficrespij,"\n");
                   11106:        }
1.183     brouard  11107:        free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   11108:        fprintf(ficrespij,"\n");
                   11109:       }
1.180     brouard  11110:       /*}*/
                   11111:     }
1.218     brouard  11112:     return 0;
1.180     brouard  11113: }
1.218     brouard  11114:  
                   11115:  int hBijx(double *p, int bage, int fage, double ***prevacurrent){
1.217     brouard  11116:     /*------------- h Bij x at various ages ------------*/
                   11117: 
                   11118:   int stepsize;
1.218     brouard  11119:   /* int agelim; */
                   11120:        int ageminl;
1.217     brouard  11121:   int hstepm;
                   11122:   int nhstepm;
1.238     brouard  11123:   int h, i, i1, j, k, nres;
1.218     brouard  11124:        
1.217     brouard  11125:   double agedeb;
                   11126:   double ***p3mat;
1.218     brouard  11127:        
                   11128:   strcpy(filerespijb,"PIJB_");  strcat(filerespijb,fileresu);
                   11129:   if((ficrespijb=fopen(filerespijb,"w"))==NULL) {
                   11130:     printf("Problem with Pij back resultfile: %s\n", filerespijb); return 1;
                   11131:     fprintf(ficlog,"Problem with Pij back resultfile: %s\n", filerespijb); return 1;
                   11132:   }
                   11133:   printf("Computing pij back: result on file '%s' \n", filerespijb);
                   11134:   fprintf(ficlog,"Computing pij back: result on file '%s' \n", filerespijb);
                   11135:   
                   11136:   stepsize=(int) (stepm+YEARM-1)/YEARM;
                   11137:   /*if (stepm<=24) stepsize=2;*/
1.217     brouard  11138:   
1.218     brouard  11139:   /* agelim=AGESUP; */
1.289     brouard  11140:   ageminl=AGEINF; /* was 30 */
1.218     brouard  11141:   hstepm=stepsize*YEARM; /* Every year of age */
                   11142:   hstepm=hstepm/stepm; /* Typically 2 years, = 2/6 months = 4 */
                   11143:   
                   11144:   /* hstepm=1;   aff par mois*/
                   11145:   pstamp(ficrespijb);
1.255     brouard  11146:   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  11147:   i1= pow(2,cptcoveff);
1.218     brouard  11148:   /* for(cptcov=1,k=0;cptcov<=i1;cptcov++){ */
                   11149:   /*    /\*for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*\/ */
                   11150:   /*   k=k+1;  */
1.238     brouard  11151:   for(nres=1; nres <= nresult; nres++){ /* For each resultline */
                   11152:     for(k=1; k<=i1;k++){ /* For any combination of dummy covariates, fixed and varying */
1.253     brouard  11153:       if(i1 != 1 && TKresult[nres]!= k)
1.238     brouard  11154:        continue;
                   11155:       fprintf(ficrespijb,"\n#****** ");
                   11156:       for(j=1;j<=cptcoveff;j++)
                   11157:        fprintf(ficrespijb,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   11158:       for (j=1; j<= nsq; j++){ /* For each selected (single) quantitative value */
                   11159:        fprintf(ficrespijb," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]);
                   11160:       }
                   11161:       fprintf(ficrespijb,"******\n");
1.264     brouard  11162:       if(invalidvarcomb[k]){  /* Is it necessary here? */
1.238     brouard  11163:        fprintf(ficrespijb,"\n#Combination (%d) ignored because no cases \n",k); 
                   11164:        continue;
                   11165:       }
                   11166:       
                   11167:       /* for (agedeb=fage; agedeb>=bage; agedeb--){ /\* If stepm=6 months *\/ */
                   11168:       for (agedeb=bage; agedeb<=fage; agedeb++){ /* If stepm=6 months and estepm=24 (2 years) */
                   11169:        /* nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm); /\* Typically 20 years = 20*12/6=40 *\/ */
1.297     brouard  11170:        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 */
                   11171:        nhstepm = nhstepm/hstepm; /* Typically 40/4=10, because estepm=24 stepm=6 => hstepm=24/6=4 or 28*/
1.238     brouard  11172:        
                   11173:        /*        nhstepm=nhstepm*YEARM; aff par mois*/
                   11174:        
1.266     brouard  11175:        p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm); /* We can't have it at an upper level because of nhstepm */
                   11176:        /* and memory limitations if stepm is small */
                   11177: 
1.238     brouard  11178:        /* oldm=oldms;savm=savms; */
                   11179:        /* hbxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);   */
1.267     brouard  11180:        hbxij(p3mat,nhstepm,agedeb,hstepm,p,prevacurrent,nlstate,stepm, k, nres);
1.238     brouard  11181:        /* hbxij(p3mat,nhstepm,agedeb,hstepm,p,prevacurrent,nlstate,stepm,oldm,savm, dnewm, doldm, dsavm, k); */
1.255     brouard  11182:        fprintf(ficrespijb,"# Cov Agex agex-h hbijx with i,j=");
1.217     brouard  11183:        for(i=1; i<=nlstate;i++)
                   11184:          for(j=1; j<=nlstate+ndeath;j++)
1.238     brouard  11185:            fprintf(ficrespijb," %1d-%1d",i,j);
1.217     brouard  11186:        fprintf(ficrespijb,"\n");
1.238     brouard  11187:        for (h=0; h<=nhstepm; h++){
                   11188:          /*agedebphstep = agedeb + h*hstepm/YEARM*stepm;*/
                   11189:          fprintf(ficrespijb,"%d %3.f %3.f",k, agedeb, agedeb - h*hstepm/YEARM*stepm );
                   11190:          /* fprintf(ficrespijb,"%d %3.f %3.f",k, agedeb, agedeb + h*hstepm/YEARM*stepm ); */
                   11191:          for(i=1; i<=nlstate;i++)
                   11192:            for(j=1; j<=nlstate+ndeath;j++)
                   11193:              fprintf(ficrespijb," %.5f", p3mat[i][j][h]);
                   11194:          fprintf(ficrespijb,"\n");
                   11195:        }
                   11196:        free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   11197:        fprintf(ficrespijb,"\n");
                   11198:       } /* end age deb */
                   11199:     } /* end combination */
                   11200:   } /* end nres */
1.218     brouard  11201:   return 0;
                   11202:  } /*  hBijx */
1.217     brouard  11203: 
1.180     brouard  11204: 
1.136     brouard  11205: /***********************************************/
                   11206: /**************** Main Program *****************/
                   11207: /***********************************************/
                   11208: 
                   11209: int main(int argc, char *argv[])
                   11210: {
                   11211: #ifdef GSL
                   11212:   const gsl_multimin_fminimizer_type *T;
                   11213:   size_t iteri = 0, it;
                   11214:   int rval = GSL_CONTINUE;
                   11215:   int status = GSL_SUCCESS;
                   11216:   double ssval;
                   11217: #endif
                   11218:   int movingaverage(double ***probs, double bage,double fage, double ***mobaverage, int mobilav);
1.290     brouard  11219:   int i,j, k, iter=0,m,size=100, cptcod; /* Suppressing because nobs */
                   11220:   /* int i,j, k, n=MAXN,iter=0,m,size=100, cptcod; */
1.209     brouard  11221:   int ncvyear=0; /* Number of years needed for the period prevalence to converge */
1.164     brouard  11222:   int jj, ll, li, lj, lk;
1.136     brouard  11223:   int numlinepar=0; /* Current linenumber of parameter file */
1.197     brouard  11224:   int num_filled;
1.136     brouard  11225:   int itimes;
                   11226:   int NDIM=2;
                   11227:   int vpopbased=0;
1.235     brouard  11228:   int nres=0;
1.258     brouard  11229:   int endishere=0;
1.277     brouard  11230:   int noffset=0;
1.274     brouard  11231:   int ncurrv=0; /* Temporary variable */
                   11232:   
1.164     brouard  11233:   char ca[32], cb[32];
1.136     brouard  11234:   /*  FILE *fichtm; *//* Html File */
                   11235:   /* FILE *ficgp;*/ /*Gnuplot File */
                   11236:   struct stat info;
1.191     brouard  11237:   double agedeb=0.;
1.194     brouard  11238: 
                   11239:   double ageminpar=AGEOVERFLOW,agemin=AGEOVERFLOW, agemaxpar=-AGEOVERFLOW, agemax=-AGEOVERFLOW;
1.219     brouard  11240:   double ageminout=-AGEOVERFLOW,agemaxout=AGEOVERFLOW; /* Smaller Age range redefined after movingaverage */
1.136     brouard  11241: 
1.165     brouard  11242:   double fret;
1.191     brouard  11243:   double dum=0.; /* Dummy variable */
1.136     brouard  11244:   double ***p3mat;
1.218     brouard  11245:   /* double ***mobaverage; */
1.319     brouard  11246:   double wald;
1.164     brouard  11247: 
                   11248:   char line[MAXLINE];
1.197     brouard  11249:   char path[MAXLINE],pathc[MAXLINE],pathcd[MAXLINE],pathtot[MAXLINE];
                   11250: 
1.234     brouard  11251:   char  modeltemp[MAXLINE];
1.230     brouard  11252:   char resultline[MAXLINE];
                   11253:   
1.136     brouard  11254:   char pathr[MAXLINE], pathimach[MAXLINE]; 
1.164     brouard  11255:   char *tok, *val; /* pathtot */
1.290     brouard  11256:   int firstobs=1, lastobs=10; /* nobs = lastobs-firstobs declared globally ;*/
1.195     brouard  11257:   int c,  h , cpt, c2;
1.191     brouard  11258:   int jl=0;
                   11259:   int i1, j1, jk, stepsize=0;
1.194     brouard  11260:   int count=0;
                   11261: 
1.164     brouard  11262:   int *tab; 
1.136     brouard  11263:   int mobilavproj=0 , prevfcast=0 ; /* moving average of prev, If prevfcast=1 prevalence projection */
1.296     brouard  11264:   /* double anprojd, mprojd, jprojd; /\* For eventual projections *\/ */
                   11265:   /* double anprojf, mprojf, jprojf; */
                   11266:   /* double jintmean,mintmean,aintmean;   */
                   11267:   int prvforecast = 0; /* Might be 1 (date of beginning of projection is a choice or 2 is the dateintmean */
                   11268:   int prvbackcast = 0; /* Might be 1 (date of beginning of projection is a choice or 2 is the dateintmean */
                   11269:   double yrfproj= 10.0; /* Number of years of forward projections */
                   11270:   double yrbproj= 10.0; /* Number of years of backward projections */
                   11271:   int prevbcast=0; /* defined as global for mlikeli and mle, replacing backcast */
1.136     brouard  11272:   int mobilav=0,popforecast=0;
1.191     brouard  11273:   int hstepm=0, nhstepm=0;
1.136     brouard  11274:   int agemortsup;
                   11275:   float  sumlpop=0.;
                   11276:   double jprev1=1, mprev1=1,anprev1=2000,jprev2=1, mprev2=1,anprev2=2000;
                   11277:   double jpyram=1, mpyram=1,anpyram=2000,jpyram1=1, mpyram1=1,anpyram1=2000;
                   11278: 
1.191     brouard  11279:   double bage=0, fage=110., age, agelim=0., agebase=0.;
1.136     brouard  11280:   double ftolpl=FTOL;
                   11281:   double **prlim;
1.217     brouard  11282:   double **bprlim;
1.317     brouard  11283:   double ***param; /* Matrix of parameters, param[i][j][k] param=ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel) 
                   11284:                     state of origin, state of destination including death, for each covariate: constante, age, and V1 V2 etc. */
1.251     brouard  11285:   double ***paramstart; /* Matrix of starting parameter values */
                   11286:   double  *p, *pstart; /* p=param[1][1] pstart is for starting values guessed by freqsummary */
1.136     brouard  11287:   double **matcov; /* Matrix of covariance */
1.203     brouard  11288:   double **hess; /* Hessian matrix */
1.136     brouard  11289:   double ***delti3; /* Scale */
                   11290:   double *delti; /* Scale */
                   11291:   double ***eij, ***vareij;
                   11292:   double **varpl; /* Variances of prevalence limits by age */
1.269     brouard  11293: 
1.136     brouard  11294:   double *epj, vepp;
1.164     brouard  11295: 
1.273     brouard  11296:   double dateprev1, dateprev2;
1.296     brouard  11297:   double jproj1=1,mproj1=1,anproj1=2000,jproj2=1,mproj2=1,anproj2=2000, dateproj1=0, dateproj2=0, dateprojd=0, dateprojf=0;
                   11298:   double jback1=1,mback1=1,anback1=2000,jback2=1,mback2=1,anback2=2000, dateback1=0, dateback2=0, datebackd=0, datebackf=0;
                   11299: 
1.217     brouard  11300: 
1.136     brouard  11301:   double **ximort;
1.145     brouard  11302:   char *alph[]={"a","a","b","c","d","e"}, str[4]="1234";
1.136     brouard  11303:   int *dcwave;
                   11304: 
1.164     brouard  11305:   char z[1]="c";
1.136     brouard  11306: 
                   11307:   /*char  *strt;*/
                   11308:   char strtend[80];
1.126     brouard  11309: 
1.164     brouard  11310: 
1.126     brouard  11311: /*   setlocale (LC_ALL, ""); */
                   11312: /*   bindtextdomain (PACKAGE, LOCALEDIR); */
                   11313: /*   textdomain (PACKAGE); */
                   11314: /*   setlocale (LC_CTYPE, ""); */
                   11315: /*   setlocale (LC_MESSAGES, ""); */
                   11316: 
                   11317:   /*   gettimeofday(&start_time, (struct timezone*)0); */ /* at first time */
1.157     brouard  11318:   rstart_time = time(NULL);  
                   11319:   /*  (void) gettimeofday(&start_time,&tzp);*/
                   11320:   start_time = *localtime(&rstart_time);
1.126     brouard  11321:   curr_time=start_time;
1.157     brouard  11322:   /*tml = *localtime(&start_time.tm_sec);*/
                   11323:   /* strcpy(strstart,asctime(&tml)); */
                   11324:   strcpy(strstart,asctime(&start_time));
1.126     brouard  11325: 
                   11326: /*  printf("Localtime (at start)=%s",strstart); */
1.157     brouard  11327: /*  tp.tm_sec = tp.tm_sec +86400; */
                   11328: /*  tm = *localtime(&start_time.tm_sec); */
1.126     brouard  11329: /*   tmg.tm_year=tmg.tm_year +dsign*dyear; */
                   11330: /*   tmg.tm_mon=tmg.tm_mon +dsign*dmonth; */
                   11331: /*   tmg.tm_hour=tmg.tm_hour + 1; */
1.157     brouard  11332: /*   tp.tm_sec = mktime(&tmg); */
1.126     brouard  11333: /*   strt=asctime(&tmg); */
                   11334: /*   printf("Time(after) =%s",strstart);  */
                   11335: /*  (void) time (&time_value);
                   11336: *  printf("time=%d,t-=%d\n",time_value,time_value-86400);
                   11337: *  tm = *localtime(&time_value);
                   11338: *  strstart=asctime(&tm);
                   11339: *  printf("tim_value=%d,asctime=%s\n",time_value,strstart); 
                   11340: */
                   11341: 
                   11342:   nberr=0; /* Number of errors and warnings */
                   11343:   nbwarn=0;
1.184     brouard  11344: #ifdef WIN32
                   11345:   _getcwd(pathcd, size);
                   11346: #else
1.126     brouard  11347:   getcwd(pathcd, size);
1.184     brouard  11348: #endif
1.191     brouard  11349:   syscompilerinfo(0);
1.196     brouard  11350:   printf("\nIMaCh version %s, %s\n%s",version, copyright, fullversion);
1.126     brouard  11351:   if(argc <=1){
                   11352:     printf("\nEnter the parameter file name: ");
1.205     brouard  11353:     if(!fgets(pathr,FILENAMELENGTH,stdin)){
                   11354:       printf("ERROR Empty parameter file name\n");
                   11355:       goto end;
                   11356:     }
1.126     brouard  11357:     i=strlen(pathr);
                   11358:     if(pathr[i-1]=='\n')
                   11359:       pathr[i-1]='\0';
1.156     brouard  11360:     i=strlen(pathr);
1.205     brouard  11361:     if(i >= 1 && pathr[i-1]==' ') {/* This may happen when dragging on oS/X! */
1.156     brouard  11362:       pathr[i-1]='\0';
1.205     brouard  11363:     }
                   11364:     i=strlen(pathr);
                   11365:     if( i==0 ){
                   11366:       printf("ERROR Empty parameter file name\n");
                   11367:       goto end;
                   11368:     }
                   11369:     for (tok = pathr; tok != NULL; ){
1.126     brouard  11370:       printf("Pathr |%s|\n",pathr);
                   11371:       while ((val = strsep(&tok, "\"" )) != NULL && *val == '\0');
                   11372:       printf("val= |%s| pathr=%s\n",val,pathr);
                   11373:       strcpy (pathtot, val);
                   11374:       if(pathr[0] == '\0') break; /* Dirty */
                   11375:     }
                   11376:   }
1.281     brouard  11377:   else if (argc<=2){
                   11378:     strcpy(pathtot,argv[1]);
                   11379:   }
1.126     brouard  11380:   else{
                   11381:     strcpy(pathtot,argv[1]);
1.281     brouard  11382:     strcpy(z,argv[2]);
                   11383:     printf("\nargv[2]=%s z=%c\n",argv[2],z[0]);
1.126     brouard  11384:   }
                   11385:   /*if(getcwd(pathcd, MAXLINE)!= NULL)printf ("Error pathcd\n");*/
                   11386:   /*cygwin_split_path(pathtot,path,optionfile);
                   11387:     printf("pathtot=%s, path=%s, optionfile=%s\n",pathtot,path,optionfile);*/
                   11388:   /* cutv(path,optionfile,pathtot,'\\');*/
                   11389: 
                   11390:   /* Split argv[0], imach program to get pathimach */
                   11391:   printf("\nargv[0]=%s argv[1]=%s, \n",argv[0],argv[1]);
                   11392:   split(argv[0],pathimach,optionfile,optionfilext,optionfilefiname);
                   11393:   printf("\nargv[0]=%s pathimach=%s, \noptionfile=%s \noptionfilext=%s \noptionfilefiname=%s\n",argv[0],pathimach,optionfile,optionfilext,optionfilefiname);
                   11394:  /*   strcpy(pathimach,argv[0]); */
                   11395:   /* Split argv[1]=pathtot, parameter file name to get path, optionfile, extension and name */
                   11396:   split(pathtot,path,optionfile,optionfilext,optionfilefiname);
                   11397:   printf("\npathtot=%s,\npath=%s,\noptionfile=%s \noptionfilext=%s \noptionfilefiname=%s\n",pathtot,path,optionfile,optionfilext,optionfilefiname);
1.184     brouard  11398: #ifdef WIN32
                   11399:   _chdir(path); /* Can be a relative path */
                   11400:   if(_getcwd(pathcd,MAXLINE) > 0) /* So pathcd is the full path */
                   11401: #else
1.126     brouard  11402:   chdir(path); /* Can be a relative path */
1.184     brouard  11403:   if (getcwd(pathcd, MAXLINE) > 0) /* So pathcd is the full path */
                   11404: #endif
                   11405:   printf("Current directory %s!\n",pathcd);
1.126     brouard  11406:   strcpy(command,"mkdir ");
                   11407:   strcat(command,optionfilefiname);
                   11408:   if((outcmd=system(command)) != 0){
1.169     brouard  11409:     printf("Directory already exists (or can't create it) %s%s, err=%d\n",path,optionfilefiname,outcmd);
1.126     brouard  11410:     /* fprintf(ficlog,"Problem creating directory %s%s\n",path,optionfilefiname); */
                   11411:     /* fclose(ficlog); */
                   11412: /*     exit(1); */
                   11413:   }
                   11414: /*   if((imk=mkdir(optionfilefiname))<0){ */
                   11415: /*     perror("mkdir"); */
                   11416: /*   } */
                   11417: 
                   11418:   /*-------- arguments in the command line --------*/
                   11419: 
1.186     brouard  11420:   /* Main Log file */
1.126     brouard  11421:   strcat(filelog, optionfilefiname);
                   11422:   strcat(filelog,".log");    /* */
                   11423:   if((ficlog=fopen(filelog,"w"))==NULL)    {
                   11424:     printf("Problem with logfile %s\n",filelog);
                   11425:     goto end;
                   11426:   }
                   11427:   fprintf(ficlog,"Log filename:%s\n",filelog);
1.197     brouard  11428:   fprintf(ficlog,"Version %s %s",version,fullversion);
1.126     brouard  11429:   fprintf(ficlog,"\nEnter the parameter file name: \n");
                   11430:   fprintf(ficlog,"pathimach=%s\npathtot=%s\n\
                   11431:  path=%s \n\
                   11432:  optionfile=%s\n\
                   11433:  optionfilext=%s\n\
1.156     brouard  11434:  optionfilefiname='%s'\n",pathimach,pathtot,path,optionfile,optionfilext,optionfilefiname);
1.126     brouard  11435: 
1.197     brouard  11436:   syscompilerinfo(1);
1.167     brouard  11437: 
1.126     brouard  11438:   printf("Local time (at start):%s",strstart);
                   11439:   fprintf(ficlog,"Local time (at start): %s",strstart);
                   11440:   fflush(ficlog);
                   11441: /*   (void) gettimeofday(&curr_time,&tzp); */
1.157     brouard  11442: /*   printf("Elapsed time %d\n", asc_diff_time(curr_time.tm_sec-start_time.tm_sec,tmpout)); */
1.126     brouard  11443: 
                   11444:   /* */
                   11445:   strcpy(fileres,"r");
                   11446:   strcat(fileres, optionfilefiname);
1.201     brouard  11447:   strcat(fileresu, optionfilefiname); /* Without r in front */
1.126     brouard  11448:   strcat(fileres,".txt");    /* Other files have txt extension */
1.201     brouard  11449:   strcat(fileresu,".txt");    /* Other files have txt extension */
1.126     brouard  11450: 
1.186     brouard  11451:   /* Main ---------arguments file --------*/
1.126     brouard  11452: 
                   11453:   if((ficpar=fopen(optionfile,"r"))==NULL)    {
1.155     brouard  11454:     printf("Problem with optionfile '%s' with errno='%s'\n",optionfile,strerror(errno));
                   11455:     fprintf(ficlog,"Problem with optionfile '%s' with errno='%s'\n",optionfile,strerror(errno));
1.126     brouard  11456:     fflush(ficlog);
1.149     brouard  11457:     /* goto end; */
                   11458:     exit(70); 
1.126     brouard  11459:   }
                   11460: 
                   11461:   strcpy(filereso,"o");
1.201     brouard  11462:   strcat(filereso,fileresu);
1.126     brouard  11463:   if((ficparo=fopen(filereso,"w"))==NULL) { /* opened on subdirectory */
                   11464:     printf("Problem with Output resultfile: %s\n", filereso);
                   11465:     fprintf(ficlog,"Problem with Output resultfile: %s\n", filereso);
                   11466:     fflush(ficlog);
                   11467:     goto end;
                   11468:   }
1.278     brouard  11469:       /*-------- Rewriting parameter file ----------*/
                   11470:   strcpy(rfileres,"r");    /* "Rparameterfile */
                   11471:   strcat(rfileres,optionfilefiname);    /* Parameter file first name */
                   11472:   strcat(rfileres,".");    /* */
                   11473:   strcat(rfileres,optionfilext);    /* Other files have txt extension */
                   11474:   if((ficres =fopen(rfileres,"w"))==NULL) {
                   11475:     printf("Problem writing new parameter file: %s\n", rfileres);goto end;
                   11476:     fprintf(ficlog,"Problem writing new parameter file: %s\n", rfileres);goto end;
                   11477:     fflush(ficlog);
                   11478:     goto end;
                   11479:   }
                   11480:   fprintf(ficres,"#IMaCh %s\n",version);
1.126     brouard  11481: 
1.278     brouard  11482:                                      
1.126     brouard  11483:   /* Reads comments: lines beginning with '#' */
                   11484:   numlinepar=0;
1.277     brouard  11485:   /* Is it a BOM UTF-8 Windows file? */
                   11486:   /* First parameter line */
1.197     brouard  11487:   while(fgets(line, MAXLINE, ficpar)) {
1.277     brouard  11488:     noffset=0;
                   11489:     if( line[0] == (char)0xEF && line[1] == (char)0xBB) /* EF BB BF */
                   11490:     {
                   11491:       noffset=noffset+3;
                   11492:       printf("# File is an UTF8 Bom.\n"); // 0xBF
                   11493:     }
1.302     brouard  11494: /*    else if( line[0] == (char)0xFE && line[1] == (char)0xFF)*/
                   11495:     else if( line[0] == (char)0xFF && line[1] == (char)0xFE)
1.277     brouard  11496:     {
                   11497:       noffset=noffset+2;
                   11498:       printf("# File is an UTF16BE BOM file\n");
                   11499:     }
                   11500:     else if( line[0] == 0 && line[1] == 0)
                   11501:     {
                   11502:       if( line[2] == (char)0xFE && line[3] == (char)0xFF){
                   11503:        noffset=noffset+4;
                   11504:        printf("# File is an UTF16BE BOM file\n");
                   11505:       }
                   11506:     } else{
                   11507:       ;/*printf(" Not a BOM file\n");*/
                   11508:     }
                   11509:   
1.197     brouard  11510:     /* If line starts with a # it is a comment */
1.277     brouard  11511:     if (line[noffset] == '#') {
1.197     brouard  11512:       numlinepar++;
                   11513:       fputs(line,stdout);
                   11514:       fputs(line,ficparo);
1.278     brouard  11515:       fputs(line,ficres);
1.197     brouard  11516:       fputs(line,ficlog);
                   11517:       continue;
                   11518:     }else
                   11519:       break;
                   11520:   }
                   11521:   if((num_filled=sscanf(line,"title=%s datafile=%s lastobs=%d firstpass=%d lastpass=%d\n", \
                   11522:                        title, datafile, &lastobs, &firstpass,&lastpass)) !=EOF){
                   11523:     if (num_filled != 5) {
                   11524:       printf("Should be 5 parameters\n");
1.283     brouard  11525:       fprintf(ficlog,"Should be 5 parameters\n");
1.197     brouard  11526:     }
1.126     brouard  11527:     numlinepar++;
1.197     brouard  11528:     printf("title=%s datafile=%s lastobs=%d firstpass=%d lastpass=%d\n", title, datafile, lastobs, firstpass,lastpass);
1.283     brouard  11529:     fprintf(ficparo,"title=%s datafile=%s lastobs=%d firstpass=%d lastpass=%d\n", title, datafile, lastobs, firstpass,lastpass);
                   11530:     fprintf(ficres,"title=%s datafile=%s lastobs=%d firstpass=%d lastpass=%d\n", title, datafile, lastobs, firstpass,lastpass);
                   11531:     fprintf(ficlog,"title=%s datafile=%s lastobs=%d firstpass=%d lastpass=%d\n", title, datafile, lastobs, firstpass,lastpass);
1.197     brouard  11532:   }
                   11533:   /* Second parameter line */
                   11534:   while(fgets(line, MAXLINE, ficpar)) {
1.283     brouard  11535:     /* while(fscanf(ficpar,"%[^\n]", line)) { */
                   11536:     /* If line starts with a # it is a comment. Strangely fgets reads the EOL and fputs doesn't */
1.197     brouard  11537:     if (line[0] == '#') {
                   11538:       numlinepar++;
1.283     brouard  11539:       printf("%s",line);
                   11540:       fprintf(ficres,"%s",line);
                   11541:       fprintf(ficparo,"%s",line);
                   11542:       fprintf(ficlog,"%s",line);
1.197     brouard  11543:       continue;
                   11544:     }else
                   11545:       break;
                   11546:   }
1.223     brouard  11547:   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", \
                   11548:                        &ftol, &stepm, &ncovcol, &nqv, &ntv, &nqtv, &nlstate, &ndeath, &maxwav, &mle, &weightopt)) !=EOF){
                   11549:     if (num_filled != 11) {
                   11550:       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  11551:       printf("but line=%s\n",line);
1.283     brouard  11552:       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");
                   11553:       fprintf(ficlog,"but line=%s\n",line);
1.197     brouard  11554:     }
1.286     brouard  11555:     if( lastpass > maxwav){
                   11556:       printf("Error (lastpass = %d) > (maxwav = %d)\n",lastpass, maxwav);
                   11557:       fprintf(ficlog,"Error (lastpass = %d) > (maxwav = %d)\n",lastpass, maxwav);
                   11558:       fflush(ficlog);
                   11559:       goto end;
                   11560:     }
                   11561:       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  11562:     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  11563:     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  11564:     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  11565:   }
1.203     brouard  11566:   /* ftolpl=6*ftol*1.e5; /\* 6.e-3 make convergences in less than 80 loops for the prevalence limit *\/ */
1.209     brouard  11567:   /*ftolpl=6.e-4; *//* 6.e-3 make convergences in less than 80 loops for the prevalence limit */
1.197     brouard  11568:   /* Third parameter line */
                   11569:   while(fgets(line, MAXLINE, ficpar)) {
                   11570:     /* If line starts with a # it is a comment */
                   11571:     if (line[0] == '#') {
                   11572:       numlinepar++;
1.283     brouard  11573:       printf("%s",line);
                   11574:       fprintf(ficres,"%s",line);
                   11575:       fprintf(ficparo,"%s",line);
                   11576:       fprintf(ficlog,"%s",line);
1.197     brouard  11577:       continue;
                   11578:     }else
                   11579:       break;
                   11580:   }
1.201     brouard  11581:   if((num_filled=sscanf(line,"model=1+age%[^.\n]", model)) !=EOF){
1.279     brouard  11582:     if (num_filled != 1){
1.302     brouard  11583:       printf("ERROR %d: Model should be at minimum 'model=1+age+' instead of '%s'\n",num_filled, line);
                   11584:       fprintf(ficlog,"ERROR %d: Model should be at minimum 'model=1+age+' instead of '%s'\n",num_filled, line);
1.197     brouard  11585:       model[0]='\0';
                   11586:       goto end;
                   11587:     }
                   11588:     else{
                   11589:       if (model[0]=='+'){
                   11590:        for(i=1; i<=strlen(model);i++)
                   11591:          modeltemp[i-1]=model[i];
1.201     brouard  11592:        strcpy(model,modeltemp); 
1.197     brouard  11593:       }
                   11594:     }
1.199     brouard  11595:     /* printf(" model=1+age%s modeltemp= %s, model=%s\n",model, modeltemp, model);fflush(stdout); */
1.203     brouard  11596:     printf("model=1+age+%s\n",model);fflush(stdout);
1.283     brouard  11597:     fprintf(ficparo,"model=1+age+%s\n",model);fflush(stdout);
                   11598:     fprintf(ficres,"model=1+age+%s\n",model);fflush(stdout);
                   11599:     fprintf(ficlog,"model=1+age+%s\n",model);fflush(stdout);
1.197     brouard  11600:   }
                   11601:   /* 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); */
                   11602:   /* numlinepar=numlinepar+3; /\* In general *\/ */
                   11603:   /* 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  11604:   /* 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); */
                   11605:   /* 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  11606:   fflush(ficlog);
1.190     brouard  11607:   /* if(model[0]=='#'|| model[0]== '\0'){ */
                   11608:   if(model[0]=='#'){
1.279     brouard  11609:     printf("Error in 'model' line: model should start with 'model=1+age+' and end without space \n \
                   11610:  'model=1+age+' or 'model=1+age+V1.' or 'model=1+age+age*age+V1+V1*age' or \n \
                   11611:  'model=1+age+V1+V2' or 'model=1+age+V1+V2+V1*V2' etc. \n");           \
1.187     brouard  11612:     if(mle != -1){
1.279     brouard  11613:       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  11614:       exit(1);
                   11615:     }
                   11616:   }
1.126     brouard  11617:   while((c=getc(ficpar))=='#' && c!= EOF){
                   11618:     ungetc(c,ficpar);
                   11619:     fgets(line, MAXLINE, ficpar);
                   11620:     numlinepar++;
1.195     brouard  11621:     if(line[1]=='q'){ /* This #q will quit imach (the answer is q) */
                   11622:       z[0]=line[1];
                   11623:     }
                   11624:     /* printf("****line [1] = %c \n",line[1]); */
1.141     brouard  11625:     fputs(line, stdout);
                   11626:     //puts(line);
1.126     brouard  11627:     fputs(line,ficparo);
                   11628:     fputs(line,ficlog);
                   11629:   }
                   11630:   ungetc(c,ficpar);
                   11631: 
                   11632:    
1.290     brouard  11633:   covar=matrix(0,NCOVMAX,firstobs,lastobs);  /**< used in readdata */
                   11634:   if(nqv>=1)coqvar=matrix(1,nqv,firstobs,lastobs);  /**< Fixed quantitative covariate */
                   11635:   if(nqtv>=1)cotqvar=ma3x(1,maxwav,1,nqtv,firstobs,lastobs);  /**< Time varying quantitative covariate */
                   11636:   if(ntv+nqtv>=1)cotvar=ma3x(1,maxwav,1,ntv+nqtv,firstobs,lastobs);  /**< Time varying covariate (dummy and quantitative)*/
1.136     brouard  11637:   cptcovn=0; /*Number of covariates, i.e. number of '+' in model statement plus one, indepently of n in Vn*/
                   11638:   /* v1+v2+v3+v2*v4+v5*age makes cptcovn = 5
                   11639:      v1+v2*age+v2*v3 makes cptcovn = 3
                   11640:   */
                   11641:   if (strlen(model)>1) 
1.187     brouard  11642:     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  11643:   else
1.187     brouard  11644:     ncovmodel=2; /* Constant and age */
1.133     brouard  11645:   nforce= (nlstate+ndeath-1)*nlstate; /* Number of forces ij from state i to j */
                   11646:   npar= nforce*ncovmodel; /* Number of parameters like aij*/
1.131     brouard  11647:   if(npar >MAXPARM || nlstate >NLSTATEMAX || ndeath >NDEATHMAX || ncovmodel>NCOVMAX){
                   11648:     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);
                   11649:     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);
                   11650:     fflush(stdout);
                   11651:     fclose (ficlog);
                   11652:     goto end;
                   11653:   }
1.126     brouard  11654:   delti3= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
                   11655:   delti=delti3[1][1];
                   11656:   /*delti=vector(1,npar); *//* Scale of each paramater (output from hesscov)*/
                   11657:   if(mle==-1){ /* Print a wizard for help writing covariance matrix */
1.247     brouard  11658: /* We could also provide initial parameters values giving by simple logistic regression 
                   11659:  * only one way, that is without matrix product. We will have nlstate maximizations */
                   11660:       /* for(i=1;i<nlstate;i++){ */
                   11661:       /*       /\*reducing xi for 1 to npar to 1 to ncovmodel; *\/ */
                   11662:       /*    mlikeli(ficres,p, ncovmodel, ncovmodel, nlstate, ftol, funcnoprod); */
                   11663:       /* } */
1.126     brouard  11664:     prwizard(ncovmodel, nlstate, ndeath, model, ficparo);
1.191     brouard  11665:     printf(" You chose mle=-1, look at file %s for a template of covariance matrix \n",filereso);
                   11666:     fprintf(ficlog," You chose mle=-1, look at file %s for a template of covariance matrix \n",filereso);
1.126     brouard  11667:     free_ma3x(delti3,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel); 
                   11668:     fclose (ficparo);
                   11669:     fclose (ficlog);
                   11670:     goto end;
                   11671:     exit(0);
1.220     brouard  11672:   }  else if(mle==-5) { /* Main Wizard */
1.126     brouard  11673:     prwizard(ncovmodel, nlstate, ndeath, model, ficparo);
1.192     brouard  11674:     printf(" You chose mle=-3, look at file %s for a template of covariance matrix \n",filereso);
                   11675:     fprintf(ficlog," You chose mle=-3, look at file %s for a template of covariance matrix \n",filereso);
1.126     brouard  11676:     param= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
                   11677:     matcov=matrix(1,npar,1,npar);
1.203     brouard  11678:     hess=matrix(1,npar,1,npar);
1.220     brouard  11679:   }  else{ /* Begin of mle != -1 or -5 */
1.145     brouard  11680:     /* Read guessed parameters */
1.126     brouard  11681:     /* Reads comments: lines beginning with '#' */
                   11682:     while((c=getc(ficpar))=='#' && c!= EOF){
                   11683:       ungetc(c,ficpar);
                   11684:       fgets(line, MAXLINE, ficpar);
                   11685:       numlinepar++;
1.141     brouard  11686:       fputs(line,stdout);
1.126     brouard  11687:       fputs(line,ficparo);
                   11688:       fputs(line,ficlog);
                   11689:     }
                   11690:     ungetc(c,ficpar);
                   11691:     
                   11692:     param= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
1.251     brouard  11693:     paramstart= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
1.126     brouard  11694:     for(i=1; i <=nlstate; i++){
1.234     brouard  11695:       j=0;
1.126     brouard  11696:       for(jj=1; jj <=nlstate+ndeath; jj++){
1.234     brouard  11697:        if(jj==i) continue;
                   11698:        j++;
1.292     brouard  11699:        while((c=getc(ficpar))=='#' && c!= EOF){
                   11700:          ungetc(c,ficpar);
                   11701:          fgets(line, MAXLINE, ficpar);
                   11702:          numlinepar++;
                   11703:          fputs(line,stdout);
                   11704:          fputs(line,ficparo);
                   11705:          fputs(line,ficlog);
                   11706:        }
                   11707:        ungetc(c,ficpar);
1.234     brouard  11708:        fscanf(ficpar,"%1d%1d",&i1,&j1);
                   11709:        if ((i1 != i) || (j1 != jj)){
                   11710:          printf("Error in line parameters number %d, %1d%1d instead of %1d%1d \n \
1.126     brouard  11711: It might be a problem of design; if ncovcol and the model are correct\n \
                   11712: run imach with mle=-1 to get a correct template of the parameter file.\n",numlinepar, i,j, i1, j1);
1.234     brouard  11713:          exit(1);
                   11714:        }
                   11715:        fprintf(ficparo,"%1d%1d",i1,j1);
                   11716:        if(mle==1)
                   11717:          printf("%1d%1d",i,jj);
                   11718:        fprintf(ficlog,"%1d%1d",i,jj);
                   11719:        for(k=1; k<=ncovmodel;k++){
                   11720:          fscanf(ficpar," %lf",&param[i][j][k]);
                   11721:          if(mle==1){
                   11722:            printf(" %lf",param[i][j][k]);
                   11723:            fprintf(ficlog," %lf",param[i][j][k]);
                   11724:          }
                   11725:          else
                   11726:            fprintf(ficlog," %lf",param[i][j][k]);
                   11727:          fprintf(ficparo," %lf",param[i][j][k]);
                   11728:        }
                   11729:        fscanf(ficpar,"\n");
                   11730:        numlinepar++;
                   11731:        if(mle==1)
                   11732:          printf("\n");
                   11733:        fprintf(ficlog,"\n");
                   11734:        fprintf(ficparo,"\n");
1.126     brouard  11735:       }
                   11736:     }  
                   11737:     fflush(ficlog);
1.234     brouard  11738:     
1.251     brouard  11739:     /* Reads parameters values */
1.126     brouard  11740:     p=param[1][1];
1.251     brouard  11741:     pstart=paramstart[1][1];
1.126     brouard  11742:     
                   11743:     /* Reads comments: lines beginning with '#' */
                   11744:     while((c=getc(ficpar))=='#' && c!= EOF){
                   11745:       ungetc(c,ficpar);
                   11746:       fgets(line, MAXLINE, ficpar);
                   11747:       numlinepar++;
1.141     brouard  11748:       fputs(line,stdout);
1.126     brouard  11749:       fputs(line,ficparo);
                   11750:       fputs(line,ficlog);
                   11751:     }
                   11752:     ungetc(c,ficpar);
                   11753: 
                   11754:     for(i=1; i <=nlstate; i++){
                   11755:       for(j=1; j <=nlstate+ndeath-1; j++){
1.234     brouard  11756:        fscanf(ficpar,"%1d%1d",&i1,&j1);
                   11757:        if ( (i1-i) * (j1-j) != 0){
                   11758:          printf("Error in line parameters number %d, %1d%1d instead of %1d%1d \n",numlinepar, i,j, i1, j1);
                   11759:          exit(1);
                   11760:        }
                   11761:        printf("%1d%1d",i,j);
                   11762:        fprintf(ficparo,"%1d%1d",i1,j1);
                   11763:        fprintf(ficlog,"%1d%1d",i1,j1);
                   11764:        for(k=1; k<=ncovmodel;k++){
                   11765:          fscanf(ficpar,"%le",&delti3[i][j][k]);
                   11766:          printf(" %le",delti3[i][j][k]);
                   11767:          fprintf(ficparo," %le",delti3[i][j][k]);
                   11768:          fprintf(ficlog," %le",delti3[i][j][k]);
                   11769:        }
                   11770:        fscanf(ficpar,"\n");
                   11771:        numlinepar++;
                   11772:        printf("\n");
                   11773:        fprintf(ficparo,"\n");
                   11774:        fprintf(ficlog,"\n");
1.126     brouard  11775:       }
                   11776:     }
                   11777:     fflush(ficlog);
1.234     brouard  11778:     
1.145     brouard  11779:     /* Reads covariance matrix */
1.126     brouard  11780:     delti=delti3[1][1];
1.220     brouard  11781:                
                   11782:                
1.126     brouard  11783:     /* 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  11784:                
1.126     brouard  11785:     /* Reads comments: lines beginning with '#' */
                   11786:     while((c=getc(ficpar))=='#' && c!= EOF){
                   11787:       ungetc(c,ficpar);
                   11788:       fgets(line, MAXLINE, ficpar);
                   11789:       numlinepar++;
1.141     brouard  11790:       fputs(line,stdout);
1.126     brouard  11791:       fputs(line,ficparo);
                   11792:       fputs(line,ficlog);
                   11793:     }
                   11794:     ungetc(c,ficpar);
1.220     brouard  11795:                
1.126     brouard  11796:     matcov=matrix(1,npar,1,npar);
1.203     brouard  11797:     hess=matrix(1,npar,1,npar);
1.131     brouard  11798:     for(i=1; i <=npar; i++)
                   11799:       for(j=1; j <=npar; j++) matcov[i][j]=0.;
1.220     brouard  11800:                
1.194     brouard  11801:     /* Scans npar lines */
1.126     brouard  11802:     for(i=1; i <=npar; i++){
1.226     brouard  11803:       count=fscanf(ficpar,"%1d%1d%d",&i1,&j1,&jk);
1.194     brouard  11804:       if(count != 3){
1.226     brouard  11805:        printf("Error! Error in parameter file %s at line %d after line starting with %1d%1d%1d\n\
1.194     brouard  11806: This is probably because your covariance matrix doesn't \n  contain exactly %d lines corresponding to your model line '1+age+%s'.\n\
                   11807: Please run with mle=-1 to get a correct covariance matrix.\n",optionfile,numlinepar, i1,j1,jk, npar, model);
1.226     brouard  11808:        fprintf(ficlog,"Error! Error in parameter file %s at line %d after line starting with %1d%1d%1d\n\
1.194     brouard  11809: This is probably because your covariance matrix doesn't \n  contain exactly %d lines corresponding to your model line '1+age+%s'.\n\
                   11810: Please run with mle=-1 to get a correct covariance matrix.\n",optionfile,numlinepar, i1,j1,jk, npar, model);
1.226     brouard  11811:        exit(1);
1.220     brouard  11812:       }else{
1.226     brouard  11813:        if(mle==1)
                   11814:          printf("%1d%1d%d",i1,j1,jk);
                   11815:       }
                   11816:       fprintf(ficlog,"%1d%1d%d",i1,j1,jk);
                   11817:       fprintf(ficparo,"%1d%1d%d",i1,j1,jk);
1.126     brouard  11818:       for(j=1; j <=i; j++){
1.226     brouard  11819:        fscanf(ficpar," %le",&matcov[i][j]);
                   11820:        if(mle==1){
                   11821:          printf(" %.5le",matcov[i][j]);
                   11822:        }
                   11823:        fprintf(ficlog," %.5le",matcov[i][j]);
                   11824:        fprintf(ficparo," %.5le",matcov[i][j]);
1.126     brouard  11825:       }
                   11826:       fscanf(ficpar,"\n");
                   11827:       numlinepar++;
                   11828:       if(mle==1)
1.220     brouard  11829:                                printf("\n");
1.126     brouard  11830:       fprintf(ficlog,"\n");
                   11831:       fprintf(ficparo,"\n");
                   11832:     }
1.194     brouard  11833:     /* End of read covariance matrix npar lines */
1.126     brouard  11834:     for(i=1; i <=npar; i++)
                   11835:       for(j=i+1;j<=npar;j++)
1.226     brouard  11836:        matcov[i][j]=matcov[j][i];
1.126     brouard  11837:     
                   11838:     if(mle==1)
                   11839:       printf("\n");
                   11840:     fprintf(ficlog,"\n");
                   11841:     
                   11842:     fflush(ficlog);
                   11843:     
                   11844:   }    /* End of mle != -3 */
1.218     brouard  11845:   
1.186     brouard  11846:   /*  Main data
                   11847:    */
1.290     brouard  11848:   nobs=lastobs-firstobs+1; /* was = lastobs;*/
                   11849:   /* num=lvector(1,n); */
                   11850:   /* moisnais=vector(1,n); */
                   11851:   /* annais=vector(1,n); */
                   11852:   /* moisdc=vector(1,n); */
                   11853:   /* andc=vector(1,n); */
                   11854:   /* weight=vector(1,n); */
                   11855:   /* agedc=vector(1,n); */
                   11856:   /* cod=ivector(1,n); */
                   11857:   /* for(i=1;i<=n;i++){ */
                   11858:   num=lvector(firstobs,lastobs);
                   11859:   moisnais=vector(firstobs,lastobs);
                   11860:   annais=vector(firstobs,lastobs);
                   11861:   moisdc=vector(firstobs,lastobs);
                   11862:   andc=vector(firstobs,lastobs);
                   11863:   weight=vector(firstobs,lastobs);
                   11864:   agedc=vector(firstobs,lastobs);
                   11865:   cod=ivector(firstobs,lastobs);
                   11866:   for(i=firstobs;i<=lastobs;i++){
1.234     brouard  11867:     num[i]=0;
                   11868:     moisnais[i]=0;
                   11869:     annais[i]=0;
                   11870:     moisdc[i]=0;
                   11871:     andc[i]=0;
                   11872:     agedc[i]=0;
                   11873:     cod[i]=0;
                   11874:     weight[i]=1.0; /* Equal weights, 1 by default */
                   11875:   }
1.290     brouard  11876:   mint=matrix(1,maxwav,firstobs,lastobs);
                   11877:   anint=matrix(1,maxwav,firstobs,lastobs);
                   11878:   s=imatrix(1,maxwav+1,firstobs,lastobs); /* s[i][j] health state for wave i and individual j */ 
1.126     brouard  11879:   tab=ivector(1,NCOVMAX);
1.144     brouard  11880:   ncodemax=ivector(1,NCOVMAX); /* Number of code per covariate; if O and 1 only, 2**ncov; V1+V2+V3+V4=>16 */
1.192     brouard  11881:   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  11882: 
1.136     brouard  11883:   /* Reads data from file datafile */
                   11884:   if (readdata(datafile, firstobs, lastobs, &imx)==1)
                   11885:     goto end;
                   11886: 
                   11887:   /* Calculation of the number of parameters from char model */
1.234     brouard  11888:   /*    modelsav=V2+V1+V4+age*V3 strb=age*V3 stra=V2+V1+V4 
1.137     brouard  11889:        k=4 (age*V3) Tvar[k=4]= 3 (from V3) Tag[cptcovage=1]=4
                   11890:        k=3 V4 Tvar[k=3]= 4 (from V4)
                   11891:        k=2 V1 Tvar[k=2]= 1 (from V1)
                   11892:        k=1 Tvar[1]=2 (from V2)
1.234     brouard  11893:   */
                   11894:   
                   11895:   Tvar=ivector(1,NCOVMAX); /* Was 15 changed to NCOVMAX. */
                   11896:   TvarsDind=ivector(1,NCOVMAX); /*  */
                   11897:   TvarsD=ivector(1,NCOVMAX); /*  */
                   11898:   TvarsQind=ivector(1,NCOVMAX); /*  */
                   11899:   TvarsQ=ivector(1,NCOVMAX); /*  */
1.232     brouard  11900:   TvarF=ivector(1,NCOVMAX); /*  */
                   11901:   TvarFind=ivector(1,NCOVMAX); /*  */
                   11902:   TvarV=ivector(1,NCOVMAX); /*  */
                   11903:   TvarVind=ivector(1,NCOVMAX); /*  */
                   11904:   TvarA=ivector(1,NCOVMAX); /*  */
                   11905:   TvarAind=ivector(1,NCOVMAX); /*  */
1.231     brouard  11906:   TvarFD=ivector(1,NCOVMAX); /*  */
                   11907:   TvarFDind=ivector(1,NCOVMAX); /*  */
                   11908:   TvarFQ=ivector(1,NCOVMAX); /*  */
                   11909:   TvarFQind=ivector(1,NCOVMAX); /*  */
                   11910:   TvarVD=ivector(1,NCOVMAX); /*  */
                   11911:   TvarVDind=ivector(1,NCOVMAX); /*  */
                   11912:   TvarVQ=ivector(1,NCOVMAX); /*  */
                   11913:   TvarVQind=ivector(1,NCOVMAX); /*  */
                   11914: 
1.230     brouard  11915:   Tvalsel=vector(1,NCOVMAX); /*  */
1.233     brouard  11916:   Tvarsel=ivector(1,NCOVMAX); /*  */
1.226     brouard  11917:   Typevar=ivector(-1,NCOVMAX); /* -1 to 2 */
                   11918:   Fixed=ivector(-1,NCOVMAX); /* -1 to 3 */
                   11919:   Dummy=ivector(-1,NCOVMAX); /* -1 to 3 */
1.137     brouard  11920:   /*  V2+V1+V4+age*V3 is a model with 4 covariates (3 plus signs). 
                   11921:       For each model-covariate stores the data-covariate id. Tvar[1]=2, Tvar[2]=1, Tvar[3]=4, 
                   11922:       Tvar[4=age*V3] is 3 and 'age' is recorded in Tage.
                   11923:   */
                   11924:   /* For model-covariate k tells which data-covariate to use but
                   11925:     because this model-covariate is a construction we invent a new column
                   11926:     ncovcol + k1
                   11927:     If already ncovcol=4 and model=V2+V1+V1*V4+age*V3
                   11928:     Tvar[3=V1*V4]=4+1 etc */
1.227     brouard  11929:   Tprod=ivector(1,NCOVMAX); /* Gives the k position of the k1 product */
                   11930:   Tposprod=ivector(1,NCOVMAX); /* Gives the k1 product from the k position */
1.137     brouard  11931:   /* Tprod[k1=1]=3(=V1*V4) for V2+V1+V1*V4+age*V3
                   11932:      if  V2+V1+V1*V4+age*V3+V3*V2   TProd[k1=2]=5 (V3*V2)
1.227     brouard  11933:      Tposprod[k]=k1 , Tposprod[3]=1, Tposprod[5]=2 
1.137     brouard  11934:   */
1.145     brouard  11935:   Tvaraff=ivector(1,NCOVMAX); /* Unclear */
                   11936:   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  11937:                            * For V3*V2 (in V2+V1+V1*V4+age*V3+V3*V2), V3*V2 position is 2nd. 
                   11938:                            * Tvard[k1=2][1]=3 (V3) Tvard[k1=2][2]=2(V2) */
1.145     brouard  11939:   Tage=ivector(1,NCOVMAX); /* Gives the covariate id of covariates associated with age: V2 + V1 + age*V4 + V3*age
1.137     brouard  11940:                         4 covariates (3 plus signs)
                   11941:                         Tage[1=V3*age]= 4; Tage[2=age*V4] = 3
                   11942:                      */  
1.230     brouard  11943:   Tmodelind=ivector(1,NCOVMAX);/** gives the k model position of an
1.227     brouard  11944:                                * individual dummy, fixed or varying:
                   11945:                                * Tmodelind[Tvaraff[3]]=9,Tvaraff[1]@9={4,
                   11946:                                * 3, 1, 0, 0, 0, 0, 0, 0},
1.230     brouard  11947:                                * model=V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 , 
                   11948:                                * V1 df, V2 qf, V3 & V4 dv, V5 qv
                   11949:                                * Tmodelind[1]@9={9,0,3,2,}*/
                   11950:   TmodelInvind=ivector(1,NCOVMAX); /* TmodelInvind=Tvar[k]- ncovcol-nqv={5-2-1=2,*/
                   11951:   TmodelInvQind=ivector(1,NCOVMAX);/** gives the k model position of an
1.228     brouard  11952:                                * individual quantitative, fixed or varying:
                   11953:                                * Tmodelqind[1]=1,Tvaraff[1]@9={4,
                   11954:                                * 3, 1, 0, 0, 0, 0, 0, 0},
                   11955:                                * model=V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1*/
1.186     brouard  11956: /* Main decodemodel */
                   11957: 
1.187     brouard  11958: 
1.223     brouard  11959:   if(decodemodel(model, lastobs) == 1) /* In order to get Tvar[k] V4+V3+V5 p Tvar[1]@3  = {4, 3, 5}*/
1.136     brouard  11960:     goto end;
                   11961: 
1.137     brouard  11962:   if((double)(lastobs-imx)/(double)imx > 1.10){
                   11963:     nbwarn++;
                   11964:     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); 
                   11965:     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); 
                   11966:   }
1.136     brouard  11967:     /*  if(mle==1){*/
1.137     brouard  11968:   if (weightopt != 1) { /* Maximisation without weights. We can have weights different from 1 but want no weight*/
                   11969:     for(i=1;i<=imx;i++) weight[i]=1.0; /* changed to imx */
1.136     brouard  11970:   }
                   11971: 
                   11972:     /*-calculation of age at interview from date of interview and age at death -*/
                   11973:   agev=matrix(1,maxwav,1,imx);
                   11974: 
                   11975:   if(calandcheckages(imx, maxwav, &agemin, &agemax, &nberr, &nbwarn) == 1)
                   11976:     goto end;
                   11977: 
1.126     brouard  11978: 
1.136     brouard  11979:   agegomp=(int)agemin;
1.290     brouard  11980:   free_vector(moisnais,firstobs,lastobs);
                   11981:   free_vector(annais,firstobs,lastobs);
1.126     brouard  11982:   /* free_matrix(mint,1,maxwav,1,n);
                   11983:      free_matrix(anint,1,maxwav,1,n);*/
1.215     brouard  11984:   /* free_vector(moisdc,1,n); */
                   11985:   /* free_vector(andc,1,n); */
1.145     brouard  11986:   /* */
                   11987:   
1.126     brouard  11988:   wav=ivector(1,imx);
1.214     brouard  11989:   /* dh=imatrix(1,lastpass-firstpass+1,1,imx); */
                   11990:   /* bh=imatrix(1,lastpass-firstpass+1,1,imx); */
                   11991:   /* mw=imatrix(1,lastpass-firstpass+1,1,imx); */
                   11992:   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.*/
                   11993:   bh=imatrix(1,lastpass-firstpass+2,1,imx);
                   11994:   mw=imatrix(1,lastpass-firstpass+2,1,imx);
1.126     brouard  11995:    
                   11996:   /* Concatenates waves */
1.214     brouard  11997:   /* Concatenates waves: wav[i] is the number of effective (useful waves) of individual i.
                   11998:      Death is a valid wave (if date is known).
                   11999:      mw[mi][i] is the number of (mi=1 to wav[i]) effective wave out of mi of individual i
                   12000:      dh[m][i] or dh[mw[mi][i]][i] is the delay between two effective waves m=mw[mi][i]
                   12001:      and mw[mi+1][i]. dh depends on stepm.
                   12002:   */
                   12003: 
1.126     brouard  12004:   concatwav(wav, dh, bh, mw, s, agedc, agev,  firstpass, lastpass, imx, nlstate, stepm);
1.248     brouard  12005:   /* Concatenates waves */
1.145     brouard  12006:  
1.290     brouard  12007:   free_vector(moisdc,firstobs,lastobs);
                   12008:   free_vector(andc,firstobs,lastobs);
1.215     brouard  12009: 
1.126     brouard  12010:   /* Routine tricode is to calculate cptcoveff (real number of unique covariates) and to associate covariable number and modality */
                   12011:   nbcode=imatrix(0,NCOVMAX,0,NCOVMAX); 
                   12012:   ncodemax[1]=1;
1.145     brouard  12013:   Ndum =ivector(-1,NCOVMAX);  
1.225     brouard  12014:   cptcoveff=0;
1.220     brouard  12015:   if (ncovmodel-nagesqr > 2 ){ /* That is if covariate other than cst, age and age*age */
                   12016:     tricode(&cptcoveff,Tvar,nbcode,imx, Ndum); /**< Fills nbcode[Tvar[j]][l]; */
1.227     brouard  12017:   }
                   12018:   
                   12019:   ncovcombmax=pow(2,cptcoveff);
                   12020:   invalidvarcomb=ivector(1, ncovcombmax); 
                   12021:   for(i=1;i<ncovcombmax;i++)
                   12022:     invalidvarcomb[i]=0;
                   12023:   
1.211     brouard  12024:   /* Nbcode gives the value of the lth modality (currently 1 to 2) of jth covariate, in
1.186     brouard  12025:      V2+V1*age, there are 3 covariates Tvar[2]=1 (V1).*/
1.211     brouard  12026:   /* 1 to ncodemax[j] which is the maximum value of this jth covariate */
1.227     brouard  12027:   
1.200     brouard  12028:   /*  codtab=imatrix(1,100,1,10);*/ /* codtab[h,k]=( (h-1) - mod(k-1,2**(k-1) )/2**(k-1) */
1.198     brouard  12029:   /*printf(" codtab[1,1],codtab[100,10]=%d,%d\n", codtab[1][1],codtabm(100,10));*/
1.186     brouard  12030:   /* codtab gives the value 1 or 2 of the hth combination of k covariates (1 or 2).*/
1.211     brouard  12031:   /* nbcode[Tvaraff[j]][codtabm(h,j)]) : if there are only 2 modalities for a covariate j, 
                   12032:    * codtabm(h,j) gives its value classified at position h and nbcode gives how it is coded 
                   12033:    * (currently 0 or 1) in the data.
                   12034:    * In a loop on h=1 to 2**k, and a loop on j (=1 to k), we get the value of 
                   12035:    * corresponding modality (h,j).
                   12036:    */
                   12037: 
1.145     brouard  12038:   h=0;
                   12039:   /*if (cptcovn > 0) */
1.126     brouard  12040:   m=pow(2,cptcoveff);
                   12041:  
1.144     brouard  12042:          /**< codtab(h,k)  k   = codtab[h,k]=( (h-1) - mod(k-1,2**(k-1) )/2**(k-1) + 1
1.211     brouard  12043:           * For k=4 covariates, h goes from 1 to m=2**k
                   12044:           * codtabm(h,k)=  (1 & (h-1) >> (k-1)) + 1;
                   12045:            * #define codtabm(h,k)  (1 & (h-1) >> (k-1))+1
1.186     brouard  12046:           *     h\k   1     2     3     4
1.143     brouard  12047:           *______________________________  
                   12048:           *     1 i=1 1 i=1 1 i=1 1 i=1 1
                   12049:           *     2     2     1     1     1
                   12050:           *     3 i=2 1     2     1     1
                   12051:           *     4     2     2     1     1
                   12052:           *     5 i=3 1 i=2 1     2     1
                   12053:           *     6     2     1     2     1
                   12054:           *     7 i=4 1     2     2     1
                   12055:           *     8     2     2     2     1
1.197     brouard  12056:           *     9 i=5 1 i=3 1 i=2 1     2
                   12057:           *    10     2     1     1     2
                   12058:           *    11 i=6 1     2     1     2
                   12059:           *    12     2     2     1     2
                   12060:           *    13 i=7 1 i=4 1     2     2    
                   12061:           *    14     2     1     2     2
                   12062:           *    15 i=8 1     2     2     2
                   12063:           *    16     2     2     2     2
1.143     brouard  12064:           */
1.212     brouard  12065:   /* How to do the opposite? From combination h (=1 to 2**k) how to get the value on the covariates? */
1.211     brouard  12066:      /* from h=5 and m, we get then number of covariates k=log(m)/log(2)=4
                   12067:      * and the value of each covariate?
                   12068:      * V1=1, V2=1, V3=2, V4=1 ?
                   12069:      * h-1=4 and 4 is 0100 or reverse 0010, and +1 is 1121 ok.
                   12070:      * h=6, 6-1=5, 5 is 0101, 1010, 2121, V1=2nd, V2=1st, V3=2nd, V4=1st.
                   12071:      * In order to get the real value in the data, we use nbcode
                   12072:      * nbcode[Tvar[3][2nd]]=1 and nbcode[Tvar[4][1]]=0
                   12073:      * We are keeping this crazy system in order to be able (in the future?) 
                   12074:      * to have more than 2 values (0 or 1) for a covariate.
                   12075:      * #define codtabm(h,k)  (1 & (h-1) >> (k-1))+1
                   12076:      * h=6, k=2? h-1=5=0101, reverse 1010, +1=2121, k=2nd position: value is 1: codtabm(6,2)=1
                   12077:      *              bbbbbbbb
                   12078:      *              76543210     
                   12079:      *   h-1        00000101 (6-1=5)
1.219     brouard  12080:      *(h-1)>>(k-1)= 00000010 >> (2-1) = 1 right shift
1.211     brouard  12081:      *           &
                   12082:      *     1        00000001 (1)
1.219     brouard  12083:      *              00000000        = 1 & ((h-1) >> (k-1))
                   12084:      *          +1= 00000001 =1 
1.211     brouard  12085:      *
                   12086:      * h=14, k=3 => h'=h-1=13, k'=k-1=2
                   12087:      *          h'      1101 =2^3+2^2+0x2^1+2^0
                   12088:      *    >>k'            11
                   12089:      *          &   00000001
                   12090:      *            = 00000001
                   12091:      *      +1    = 00000010=2    =  codtabm(14,3)   
                   12092:      * Reverse h=6 and m=16?
                   12093:      * cptcoveff=log(16)/log(2)=4 covariate: 6-1=5=0101 reversed=1010 +1=2121 =>V1=2, V2=1, V3=2, V4=1.
                   12094:      * for (j=1 to cptcoveff) Vj=decodtabm(j,h,cptcoveff)
                   12095:      * decodtabm(h,j,cptcoveff)= (((h-1) >> (j-1)) & 1) +1 
                   12096:      * decodtabm(h,j,cptcoveff)= (h <= (1<<cptcoveff)?(((h-1) >> (j-1)) & 1) +1 : -1)
                   12097:      * V3=decodtabm(14,3,2**4)=2
                   12098:      *          h'=13   1101 =2^3+2^2+0x2^1+2^0
                   12099:      *(h-1) >> (j-1)    0011 =13 >> 2
                   12100:      *          &1 000000001
                   12101:      *           = 000000001
                   12102:      *         +1= 000000010 =2
                   12103:      *                  2211
                   12104:      *                  V1=1+1, V2=0+1, V3=1+1, V4=1+1
                   12105:      *                  V3=2
1.220     brouard  12106:                 * codtabm and decodtabm are identical
1.211     brouard  12107:      */
                   12108: 
1.145     brouard  12109: 
                   12110:  free_ivector(Ndum,-1,NCOVMAX);
                   12111: 
                   12112: 
1.126     brouard  12113:     
1.186     brouard  12114:   /* Initialisation of ----------- gnuplot -------------*/
1.126     brouard  12115:   strcpy(optionfilegnuplot,optionfilefiname);
                   12116:   if(mle==-3)
1.201     brouard  12117:     strcat(optionfilegnuplot,"-MORT_");
1.126     brouard  12118:   strcat(optionfilegnuplot,".gp");
                   12119: 
                   12120:   if((ficgp=fopen(optionfilegnuplot,"w"))==NULL) {
                   12121:     printf("Problem with file %s",optionfilegnuplot);
                   12122:   }
                   12123:   else{
1.204     brouard  12124:     fprintf(ficgp,"\n# IMaCh-%s\n", version); 
1.126     brouard  12125:     fprintf(ficgp,"# %s\n", optionfilegnuplot); 
1.141     brouard  12126:     //fprintf(ficgp,"set missing 'NaNq'\n");
                   12127:     fprintf(ficgp,"set datafile missing 'NaNq'\n");
1.126     brouard  12128:   }
                   12129:   /*  fclose(ficgp);*/
1.186     brouard  12130: 
                   12131: 
                   12132:   /* Initialisation of --------- index.htm --------*/
1.126     brouard  12133: 
                   12134:   strcpy(optionfilehtm,optionfilefiname); /* Main html file */
                   12135:   if(mle==-3)
1.201     brouard  12136:     strcat(optionfilehtm,"-MORT_");
1.126     brouard  12137:   strcat(optionfilehtm,".htm");
                   12138:   if((fichtm=fopen(optionfilehtm,"w"))==NULL)    {
1.131     brouard  12139:     printf("Problem with %s \n",optionfilehtm);
                   12140:     exit(0);
1.126     brouard  12141:   }
                   12142: 
                   12143:   strcpy(optionfilehtmcov,optionfilefiname); /* Only for matrix of covariance */
                   12144:   strcat(optionfilehtmcov,"-cov.htm");
                   12145:   if((fichtmcov=fopen(optionfilehtmcov,"w"))==NULL)    {
                   12146:     printf("Problem with %s \n",optionfilehtmcov), exit(0);
                   12147:   }
                   12148:   else{
                   12149:   fprintf(fichtmcov,"<html><head>\n<title>IMaCh Cov %s</title></head>\n <body><font size=\"2\">%s <br> %s</font> \
                   12150: <hr size=\"2\" color=\"#EC5E5E\"> \n\
1.204     brouard  12151: Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=1+age+%s<br>\n",\
1.126     brouard  12152:          optionfilehtmcov,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model);
                   12153:   }
                   12154: 
1.324   ! brouard  12155:   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  12156: <hr size=\"2\" color=\"#EC5E5E\"> \n\
                   12157: <font size=\"2\">IMaCh-%s <br> %s</font> \
1.126     brouard  12158: <hr size=\"2\" color=\"#EC5E5E\"> \n\
1.204     brouard  12159: Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=1+age+%s<br>\n\
1.126     brouard  12160: \n\
                   12161: <hr  size=\"2\" color=\"#EC5E5E\">\
                   12162:  <ul><li><h4>Parameter files</h4>\n\
                   12163:  - Parameter file: <a href=\"%s.%s\">%s.%s</a><br>\n\
                   12164:  - Copy of the parameter file: <a href=\"o%s\">o%s</a><br>\n\
                   12165:  - Log file of the run: <a href=\"%s\">%s</a><br>\n\
                   12166:  - Gnuplot file name: <a href=\"%s\">%s</a><br>\n\
                   12167:  - Date and time at start: %s</ul>\n",\
                   12168:          optionfilehtm,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model,\
                   12169:          optionfilefiname,optionfilext,optionfilefiname,optionfilext,\
                   12170:          fileres,fileres,\
                   12171:          filelog,filelog,optionfilegnuplot,optionfilegnuplot,strstart);
                   12172:   fflush(fichtm);
                   12173: 
                   12174:   strcpy(pathr,path);
                   12175:   strcat(pathr,optionfilefiname);
1.184     brouard  12176: #ifdef WIN32
                   12177:   _chdir(optionfilefiname); /* Move to directory named optionfile */
                   12178: #else
1.126     brouard  12179:   chdir(optionfilefiname); /* Move to directory named optionfile */
1.184     brouard  12180: #endif
                   12181:          
1.126     brouard  12182:   
1.220     brouard  12183:   /* Calculates basic frequencies. Computes observed prevalence at single age 
                   12184:                 and for any valid combination of covariates
1.126     brouard  12185:      and prints on file fileres'p'. */
1.251     brouard  12186:   freqsummary(fileres, p, pstart, agemin, agemax, s, agev, nlstate, imx, Tvaraff, invalidvarcomb, nbcode, ncodemax,mint,anint,strstart, \
1.227     brouard  12187:              firstpass, lastpass,  stepm,  weightopt, model);
1.126     brouard  12188: 
                   12189:   fprintf(fichtm,"\n");
1.286     brouard  12190:   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  12191:          ftol, stepm);
                   12192:   fprintf(fichtm,"\n<li>Number of fixed dummy covariates: ncovcol=%d ", ncovcol);
                   12193:   ncurrv=1;
                   12194:   for(i=ncurrv; i <=ncovcol; i++) fprintf(fichtm,"V%d ", i);
                   12195:   fprintf(fichtm,"\n<li> Number of fixed quantitative variables: nqv=%d ", nqv); 
                   12196:   ncurrv=i;
                   12197:   for(i=ncurrv; i <=ncurrv-1+nqv; i++) fprintf(fichtm,"V%d ", i);
1.290     brouard  12198:   fprintf(fichtm,"\n<li> Number of time varying (wave varying) dummy covariates: ntv=%d ", ntv);
1.274     brouard  12199:   ncurrv=i;
                   12200:   for(i=ncurrv; i <=ncurrv-1+ntv; i++) fprintf(fichtm,"V%d ", i);
1.290     brouard  12201:   fprintf(fichtm,"\n<li>Number of time varying  quantitative covariates: nqtv=%d ", nqtv);
1.274     brouard  12202:   ncurrv=i;
                   12203:   for(i=ncurrv; i <=ncurrv-1+nqtv; i++) fprintf(fichtm,"V%d ", i);
                   12204:   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", \
                   12205:           nlstate, ndeath, maxwav, mle, weightopt);
                   12206: 
                   12207:   fprintf(fichtm,"<h4> Diagram of states <a href=\"%s_.svg\">%s_.svg</a></h4> \n\
                   12208: <img src=\"%s_.svg\">", subdirf2(optionfilefiname,"D_"),subdirf2(optionfilefiname,"D_"),subdirf2(optionfilefiname,"D_"));
                   12209: 
                   12210:   
1.317     brouard  12211:   fprintf(fichtm,"\n<h4>Some descriptive statistics </h4>\n<br>Number of (used) observations=%d <br>\n\
1.126     brouard  12212: Youngest age at first (selected) pass %.2f, oldest age %.2f<br>\n\
                   12213: Interval (in months) between two waves: Min=%d Max=%d Mean=%.2lf<br>\n",\
1.274     brouard  12214:   imx,agemin,agemax,jmin,jmax,jmean);
1.126     brouard  12215:   pmmij= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
1.268     brouard  12216:   oldms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
                   12217:   newms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
                   12218:   savms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
                   12219:   oldm=oldms; newm=newms; savm=savms; /* Keeps fixed addresses to free */
1.218     brouard  12220: 
1.126     brouard  12221:   /* For Powell, parameters are in a vector p[] starting at p[1]
                   12222:      so we point p on param[1][1] so that p[1] maps on param[1][1][1] */
                   12223:   p=param[1][1]; /* *(*(*(param +1)+1)+0) */
                   12224: 
                   12225:   globpr=0; /* To get the number ipmx of contributions and the sum of weights*/
1.186     brouard  12226:   /* For mortality only */
1.126     brouard  12227:   if (mle==-3){
1.136     brouard  12228:     ximort=matrix(1,NDIM,1,NDIM); 
1.248     brouard  12229:     for(i=1;i<=NDIM;i++)
                   12230:       for(j=1;j<=NDIM;j++)
                   12231:        ximort[i][j]=0.;
1.186     brouard  12232:     /*     ximort=gsl_matrix_alloc(1,NDIM,1,NDIM); */
1.290     brouard  12233:     cens=ivector(firstobs,lastobs);
                   12234:     ageexmed=vector(firstobs,lastobs);
                   12235:     agecens=vector(firstobs,lastobs);
                   12236:     dcwave=ivector(firstobs,lastobs);
1.223     brouard  12237:                
1.126     brouard  12238:     for (i=1; i<=imx; i++){
                   12239:       dcwave[i]=-1;
                   12240:       for (m=firstpass; m<=lastpass; m++)
1.226     brouard  12241:        if (s[m][i]>nlstate) {
                   12242:          dcwave[i]=m;
                   12243:          /*    printf("i=%d j=%d s=%d dcwave=%d\n",i,j, s[j][i],dcwave[i]);*/
                   12244:          break;
                   12245:        }
1.126     brouard  12246:     }
1.226     brouard  12247:     
1.126     brouard  12248:     for (i=1; i<=imx; i++) {
                   12249:       if (wav[i]>0){
1.226     brouard  12250:        ageexmed[i]=agev[mw[1][i]][i];
                   12251:        j=wav[i];
                   12252:        agecens[i]=1.; 
                   12253:        
                   12254:        if (ageexmed[i]> 1 && wav[i] > 0){
                   12255:          agecens[i]=agev[mw[j][i]][i];
                   12256:          cens[i]= 1;
                   12257:        }else if (ageexmed[i]< 1) 
                   12258:          cens[i]= -1;
                   12259:        if (agedc[i]< AGESUP && agedc[i]>1 && dcwave[i]>firstpass && dcwave[i]<=lastpass)
                   12260:          cens[i]=0 ;
1.126     brouard  12261:       }
                   12262:       else cens[i]=-1;
                   12263:     }
                   12264:     
                   12265:     for (i=1;i<=NDIM;i++) {
                   12266:       for (j=1;j<=NDIM;j++)
1.226     brouard  12267:        ximort[i][j]=(i == j ? 1.0 : 0.0);
1.126     brouard  12268:     }
                   12269:     
1.302     brouard  12270:     p[1]=0.0268; p[NDIM]=0.083;
                   12271:     /* printf("%lf %lf", p[1], p[2]); */
1.126     brouard  12272:     
                   12273:     
1.136     brouard  12274: #ifdef GSL
                   12275:     printf("GSL optimization\n");  fprintf(ficlog,"Powell\n");
1.162     brouard  12276: #else
1.126     brouard  12277:     printf("Powell\n");  fprintf(ficlog,"Powell\n");
1.136     brouard  12278: #endif
1.201     brouard  12279:     strcpy(filerespow,"POW-MORT_"); 
                   12280:     strcat(filerespow,fileresu);
1.126     brouard  12281:     if((ficrespow=fopen(filerespow,"w"))==NULL) {
                   12282:       printf("Problem with resultfile: %s\n", filerespow);
                   12283:       fprintf(ficlog,"Problem with resultfile: %s\n", filerespow);
                   12284:     }
1.136     brouard  12285: #ifdef GSL
                   12286:     fprintf(ficrespow,"# GSL optimization\n# iter -2*LL");
1.162     brouard  12287: #else
1.126     brouard  12288:     fprintf(ficrespow,"# Powell\n# iter -2*LL");
1.136     brouard  12289: #endif
1.126     brouard  12290:     /*  for (i=1;i<=nlstate;i++)
                   12291:        for(j=1;j<=nlstate+ndeath;j++)
                   12292:        if(j!=i)fprintf(ficrespow," p%1d%1d",i,j);
                   12293:     */
                   12294:     fprintf(ficrespow,"\n");
1.136     brouard  12295: #ifdef GSL
                   12296:     /* gsl starts here */ 
                   12297:     T = gsl_multimin_fminimizer_nmsimplex;
                   12298:     gsl_multimin_fminimizer *sfm = NULL;
                   12299:     gsl_vector *ss, *x;
                   12300:     gsl_multimin_function minex_func;
                   12301: 
                   12302:     /* Initial vertex size vector */
                   12303:     ss = gsl_vector_alloc (NDIM);
                   12304:     
                   12305:     if (ss == NULL){
                   12306:       GSL_ERROR_VAL ("failed to allocate space for ss", GSL_ENOMEM, 0);
                   12307:     }
                   12308:     /* Set all step sizes to 1 */
                   12309:     gsl_vector_set_all (ss, 0.001);
                   12310: 
                   12311:     /* Starting point */
1.126     brouard  12312:     
1.136     brouard  12313:     x = gsl_vector_alloc (NDIM);
                   12314:     
                   12315:     if (x == NULL){
                   12316:       gsl_vector_free(ss);
                   12317:       GSL_ERROR_VAL ("failed to allocate space for x", GSL_ENOMEM, 0);
                   12318:     }
                   12319:   
                   12320:     /* Initialize method and iterate */
                   12321:     /*     p[1]=0.0268; p[NDIM]=0.083; */
1.186     brouard  12322:     /*     gsl_vector_set(x, 0, 0.0268); */
                   12323:     /*     gsl_vector_set(x, 1, 0.083); */
1.136     brouard  12324:     gsl_vector_set(x, 0, p[1]);
                   12325:     gsl_vector_set(x, 1, p[2]);
                   12326: 
                   12327:     minex_func.f = &gompertz_f;
                   12328:     minex_func.n = NDIM;
                   12329:     minex_func.params = (void *)&p; /* ??? */
                   12330:     
                   12331:     sfm = gsl_multimin_fminimizer_alloc (T, NDIM);
                   12332:     gsl_multimin_fminimizer_set (sfm, &minex_func, x, ss);
                   12333:     
                   12334:     printf("Iterations beginning .....\n\n");
                   12335:     printf("Iter. #    Intercept       Slope     -Log Likelihood     Simplex size\n");
                   12336: 
                   12337:     iteri=0;
                   12338:     while (rval == GSL_CONTINUE){
                   12339:       iteri++;
                   12340:       status = gsl_multimin_fminimizer_iterate(sfm);
                   12341:       
                   12342:       if (status) printf("error: %s\n", gsl_strerror (status));
                   12343:       fflush(0);
                   12344:       
                   12345:       if (status) 
                   12346:         break;
                   12347:       
                   12348:       rval = gsl_multimin_test_size (gsl_multimin_fminimizer_size (sfm), 1e-6);
                   12349:       ssval = gsl_multimin_fminimizer_size (sfm);
                   12350:       
                   12351:       if (rval == GSL_SUCCESS)
                   12352:         printf ("converged to a local maximum at\n");
                   12353:       
                   12354:       printf("%5d ", iteri);
                   12355:       for (it = 0; it < NDIM; it++){
                   12356:        printf ("%10.5f ", gsl_vector_get (sfm->x, it));
                   12357:       }
                   12358:       printf("f() = %-10.5f ssize = %.7f\n", sfm->fval, ssval);
                   12359:     }
                   12360:     
                   12361:     printf("\n\n Please note: Program should be run many times with varying starting points to detemine global maximum\n\n");
                   12362:     
                   12363:     gsl_vector_free(x); /* initial values */
                   12364:     gsl_vector_free(ss); /* inital step size */
                   12365:     for (it=0; it<NDIM; it++){
                   12366:       p[it+1]=gsl_vector_get(sfm->x,it);
                   12367:       fprintf(ficrespow," %.12lf", p[it]);
                   12368:     }
                   12369:     gsl_multimin_fminimizer_free (sfm); /* p *(sfm.x.data) et p *(sfm.x.data+1)  */
                   12370: #endif
                   12371: #ifdef POWELL
                   12372:      powell(p,ximort,NDIM,ftol,&iter,&fret,gompertz);
                   12373: #endif  
1.126     brouard  12374:     fclose(ficrespow);
                   12375:     
1.203     brouard  12376:     hesscov(matcov, hess, p, NDIM, delti, 1e-4, gompertz); 
1.126     brouard  12377: 
                   12378:     for(i=1; i <=NDIM; i++)
                   12379:       for(j=i+1;j<=NDIM;j++)
1.220     brouard  12380:                                matcov[i][j]=matcov[j][i];
1.126     brouard  12381:     
                   12382:     printf("\nCovariance matrix\n ");
1.203     brouard  12383:     fprintf(ficlog,"\nCovariance matrix\n ");
1.126     brouard  12384:     for(i=1; i <=NDIM; i++) {
                   12385:       for(j=1;j<=NDIM;j++){ 
1.220     brouard  12386:                                printf("%f ",matcov[i][j]);
                   12387:                                fprintf(ficlog,"%f ",matcov[i][j]);
1.126     brouard  12388:       }
1.203     brouard  12389:       printf("\n ");  fprintf(ficlog,"\n ");
1.126     brouard  12390:     }
                   12391:     
                   12392:     printf("iter=%d MLE=%f Eq=%lf*exp(%lf*(age-%d))\n",iter,-gompertz(p),p[1],p[2],agegomp);
1.193     brouard  12393:     for (i=1;i<=NDIM;i++) {
1.126     brouard  12394:       printf("%f [%f ; %f]\n",p[i],p[i]-2*sqrt(matcov[i][i]),p[i]+2*sqrt(matcov[i][i]));
1.193     brouard  12395:       fprintf(ficlog,"%f [%f ; %f]\n",p[i],p[i]-2*sqrt(matcov[i][i]),p[i]+2*sqrt(matcov[i][i]));
                   12396:     }
1.302     brouard  12397:     lsurv=vector(agegomp,AGESUP);
                   12398:     lpop=vector(agegomp,AGESUP);
                   12399:     tpop=vector(agegomp,AGESUP);
1.126     brouard  12400:     lsurv[agegomp]=100000;
                   12401:     
                   12402:     for (k=agegomp;k<=AGESUP;k++) {
                   12403:       agemortsup=k;
                   12404:       if (p[1]*exp(p[2]*(k-agegomp))>1) break;
                   12405:     }
                   12406:     
                   12407:     for (k=agegomp;k<agemortsup;k++)
                   12408:       lsurv[k+1]=lsurv[k]-lsurv[k]*(p[1]*exp(p[2]*(k-agegomp)));
                   12409:     
                   12410:     for (k=agegomp;k<agemortsup;k++){
                   12411:       lpop[k]=(lsurv[k]+lsurv[k+1])/2.;
                   12412:       sumlpop=sumlpop+lpop[k];
                   12413:     }
                   12414:     
                   12415:     tpop[agegomp]=sumlpop;
                   12416:     for (k=agegomp;k<(agemortsup-3);k++){
                   12417:       /*  tpop[k+1]=2;*/
                   12418:       tpop[k+1]=tpop[k]-lpop[k];
                   12419:     }
                   12420:     
                   12421:     
                   12422:     printf("\nAge   lx     qx    dx    Lx     Tx     e(x)\n");
                   12423:     for (k=agegomp;k<(agemortsup-2);k++) 
                   12424:       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]);
                   12425:     
                   12426:     
                   12427:     replace_back_to_slash(pathc,pathcd); /* Even gnuplot wants a / */
1.220     brouard  12428:                ageminpar=50;
                   12429:                agemaxpar=100;
1.194     brouard  12430:     if(ageminpar == AGEOVERFLOW ||agemaxpar == AGEOVERFLOW){
                   12431:        printf("Warning! Error in gnuplot file with ageminpar %f or agemaxpar %f overflow\n\
                   12432: This is probably because your parameter file doesn't \n  contain the exact number of lines (or columns) corresponding to your model line.\n\
                   12433: Please run with mle=-1 to get a correct covariance matrix.\n",ageminpar,agemaxpar);
                   12434:        fprintf(ficlog,"Warning! Error in gnuplot file with ageminpar %f or agemaxpar %f overflow\n\
                   12435: This is probably because your parameter file doesn't \n  contain the exact number of lines (or columns) corresponding to your model line.\n\
                   12436: Please run with mle=-1 to get a correct covariance matrix.\n",ageminpar,agemaxpar);
1.220     brouard  12437:     }else{
                   12438:                        printf("Warning! ageminpar %f and agemaxpar %f have been fixed because for simplification until it is fixed...\n\n",ageminpar,agemaxpar);
                   12439:                        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  12440:       printinggnuplotmort(fileresu, optionfilefiname,ageminpar,agemaxpar,fage, pathc,p);
1.220     brouard  12441:                }
1.201     brouard  12442:     printinghtmlmort(fileresu,title,datafile, firstpass, lastpass, \
1.126     brouard  12443:                     stepm, weightopt,\
                   12444:                     model,imx,p,matcov,agemortsup);
                   12445:     
1.302     brouard  12446:     free_vector(lsurv,agegomp,AGESUP);
                   12447:     free_vector(lpop,agegomp,AGESUP);
                   12448:     free_vector(tpop,agegomp,AGESUP);
1.220     brouard  12449:     free_matrix(ximort,1,NDIM,1,NDIM);
1.290     brouard  12450:     free_ivector(dcwave,firstobs,lastobs);
                   12451:     free_vector(agecens,firstobs,lastobs);
                   12452:     free_vector(ageexmed,firstobs,lastobs);
                   12453:     free_ivector(cens,firstobs,lastobs);
1.220     brouard  12454: #ifdef GSL
1.136     brouard  12455: #endif
1.186     brouard  12456:   } /* Endof if mle==-3 mortality only */
1.205     brouard  12457:   /* Standard  */
                   12458:   else{ /* For mle !=- 3, could be 0 or 1 or 4 etc. */
                   12459:     globpr=0;/* Computes sum of likelihood for globpr=1 and funcone */
                   12460:     /* Computes likelihood for initial parameters, uses funcone to compute gpimx and gsw */
1.132     brouard  12461:     likelione(ficres, p, npar, nlstate, &globpr, &ipmx, &sw, &fretone, funcone); /* Prints the contributions to the likelihood */
1.126     brouard  12462:     printf("First Likeli=%12.6f ipmx=%ld sw=%12.6f",fretone,ipmx,sw);
                   12463:     for (k=1; k<=npar;k++)
                   12464:       printf(" %d %8.5f",k,p[k]);
                   12465:     printf("\n");
1.205     brouard  12466:     if(mle>=1){ /* Could be 1 or 2, Real Maximization */
                   12467:       /* mlikeli uses func not funcone */
1.247     brouard  12468:       /* for(i=1;i<nlstate;i++){ */
                   12469:       /*       /\*reducing xi for 1 to npar to 1 to ncovmodel; *\/ */
                   12470:       /*    mlikeli(ficres,p, ncovmodel, ncovmodel, nlstate, ftol, funcnoprod); */
                   12471:       /* } */
1.205     brouard  12472:       mlikeli(ficres,p, npar, ncovmodel, nlstate, ftol, func);
                   12473:     }
                   12474:     if(mle==0) {/* No optimization, will print the likelihoods for the datafile */
                   12475:       globpr=0;/* Computes sum of likelihood for globpr=1 and funcone */
                   12476:       /* Computes likelihood for initial parameters, uses funcone to compute gpimx and gsw */
                   12477:       likelione(ficres, p, npar, nlstate, &globpr, &ipmx, &sw, &fretone, funcone); /* Prints the contributions to the likelihood */
                   12478:     }
                   12479:     globpr=1; /* again, to print the individual contributions using computed gpimx and gsw */
1.126     brouard  12480:     likelione(ficres, p, npar, nlstate, &globpr, &ipmx, &sw, &fretone, funcone); /* Prints the contributions to the likelihood */
                   12481:     printf("Second Likeli=%12.6f ipmx=%ld sw=%12.6f",fretone,ipmx,sw);
                   12482:     for (k=1; k<=npar;k++)
                   12483:       printf(" %d %8.5f",k,p[k]);
                   12484:     printf("\n");
                   12485:     
                   12486:     /*--------- results files --------------*/
1.283     brouard  12487:     /* 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  12488:     
                   12489:     
                   12490:     fprintf(ficres,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
1.319     brouard  12491:     printf("# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n"); /* Printing model equation */
1.126     brouard  12492:     fprintf(ficlog,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
1.319     brouard  12493: 
                   12494:     printf("#model=  1      +     age ");
                   12495:     fprintf(ficres,"#model=  1      +     age ");
                   12496:     fprintf(ficlog,"#model=  1      +     age ");
                   12497:     fprintf(fichtm,"\n<ul><li> model=1+age+%s\n \
                   12498: </ul>", model);
                   12499: 
                   12500:     fprintf(fichtm,"\n<table style=\"text-align:center; border: 1px solid\">\n");
                   12501:     fprintf(fichtm, "<tr><th>Model=</th><th>1</th><th>+ age</th>");
                   12502:     if(nagesqr==1){
                   12503:       printf("  + age*age  ");
                   12504:       fprintf(ficres,"  + age*age  ");
                   12505:       fprintf(ficlog,"  + age*age  ");
                   12506:       fprintf(fichtm, "<th>+ age*age</th>");
                   12507:     }
                   12508:     for(j=1;j <=ncovmodel-2;j++){
                   12509:       if(Typevar[j]==0) {
                   12510:        printf("  +      V%d  ",Tvar[j]);
                   12511:        fprintf(ficres,"  +      V%d  ",Tvar[j]);
                   12512:        fprintf(ficlog,"  +      V%d  ",Tvar[j]);
                   12513:        fprintf(fichtm, "<th>+ V%d</th>",Tvar[j]);
                   12514:       }else if(Typevar[j]==1) {
                   12515:        printf("  +    V%d*age ",Tvar[j]);
                   12516:        fprintf(ficres,"  +    V%d*age ",Tvar[j]);
                   12517:        fprintf(ficlog,"  +    V%d*age ",Tvar[j]);
                   12518:        fprintf(fichtm, "<th>+  V%d*age</th>",Tvar[j]);
                   12519:       }else if(Typevar[j]==2) {
                   12520:        printf("  +    V%d*V%d ",Tvard[Tposprod[j]][1],Tvard[Tposprod[j]][2]);
                   12521:        fprintf(ficres,"  +    V%d*V%d ",Tvard[Tposprod[j]][1],Tvard[Tposprod[j]][2]);
                   12522:        fprintf(ficlog,"  +    V%d*V%d ",Tvard[Tposprod[j]][1],Tvard[Tposprod[j]][2]);
                   12523:        fprintf(fichtm, "<th>+  V%d*V%d</th>",Tvard[Tposprod[j]][1],Tvard[Tposprod[j]][2]);
                   12524:       }
                   12525:     }
                   12526:     printf("\n");
                   12527:     fprintf(ficres,"\n");
                   12528:     fprintf(ficlog,"\n");
                   12529:     fprintf(fichtm, "</tr>");
                   12530:     fprintf(fichtm, "\n");
                   12531:     
                   12532:     
1.126     brouard  12533:     for(i=1,jk=1; i <=nlstate; i++){
                   12534:       for(k=1; k <=(nlstate+ndeath); k++){
1.225     brouard  12535:        if (k != i) {
1.319     brouard  12536:          fprintf(fichtm, "<tr>");
1.225     brouard  12537:          printf("%d%d ",i,k);
                   12538:          fprintf(ficlog,"%d%d ",i,k);
                   12539:          fprintf(ficres,"%1d%1d ",i,k);
1.319     brouard  12540:          fprintf(fichtm, "<td>%1d%1d</td>",i,k);
1.225     brouard  12541:          for(j=1; j <=ncovmodel; j++){
                   12542:            printf("%12.7f ",p[jk]);
                   12543:            fprintf(ficlog,"%12.7f ",p[jk]);
                   12544:            fprintf(ficres,"%12.7f ",p[jk]);
1.319     brouard  12545:            fprintf(fichtm, "<td>%12.7f</td>",p[jk]);
1.225     brouard  12546:            jk++; 
                   12547:          }
                   12548:          printf("\n");
                   12549:          fprintf(ficlog,"\n");
                   12550:          fprintf(ficres,"\n");
1.319     brouard  12551:          fprintf(fichtm, "</tr>\n");
1.225     brouard  12552:        }
1.126     brouard  12553:       }
                   12554:     }
1.319     brouard  12555:     /* fprintf(fichtm,"</tr>\n"); */
                   12556:     fprintf(fichtm,"</table>\n");
                   12557:     fprintf(fichtm, "\n");
                   12558: 
1.203     brouard  12559:     if(mle != 0){
                   12560:       /* Computing hessian and covariance matrix only at a peak of the Likelihood, that is after optimization */
1.126     brouard  12561:       ftolhess=ftol; /* Usually correct */
1.203     brouard  12562:       hesscov(matcov, hess, p, npar, delti, ftolhess, func);
                   12563:       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");
                   12564:       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");
1.322     brouard  12565:       fprintf(fichtm, "\n<p>The Wald test results are output only if the maximimzation of the Likelihood is performed (mle=1)\n</br>Parameters, Wald tests and Wald-based confidence intervals\n</br> W is simply the result of the division of the parameter by the square root of covariance of the parameter.\n</br> And Wald-based confidence intervals plus and minus 1.96 * W \n </br> It might be better to visualize the covariance matrix. See the page '<a href=\"%s\">Matrix of variance-covariance of one-step probabilities and its graphs</a>'.\n</br>",optionfilehtmcov);
1.319     brouard  12566:       fprintf(fichtm,"\n<table style=\"text-align:center; border: 1px solid\">");
                   12567:       fprintf(fichtm, "\n<tr><th>Model=</th><th>1</th><th>+ age</th>");
                   12568:       if(nagesqr==1){
                   12569:        printf("  + age*age  ");
                   12570:        fprintf(ficres,"  + age*age  ");
                   12571:        fprintf(ficlog,"  + age*age  ");
                   12572:        fprintf(fichtm, "<th>+ age*age</th>");
                   12573:       }
                   12574:       for(j=1;j <=ncovmodel-2;j++){
                   12575:        if(Typevar[j]==0) {
                   12576:          printf("  +      V%d  ",Tvar[j]);
                   12577:          fprintf(fichtm, "<th>+ V%d</th>",Tvar[j]);
                   12578:        }else if(Typevar[j]==1) {
                   12579:          printf("  +    V%d*age ",Tvar[j]);
                   12580:          fprintf(fichtm, "<th>+  V%d*age</th>",Tvar[j]);
                   12581:        }else if(Typevar[j]==2) {
                   12582:          fprintf(fichtm, "<th>+  V%d*V%d</th>",Tvard[Tposprod[j]][1],Tvard[Tposprod[j]][2]);
                   12583:        }
                   12584:       }
                   12585:       fprintf(fichtm, "</tr>\n");
                   12586:  
1.203     brouard  12587:       for(i=1,jk=1; i <=nlstate; i++){
1.225     brouard  12588:        for(k=1; k <=(nlstate+ndeath); k++){
                   12589:          if (k != i) {
1.319     brouard  12590:            fprintf(fichtm, "<tr valign=top>");
1.225     brouard  12591:            printf("%d%d ",i,k);
                   12592:            fprintf(ficlog,"%d%d ",i,k);
1.319     brouard  12593:            fprintf(fichtm, "<td>%1d%1d</td>",i,k);
1.225     brouard  12594:            for(j=1; j <=ncovmodel; j++){
1.319     brouard  12595:              wald=p[jk]/sqrt(matcov[jk][jk]);
1.324   ! brouard  12596:              printf("%12.7f(%12.7f) W=%8.3f CI=[%12.7f ; %12.7f] ",p[jk],sqrt(matcov[jk][jk]), p[jk]/sqrt(matcov[jk][jk]), p[jk]-1.96*sqrt(matcov[jk][jk]),p[jk]+1.96*sqrt(matcov[jk][jk]));
        !          12597:              fprintf(ficlog,"%12.7f(%12.7f) W=%8.3f CI=[%12.7f ; %12.7f] ",p[jk],sqrt(matcov[jk][jk]), p[jk]/sqrt(matcov[jk][jk]), p[jk]-1.96*sqrt(matcov[jk][jk]),p[jk]+1.96*sqrt(matcov[jk][jk]));
1.319     brouard  12598:              if(fabs(wald) > 1.96){
1.321     brouard  12599:                fprintf(fichtm, "<td><b>%12.7f</b></br> (%12.7f)</br>",p[jk],sqrt(matcov[jk][jk]));
1.319     brouard  12600:              }else{
                   12601:                fprintf(fichtm, "<td>%12.7f (%12.7f)</br>",p[jk],sqrt(matcov[jk][jk]));
                   12602:              }
1.324   ! brouard  12603:              fprintf(fichtm,"W=%8.3f</br>",wald);
1.319     brouard  12604:              fprintf(fichtm,"[%12.7f;%12.7f]</br></td>", p[jk]-1.96*sqrt(matcov[jk][jk]),p[jk]+1.96*sqrt(matcov[jk][jk]));
1.225     brouard  12605:              jk++; 
                   12606:            }
                   12607:            printf("\n");
                   12608:            fprintf(ficlog,"\n");
1.319     brouard  12609:            fprintf(fichtm, "</tr>\n");
1.225     brouard  12610:          }
                   12611:        }
1.193     brouard  12612:       }
1.203     brouard  12613:     } /* end of hesscov and Wald tests */
1.319     brouard  12614:     fprintf(fichtm,"</table>\n");
1.225     brouard  12615:     
1.203     brouard  12616:     /*  */
1.126     brouard  12617:     fprintf(ficres,"# Scales (for hessian or gradient estimation)\n");
                   12618:     printf("# Scales (for hessian or gradient estimation)\n");
                   12619:     fprintf(ficlog,"# Scales (for hessian or gradient estimation)\n");
                   12620:     for(i=1,jk=1; i <=nlstate; i++){
                   12621:       for(j=1; j <=nlstate+ndeath; j++){
1.225     brouard  12622:        if (j!=i) {
                   12623:          fprintf(ficres,"%1d%1d",i,j);
                   12624:          printf("%1d%1d",i,j);
                   12625:          fprintf(ficlog,"%1d%1d",i,j);
                   12626:          for(k=1; k<=ncovmodel;k++){
                   12627:            printf(" %.5e",delti[jk]);
                   12628:            fprintf(ficlog," %.5e",delti[jk]);
                   12629:            fprintf(ficres," %.5e",delti[jk]);
                   12630:            jk++;
                   12631:          }
                   12632:          printf("\n");
                   12633:          fprintf(ficlog,"\n");
                   12634:          fprintf(ficres,"\n");
                   12635:        }
1.126     brouard  12636:       }
                   12637:     }
                   12638:     
                   12639:     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  12640:     if(mle >= 1) /* To big for the screen */
1.126     brouard  12641:       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");
                   12642:     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");
                   12643:     /* # 121 Var(a12)\n\ */
                   12644:     /* # 122 Cov(b12,a12) Var(b12)\n\ */
                   12645:     /* # 131 Cov(a13,a12) Cov(a13,b12, Var(a13)\n\ */
                   12646:     /* # 132 Cov(b13,a12) Cov(b13,b12, Cov(b13,a13) Var(b13)\n\ */
                   12647:     /* # 212 Cov(a21,a12) Cov(a21,b12, Cov(a21,a13) Cov(a21,b13) Var(a21)\n\ */
                   12648:     /* # 212 Cov(b21,a12) Cov(b21,b12, Cov(b21,a13) Cov(b21,b13) Cov(b21,a21) Var(b21)\n\ */
                   12649:     /* # 232 Cov(a23,a12) Cov(a23,b12, Cov(a23,a13) Cov(a23,b13) Cov(a23,a21) Cov(a23,b21) Var(a23)\n\ */
                   12650:     /* # 232 Cov(b23,a12) Cov(b23,b12) ... Var (b23)\n" */
                   12651:     
                   12652:     
                   12653:     /* Just to have a covariance matrix which will be more understandable
                   12654:        even is we still don't want to manage dictionary of variables
                   12655:     */
                   12656:     for(itimes=1;itimes<=2;itimes++){
                   12657:       jj=0;
                   12658:       for(i=1; i <=nlstate; i++){
1.225     brouard  12659:        for(j=1; j <=nlstate+ndeath; j++){
                   12660:          if(j==i) continue;
                   12661:          for(k=1; k<=ncovmodel;k++){
                   12662:            jj++;
                   12663:            ca[0]= k+'a'-1;ca[1]='\0';
                   12664:            if(itimes==1){
                   12665:              if(mle>=1)
                   12666:                printf("#%1d%1d%d",i,j,k);
                   12667:              fprintf(ficlog,"#%1d%1d%d",i,j,k);
                   12668:              fprintf(ficres,"#%1d%1d%d",i,j,k);
                   12669:            }else{
                   12670:              if(mle>=1)
                   12671:                printf("%1d%1d%d",i,j,k);
                   12672:              fprintf(ficlog,"%1d%1d%d",i,j,k);
                   12673:              fprintf(ficres,"%1d%1d%d",i,j,k);
                   12674:            }
                   12675:            ll=0;
                   12676:            for(li=1;li <=nlstate; li++){
                   12677:              for(lj=1;lj <=nlstate+ndeath; lj++){
                   12678:                if(lj==li) continue;
                   12679:                for(lk=1;lk<=ncovmodel;lk++){
                   12680:                  ll++;
                   12681:                  if(ll<=jj){
                   12682:                    cb[0]= lk +'a'-1;cb[1]='\0';
                   12683:                    if(ll<jj){
                   12684:                      if(itimes==1){
                   12685:                        if(mle>=1)
                   12686:                          printf(" Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
                   12687:                        fprintf(ficlog," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
                   12688:                        fprintf(ficres," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
                   12689:                      }else{
                   12690:                        if(mle>=1)
                   12691:                          printf(" %.5e",matcov[jj][ll]); 
                   12692:                        fprintf(ficlog," %.5e",matcov[jj][ll]); 
                   12693:                        fprintf(ficres," %.5e",matcov[jj][ll]); 
                   12694:                      }
                   12695:                    }else{
                   12696:                      if(itimes==1){
                   12697:                        if(mle>=1)
                   12698:                          printf(" Var(%s%1d%1d)",ca,i,j);
                   12699:                        fprintf(ficlog," Var(%s%1d%1d)",ca,i,j);
                   12700:                        fprintf(ficres," Var(%s%1d%1d)",ca,i,j);
                   12701:                      }else{
                   12702:                        if(mle>=1)
                   12703:                          printf(" %.7e",matcov[jj][ll]); 
                   12704:                        fprintf(ficlog," %.7e",matcov[jj][ll]); 
                   12705:                        fprintf(ficres," %.7e",matcov[jj][ll]); 
                   12706:                      }
                   12707:                    }
                   12708:                  }
                   12709:                } /* end lk */
                   12710:              } /* end lj */
                   12711:            } /* end li */
                   12712:            if(mle>=1)
                   12713:              printf("\n");
                   12714:            fprintf(ficlog,"\n");
                   12715:            fprintf(ficres,"\n");
                   12716:            numlinepar++;
                   12717:          } /* end k*/
                   12718:        } /*end j */
1.126     brouard  12719:       } /* end i */
                   12720:     } /* end itimes */
                   12721:     
                   12722:     fflush(ficlog);
                   12723:     fflush(ficres);
1.225     brouard  12724:     while(fgets(line, MAXLINE, ficpar)) {
                   12725:       /* If line starts with a # it is a comment */
                   12726:       if (line[0] == '#') {
                   12727:        numlinepar++;
                   12728:        fputs(line,stdout);
                   12729:        fputs(line,ficparo);
                   12730:        fputs(line,ficlog);
1.299     brouard  12731:        fputs(line,ficres);
1.225     brouard  12732:        continue;
                   12733:       }else
                   12734:        break;
                   12735:     }
                   12736:     
1.209     brouard  12737:     /* while((c=getc(ficpar))=='#' && c!= EOF){ */
                   12738:     /*   ungetc(c,ficpar); */
                   12739:     /*   fgets(line, MAXLINE, ficpar); */
                   12740:     /*   fputs(line,stdout); */
                   12741:     /*   fputs(line,ficparo); */
                   12742:     /* } */
                   12743:     /* ungetc(c,ficpar); */
1.126     brouard  12744:     
                   12745:     estepm=0;
1.209     brouard  12746:     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  12747:       
                   12748:       if (num_filled != 6) {
                   12749:        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);
                   12750:        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);
                   12751:        goto end;
                   12752:       }
                   12753:       printf("agemin=%lf agemax=%lf bage=%lf fage=%lf estepm=%d ftolpl=%lf\n",ageminpar,agemaxpar, bage, fage, estepm, ftolpl);
                   12754:     }
                   12755:     /* ftolpl=6*ftol*1.e5; /\* 6.e-3 make convergences in less than 80 loops for the prevalence limit *\/ */
                   12756:     /*ftolpl=6.e-4;*/ /* 6.e-3 make convergences in less than 80 loops for the prevalence limit */
                   12757:     
1.209     brouard  12758:     /* fscanf(ficpar,"agemin=%lf agemax=%lf bage=%lf fage=%lf estepm=%d ftolpl=%\n",&ageminpar,&agemaxpar, &bage, &fage, &estepm); */
1.126     brouard  12759:     if (estepm==0 || estepm < stepm) estepm=stepm;
                   12760:     if (fage <= 2) {
                   12761:       bage = ageminpar;
                   12762:       fage = agemaxpar;
                   12763:     }
                   12764:     
                   12765:     fprintf(ficres,"# agemin agemax for life expectancy, bage fage (if mle==0 ie no data nor Max likelihood).\n");
1.211     brouard  12766:     fprintf(ficres,"agemin=%.0f agemax=%.0f bage=%.0f fage=%.0f estepm=%d ftolpl=%e\n",ageminpar,agemaxpar,bage,fage, estepm, ftolpl);
                   12767:     fprintf(ficparo,"agemin=%.0f agemax=%.0f bage=%.0f fage=%.0f estepm=%d, ftolpl=%e\n",ageminpar,agemaxpar,bage,fage, estepm, ftolpl);
1.220     brouard  12768:                
1.186     brouard  12769:     /* Other stuffs, more or less useful */    
1.254     brouard  12770:     while(fgets(line, MAXLINE, ficpar)) {
                   12771:       /* If line starts with a # it is a comment */
                   12772:       if (line[0] == '#') {
                   12773:        numlinepar++;
                   12774:        fputs(line,stdout);
                   12775:        fputs(line,ficparo);
                   12776:        fputs(line,ficlog);
1.299     brouard  12777:        fputs(line,ficres);
1.254     brouard  12778:        continue;
                   12779:       }else
                   12780:        break;
                   12781:     }
                   12782: 
                   12783:     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){
                   12784:       
                   12785:       if (num_filled != 7) {
                   12786:        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);
                   12787:        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);
                   12788:        goto end;
                   12789:       }
                   12790:       printf("begin-prev-date=%.lf/%.lf/%.lf end-prev-date=%.lf/%.lf/%.lf mov_average=%d\n",jprev1, mprev1,anprev1,jprev2, mprev2,anprev2,mobilav);
                   12791:       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);
                   12792:       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);
                   12793:       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  12794:     }
1.254     brouard  12795: 
                   12796:     while(fgets(line, MAXLINE, ficpar)) {
                   12797:       /* If line starts with a # it is a comment */
                   12798:       if (line[0] == '#') {
                   12799:        numlinepar++;
                   12800:        fputs(line,stdout);
                   12801:        fputs(line,ficparo);
                   12802:        fputs(line,ficlog);
1.299     brouard  12803:        fputs(line,ficres);
1.254     brouard  12804:        continue;
                   12805:       }else
                   12806:        break;
1.126     brouard  12807:     }
                   12808:     
                   12809:     
                   12810:     dateprev1=anprev1+(mprev1-1)/12.+(jprev1-1)/365.;
                   12811:     dateprev2=anprev2+(mprev2-1)/12.+(jprev2-1)/365.;
                   12812:     
1.254     brouard  12813:     if((num_filled=sscanf(line,"pop_based=%d\n",&popbased)) !=EOF){
                   12814:       if (num_filled != 1) {
                   12815:        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);
                   12816:        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);
                   12817:        goto end;
                   12818:       }
                   12819:       printf("pop_based=%d\n",popbased);
                   12820:       fprintf(ficlog,"pop_based=%d\n",popbased);
                   12821:       fprintf(ficparo,"pop_based=%d\n",popbased);   
                   12822:       fprintf(ficres,"pop_based=%d\n",popbased);   
                   12823:     }
                   12824:      
1.258     brouard  12825:     /* Results */
1.307     brouard  12826:     endishere=0;
1.258     brouard  12827:     nresult=0;
1.308     brouard  12828:     parameterline=0;
1.258     brouard  12829:     do{
                   12830:       if(!fgets(line, MAXLINE, ficpar)){
                   12831:        endishere=1;
1.308     brouard  12832:        parameterline=15;
1.258     brouard  12833:       }else if (line[0] == '#') {
                   12834:        /* If line starts with a # it is a comment */
1.254     brouard  12835:        numlinepar++;
                   12836:        fputs(line,stdout);
                   12837:        fputs(line,ficparo);
                   12838:        fputs(line,ficlog);
1.299     brouard  12839:        fputs(line,ficres);
1.254     brouard  12840:        continue;
1.258     brouard  12841:       }else if(sscanf(line,"prevforecast=%[^\n]\n",modeltemp))
                   12842:        parameterline=11;
1.296     brouard  12843:       else if(sscanf(line,"prevbackcast=%[^\n]\n",modeltemp))
1.258     brouard  12844:        parameterline=12;
1.307     brouard  12845:       else if(sscanf(line,"result:%[^\n]\n",modeltemp)){
1.258     brouard  12846:        parameterline=13;
1.307     brouard  12847:       }
1.258     brouard  12848:       else{
                   12849:        parameterline=14;
1.254     brouard  12850:       }
1.308     brouard  12851:       switch (parameterline){ /* =0 only if only comments */
1.258     brouard  12852:       case 11:
1.296     brouard  12853:        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)){
                   12854:                  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  12855:          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);
                   12856:          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);
                   12857:          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);
                   12858:          /* day and month of proj2 are not used but only year anproj2.*/
1.273     brouard  12859:          dateproj1=anproj1+(mproj1-1)/12.+(jproj1-1)/365.;
                   12860:          dateproj2=anproj2+(mproj2-1)/12.+(jproj2-1)/365.;
1.296     brouard  12861:           prvforecast = 1;
                   12862:        } 
                   12863:        else if((num_filled=sscanf(line,"prevforecast=%d yearsfproj=%lf mobil_average=%d\n",&prevfcast,&yrfproj,&mobilavproj)) !=EOF){/* && (num_filled == 3))*/
1.313     brouard  12864:          printf("prevforecast=%d yearsfproj=%.2lf mobil_average=%d\n",prevfcast,yrfproj,mobilavproj);
                   12865:          fprintf(ficlog,"prevforecast=%d yearsfproj=%.2lf mobil_average=%d\n",prevfcast,yrfproj,mobilavproj);
                   12866:          fprintf(ficres,"prevforecast=%d yearsfproj=%.2lf mobil_average=%d\n",prevfcast,yrfproj,mobilavproj);
1.296     brouard  12867:           prvforecast = 2;
                   12868:        }
                   12869:        else {
                   12870:          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);
                   12871:          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);
                   12872:          goto end;
1.258     brouard  12873:        }
1.254     brouard  12874:        break;
1.258     brouard  12875:       case 12:
1.296     brouard  12876:        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)){
                   12877:           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);
                   12878:          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);
                   12879:          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);
                   12880:          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);
                   12881:          /* day and month of back2 are not used but only year anback2.*/
1.273     brouard  12882:          dateback1=anback1+(mback1-1)/12.+(jback1-1)/365.;
                   12883:          dateback2=anback2+(mback2-1)/12.+(jback2-1)/365.;
1.296     brouard  12884:           prvbackcast = 1;
                   12885:        } 
                   12886:        else if((num_filled=sscanf(line,"prevbackcast=%d yearsbproj=%lf mobil_average=%d\n",&prevbcast,&yrbproj,&mobilavproj)) ==3){/* && (num_filled == 3))*/
1.313     brouard  12887:          printf("prevbackcast=%d yearsbproj=%.2lf mobil_average=%d\n",prevbcast,yrbproj,mobilavproj);
                   12888:          fprintf(ficlog,"prevbackcast=%d yearsbproj=%.2lf mobil_average=%d\n",prevbcast,yrbproj,mobilavproj);
                   12889:          fprintf(ficres,"prevbackcast=%d yearsbproj=%.2lf mobil_average=%d\n",prevbcast,yrbproj,mobilavproj);
1.296     brouard  12890:           prvbackcast = 2;
                   12891:        }
                   12892:        else {
                   12893:          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);
                   12894:          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);
                   12895:          goto end;
1.258     brouard  12896:        }
1.230     brouard  12897:        break;
1.258     brouard  12898:       case 13:
1.307     brouard  12899:        num_filled=sscanf(line,"result:%[^\n]\n",resultline);
                   12900:        nresult++; /* Sum of resultlines */
                   12901:        printf("Result %d: result:%s\n",nresult, resultline);
1.318     brouard  12902:        if(nresult > MAXRESULTLINESPONE-1){
                   12903:          printf("ERROR: Current version of IMaCh limits the number of resultlines to %d, you used %d\nYou can use the 'r' parameter file '%s' which uses option mle=0 to get other results. ",MAXRESULTLINESPONE-1,nresult,rfileres);
                   12904:          fprintf(ficlog,"ERROR: Current version of IMaCh limits the number of resultlines to %d, you used %d\nYou can use the 'r' parameter file '%s' which uses option mle=0 to get other results. ",MAXRESULTLINESPONE-1,nresult,rfileres);
1.307     brouard  12905:          goto end;
                   12906:        }
1.310     brouard  12907:        if(!decoderesult(resultline, nresult)){ /* Fills TKresult[nresult] combination and Tresult[nresult][k4+1] combination values */
1.314     brouard  12908:          fprintf(ficparo,"result: %s\n",resultline);
                   12909:          fprintf(ficres,"result: %s\n",resultline);
                   12910:          fprintf(ficlog,"result: %s\n",resultline);
1.310     brouard  12911:        } else
                   12912:          goto end;
1.307     brouard  12913:        break;
                   12914:       case 14:
                   12915:        printf("Error: Unknown command '%s'\n",line);
                   12916:        fprintf(ficlog,"Error: Unknown command '%s'\n",line);
1.314     brouard  12917:        if(line[0] == ' ' || line[0] == '\n'){
                   12918:          printf("It should not be an empty line '%s'\n",line);
                   12919:          fprintf(ficlog,"It should not be an empty line '%s'\n",line);
                   12920:        }         
1.307     brouard  12921:        if(ncovmodel >=2 && nresult==0 ){
                   12922:          printf("ERROR: no result lines! It should be at minimum 'result: V2=0 V1=1 or result:.' %s\n",line);
                   12923:          fprintf(ficlog,"ERROR: no result lines! It should be at minimum 'result: V2=0 V1=1 or result:.' %s\n",line);
1.258     brouard  12924:        }
1.307     brouard  12925:        /* goto end; */
                   12926:        break;
1.308     brouard  12927:       case 15:
                   12928:        printf("End of resultlines.\n");
                   12929:        fprintf(ficlog,"End of resultlines.\n");
                   12930:        break;
                   12931:       default: /* parameterline =0 */
1.307     brouard  12932:        nresult=1;
                   12933:        decoderesult(".",nresult ); /* No covariate */
1.258     brouard  12934:       } /* End switch parameterline */
                   12935:     }while(endishere==0); /* End do */
1.126     brouard  12936:     
1.230     brouard  12937:     /* freqsummary(fileres, agemin, agemax, s, agev, nlstate, imx,Tvaraff,nbcode, ncodemax,mint,anint); */
1.145     brouard  12938:     /* ,dateprev1,dateprev2,jprev1, mprev1,anprev1,jprev2, mprev2,anprev2); */
1.126     brouard  12939:     
                   12940:     replace_back_to_slash(pathc,pathcd); /* Even gnuplot wants a / */
1.194     brouard  12941:     if(ageminpar == AGEOVERFLOW ||agemaxpar == -AGEOVERFLOW){
1.230     brouard  12942:       printf("Warning! Error in gnuplot file with ageminpar %f or agemaxpar %f overflow\n\
1.194     brouard  12943: This is probably because your parameter file doesn't \n  contain the exact number of lines (or columns) corresponding to your model line.\n\
                   12944: Please run with mle=-1 to get a correct covariance matrix.\n",ageminpar,agemaxpar);
1.230     brouard  12945:       fprintf(ficlog,"Warning! Error in gnuplot file with ageminpar %f or agemaxpar %f overflow\n\
1.194     brouard  12946: This is probably because your parameter file doesn't \n  contain the exact number of lines (or columns) corresponding to your model line.\n\
                   12947: Please run with mle=-1 to get a correct covariance matrix.\n",ageminpar,agemaxpar);
1.220     brouard  12948:     }else{
1.270     brouard  12949:       /* printinggnuplot(fileresu, optionfilefiname,ageminpar,agemaxpar,fage, prevfcast, backcast, pathc,p, (int)anproj1-(int)agemin, (int)anback1-(int)agemax+1); */
1.296     brouard  12950:       /* It seems that anprojd which is computed from the mean year at interview which is known yet because of freqsummary */
                   12951:       /* date2dmy(dateintmean,&jintmean,&mintmean,&aintmean); */ /* Done in freqsummary */
                   12952:       if(prvforecast==1){
                   12953:         dateprojd=(jproj1+12*mproj1+365*anproj1)/365;
                   12954:         jprojd=jproj1;
                   12955:         mprojd=mproj1;
                   12956:         anprojd=anproj1;
                   12957:         dateprojf=(jproj2+12*mproj2+365*anproj2)/365;
                   12958:         jprojf=jproj2;
                   12959:         mprojf=mproj2;
                   12960:         anprojf=anproj2;
                   12961:       } else if(prvforecast == 2){
                   12962:         dateprojd=dateintmean;
                   12963:         date2dmy(dateprojd,&jprojd, &mprojd, &anprojd);
                   12964:         dateprojf=dateintmean+yrfproj;
                   12965:         date2dmy(dateprojf,&jprojf, &mprojf, &anprojf);
                   12966:       }
                   12967:       if(prvbackcast==1){
                   12968:         datebackd=(jback1+12*mback1+365*anback1)/365;
                   12969:         jbackd=jback1;
                   12970:         mbackd=mback1;
                   12971:         anbackd=anback1;
                   12972:         datebackf=(jback2+12*mback2+365*anback2)/365;
                   12973:         jbackf=jback2;
                   12974:         mbackf=mback2;
                   12975:         anbackf=anback2;
                   12976:       } else if(prvbackcast == 2){
                   12977:         datebackd=dateintmean;
                   12978:         date2dmy(datebackd,&jbackd, &mbackd, &anbackd);
                   12979:         datebackf=dateintmean-yrbproj;
                   12980:         date2dmy(datebackf,&jbackf, &mbackf, &anbackf);
                   12981:       }
                   12982:       
                   12983:       printinggnuplot(fileresu, optionfilefiname,ageminpar,agemaxpar,bage, fage, prevfcast, prevbcast, pathc,p, (int)anprojd-bage, (int)anbackd-fage);
1.220     brouard  12984:     }
                   12985:     printinghtml(fileresu,title,datafile, firstpass, lastpass, stepm, weightopt, \
1.296     brouard  12986:                 model,imx,jmin,jmax,jmean,rfileres,popforecast,mobilav,prevfcast,mobilavproj,prevbcast, estepm, \
                   12987:                 jprev1,mprev1,anprev1,dateprev1, dateprojd, datebackd,jprev2,mprev2,anprev2,dateprev2,dateprojf, datebackf);
1.220     brouard  12988:                
1.225     brouard  12989:     /*------------ free_vector  -------------*/
                   12990:     /*  chdir(path); */
1.220     brouard  12991:                
1.215     brouard  12992:     /* free_ivector(wav,1,imx); */  /* Moved after last prevalence call */
                   12993:     /* free_imatrix(dh,1,lastpass-firstpass+2,1,imx); */
                   12994:     /* free_imatrix(bh,1,lastpass-firstpass+2,1,imx); */
                   12995:     /* free_imatrix(mw,1,lastpass-firstpass+2,1,imx);    */
1.290     brouard  12996:     free_lvector(num,firstobs,lastobs);
                   12997:     free_vector(agedc,firstobs,lastobs);
1.126     brouard  12998:     /*free_matrix(covar,0,NCOVMAX,1,n);*/
                   12999:     /*free_matrix(covar,1,NCOVMAX,1,n);*/
                   13000:     fclose(ficparo);
                   13001:     fclose(ficres);
1.220     brouard  13002:                
                   13003:                
1.186     brouard  13004:     /* Other results (useful)*/
1.220     brouard  13005:                
                   13006:                
1.126     brouard  13007:     /*--------------- Prevalence limit  (period or stable prevalence) --------------*/
1.180     brouard  13008:     /*#include "prevlim.h"*/  /* Use ficrespl, ficlog */
                   13009:     prlim=matrix(1,nlstate,1,nlstate);
1.209     brouard  13010:     prevalence_limit(p, prlim,  ageminpar, agemaxpar, ftolpl, &ncvyear);
1.126     brouard  13011:     fclose(ficrespl);
                   13012: 
                   13013:     /*------------- h Pij x at various ages ------------*/
1.180     brouard  13014:     /*#include "hpijx.h"*/
                   13015:     hPijx(p, bage, fage);
1.145     brouard  13016:     fclose(ficrespij);
1.227     brouard  13017:     
1.220     brouard  13018:     /* ncovcombmax=  pow(2,cptcoveff); */
1.219     brouard  13019:     /*-------------- Variance of one-step probabilities---*/
1.145     brouard  13020:     k=1;
1.126     brouard  13021:     varprob(optionfilefiname, matcov, p, delti, nlstate, bage, fage,k,Tvar,nbcode, ncodemax,strstart);
1.227     brouard  13022:     
1.269     brouard  13023:     /* Prevalence for each covariate combination in probs[age][status][cov] */
                   13024:     probs= ma3x(AGEINF,AGESUP,1,nlstate+ndeath, 1,ncovcombmax);
                   13025:     for(i=AGEINF;i<=AGESUP;i++)
1.219     brouard  13026:       for(j=1;j<=nlstate+ndeath;j++) /* ndeath is useless but a necessity to be compared with mobaverages */
1.225     brouard  13027:        for(k=1;k<=ncovcombmax;k++)
                   13028:          probs[i][j][k]=0.;
1.269     brouard  13029:     prevalence(probs, ageminpar, agemaxpar, s, agev, nlstate, imx, Tvar, nbcode, 
                   13030:               ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass);
1.219     brouard  13031:     if (mobilav!=0 ||mobilavproj !=0 ) {
1.269     brouard  13032:       mobaverages= ma3x(AGEINF, AGESUP,1,nlstate+ndeath, 1,ncovcombmax);
                   13033:       for(i=AGEINF;i<=AGESUP;i++)
1.268     brouard  13034:        for(j=1;j<=nlstate+ndeath;j++)
1.227     brouard  13035:          for(k=1;k<=ncovcombmax;k++)
                   13036:            mobaverages[i][j][k]=0.;
1.219     brouard  13037:       mobaverage=mobaverages;
                   13038:       if (mobilav!=0) {
1.235     brouard  13039:        printf("Movingaveraging observed prevalence\n");
1.258     brouard  13040:        fprintf(ficlog,"Movingaveraging observed prevalence\n");
1.227     brouard  13041:        if (movingaverage(probs, ageminpar, agemaxpar, mobaverage, mobilav)!=0){
                   13042:          fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);
                   13043:          printf(" Error in movingaverage mobilav=%d\n",mobilav);
                   13044:        }
1.269     brouard  13045:       } else if (mobilavproj !=0) {
1.235     brouard  13046:        printf("Movingaveraging projected observed prevalence\n");
1.258     brouard  13047:        fprintf(ficlog,"Movingaveraging projected observed prevalence\n");
1.227     brouard  13048:        if (movingaverage(probs, ageminpar, agemaxpar, mobaverage, mobilavproj)!=0){
                   13049:          fprintf(ficlog," Error in movingaverage mobilavproj=%d\n",mobilavproj);
                   13050:          printf(" Error in movingaverage mobilavproj=%d\n",mobilavproj);
                   13051:        }
1.269     brouard  13052:       }else{
                   13053:        printf("Internal error moving average\n");
                   13054:        fflush(stdout);
                   13055:        exit(1);
1.219     brouard  13056:       }
                   13057:     }/* end if moving average */
1.227     brouard  13058:     
1.126     brouard  13059:     /*---------- Forecasting ------------------*/
1.296     brouard  13060:     if(prevfcast==1){ 
                   13061:       /*   /\*    if(stepm ==1){*\/ */
                   13062:       /*   /\*  anproj1, mproj1, jproj1 either read explicitly or yrfproj *\/ */
                   13063:       /*This done previously after freqsummary.*/
                   13064:       /*   dateprojd=(jproj1+12*mproj1+365*anproj1)/365; */
                   13065:       /*   dateprojf=(jproj2+12*mproj2+365*anproj2)/365; */
                   13066:       
                   13067:       /* } else if (prvforecast==2){ */
                   13068:       /*   /\*    if(stepm ==1){*\/ */
                   13069:       /*   /\*  anproj1, mproj1, jproj1 either read explicitly or yrfproj *\/ */
                   13070:       /* } */
                   13071:       /*prevforecast(fileresu, dateintmean, anproj1, mproj1, jproj1, agemin, agemax, dateprev1, dateprev2, mobilavproj, mobaverage, bage, fage, firstpass, lastpass, anproj2, p, cptcoveff);*/
                   13072:       prevforecast(fileresu,dateintmean, dateprojd, dateprojf, agemin, agemax, dateprev1, dateprev2, mobilavproj, mobaverage, bage, fage, firstpass, lastpass, p, cptcoveff);
1.126     brouard  13073:     }
1.269     brouard  13074: 
1.296     brouard  13075:     /* Prevbcasting */
                   13076:     if(prevbcast==1){
1.219     brouard  13077:       ddnewms=matrix(1,nlstate+ndeath,1,nlstate+ndeath);       
                   13078:       ddoldms=matrix(1,nlstate+ndeath,1,nlstate+ndeath);       
                   13079:       ddsavms=matrix(1,nlstate+ndeath,1,nlstate+ndeath);
                   13080: 
                   13081:       /*--------------- Back Prevalence limit  (period or stable prevalence) --------------*/
                   13082: 
                   13083:       bprlim=matrix(1,nlstate,1,nlstate);
1.269     brouard  13084: 
1.219     brouard  13085:       back_prevalence_limit(p, bprlim,  ageminpar, agemaxpar, ftolpl, &ncvyear, dateprev1, dateprev2, firstpass, lastpass, mobilavproj);
                   13086:       fclose(ficresplb);
                   13087: 
1.222     brouard  13088:       hBijx(p, bage, fage, mobaverage);
                   13089:       fclose(ficrespijb);
1.219     brouard  13090: 
1.296     brouard  13091:       /* /\* prevbackforecast(fileresu, mobaverage, anback1, mback1, jback1, agemin, agemax, dateprev1, dateprev2, *\/ */
                   13092:       /* /\*                  mobilavproj, bage, fage, firstpass, lastpass, anback2, p, cptcoveff); *\/ */
                   13093:       /* prevbackforecast(fileresu, mobaverage, anback1, mback1, jback1, agemin, agemax, dateprev1, dateprev2, */
                   13094:       /*                      mobilavproj, bage, fage, firstpass, lastpass, anback2, p, cptcoveff); */
                   13095:       prevbackforecast(fileresu, mobaverage, dateintmean, dateprojd, dateprojf, agemin, agemax, dateprev1, dateprev2,
                   13096:                       mobilavproj, bage, fage, firstpass, lastpass, p, cptcoveff);
                   13097: 
                   13098:       
1.269     brouard  13099:       varbprlim(fileresu, nresult, mobaverage, mobilavproj, bage, fage, bprlim, &ncvyear, ftolpl, p, matcov, delti, stepm, cptcoveff);
1.268     brouard  13100: 
                   13101:       
1.269     brouard  13102:       free_matrix(bprlim,1,nlstate,1,nlstate); /*here or after loop ? */
1.219     brouard  13103:       free_matrix(ddnewms, 1, nlstate+ndeath, 1, nlstate+ndeath);
                   13104:       free_matrix(ddsavms, 1, nlstate+ndeath, 1, nlstate+ndeath);
                   13105:       free_matrix(ddoldms, 1, nlstate+ndeath, 1, nlstate+ndeath);
1.296     brouard  13106:     }    /* end  Prevbcasting */
1.268     brouard  13107:  
1.186     brouard  13108:  
                   13109:     /* ------ Other prevalence ratios------------ */
1.126     brouard  13110: 
1.215     brouard  13111:     free_ivector(wav,1,imx);
                   13112:     free_imatrix(dh,1,lastpass-firstpass+2,1,imx);
                   13113:     free_imatrix(bh,1,lastpass-firstpass+2,1,imx);
                   13114:     free_imatrix(mw,1,lastpass-firstpass+2,1,imx);   
1.218     brouard  13115:                
                   13116:                
1.127     brouard  13117:     /*---------- Health expectancies, no variances ------------*/
1.218     brouard  13118:                
1.201     brouard  13119:     strcpy(filerese,"E_");
                   13120:     strcat(filerese,fileresu);
1.126     brouard  13121:     if((ficreseij=fopen(filerese,"w"))==NULL) {
                   13122:       printf("Problem with Health Exp. resultfile: %s\n", filerese); exit(0);
                   13123:       fprintf(ficlog,"Problem with Health Exp. resultfile: %s\n", filerese); exit(0);
                   13124:     }
1.208     brouard  13125:     printf("Computing Health Expectancies: result on file '%s' ...", filerese);fflush(stdout);
                   13126:     fprintf(ficlog,"Computing Health Expectancies: result on file '%s' ...", filerese);fflush(ficlog);
1.238     brouard  13127: 
                   13128:     pstamp(ficreseij);
1.219     brouard  13129:                
1.235     brouard  13130:     i1=pow(2,cptcoveff); /* Number of combination of dummy covariates */
                   13131:     if (cptcovn < 1){i1=1;}
                   13132:     
                   13133:     for(nres=1; nres <= nresult; nres++) /* For each resultline */
                   13134:     for(k=1; k<=i1;k++){ /* For any combination of dummy covariates, fixed and varying */
1.253     brouard  13135:       if(i1 != 1 && TKresult[nres]!= k)
1.235     brouard  13136:        continue;
1.219     brouard  13137:       fprintf(ficreseij,"\n#****** ");
1.235     brouard  13138:       printf("\n#****** ");
1.225     brouard  13139:       for(j=1;j<=cptcoveff;j++) {
1.227     brouard  13140:        fprintf(ficreseij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
1.235     brouard  13141:        printf("V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   13142:       }
                   13143:       for (j=1; j<= nsq; j++){ /* For each selected (single) quantitative value */
                   13144:        printf(" V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]);
                   13145:        fprintf(ficreseij," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]);
1.219     brouard  13146:       }
                   13147:       fprintf(ficreseij,"******\n");
1.235     brouard  13148:       printf("******\n");
1.219     brouard  13149:       
                   13150:       eij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
                   13151:       oldm=oldms;savm=savms;
1.235     brouard  13152:       evsij(eij, p, nlstate, stepm, (int) bage, (int)fage, oldm, savm, k, estepm, strstart, nres);  
1.127     brouard  13153:       
1.219     brouard  13154:       free_ma3x(eij,1,nlstate,1,nlstate,(int) bage, (int)fage);
1.127     brouard  13155:     }
                   13156:     fclose(ficreseij);
1.208     brouard  13157:     printf("done evsij\n");fflush(stdout);
                   13158:     fprintf(ficlog,"done evsij\n");fflush(ficlog);
1.269     brouard  13159: 
1.218     brouard  13160:                
1.227     brouard  13161:     /*---------- State-specific expectancies and variances ------------*/
1.218     brouard  13162:                
1.201     brouard  13163:     strcpy(filerest,"T_");
                   13164:     strcat(filerest,fileresu);
1.127     brouard  13165:     if((ficrest=fopen(filerest,"w"))==NULL) {
                   13166:       printf("Problem with total LE resultfile: %s\n", filerest);goto end;
                   13167:       fprintf(ficlog,"Problem with total LE resultfile: %s\n", filerest);goto end;
                   13168:     }
1.208     brouard  13169:     printf("Computing Total Life expectancies with their standard errors: file '%s' ...\n", filerest); fflush(stdout);
                   13170:     fprintf(ficlog,"Computing Total Life expectancies with their standard errors: file '%s' ...\n", filerest); fflush(ficlog);
1.201     brouard  13171:     strcpy(fileresstde,"STDE_");
                   13172:     strcat(fileresstde,fileresu);
1.126     brouard  13173:     if((ficresstdeij=fopen(fileresstde,"w"))==NULL) {
1.227     brouard  13174:       printf("Problem with State specific Exp. and std errors resultfile: %s\n", fileresstde); exit(0);
                   13175:       fprintf(ficlog,"Problem with State specific Exp. and std errors resultfile: %s\n", fileresstde); exit(0);
1.126     brouard  13176:     }
1.227     brouard  13177:     printf("  Computing State-specific Expectancies and standard errors: result on file '%s' \n", fileresstde);
                   13178:     fprintf(ficlog,"  Computing State-specific Expectancies and standard errors: result on file '%s' \n", fileresstde);
1.126     brouard  13179: 
1.201     brouard  13180:     strcpy(filerescve,"CVE_");
                   13181:     strcat(filerescve,fileresu);
1.126     brouard  13182:     if((ficrescveij=fopen(filerescve,"w"))==NULL) {
1.227     brouard  13183:       printf("Problem with Covar. State-specific Exp. resultfile: %s\n", filerescve); exit(0);
                   13184:       fprintf(ficlog,"Problem with Covar. State-specific Exp. resultfile: %s\n", filerescve); exit(0);
1.126     brouard  13185:     }
1.227     brouard  13186:     printf("    Computing Covar. of State-specific Expectancies: result on file '%s' \n", filerescve);
                   13187:     fprintf(ficlog,"    Computing Covar. of State-specific Expectancies: result on file '%s' \n", filerescve);
1.126     brouard  13188: 
1.201     brouard  13189:     strcpy(fileresv,"V_");
                   13190:     strcat(fileresv,fileresu);
1.126     brouard  13191:     if((ficresvij=fopen(fileresv,"w"))==NULL) {
                   13192:       printf("Problem with variance resultfile: %s\n", fileresv);exit(0);
                   13193:       fprintf(ficlog,"Problem with variance resultfile: %s\n", fileresv);exit(0);
                   13194:     }
1.227     brouard  13195:     printf("      Computing Variance-covariance of State-specific Expectancies: file '%s' ... ", fileresv);fflush(stdout);
                   13196:     fprintf(ficlog,"      Computing Variance-covariance of State-specific Expectancies: file '%s' ... ", fileresv);fflush(ficlog);
1.126     brouard  13197: 
1.235     brouard  13198:     i1=pow(2,cptcoveff); /* Number of combination of dummy covariates */
                   13199:     if (cptcovn < 1){i1=1;}
                   13200:     
                   13201:     for(nres=1; nres <= nresult; nres++) /* For each resultline */
                   13202:     for(k=1; k<=i1;k++){ /* For any combination of dummy covariates, fixed and varying */
1.253     brouard  13203:       if(i1 != 1 && TKresult[nres]!= k)
1.235     brouard  13204:        continue;
1.321     brouard  13205:       printf("\n# model %s \n#****** Result for:", model);
                   13206:       fprintf(ficrest,"\n# model %s \n#****** Result for:", model);
                   13207:       fprintf(ficlog,"\n# model %s \n#****** Result for:", model);
1.227     brouard  13208:       for(j=1;j<=cptcoveff;j++){ 
                   13209:        printf("V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   13210:        fprintf(ficrest,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   13211:        fprintf(ficlog,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   13212:       }
1.235     brouard  13213:       for (j=1; j<= nsq; j++){ /* For each selected (single) quantitative value */
                   13214:        printf(" V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]);
                   13215:        fprintf(ficrest," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]);
                   13216:        fprintf(ficlog," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]);
                   13217:       }        
1.208     brouard  13218:       fprintf(ficrest,"******\n");
1.227     brouard  13219:       fprintf(ficlog,"******\n");
                   13220:       printf("******\n");
1.208     brouard  13221:       
                   13222:       fprintf(ficresstdeij,"\n#****** ");
                   13223:       fprintf(ficrescveij,"\n#****** ");
1.225     brouard  13224:       for(j=1;j<=cptcoveff;j++) {
1.227     brouard  13225:        fprintf(ficresstdeij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   13226:        fprintf(ficrescveij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
1.208     brouard  13227:       }
1.235     brouard  13228:       for (j=1; j<= nsq; j++){ /* For each selected (single) quantitative value */
                   13229:        fprintf(ficresstdeij," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]);
                   13230:        fprintf(ficrescveij," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]);
                   13231:       }        
1.208     brouard  13232:       fprintf(ficresstdeij,"******\n");
                   13233:       fprintf(ficrescveij,"******\n");
                   13234:       
                   13235:       fprintf(ficresvij,"\n#****** ");
1.238     brouard  13236:       /* pstamp(ficresvij); */
1.225     brouard  13237:       for(j=1;j<=cptcoveff;j++) 
1.227     brouard  13238:        fprintf(ficresvij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
1.235     brouard  13239:       for (j=1; j<= nsq; j++){ /* For each selected (single) quantitative value */
                   13240:        fprintf(ficresvij," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]);
                   13241:       }        
1.208     brouard  13242:       fprintf(ficresvij,"******\n");
                   13243:       
                   13244:       eij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
                   13245:       oldm=oldms;savm=savms;
1.235     brouard  13246:       printf(" cvevsij ");
                   13247:       fprintf(ficlog, " cvevsij ");
                   13248:       cvevsij(eij, p, nlstate, stepm, (int) bage, (int)fage, oldm, savm, k, estepm, delti, matcov, strstart, nres);
1.208     brouard  13249:       printf(" end cvevsij \n ");
                   13250:       fprintf(ficlog, " end cvevsij \n ");
                   13251:       
                   13252:       /*
                   13253:        */
                   13254:       /* goto endfree; */
                   13255:       
                   13256:       vareij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
                   13257:       pstamp(ficrest);
                   13258:       
1.269     brouard  13259:       epj=vector(1,nlstate+1);
1.208     brouard  13260:       for(vpopbased=0; vpopbased <= popbased; vpopbased++){ /* Done for vpopbased=0 and vpopbased=1 if popbased==1*/
1.227     brouard  13261:        oldm=oldms;savm=savms; /* ZZ Segmentation fault */
                   13262:        cptcod= 0; /* To be deleted */
                   13263:        printf("varevsij vpopbased=%d \n",vpopbased);
                   13264:        fprintf(ficlog, "varevsij vpopbased=%d \n",vpopbased);
1.235     brouard  13265:        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  13266:        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 ");
                   13267:        if(vpopbased==1)
                   13268:          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);
                   13269:        else
1.288     brouard  13270:          fprintf(ficrest,"the age specific forward period (stable) prevalences in each health state \n");
1.227     brouard  13271:        fprintf(ficrest,"# Age popbased mobilav e.. (std) ");
                   13272:        for (i=1;i<=nlstate;i++) fprintf(ficrest,"e.%d (std) ",i);
                   13273:        fprintf(ficrest,"\n");
                   13274:        /* printf("Which p?\n"); for(i=1;i<=npar;i++)printf("p[i=%d]=%lf,",i,p[i]);printf("\n"); */
1.288     brouard  13275:        printf("Computing age specific forward period (stable) prevalences in each health state \n");
                   13276:        fprintf(ficlog,"Computing age specific forward period (stable) prevalences in each health state \n");
1.227     brouard  13277:        for(age=bage; age <=fage ;age++){
1.235     brouard  13278:          prevalim(prlim, nlstate, p, age, oldm, savm, ftolpl, &ncvyear, k, nres); /*ZZ Is it the correct prevalim */
1.227     brouard  13279:          if (vpopbased==1) {
                   13280:            if(mobilav ==0){
                   13281:              for(i=1; i<=nlstate;i++)
                   13282:                prlim[i][i]=probs[(int)age][i][k];
                   13283:            }else{ /* mobilav */ 
                   13284:              for(i=1; i<=nlstate;i++)
                   13285:                prlim[i][i]=mobaverage[(int)age][i][k];
                   13286:            }
                   13287:          }
1.219     brouard  13288:          
1.227     brouard  13289:          fprintf(ficrest," %4.0f %d %d",age, vpopbased, mobilav);
                   13290:          /* fprintf(ficrest," %4.0f %d %d %d %d",age, vpopbased, mobilav,Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]); */ /* to be done */
                   13291:          /* printf(" age %4.0f ",age); */
                   13292:          for(j=1, epj[nlstate+1]=0.;j <=nlstate;j++){
                   13293:            for(i=1, epj[j]=0.;i <=nlstate;i++) {
                   13294:              epj[j] += prlim[i][i]*eij[i][j][(int)age];
                   13295:              /*ZZZ  printf("%lf %lf ", prlim[i][i] ,eij[i][j][(int)age]);*/
                   13296:              /* printf("%lf %lf ", prlim[i][i] ,eij[i][j][(int)age]); */
                   13297:            }
                   13298:            epj[nlstate+1] +=epj[j];
                   13299:          }
                   13300:          /* printf(" age %4.0f \n",age); */
1.219     brouard  13301:          
1.227     brouard  13302:          for(i=1, vepp=0.;i <=nlstate;i++)
                   13303:            for(j=1;j <=nlstate;j++)
                   13304:              vepp += vareij[i][j][(int)age];
                   13305:          fprintf(ficrest," %7.3f (%7.3f)", epj[nlstate+1],sqrt(vepp));
                   13306:          for(j=1;j <=nlstate;j++){
                   13307:            fprintf(ficrest," %7.3f (%7.3f)", epj[j],sqrt(vareij[j][j][(int)age]));
                   13308:          }
                   13309:          fprintf(ficrest,"\n");
                   13310:        }
1.208     brouard  13311:       } /* End vpopbased */
1.269     brouard  13312:       free_vector(epj,1,nlstate+1);
1.208     brouard  13313:       free_ma3x(eij,1,nlstate,1,nlstate,(int) bage, (int)fage);
                   13314:       free_ma3x(vareij,1,nlstate,1,nlstate,(int) bage, (int)fage);
1.235     brouard  13315:       printf("done selection\n");fflush(stdout);
                   13316:       fprintf(ficlog,"done selection\n");fflush(ficlog);
1.208     brouard  13317:       
1.235     brouard  13318:     } /* End k selection */
1.227     brouard  13319: 
                   13320:     printf("done State-specific expectancies\n");fflush(stdout);
                   13321:     fprintf(ficlog,"done State-specific expectancies\n");fflush(ficlog);
                   13322: 
1.288     brouard  13323:     /* variance-covariance of forward period prevalence*/
1.269     brouard  13324:     varprlim(fileresu, nresult, mobaverage, mobilavproj, bage, fage, prlim, &ncvyear, ftolpl, p, matcov, delti, stepm, cptcoveff);
1.268     brouard  13325: 
1.227     brouard  13326:     
1.290     brouard  13327:     free_vector(weight,firstobs,lastobs);
1.227     brouard  13328:     free_imatrix(Tvard,1,NCOVMAX,1,2);
1.290     brouard  13329:     free_imatrix(s,1,maxwav+1,firstobs,lastobs);
                   13330:     free_matrix(anint,1,maxwav,firstobs,lastobs); 
                   13331:     free_matrix(mint,1,maxwav,firstobs,lastobs);
                   13332:     free_ivector(cod,firstobs,lastobs);
1.227     brouard  13333:     free_ivector(tab,1,NCOVMAX);
                   13334:     fclose(ficresstdeij);
                   13335:     fclose(ficrescveij);
                   13336:     fclose(ficresvij);
                   13337:     fclose(ficrest);
                   13338:     fclose(ficpar);
                   13339:     
                   13340:     
1.126     brouard  13341:     /*---------- End : free ----------------*/
1.219     brouard  13342:     if (mobilav!=0 ||mobilavproj !=0)
1.269     brouard  13343:       free_ma3x(mobaverages,AGEINF, AGESUP,1,nlstate+ndeath, 1,ncovcombmax); /* We need to have a squared matrix with prevalence of the dead! */
                   13344:     free_ma3x(probs,AGEINF,AGESUP,1,nlstate+ndeath, 1,ncovcombmax);
1.220     brouard  13345:     free_matrix(prlim,1,nlstate,1,nlstate); /*here or after loop ? */
                   13346:     free_matrix(pmmij,1,nlstate+ndeath,1,nlstate+ndeath);
1.126     brouard  13347:   }  /* mle==-3 arrives here for freeing */
1.227     brouard  13348:   /* endfree:*/
                   13349:   free_matrix(oldms, 1,nlstate+ndeath,1,nlstate+ndeath);
                   13350:   free_matrix(newms, 1,nlstate+ndeath,1,nlstate+ndeath);
                   13351:   free_matrix(savms, 1,nlstate+ndeath,1,nlstate+ndeath);
1.290     brouard  13352:   if(ntv+nqtv>=1)free_ma3x(cotvar,1,maxwav,1,ntv+nqtv,firstobs,lastobs);
                   13353:   if(nqtv>=1)free_ma3x(cotqvar,1,maxwav,1,nqtv,firstobs,lastobs);
                   13354:   if(nqv>=1)free_matrix(coqvar,1,nqv,firstobs,lastobs);
                   13355:   free_matrix(covar,0,NCOVMAX,firstobs,lastobs);
1.227     brouard  13356:   free_matrix(matcov,1,npar,1,npar);
                   13357:   free_matrix(hess,1,npar,1,npar);
                   13358:   /*free_vector(delti,1,npar);*/
                   13359:   free_ma3x(delti3,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel); 
                   13360:   free_matrix(agev,1,maxwav,1,imx);
1.269     brouard  13361:   free_ma3x(paramstart,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel);
1.227     brouard  13362:   free_ma3x(param,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel);
                   13363:   
                   13364:   free_ivector(ncodemax,1,NCOVMAX);
                   13365:   free_ivector(ncodemaxwundef,1,NCOVMAX);
                   13366:   free_ivector(Dummy,-1,NCOVMAX);
                   13367:   free_ivector(Fixed,-1,NCOVMAX);
1.238     brouard  13368:   free_ivector(DummyV,1,NCOVMAX);
                   13369:   free_ivector(FixedV,1,NCOVMAX);
1.227     brouard  13370:   free_ivector(Typevar,-1,NCOVMAX);
                   13371:   free_ivector(Tvar,1,NCOVMAX);
1.234     brouard  13372:   free_ivector(TvarsQ,1,NCOVMAX);
                   13373:   free_ivector(TvarsQind,1,NCOVMAX);
                   13374:   free_ivector(TvarsD,1,NCOVMAX);
                   13375:   free_ivector(TvarsDind,1,NCOVMAX);
1.231     brouard  13376:   free_ivector(TvarFD,1,NCOVMAX);
                   13377:   free_ivector(TvarFDind,1,NCOVMAX);
1.232     brouard  13378:   free_ivector(TvarF,1,NCOVMAX);
                   13379:   free_ivector(TvarFind,1,NCOVMAX);
                   13380:   free_ivector(TvarV,1,NCOVMAX);
                   13381:   free_ivector(TvarVind,1,NCOVMAX);
                   13382:   free_ivector(TvarA,1,NCOVMAX);
                   13383:   free_ivector(TvarAind,1,NCOVMAX);
1.231     brouard  13384:   free_ivector(TvarFQ,1,NCOVMAX);
                   13385:   free_ivector(TvarFQind,1,NCOVMAX);
                   13386:   free_ivector(TvarVD,1,NCOVMAX);
                   13387:   free_ivector(TvarVDind,1,NCOVMAX);
                   13388:   free_ivector(TvarVQ,1,NCOVMAX);
                   13389:   free_ivector(TvarVQind,1,NCOVMAX);
1.230     brouard  13390:   free_ivector(Tvarsel,1,NCOVMAX);
                   13391:   free_vector(Tvalsel,1,NCOVMAX);
1.227     brouard  13392:   free_ivector(Tposprod,1,NCOVMAX);
                   13393:   free_ivector(Tprod,1,NCOVMAX);
                   13394:   free_ivector(Tvaraff,1,NCOVMAX);
                   13395:   free_ivector(invalidvarcomb,1,ncovcombmax);
                   13396:   free_ivector(Tage,1,NCOVMAX);
                   13397:   free_ivector(Tmodelind,1,NCOVMAX);
1.228     brouard  13398:   free_ivector(TmodelInvind,1,NCOVMAX);
                   13399:   free_ivector(TmodelInvQind,1,NCOVMAX);
1.227     brouard  13400:   
                   13401:   free_imatrix(nbcode,0,NCOVMAX,0,NCOVMAX);
                   13402:   /* free_imatrix(codtab,1,100,1,10); */
1.126     brouard  13403:   fflush(fichtm);
                   13404:   fflush(ficgp);
                   13405:   
1.227     brouard  13406:   
1.126     brouard  13407:   if((nberr >0) || (nbwarn>0)){
1.216     brouard  13408:     printf("End of Imach with %d errors and/or %d warnings. Please look at the log file for details.\n",nberr,nbwarn);
                   13409:     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  13410:   }else{
                   13411:     printf("End of Imach\n");
                   13412:     fprintf(ficlog,"End of Imach\n");
                   13413:   }
                   13414:   printf("See log file on %s\n",filelog);
                   13415:   /*  gettimeofday(&end_time, (struct timezone*)0);*/  /* after time */
1.157     brouard  13416:   /*(void) gettimeofday(&end_time,&tzp);*/
                   13417:   rend_time = time(NULL);  
                   13418:   end_time = *localtime(&rend_time);
                   13419:   /* tml = *localtime(&end_time.tm_sec); */
                   13420:   strcpy(strtend,asctime(&end_time));
1.126     brouard  13421:   printf("Local time at start %s\nLocal time at end   %s",strstart, strtend); 
                   13422:   fprintf(ficlog,"Local time at start %s\nLocal time at end   %s\n",strstart, strtend); 
1.157     brouard  13423:   printf("Total time used %s\n", asc_diff_time(rend_time -rstart_time,tmpout));
1.227     brouard  13424:   
1.157     brouard  13425:   printf("Total time was %.0lf Sec.\n", difftime(rend_time,rstart_time));
                   13426:   fprintf(ficlog,"Total time used %s\n", asc_diff_time(rend_time -rstart_time,tmpout));
                   13427:   fprintf(ficlog,"Total time was %.0lf Sec.\n", difftime(rend_time,rstart_time));
1.126     brouard  13428:   /*  printf("Total time was %d uSec.\n", total_usecs);*/
                   13429: /*   if(fileappend(fichtm,optionfilehtm)){ */
                   13430:   fprintf(fichtm,"<br>Local time at start %s<br>Local time at end   %s<br>\n</body></html>",strstart, strtend);
                   13431:   fclose(fichtm);
                   13432:   fprintf(fichtmcov,"<br>Local time at start %s<br>Local time at end   %s<br>\n</body></html>",strstart, strtend);
                   13433:   fclose(fichtmcov);
                   13434:   fclose(ficgp);
                   13435:   fclose(ficlog);
                   13436:   /*------ End -----------*/
1.227     brouard  13437:   
1.281     brouard  13438: 
                   13439: /* Executes gnuplot */
1.227     brouard  13440:   
                   13441:   printf("Before Current directory %s!\n",pathcd);
1.184     brouard  13442: #ifdef WIN32
1.227     brouard  13443:   if (_chdir(pathcd) != 0)
                   13444:     printf("Can't move to directory %s!\n",path);
                   13445:   if(_getcwd(pathcd,MAXLINE) > 0)
1.184     brouard  13446: #else
1.227     brouard  13447:     if(chdir(pathcd) != 0)
                   13448:       printf("Can't move to directory %s!\n", path);
                   13449:   if (getcwd(pathcd, MAXLINE) > 0)
1.184     brouard  13450: #endif 
1.126     brouard  13451:     printf("Current directory %s!\n",pathcd);
                   13452:   /*strcat(plotcmd,CHARSEPARATOR);*/
                   13453:   sprintf(plotcmd,"gnuplot");
1.157     brouard  13454: #ifdef _WIN32
1.126     brouard  13455:   sprintf(plotcmd,"\"%sgnuplot.exe\"",pathimach);
                   13456: #endif
                   13457:   if(!stat(plotcmd,&info)){
1.158     brouard  13458:     printf("Error or gnuplot program not found: '%s'\n",plotcmd);fflush(stdout);
1.126     brouard  13459:     if(!stat(getenv("GNUPLOTBIN"),&info)){
1.158     brouard  13460:       printf("Error or gnuplot program not found: '%s' Environment GNUPLOTBIN not set.\n",plotcmd);fflush(stdout);
1.126     brouard  13461:     }else
                   13462:       strcpy(pplotcmd,plotcmd);
1.157     brouard  13463: #ifdef __unix
1.126     brouard  13464:     strcpy(plotcmd,GNUPLOTPROGRAM);
                   13465:     if(!stat(plotcmd,&info)){
1.158     brouard  13466:       printf("Error gnuplot program not found: '%s'\n",plotcmd);fflush(stdout);
1.126     brouard  13467:     }else
                   13468:       strcpy(pplotcmd,plotcmd);
                   13469: #endif
                   13470:   }else
                   13471:     strcpy(pplotcmd,plotcmd);
                   13472:   
                   13473:   sprintf(plotcmd,"%s %s",pplotcmd, optionfilegnuplot);
1.158     brouard  13474:   printf("Starting graphs with: '%s'\n",plotcmd);fflush(stdout);
1.292     brouard  13475:   strcpy(pplotcmd,plotcmd);
1.227     brouard  13476:   
1.126     brouard  13477:   if((outcmd=system(plotcmd)) != 0){
1.292     brouard  13478:     printf("Error in gnuplot, command might not be in your path: '%s', err=%d\n", plotcmd, outcmd);
1.154     brouard  13479:     printf("\n Trying if gnuplot resides on the same directory that IMaCh\n");
1.152     brouard  13480:     sprintf(plotcmd,"%sgnuplot %s", pathimach, optionfilegnuplot);
1.292     brouard  13481:     if((outcmd=system(plotcmd)) != 0){
1.153     brouard  13482:       printf("\n Still a problem with gnuplot command %s, err=%d\n", plotcmd, outcmd);
1.292     brouard  13483:       strcpy(plotcmd,pplotcmd);
                   13484:     }
1.126     brouard  13485:   }
1.158     brouard  13486:   printf(" Successful, please wait...");
1.126     brouard  13487:   while (z[0] != 'q') {
                   13488:     /* chdir(path); */
1.154     brouard  13489:     printf("\nType e to edit results with your browser, g to graph again and q for exit: ");
1.126     brouard  13490:     scanf("%s",z);
                   13491: /*     if (z[0] == 'c') system("./imach"); */
                   13492:     if (z[0] == 'e') {
1.158     brouard  13493: #ifdef __APPLE__
1.152     brouard  13494:       sprintf(pplotcmd, "open %s", optionfilehtm);
1.157     brouard  13495: #elif __linux
                   13496:       sprintf(pplotcmd, "xdg-open %s", optionfilehtm);
1.153     brouard  13497: #else
1.152     brouard  13498:       sprintf(pplotcmd, "%s", optionfilehtm);
1.153     brouard  13499: #endif
                   13500:       printf("Starting browser with: %s",pplotcmd);fflush(stdout);
                   13501:       system(pplotcmd);
1.126     brouard  13502:     }
                   13503:     else if (z[0] == 'g') system(plotcmd);
                   13504:     else if (z[0] == 'q') exit(0);
                   13505:   }
1.227     brouard  13506: end:
1.126     brouard  13507:   while (z[0] != 'q') {
1.195     brouard  13508:     printf("\nType  q for exiting: "); fflush(stdout);
1.126     brouard  13509:     scanf("%s",z);
                   13510:   }
1.283     brouard  13511:   printf("End\n");
1.282     brouard  13512:   exit(0);
1.126     brouard  13513: }

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