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

1.330   ! brouard     1: /* $Id: imach.c,v 1.329 2022/08/03 17:29:54 brouard Exp $
1.126     brouard     2:   $State: Exp $
1.163     brouard     3:   $Log: imach.c,v $
1.330   ! brouard     4:   Revision 1.329  2022/08/03 17:29:54  brouard
        !             5:   *  imach.c (Module): Many errors in graphs fixed with Vn*age covariates.
        !             6: 
1.329     brouard     7:   Revision 1.328  2022/07/27 17:40:48  brouard
                      8:   Summary: valgrind bug fixed by initializing to zero DummyV as well as Tage
                      9: 
1.328     brouard    10:   Revision 1.327  2022/07/27 14:47:35  brouard
                     11:   Summary: Still a problem for one-step probabilities in case of quantitative variables
                     12: 
1.327     brouard    13:   Revision 1.326  2022/07/26 17:33:55  brouard
                     14:   Summary: some test with nres=1
                     15: 
1.326     brouard    16:   Revision 1.325  2022/07/25 14:27:23  brouard
                     17:   Summary: r30
                     18: 
                     19:   * imach.c (Module): Error cptcovn instead of nsd in bmij (was
                     20:   coredumped, revealed by Feiuno, thank you.
                     21: 
1.325     brouard    22:   Revision 1.324  2022/07/23 17:44:26  brouard
                     23:   *** empty log message ***
                     24: 
1.324     brouard    25:   Revision 1.323  2022/07/22 12:30:08  brouard
                     26:   *  imach.c (Module): Output of Wald test in the htm file and not only in the log.
                     27: 
1.323     brouard    28:   Revision 1.322  2022/07/22 12:27:48  brouard
                     29:   *  imach.c (Module): Output of Wald test in the htm file and not only in the log.
                     30: 
1.322     brouard    31:   Revision 1.321  2022/07/22 12:04:24  brouard
                     32:   Summary: r28
                     33: 
                     34:   *  imach.c (Module): Output of Wald test in the htm file and not only in the log.
                     35: 
1.321     brouard    36:   Revision 1.320  2022/06/02 05:10:11  brouard
                     37:   *** empty log message ***
                     38: 
1.320     brouard    39:   Revision 1.319  2022/06/02 04:45:11  brouard
                     40:   * imach.c (Module): Adding the Wald tests from the log to the main
                     41:   htm for better display of the maximum likelihood estimators.
                     42: 
1.319     brouard    43:   Revision 1.318  2022/05/24 08:10:59  brouard
                     44:   * imach.c (Module): Some attempts to find a bug of wrong estimates
                     45:   of confidencce intervals with product in the equation modelC
                     46: 
1.318     brouard    47:   Revision 1.317  2022/05/15 15:06:23  brouard
                     48:   * imach.c (Module):  Some minor improvements
                     49: 
1.317     brouard    50:   Revision 1.316  2022/05/11 15:11:31  brouard
                     51:   Summary: r27
                     52: 
1.316     brouard    53:   Revision 1.315  2022/05/11 15:06:32  brouard
                     54:   *** empty log message ***
                     55: 
1.315     brouard    56:   Revision 1.314  2022/04/13 17:43:09  brouard
                     57:   * imach.c (Module): Adding link to text data files
                     58: 
1.314     brouard    59:   Revision 1.313  2022/04/11 15:57:42  brouard
                     60:   * imach.c (Module): Error in rewriting the 'r' file with yearsfproj or yearsbproj fixed
                     61: 
1.313     brouard    62:   Revision 1.312  2022/04/05 21:24:39  brouard
                     63:   *** empty log message ***
                     64: 
1.312     brouard    65:   Revision 1.311  2022/04/05 21:03:51  brouard
                     66:   Summary: Fixed quantitative covariates
                     67: 
                     68:          Fixed covariates (dummy or quantitative)
                     69:        with missing values have never been allowed but are ERRORS and
                     70:        program quits. Standard deviations of fixed covariates were
                     71:        wrongly computed. Mean and standard deviations of time varying
                     72:        covariates are still not computed.
                     73: 
1.311     brouard    74:   Revision 1.310  2022/03/17 08:45:53  brouard
                     75:   Summary: 99r25
                     76: 
                     77:   Improving detection of errors: result lines should be compatible with
                     78:   the model.
                     79: 
1.310     brouard    80:   Revision 1.309  2021/05/20 12:39:14  brouard
                     81:   Summary: Version 0.99r24
                     82: 
1.309     brouard    83:   Revision 1.308  2021/03/31 13:11:57  brouard
                     84:   Summary: Version 0.99r23
                     85: 
                     86: 
                     87:   * imach.c (Module): Still bugs in the result loop. Thank to Holly Benett
                     88: 
1.308     brouard    89:   Revision 1.307  2021/03/08 18:11:32  brouard
                     90:   Summary: 0.99r22 fixed bug on result:
                     91: 
1.307     brouard    92:   Revision 1.306  2021/02/20 15:44:02  brouard
                     93:   Summary: Version 0.99r21
                     94: 
                     95:   * imach.c (Module): Fix bug on quitting after result lines!
                     96:   (Module): Version 0.99r21
                     97: 
1.306     brouard    98:   Revision 1.305  2021/02/20 15:28:30  brouard
                     99:   * imach.c (Module): Fix bug on quitting after result lines!
                    100: 
1.305     brouard   101:   Revision 1.304  2021/02/12 11:34:20  brouard
                    102:   * imach.c (Module): The use of a Windows BOM (huge) file is now an error
                    103: 
1.304     brouard   104:   Revision 1.303  2021/02/11 19:50:15  brouard
                    105:   *  (Module): imach.c Someone entered 'results:' instead of 'result:'. Now it is an error which is printed.
                    106: 
1.303     brouard   107:   Revision 1.302  2020/02/22 21:00:05  brouard
                    108:   *  (Module): imach.c Update mle=-3 (for computing Life expectancy
                    109:   and life table from the data without any state)
                    110: 
1.302     brouard   111:   Revision 1.301  2019/06/04 13:51:20  brouard
                    112:   Summary: Error in 'r'parameter file backcast yearsbproj instead of yearsfproj
                    113: 
1.301     brouard   114:   Revision 1.300  2019/05/22 19:09:45  brouard
                    115:   Summary: version 0.99r19 of May 2019
                    116: 
1.300     brouard   117:   Revision 1.299  2019/05/22 18:37:08  brouard
                    118:   Summary: Cleaned 0.99r19
                    119: 
1.299     brouard   120:   Revision 1.298  2019/05/22 18:19:56  brouard
                    121:   *** empty log message ***
                    122: 
1.298     brouard   123:   Revision 1.297  2019/05/22 17:56:10  brouard
                    124:   Summary: Fix bug by moving date2dmy and nhstepm which gaefin=-1
                    125: 
1.297     brouard   126:   Revision 1.296  2019/05/20 13:03:18  brouard
                    127:   Summary: Projection syntax simplified
                    128: 
                    129: 
                    130:   We can now start projections, forward or backward, from the mean date
                    131:   of inteviews up to or down to a number of years of projection:
                    132:   prevforecast=1 yearsfproj=15.3 mobil_average=0
                    133:   or
                    134:   prevforecast=1 starting-proj-date=1/1/2007 final-proj-date=12/31/2017 mobil_average=0
                    135:   or
                    136:   prevbackcast=1 yearsbproj=12.3 mobil_average=1
                    137:   or
                    138:   prevbackcast=1 starting-back-date=1/10/1999 final-back-date=1/1/1985 mobil_average=1
                    139: 
1.296     brouard   140:   Revision 1.295  2019/05/18 09:52:50  brouard
                    141:   Summary: doxygen tex bug
                    142: 
1.295     brouard   143:   Revision 1.294  2019/05/16 14:54:33  brouard
                    144:   Summary: There was some wrong lines added
                    145: 
1.294     brouard   146:   Revision 1.293  2019/05/09 15:17:34  brouard
                    147:   *** empty log message ***
                    148: 
1.293     brouard   149:   Revision 1.292  2019/05/09 14:17:20  brouard
                    150:   Summary: Some updates
                    151: 
1.292     brouard   152:   Revision 1.291  2019/05/09 13:44:18  brouard
                    153:   Summary: Before ncovmax
                    154: 
1.291     brouard   155:   Revision 1.290  2019/05/09 13:39:37  brouard
                    156:   Summary: 0.99r18 unlimited number of individuals
                    157: 
                    158:   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.
                    159: 
1.290     brouard   160:   Revision 1.289  2018/12/13 09:16:26  brouard
                    161:   Summary: Bug for young ages (<-30) will be in r17
                    162: 
1.289     brouard   163:   Revision 1.288  2018/05/02 20:58:27  brouard
                    164:   Summary: Some bugs fixed
                    165: 
1.288     brouard   166:   Revision 1.287  2018/05/01 17:57:25  brouard
                    167:   Summary: Bug fixed by providing frequencies only for non missing covariates
                    168: 
1.287     brouard   169:   Revision 1.286  2018/04/27 14:27:04  brouard
                    170:   Summary: some minor bugs
                    171: 
1.286     brouard   172:   Revision 1.285  2018/04/21 21:02:16  brouard
                    173:   Summary: Some bugs fixed, valgrind tested
                    174: 
1.285     brouard   175:   Revision 1.284  2018/04/20 05:22:13  brouard
                    176:   Summary: Computing mean and stdeviation of fixed quantitative variables
                    177: 
1.284     brouard   178:   Revision 1.283  2018/04/19 14:49:16  brouard
                    179:   Summary: Some minor bugs fixed
                    180: 
1.283     brouard   181:   Revision 1.282  2018/02/27 22:50:02  brouard
                    182:   *** empty log message ***
                    183: 
1.282     brouard   184:   Revision 1.281  2018/02/27 19:25:23  brouard
                    185:   Summary: Adding second argument for quitting
                    186: 
1.281     brouard   187:   Revision 1.280  2018/02/21 07:58:13  brouard
                    188:   Summary: 0.99r15
                    189: 
                    190:   New Makefile with recent VirtualBox 5.26. Bug in sqrt negatve in imach.c
                    191: 
1.280     brouard   192:   Revision 1.279  2017/07/20 13:35:01  brouard
                    193:   Summary: temporary working
                    194: 
1.279     brouard   195:   Revision 1.278  2017/07/19 14:09:02  brouard
                    196:   Summary: Bug for mobil_average=0 and prevforecast fixed(?)
                    197: 
1.278     brouard   198:   Revision 1.277  2017/07/17 08:53:49  brouard
                    199:   Summary: BOM files can be read now
                    200: 
1.277     brouard   201:   Revision 1.276  2017/06/30 15:48:31  brouard
                    202:   Summary: Graphs improvements
                    203: 
1.276     brouard   204:   Revision 1.275  2017/06/30 13:39:33  brouard
                    205:   Summary: Saito's color
                    206: 
1.275     brouard   207:   Revision 1.274  2017/06/29 09:47:08  brouard
                    208:   Summary: Version 0.99r14
                    209: 
1.274     brouard   210:   Revision 1.273  2017/06/27 11:06:02  brouard
                    211:   Summary: More documentation on projections
                    212: 
1.273     brouard   213:   Revision 1.272  2017/06/27 10:22:40  brouard
                    214:   Summary: Color of backprojection changed from 6 to 5(yellow)
                    215: 
1.272     brouard   216:   Revision 1.271  2017/06/27 10:17:50  brouard
                    217:   Summary: Some bug with rint
                    218: 
1.271     brouard   219:   Revision 1.270  2017/05/24 05:45:29  brouard
                    220:   *** empty log message ***
                    221: 
1.270     brouard   222:   Revision 1.269  2017/05/23 08:39:25  brouard
                    223:   Summary: Code into subroutine, cleanings
                    224: 
1.269     brouard   225:   Revision 1.268  2017/05/18 20:09:32  brouard
                    226:   Summary: backprojection and confidence intervals of backprevalence
                    227: 
1.268     brouard   228:   Revision 1.267  2017/05/13 10:25:05  brouard
                    229:   Summary: temporary save for backprojection
                    230: 
1.267     brouard   231:   Revision 1.266  2017/05/13 07:26:12  brouard
                    232:   Summary: Version 0.99r13 (improvements and bugs fixed)
                    233: 
1.266     brouard   234:   Revision 1.265  2017/04/26 16:22:11  brouard
                    235:   Summary: imach 0.99r13 Some bugs fixed
                    236: 
1.265     brouard   237:   Revision 1.264  2017/04/26 06:01:29  brouard
                    238:   Summary: Labels in graphs
                    239: 
1.264     brouard   240:   Revision 1.263  2017/04/24 15:23:15  brouard
                    241:   Summary: to save
                    242: 
1.263     brouard   243:   Revision 1.262  2017/04/18 16:48:12  brouard
                    244:   *** empty log message ***
                    245: 
1.262     brouard   246:   Revision 1.261  2017/04/05 10:14:09  brouard
                    247:   Summary: Bug in E_ as well as in T_ fixed nres-1 vs k1-1
                    248: 
1.261     brouard   249:   Revision 1.260  2017/04/04 17:46:59  brouard
                    250:   Summary: Gnuplot indexations fixed (humm)
                    251: 
1.260     brouard   252:   Revision 1.259  2017/04/04 13:01:16  brouard
                    253:   Summary: Some errors to warnings only if date of death is unknown but status is death we could set to pi3
                    254: 
1.259     brouard   255:   Revision 1.258  2017/04/03 10:17:47  brouard
                    256:   Summary: Version 0.99r12
                    257: 
                    258:   Some cleanings, conformed with updated documentation.
                    259: 
1.258     brouard   260:   Revision 1.257  2017/03/29 16:53:30  brouard
                    261:   Summary: Temp
                    262: 
1.257     brouard   263:   Revision 1.256  2017/03/27 05:50:23  brouard
                    264:   Summary: Temporary
                    265: 
1.256     brouard   266:   Revision 1.255  2017/03/08 16:02:28  brouard
                    267:   Summary: IMaCh version 0.99r10 bugs in gnuplot fixed
                    268: 
1.255     brouard   269:   Revision 1.254  2017/03/08 07:13:00  brouard
                    270:   Summary: Fixing data parameter line
                    271: 
1.254     brouard   272:   Revision 1.253  2016/12/15 11:59:41  brouard
                    273:   Summary: 0.99 in progress
                    274: 
1.253     brouard   275:   Revision 1.252  2016/09/15 21:15:37  brouard
                    276:   *** empty log message ***
                    277: 
1.252     brouard   278:   Revision 1.251  2016/09/15 15:01:13  brouard
                    279:   Summary: not working
                    280: 
1.251     brouard   281:   Revision 1.250  2016/09/08 16:07:27  brouard
                    282:   Summary: continue
                    283: 
1.250     brouard   284:   Revision 1.249  2016/09/07 17:14:18  brouard
                    285:   Summary: Starting values from frequencies
                    286: 
1.249     brouard   287:   Revision 1.248  2016/09/07 14:10:18  brouard
                    288:   *** empty log message ***
                    289: 
1.248     brouard   290:   Revision 1.247  2016/09/02 11:11:21  brouard
                    291:   *** empty log message ***
                    292: 
1.247     brouard   293:   Revision 1.246  2016/09/02 08:49:22  brouard
                    294:   *** empty log message ***
                    295: 
1.246     brouard   296:   Revision 1.245  2016/09/02 07:25:01  brouard
                    297:   *** empty log message ***
                    298: 
1.245     brouard   299:   Revision 1.244  2016/09/02 07:17:34  brouard
                    300:   *** empty log message ***
                    301: 
1.244     brouard   302:   Revision 1.243  2016/09/02 06:45:35  brouard
                    303:   *** empty log message ***
                    304: 
1.243     brouard   305:   Revision 1.242  2016/08/30 15:01:20  brouard
                    306:   Summary: Fixing a lots
                    307: 
1.242     brouard   308:   Revision 1.241  2016/08/29 17:17:25  brouard
                    309:   Summary: gnuplot problem in Back projection to fix
                    310: 
1.241     brouard   311:   Revision 1.240  2016/08/29 07:53:18  brouard
                    312:   Summary: Better
                    313: 
1.240     brouard   314:   Revision 1.239  2016/08/26 15:51:03  brouard
                    315:   Summary: Improvement in Powell output in order to copy and paste
                    316: 
                    317:   Author:
                    318: 
1.239     brouard   319:   Revision 1.238  2016/08/26 14:23:35  brouard
                    320:   Summary: Starting tests of 0.99
                    321: 
1.238     brouard   322:   Revision 1.237  2016/08/26 09:20:19  brouard
                    323:   Summary: to valgrind
                    324: 
1.237     brouard   325:   Revision 1.236  2016/08/25 10:50:18  brouard
                    326:   *** empty log message ***
                    327: 
1.236     brouard   328:   Revision 1.235  2016/08/25 06:59:23  brouard
                    329:   *** empty log message ***
                    330: 
1.235     brouard   331:   Revision 1.234  2016/08/23 16:51:20  brouard
                    332:   *** empty log message ***
                    333: 
1.234     brouard   334:   Revision 1.233  2016/08/23 07:40:50  brouard
                    335:   Summary: not working
                    336: 
1.233     brouard   337:   Revision 1.232  2016/08/22 14:20:21  brouard
                    338:   Summary: not working
                    339: 
1.232     brouard   340:   Revision 1.231  2016/08/22 07:17:15  brouard
                    341:   Summary: not working
                    342: 
1.231     brouard   343:   Revision 1.230  2016/08/22 06:55:53  brouard
                    344:   Summary: Not working
                    345: 
1.230     brouard   346:   Revision 1.229  2016/07/23 09:45:53  brouard
                    347:   Summary: Completing for func too
                    348: 
1.229     brouard   349:   Revision 1.228  2016/07/22 17:45:30  brouard
                    350:   Summary: Fixing some arrays, still debugging
                    351: 
1.227     brouard   352:   Revision 1.226  2016/07/12 18:42:34  brouard
                    353:   Summary: temp
                    354: 
1.226     brouard   355:   Revision 1.225  2016/07/12 08:40:03  brouard
                    356:   Summary: saving but not running
                    357: 
1.225     brouard   358:   Revision 1.224  2016/07/01 13:16:01  brouard
                    359:   Summary: Fixes
                    360: 
1.224     brouard   361:   Revision 1.223  2016/02/19 09:23:35  brouard
                    362:   Summary: temporary
                    363: 
1.223     brouard   364:   Revision 1.222  2016/02/17 08:14:50  brouard
                    365:   Summary: Probably last 0.98 stable version 0.98r6
                    366: 
1.222     brouard   367:   Revision 1.221  2016/02/15 23:35:36  brouard
                    368:   Summary: minor bug
                    369: 
1.220     brouard   370:   Revision 1.219  2016/02/15 00:48:12  brouard
                    371:   *** empty log message ***
                    372: 
1.219     brouard   373:   Revision 1.218  2016/02/12 11:29:23  brouard
                    374:   Summary: 0.99 Back projections
                    375: 
1.218     brouard   376:   Revision 1.217  2015/12/23 17:18:31  brouard
                    377:   Summary: Experimental backcast
                    378: 
1.217     brouard   379:   Revision 1.216  2015/12/18 17:32:11  brouard
                    380:   Summary: 0.98r4 Warning and status=-2
                    381: 
                    382:   Version 0.98r4 is now:
                    383:    - displaying an error when status is -1, date of interview unknown and date of death known;
                    384:    - permitting a status -2 when the vital status is unknown at a known date of right truncation.
                    385:   Older changes concerning s=-2, dating from 2005 have been supersed.
                    386: 
1.216     brouard   387:   Revision 1.215  2015/12/16 08:52:24  brouard
                    388:   Summary: 0.98r4 working
                    389: 
1.215     brouard   390:   Revision 1.214  2015/12/16 06:57:54  brouard
                    391:   Summary: temporary not working
                    392: 
1.214     brouard   393:   Revision 1.213  2015/12/11 18:22:17  brouard
                    394:   Summary: 0.98r4
                    395: 
1.213     brouard   396:   Revision 1.212  2015/11/21 12:47:24  brouard
                    397:   Summary: minor typo
                    398: 
1.212     brouard   399:   Revision 1.211  2015/11/21 12:41:11  brouard
                    400:   Summary: 0.98r3 with some graph of projected cross-sectional
                    401: 
                    402:   Author: Nicolas Brouard
                    403: 
1.211     brouard   404:   Revision 1.210  2015/11/18 17:41:20  brouard
1.252     brouard   405:   Summary: Start working on projected prevalences  Revision 1.209  2015/11/17 22:12:03  brouard
1.210     brouard   406:   Summary: Adding ftolpl parameter
                    407:   Author: N Brouard
                    408: 
                    409:   We had difficulties to get smoothed confidence intervals. It was due
                    410:   to the period prevalence which wasn't computed accurately. The inner
                    411:   parameter ftolpl is now an outer parameter of the .imach parameter
                    412:   file after estepm. If ftolpl is small 1.e-4 and estepm too,
                    413:   computation are long.
                    414: 
1.209     brouard   415:   Revision 1.208  2015/11/17 14:31:57  brouard
                    416:   Summary: temporary
                    417: 
1.208     brouard   418:   Revision 1.207  2015/10/27 17:36:57  brouard
                    419:   *** empty log message ***
                    420: 
1.207     brouard   421:   Revision 1.206  2015/10/24 07:14:11  brouard
                    422:   *** empty log message ***
                    423: 
1.206     brouard   424:   Revision 1.205  2015/10/23 15:50:53  brouard
                    425:   Summary: 0.98r3 some clarification for graphs on likelihood contributions
                    426: 
1.205     brouard   427:   Revision 1.204  2015/10/01 16:20:26  brouard
                    428:   Summary: Some new graphs of contribution to likelihood
                    429: 
1.204     brouard   430:   Revision 1.203  2015/09/30 17:45:14  brouard
                    431:   Summary: looking at better estimation of the hessian
                    432: 
                    433:   Also a better criteria for convergence to the period prevalence And
                    434:   therefore adding the number of years needed to converge. (The
                    435:   prevalence in any alive state shold sum to one
                    436: 
1.203     brouard   437:   Revision 1.202  2015/09/22 19:45:16  brouard
                    438:   Summary: Adding some overall graph on contribution to likelihood. Might change
                    439: 
1.202     brouard   440:   Revision 1.201  2015/09/15 17:34:58  brouard
                    441:   Summary: 0.98r0
                    442: 
                    443:   - Some new graphs like suvival functions
                    444:   - Some bugs fixed like model=1+age+V2.
                    445: 
1.201     brouard   446:   Revision 1.200  2015/09/09 16:53:55  brouard
                    447:   Summary: Big bug thanks to Flavia
                    448: 
                    449:   Even model=1+age+V2. did not work anymore
                    450: 
1.200     brouard   451:   Revision 1.199  2015/09/07 14:09:23  brouard
                    452:   Summary: 0.98q6 changing default small png format for graph to vectorized svg.
                    453: 
1.199     brouard   454:   Revision 1.198  2015/09/03 07:14:39  brouard
                    455:   Summary: 0.98q5 Flavia
                    456: 
1.198     brouard   457:   Revision 1.197  2015/09/01 18:24:39  brouard
                    458:   *** empty log message ***
                    459: 
1.197     brouard   460:   Revision 1.196  2015/08/18 23:17:52  brouard
                    461:   Summary: 0.98q5
                    462: 
1.196     brouard   463:   Revision 1.195  2015/08/18 16:28:39  brouard
                    464:   Summary: Adding a hack for testing purpose
                    465: 
                    466:   After reading the title, ftol and model lines, if the comment line has
                    467:   a q, starting with #q, the answer at the end of the run is quit. It
                    468:   permits to run test files in batch with ctest. The former workaround was
                    469:   $ echo q | imach foo.imach
                    470: 
1.195     brouard   471:   Revision 1.194  2015/08/18 13:32:00  brouard
                    472:   Summary:  Adding error when the covariance matrix doesn't contain the exact number of lines required by the model line.
                    473: 
1.194     brouard   474:   Revision 1.193  2015/08/04 07:17:42  brouard
                    475:   Summary: 0.98q4
                    476: 
1.193     brouard   477:   Revision 1.192  2015/07/16 16:49:02  brouard
                    478:   Summary: Fixing some outputs
                    479: 
1.192     brouard   480:   Revision 1.191  2015/07/14 10:00:33  brouard
                    481:   Summary: Some fixes
                    482: 
1.191     brouard   483:   Revision 1.190  2015/05/05 08:51:13  brouard
                    484:   Summary: Adding digits in output parameters (7 digits instead of 6)
                    485: 
                    486:   Fix 1+age+.
                    487: 
1.190     brouard   488:   Revision 1.189  2015/04/30 14:45:16  brouard
                    489:   Summary: 0.98q2
                    490: 
1.189     brouard   491:   Revision 1.188  2015/04/30 08:27:53  brouard
                    492:   *** empty log message ***
                    493: 
1.188     brouard   494:   Revision 1.187  2015/04/29 09:11:15  brouard
                    495:   *** empty log message ***
                    496: 
1.187     brouard   497:   Revision 1.186  2015/04/23 12:01:52  brouard
                    498:   Summary: V1*age is working now, version 0.98q1
                    499: 
                    500:   Some codes had been disabled in order to simplify and Vn*age was
                    501:   working in the optimization phase, ie, giving correct MLE parameters,
                    502:   but, as usual, outputs were not correct and program core dumped.
                    503: 
1.186     brouard   504:   Revision 1.185  2015/03/11 13:26:42  brouard
                    505:   Summary: Inclusion of compile and links command line for Intel Compiler
                    506: 
1.185     brouard   507:   Revision 1.184  2015/03/11 11:52:39  brouard
                    508:   Summary: Back from Windows 8. Intel Compiler
                    509: 
1.184     brouard   510:   Revision 1.183  2015/03/10 20:34:32  brouard
                    511:   Summary: 0.98q0, trying with directest, mnbrak fixed
                    512: 
                    513:   We use directest instead of original Powell test; probably no
                    514:   incidence on the results, but better justifications;
                    515:   We fixed Numerical Recipes mnbrak routine which was wrong and gave
                    516:   wrong results.
                    517: 
1.183     brouard   518:   Revision 1.182  2015/02/12 08:19:57  brouard
                    519:   Summary: Trying to keep directest which seems simpler and more general
                    520:   Author: Nicolas Brouard
                    521: 
1.182     brouard   522:   Revision 1.181  2015/02/11 23:22:24  brouard
                    523:   Summary: Comments on Powell added
                    524: 
                    525:   Author:
                    526: 
1.181     brouard   527:   Revision 1.180  2015/02/11 17:33:45  brouard
                    528:   Summary: Finishing move from main to function (hpijx and prevalence_limit)
                    529: 
1.180     brouard   530:   Revision 1.179  2015/01/04 09:57:06  brouard
                    531:   Summary: back to OS/X
                    532: 
1.179     brouard   533:   Revision 1.178  2015/01/04 09:35:48  brouard
                    534:   *** empty log message ***
                    535: 
1.178     brouard   536:   Revision 1.177  2015/01/03 18:40:56  brouard
                    537:   Summary: Still testing ilc32 on OSX
                    538: 
1.177     brouard   539:   Revision 1.176  2015/01/03 16:45:04  brouard
                    540:   *** empty log message ***
                    541: 
1.176     brouard   542:   Revision 1.175  2015/01/03 16:33:42  brouard
                    543:   *** empty log message ***
                    544: 
1.175     brouard   545:   Revision 1.174  2015/01/03 16:15:49  brouard
                    546:   Summary: Still in cross-compilation
                    547: 
1.174     brouard   548:   Revision 1.173  2015/01/03 12:06:26  brouard
                    549:   Summary: trying to detect cross-compilation
                    550: 
1.173     brouard   551:   Revision 1.172  2014/12/27 12:07:47  brouard
                    552:   Summary: Back from Visual Studio and Intel, options for compiling for Windows XP
                    553: 
1.172     brouard   554:   Revision 1.171  2014/12/23 13:26:59  brouard
                    555:   Summary: Back from Visual C
                    556: 
                    557:   Still problem with utsname.h on Windows
                    558: 
1.171     brouard   559:   Revision 1.170  2014/12/23 11:17:12  brouard
                    560:   Summary: Cleaning some \%% back to %%
                    561: 
                    562:   The escape was mandatory for a specific compiler (which one?), but too many warnings.
                    563: 
1.170     brouard   564:   Revision 1.169  2014/12/22 23:08:31  brouard
                    565:   Summary: 0.98p
                    566: 
                    567:   Outputs some informations on compiler used, OS etc. Testing on different platforms.
                    568: 
1.169     brouard   569:   Revision 1.168  2014/12/22 15:17:42  brouard
1.170     brouard   570:   Summary: update
1.169     brouard   571: 
1.168     brouard   572:   Revision 1.167  2014/12/22 13:50:56  brouard
                    573:   Summary: Testing uname and compiler version and if compiled 32 or 64
                    574: 
                    575:   Testing on Linux 64
                    576: 
1.167     brouard   577:   Revision 1.166  2014/12/22 11:40:47  brouard
                    578:   *** empty log message ***
                    579: 
1.166     brouard   580:   Revision 1.165  2014/12/16 11:20:36  brouard
                    581:   Summary: After compiling on Visual C
                    582: 
                    583:   * imach.c (Module): Merging 1.61 to 1.162
                    584: 
1.165     brouard   585:   Revision 1.164  2014/12/16 10:52:11  brouard
                    586:   Summary: Merging with Visual C after suppressing some warnings for unused variables. Also fixing Saito's bug 0.98Xn
                    587: 
                    588:   * imach.c (Module): Merging 1.61 to 1.162
                    589: 
1.164     brouard   590:   Revision 1.163  2014/12/16 10:30:11  brouard
                    591:   * imach.c (Module): Merging 1.61 to 1.162
                    592: 
1.163     brouard   593:   Revision 1.162  2014/09/25 11:43:39  brouard
                    594:   Summary: temporary backup 0.99!
                    595: 
1.162     brouard   596:   Revision 1.1  2014/09/16 11:06:58  brouard
                    597:   Summary: With some code (wrong) for nlopt
                    598: 
                    599:   Author:
                    600: 
                    601:   Revision 1.161  2014/09/15 20:41:41  brouard
                    602:   Summary: Problem with macro SQR on Intel compiler
                    603: 
1.161     brouard   604:   Revision 1.160  2014/09/02 09:24:05  brouard
                    605:   *** empty log message ***
                    606: 
1.160     brouard   607:   Revision 1.159  2014/09/01 10:34:10  brouard
                    608:   Summary: WIN32
                    609:   Author: Brouard
                    610: 
1.159     brouard   611:   Revision 1.158  2014/08/27 17:11:51  brouard
                    612:   *** empty log message ***
                    613: 
1.158     brouard   614:   Revision 1.157  2014/08/27 16:26:55  brouard
                    615:   Summary: Preparing windows Visual studio version
                    616:   Author: Brouard
                    617: 
                    618:   In order to compile on Visual studio, time.h is now correct and time_t
                    619:   and tm struct should be used. difftime should be used but sometimes I
                    620:   just make the differences in raw time format (time(&now).
                    621:   Trying to suppress #ifdef LINUX
                    622:   Add xdg-open for __linux in order to open default browser.
                    623: 
1.157     brouard   624:   Revision 1.156  2014/08/25 20:10:10  brouard
                    625:   *** empty log message ***
                    626: 
1.156     brouard   627:   Revision 1.155  2014/08/25 18:32:34  brouard
                    628:   Summary: New compile, minor changes
                    629:   Author: Brouard
                    630: 
1.155     brouard   631:   Revision 1.154  2014/06/20 17:32:08  brouard
                    632:   Summary: Outputs now all graphs of convergence to period prevalence
                    633: 
1.154     brouard   634:   Revision 1.153  2014/06/20 16:45:46  brouard
                    635:   Summary: If 3 live state, convergence to period prevalence on same graph
                    636:   Author: Brouard
                    637: 
1.153     brouard   638:   Revision 1.152  2014/06/18 17:54:09  brouard
                    639:   Summary: open browser, use gnuplot on same dir than imach if not found in the path
                    640: 
1.152     brouard   641:   Revision 1.151  2014/06/18 16:43:30  brouard
                    642:   *** empty log message ***
                    643: 
1.151     brouard   644:   Revision 1.150  2014/06/18 16:42:35  brouard
                    645:   Summary: If gnuplot is not in the path try on same directory than imach binary (OSX)
                    646:   Author: brouard
                    647: 
1.150     brouard   648:   Revision 1.149  2014/06/18 15:51:14  brouard
                    649:   Summary: Some fixes in parameter files errors
                    650:   Author: Nicolas Brouard
                    651: 
1.149     brouard   652:   Revision 1.148  2014/06/17 17:38:48  brouard
                    653:   Summary: Nothing new
                    654:   Author: Brouard
                    655: 
                    656:   Just a new packaging for OS/X version 0.98nS
                    657: 
1.148     brouard   658:   Revision 1.147  2014/06/16 10:33:11  brouard
                    659:   *** empty log message ***
                    660: 
1.147     brouard   661:   Revision 1.146  2014/06/16 10:20:28  brouard
                    662:   Summary: Merge
                    663:   Author: Brouard
                    664: 
                    665:   Merge, before building revised version.
                    666: 
1.146     brouard   667:   Revision 1.145  2014/06/10 21:23:15  brouard
                    668:   Summary: Debugging with valgrind
                    669:   Author: Nicolas Brouard
                    670: 
                    671:   Lot of changes in order to output the results with some covariates
                    672:   After the Edimburgh REVES conference 2014, it seems mandatory to
                    673:   improve the code.
                    674:   No more memory valgrind error but a lot has to be done in order to
                    675:   continue the work of splitting the code into subroutines.
                    676:   Also, decodemodel has been improved. Tricode is still not
                    677:   optimal. nbcode should be improved. Documentation has been added in
                    678:   the source code.
                    679: 
1.144     brouard   680:   Revision 1.143  2014/01/26 09:45:38  brouard
                    681:   Summary: Version 0.98nR (to be improved, but gives same optimization results as 0.98k. Nice, promising
                    682: 
                    683:   * imach.c (Module): Trying to merge old staffs together while being at Tokyo. Not tested...
                    684:   (Module): Version 0.98nR Running ok, but output format still only works for three covariates.
                    685: 
1.143     brouard   686:   Revision 1.142  2014/01/26 03:57:36  brouard
                    687:   Summary: gnuplot changed plot w l 1 has to be changed to plot w l lt 2
                    688: 
                    689:   * imach.c (Module): Trying to merge old staffs together while being at Tokyo. Not tested...
                    690: 
1.142     brouard   691:   Revision 1.141  2014/01/26 02:42:01  brouard
                    692:   * imach.c (Module): Trying to merge old staffs together while being at Tokyo. Not tested...
                    693: 
1.141     brouard   694:   Revision 1.140  2011/09/02 10:37:54  brouard
                    695:   Summary: times.h is ok with mingw32 now.
                    696: 
1.140     brouard   697:   Revision 1.139  2010/06/14 07:50:17  brouard
                    698:   After the theft of my laptop, I probably lost some lines of codes which were not uploaded to the CVS tree.
                    699:   I remember having already fixed agemin agemax which are pointers now but not cvs saved.
                    700: 
1.139     brouard   701:   Revision 1.138  2010/04/30 18:19:40  brouard
                    702:   *** empty log message ***
                    703: 
1.138     brouard   704:   Revision 1.137  2010/04/29 18:11:38  brouard
                    705:   (Module): Checking covariates for more complex models
                    706:   than V1+V2. A lot of change to be done. Unstable.
                    707: 
1.137     brouard   708:   Revision 1.136  2010/04/26 20:30:53  brouard
                    709:   (Module): merging some libgsl code. Fixing computation
                    710:   of likelione (using inter/intrapolation if mle = 0) in order to
                    711:   get same likelihood as if mle=1.
                    712:   Some cleaning of code and comments added.
                    713: 
1.136     brouard   714:   Revision 1.135  2009/10/29 15:33:14  brouard
                    715:   (Module): Now imach stops if date of birth, at least year of birth, is not given. Some cleaning of the code.
                    716: 
1.135     brouard   717:   Revision 1.134  2009/10/29 13:18:53  brouard
                    718:   (Module): Now imach stops if date of birth, at least year of birth, is not given. Some cleaning of the code.
                    719: 
1.134     brouard   720:   Revision 1.133  2009/07/06 10:21:25  brouard
                    721:   just nforces
                    722: 
1.133     brouard   723:   Revision 1.132  2009/07/06 08:22:05  brouard
                    724:   Many tings
                    725: 
1.132     brouard   726:   Revision 1.131  2009/06/20 16:22:47  brouard
                    727:   Some dimensions resccaled
                    728: 
1.131     brouard   729:   Revision 1.130  2009/05/26 06:44:34  brouard
                    730:   (Module): Max Covariate is now set to 20 instead of 8. A
                    731:   lot of cleaning with variables initialized to 0. Trying to make
                    732:   V2+V3*age+V1+V4 strb=V3*age+V1+V4 working better.
                    733: 
1.130     brouard   734:   Revision 1.129  2007/08/31 13:49:27  lievre
                    735:   Modification of the way of exiting when the covariate is not binary in order to see on the window the error message before exiting
                    736: 
1.129     lievre    737:   Revision 1.128  2006/06/30 13:02:05  brouard
                    738:   (Module): Clarifications on computing e.j
                    739: 
1.128     brouard   740:   Revision 1.127  2006/04/28 18:11:50  brouard
                    741:   (Module): Yes the sum of survivors was wrong since
                    742:   imach-114 because nhstepm was no more computed in the age
                    743:   loop. Now we define nhstepma in the age loop.
                    744:   (Module): In order to speed up (in case of numerous covariates) we
                    745:   compute health expectancies (without variances) in a first step
                    746:   and then all the health expectancies with variances or standard
                    747:   deviation (needs data from the Hessian matrices) which slows the
                    748:   computation.
                    749:   In the future we should be able to stop the program is only health
                    750:   expectancies and graph are needed without standard deviations.
                    751: 
1.127     brouard   752:   Revision 1.126  2006/04/28 17:23:28  brouard
                    753:   (Module): Yes the sum of survivors was wrong since
                    754:   imach-114 because nhstepm was no more computed in the age
                    755:   loop. Now we define nhstepma in the age loop.
                    756:   Version 0.98h
                    757: 
1.126     brouard   758:   Revision 1.125  2006/04/04 15:20:31  lievre
                    759:   Errors in calculation of health expectancies. Age was not initialized.
                    760:   Forecasting file added.
                    761: 
                    762:   Revision 1.124  2006/03/22 17:13:53  lievre
                    763:   Parameters are printed with %lf instead of %f (more numbers after the comma).
                    764:   The log-likelihood is printed in the log file
                    765: 
                    766:   Revision 1.123  2006/03/20 10:52:43  brouard
                    767:   * imach.c (Module): <title> changed, corresponds to .htm file
                    768:   name. <head> headers where missing.
                    769: 
                    770:   * imach.c (Module): Weights can have a decimal point as for
                    771:   English (a comma might work with a correct LC_NUMERIC environment,
                    772:   otherwise the weight is truncated).
                    773:   Modification of warning when the covariates values are not 0 or
                    774:   1.
                    775:   Version 0.98g
                    776: 
                    777:   Revision 1.122  2006/03/20 09:45:41  brouard
                    778:   (Module): Weights can have a decimal point as for
                    779:   English (a comma might work with a correct LC_NUMERIC environment,
                    780:   otherwise the weight is truncated).
                    781:   Modification of warning when the covariates values are not 0 or
                    782:   1.
                    783:   Version 0.98g
                    784: 
                    785:   Revision 1.121  2006/03/16 17:45:01  lievre
                    786:   * imach.c (Module): Comments concerning covariates added
                    787: 
                    788:   * imach.c (Module): refinements in the computation of lli if
                    789:   status=-2 in order to have more reliable computation if stepm is
                    790:   not 1 month. Version 0.98f
                    791: 
                    792:   Revision 1.120  2006/03/16 15:10:38  lievre
                    793:   (Module): refinements in the computation of lli if
                    794:   status=-2 in order to have more reliable computation if stepm is
                    795:   not 1 month. Version 0.98f
                    796: 
                    797:   Revision 1.119  2006/03/15 17:42:26  brouard
                    798:   (Module): Bug if status = -2, the loglikelihood was
                    799:   computed as likelihood omitting the logarithm. Version O.98e
                    800: 
                    801:   Revision 1.118  2006/03/14 18:20:07  brouard
                    802:   (Module): varevsij Comments added explaining the second
                    803:   table of variances if popbased=1 .
                    804:   (Module): Covariances of eij, ekl added, graphs fixed, new html link.
                    805:   (Module): Function pstamp added
                    806:   (Module): Version 0.98d
                    807: 
                    808:   Revision 1.117  2006/03/14 17:16:22  brouard
                    809:   (Module): varevsij Comments added explaining the second
                    810:   table of variances if popbased=1 .
                    811:   (Module): Covariances of eij, ekl added, graphs fixed, new html link.
                    812:   (Module): Function pstamp added
                    813:   (Module): Version 0.98d
                    814: 
                    815:   Revision 1.116  2006/03/06 10:29:27  brouard
                    816:   (Module): Variance-covariance wrong links and
                    817:   varian-covariance of ej. is needed (Saito).
                    818: 
                    819:   Revision 1.115  2006/02/27 12:17:45  brouard
                    820:   (Module): One freematrix added in mlikeli! 0.98c
                    821: 
                    822:   Revision 1.114  2006/02/26 12:57:58  brouard
                    823:   (Module): Some improvements in processing parameter
                    824:   filename with strsep.
                    825: 
                    826:   Revision 1.113  2006/02/24 14:20:24  brouard
                    827:   (Module): Memory leaks checks with valgrind and:
                    828:   datafile was not closed, some imatrix were not freed and on matrix
                    829:   allocation too.
                    830: 
                    831:   Revision 1.112  2006/01/30 09:55:26  brouard
                    832:   (Module): Back to gnuplot.exe instead of wgnuplot.exe
                    833: 
                    834:   Revision 1.111  2006/01/25 20:38:18  brouard
                    835:   (Module): Lots of cleaning and bugs added (Gompertz)
                    836:   (Module): Comments can be added in data file. Missing date values
                    837:   can be a simple dot '.'.
                    838: 
                    839:   Revision 1.110  2006/01/25 00:51:50  brouard
                    840:   (Module): Lots of cleaning and bugs added (Gompertz)
                    841: 
                    842:   Revision 1.109  2006/01/24 19:37:15  brouard
                    843:   (Module): Comments (lines starting with a #) are allowed in data.
                    844: 
                    845:   Revision 1.108  2006/01/19 18:05:42  lievre
                    846:   Gnuplot problem appeared...
                    847:   To be fixed
                    848: 
                    849:   Revision 1.107  2006/01/19 16:20:37  brouard
                    850:   Test existence of gnuplot in imach path
                    851: 
                    852:   Revision 1.106  2006/01/19 13:24:36  brouard
                    853:   Some cleaning and links added in html output
                    854: 
                    855:   Revision 1.105  2006/01/05 20:23:19  lievre
                    856:   *** empty log message ***
                    857: 
                    858:   Revision 1.104  2005/09/30 16:11:43  lievre
                    859:   (Module): sump fixed, loop imx fixed, and simplifications.
                    860:   (Module): If the status is missing at the last wave but we know
                    861:   that the person is alive, then we can code his/her status as -2
                    862:   (instead of missing=-1 in earlier versions) and his/her
                    863:   contributions to the likelihood is 1 - Prob of dying from last
                    864:   health status (= 1-p13= p11+p12 in the easiest case of somebody in
                    865:   the healthy state at last known wave). Version is 0.98
                    866: 
                    867:   Revision 1.103  2005/09/30 15:54:49  lievre
                    868:   (Module): sump fixed, loop imx fixed, and simplifications.
                    869: 
                    870:   Revision 1.102  2004/09/15 17:31:30  brouard
                    871:   Add the possibility to read data file including tab characters.
                    872: 
                    873:   Revision 1.101  2004/09/15 10:38:38  brouard
                    874:   Fix on curr_time
                    875: 
                    876:   Revision 1.100  2004/07/12 18:29:06  brouard
                    877:   Add version for Mac OS X. Just define UNIX in Makefile
                    878: 
                    879:   Revision 1.99  2004/06/05 08:57:40  brouard
                    880:   *** empty log message ***
                    881: 
                    882:   Revision 1.98  2004/05/16 15:05:56  brouard
                    883:   New version 0.97 . First attempt to estimate force of mortality
                    884:   directly from the data i.e. without the need of knowing the health
                    885:   state at each age, but using a Gompertz model: log u =a + b*age .
                    886:   This is the basic analysis of mortality and should be done before any
                    887:   other analysis, in order to test if the mortality estimated from the
                    888:   cross-longitudinal survey is different from the mortality estimated
                    889:   from other sources like vital statistic data.
                    890: 
                    891:   The same imach parameter file can be used but the option for mle should be -3.
                    892: 
1.324     brouard   893:   Agnès, who wrote this part of the code, tried to keep most of the
1.126     brouard   894:   former routines in order to include the new code within the former code.
                    895: 
                    896:   The output is very simple: only an estimate of the intercept and of
                    897:   the slope with 95% confident intervals.
                    898: 
                    899:   Current limitations:
                    900:   A) Even if you enter covariates, i.e. with the
                    901:   model= V1+V2 equation for example, the programm does only estimate a unique global model without covariates.
                    902:   B) There is no computation of Life Expectancy nor Life Table.
                    903: 
                    904:   Revision 1.97  2004/02/20 13:25:42  lievre
                    905:   Version 0.96d. Population forecasting command line is (temporarily)
                    906:   suppressed.
                    907: 
                    908:   Revision 1.96  2003/07/15 15:38:55  brouard
                    909:   * imach.c (Repository): Errors in subdirf, 2, 3 while printing tmpout is
                    910:   rewritten within the same printf. Workaround: many printfs.
                    911: 
                    912:   Revision 1.95  2003/07/08 07:54:34  brouard
                    913:   * imach.c (Repository):
                    914:   (Repository): Using imachwizard code to output a more meaningful covariance
                    915:   matrix (cov(a12,c31) instead of numbers.
                    916: 
                    917:   Revision 1.94  2003/06/27 13:00:02  brouard
                    918:   Just cleaning
                    919: 
                    920:   Revision 1.93  2003/06/25 16:33:55  brouard
                    921:   (Module): On windows (cygwin) function asctime_r doesn't
                    922:   exist so I changed back to asctime which exists.
                    923:   (Module): Version 0.96b
                    924: 
                    925:   Revision 1.92  2003/06/25 16:30:45  brouard
                    926:   (Module): On windows (cygwin) function asctime_r doesn't
                    927:   exist so I changed back to asctime which exists.
                    928: 
                    929:   Revision 1.91  2003/06/25 15:30:29  brouard
                    930:   * imach.c (Repository): Duplicated warning errors corrected.
                    931:   (Repository): Elapsed time after each iteration is now output. It
                    932:   helps to forecast when convergence will be reached. Elapsed time
                    933:   is stamped in powell.  We created a new html file for the graphs
                    934:   concerning matrix of covariance. It has extension -cov.htm.
                    935: 
                    936:   Revision 1.90  2003/06/24 12:34:15  brouard
                    937:   (Module): Some bugs corrected for windows. Also, when
                    938:   mle=-1 a template is output in file "or"mypar.txt with the design
                    939:   of the covariance matrix to be input.
                    940: 
                    941:   Revision 1.89  2003/06/24 12:30:52  brouard
                    942:   (Module): Some bugs corrected for windows. Also, when
                    943:   mle=-1 a template is output in file "or"mypar.txt with the design
                    944:   of the covariance matrix to be input.
                    945: 
                    946:   Revision 1.88  2003/06/23 17:54:56  brouard
                    947:   * 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.
                    948: 
                    949:   Revision 1.87  2003/06/18 12:26:01  brouard
                    950:   Version 0.96
                    951: 
                    952:   Revision 1.86  2003/06/17 20:04:08  brouard
                    953:   (Module): Change position of html and gnuplot routines and added
                    954:   routine fileappend.
                    955: 
                    956:   Revision 1.85  2003/06/17 13:12:43  brouard
                    957:   * imach.c (Repository): Check when date of death was earlier that
                    958:   current date of interview. It may happen when the death was just
                    959:   prior to the death. In this case, dh was negative and likelihood
                    960:   was wrong (infinity). We still send an "Error" but patch by
                    961:   assuming that the date of death was just one stepm after the
                    962:   interview.
                    963:   (Repository): Because some people have very long ID (first column)
                    964:   we changed int to long in num[] and we added a new lvector for
                    965:   memory allocation. But we also truncated to 8 characters (left
                    966:   truncation)
                    967:   (Repository): No more line truncation errors.
                    968: 
                    969:   Revision 1.84  2003/06/13 21:44:43  brouard
                    970:   * imach.c (Repository): Replace "freqsummary" at a correct
                    971:   place. It differs from routine "prevalence" which may be called
                    972:   many times. Probs is memory consuming and must be used with
                    973:   parcimony.
                    974:   Version 0.95a3 (should output exactly the same maximization than 0.8a2)
                    975: 
                    976:   Revision 1.83  2003/06/10 13:39:11  lievre
                    977:   *** empty log message ***
                    978: 
                    979:   Revision 1.82  2003/06/05 15:57:20  brouard
                    980:   Add log in  imach.c and  fullversion number is now printed.
                    981: 
                    982: */
                    983: /*
                    984:    Interpolated Markov Chain
                    985: 
                    986:   Short summary of the programme:
                    987:   
1.227     brouard   988:   This program computes Healthy Life Expectancies or State-specific
                    989:   (if states aren't health statuses) Expectancies from
                    990:   cross-longitudinal data. Cross-longitudinal data consist in: 
                    991: 
                    992:   -1- a first survey ("cross") where individuals from different ages
                    993:   are interviewed on their health status or degree of disability (in
                    994:   the case of a health survey which is our main interest)
                    995: 
                    996:   -2- at least a second wave of interviews ("longitudinal") which
                    997:   measure each change (if any) in individual health status.  Health
                    998:   expectancies are computed from the time spent in each health state
                    999:   according to a model. More health states you consider, more time is
                   1000:   necessary to reach the Maximum Likelihood of the parameters involved
                   1001:   in the model.  The simplest model is the multinomial logistic model
                   1002:   where pij is the probability to be observed in state j at the second
                   1003:   wave conditional to be observed in state i at the first
                   1004:   wave. Therefore the model is: log(pij/pii)= aij + bij*age+ cij*sex +
                   1005:   etc , where 'age' is age and 'sex' is a covariate. If you want to
                   1006:   have a more complex model than "constant and age", you should modify
                   1007:   the program where the markup *Covariates have to be included here
                   1008:   again* invites you to do it.  More covariates you add, slower the
1.126     brouard  1009:   convergence.
                   1010: 
                   1011:   The advantage of this computer programme, compared to a simple
                   1012:   multinomial logistic model, is clear when the delay between waves is not
                   1013:   identical for each individual. Also, if a individual missed an
                   1014:   intermediate interview, the information is lost, but taken into
                   1015:   account using an interpolation or extrapolation.  
                   1016: 
                   1017:   hPijx is the probability to be observed in state i at age x+h
                   1018:   conditional to the observed state i at age x. The delay 'h' can be
                   1019:   split into an exact number (nh*stepm) of unobserved intermediate
                   1020:   states. This elementary transition (by month, quarter,
                   1021:   semester or year) is modelled as a multinomial logistic.  The hPx
                   1022:   matrix is simply the matrix product of nh*stepm elementary matrices
                   1023:   and the contribution of each individual to the likelihood is simply
                   1024:   hPijx.
                   1025: 
                   1026:   Also this programme outputs the covariance matrix of the parameters but also
1.218     brouard  1027:   of the life expectancies. It also computes the period (stable) prevalence.
                   1028: 
                   1029: Back prevalence and projections:
1.227     brouard  1030: 
                   1031:  - back_prevalence_limit(double *p, double **bprlim, double ageminpar,
                   1032:    double agemaxpar, double ftolpl, int *ncvyearp, double
                   1033:    dateprev1,double dateprev2, int firstpass, int lastpass, int
                   1034:    mobilavproj)
                   1035: 
                   1036:     Computes the back prevalence limit for any combination of
                   1037:     covariate values k at any age between ageminpar and agemaxpar and
                   1038:     returns it in **bprlim. In the loops,
                   1039: 
                   1040:    - **bprevalim(**bprlim, ***mobaverage, nlstate, *p, age, **oldm,
                   1041:        **savm, **dnewm, **doldm, **dsavm, ftolpl, ncvyearp, k);
                   1042: 
                   1043:    - hBijx Back Probability to be in state i at age x-h being in j at x
1.218     brouard  1044:    Computes for any combination of covariates k and any age between bage and fage 
                   1045:    p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   1046:                        oldm=oldms;savm=savms;
1.227     brouard  1047: 
1.267     brouard  1048:    - hbxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k, nres);
1.218     brouard  1049:      Computes the transition matrix starting at age 'age' over
                   1050:      'nhstepm*hstepm*stepm' months (i.e. until
                   1051:      age (in years)  age+nhstepm*hstepm*stepm/12) by multiplying
1.227     brouard  1052:      nhstepm*hstepm matrices. 
                   1053: 
                   1054:      Returns p3mat[i][j][h] after calling
                   1055:      p3mat[i][j][h]=matprod2(newm,
                   1056:      bmij(pmmij,cov,ncovmodel,x,nlstate,prevacurrent, dnewm, doldm,
                   1057:      dsavm,ij),\ 1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath,
                   1058:      oldm);
1.226     brouard  1059: 
                   1060: Important routines
                   1061: 
                   1062: - func (or funcone), computes logit (pij) distinguishing
                   1063:   o fixed variables (single or product dummies or quantitative);
                   1064:   o varying variables by:
                   1065:    (1) wave (single, product dummies, quantitative), 
                   1066:    (2) by age (can be month) age (done), age*age (done), age*Vn where Vn can be:
                   1067:        % fixed dummy (treated) or quantitative (not done because time-consuming);
                   1068:        % varying dummy (not done) or quantitative (not done);
                   1069: - Tricode which tests the modality of dummy variables (in order to warn with wrong or empty modalities)
                   1070:   and returns the number of efficient covariates cptcoveff and modalities nbcode[Tvar[k]][1]= 0 and nbcode[Tvar[k]][2]= 1 usually.
                   1071: - printinghtml which outputs results like life expectancy in and from a state for a combination of modalities of dummy variables
1.325     brouard  1072:   o There are 2**cptcoveff combinations of (0,1) for cptcoveff variables. Outputting only combinations with people, éliminating 1 1 if
1.226     brouard  1073:     race White (0 0), Black vs White (1 0), Hispanic (0 1) and 1 1 being meaningless.
1.218     brouard  1074: 
1.226     brouard  1075: 
                   1076:   
1.324     brouard  1077:   Authors: Nicolas Brouard (brouard@ined.fr) and Agnès Lièvre (lievre@ined.fr).
                   1078:            Institut national d'études démographiques, Paris.
1.126     brouard  1079:   This software have been partly granted by Euro-REVES, a concerted action
                   1080:   from the European Union.
                   1081:   It is copyrighted identically to a GNU software product, ie programme and
                   1082:   software can be distributed freely for non commercial use. Latest version
                   1083:   can be accessed at http://euroreves.ined.fr/imach .
                   1084: 
                   1085:   Help to debug: LD_PRELOAD=/usr/local/lib/libnjamd.so ./imach foo.imach
                   1086:   or better on gdb : set env LD_PRELOAD=/usr/local/lib/libnjamd.so
                   1087:   
                   1088:   **********************************************************************/
                   1089: /*
                   1090:   main
                   1091:   read parameterfile
                   1092:   read datafile
                   1093:   concatwav
                   1094:   freqsummary
                   1095:   if (mle >= 1)
                   1096:     mlikeli
                   1097:   print results files
                   1098:   if mle==1 
                   1099:      computes hessian
                   1100:   read end of parameter file: agemin, agemax, bage, fage, estepm
                   1101:       begin-prev-date,...
                   1102:   open gnuplot file
                   1103:   open html file
1.145     brouard  1104:   period (stable) prevalence      | pl_nom    1-1 2-2 etc by covariate
                   1105:    for age prevalim()             | #****** V1=0  V2=1  V3=1  V4=0 ******
                   1106:                                   | 65 1 0 2 1 3 1 4 0  0.96326 0.03674
                   1107:     freexexit2 possible for memory heap.
                   1108: 
                   1109:   h Pij x                         | pij_nom  ficrestpij
                   1110:    # Cov Agex agex+h hpijx with i,j= 1-1 1-2     1-3     2-1     2-2     2-3
                   1111:        1  85   85    1.00000             0.00000 0.00000 0.00000 1.00000 0.00000
                   1112:        1  85   86    0.68299             0.22291 0.09410 0.71093 0.00000 0.28907
                   1113: 
                   1114:        1  65   99    0.00364             0.00322 0.99314 0.00350 0.00310 0.99340
                   1115:        1  65  100    0.00214             0.00204 0.99581 0.00206 0.00196 0.99597
                   1116:   variance of p one-step probabilities varprob  | prob_nom   ficresprob #One-step probabilities and stand. devi in ()
                   1117:    Standard deviation of one-step probabilities | probcor_nom   ficresprobcor #One-step probabilities and correlation matrix
                   1118:    Matrix of variance covariance of one-step probabilities |  probcov_nom ficresprobcov #One-step probabilities and covariance matrix
                   1119: 
1.126     brouard  1120:   forecasting if prevfcast==1 prevforecast call prevalence()
                   1121:   health expectancies
                   1122:   Variance-covariance of DFLE
                   1123:   prevalence()
                   1124:    movingaverage()
                   1125:   varevsij() 
                   1126:   if popbased==1 varevsij(,popbased)
                   1127:   total life expectancies
                   1128:   Variance of period (stable) prevalence
                   1129:  end
                   1130: */
                   1131: 
1.187     brouard  1132: /* #define DEBUG */
                   1133: /* #define DEBUGBRENT */
1.203     brouard  1134: /* #define DEBUGLINMIN */
                   1135: /* #define DEBUGHESS */
                   1136: #define DEBUGHESSIJ
1.224     brouard  1137: /* #define LINMINORIGINAL  /\* Don't use loop on scale in linmin (accepting nan) *\/ */
1.165     brouard  1138: #define POWELL /* Instead of NLOPT */
1.224     brouard  1139: #define POWELLNOF3INFF1TEST /* Skip test */
1.186     brouard  1140: /* #define POWELLORIGINAL /\* Don't use Directest to decide new direction but original Powell test *\/ */
                   1141: /* #define MNBRAKORIGINAL /\* Don't use mnbrak fix *\/ */
1.319     brouard  1142: /* #define FLATSUP  *//* Suppresses directions where likelihood is flat */
1.126     brouard  1143: 
                   1144: #include <math.h>
                   1145: #include <stdio.h>
                   1146: #include <stdlib.h>
                   1147: #include <string.h>
1.226     brouard  1148: #include <ctype.h>
1.159     brouard  1149: 
                   1150: #ifdef _WIN32
                   1151: #include <io.h>
1.172     brouard  1152: #include <windows.h>
                   1153: #include <tchar.h>
1.159     brouard  1154: #else
1.126     brouard  1155: #include <unistd.h>
1.159     brouard  1156: #endif
1.126     brouard  1157: 
                   1158: #include <limits.h>
                   1159: #include <sys/types.h>
1.171     brouard  1160: 
                   1161: #if defined(__GNUC__)
                   1162: #include <sys/utsname.h> /* Doesn't work on Windows */
                   1163: #endif
                   1164: 
1.126     brouard  1165: #include <sys/stat.h>
                   1166: #include <errno.h>
1.159     brouard  1167: /* extern int errno; */
1.126     brouard  1168: 
1.157     brouard  1169: /* #ifdef LINUX */
                   1170: /* #include <time.h> */
                   1171: /* #include "timeval.h" */
                   1172: /* #else */
                   1173: /* #include <sys/time.h> */
                   1174: /* #endif */
                   1175: 
1.126     brouard  1176: #include <time.h>
                   1177: 
1.136     brouard  1178: #ifdef GSL
                   1179: #include <gsl/gsl_errno.h>
                   1180: #include <gsl/gsl_multimin.h>
                   1181: #endif
                   1182: 
1.167     brouard  1183: 
1.162     brouard  1184: #ifdef NLOPT
                   1185: #include <nlopt.h>
                   1186: typedef struct {
                   1187:   double (* function)(double [] );
                   1188: } myfunc_data ;
                   1189: #endif
                   1190: 
1.126     brouard  1191: /* #include <libintl.h> */
                   1192: /* #define _(String) gettext (String) */
                   1193: 
1.251     brouard  1194: #define MAXLINE 2048 /* Was 256 and 1024. Overflow with 312 with 2 states and 4 covariates. Should be ok */
1.126     brouard  1195: 
                   1196: #define GNUPLOTPROGRAM "gnuplot"
                   1197: /*#define GNUPLOTPROGRAM "..\\gp37mgw\\wgnuplot"*/
1.329     brouard  1198: #define FILENAMELENGTH 256
1.126     brouard  1199: 
                   1200: #define        GLOCK_ERROR_NOPATH              -1      /* empty path */
                   1201: #define        GLOCK_ERROR_GETCWD              -2      /* cannot get cwd */
                   1202: 
1.144     brouard  1203: #define MAXPARM 128 /**< Maximum number of parameters for the optimization */
                   1204: #define NPARMAX 64 /**< (nlstate+ndeath-1)*nlstate*ncovmodel */
1.126     brouard  1205: 
                   1206: #define NINTERVMAX 8
1.144     brouard  1207: #define NLSTATEMAX 8 /**< Maximum number of live states (for func) */
                   1208: #define NDEATHMAX 8 /**< Maximum number of dead states (for func) */
1.325     brouard  1209: #define NCOVMAX 30  /**< Maximum number of covariates used in the model, including generated covariates V1*V2 or V1*age */
1.197     brouard  1210: #define codtabm(h,k)  (1 & (h-1) >> (k-1))+1
1.211     brouard  1211: /*#define decodtabm(h,k,cptcoveff)= (h <= (1<<cptcoveff)?(((h-1) >> (k-1)) & 1) +1 : -1)*/
                   1212: #define decodtabm(h,k,cptcoveff) (((h-1) >> (k-1)) & 1) +1 
1.290     brouard  1213: /*#define MAXN 20000 */ /* Should by replaced by nobs, real number of observations and unlimited */
1.144     brouard  1214: #define YEARM 12. /**< Number of months per year */
1.218     brouard  1215: /* #define AGESUP 130 */
1.288     brouard  1216: /* #define AGESUP 150 */
                   1217: #define AGESUP 200
1.268     brouard  1218: #define AGEINF 0
1.218     brouard  1219: #define AGEMARGE 25 /* Marge for agemin and agemax for(iage=agemin-AGEMARGE; iage <= agemax+3+AGEMARGE; iage++) */
1.126     brouard  1220: #define AGEBASE 40
1.194     brouard  1221: #define AGEOVERFLOW 1.e20
1.164     brouard  1222: #define AGEGOMP 10 /**< Minimal age for Gompertz adjustment */
1.157     brouard  1223: #ifdef _WIN32
                   1224: #define DIRSEPARATOR '\\'
                   1225: #define CHARSEPARATOR "\\"
                   1226: #define ODIRSEPARATOR '/'
                   1227: #else
1.126     brouard  1228: #define DIRSEPARATOR '/'
                   1229: #define CHARSEPARATOR "/"
                   1230: #define ODIRSEPARATOR '\\'
                   1231: #endif
                   1232: 
1.330   ! brouard  1233: /* $Id: imach.c,v 1.329 2022/08/03 17:29:54 brouard Exp $ */
1.126     brouard  1234: /* $State: Exp $ */
1.196     brouard  1235: #include "version.h"
                   1236: char version[]=__IMACH_VERSION__;
1.323     brouard  1237: 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.330   ! brouard  1238: char fullversion[]="$Revision: 1.329 $ $Date: 2022/08/03 17:29:54 $"; 
1.126     brouard  1239: char strstart[80];
                   1240: char optionfilext[10], optionfilefiname[FILENAMELENGTH];
1.130     brouard  1241: int erreur=0, nberr=0, nbwarn=0; /* Error number, number of errors number of warnings  */
1.187     brouard  1242: int nagesqr=0, nforce=0; /* nagesqr=1 if model is including age*age, number of forces */
1.330   ! brouard  1243: /* Number of covariates model (1)=V2+V1+ V3*age+V2*V4 */
        !          1244: /* Model(2)  V1 + V2 + V3 + V8 + V7*V8 + V5*V6 + V8*age + V3*age + age*age */
        !          1245: int cptcovn=0; /**< cptcovn decodemodel: number of covariates k of the models excluding age*products =6 and age*age */
        !          1246: int cptcovt=0; /**< cptcovt: total number of covariates of the model (2) nbocc(+)+1 = 8 excepting constant and age and age*age */
        !          1247: int cptcovs=0; /**< cptcovs number of simple covariates in the model V2+V1 =2 (dummy or quantit or time varying) */
1.225     brouard  1248: int cptcovsnq=0; /**< cptcovsnq number of simple covariates in the model but non quantitative V2+V1 =2 */
1.145     brouard  1249: int cptcovage=0; /**< Number of covariates with age: V3*age only =1 */
                   1250: int cptcovprodnoage=0; /**< Number of covariate products without age */   
1.330   ! brouard  1251: int cptcoveff=0; /* Total number of covariates to vary for printing results (2**cptcoveff combinations of dummies)(computed in tricode as cptcov) */
1.233     brouard  1252: int ncovf=0; /* Total number of effective fixed covariates (dummy or quantitative) in the model */
                   1253: int ncovv=0; /* Total number of effective (wave) varying covariates (dummy or quantitative) in the model */
1.232     brouard  1254: int ncova=0; /* Total number of effective (wave and stepm) varying with age covariates (dummy of quantitative) in the model */
1.234     brouard  1255: int nsd=0; /**< Total number of single dummy variables (output) */
                   1256: int nsq=0; /**< Total number of single quantitative variables (output) */
1.232     brouard  1257: int ncoveff=0; /* Total number of effective fixed dummy covariates in the model */
1.225     brouard  1258: int nqfveff=0; /**< nqfveff Number of Quantitative Fixed Variables Effective */
1.224     brouard  1259: int ntveff=0; /**< ntveff number of effective time varying variables */
                   1260: int nqtveff=0; /**< ntqveff number of effective time varying quantitative variables */
1.145     brouard  1261: int cptcov=0; /* Working variable */
1.290     brouard  1262: int nobs=10;  /* Number of observations in the data lastobs-firstobs */
1.218     brouard  1263: int ncovcombmax=NCOVMAX; /* Maximum calculated number of covariate combination = pow(2, cptcoveff) */
1.302     brouard  1264: int npar=NPARMAX; /* Number of parameters (nlstate+ndeath-1)*nlstate*ncovmodel; */
1.126     brouard  1265: int nlstate=2; /* Number of live states */
                   1266: int ndeath=1; /* Number of dead states */
1.130     brouard  1267: int ncovmodel=0, ncovcol=0;     /* Total number of covariables including constant a12*1 +b12*x ncovmodel=2 */
1.223     brouard  1268: int  nqv=0, ntv=0, nqtv=0;    /* Total number of quantitative variables, time variable (dummy), quantitative and time variable */ 
1.126     brouard  1269: int popbased=0;
                   1270: 
                   1271: int *wav; /* Number of waves for this individuual 0 is possible */
1.130     brouard  1272: int maxwav=0; /* Maxim number of waves */
                   1273: int jmin=0, jmax=0; /* min, max spacing between 2 waves */
                   1274: int ijmin=0, ijmax=0; /* Individuals having jmin and jmax */ 
                   1275: int gipmx=0, gsw=0; /* Global variables on the number of contributions 
1.126     brouard  1276:                   to the likelihood and the sum of weights (done by funcone)*/
1.130     brouard  1277: int mle=1, weightopt=0;
1.126     brouard  1278: int **mw; /* mw[mi][i] is number of the mi wave for this individual */
                   1279: int **dh; /* dh[mi][i] is number of steps between mi,mi+1 for this individual */
                   1280: int **bh; /* bh[mi][i] is the bias (+ or -) for this individual if the delay between
                   1281:           * wave mi and wave mi+1 is not an exact multiple of stepm. */
1.162     brouard  1282: int countcallfunc=0;  /* Count the number of calls to func */
1.230     brouard  1283: int selected(int kvar); /* Is covariate kvar selected for printing results */
                   1284: 
1.130     brouard  1285: double jmean=1; /* Mean space between 2 waves */
1.145     brouard  1286: double **matprod2(); /* test */
1.126     brouard  1287: double **oldm, **newm, **savm; /* Working pointers to matrices */
                   1288: double **oldms, **newms, **savms; /* Fixed working pointers to matrices */
1.218     brouard  1289: double  **ddnewms, **ddoldms, **ddsavms; /* for freeing later */
                   1290: 
1.136     brouard  1291: /*FILE *fic ; */ /* Used in readdata only */
1.217     brouard  1292: FILE *ficpar, *ficparo,*ficres, *ficresp, *ficresphtm, *ficresphtmfr, *ficrespl, *ficresplb,*ficrespij, *ficrespijb, *ficrest,*ficresf, *ficresfb,*ficrespop;
1.126     brouard  1293: FILE *ficlog, *ficrespow;
1.130     brouard  1294: int globpr=0; /* Global variable for printing or not */
1.126     brouard  1295: double fretone; /* Only one call to likelihood */
1.130     brouard  1296: long ipmx=0; /* Number of contributions */
1.126     brouard  1297: double sw; /* Sum of weights */
                   1298: char filerespow[FILENAMELENGTH];
                   1299: char fileresilk[FILENAMELENGTH]; /* File of individual contributions to the likelihood */
                   1300: FILE *ficresilk;
                   1301: FILE *ficgp,*ficresprob,*ficpop, *ficresprobcov, *ficresprobcor;
                   1302: FILE *ficresprobmorprev;
                   1303: FILE *fichtm, *fichtmcov; /* Html File */
                   1304: FILE *ficreseij;
                   1305: char filerese[FILENAMELENGTH];
                   1306: FILE *ficresstdeij;
                   1307: char fileresstde[FILENAMELENGTH];
                   1308: FILE *ficrescveij;
                   1309: char filerescve[FILENAMELENGTH];
                   1310: FILE  *ficresvij;
                   1311: char fileresv[FILENAMELENGTH];
1.269     brouard  1312: 
1.126     brouard  1313: char title[MAXLINE];
1.234     brouard  1314: char model[MAXLINE]; /**< The model line */
1.217     brouard  1315: char optionfile[FILENAMELENGTH], datafile[FILENAMELENGTH],  filerespl[FILENAMELENGTH],  fileresplb[FILENAMELENGTH];
1.126     brouard  1316: char plotcmd[FILENAMELENGTH], pplotcmd[FILENAMELENGTH];
                   1317: char tmpout[FILENAMELENGTH],  tmpout2[FILENAMELENGTH]; 
                   1318: char command[FILENAMELENGTH];
                   1319: int  outcmd=0;
                   1320: 
1.217     brouard  1321: char fileres[FILENAMELENGTH], filerespij[FILENAMELENGTH], filerespijb[FILENAMELENGTH], filereso[FILENAMELENGTH], rfileres[FILENAMELENGTH];
1.202     brouard  1322: char fileresu[FILENAMELENGTH]; /* fileres without r in front */
1.126     brouard  1323: char filelog[FILENAMELENGTH]; /* Log file */
                   1324: char filerest[FILENAMELENGTH];
                   1325: char fileregp[FILENAMELENGTH];
                   1326: char popfile[FILENAMELENGTH];
                   1327: 
                   1328: char optionfilegnuplot[FILENAMELENGTH], optionfilehtm[FILENAMELENGTH], optionfilehtmcov[FILENAMELENGTH] ;
                   1329: 
1.157     brouard  1330: /* struct timeval start_time, end_time, curr_time, last_time, forecast_time; */
                   1331: /* struct timezone tzp; */
                   1332: /* extern int gettimeofday(); */
                   1333: struct tm tml, *gmtime(), *localtime();
                   1334: 
                   1335: extern time_t time();
                   1336: 
                   1337: struct tm start_time, end_time, curr_time, last_time, forecast_time;
                   1338: time_t  rstart_time, rend_time, rcurr_time, rlast_time, rforecast_time; /* raw time */
                   1339: struct tm tm;
                   1340: 
1.126     brouard  1341: char strcurr[80], strfor[80];
                   1342: 
                   1343: char *endptr;
                   1344: long lval;
                   1345: double dval;
                   1346: 
                   1347: #define NR_END 1
                   1348: #define FREE_ARG char*
                   1349: #define FTOL 1.0e-10
                   1350: 
                   1351: #define NRANSI 
1.240     brouard  1352: #define ITMAX 200
                   1353: #define ITPOWMAX 20 /* This is now multiplied by the number of parameters */ 
1.126     brouard  1354: 
                   1355: #define TOL 2.0e-4 
                   1356: 
                   1357: #define CGOLD 0.3819660 
                   1358: #define ZEPS 1.0e-10 
                   1359: #define SHFT(a,b,c,d) (a)=(b);(b)=(c);(c)=(d); 
                   1360: 
                   1361: #define GOLD 1.618034 
                   1362: #define GLIMIT 100.0 
                   1363: #define TINY 1.0e-20 
                   1364: 
                   1365: static double maxarg1,maxarg2;
                   1366: #define FMAX(a,b) (maxarg1=(a),maxarg2=(b),(maxarg1)>(maxarg2)? (maxarg1):(maxarg2))
                   1367: #define FMIN(a,b) (maxarg1=(a),maxarg2=(b),(maxarg1)<(maxarg2)? (maxarg1):(maxarg2))
                   1368:   
                   1369: #define SIGN(a,b) ((b)>0.0 ? fabs(a) : -fabs(a))
                   1370: #define rint(a) floor(a+0.5)
1.166     brouard  1371: /* http://www.thphys.uni-heidelberg.de/~robbers/cmbeasy/doc/html/myutils_8h-source.html */
1.183     brouard  1372: #define mytinydouble 1.0e-16
1.166     brouard  1373: /* #define DEQUAL(a,b) (fabs((a)-(b))<mytinydouble) */
                   1374: /* http://www.thphys.uni-heidelberg.de/~robbers/cmbeasy/doc/html/mynrutils_8h-source.html */
                   1375: /* static double dsqrarg; */
                   1376: /* #define DSQR(a) (DEQUAL((dsqrarg=(a)),0.0) ? 0.0 : dsqrarg*dsqrarg) */
1.126     brouard  1377: static double sqrarg;
                   1378: #define SQR(a) ((sqrarg=(a)) == 0.0 ? 0.0 :sqrarg*sqrarg)
                   1379: #define SWAP(a,b) {temp=(a);(a)=(b);(b)=temp;} 
                   1380: int agegomp= AGEGOMP;
                   1381: 
                   1382: int imx; 
                   1383: int stepm=1;
                   1384: /* Stepm, step in month: minimum step interpolation*/
                   1385: 
                   1386: int estepm;
                   1387: /* Estepm, step in month to interpolate survival function in order to approximate Life Expectancy*/
                   1388: 
                   1389: int m,nb;
                   1390: long *num;
1.197     brouard  1391: int firstpass=0, lastpass=4,*cod, *cens;
1.192     brouard  1392: int *ncodemax;  /* ncodemax[j]= Number of modalities of the j th
                   1393:                   covariate for which somebody answered excluding 
                   1394:                   undefined. Usually 2: 0 and 1. */
                   1395: int *ncodemaxwundef;  /* ncodemax[j]= Number of modalities of the j th
                   1396:                             covariate for which somebody answered including 
                   1397:                             undefined. Usually 3: -1, 0 and 1. */
1.126     brouard  1398: double **agev,*moisnais, *annais, *moisdc, *andc,**mint, **anint;
1.218     brouard  1399: double **pmmij, ***probs; /* Global pointer */
1.219     brouard  1400: double ***mobaverage, ***mobaverages; /* New global variable */
1.126     brouard  1401: double *ageexmed,*agecens;
                   1402: double dateintmean=0;
1.296     brouard  1403:   double anprojd, mprojd, jprojd; /* For eventual projections */
                   1404:   double anprojf, mprojf, jprojf;
1.126     brouard  1405: 
1.296     brouard  1406:   double anbackd, mbackd, jbackd; /* For eventual backprojections */
                   1407:   double anbackf, mbackf, jbackf;
                   1408:   double jintmean,mintmean,aintmean;  
1.126     brouard  1409: double *weight;
                   1410: int **s; /* Status */
1.141     brouard  1411: double *agedc;
1.145     brouard  1412: double  **covar; /**< covar[j,i], value of jth covariate for individual i,
1.141     brouard  1413:                  * covar=matrix(0,NCOVMAX,1,n); 
1.187     brouard  1414:                  * cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*age; */
1.268     brouard  1415: double **coqvar; /* Fixed quantitative covariate nqv */
                   1416: double ***cotvar; /* Time varying covariate ntv */
1.225     brouard  1417: double ***cotqvar; /* Time varying quantitative covariate itqv */
1.141     brouard  1418: double  idx; 
                   1419: int **nbcode, *Tvar; /**< model=V2 => Tvar[1]= 2 */
1.319     brouard  1420: /* Some documentation */
                   1421:       /*   Design original data
                   1422:        *  V1   V2   V3   V4  V5  V6  V7  V8  Weight ddb ddth d1st s1 V9 V10 V11 V12 s2 V9 V10 V11 V12 
                   1423:        *  <          ncovcol=6   >   nqv=2 (V7 V8)                   dv dv  dv  qtv    dv dv  dvv qtv
                   1424:        *                                                             ntv=3     nqtv=1
1.330   ! brouard  1425:        *  cptcovn number of covariates (not including constant and age or age*age) = number of plus sign + 1 = 10+1=11
1.319     brouard  1426:        * For time varying covariate, quanti or dummies
                   1427:        *       cotqvar[wav][iv(1 to nqtv)][i]= [1][12][i]=(V12) quanti
                   1428:        *       cotvar[wav][ntv+iv][i]= [3+(1 to nqtv)][i]=(V12) quanti
                   1429:        *       cotvar[wav][iv(1 to ntv)][i]= [1][1][i]=(V9) dummies at wav 1
                   1430:        *       cotvar[wav][iv(1 to ntv)][i]= [1][2][i]=(V10) dummies at wav 1
                   1431:        *       covar[k,i], value of kth fixed covariate dummy or quanti :
                   1432:        *       covar[1][i]= (V1), covar[4][i]=(V4), covar[8][i]=(V8)
                   1433:        * Model V2 + V1 + V3*age + V3 + V5*V6 + V7*V8 + V8*age + V8 + V9 + V9*age + V10
                   1434:        *   k=  1    2      3       4     5       6      7        8   9     10       11 
                   1435:        */
                   1436: /* According to the model, more columns can be added to covar by the product of covariates */
1.318     brouard  1437: /* 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
                   1438:   # States 1=Coresidence, 2 Living alone, 3 Institution
                   1439:   # V1=sex, V2=raedyrs Quant Fixed, State=livarnb4..livarnb11, V3=iadl4..iald11, V4=adlw4..adlw11, V5=r4bmi..r11bmi
                   1440: */
1.319     brouard  1441: /*             V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
                   1442: /*    k        1  2   3   4     5    6    7     8    9 */
                   1443: /*Typevar[k]=  0  0   0   2     1    0    2     1    0 *//*0 for simple covariate (dummy, quantitative,*/
                   1444:                                                          /* fixed or varying), 1 for age product, 2 for*/
                   1445:                                                          /* product */
                   1446: /*Dummy[k]=    1  0   0   1     3    1    1     2    0 *//*Dummy[k] 0=dummy (0 1), 1 quantitative */
                   1447:                                                          /*(single or product without age), 2 dummy*/
                   1448:                                                          /* with age product, 3 quant with age product*/
                   1449: /*Tvar[k]=     5  4   3   6     5    2    7     1    1 */
                   1450: /*    nsd         1   2                              3 */ /* Counting single dummies covar fixed or tv */
1.330   ! brouard  1451: /*TnsdVar[Tvar]   1   2                              3 */ 
1.319     brouard  1452: /*TvarsD[nsd]     4   3                              1 */ /* ID of single dummy cova fixed or timevary*/
                   1453: /*TvarsDind[k]    2   3                              9 */ /* position K of single dummy cova */
                   1454: /*    nsq      1                     2                 */ /* Counting single quantit tv */
                   1455: /* TvarsQ[k]   5                     2                 */ /* Number of single quantitative cova */
                   1456: /* TvarsQind   1                     6                 */ /* position K of single quantitative cova */
                   1457: /* Tprod[i]=k             1               2            */ /* Position in model of the ith prod without age */
                   1458: /* cptcovage                    1               2      */ /* Counting cov*age in the model equation */
                   1459: /* Tage[cptcovage]=k            5               8      */ /* Position in the model of ith cov*age */
                   1460: /* Tvard[1][1]@4={4,3,1,2}    V4*V3 V1*V2              */ /* Position in model of the ith prod without age */
1.330   ! brouard  1461: /* Tvardk[4][1]=4;Tvardk[4][2]=3;Tvardk[7][1]=1;Tvardk[7][2]=2 */ /* Variables of a prod at position in the model equation*/
1.319     brouard  1462: /* 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  1463: /* TvarFind;  TvarFind[1]=6,  TvarFind[2]=7, TvarFind[3]=9 *//* Inverse V2(6) is first fixed (single or prod)  */
1.234     brouard  1464: /* Type                    */
                   1465: /* V         1  2  3  4  5 */
                   1466: /*           F  F  V  V  V */
                   1467: /*           D  Q  D  D  Q */
                   1468: /*                         */
                   1469: int *TvarsD;
1.330   ! brouard  1470: int *TnsdVar;
1.234     brouard  1471: int *TvarsDind;
                   1472: int *TvarsQ;
                   1473: int *TvarsQind;
                   1474: 
1.318     brouard  1475: #define MAXRESULTLINESPONE 10+1
1.235     brouard  1476: int nresult=0;
1.258     brouard  1477: int parameterline=0; /* # of the parameter (type) line */
1.318     brouard  1478: int TKresult[MAXRESULTLINESPONE];
1.330   ! brouard  1479: int resultmodel[MAXRESULTLINESPONE][NCOVMAX];/* resultmodel[k1]=k3: k1th position in the model correspond to the k3 position in the resultline */
1.318     brouard  1480: int Tresult[MAXRESULTLINESPONE][NCOVMAX];/* For dummy variable , value (output) */
                   1481: int Tinvresult[MAXRESULTLINESPONE][NCOVMAX];/* For dummy variable , value (output) */
1.330   ! brouard  1482: int TinvDoQresult[MAXRESULTLINESPONE][NCOVMAX];/* For dummy variable or quanti value (output) */
1.318     brouard  1483: int Tvresult[MAXRESULTLINESPONE][NCOVMAX]; /* For dummy variable , variable # (output) */
                   1484: double Tqresult[MAXRESULTLINESPONE][NCOVMAX]; /* For quantitative variable , value (output) */
                   1485: double Tqinvresult[MAXRESULTLINESPONE][NCOVMAX]; /* For quantitative variable , value (output) */
                   1486: int Tvqresult[MAXRESULTLINESPONE][NCOVMAX]; /* For quantitative variable , variable # (output) */
                   1487: 
                   1488: /* 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
                   1489:   # States 1=Coresidence, 2 Living alone, 3 Institution
                   1490:   # V1=sex, V2=raedyrs Quant Fixed, State=livarnb4..livarnb11, V3=iadl4..iald11, V4=adlw4..adlw11, V5=r4bmi..r11bmi
                   1491: */
1.234     brouard  1492: /* 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  1493: 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 */
                   1494: 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 */
                   1495: 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 */
                   1496: int *TvarVind; /**< TvarVind[1]=1, TvarVind[2]=2  in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
                   1497: 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 */
                   1498: 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  1499: int *TvarFD; /**< TvarFD[1]=V1 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
                   1500: int *TvarFDind; /* TvarFDind[1]=9 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
                   1501: int *TvarFQ; /* TvarFQ[1]=V2 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */ /* Only simple fixed quantitative variable */
                   1502: int *TvarFQind; /* TvarFQind[1]=6 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */ /* Only simple fixed quantitative variable */
                   1503: int *TvarVD; /* TvarVD[1]=V5 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */ /* Only simple fixed quantitative variable */
                   1504: int *TvarVDind; /* TvarVDind[1]=1 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */ /* Only simple fixed quantitative variable */
                   1505: 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 */
                   1506: 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 */
                   1507: 
1.230     brouard  1508: int *Tvarsel; /**< Selected covariates for output */
                   1509: double *Tvalsel; /**< Selected modality value of covariate for output */
1.226     brouard  1510: int *Typevar; /**< 0 for simple covariate (dummy, quantitative, fixed or varying), 1 for age product, 2 for  product */
1.227     brouard  1511: int *Fixed; /** Fixed[k] 0=fixed, 1 varying, 2 fixed with age product, 3 varying with age product */ 
                   1512: 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  1513: int *DummyV; /** Dummy[v] 0=dummy (0 1), 1 quantitative */
                   1514: int *FixedV; /** FixedV[v] 0 fixed, 1 varying */
1.197     brouard  1515: int *Tage;
1.227     brouard  1516: int anyvaryingduminmodel=0; /**< Any varying dummy in Model=1 yes, 0 no, to avoid a loop on waves in freq */ 
1.228     brouard  1517: 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  1518: 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*/ 
                   1519: 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  1520: int *Ndum; /** Freq of modality (tricode */
1.200     brouard  1521: /* int **codtab;*/ /**< codtab=imatrix(1,100,1,10); */
1.227     brouard  1522: int **Tvard;
1.330   ! brouard  1523: int **Tvardk;
1.227     brouard  1524: int *Tprod;/**< Gives the k position of the k1 product */
1.238     brouard  1525: /* Tprod[k1=1]=3(=V1*V4) for V2+V1+V1*V4+age*V3  */
1.227     brouard  1526: int *Tposprod; /**< Gives the k1 product from the k position */
1.238     brouard  1527:    /* if  V2+V1+V1*V4+age*V3+V3*V2   TProd[k1=2]=5 (V3*V2) */
                   1528:    /* Tposprod[k]=k1 , Tposprod[3]=1, Tposprod[5(V3*V2)]=2 (2nd product without age) */
1.227     brouard  1529: int cptcovprod, *Tvaraff, *invalidvarcomb;
1.126     brouard  1530: double *lsurv, *lpop, *tpop;
                   1531: 
1.231     brouard  1532: #define FD 1; /* Fixed dummy covariate */
                   1533: #define FQ 2; /* Fixed quantitative covariate */
                   1534: #define FP 3; /* Fixed product covariate */
                   1535: #define FPDD 7; /* Fixed product dummy*dummy covariate */
                   1536: #define FPDQ 8; /* Fixed product dummy*quantitative covariate */
                   1537: #define FPQQ 9; /* Fixed product quantitative*quantitative covariate */
                   1538: #define VD 10; /* Varying dummy covariate */
                   1539: #define VQ 11; /* Varying quantitative covariate */
                   1540: #define VP 12; /* Varying product covariate */
                   1541: #define VPDD 13; /* Varying product dummy*dummy covariate */
                   1542: #define VPDQ 14; /* Varying product dummy*quantitative covariate */
                   1543: #define VPQQ 15; /* Varying product quantitative*quantitative covariate */
                   1544: #define APFD 16; /* Age product * fixed dummy covariate */
                   1545: #define APFQ 17; /* Age product * fixed quantitative covariate */
                   1546: #define APVD 18; /* Age product * varying dummy covariate */
                   1547: #define APVQ 19; /* Age product * varying quantitative covariate */
                   1548: 
                   1549: #define FTYPE 1; /* Fixed covariate */
                   1550: #define VTYPE 2; /* Varying covariate (loop in wave) */
                   1551: #define ATYPE 2; /* Age product covariate (loop in dh within wave)*/
                   1552: 
                   1553: struct kmodel{
                   1554:        int maintype; /* main type */
                   1555:        int subtype; /* subtype */
                   1556: };
                   1557: struct kmodel modell[NCOVMAX];
                   1558: 
1.143     brouard  1559: double ftol=FTOL; /**< Tolerance for computing Max Likelihood */
                   1560: double ftolhess; /**< Tolerance for computing hessian */
1.126     brouard  1561: 
                   1562: /**************** split *************************/
                   1563: static int split( char *path, char *dirc, char *name, char *ext, char *finame )
                   1564: {
                   1565:   /* From a file name with (full) path (either Unix or Windows) we extract the directory (dirc)
                   1566:      the name of the file (name), its extension only (ext) and its first part of the name (finame)
                   1567:   */ 
                   1568:   char *ss;                            /* pointer */
1.186     brouard  1569:   int  l1=0, l2=0;                             /* length counters */
1.126     brouard  1570: 
                   1571:   l1 = strlen(path );                  /* length of path */
                   1572:   if ( l1 == 0 ) return( GLOCK_ERROR_NOPATH );
                   1573:   ss= strrchr( path, DIRSEPARATOR );           /* find last / */
                   1574:   if ( ss == NULL ) {                  /* no directory, so determine current directory */
                   1575:     strcpy( name, path );              /* we got the fullname name because no directory */
                   1576:     /*if(strrchr(path, ODIRSEPARATOR )==NULL)
                   1577:       printf("Warning you should use %s as a separator\n",DIRSEPARATOR);*/
                   1578:     /* get current working directory */
                   1579:     /*    extern  char* getcwd ( char *buf , int len);*/
1.184     brouard  1580: #ifdef WIN32
                   1581:     if (_getcwd( dirc, FILENAME_MAX ) == NULL ) {
                   1582: #else
                   1583:        if (getcwd(dirc, FILENAME_MAX) == NULL) {
                   1584: #endif
1.126     brouard  1585:       return( GLOCK_ERROR_GETCWD );
                   1586:     }
                   1587:     /* got dirc from getcwd*/
                   1588:     printf(" DIRC = %s \n",dirc);
1.205     brouard  1589:   } else {                             /* strip directory from path */
1.126     brouard  1590:     ss++;                              /* after this, the filename */
                   1591:     l2 = strlen( ss );                 /* length of filename */
                   1592:     if ( l2 == 0 ) return( GLOCK_ERROR_NOPATH );
                   1593:     strcpy( name, ss );                /* save file name */
                   1594:     strncpy( dirc, path, l1 - l2 );    /* now the directory */
1.186     brouard  1595:     dirc[l1-l2] = '\0';                        /* add zero */
1.126     brouard  1596:     printf(" DIRC2 = %s \n",dirc);
                   1597:   }
                   1598:   /* We add a separator at the end of dirc if not exists */
                   1599:   l1 = strlen( dirc );                 /* length of directory */
                   1600:   if( dirc[l1-1] != DIRSEPARATOR ){
                   1601:     dirc[l1] =  DIRSEPARATOR;
                   1602:     dirc[l1+1] = 0; 
                   1603:     printf(" DIRC3 = %s \n",dirc);
                   1604:   }
                   1605:   ss = strrchr( name, '.' );           /* find last / */
                   1606:   if (ss >0){
                   1607:     ss++;
                   1608:     strcpy(ext,ss);                    /* save extension */
                   1609:     l1= strlen( name);
                   1610:     l2= strlen(ss)+1;
                   1611:     strncpy( finame, name, l1-l2);
                   1612:     finame[l1-l2]= 0;
                   1613:   }
                   1614: 
                   1615:   return( 0 );                         /* we're done */
                   1616: }
                   1617: 
                   1618: 
                   1619: /******************************************/
                   1620: 
                   1621: void replace_back_to_slash(char *s, char*t)
                   1622: {
                   1623:   int i;
                   1624:   int lg=0;
                   1625:   i=0;
                   1626:   lg=strlen(t);
                   1627:   for(i=0; i<= lg; i++) {
                   1628:     (s[i] = t[i]);
                   1629:     if (t[i]== '\\') s[i]='/';
                   1630:   }
                   1631: }
                   1632: 
1.132     brouard  1633: char *trimbb(char *out, char *in)
1.137     brouard  1634: { /* Trim multiple blanks in line but keeps first blanks if line starts with blanks */
1.132     brouard  1635:   char *s;
                   1636:   s=out;
                   1637:   while (*in != '\0'){
1.137     brouard  1638:     while( *in == ' ' && *(in+1) == ' '){ /* && *(in+1) != '\0'){*/
1.132     brouard  1639:       in++;
                   1640:     }
                   1641:     *out++ = *in++;
                   1642:   }
                   1643:   *out='\0';
                   1644:   return s;
                   1645: }
                   1646: 
1.187     brouard  1647: /* char *substrchaine(char *out, char *in, char *chain) */
                   1648: /* { */
                   1649: /*   /\* Substract chain 'chain' from 'in', return and output 'out' *\/ */
                   1650: /*   char *s, *t; */
                   1651: /*   t=in;s=out; */
                   1652: /*   while ((*in != *chain) && (*in != '\0')){ */
                   1653: /*     *out++ = *in++; */
                   1654: /*   } */
                   1655: 
                   1656: /*   /\* *in matches *chain *\/ */
                   1657: /*   while ((*in++ == *chain++) && (*in != '\0')){ */
                   1658: /*     printf("*in = %c, *out= %c *chain= %c \n", *in, *out, *chain);  */
                   1659: /*   } */
                   1660: /*   in--; chain--; */
                   1661: /*   while ( (*in != '\0')){ */
                   1662: /*     printf("Bef *in = %c, *out= %c *chain= %c \n", *in, *out, *chain);  */
                   1663: /*     *out++ = *in++; */
                   1664: /*     printf("Aft *in = %c, *out= %c *chain= %c \n", *in, *out, *chain);  */
                   1665: /*   } */
                   1666: /*   *out='\0'; */
                   1667: /*   out=s; */
                   1668: /*   return out; */
                   1669: /* } */
                   1670: char *substrchaine(char *out, char *in, char *chain)
                   1671: {
                   1672:   /* Substract chain 'chain' from 'in', return and output 'out' */
                   1673:   /* in="V1+V1*age+age*age+V2", chain="age*age" */
                   1674: 
                   1675:   char *strloc;
                   1676: 
                   1677:   strcpy (out, in); 
                   1678:   strloc = strstr(out, chain); /* strloc points to out at age*age+V2 */
                   1679:   printf("Bef strloc=%s chain=%s out=%s \n", strloc, chain, out);
                   1680:   if(strloc != NULL){ 
                   1681:     /* will affect out */ /* strloc+strlenc(chain)=+V2 */ /* Will also work in Unicode */
                   1682:     memmove(strloc,strloc+strlen(chain), strlen(strloc+strlen(chain))+1);
                   1683:     /* strcpy (strloc, strloc +strlen(chain));*/
                   1684:   }
                   1685:   printf("Aft strloc=%s chain=%s in=%s out=%s \n", strloc, chain, in, out);
                   1686:   return out;
                   1687: }
                   1688: 
                   1689: 
1.145     brouard  1690: char *cutl(char *blocc, char *alocc, char *in, char occ)
                   1691: {
1.187     brouard  1692:   /* cuts string in into blocc and alocc where blocc ends before FIRST occurence of char 'occ' 
1.145     brouard  1693:      and alocc starts after first occurence of char 'occ' : ex cutv(blocc,alocc,"abcdef2ghi2j",'2')
1.310     brouard  1694:      gives alocc="abcdef" and blocc="ghi2j".
1.145     brouard  1695:      If occ is not found blocc is null and alocc is equal to in. Returns blocc
                   1696:   */
1.160     brouard  1697:   char *s, *t;
1.145     brouard  1698:   t=in;s=in;
                   1699:   while ((*in != occ) && (*in != '\0')){
                   1700:     *alocc++ = *in++;
                   1701:   }
                   1702:   if( *in == occ){
                   1703:     *(alocc)='\0';
                   1704:     s=++in;
                   1705:   }
                   1706:  
                   1707:   if (s == t) {/* occ not found */
                   1708:     *(alocc-(in-s))='\0';
                   1709:     in=s;
                   1710:   }
                   1711:   while ( *in != '\0'){
                   1712:     *blocc++ = *in++;
                   1713:   }
                   1714: 
                   1715:   *blocc='\0';
                   1716:   return t;
                   1717: }
1.137     brouard  1718: char *cutv(char *blocc, char *alocc, char *in, char occ)
                   1719: {
1.187     brouard  1720:   /* cuts string in into blocc and alocc where blocc ends before LAST occurence of char 'occ' 
1.137     brouard  1721:      and alocc starts after last occurence of char 'occ' : ex cutv(blocc,alocc,"abcdef2ghi2j",'2')
                   1722:      gives blocc="abcdef2ghi" and alocc="j".
                   1723:      If occ is not found blocc is null and alocc is equal to in. Returns alocc
                   1724:   */
                   1725:   char *s, *t;
                   1726:   t=in;s=in;
                   1727:   while (*in != '\0'){
                   1728:     while( *in == occ){
                   1729:       *blocc++ = *in++;
                   1730:       s=in;
                   1731:     }
                   1732:     *blocc++ = *in++;
                   1733:   }
                   1734:   if (s == t) /* occ not found */
                   1735:     *(blocc-(in-s))='\0';
                   1736:   else
                   1737:     *(blocc-(in-s)-1)='\0';
                   1738:   in=s;
                   1739:   while ( *in != '\0'){
                   1740:     *alocc++ = *in++;
                   1741:   }
                   1742: 
                   1743:   *alocc='\0';
                   1744:   return s;
                   1745: }
                   1746: 
1.126     brouard  1747: int nbocc(char *s, char occ)
                   1748: {
                   1749:   int i,j=0;
                   1750:   int lg=20;
                   1751:   i=0;
                   1752:   lg=strlen(s);
                   1753:   for(i=0; i<= lg; i++) {
1.234     brouard  1754:     if  (s[i] == occ ) j++;
1.126     brouard  1755:   }
                   1756:   return j;
                   1757: }
                   1758: 
1.137     brouard  1759: /* void cutv(char *u,char *v, char*t, char occ) */
                   1760: /* { */
                   1761: /*   /\* cuts string t into u and v where u ends before last occurence of char 'occ'  */
                   1762: /*      and v starts after last occurence of char 'occ' : ex cutv(u,v,"abcdef2ghi2j",'2') */
                   1763: /*      gives u="abcdef2ghi" and v="j" *\/ */
                   1764: /*   int i,lg,j,p=0; */
                   1765: /*   i=0; */
                   1766: /*   lg=strlen(t); */
                   1767: /*   for(j=0; j<=lg-1; j++) { */
                   1768: /*     if((t[j]!= occ) && (t[j+1]== occ)) p=j+1; */
                   1769: /*   } */
1.126     brouard  1770: 
1.137     brouard  1771: /*   for(j=0; j<p; j++) { */
                   1772: /*     (u[j] = t[j]); */
                   1773: /*   } */
                   1774: /*      u[p]='\0'; */
1.126     brouard  1775: 
1.137     brouard  1776: /*    for(j=0; j<= lg; j++) { */
                   1777: /*     if (j>=(p+1))(v[j-p-1] = t[j]); */
                   1778: /*   } */
                   1779: /* } */
1.126     brouard  1780: 
1.160     brouard  1781: #ifdef _WIN32
                   1782: char * strsep(char **pp, const char *delim)
                   1783: {
                   1784:   char *p, *q;
                   1785:          
                   1786:   if ((p = *pp) == NULL)
                   1787:     return 0;
                   1788:   if ((q = strpbrk (p, delim)) != NULL)
                   1789:   {
                   1790:     *pp = q + 1;
                   1791:     *q = '\0';
                   1792:   }
                   1793:   else
                   1794:     *pp = 0;
                   1795:   return p;
                   1796: }
                   1797: #endif
                   1798: 
1.126     brouard  1799: /********************** nrerror ********************/
                   1800: 
                   1801: void nrerror(char error_text[])
                   1802: {
                   1803:   fprintf(stderr,"ERREUR ...\n");
                   1804:   fprintf(stderr,"%s\n",error_text);
                   1805:   exit(EXIT_FAILURE);
                   1806: }
                   1807: /*********************** vector *******************/
                   1808: double *vector(int nl, int nh)
                   1809: {
                   1810:   double *v;
                   1811:   v=(double *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(double)));
                   1812:   if (!v) nrerror("allocation failure in vector");
                   1813:   return v-nl+NR_END;
                   1814: }
                   1815: 
                   1816: /************************ free vector ******************/
                   1817: void free_vector(double*v, int nl, int nh)
                   1818: {
                   1819:   free((FREE_ARG)(v+nl-NR_END));
                   1820: }
                   1821: 
                   1822: /************************ivector *******************************/
                   1823: int *ivector(long nl,long nh)
                   1824: {
                   1825:   int *v;
                   1826:   v=(int *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(int)));
                   1827:   if (!v) nrerror("allocation failure in ivector");
                   1828:   return v-nl+NR_END;
                   1829: }
                   1830: 
                   1831: /******************free ivector **************************/
                   1832: void free_ivector(int *v, long nl, long nh)
                   1833: {
                   1834:   free((FREE_ARG)(v+nl-NR_END));
                   1835: }
                   1836: 
                   1837: /************************lvector *******************************/
                   1838: long *lvector(long nl,long nh)
                   1839: {
                   1840:   long *v;
                   1841:   v=(long *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(long)));
                   1842:   if (!v) nrerror("allocation failure in ivector");
                   1843:   return v-nl+NR_END;
                   1844: }
                   1845: 
                   1846: /******************free lvector **************************/
                   1847: void free_lvector(long *v, long nl, long nh)
                   1848: {
                   1849:   free((FREE_ARG)(v+nl-NR_END));
                   1850: }
                   1851: 
                   1852: /******************* imatrix *******************************/
                   1853: int **imatrix(long nrl, long nrh, long ncl, long nch) 
                   1854:      /* allocate a int matrix with subscript range m[nrl..nrh][ncl..nch] */ 
                   1855: { 
                   1856:   long i, nrow=nrh-nrl+1,ncol=nch-ncl+1; 
                   1857:   int **m; 
                   1858:   
                   1859:   /* allocate pointers to rows */ 
                   1860:   m=(int **) malloc((size_t)((nrow+NR_END)*sizeof(int*))); 
                   1861:   if (!m) nrerror("allocation failure 1 in matrix()"); 
                   1862:   m += NR_END; 
                   1863:   m -= nrl; 
                   1864:   
                   1865:   
                   1866:   /* allocate rows and set pointers to them */ 
                   1867:   m[nrl]=(int *) malloc((size_t)((nrow*ncol+NR_END)*sizeof(int))); 
                   1868:   if (!m[nrl]) nrerror("allocation failure 2 in matrix()"); 
                   1869:   m[nrl] += NR_END; 
                   1870:   m[nrl] -= ncl; 
                   1871:   
                   1872:   for(i=nrl+1;i<=nrh;i++) m[i]=m[i-1]+ncol; 
                   1873:   
                   1874:   /* return pointer to array of pointers to rows */ 
                   1875:   return m; 
                   1876: } 
                   1877: 
                   1878: /****************** free_imatrix *************************/
                   1879: void free_imatrix(m,nrl,nrh,ncl,nch)
                   1880:       int **m;
                   1881:       long nch,ncl,nrh,nrl; 
                   1882:      /* free an int matrix allocated by imatrix() */ 
                   1883: { 
                   1884:   free((FREE_ARG) (m[nrl]+ncl-NR_END)); 
                   1885:   free((FREE_ARG) (m+nrl-NR_END)); 
                   1886: } 
                   1887: 
                   1888: /******************* matrix *******************************/
                   1889: double **matrix(long nrl, long nrh, long ncl, long nch)
                   1890: {
                   1891:   long i, nrow=nrh-nrl+1, ncol=nch-ncl+1;
                   1892:   double **m;
                   1893: 
                   1894:   m=(double **) malloc((size_t)((nrow+NR_END)*sizeof(double*)));
                   1895:   if (!m) nrerror("allocation failure 1 in matrix()");
                   1896:   m += NR_END;
                   1897:   m -= nrl;
                   1898: 
                   1899:   m[nrl]=(double *) malloc((size_t)((nrow*ncol+NR_END)*sizeof(double)));
                   1900:   if (!m[nrl]) nrerror("allocation failure 2 in matrix()");
                   1901:   m[nrl] += NR_END;
                   1902:   m[nrl] -= ncl;
                   1903: 
                   1904:   for (i=nrl+1; i<=nrh; i++) m[i]=m[i-1]+ncol;
                   1905:   return m;
1.145     brouard  1906:   /* print *(*(m+1)+70) or print m[1][70]; print m+1 or print &(m[1]) or &(m[1][0])
                   1907: m[i] = address of ith row of the table. &(m[i]) is its value which is another adress
                   1908: that of m[i][0]. In order to get the value p m[i][0] but it is unitialized.
1.126     brouard  1909:    */
                   1910: }
                   1911: 
                   1912: /*************************free matrix ************************/
                   1913: void free_matrix(double **m, long nrl, long nrh, long ncl, long nch)
                   1914: {
                   1915:   free((FREE_ARG)(m[nrl]+ncl-NR_END));
                   1916:   free((FREE_ARG)(m+nrl-NR_END));
                   1917: }
                   1918: 
                   1919: /******************* ma3x *******************************/
                   1920: double ***ma3x(long nrl, long nrh, long ncl, long nch, long nll, long nlh)
                   1921: {
                   1922:   long i, j, nrow=nrh-nrl+1, ncol=nch-ncl+1, nlay=nlh-nll+1;
                   1923:   double ***m;
                   1924: 
                   1925:   m=(double ***) malloc((size_t)((nrow+NR_END)*sizeof(double*)));
                   1926:   if (!m) nrerror("allocation failure 1 in matrix()");
                   1927:   m += NR_END;
                   1928:   m -= nrl;
                   1929: 
                   1930:   m[nrl]=(double **) malloc((size_t)((nrow*ncol+NR_END)*sizeof(double)));
                   1931:   if (!m[nrl]) nrerror("allocation failure 2 in matrix()");
                   1932:   m[nrl] += NR_END;
                   1933:   m[nrl] -= ncl;
                   1934: 
                   1935:   for (i=nrl+1; i<=nrh; i++) m[i]=m[i-1]+ncol;
                   1936: 
                   1937:   m[nrl][ncl]=(double *) malloc((size_t)((nrow*ncol*nlay+NR_END)*sizeof(double)));
                   1938:   if (!m[nrl][ncl]) nrerror("allocation failure 3 in matrix()");
                   1939:   m[nrl][ncl] += NR_END;
                   1940:   m[nrl][ncl] -= nll;
                   1941:   for (j=ncl+1; j<=nch; j++) 
                   1942:     m[nrl][j]=m[nrl][j-1]+nlay;
                   1943:   
                   1944:   for (i=nrl+1; i<=nrh; i++) {
                   1945:     m[i][ncl]=m[i-1l][ncl]+ncol*nlay;
                   1946:     for (j=ncl+1; j<=nch; j++) 
                   1947:       m[i][j]=m[i][j-1]+nlay;
                   1948:   }
                   1949:   return m; 
                   1950:   /*  gdb: p *(m+1) <=> p m[1] and p (m+1) <=> p (m+1) <=> p &(m[1])
                   1951:            &(m[i][j][k]) <=> *((*(m+i) + j)+k)
                   1952:   */
                   1953: }
                   1954: 
                   1955: /*************************free ma3x ************************/
                   1956: void free_ma3x(double ***m, long nrl, long nrh, long ncl, long nch,long nll, long nlh)
                   1957: {
                   1958:   free((FREE_ARG)(m[nrl][ncl]+ nll-NR_END));
                   1959:   free((FREE_ARG)(m[nrl]+ncl-NR_END));
                   1960:   free((FREE_ARG)(m+nrl-NR_END));
                   1961: }
                   1962: 
                   1963: /*************** function subdirf ***********/
                   1964: char *subdirf(char fileres[])
                   1965: {
                   1966:   /* Caution optionfilefiname is hidden */
                   1967:   strcpy(tmpout,optionfilefiname);
                   1968:   strcat(tmpout,"/"); /* Add to the right */
                   1969:   strcat(tmpout,fileres);
                   1970:   return tmpout;
                   1971: }
                   1972: 
                   1973: /*************** function subdirf2 ***********/
                   1974: char *subdirf2(char fileres[], char *preop)
                   1975: {
1.314     brouard  1976:   /* Example subdirf2(optionfilefiname,"FB_") with optionfilefiname="texte", result="texte/FB_texte"
                   1977:  Errors in subdirf, 2, 3 while printing tmpout is
1.315     brouard  1978:  rewritten within the same printf. Workaround: many printfs */
1.126     brouard  1979:   /* Caution optionfilefiname is hidden */
                   1980:   strcpy(tmpout,optionfilefiname);
                   1981:   strcat(tmpout,"/");
                   1982:   strcat(tmpout,preop);
                   1983:   strcat(tmpout,fileres);
                   1984:   return tmpout;
                   1985: }
                   1986: 
                   1987: /*************** function subdirf3 ***********/
                   1988: char *subdirf3(char fileres[], char *preop, char *preop2)
                   1989: {
                   1990:   
                   1991:   /* Caution optionfilefiname is hidden */
                   1992:   strcpy(tmpout,optionfilefiname);
                   1993:   strcat(tmpout,"/");
                   1994:   strcat(tmpout,preop);
                   1995:   strcat(tmpout,preop2);
                   1996:   strcat(tmpout,fileres);
                   1997:   return tmpout;
                   1998: }
1.213     brouard  1999:  
                   2000: /*************** function subdirfext ***********/
                   2001: char *subdirfext(char fileres[], char *preop, char *postop)
                   2002: {
                   2003:   
                   2004:   strcpy(tmpout,preop);
                   2005:   strcat(tmpout,fileres);
                   2006:   strcat(tmpout,postop);
                   2007:   return tmpout;
                   2008: }
1.126     brouard  2009: 
1.213     brouard  2010: /*************** function subdirfext3 ***********/
                   2011: char *subdirfext3(char fileres[], char *preop, char *postop)
                   2012: {
                   2013:   
                   2014:   /* Caution optionfilefiname is hidden */
                   2015:   strcpy(tmpout,optionfilefiname);
                   2016:   strcat(tmpout,"/");
                   2017:   strcat(tmpout,preop);
                   2018:   strcat(tmpout,fileres);
                   2019:   strcat(tmpout,postop);
                   2020:   return tmpout;
                   2021: }
                   2022:  
1.162     brouard  2023: char *asc_diff_time(long time_sec, char ascdiff[])
                   2024: {
                   2025:   long sec_left, days, hours, minutes;
                   2026:   days = (time_sec) / (60*60*24);
                   2027:   sec_left = (time_sec) % (60*60*24);
                   2028:   hours = (sec_left) / (60*60) ;
                   2029:   sec_left = (sec_left) %(60*60);
                   2030:   minutes = (sec_left) /60;
                   2031:   sec_left = (sec_left) % (60);
                   2032:   sprintf(ascdiff,"%ld day(s) %ld hour(s) %ld minute(s) %ld second(s)",days, hours, minutes, sec_left);  
                   2033:   return ascdiff;
                   2034: }
                   2035: 
1.126     brouard  2036: /***************** f1dim *************************/
                   2037: extern int ncom; 
                   2038: extern double *pcom,*xicom;
                   2039: extern double (*nrfunc)(double []); 
                   2040:  
                   2041: double f1dim(double x) 
                   2042: { 
                   2043:   int j; 
                   2044:   double f;
                   2045:   double *xt; 
                   2046:  
                   2047:   xt=vector(1,ncom); 
                   2048:   for (j=1;j<=ncom;j++) xt[j]=pcom[j]+x*xicom[j]; 
                   2049:   f=(*nrfunc)(xt); 
                   2050:   free_vector(xt,1,ncom); 
                   2051:   return f; 
                   2052: } 
                   2053: 
                   2054: /*****************brent *************************/
                   2055: double brent(double ax, double bx, double cx, double (*f)(double), double tol,         double *xmin) 
1.187     brouard  2056: {
                   2057:   /* Given a function f, and given a bracketing triplet of abscissas ax, bx, cx (such that bx is
                   2058:    * between ax and cx, and f(bx) is less than both f(ax) and f(cx) ), this routine isolates
                   2059:    * the minimum to a fractional precision of about tol using Brent’s method. The abscissa of
                   2060:    * the minimum is returned as xmin, and the minimum function value is returned as brent , the
                   2061:    * returned function value. 
                   2062:   */
1.126     brouard  2063:   int iter; 
                   2064:   double a,b,d,etemp;
1.159     brouard  2065:   double fu=0,fv,fw,fx;
1.164     brouard  2066:   double ftemp=0.;
1.126     brouard  2067:   double p,q,r,tol1,tol2,u,v,w,x,xm; 
                   2068:   double e=0.0; 
                   2069:  
                   2070:   a=(ax < cx ? ax : cx); 
                   2071:   b=(ax > cx ? ax : cx); 
                   2072:   x=w=v=bx; 
                   2073:   fw=fv=fx=(*f)(x); 
                   2074:   for (iter=1;iter<=ITMAX;iter++) { 
                   2075:     xm=0.5*(a+b); 
                   2076:     tol2=2.0*(tol1=tol*fabs(x)+ZEPS); 
                   2077:     /*         if (2.0*fabs(fp-(*fret)) <= ftol*(fabs(fp)+fabs(*fret)))*/
                   2078:     printf(".");fflush(stdout);
                   2079:     fprintf(ficlog,".");fflush(ficlog);
1.162     brouard  2080: #ifdef DEBUGBRENT
1.126     brouard  2081:     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);
                   2082:     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);
                   2083:     /*         if ((fabs(x-xm) <= (tol2-0.5*(b-a)))||(2.0*fabs(fu-ftemp) <= ftol*1.e-2*(fabs(fu)+fabs(ftemp)))) { */
                   2084: #endif
                   2085:     if (fabs(x-xm) <= (tol2-0.5*(b-a))){ 
                   2086:       *xmin=x; 
                   2087:       return fx; 
                   2088:     } 
                   2089:     ftemp=fu;
                   2090:     if (fabs(e) > tol1) { 
                   2091:       r=(x-w)*(fx-fv); 
                   2092:       q=(x-v)*(fx-fw); 
                   2093:       p=(x-v)*q-(x-w)*r; 
                   2094:       q=2.0*(q-r); 
                   2095:       if (q > 0.0) p = -p; 
                   2096:       q=fabs(q); 
                   2097:       etemp=e; 
                   2098:       e=d; 
                   2099:       if (fabs(p) >= fabs(0.5*q*etemp) || p <= q*(a-x) || p >= q*(b-x)) 
1.224     brouard  2100:                                d=CGOLD*(e=(x >= xm ? a-x : b-x)); 
1.126     brouard  2101:       else { 
1.224     brouard  2102:                                d=p/q; 
                   2103:                                u=x+d; 
                   2104:                                if (u-a < tol2 || b-u < tol2) 
                   2105:                                        d=SIGN(tol1,xm-x); 
1.126     brouard  2106:       } 
                   2107:     } else { 
                   2108:       d=CGOLD*(e=(x >= xm ? a-x : b-x)); 
                   2109:     } 
                   2110:     u=(fabs(d) >= tol1 ? x+d : x+SIGN(tol1,d)); 
                   2111:     fu=(*f)(u); 
                   2112:     if (fu <= fx) { 
                   2113:       if (u >= x) a=x; else b=x; 
                   2114:       SHFT(v,w,x,u) 
1.183     brouard  2115:       SHFT(fv,fw,fx,fu) 
                   2116:     } else { 
                   2117:       if (u < x) a=u; else b=u; 
                   2118:       if (fu <= fw || w == x) { 
1.224     brouard  2119:                                v=w; 
                   2120:                                w=u; 
                   2121:                                fv=fw; 
                   2122:                                fw=fu; 
1.183     brouard  2123:       } else if (fu <= fv || v == x || v == w) { 
1.224     brouard  2124:                                v=u; 
                   2125:                                fv=fu; 
1.183     brouard  2126:       } 
                   2127:     } 
1.126     brouard  2128:   } 
                   2129:   nrerror("Too many iterations in brent"); 
                   2130:   *xmin=x; 
                   2131:   return fx; 
                   2132: } 
                   2133: 
                   2134: /****************** mnbrak ***********************/
                   2135: 
                   2136: void mnbrak(double *ax, double *bx, double *cx, double *fa, double *fb, double *fc, 
                   2137:            double (*func)(double)) 
1.183     brouard  2138: { /* Given a function func , and given distinct initial points ax and bx , this routine searches in
                   2139: the downhill direction (defined by the function as evaluated at the initial points) and returns
                   2140: new points ax , bx , cx that bracket a minimum of the function. Also returned are the function
                   2141: values at the three points, fa, fb , and fc such that fa > fb and fb < fc.
                   2142:    */
1.126     brouard  2143:   double ulim,u,r,q, dum;
                   2144:   double fu; 
1.187     brouard  2145: 
                   2146:   double scale=10.;
                   2147:   int iterscale=0;
                   2148: 
                   2149:   *fa=(*func)(*ax); /*  xta[j]=pcom[j]+(*ax)*xicom[j]; fa=f(xta[j])*/
                   2150:   *fb=(*func)(*bx); /*  xtb[j]=pcom[j]+(*bx)*xicom[j]; fb=f(xtb[j]) */
                   2151: 
                   2152: 
                   2153:   /* while(*fb != *fb){ /\* *ax should be ok, reducing distance to *ax *\/ */
                   2154:   /*   printf("Warning mnbrak *fb = %lf, *bx=%lf *ax=%lf *fa==%lf iter=%d\n",*fb, *bx, *ax, *fa, iterscale++); */
                   2155:   /*   *bx = *ax - (*ax - *bx)/scale; */
                   2156:   /*   *fb=(*func)(*bx);  /\*  xtb[j]=pcom[j]+(*bx)*xicom[j]; fb=f(xtb[j]) *\/ */
                   2157:   /* } */
                   2158: 
1.126     brouard  2159:   if (*fb > *fa) { 
                   2160:     SHFT(dum,*ax,*bx,dum) 
1.183     brouard  2161:     SHFT(dum,*fb,*fa,dum) 
                   2162:   } 
1.126     brouard  2163:   *cx=(*bx)+GOLD*(*bx-*ax); 
                   2164:   *fc=(*func)(*cx); 
1.183     brouard  2165: #ifdef DEBUG
1.224     brouard  2166:   printf("mnbrak0 a=%lf *fa=%lf, b=%lf *fb=%lf, c=%lf *fc=%lf\n",*ax,*fa,*bx,*fb,*cx, *fc);
                   2167:   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  2168: #endif
1.224     brouard  2169:   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  2170:     r=(*bx-*ax)*(*fb-*fc); 
1.224     brouard  2171:     q=(*bx-*cx)*(*fb-*fa); /* What if fa=inf */
1.126     brouard  2172:     u=(*bx)-((*bx-*cx)*q-(*bx-*ax)*r)/ 
1.183     brouard  2173:       (2.0*SIGN(FMAX(fabs(q-r),TINY),q-r)); /* Minimum abscissa of a parabolic estimated from (a,fa), (b,fb) and (c,fc). */
                   2174:     ulim=(*bx)+GLIMIT*(*cx-*bx); /* Maximum abscissa where function should be evaluated */
                   2175:     if ((*bx-u)*(u-*cx) > 0.0) { /* if u_p is between b and c */
1.126     brouard  2176:       fu=(*func)(u); 
1.163     brouard  2177: #ifdef DEBUG
                   2178:       /* f(x)=A(x-u)**2+f(u) */
                   2179:       double A, fparabu; 
                   2180:       A= (*fb - *fa)/(*bx-*ax)/(*bx+*ax-2*u);
                   2181:       fparabu= *fa - A*(*ax-u)*(*ax-u);
1.224     brouard  2182:       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);
                   2183:       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  2184:       /* And thus,it can be that fu > *fc even if fparabu < *fc */
                   2185:       /* mnbrak (*ax=7.666299858533, *fa=299039.693133272231), (*bx=8.595447774979, *fb=298976.598289369489),
                   2186:         (*cx=10.098840694817, *fc=298946.631474258087),  (*u=9.852501168332, fu=298948.773013752128, fparabu=298945.434711494134) */
                   2187:       /* In that case, there is no bracket in the output! Routine is wrong with many consequences.*/
1.163     brouard  2188: #endif 
1.184     brouard  2189: #ifdef MNBRAKORIGINAL
1.183     brouard  2190: #else
1.191     brouard  2191: /*       if (fu > *fc) { */
                   2192: /* #ifdef DEBUG */
                   2193: /*       printf("mnbrak4  fu > fc \n"); */
                   2194: /*       fprintf(ficlog, "mnbrak4 fu > fc\n"); */
                   2195: /* #endif */
                   2196: /*     /\* 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 *\\/  *\/ */
                   2197: /*     /\* SHFT(*fa,*fc,fu,*fc) /\\* (b, u, c) is a bracket while test fb > fc will be fu > fc  will exit *\\/ *\/ */
                   2198: /*     dum=u; /\* Shifting c and u *\/ */
                   2199: /*     u = *cx; */
                   2200: /*     *cx = dum; */
                   2201: /*     dum = fu; */
                   2202: /*     fu = *fc; */
                   2203: /*     *fc =dum; */
                   2204: /*       } else { /\* end *\/ */
                   2205: /* #ifdef DEBUG */
                   2206: /*       printf("mnbrak3  fu < fc \n"); */
                   2207: /*       fprintf(ficlog, "mnbrak3 fu < fc\n"); */
                   2208: /* #endif */
                   2209: /*     dum=u; /\* Shifting c and u *\/ */
                   2210: /*     u = *cx; */
                   2211: /*     *cx = dum; */
                   2212: /*     dum = fu; */
                   2213: /*     fu = *fc; */
                   2214: /*     *fc =dum; */
                   2215: /*       } */
1.224     brouard  2216: #ifdef DEBUGMNBRAK
                   2217:                 double A, fparabu; 
                   2218:      A= (*fb - *fa)/(*bx-*ax)/(*bx+*ax-2*u);
                   2219:      fparabu= *fa - A*(*ax-u)*(*ax-u);
                   2220:      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);
                   2221:      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  2222: #endif
1.191     brouard  2223:       dum=u; /* Shifting c and u */
                   2224:       u = *cx;
                   2225:       *cx = dum;
                   2226:       dum = fu;
                   2227:       fu = *fc;
                   2228:       *fc =dum;
1.183     brouard  2229: #endif
1.162     brouard  2230:     } else if ((*cx-u)*(u-ulim) > 0.0) { /* u is after c but before ulim */
1.183     brouard  2231: #ifdef DEBUG
1.224     brouard  2232:       printf("\nmnbrak2  u=%lf after c=%lf but before ulim\n",u,*cx);
                   2233:       fprintf(ficlog,"\nmnbrak2  u=%lf after c=%lf but before ulim\n",u,*cx);
1.183     brouard  2234: #endif
1.126     brouard  2235:       fu=(*func)(u); 
                   2236:       if (fu < *fc) { 
1.183     brouard  2237: #ifdef DEBUG
1.224     brouard  2238:                                printf("\nmnbrak2  u=%lf after c=%lf but before ulim=%lf AND fu=%lf < %lf=fc\n",u,*cx,ulim,fu, *fc);
                   2239:                          fprintf(ficlog,"\nmnbrak2  u=%lf after c=%lf but before ulim=%lf AND fu=%lf < %lf=fc\n",u,*cx,ulim,fu, *fc);
                   2240: #endif
                   2241:                          SHFT(*bx,*cx,u,*cx+GOLD*(*cx-*bx)) 
                   2242:                                SHFT(*fb,*fc,fu,(*func)(u)) 
                   2243: #ifdef DEBUG
                   2244:                                        printf("\nmnbrak2 shift GOLD c=%lf",*cx+GOLD*(*cx-*bx));
1.183     brouard  2245: #endif
                   2246:       } 
1.162     brouard  2247:     } else if ((u-ulim)*(ulim-*cx) >= 0.0) { /* u outside ulim (verifying that ulim is beyond c) */
1.183     brouard  2248: #ifdef DEBUG
1.224     brouard  2249:       printf("\nmnbrak2  u=%lf outside ulim=%lf (verifying that ulim is beyond c=%lf)\n",u,ulim,*cx);
                   2250:       fprintf(ficlog,"\nmnbrak2  u=%lf outside ulim=%lf (verifying that ulim is beyond c=%lf)\n",u,ulim,*cx);
1.183     brouard  2251: #endif
1.126     brouard  2252:       u=ulim; 
                   2253:       fu=(*func)(u); 
1.183     brouard  2254:     } else { /* u could be left to b (if r > q parabola has a maximum) */
                   2255: #ifdef DEBUG
1.224     brouard  2256:       printf("\nmnbrak2  u=%lf could be left to b=%lf (if r=%lf > q=%lf parabola has a maximum)\n",u,*bx,r,q);
                   2257:       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  2258: #endif
1.126     brouard  2259:       u=(*cx)+GOLD*(*cx-*bx); 
                   2260:       fu=(*func)(u); 
1.224     brouard  2261: #ifdef DEBUG
                   2262:       printf("\nmnbrak2 new u=%lf fu=%lf shifted gold left from c=%lf and b=%lf \n",u,fu,*cx,*bx);
                   2263:       fprintf(ficlog,"\nmnbrak2 new u=%lf fu=%lf shifted gold left from c=%lf and b=%lf \n",u,fu,*cx,*bx);
                   2264: #endif
1.183     brouard  2265:     } /* end tests */
1.126     brouard  2266:     SHFT(*ax,*bx,*cx,u) 
1.183     brouard  2267:     SHFT(*fa,*fb,*fc,fu) 
                   2268: #ifdef DEBUG
1.224     brouard  2269:       printf("\nmnbrak2 shift (*ax=%.12f, *fa=%.12lf), (*bx=%.12f, *fb=%.12lf), (*cx=%.12f, *fc=%.12lf)\n",*ax,*fa,*bx,*fb,*cx,*fc);
                   2270:       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  2271: #endif
                   2272:   } /* 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  2273: } 
                   2274: 
                   2275: /*************** linmin ************************/
1.162     brouard  2276: /* Given an n -dimensional point p[1..n] and an n -dimensional direction xi[1..n] , moves and
                   2277: resets p to where the function func(p) takes on a minimum along the direction xi from p ,
                   2278: and replaces xi by the actual vector displacement that p was moved. Also returns as fret
                   2279: the value of func at the returned location p . This is actually all accomplished by calling the
                   2280: routines mnbrak and brent .*/
1.126     brouard  2281: int ncom; 
                   2282: double *pcom,*xicom;
                   2283: double (*nrfunc)(double []); 
                   2284:  
1.224     brouard  2285: #ifdef LINMINORIGINAL
1.126     brouard  2286: void linmin(double p[], double xi[], int n, double *fret,double (*func)(double [])) 
1.224     brouard  2287: #else
                   2288: void linmin(double p[], double xi[], int n, double *fret,double (*func)(double []), int *flat) 
                   2289: #endif
1.126     brouard  2290: { 
                   2291:   double brent(double ax, double bx, double cx, 
                   2292:               double (*f)(double), double tol, double *xmin); 
                   2293:   double f1dim(double x); 
                   2294:   void mnbrak(double *ax, double *bx, double *cx, double *fa, double *fb, 
                   2295:              double *fc, double (*func)(double)); 
                   2296:   int j; 
                   2297:   double xx,xmin,bx,ax; 
                   2298:   double fx,fb,fa;
1.187     brouard  2299: 
1.203     brouard  2300: #ifdef LINMINORIGINAL
                   2301: #else
                   2302:   double scale=10., axs, xxs; /* Scale added for infinity */
                   2303: #endif
                   2304:   
1.126     brouard  2305:   ncom=n; 
                   2306:   pcom=vector(1,n); 
                   2307:   xicom=vector(1,n); 
                   2308:   nrfunc=func; 
                   2309:   for (j=1;j<=n;j++) { 
                   2310:     pcom[j]=p[j]; 
1.202     brouard  2311:     xicom[j]=xi[j]; /* Former scale xi[j] of currrent direction i */
1.126     brouard  2312:   } 
1.187     brouard  2313: 
1.203     brouard  2314: #ifdef LINMINORIGINAL
                   2315:   xx=1.;
                   2316: #else
                   2317:   axs=0.0;
                   2318:   xxs=1.;
                   2319:   do{
                   2320:     xx= xxs;
                   2321: #endif
1.187     brouard  2322:     ax=0.;
                   2323:     mnbrak(&ax,&xx,&bx,&fa,&fx,&fb,f1dim);  /* Outputs: xtx[j]=pcom[j]+(*xx)*xicom[j]; fx=f(xtx[j]) */
                   2324:     /* brackets with inputs ax=0 and xx=1, but points, pcom=p, and directions values, xicom=xi, are sent via f1dim(x) */
                   2325:     /* 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))   */
                   2326:     /* Outputs: fa=f(p(j)) and fx=f(p(j) + xxs * xi(j) ) and f(bx)= f(p(j)+ bx* xi(j)) */
                   2327:     /* Given input ax=axs and xx=xxs, xx might be too far from ax to get a finite f(xx) */
                   2328:     /* Searches on line, outputs (ax, xx, bx) such that fx < min(fa and fb) */
                   2329:     /* 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  2330: #ifdef LINMINORIGINAL
                   2331: #else
                   2332:     if (fx != fx){
1.224     brouard  2333:                        xxs=xxs/scale; /* Trying a smaller xx, closer to initial ax=0 */
                   2334:                        printf("|");
                   2335:                        fprintf(ficlog,"|");
1.203     brouard  2336: #ifdef DEBUGLINMIN
1.224     brouard  2337:                        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  2338: #endif
                   2339:     }
1.224     brouard  2340:   }while(fx != fx && xxs > 1.e-5);
1.203     brouard  2341: #endif
                   2342:   
1.191     brouard  2343: #ifdef DEBUGLINMIN
                   2344:   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  2345:   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  2346: #endif
1.224     brouard  2347: #ifdef LINMINORIGINAL
                   2348: #else
1.317     brouard  2349:   if(fb == fx){ /* Flat function in the direction */
                   2350:     xmin=xx;
1.224     brouard  2351:     *flat=1;
1.317     brouard  2352:   }else{
1.224     brouard  2353:     *flat=0;
                   2354: #endif
                   2355:                /*Flat mnbrak2 shift (*ax=0.000000000000, *fa=51626.272983130431), (*bx=-1.618034000000, *fb=51590.149499362531), (*cx=-4.236068025156, *fc=51590.149499362531) */
1.187     brouard  2356:   *fret=brent(ax,xx,bx,f1dim,TOL,&xmin); /* Giving a bracketting triplet (ax, xx, bx), find a minimum, xmin, according to f1dim, *fret(xmin),*/
                   2357:   /* fa = f(p[j] + ax * xi[j]), fx = f(p[j] + xx * xi[j]), fb = f(p[j] + bx * xi[j]) */
                   2358:   /* fmin = f(p[j] + xmin * xi[j]) */
                   2359:   /* P+lambda n in that direction (lambdamin), with TOL between abscisses */
                   2360:   /* f1dim(xmin): for (j=1;j<=ncom;j++) xt[j]=pcom[j]+xmin*xicom[j]; */
1.126     brouard  2361: #ifdef DEBUG
1.224     brouard  2362:   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);
                   2363:   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);
                   2364: #endif
                   2365: #ifdef LINMINORIGINAL
                   2366: #else
                   2367:                        }
1.126     brouard  2368: #endif
1.191     brouard  2369: #ifdef DEBUGLINMIN
                   2370:   printf("linmin end ");
1.202     brouard  2371:   fprintf(ficlog,"linmin end ");
1.191     brouard  2372: #endif
1.126     brouard  2373:   for (j=1;j<=n;j++) { 
1.203     brouard  2374: #ifdef LINMINORIGINAL
                   2375:     xi[j] *= xmin; 
                   2376: #else
                   2377: #ifdef DEBUGLINMIN
                   2378:     if(xxs <1.0)
                   2379:       printf(" before xi[%d]=%12.8f", j,xi[j]);
                   2380: #endif
                   2381:     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) */
                   2382: #ifdef DEBUGLINMIN
                   2383:     if(xxs <1.0)
                   2384:       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 );
                   2385: #endif
                   2386: #endif
1.187     brouard  2387:     p[j] += xi[j]; /* Parameters values are updated accordingly */
1.126     brouard  2388:   } 
1.191     brouard  2389: #ifdef DEBUGLINMIN
1.203     brouard  2390:   printf("\n");
1.191     brouard  2391:   printf("Comparing last *frec(xmin=%12.8f)=%12.8f from Brent and frec(0.)=%12.8f \n", xmin, *fret, (*func)(p));
1.202     brouard  2392:   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  2393:   for (j=1;j<=n;j++) { 
1.202     brouard  2394:     printf(" xi[%d]= %14.10f p[%d]= %12.7f",j,xi[j],j,p[j]);
                   2395:     fprintf(ficlog," xi[%d]= %14.10f p[%d]= %12.7f",j,xi[j],j,p[j]);
                   2396:     if(j % ncovmodel == 0){
1.191     brouard  2397:       printf("\n");
1.202     brouard  2398:       fprintf(ficlog,"\n");
                   2399:     }
1.191     brouard  2400:   }
1.203     brouard  2401: #else
1.191     brouard  2402: #endif
1.126     brouard  2403:   free_vector(xicom,1,n); 
                   2404:   free_vector(pcom,1,n); 
                   2405: } 
                   2406: 
                   2407: 
                   2408: /*************** powell ************************/
1.162     brouard  2409: /*
1.317     brouard  2410: Minimization of a function func of n variables. Input consists in an initial starting point
                   2411: p[1..n] ; an initial matrix xi[1..n][1..n]  whose columns contain the initial set of di-
                   2412: rections (usually the n unit vectors); and ftol, the fractional tolerance in the function value
                   2413: such that failure to decrease by more than this amount in one iteration signals doneness. On
1.162     brouard  2414: output, p is set to the best point found, xi is the then-current direction set, fret is the returned
                   2415: function value at p , and iter is the number of iterations taken. The routine linmin is used.
                   2416:  */
1.224     brouard  2417: #ifdef LINMINORIGINAL
                   2418: #else
                   2419:        int *flatdir; /* Function is vanishing in that direction */
1.225     brouard  2420:        int flat=0, flatd=0; /* Function is vanishing in that direction */
1.224     brouard  2421: #endif
1.126     brouard  2422: void powell(double p[], double **xi, int n, double ftol, int *iter, double *fret, 
                   2423:            double (*func)(double [])) 
                   2424: { 
1.224     brouard  2425: #ifdef LINMINORIGINAL
                   2426:  void linmin(double p[], double xi[], int n, double *fret, 
1.126     brouard  2427:              double (*func)(double [])); 
1.224     brouard  2428: #else 
1.241     brouard  2429:  void linmin(double p[], double xi[], int n, double *fret,
                   2430:             double (*func)(double []),int *flat); 
1.224     brouard  2431: #endif
1.239     brouard  2432:  int i,ibig,j,jk,k; 
1.126     brouard  2433:   double del,t,*pt,*ptt,*xit;
1.181     brouard  2434:   double directest;
1.126     brouard  2435:   double fp,fptt;
                   2436:   double *xits;
                   2437:   int niterf, itmp;
                   2438: 
                   2439:   pt=vector(1,n); 
                   2440:   ptt=vector(1,n); 
                   2441:   xit=vector(1,n); 
                   2442:   xits=vector(1,n); 
                   2443:   *fret=(*func)(p); 
                   2444:   for (j=1;j<=n;j++) pt[j]=p[j]; 
1.202     brouard  2445:   rcurr_time = time(NULL);  
1.126     brouard  2446:   for (*iter=1;;++(*iter)) { 
                   2447:     ibig=0; 
                   2448:     del=0.0; 
1.157     brouard  2449:     rlast_time=rcurr_time;
                   2450:     /* (void) gettimeofday(&curr_time,&tzp); */
                   2451:     rcurr_time = time(NULL);  
                   2452:     curr_time = *localtime(&rcurr_time);
1.324     brouard  2453:     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);
                   2454:     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  2455: /*     fprintf(ficrespow,"%d %.12f %ld",*iter,*fret,curr_time.tm_sec-start_time.tm_sec); */
1.324     brouard  2456:     fp=(*fret); /* From former iteration or initial value */
1.192     brouard  2457:     for (i=1;i<=n;i++) {
1.126     brouard  2458:       fprintf(ficrespow," %.12lf", p[i]);
                   2459:     }
1.239     brouard  2460:     fprintf(ficrespow,"\n");fflush(ficrespow);
                   2461:     printf("\n#model=  1      +     age ");
                   2462:     fprintf(ficlog,"\n#model=  1      +     age ");
                   2463:     if(nagesqr==1){
1.241     brouard  2464:        printf("  + age*age  ");
                   2465:        fprintf(ficlog,"  + age*age  ");
1.239     brouard  2466:     }
                   2467:     for(j=1;j <=ncovmodel-2;j++){
                   2468:       if(Typevar[j]==0) {
                   2469:        printf("  +      V%d  ",Tvar[j]);
                   2470:        fprintf(ficlog,"  +      V%d  ",Tvar[j]);
                   2471:       }else if(Typevar[j]==1) {
                   2472:        printf("  +    V%d*age ",Tvar[j]);
                   2473:        fprintf(ficlog,"  +    V%d*age ",Tvar[j]);
                   2474:       }else if(Typevar[j]==2) {
                   2475:        printf("  +    V%d*V%d ",Tvard[Tposprod[j]][1],Tvard[Tposprod[j]][2]);
                   2476:        fprintf(ficlog,"  +    V%d*V%d ",Tvard[Tposprod[j]][1],Tvard[Tposprod[j]][2]);
                   2477:       }
                   2478:     }
1.126     brouard  2479:     printf("\n");
1.239     brouard  2480: /*     printf("12   47.0114589    0.0154322   33.2424412    0.3279905    2.3731903  */
                   2481: /* 13  -21.5392400    0.1118147    1.2680506    1.2973408   -1.0663662  */
1.126     brouard  2482:     fprintf(ficlog,"\n");
1.239     brouard  2483:     for(i=1,jk=1; i <=nlstate; i++){
                   2484:       for(k=1; k <=(nlstate+ndeath); k++){
                   2485:        if (k != i) {
                   2486:          printf("%d%d ",i,k);
                   2487:          fprintf(ficlog,"%d%d ",i,k);
                   2488:          for(j=1; j <=ncovmodel; j++){
                   2489:            printf("%12.7f ",p[jk]);
                   2490:            fprintf(ficlog,"%12.7f ",p[jk]);
                   2491:            jk++; 
                   2492:          }
                   2493:          printf("\n");
                   2494:          fprintf(ficlog,"\n");
                   2495:        }
                   2496:       }
                   2497:     }
1.241     brouard  2498:     if(*iter <=3 && *iter >1){
1.157     brouard  2499:       tml = *localtime(&rcurr_time);
                   2500:       strcpy(strcurr,asctime(&tml));
                   2501:       rforecast_time=rcurr_time; 
1.126     brouard  2502:       itmp = strlen(strcurr);
                   2503:       if(strcurr[itmp-1]=='\n')  /* Windows outputs with a new line */
1.241     brouard  2504:        strcurr[itmp-1]='\0';
1.162     brouard  2505:       printf("\nConsidering the time needed for the last iteration #%d: %ld seconds,\n",*iter,rcurr_time-rlast_time);
1.157     brouard  2506:       fprintf(ficlog,"\nConsidering the time needed for this last iteration #%d: %ld seconds,\n",*iter,rcurr_time-rlast_time);
1.126     brouard  2507:       for(niterf=10;niterf<=30;niterf+=10){
1.241     brouard  2508:        rforecast_time=rcurr_time+(niterf-*iter)*(rcurr_time-rlast_time);
                   2509:        forecast_time = *localtime(&rforecast_time);
                   2510:        strcpy(strfor,asctime(&forecast_time));
                   2511:        itmp = strlen(strfor);
                   2512:        if(strfor[itmp-1]=='\n')
                   2513:          strfor[itmp-1]='\0';
                   2514:        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);
                   2515:        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  2516:       }
                   2517:     }
1.187     brouard  2518:     for (i=1;i<=n;i++) { /* For each direction i */
                   2519:       for (j=1;j<=n;j++) xit[j]=xi[j][i]; /* Directions stored from previous iteration with previous scales */
1.126     brouard  2520:       fptt=(*fret); 
                   2521: #ifdef DEBUG
1.203     brouard  2522:       printf("fret=%lf, %lf, %lf \n", *fret, *fret, *fret);
                   2523:       fprintf(ficlog, "fret=%lf, %lf, %lf \n", *fret, *fret, *fret);
1.126     brouard  2524: #endif
1.203     brouard  2525:       printf("%d",i);fflush(stdout); /* print direction (parameter) i */
1.126     brouard  2526:       fprintf(ficlog,"%d",i);fflush(ficlog);
1.224     brouard  2527: #ifdef LINMINORIGINAL
1.188     brouard  2528:       linmin(p,xit,n,fret,func); /* Point p[n]. xit[n] has been loaded for direction i as input.*/
1.224     brouard  2529: #else
                   2530:       linmin(p,xit,n,fret,func,&flat); /* Point p[n]. xit[n] has been loaded for direction i as input.*/
                   2531:                        flatdir[i]=flat; /* Function is vanishing in that direction i */
                   2532: #endif
                   2533:                        /* Outputs are fret(new point p) p is updated and xit rescaled */
1.188     brouard  2534:       if (fabs(fptt-(*fret)) > del) { /* We are keeping the max gain on each of the n directions */
1.224     brouard  2535:                                /* because that direction will be replaced unless the gain del is small */
                   2536:                                /* in comparison with the 'probable' gain, mu^2, with the last average direction. */
                   2537:                                /* Unless the n directions are conjugate some gain in the determinant may be obtained */
                   2538:                                /* with the new direction. */
                   2539:                                del=fabs(fptt-(*fret)); 
                   2540:                                ibig=i; 
1.126     brouard  2541:       } 
                   2542: #ifdef DEBUG
                   2543:       printf("%d %.12e",i,(*fret));
                   2544:       fprintf(ficlog,"%d %.12e",i,(*fret));
                   2545:       for (j=1;j<=n;j++) {
1.224     brouard  2546:                                xits[j]=FMAX(fabs(p[j]-pt[j]),1.e-5);
                   2547:                                printf(" x(%d)=%.12e",j,xit[j]);
                   2548:                                fprintf(ficlog," x(%d)=%.12e",j,xit[j]);
1.126     brouard  2549:       }
                   2550:       for(j=1;j<=n;j++) {
1.225     brouard  2551:                                printf(" p(%d)=%.12e",j,p[j]);
                   2552:                                fprintf(ficlog," p(%d)=%.12e",j,p[j]);
1.126     brouard  2553:       }
                   2554:       printf("\n");
                   2555:       fprintf(ficlog,"\n");
                   2556: #endif
1.187     brouard  2557:     } /* end loop on each direction i */
                   2558:     /* Convergence test will use last linmin estimation (fret) and compare former iteration (fp) */ 
1.188     brouard  2559:     /* But p and xit have been updated at the end of linmin, *fret corresponds to new p, xit  */
1.187     brouard  2560:     /* New value of last point Pn is not computed, P(n-1) */
1.319     brouard  2561:     for(j=1;j<=n;j++) {
                   2562:       if(flatdir[j] >0){
                   2563:         printf(" p(%d)=%lf flat=%d ",j,p[j],flatdir[j]);
                   2564:         fprintf(ficlog," p(%d)=%lf flat=%d ",j,p[j],flatdir[j]);
1.302     brouard  2565:       }
1.319     brouard  2566:       /* printf("\n"); */
                   2567:       /* fprintf(ficlog,"\n"); */
                   2568:     }
1.243     brouard  2569:     /* if (2.0*fabs(fp-(*fret)) <= ftol*(fabs(fp)+fabs(*fret))) { /\* Did we reach enough precision? *\/ */
                   2570:     if (2.0*fabs(fp-(*fret)) <= ftol) { /* Did we reach enough precision? */
1.188     brouard  2571:       /* We could compare with a chi^2. chisquare(0.95,ddl=1)=3.84 */
                   2572:       /* By adding age*age in a model, the new -2LL should be lower and the difference follows a */
                   2573:       /* a chisquare statistics with 1 degree. To be significant at the 95% level, it should have */
                   2574:       /* decreased of more than 3.84  */
                   2575:       /* By adding age*age and V1*age the gain (-2LL) should be more than 5.99 (ddl=2) */
                   2576:       /* By using V1+V2+V3, the gain should be  7.82, compared with basic 1+age. */
                   2577:       /* By adding 10 parameters more the gain should be 18.31 */
1.224     brouard  2578:                        
1.188     brouard  2579:       /* Starting the program with initial values given by a former maximization will simply change */
                   2580:       /* the scales of the directions and the directions, because the are reset to canonical directions */
                   2581:       /* Thus the first calls to linmin will give new points and better maximizations until fp-(*fret) is */
                   2582:       /* under the tolerance value. If the tolerance is very small 1.e-9, it could last long.  */
1.126     brouard  2583: #ifdef DEBUG
                   2584:       int k[2],l;
                   2585:       k[0]=1;
                   2586:       k[1]=-1;
                   2587:       printf("Max: %.12e",(*func)(p));
                   2588:       fprintf(ficlog,"Max: %.12e",(*func)(p));
                   2589:       for (j=1;j<=n;j++) {
                   2590:        printf(" %.12e",p[j]);
                   2591:        fprintf(ficlog," %.12e",p[j]);
                   2592:       }
                   2593:       printf("\n");
                   2594:       fprintf(ficlog,"\n");
                   2595:       for(l=0;l<=1;l++) {
                   2596:        for (j=1;j<=n;j++) {
                   2597:          ptt[j]=p[j]+(p[j]-pt[j])*k[l];
                   2598:          printf("l=%d j=%d ptt=%.12e, xits=%.12e, p=%.12e, xit=%.12e", l,j,ptt[j],xits[j],p[j],xit[j]);
                   2599:          fprintf(ficlog,"l=%d j=%d ptt=%.12e, xits=%.12e, p=%.12e, xit=%.12e", l,j,ptt[j],xits[j],p[j],xit[j]);
                   2600:        }
                   2601:        printf("func(ptt)=%.12e, deriv=%.12e\n",(*func)(ptt),(ptt[j]-p[j])/((*func)(ptt)-(*func)(p)));
                   2602:        fprintf(ficlog,"func(ptt)=%.12e, deriv=%.12e\n",(*func)(ptt),(ptt[j]-p[j])/((*func)(ptt)-(*func)(p)));
                   2603:       }
                   2604: #endif
                   2605: 
                   2606:       free_vector(xit,1,n); 
                   2607:       free_vector(xits,1,n); 
                   2608:       free_vector(ptt,1,n); 
                   2609:       free_vector(pt,1,n); 
                   2610:       return; 
1.192     brouard  2611:     } /* enough precision */ 
1.240     brouard  2612:     if (*iter == ITMAX*n) nrerror("powell exceeding maximum iterations."); 
1.181     brouard  2613:     for (j=1;j<=n;j++) { /* Computes the extrapolated point P_0 + 2 (P_n-P_0) */
1.126     brouard  2614:       ptt[j]=2.0*p[j]-pt[j]; 
                   2615:       xit[j]=p[j]-pt[j]; 
                   2616:       pt[j]=p[j]; 
                   2617:     } 
1.181     brouard  2618:     fptt=(*func)(ptt); /* f_3 */
1.224     brouard  2619: #ifdef NODIRECTIONCHANGEDUNTILNITER  /* No change in drections until some iterations are done */
                   2620:                if (*iter <=4) {
1.225     brouard  2621: #else
                   2622: #endif
1.224     brouard  2623: #ifdef POWELLNOF3INFF1TEST    /* skips test F3 <F1 */
1.192     brouard  2624: #else
1.161     brouard  2625:     if (fptt < fp) { /* If extrapolated point is better, decide if we keep that new direction or not */
1.192     brouard  2626: #endif
1.162     brouard  2627:       /* (x1 f1=fp), (x2 f2=*fret), (x3 f3=fptt), (xm fm) */
1.161     brouard  2628:       /* From x1 (P0) distance of x2 is at h and x3 is 2h */
1.162     brouard  2629:       /* Let f"(x2) be the 2nd derivative equal everywhere.  */
                   2630:       /* Then the parabolic through (x1,f1), (x2,f2) and (x3,f3) */
                   2631:       /* will reach at f3 = fm + h^2/2 f"m  ; f" = (f1 -2f2 +f3 ) / h**2 */
1.224     brouard  2632:       /* Conditional for using this new direction is that mu^2 = (f1-2f2+f3)^2 /2 < del or directest <0 */
                   2633:       /* also  lamda^2=(f1-f2)^2/mu² is a parasite solution of powell */
                   2634:       /* For powell, inclusion of this average direction is only if t(del)<0 or del inbetween mu^2 and lambda^2 */
1.161     brouard  2635:       /* t=2.0*(fp-2.0*(*fret)+fptt)*SQR(fp-(*fret)-del)-del*SQR(fp-fptt); */
1.224     brouard  2636:       /*  Even if f3 <f1, directest can be negative and t >0 */
                   2637:       /* mu² and del² are equal when f3=f1 */
                   2638:                        /* f3 < f1 : mu² < del <= lambda^2 both test are equivalent */
                   2639:                        /* f3 < f1 : mu² < lambda^2 < del then directtest is negative and powell t is positive */
                   2640:                        /* f3 > f1 : lambda² < mu^2 < del then t is negative and directest >0  */
                   2641:                        /* f3 > f1 : lambda² < del < mu^2 then t is positive and directest >0  */
1.183     brouard  2642: #ifdef NRCORIGINAL
                   2643:       t=2.0*(fp-2.0*(*fret)+fptt)*SQR(fp-(*fret)-del)- del*SQR(fp-fptt); /* Original Numerical Recipes in C*/
                   2644: #else
                   2645:       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  2646:       t= t- del*SQR(fp-fptt);
1.183     brouard  2647: #endif
1.202     brouard  2648:       directest = fp-2.0*(*fret)+fptt - 2.0 * del; /* If delta was big enough we change it for a new direction */
1.161     brouard  2649: #ifdef DEBUG
1.181     brouard  2650:       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);
                   2651:       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  2652:       printf("t3= %.12lf, t4= %.12lf, t3*= %.12lf, t4*= %.12lf\n",SQR(fp-(*fret)-del),SQR(fp-fptt),
                   2653:             (fp-(*fret)-del)*(fp-(*fret)-del),(fp-fptt)*(fp-fptt));
                   2654:       fprintf(ficlog,"t3= %.12lf, t4= %.12lf, t3*= %.12lf, t4*= %.12lf\n",SQR(fp-(*fret)-del),SQR(fp-fptt),
                   2655:             (fp-(*fret)-del)*(fp-(*fret)-del),(fp-fptt)*(fp-fptt));
                   2656:       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);
                   2657:       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);
                   2658: #endif
1.183     brouard  2659: #ifdef POWELLORIGINAL
                   2660:       if (t < 0.0) { /* Then we use it for new direction */
                   2661: #else
1.182     brouard  2662:       if (directest*t < 0.0) { /* Contradiction between both tests */
1.224     brouard  2663:                                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  2664:         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  2665:         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  2666:         fprintf(ficlog,"f1-2f2+f3= %.12lf, f1-f2-del= %.12lf, f1-f3= %.12lf\n",fp-2.0*(*fret)+fptt, fp -(*fret) -del, fp-fptt);
                   2667:       } 
1.181     brouard  2668:       if (directest < 0.0) { /* Then we use it for new direction */
                   2669: #endif
1.191     brouard  2670: #ifdef DEBUGLINMIN
1.234     brouard  2671:        printf("Before linmin in direction P%d-P0\n",n);
                   2672:        for (j=1;j<=n;j++) {
                   2673:          printf(" Before xit[%d]= %12.7f p[%d]= %12.7f",j,xit[j],j,p[j]);
                   2674:          fprintf(ficlog," Before xit[%d]= %12.7f p[%d]= %12.7f",j,xit[j],j,p[j]);
                   2675:          if(j % ncovmodel == 0){
                   2676:            printf("\n");
                   2677:            fprintf(ficlog,"\n");
                   2678:          }
                   2679:        }
1.224     brouard  2680: #endif
                   2681: #ifdef LINMINORIGINAL
1.234     brouard  2682:        linmin(p,xit,n,fret,func); /* computes minimum on the extrapolated direction: changes p and rescales xit.*/
1.224     brouard  2683: #else
1.234     brouard  2684:        linmin(p,xit,n,fret,func,&flat); /* computes minimum on the extrapolated direction: changes p and rescales xit.*/
                   2685:        flatdir[i]=flat; /* Function is vanishing in that direction i */
1.191     brouard  2686: #endif
1.234     brouard  2687:        
1.191     brouard  2688: #ifdef DEBUGLINMIN
1.234     brouard  2689:        for (j=1;j<=n;j++) { 
                   2690:          printf("After xit[%d]= %12.7f p[%d]= %12.7f",j,xit[j],j,p[j]);
                   2691:          fprintf(ficlog,"After xit[%d]= %12.7f p[%d]= %12.7f",j,xit[j],j,p[j]);
                   2692:          if(j % ncovmodel == 0){
                   2693:            printf("\n");
                   2694:            fprintf(ficlog,"\n");
                   2695:          }
                   2696:        }
1.224     brouard  2697: #endif
1.234     brouard  2698:        for (j=1;j<=n;j++) { 
                   2699:          xi[j][ibig]=xi[j][n]; /* Replace direction with biggest decrease by last direction n */
                   2700:          xi[j][n]=xit[j];      /* and this nth direction by the by the average p_0 p_n */
                   2701:        }
1.224     brouard  2702: #ifdef LINMINORIGINAL
                   2703: #else
1.234     brouard  2704:        for (j=1, flatd=0;j<=n;j++) {
                   2705:          if(flatdir[j]>0)
                   2706:            flatd++;
                   2707:        }
                   2708:        if(flatd >0){
1.255     brouard  2709:          printf("%d flat directions: ",flatd);
                   2710:          fprintf(ficlog,"%d flat directions :",flatd);
1.234     brouard  2711:          for (j=1;j<=n;j++) { 
                   2712:            if(flatdir[j]>0){
                   2713:              printf("%d ",j);
                   2714:              fprintf(ficlog,"%d ",j);
                   2715:            }
                   2716:          }
                   2717:          printf("\n");
                   2718:          fprintf(ficlog,"\n");
1.319     brouard  2719: #ifdef FLATSUP
                   2720:           free_vector(xit,1,n); 
                   2721:           free_vector(xits,1,n); 
                   2722:           free_vector(ptt,1,n); 
                   2723:           free_vector(pt,1,n); 
                   2724:           return;
                   2725: #endif
1.234     brouard  2726:        }
1.191     brouard  2727: #endif
1.234     brouard  2728:        printf("Gaining to use new average direction of P0 P%d instead of biggest increase direction %d :\n",n,ibig);
                   2729:        fprintf(ficlog,"Gaining to use new average direction of P0 P%d instead of biggest increase direction %d :\n",n,ibig);
                   2730:        
1.126     brouard  2731: #ifdef DEBUG
1.234     brouard  2732:        printf("Direction changed  last moved %d in place of ibig=%d, new last is the average:\n",n,ibig);
                   2733:        fprintf(ficlog,"Direction changed  last moved %d in place of ibig=%d, new last is the average:\n",n,ibig);
                   2734:        for(j=1;j<=n;j++){
                   2735:          printf(" %lf",xit[j]);
                   2736:          fprintf(ficlog," %lf",xit[j]);
                   2737:        }
                   2738:        printf("\n");
                   2739:        fprintf(ficlog,"\n");
1.126     brouard  2740: #endif
1.192     brouard  2741:       } /* end of t or directest negative */
1.224     brouard  2742: #ifdef POWELLNOF3INFF1TEST
1.192     brouard  2743: #else
1.234     brouard  2744:       } /* end if (fptt < fp)  */
1.192     brouard  2745: #endif
1.225     brouard  2746: #ifdef NODIRECTIONCHANGEDUNTILNITER  /* No change in drections until some iterations are done */
1.234     brouard  2747:     } /*NODIRECTIONCHANGEDUNTILNITER  No change in drections until some iterations are done */
1.225     brouard  2748: #else
1.224     brouard  2749: #endif
1.234     brouard  2750:                } /* loop iteration */ 
1.126     brouard  2751: } 
1.234     brouard  2752:   
1.126     brouard  2753: /**** Prevalence limit (stable or period prevalence)  ****************/
1.234     brouard  2754:   
1.235     brouard  2755:   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  2756:   {
1.279     brouard  2757:     /**< Computes the prevalence limit in each live state at age x and for covariate combination ij 
                   2758:      *   (and selected quantitative values in nres)
                   2759:      *  by left multiplying the unit
                   2760:      *  matrix by transitions matrix until convergence is reached with precision ftolpl 
                   2761:      * Wx= Wx-1 Px-1= Wx-2 Px-2 Px-1  = Wx-n Px-n ... Px-2 Px-1 I
                   2762:      * Wx is row vector: population in state 1, population in state 2, population dead
                   2763:      * or prevalence in state 1, prevalence in state 2, 0
                   2764:      * newm is the matrix after multiplications, its rows are identical at a factor.
                   2765:      * Inputs are the parameter, age, a tolerance for the prevalence limit ftolpl.
                   2766:      * Output is prlim.
                   2767:      * Initial matrix pimij 
                   2768:      */
1.206     brouard  2769:   /* {0.85204250825084937, 0.13044499163996345, 0.017512500109187184, */
                   2770:   /* 0.090851990222114765, 0.88271245433047185, 0.026435555447413338, */
                   2771:   /*  0,                   0                  , 1} */
                   2772:   /*
                   2773:    * and after some iteration: */
                   2774:   /* {0.45504275246439968, 0.42731458730878791, 0.11764266022681241, */
                   2775:   /*  0.45201005341706885, 0.42865420071559901, 0.11933574586733192, */
                   2776:   /*  0,                   0                  , 1} */
                   2777:   /* And prevalence by suppressing the deaths are close to identical rows in prlim: */
                   2778:   /* {0.51571254859325999, 0.4842874514067399, */
                   2779:   /*  0.51326036147820708, 0.48673963852179264} */
                   2780:   /* If we start from prlim again, prlim tends to a constant matrix */
1.234     brouard  2781:     
1.126     brouard  2782:   int i, ii,j,k;
1.209     brouard  2783:   double *min, *max, *meandiff, maxmax,sumnew=0.;
1.145     brouard  2784:   /* double **matprod2(); */ /* test */
1.218     brouard  2785:   double **out, cov[NCOVMAX+1], **pmij(); /* **pmmij is a global variable feeded with oldms etc */
1.126     brouard  2786:   double **newm;
1.209     brouard  2787:   double agefin, delaymax=200. ; /* 100 Max number of years to converge */
1.203     brouard  2788:   int ncvloop=0;
1.288     brouard  2789:   int first=0;
1.169     brouard  2790:   
1.209     brouard  2791:   min=vector(1,nlstate);
                   2792:   max=vector(1,nlstate);
                   2793:   meandiff=vector(1,nlstate);
                   2794: 
1.218     brouard  2795:        /* Starting with matrix unity */
1.126     brouard  2796:   for (ii=1;ii<=nlstate+ndeath;ii++)
                   2797:     for (j=1;j<=nlstate+ndeath;j++){
                   2798:       oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   2799:     }
1.169     brouard  2800:   
                   2801:   cov[1]=1.;
                   2802:   
                   2803:   /* Even if hstepm = 1, at least one multiplication by the unit matrix */
1.202     brouard  2804:   /* Start at agefin= age, computes the matrix of passage and loops decreasing agefin until convergence is reached */
1.126     brouard  2805:   for(agefin=age-stepm/YEARM; agefin>=age-delaymax; agefin=agefin-stepm/YEARM){
1.202     brouard  2806:     ncvloop++;
1.126     brouard  2807:     newm=savm;
                   2808:     /* Covariates have to be included here again */
1.138     brouard  2809:     cov[2]=agefin;
1.319     brouard  2810:      if(nagesqr==1){
                   2811:       cov[3]= agefin*agefin;
                   2812:      }
1.234     brouard  2813:     for (k=1; k<=nsd;k++) { /* For single dummy covariates only */
                   2814:                        /* Here comes the value of the covariate 'ij' after renumbering k with single dummy covariates */
1.330   ! brouard  2815:       cov[2+nagesqr+TvarsDind[k]]=nbcode[TvarsD[k]][codtabm(ij,TvarsD[k])];
1.319     brouard  2816:       /* cov[++k1]=nbcode[TvarsD[k]][codtabm(ij,k)]; */
1.235     brouard  2817:       /* 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  2818:     }
                   2819:     for (k=1; k<=nsq;k++) { /* For single varying covariates only */
                   2820:                        /* Here comes the value of quantitative after renumbering k with single quantitative covariates */
1.319     brouard  2821:       cov[2+nagesqr+TvarsQind[k]]=Tqresult[nres][k];
                   2822:       /* cov[++k1]=Tqresult[nres][k];  */
1.235     brouard  2823:       /* 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  2824:     }
1.237     brouard  2825:     for (k=1; k<=cptcovage;k++){  /* For product with age */
1.319     brouard  2826:       if(Dummy[Tage[k]]==2){ /* dummy with age */
1.330   ! brouard  2827:        cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,Tvar[Tage[k]])]*cov[2];
1.319     brouard  2828:        /* cov[++k1]=nbcode[Tvar[Tage[k]]][codtabm(ij,k)]*cov[2]; */
                   2829:       } else if(Dummy[Tage[k]]==3){ /* quantitative with age */
                   2830:        cov[2+nagesqr+Tage[k]]=Tqresult[nres][k];
                   2831:        /* cov[++k1]=Tqresult[nres][k];  */
1.234     brouard  2832:       }
1.235     brouard  2833:       /* 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  2834:     }
1.237     brouard  2835:     for (k=1; k<=cptcovprod;k++){ /* For product without age */
1.235     brouard  2836:       /* 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.329     brouard  2837:       if(Dummy[Tvard[k][1]]==0){
                   2838:        if(Dummy[Tvard[k][2]]==0){
1.330   ! brouard  2839:          cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,Tvard[k][1])] * nbcode[Tvard[k][2]][codtabm(ij,Tvard[k][2])];
1.319     brouard  2840:          /* cov[++k1]=nbcode[Tvard[k][1]][codtabm(ij,k)] * nbcode[Tvard[k][2]][codtabm(ij,k)]; */
1.237     brouard  2841:        }else{
1.330   ! brouard  2842:          cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,Tvard[k][1])] * Tqresult[nres][k];
1.319     brouard  2843:          /* cov[++k1]=nbcode[Tvard[k][1]][codtabm(ij,k)] * Tqresult[nres][k]; */
1.237     brouard  2844:        }
                   2845:       }else{
1.329     brouard  2846:        if(Dummy[Tvard[k][2]]==0){
1.330   ! brouard  2847:          cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][2]][codtabm(ij,Tvard[k][2])] * Tqinvresult[nres][Tvard[k][1]];
1.319     brouard  2848:          /* cov[++k1]=nbcode[Tvard[k][2]][codtabm(ij,k)] * Tqinvresult[nres][Tvard[k][1]]; */
1.237     brouard  2849:        }else{
                   2850:          cov[2+nagesqr+Tprod[k]]=Tqinvresult[nres][Tvard[k][1]]*  Tqinvresult[nres][Tvard[k][2]];
1.319     brouard  2851:          /* cov[++k1]=Tqinvresult[nres][Tvard[k][1]]*  Tqinvresult[nres][Tvard[k][2]]; */
1.237     brouard  2852:        }
                   2853:       }
1.234     brouard  2854:     }
1.138     brouard  2855:     /*printf("ij=%d cptcovprod=%d tvar=%d ", ij, cptcovprod, Tvar[1]);*/
                   2856:     /*printf("ij=%d cov[3]=%lf cov[4]=%lf \n",ij, cov[3],cov[4]);*/
                   2857:     /*printf("ij=%d cov[3]=%lf \n",ij, cov[3]);*/
1.145     brouard  2858:     /* savm=pmij(pmmij,cov,ncovmodel,x,nlstate); */
                   2859:     /* out=matprod2(newm, pmij(pmmij,cov,ncovmodel,x,nlstate),1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm); /\* Bug Valgrind *\/ */
1.319     brouard  2860:     /* age and covariate values of ij are in 'cov' */
1.142     brouard  2861:     out=matprod2(newm, pmij(pmmij,cov,ncovmodel,x,nlstate),1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm); /* Bug Valgrind */
1.138     brouard  2862:     
1.126     brouard  2863:     savm=oldm;
                   2864:     oldm=newm;
1.209     brouard  2865: 
                   2866:     for(j=1; j<=nlstate; j++){
                   2867:       max[j]=0.;
                   2868:       min[j]=1.;
                   2869:     }
                   2870:     for(i=1;i<=nlstate;i++){
                   2871:       sumnew=0;
                   2872:       for(k=1; k<=ndeath; k++) sumnew+=newm[i][nlstate+k];
                   2873:       for(j=1; j<=nlstate; j++){ 
                   2874:        prlim[i][j]= newm[i][j]/(1-sumnew);
                   2875:        max[j]=FMAX(max[j],prlim[i][j]);
                   2876:        min[j]=FMIN(min[j],prlim[i][j]);
                   2877:       }
                   2878:     }
                   2879: 
1.126     brouard  2880:     maxmax=0.;
1.209     brouard  2881:     for(j=1; j<=nlstate; j++){
                   2882:       meandiff[j]=(max[j]-min[j])/(max[j]+min[j])*2.; /* mean difference for each column */
                   2883:       maxmax=FMAX(maxmax,meandiff[j]);
                   2884:       /* 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  2885:     } /* j loop */
1.203     brouard  2886:     *ncvyear= (int)age- (int)agefin;
1.208     brouard  2887:     /* 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  2888:     if(maxmax < ftolpl){
1.209     brouard  2889:       /* printf("maxmax=%lf ncvloop=%ld, age=%d, agefin=%d ncvyear=%d \n", maxmax, ncvloop, (int)age, (int)agefin, *ncvyear); */
                   2890:       free_vector(min,1,nlstate);
                   2891:       free_vector(max,1,nlstate);
                   2892:       free_vector(meandiff,1,nlstate);
1.126     brouard  2893:       return prlim;
                   2894:     }
1.288     brouard  2895:   } /* agefin loop */
1.208     brouard  2896:     /* After some age loop it doesn't converge */
1.288     brouard  2897:   if(!first){
                   2898:     first=1;
                   2899:     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  2900:     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);
                   2901:   }else if (first >=1 && first <10){
                   2902:     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);
                   2903:     first++;
                   2904:   }else if (first ==10){
                   2905:     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);
                   2906:     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");
                   2907:     fprintf(ficlog,"Warning: the stable prevalence no convergence; too many cases, giving up noticing, even in log file\n");
                   2908:     first++;
1.288     brouard  2909:   }
                   2910: 
1.209     brouard  2911:   /* 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); */
                   2912:   free_vector(min,1,nlstate);
                   2913:   free_vector(max,1,nlstate);
                   2914:   free_vector(meandiff,1,nlstate);
1.208     brouard  2915:   
1.169     brouard  2916:   return prlim; /* should not reach here */
1.126     brouard  2917: }
                   2918: 
1.217     brouard  2919: 
                   2920:  /**** Back Prevalence limit (stable or period prevalence)  ****************/
                   2921: 
1.218     brouard  2922:  /* 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) */
                   2923:  /* 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  2924:   double **bprevalim(double **bprlim, double ***prevacurrent, int nlstate, double x[], double age, double ftolpl, int *ncvyear, int ij, int nres)
1.217     brouard  2925: {
1.264     brouard  2926:   /* 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  2927:      matrix by transitions matrix until convergence is reached with precision ftolpl */
                   2928:   /* Wx= Wx-1 Px-1= Wx-2 Px-2 Px-1  = Wx-n Px-n ... Px-2 Px-1 I */
                   2929:   /* Wx is row vector: population in state 1, population in state 2, population dead */
                   2930:   /* or prevalence in state 1, prevalence in state 2, 0 */
                   2931:   /* newm is the matrix after multiplications, its rows are identical at a factor */
                   2932:   /* Initial matrix pimij */
                   2933:   /* {0.85204250825084937, 0.13044499163996345, 0.017512500109187184, */
                   2934:   /* 0.090851990222114765, 0.88271245433047185, 0.026435555447413338, */
                   2935:   /*  0,                   0                  , 1} */
                   2936:   /*
                   2937:    * and after some iteration: */
                   2938:   /* {0.45504275246439968, 0.42731458730878791, 0.11764266022681241, */
                   2939:   /*  0.45201005341706885, 0.42865420071559901, 0.11933574586733192, */
                   2940:   /*  0,                   0                  , 1} */
                   2941:   /* And prevalence by suppressing the deaths are close to identical rows in prlim: */
                   2942:   /* {0.51571254859325999, 0.4842874514067399, */
                   2943:   /*  0.51326036147820708, 0.48673963852179264} */
                   2944:   /* If we start from prlim again, prlim tends to a constant matrix */
                   2945: 
                   2946:   int i, ii,j,k;
1.247     brouard  2947:   int first=0;
1.217     brouard  2948:   double *min, *max, *meandiff, maxmax,sumnew=0.;
                   2949:   /* double **matprod2(); */ /* test */
                   2950:   double **out, cov[NCOVMAX+1], **bmij();
                   2951:   double **newm;
1.218     brouard  2952:   double        **dnewm, **doldm, **dsavm;  /* for use */
                   2953:   double        **oldm, **savm;  /* for use */
                   2954: 
1.217     brouard  2955:   double agefin, delaymax=200. ; /* 100 Max number of years to converge */
                   2956:   int ncvloop=0;
                   2957:   
                   2958:   min=vector(1,nlstate);
                   2959:   max=vector(1,nlstate);
                   2960:   meandiff=vector(1,nlstate);
                   2961: 
1.266     brouard  2962:   dnewm=ddnewms; doldm=ddoldms; dsavm=ddsavms;
                   2963:   oldm=oldms; savm=savms;
                   2964:   
                   2965:   /* Starting with matrix unity */
                   2966:   for (ii=1;ii<=nlstate+ndeath;ii++)
                   2967:     for (j=1;j<=nlstate+ndeath;j++){
1.217     brouard  2968:       oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   2969:     }
                   2970:   
                   2971:   cov[1]=1.;
                   2972:   
                   2973:   /* Even if hstepm = 1, at least one multiplication by the unit matrix */
                   2974:   /* Start at agefin= age, computes the matrix of passage and loops decreasing agefin until convergence is reached */
1.218     brouard  2975:   /* for(agefin=age+stepm/YEARM; agefin<=age+delaymax; agefin=agefin+stepm/YEARM){ /\* A changer en age *\/ */
1.288     brouard  2976:   /* for(agefin=age; agefin<AGESUP; agefin=agefin+stepm/YEARM){ /\* A changer en age *\/ */
                   2977:   for(agefin=age; agefin<FMIN(AGESUP,age+delaymax); agefin=agefin+stepm/YEARM){ /* A changer en age */
1.217     brouard  2978:     ncvloop++;
1.218     brouard  2979:     newm=savm; /* oldm should be kept from previous iteration or unity at start */
                   2980:                /* newm points to the allocated table savm passed by the function it can be written, savm could be reallocated */
1.217     brouard  2981:     /* Covariates have to be included here again */
                   2982:     cov[2]=agefin;
1.319     brouard  2983:     if(nagesqr==1){
1.217     brouard  2984:       cov[3]= agefin*agefin;;
1.319     brouard  2985:     }
1.242     brouard  2986:     for (k=1; k<=nsd;k++) { /* For single dummy covariates only */
                   2987:                        /* Here comes the value of the covariate 'ij' after renumbering k with single dummy covariates */
1.330   ! brouard  2988:       cov[2+nagesqr+TvarsDind[k]]=nbcode[TvarsD[k]][codtabm(ij,TvarsD[k])];
1.264     brouard  2989:       /* 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  2990:     }
                   2991:     /* for (k=1; k<=cptcovn;k++) { */
                   2992:     /*   /\* cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,Tvar[k])]; *\/ */
                   2993:     /*   cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,k)]; */
                   2994:     /*   /\* 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])]); *\/ */
                   2995:     /* } */
                   2996:     for (k=1; k<=nsq;k++) { /* For single varying covariates only */
                   2997:                        /* Here comes the value of quantitative after renumbering k with single quantitative covariates */
                   2998:       cov[2+nagesqr+TvarsQind[k]]=Tqresult[nres][k]; 
                   2999:       /* 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]); */
                   3000:     }
                   3001:     /* for (k=1; k<=cptcovage;k++) cov[2+nagesqr+Tage[k]]=nbcode[Tvar[k]][codtabm(ij,k)]*cov[2]; */
                   3002:     /* for (k=1; k<=cptcovprod;k++) /\* Useless *\/ */
                   3003:     /*   /\* cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,Tvard[k][1])] * nbcode[Tvard[k][2]][codtabm(ij,Tvard[k][2])]; *\/ */
                   3004:     /*   cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)] * nbcode[Tvard[k][2]][codtabm(ij,k)]; */
                   3005:     for (k=1; k<=cptcovage;k++){  /* For product with age */
1.319     brouard  3006:       /* if(Dummy[Tvar[Tage[k]]]== 2){ /\* dummy with age *\/ ERROR ???*/
                   3007:       if(Dummy[Tage[k]]== 2){ /* dummy with age */
1.330   ! brouard  3008:        cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,Tvar[Tage[k]])]*cov[2];
1.319     brouard  3009:       } else if(Dummy[Tage[k]]== 3){ /* quantitative with age */
                   3010:        cov[2+nagesqr+Tage[k]]=Tqresult[nres][k];
1.242     brouard  3011:       }
                   3012:       /* 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]); */
                   3013:     }
                   3014:     for (k=1; k<=cptcovprod;k++){ /* For product without age */
                   3015:       /* 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.329     brouard  3016:       if(Dummy[Tvard[k][1]]==0){
                   3017:        if(Dummy[Tvard[k][2]]==0){
1.330   ! brouard  3018:          cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,Tvard[k][1])] * nbcode[Tvard[k][2]][codtabm(ij,Tvard[k][2])];
1.242     brouard  3019:        }else{
1.330   ! brouard  3020:          cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,Tvard[k][1])] * Tqresult[nres][k];
1.242     brouard  3021:        }
                   3022:       }else{
1.329     brouard  3023:        if(Dummy[Tvard[k][2]]==0){
1.330   ! brouard  3024:          cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][2]][codtabm(ij,Tvard[k][2])] * Tqinvresult[nres][Tvard[k][1]];
1.242     brouard  3025:        }else{
                   3026:          cov[2+nagesqr+Tprod[k]]=Tqinvresult[nres][Tvard[k][1]]*  Tqinvresult[nres][Tvard[k][2]];
                   3027:        }
                   3028:       }
1.217     brouard  3029:     }
                   3030:     
                   3031:     /*printf("ij=%d cptcovprod=%d tvar=%d ", ij, cptcovprod, Tvar[1]);*/
                   3032:     /*printf("ij=%d cov[3]=%lf cov[4]=%lf \n",ij, cov[3],cov[4]);*/
                   3033:     /*printf("ij=%d cov[3]=%lf \n",ij, cov[3]);*/
                   3034:     /* savm=pmij(pmmij,cov,ncovmodel,x,nlstate); */
                   3035:     /* out=matprod2(newm, pmij(pmmij,cov,ncovmodel,x,nlstate),1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm); /\* Bug Valgrind *\/ */
1.218     brouard  3036:                /* ij should be linked to the correct index of cov */
                   3037:                /* age and covariate values ij are in 'cov', but we need to pass
                   3038:                 * ij for the observed prevalence at age and status and covariate
                   3039:                 * number:  prevacurrent[(int)agefin][ii][ij]
                   3040:                 */
                   3041:     /* 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 *\/ */
                   3042:     /* 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 *\/ */
                   3043:     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  3044:     /* if((int)age == 86 || (int)age == 87){ */
1.266     brouard  3045:     /*   printf(" Backward prevalim age=%d agefin=%d \n", (int) age, (int) agefin); */
                   3046:     /*   for(i=1; i<=nlstate+ndeath; i++) { */
                   3047:     /*         printf("%d newm= ",i); */
                   3048:     /*         for(j=1;j<=nlstate+ndeath;j++) { */
                   3049:     /*           printf("%f ",newm[i][j]); */
                   3050:     /*         } */
                   3051:     /*         printf("oldm * "); */
                   3052:     /*         for(j=1;j<=nlstate+ndeath;j++) { */
                   3053:     /*           printf("%f ",oldm[i][j]); */
                   3054:     /*         } */
1.268     brouard  3055:     /*         printf(" bmmij "); */
1.266     brouard  3056:     /*         for(j=1;j<=nlstate+ndeath;j++) { */
                   3057:     /*           printf("%f ",pmmij[i][j]); */
                   3058:     /*         } */
                   3059:     /*         printf("\n"); */
                   3060:     /*   } */
                   3061:     /* } */
1.217     brouard  3062:     savm=oldm;
                   3063:     oldm=newm;
1.266     brouard  3064: 
1.217     brouard  3065:     for(j=1; j<=nlstate; j++){
                   3066:       max[j]=0.;
                   3067:       min[j]=1.;
                   3068:     }
                   3069:     for(j=1; j<=nlstate; j++){ 
                   3070:       for(i=1;i<=nlstate;i++){
1.234     brouard  3071:        /* bprlim[i][j]= newm[i][j]/(1-sumnew); */
                   3072:        bprlim[i][j]= newm[i][j];
                   3073:        max[i]=FMAX(max[i],bprlim[i][j]); /* Max in line */
                   3074:        min[i]=FMIN(min[i],bprlim[i][j]);
1.217     brouard  3075:       }
                   3076:     }
1.218     brouard  3077:                
1.217     brouard  3078:     maxmax=0.;
                   3079:     for(i=1; i<=nlstate; i++){
1.318     brouard  3080:       meandiff[i]=(max[i]-min[i])/(max[i]+min[i])*2.; /* mean difference for each column, could be nan! */
1.217     brouard  3081:       maxmax=FMAX(maxmax,meandiff[i]);
                   3082:       /* 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  3083:     } /* i loop */
1.217     brouard  3084:     *ncvyear= -( (int)age- (int)agefin);
1.268     brouard  3085:     /* printf("Back maxmax=%lf ncvloop=%d, age=%d, agefin=%d ncvyear=%d \n", maxmax, ncvloop, (int)age, (int)agefin, *ncvyear); */
1.217     brouard  3086:     if(maxmax < ftolpl){
1.220     brouard  3087:       /* printf("OK Back maxmax=%lf ncvloop=%d, age=%d, agefin=%d ncvyear=%d \n", maxmax, ncvloop, (int)age, (int)agefin, *ncvyear); */
1.217     brouard  3088:       free_vector(min,1,nlstate);
                   3089:       free_vector(max,1,nlstate);
                   3090:       free_vector(meandiff,1,nlstate);
                   3091:       return bprlim;
                   3092:     }
1.288     brouard  3093:   } /* agefin loop */
1.217     brouard  3094:     /* After some age loop it doesn't converge */
1.288     brouard  3095:   if(!first){
1.247     brouard  3096:     first=1;
                   3097:     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\
                   3098: 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);
                   3099:   }
                   3100:   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  3101: 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);
                   3102:   /* 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); */
                   3103:   free_vector(min,1,nlstate);
                   3104:   free_vector(max,1,nlstate);
                   3105:   free_vector(meandiff,1,nlstate);
                   3106:   
                   3107:   return bprlim; /* should not reach here */
                   3108: }
                   3109: 
1.126     brouard  3110: /*************** transition probabilities ***************/ 
                   3111: 
                   3112: double **pmij(double **ps, double *cov, int ncovmodel, double *x, int nlstate )
                   3113: {
1.138     brouard  3114:   /* According to parameters values stored in x and the covariate's values stored in cov,
1.266     brouard  3115:      computes the probability to be observed in state j (after stepm years) being in state i by appying the
1.138     brouard  3116:      model to the ncovmodel covariates (including constant and age).
                   3117:      lnpijopii=ln(pij/pii)= aij+bij*age+cij*v1+dij*v2+... = sum_nc=1^ncovmodel xij(nc)*cov[nc]
                   3118:      and, according on how parameters are entered, the position of the coefficient xij(nc) of the
                   3119:      ncth covariate in the global vector x is given by the formula:
                   3120:      j<i nc+((i-1)*(nlstate+ndeath-1)+j-1)*ncovmodel
                   3121:      j>=i nc + ((i-1)*(nlstate+ndeath-1)+(j-2))*ncovmodel
                   3122:      Computes ln(pij/pii) (lnpijopii), deduces pij/pii by exponentiation,
                   3123:      sums on j different of i to get 1-pii/pii, deduces pii, and then all pij.
1.266     brouard  3124:      Outputs ps[i][j] or probability to be observed in j being in i according to
1.138     brouard  3125:      the values of the covariates cov[nc] and corresponding parameter values x[nc+shiftij]
1.266     brouard  3126:      Sum on j ps[i][j] should equal to 1.
1.138     brouard  3127:   */
                   3128:   double s1, lnpijopii;
1.126     brouard  3129:   /*double t34;*/
1.164     brouard  3130:   int i,j, nc, ii, jj;
1.126     brouard  3131: 
1.223     brouard  3132:   for(i=1; i<= nlstate; i++){
                   3133:     for(j=1; j<i;j++){
                   3134:       for (nc=1, lnpijopii=0.;nc <=ncovmodel; nc++){
                   3135:        /*lnpijopii += param[i][j][nc]*cov[nc];*/
                   3136:        lnpijopii += x[nc+((i-1)*(nlstate+ndeath-1)+j-1)*ncovmodel]*cov[nc];
                   3137:        /*       printf("Int j<i s1=%.17e, lnpijopii=%.17e\n",s1,lnpijopii); */
                   3138:       }
                   3139:       ps[i][j]=lnpijopii; /* In fact ln(pij/pii) */
1.330   ! brouard  3140:       /* printf("Debug pmij() i=%d j=%d nc=%d s1=%.17f, lnpijopii=%.17f\n",i,j,nc, s1,lnpijopii); */
1.223     brouard  3141:     }
                   3142:     for(j=i+1; j<=nlstate+ndeath;j++){
                   3143:       for (nc=1, lnpijopii=0.;nc <=ncovmodel; nc++){
                   3144:        /*lnpijopii += x[(i-1)*nlstate*ncovmodel+(j-2)*ncovmodel+nc+(i-1)*(ndeath-1)*ncovmodel]*cov[nc];*/
                   3145:        lnpijopii += x[nc + ((i-1)*(nlstate+ndeath-1)+(j-2))*ncovmodel]*cov[nc];
                   3146:        /*        printf("Int j>i s1=%.17e, lnpijopii=%.17e %lx %lx\n",s1,lnpijopii,s1,lnpijopii); */
                   3147:       }
                   3148:       ps[i][j]=lnpijopii; /* In fact ln(pij/pii) */
1.330   ! brouard  3149:       /* printf("Debug pmij() i=%d j=%d nc=%d s1=%.17f, lnpijopii=%.17f\n",i,j,nc, s1,lnpijopii); */
1.223     brouard  3150:     }
                   3151:   }
1.218     brouard  3152:   
1.223     brouard  3153:   for(i=1; i<= nlstate; i++){
                   3154:     s1=0;
                   3155:     for(j=1; j<i; j++){
                   3156:       s1+=exp(ps[i][j]); /* In fact sums pij/pii */
1.330   ! brouard  3157:       /* printf("debug1 %d %d ps=%lf exp(ps)=%lf s1+=%lf\n",i,j,ps[i][j],exp(ps[i][j]),s1); */
1.223     brouard  3158:     }
                   3159:     for(j=i+1; j<=nlstate+ndeath; j++){
                   3160:       s1+=exp(ps[i][j]); /* In fact sums pij/pii */
1.330   ! brouard  3161:       /* printf("debug2 %d %d ps=%lf exp(ps)=%lf s1+=%lf\n",i,j,ps[i][j],exp(ps[i][j]),s1); */
1.223     brouard  3162:     }
                   3163:     /* s1= sum_{j<>i} pij/pii=(1-pii)/pii and thus pii is known from s1 */
                   3164:     ps[i][i]=1./(s1+1.);
                   3165:     /* Computing other pijs */
                   3166:     for(j=1; j<i; j++)
1.325     brouard  3167:       ps[i][j]= exp(ps[i][j])*ps[i][i];/* Bug valgrind */
1.223     brouard  3168:     for(j=i+1; j<=nlstate+ndeath; j++)
                   3169:       ps[i][j]= exp(ps[i][j])*ps[i][i];
                   3170:     /* ps[i][nlstate+1]=1.-s1- ps[i][i];*/ /* Sum should be 1 */
                   3171:   } /* end i */
1.218     brouard  3172:   
1.223     brouard  3173:   for(ii=nlstate+1; ii<= nlstate+ndeath; ii++){
                   3174:     for(jj=1; jj<= nlstate+ndeath; jj++){
                   3175:       ps[ii][jj]=0;
                   3176:       ps[ii][ii]=1;
                   3177:     }
                   3178:   }
1.294     brouard  3179: 
                   3180: 
1.223     brouard  3181:   /* for(ii=1; ii<= nlstate+ndeath; ii++){ */
                   3182:   /*   for(jj=1; jj<= nlstate+ndeath; jj++){ */
                   3183:   /*   printf(" pmij  ps[%d][%d]=%lf ",ii,jj,ps[ii][jj]); */
                   3184:   /*   } */
                   3185:   /*   printf("\n "); */
                   3186:   /* } */
                   3187:   /* printf("\n ");printf("%lf ",cov[2]);*/
                   3188:   /*
                   3189:     for(i=1; i<= npar; i++) printf("%f ",x[i]);
1.218     brouard  3190:                goto end;*/
1.266     brouard  3191:   return ps; /* Pointer is unchanged since its call */
1.126     brouard  3192: }
                   3193: 
1.218     brouard  3194: /*************** backward transition probabilities ***************/ 
                   3195: 
                   3196:  /* 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 ) */
                   3197: /* double **bmij(double **ps, double *cov, int ncovmodel, double *x, int nlstate,  double ***prevacurrent, double ***dnewm, double **doldm, double **dsavm, int ij ) */
                   3198:  double **bmij(double **ps, double *cov, int ncovmodel, double *x, int nlstate,  double ***prevacurrent, int ij )
                   3199: {
1.302     brouard  3200:   /* 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  3201:    * 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  3202:    */
1.218     brouard  3203:   int i, ii, j,k;
1.222     brouard  3204:   
                   3205:   double **out, **pmij();
                   3206:   double sumnew=0.;
1.218     brouard  3207:   double agefin;
1.292     brouard  3208:   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  3209:   double **dnewm, **dsavm, **doldm;
                   3210:   double **bbmij;
                   3211:   
1.218     brouard  3212:   doldm=ddoldms; /* global pointers */
1.222     brouard  3213:   dnewm=ddnewms;
                   3214:   dsavm=ddsavms;
1.318     brouard  3215: 
                   3216:   /* Debug */
                   3217:   /* printf("Bmij ij=%d, cov[2}=%f\n", ij, cov[2]); */
1.222     brouard  3218:   agefin=cov[2];
1.268     brouard  3219:   /* Bx = Diag(w_x) P_x Diag(Sum_i w^i_x p^ij_x */
1.222     brouard  3220:   /* bmij *//* age is cov[2], ij is included in cov, but we need for
1.266     brouard  3221:      the observed prevalence (with this covariate ij) at beginning of transition */
                   3222:   /* dsavm=pmij(pmmij,cov,ncovmodel,x,nlstate); */
1.268     brouard  3223: 
                   3224:   /* P_x */
1.325     brouard  3225:   pmmij=pmij(pmmij,cov,ncovmodel,x,nlstate); /*This is forward probability from agefin to agefin + stepm *//* Bug valgrind */
1.268     brouard  3226:   /* outputs pmmij which is a stochastic matrix in row */
                   3227: 
                   3228:   /* Diag(w_x) */
1.292     brouard  3229:   /* Rescaling the cross-sectional prevalence: Problem with prevacurrent which can be zero */
1.268     brouard  3230:   sumnew=0.;
1.269     brouard  3231:   /*for (ii=1;ii<=nlstate+ndeath;ii++){*/
1.268     brouard  3232:   for (ii=1;ii<=nlstate;ii++){ /* Only on live states */
1.297     brouard  3233:     /* printf(" agefin=%d, ii=%d, ij=%d, prev=%f\n",(int)agefin,ii, ij, prevacurrent[(int)agefin][ii][ij]); */
1.268     brouard  3234:     sumnew+=prevacurrent[(int)agefin][ii][ij];
                   3235:   }
                   3236:   if(sumnew >0.01){  /* At least some value in the prevalence */
                   3237:     for (ii=1;ii<=nlstate+ndeath;ii++){
                   3238:       for (j=1;j<=nlstate+ndeath;j++)
1.269     brouard  3239:        doldm[ii][j]=(ii==j ? prevacurrent[(int)agefin][ii][ij]/sumnew : 0.0);
1.268     brouard  3240:     }
                   3241:   }else{
                   3242:     for (ii=1;ii<=nlstate+ndeath;ii++){
                   3243:       for (j=1;j<=nlstate+ndeath;j++)
                   3244:       doldm[ii][j]=(ii==j ? 1./nlstate : 0.0);
                   3245:     }
                   3246:     /* if(sumnew <0.9){ */
                   3247:     /*   printf("Problem internal bmij B: sum on i wi <0.9: j=%d, sum_i wi=%lf,agefin=%d\n",j,sumnew, (int)agefin); */
                   3248:     /* } */
                   3249:   }
                   3250:   k3=0.0;  /* We put the last diagonal to 0 */
                   3251:   for (ii=nlstate+1;ii<=nlstate+ndeath;ii++){
                   3252:       doldm[ii][ii]= k3;
                   3253:   }
                   3254:   /* End doldm, At the end doldm is diag[(w_i)] */
                   3255:   
1.292     brouard  3256:   /* Left product of this diag matrix by pmmij=Px (dnewm=dsavm*doldm): diag[(w_i)*Px */
                   3257:   bbmij=matprod2(dnewm, doldm,1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, pmmij); /* was a Bug Valgrind */
1.268     brouard  3258: 
1.292     brouard  3259:   /* Diag(Sum_i w^i_x p^ij_x, should be the prevalence at age x+stepm */
1.268     brouard  3260:   /* 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  3261:   for (j=1;j<=nlstate+ndeath;j++){
1.268     brouard  3262:     sumnew=0.;
1.222     brouard  3263:     for (ii=1;ii<=nlstate;ii++){
1.266     brouard  3264:       /* sumnew+=dsavm[ii][j]*prevacurrent[(int)agefin][ii][ij]; */
1.268     brouard  3265:       sumnew+=pmmij[ii][j]*doldm[ii][ii]; /* Yes prevalence at beginning of transition */
1.222     brouard  3266:     } /* sumnew is (N11+N21)/N..= N.1/N.. = sum on i of w_i pij */
1.268     brouard  3267:     for (ii=1;ii<=nlstate+ndeath;ii++){
1.222     brouard  3268:        /* if(agefin >= agemaxpar && agefin <= agemaxpar+stepm/YEARM){ */
1.268     brouard  3269:        /*      dsavm[ii][j]=(ii==j ? 1./sumnew : 0.0); */
1.222     brouard  3270:        /* }else if(agefin >= agemaxpar+stepm/YEARM){ */
1.268     brouard  3271:        /*      dsavm[ii][j]=(ii==j ? 1./sumnew : 0.0); */
1.222     brouard  3272:        /* }else */
1.268     brouard  3273:       dsavm[ii][j]=(ii==j ? 1./sumnew : 0.0);
                   3274:     } /*End ii */
                   3275:   } /* 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 */
                   3276: 
1.292     brouard  3277:   ps=matprod2(ps, dnewm,1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, dsavm); /* was a Bug Valgrind */
1.268     brouard  3278:   /* ps is now diag[w_i] * Px * diag [1/(w_1p1i+w_2 p2i)] */
1.222     brouard  3279:   /* end bmij */
1.266     brouard  3280:   return ps; /*pointer is unchanged */
1.218     brouard  3281: }
1.217     brouard  3282: /*************** transition probabilities ***************/ 
                   3283: 
1.218     brouard  3284: double **bpmij(double **ps, double *cov, int ncovmodel, double *x, int nlstate )
1.217     brouard  3285: {
                   3286:   /* According to parameters values stored in x and the covariate's values stored in cov,
                   3287:      computes the probability to be observed in state j being in state i by appying the
                   3288:      model to the ncovmodel covariates (including constant and age).
                   3289:      lnpijopii=ln(pij/pii)= aij+bij*age+cij*v1+dij*v2+... = sum_nc=1^ncovmodel xij(nc)*cov[nc]
                   3290:      and, according on how parameters are entered, the position of the coefficient xij(nc) of the
                   3291:      ncth covariate in the global vector x is given by the formula:
                   3292:      j<i nc+((i-1)*(nlstate+ndeath-1)+j-1)*ncovmodel
                   3293:      j>=i nc + ((i-1)*(nlstate+ndeath-1)+(j-2))*ncovmodel
                   3294:      Computes ln(pij/pii) (lnpijopii), deduces pij/pii by exponentiation,
                   3295:      sums on j different of i to get 1-pii/pii, deduces pii, and then all pij.
                   3296:      Outputs ps[i][j] the probability to be observed in j being in j according to
                   3297:      the values of the covariates cov[nc] and corresponding parameter values x[nc+shiftij]
                   3298:   */
                   3299:   double s1, lnpijopii;
                   3300:   /*double t34;*/
                   3301:   int i,j, nc, ii, jj;
                   3302: 
1.234     brouard  3303:   for(i=1; i<= nlstate; i++){
                   3304:     for(j=1; j<i;j++){
                   3305:       for (nc=1, lnpijopii=0.;nc <=ncovmodel; nc++){
                   3306:        /*lnpijopii += param[i][j][nc]*cov[nc];*/
                   3307:        lnpijopii += x[nc+((i-1)*(nlstate+ndeath-1)+j-1)*ncovmodel]*cov[nc];
                   3308:        /*       printf("Int j<i s1=%.17e, lnpijopii=%.17e\n",s1,lnpijopii); */
                   3309:       }
                   3310:       ps[i][j]=lnpijopii; /* In fact ln(pij/pii) */
                   3311:       /*       printf("s1=%.17e, lnpijopii=%.17e\n",s1,lnpijopii); */
                   3312:     }
                   3313:     for(j=i+1; j<=nlstate+ndeath;j++){
                   3314:       for (nc=1, lnpijopii=0.;nc <=ncovmodel; nc++){
                   3315:        /*lnpijopii += x[(i-1)*nlstate*ncovmodel+(j-2)*ncovmodel+nc+(i-1)*(ndeath-1)*ncovmodel]*cov[nc];*/
                   3316:        lnpijopii += x[nc + ((i-1)*(nlstate+ndeath-1)+(j-2))*ncovmodel]*cov[nc];
                   3317:        /*        printf("Int j>i s1=%.17e, lnpijopii=%.17e %lx %lx\n",s1,lnpijopii,s1,lnpijopii); */
                   3318:       }
                   3319:       ps[i][j]=lnpijopii; /* In fact ln(pij/pii) */
                   3320:     }
                   3321:   }
                   3322:   
                   3323:   for(i=1; i<= nlstate; i++){
                   3324:     s1=0;
                   3325:     for(j=1; j<i; j++){
                   3326:       s1+=exp(ps[i][j]); /* In fact sums pij/pii */
                   3327:       /*printf("debug1 %d %d ps=%lf exp(ps)=%lf s1+=%lf\n",i,j,ps[i][j],exp(ps[i][j]),s1); */
                   3328:     }
                   3329:     for(j=i+1; j<=nlstate+ndeath; j++){
                   3330:       s1+=exp(ps[i][j]); /* In fact sums pij/pii */
                   3331:       /*printf("debug2 %d %d ps=%lf exp(ps)=%lf s1+=%lf\n",i,j,ps[i][j],exp(ps[i][j]),s1); */
                   3332:     }
                   3333:     /* s1= sum_{j<>i} pij/pii=(1-pii)/pii and thus pii is known from s1 */
                   3334:     ps[i][i]=1./(s1+1.);
                   3335:     /* Computing other pijs */
                   3336:     for(j=1; j<i; j++)
                   3337:       ps[i][j]= exp(ps[i][j])*ps[i][i];
                   3338:     for(j=i+1; j<=nlstate+ndeath; j++)
                   3339:       ps[i][j]= exp(ps[i][j])*ps[i][i];
                   3340:     /* ps[i][nlstate+1]=1.-s1- ps[i][i];*/ /* Sum should be 1 */
                   3341:   } /* end i */
                   3342:   
                   3343:   for(ii=nlstate+1; ii<= nlstate+ndeath; ii++){
                   3344:     for(jj=1; jj<= nlstate+ndeath; jj++){
                   3345:       ps[ii][jj]=0;
                   3346:       ps[ii][ii]=1;
                   3347:     }
                   3348:   }
1.296     brouard  3349:   /* Added for prevbcast */ /* Transposed matrix too */
1.234     brouard  3350:   for(jj=1; jj<= nlstate+ndeath; jj++){
                   3351:     s1=0.;
                   3352:     for(ii=1; ii<= nlstate+ndeath; ii++){
                   3353:       s1+=ps[ii][jj];
                   3354:     }
                   3355:     for(ii=1; ii<= nlstate; ii++){
                   3356:       ps[ii][jj]=ps[ii][jj]/s1;
                   3357:     }
                   3358:   }
                   3359:   /* Transposition */
                   3360:   for(jj=1; jj<= nlstate+ndeath; jj++){
                   3361:     for(ii=jj; ii<= nlstate+ndeath; ii++){
                   3362:       s1=ps[ii][jj];
                   3363:       ps[ii][jj]=ps[jj][ii];
                   3364:       ps[jj][ii]=s1;
                   3365:     }
                   3366:   }
                   3367:   /* for(ii=1; ii<= nlstate+ndeath; ii++){ */
                   3368:   /*   for(jj=1; jj<= nlstate+ndeath; jj++){ */
                   3369:   /*   printf(" pmij  ps[%d][%d]=%lf ",ii,jj,ps[ii][jj]); */
                   3370:   /*   } */
                   3371:   /*   printf("\n "); */
                   3372:   /* } */
                   3373:   /* printf("\n ");printf("%lf ",cov[2]);*/
                   3374:   /*
                   3375:     for(i=1; i<= npar; i++) printf("%f ",x[i]);
                   3376:     goto end;*/
                   3377:   return ps;
1.217     brouard  3378: }
                   3379: 
                   3380: 
1.126     brouard  3381: /**************** Product of 2 matrices ******************/
                   3382: 
1.145     brouard  3383: double **matprod2(double **out, double **in,int nrl, int nrh, int ncl, int nch, int ncolol, int ncoloh, double **b)
1.126     brouard  3384: {
                   3385:   /* Computes the matrix product of in(1,nrh-nrl+1)(1,nch-ncl+1) times
                   3386:      b(1,nch-ncl+1)(1,ncoloh-ncolol+1) into out(...) */
                   3387:   /* in, b, out are matrice of pointers which should have been initialized 
                   3388:      before: only the contents of out is modified. The function returns
                   3389:      a pointer to pointers identical to out */
1.145     brouard  3390:   int i, j, k;
1.126     brouard  3391:   for(i=nrl; i<= nrh; i++)
1.145     brouard  3392:     for(k=ncolol; k<=ncoloh; k++){
                   3393:       out[i][k]=0.;
                   3394:       for(j=ncl; j<=nch; j++)
                   3395:        out[i][k] +=in[i][j]*b[j][k];
                   3396:     }
1.126     brouard  3397:   return out;
                   3398: }
                   3399: 
                   3400: 
                   3401: /************* Higher Matrix Product ***************/
                   3402: 
1.235     brouard  3403: 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  3404: {
1.218     brouard  3405:   /* Computes the transition matrix starting at age 'age' and combination of covariate values corresponding to ij over 
1.126     brouard  3406:      'nhstepm*hstepm*stepm' months (i.e. until
                   3407:      age (in years)  age+nhstepm*hstepm*stepm/12) by multiplying 
                   3408:      nhstepm*hstepm matrices. 
                   3409:      Output is stored in matrix po[i][j][h] for h every 'hstepm' step 
                   3410:      (typically every 2 years instead of every month which is too big 
                   3411:      for the memory).
                   3412:      Model is determined by parameters x and covariates have to be 
                   3413:      included manually here. 
                   3414: 
                   3415:      */
                   3416: 
1.330   ! brouard  3417:   int i, j, d, h, k, k1;
1.131     brouard  3418:   double **out, cov[NCOVMAX+1];
1.126     brouard  3419:   double **newm;
1.187     brouard  3420:   double agexact;
1.214     brouard  3421:   double agebegin, ageend;
1.126     brouard  3422: 
                   3423:   /* Hstepm could be zero and should return the unit matrix */
                   3424:   for (i=1;i<=nlstate+ndeath;i++)
                   3425:     for (j=1;j<=nlstate+ndeath;j++){
                   3426:       oldm[i][j]=(i==j ? 1.0 : 0.0);
                   3427:       po[i][j][0]=(i==j ? 1.0 : 0.0);
                   3428:     }
                   3429:   /* Even if hstepm = 1, at least one multiplication by the unit matrix */
                   3430:   for(h=1; h <=nhstepm; h++){
                   3431:     for(d=1; d <=hstepm; d++){
                   3432:       newm=savm;
                   3433:       /* Covariates have to be included here again */
                   3434:       cov[1]=1.;
1.214     brouard  3435:       agexact=age+((h-1)*hstepm + (d-1))*stepm/YEARM; /* age just before transition */
1.187     brouard  3436:       cov[2]=agexact;
1.319     brouard  3437:       if(nagesqr==1){
1.227     brouard  3438:        cov[3]= agexact*agexact;
1.319     brouard  3439:       }
1.330   ! brouard  3440:       /* Model(2)  V1 + V2 + V3 + V8 + V7*V8 + V5*V6 + V8*age + V3*age + age*age */
        !          3441:       /* total number of covariates of the model nbocc(+)+1 = 8 excepting constant and age and age*age */
        !          3442:       for(k1=1;k1<=cptcovt;k1++){ /* loop on model equation (including products) */ 
        !          3443:        if( Dummy[k1]==0 && Typevar[k1]==0 ){ /* Single dummy  */
        !          3444: /*        V(Tvarsel)=Tvalsel=Tresult[nres][pos](value); V(Tvresult[nres][pos] (variable): V(variable)=value) */
        !          3445: /*       for (k=1; k<=nsd;k++) { /\* For single dummy covariates only *\/ */
        !          3446: /* /\* Here comes the value of the covariate 'ij' after renumbering k with single dummy covariates *\/ */
1.319     brouard  3447:        /* codtabm(ij,k)  (1 & (ij-1) >> (k-1))+1 */
                   3448: /*             V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
                   3449: /*    k        1  2   3   4     5    6    7     8    9 */
                   3450: /*Tvar[k]=     5  4   3   6     5    2    7     1    1 */
                   3451: /*    nsd         1   2                              3 */ /* Counting single dummies covar fixed or tv */
                   3452: /*TvarsD[nsd]     4   3                              1 */ /* ID of single dummy cova fixed or timevary*/
                   3453: /*TvarsDind[k]    2   3                              9 */ /* position K of single dummy cova */
1.330   ! brouard  3454:          /* cov[2+nagesqr+TvarsDind[k]]=nbcode[TvarsD[k]][codtabm(ij,k)];or [codtabm(ij,TnsdVar[TvarsD[k]] */
        !          3455:          cov[2+nagesqr+k1]=Tresult[nres][resultmodel[nres][k1]];
        !          3456:          /* printf("hpxij Dummy combi=%d k=%d TvarsD[%d]=V%d TvarsDind[%d]=%d nbcode=%d cov=%lf codtabm(%d,TnsdVar[TvarsD[%d])=%d \n",ij,k, k, TvarsD[k],k,TvarsDind[k],nbcode[TvarsD[k]][codtabm(ij,TnsdVar[TvarsD[k]])],cov[2+nagesqr+TvarsDind[k]], ij, k, codtabm(ij,TnsdVar[TvarsD[k]])); */
        !          3457:          printf("hpxij Dummy combi=%d k1=%d Tvar[%d]=V%d cov[2+%d+%d]=%lf resultmodel[nres][%d]=%d nres/nresult=%d/%d \n",ij,k1,k1, Tvar[k1],nagesqr,k1,cov[2+nagesqr+k1],k1,resultmodel[nres][k1],nres,nresult);
        !          3458:        }else if( Dummy[k1]==1 && Typevar[k1]==0 ){ /* Single quantitative variables  */
        !          3459:          /* resultmodel[nres][k1]=k3: k1th position in the model correspond to the k3 position in the resultline */
        !          3460:          cov[2+nagesqr+k1]=Tqresult[nres][resultmodel[nres][k1]]; 
        !          3461:          /* for (k=1; k<=nsq;k++) { /\* For single varying covariates only *\/ */
        !          3462:          /*    /\* Here comes the value of quantitative after renumbering k with single quantitative covariates *\/ */
        !          3463:          /*    cov[2+nagesqr+TvarsQind[k]]=Tqresult[nres][k]; */
        !          3464:          printf("hPxij Quantitative k1=%d resultmodel[nres][%d]=%d,Tqresult[%d][%d]=%f\n",k1,k1,resultmodel[nres][k1],nres,resultmodel[nres][k1],Tqresult[nres][resultmodel[nres][k1]]);
        !          3465:        }else if( Dummy[k1]==2 ){ /* For dummy with age product */
        !          3466:          /* Tvar[k1] Variable in the age product age*V1 is 1 */
        !          3467:          /* [Tinvresult[nres][V1] is its value in the resultline nres */
        !          3468:          cov[2+nagesqr+k1]=Tinvresult[nres][Tvar[k1]];
        !          3469:          printf("DhPxij Dummy with age k1=%d Tvar[%d]=%d Tinvresult[nres][%d]=%d,cov[2+%d+%d]=%.3f\n",k1,k1,Tvar[k1],Tinvresult[nres][Tvar[k1]],nagesqr,k1,cov[2+nagesqr+k1]);
        !          3470:          /* cov[2+nagesqr+k1]=Tresult[nres][resultmodel[nres][k1]];     */
        !          3471:          /* for (k=1; k<=cptcovage;k++){ /\* For product with age V1+V1*age +V4 +age*V3 *\/ */
        !          3472:          /* 1+2 Tage[1]=2 TVar[2]=1 Dummy[2]=2, Tage[2]=4 TVar[4]=3 Dummy[4]=3 quant*/
        !          3473:          /* */
        !          3474: /*             V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
        !          3475: /*    k        1  2   3   4     5    6    7     8    9 */
        !          3476: /*Tvar[k]=     5  4   3   6     5    2    7     1    1 */
        !          3477: /*cptcovage=2                   1               2      */
        !          3478: /*Tage[k]=                      5               8      */      
        !          3479:        }else if( Dummy[k1]==2 ){ /* For quant with age product */
        !          3480:          cov[2+nagesqr+k1]=Tresult[nres][resultmodel[nres][k1]];       
        !          3481:          printf("QhPxij Quant with age k1=%d resultmodel[nres][%d]=%d,Tqresult[%d][%d]=%f\n",k1,k1,resultmodel[nres][k1],nres,resultmodel[nres][k1],Tqresult[nres][resultmodel[nres][k1]]);
        !          3482:          /* if(Dummy[Tage[k]]== 2){ /\* dummy with age *\/ */
        !          3483:          /* /\* if(Dummy[Tvar[Tage[k]]]== 2){ /\\* dummy with age *\\/ *\/ */
        !          3484:          /*   /\* cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,k)]*cov[2]; *\/ */
        !          3485:          /*   /\* cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,TnsdVar[TvarsD[Tvar[Tage[k]]]])]*cov[2]; *\/ */
        !          3486:          /*   cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,TnsdVar[TvarsD[Tvar[Tage[k]]]])]*cov[2]; */
        !          3487:          /*   printf("hPxij Age combi=%d k=%d cptcovage=%d Tage[%d]=%d Tvar[Tage[%d]]=V%d nbcode[Tvar[Tage[k]]][codtabm(ij,TnsdVar[Tvar[Tage[k]]]])]=%d nres=%d\n",ij,k,cptcovage,k,Tage[k],k,Tvar[Tage[k]], nbcode[Tvar[Tage[k]]][codtabm(ij,TnsdVar[Tvar[Tage[k]]])],nres); */
        !          3488:          /* } else if(Dummy[Tage[k]]== 3){ /\* quantitative with age *\/ */
        !          3489:          /*   cov[2+nagesqr+Tage[k]]=Tqresult[nres][k]; */
        !          3490:          /* } */
        !          3491:          /* 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]); */
        !          3492:        }else if(Typevar[k1]==2 ){ /* For product (not with age) */
        !          3493: /*       for (k=1; k<=cptcovprod;k++){ /\*  For product without age *\/ */
        !          3494: /* /\*             V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 *\/ */
        !          3495: /* /\*    k        1  2   3   4     5    6    7     8    9 *\/ */
        !          3496: /* /\*Tvar[k]=     5  4   3   6     5    2    7     1    1 *\/ */
        !          3497: /* /\*cptcovprod=1            1               2            *\/ */
        !          3498: /* /\*Tprod[]=                4               7            *\/ */
        !          3499: /* /\*Tvard[][1]             4               1             *\/ */
        !          3500: /* /\*Tvard[][2]               3               2           *\/ */
        !          3501:          
        !          3502:          /* printf("hPxij Prod ij=%d k=%d  Tprod[%d]=%d Tvard[%d][1]=V%d, Tvard[%d][2]=V%d nbcode[Tvard[k][1]][codtabm(ij,Tvard[k][1])]=%d nbcode[Tvard[k][2]][codtabm(ij,Tvard[k][1])]=%d\n",ij,k,k,Tprod[k], k,Tvard[k][1], k,Tvard[k][2],nbcode[Tvard[k][1]][codtabm(ij,Tvard[k][1])],nbcode[Tvard[k][2]][codtabm(ij,Tvard[k][2])]); */
        !          3503:          /* cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)] * nbcode[Tvard[k][2]][codtabm(ij,k)]; */
        !          3504:          cov[2+nagesqr+k1]=TinvDoQresult[nres][Tvardk[k1][1]] * TinvDoQresult[nres][Tvardk[k1][2]];    
        !          3505:          printf("hPxij Prod ij=%d k1=%d  cov[2+%d+%d]=%.5f Tvard[%d][1]=V%d * Tvard[%d][2]=V%d ; TinvDoQresult[nres][Tvardk[k1][1]]=%.4f * TinvDoQresult[nres][Tvardk[k1][1]]=%.4f\n",ij,k1,nagesqr,k1,cov[2+nagesqr+k1],k1,Tvard[k1][1], k1,Tvard[k1][2], TinvDoQresult[nres][Tvardk[k1][1]], TinvDoQresult[nres][Tvardk[k1][2]]);
        !          3506:          /* if(Dummy[Tvardk[k1][1]]==0){ */
        !          3507:          /*   if(Dummy[Tvardk[k1][2]]==0){ /\* Product of dummies *\/ */
        !          3508:              /* cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)] * nbcode[Tvard[k][2]][codtabm(ij,k)]; */
        !          3509:              /* cov[2+nagesqr+k1]=Tinvresult[nres][Tvardk[k1][1]] * Tinvresult[nres][Tvardk[k1][2]];    */
        !          3510:              /* cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,TnsdVar[Tvard[k][1]])] * nbcode[Tvard[k][2]][codtabm(ij,TnsdVar[Tvard[k][2]])]; */
        !          3511:            /* }else{ /\* Product of dummy by quantitative *\/ */
        !          3512:              /* cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,TnsdVar[Tvard[k][1]])] * Tqresult[nres][k]; */
        !          3513:              /* cov[2+nagesqr+k1]=Tresult[nres][Tinvresult[nres][Tvardk[k1][1]]] * Tqresult[nres][Tinvresult[nres][Tvardk[k1][2]]]; */
        !          3514:          /*   } */
        !          3515:          /* }else{ /\* Product of quantitative by...*\/ */
        !          3516:          /*   if(Dummy[Tvard[k][2]]==0){  /\* quant by dummy *\/ */
        !          3517:          /*     /\* cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][2]][codtabm(ij,TnsdVar[Tvard[k][2]])] * Tqinvresult[nres][Tvard[k][1]]; *\/ */
        !          3518:          /*     cov[2+nagesqr+k1]=Tqresult[nres][Tinvresult[nres][Tvardk[k1][1]]] * Tresult[nres][Tinvresult[nres][Tvardk[k1][2]]]  ; */
        !          3519:          /*   }else{ /\* Product of two quant *\/ */
        !          3520:          /*     /\* cov[2+nagesqr+Tprod[k]]=Tqinvresult[nres][Tvard[k][1]]*  Tqinvresult[nres][Tvard[k][2]]; *\/ */
        !          3521:          /*     cov[2+nagesqr+k1]=Tqresult[nres][Tinvresult[nres][Tvardk[k1][1]]] * Tqresult[nres][Tinvresult[nres][Tvardk[k1][2]]]  ; */
        !          3522:          /*   } */
        !          3523:          /* }/\*end of products quantitative *\/ */
        !          3524:        }/*end of products */
        !          3525:       } /* End of loop on model equation */
1.235     brouard  3526:       /* for (k=1; k<=cptcovn;k++)  */
                   3527:       /*       cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,k)]; */
                   3528:       /* for (k=1; k<=cptcovage;k++) /\* Should start at cptcovn+1 *\/ */
                   3529:       /*       cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,k)]*cov[2]; */
                   3530:       /* for (k=1; k<=cptcovprod;k++) /\* Useless because included in cptcovn *\/ */
                   3531:       /*       cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)]*nbcode[Tvard[k][2]][codtabm(ij,k)]; */
1.227     brouard  3532:       
                   3533:       
1.126     brouard  3534:       /*printf("hxi cptcov=%d cptcode=%d\n",cptcov,cptcode);*/
                   3535:       /*printf("h=%d d=%d age=%f cov=%f\n",h,d,age,cov[2]);*/
1.319     brouard  3536:       /* right multiplication of oldm by the current matrix */
1.126     brouard  3537:       out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, 
                   3538:                   pmij(pmmij,cov,ncovmodel,x,nlstate));
1.217     brouard  3539:       /* if((int)age == 70){ */
                   3540:       /*       printf(" Forward hpxij age=%d agexact=%f d=%d nhstepm=%d hstepm=%d\n", (int) age, agexact, d, nhstepm, hstepm); */
                   3541:       /*       for(i=1; i<=nlstate+ndeath; i++) { */
                   3542:       /*         printf("%d pmmij ",i); */
                   3543:       /*         for(j=1;j<=nlstate+ndeath;j++) { */
                   3544:       /*           printf("%f ",pmmij[i][j]); */
                   3545:       /*         } */
                   3546:       /*         printf(" oldm "); */
                   3547:       /*         for(j=1;j<=nlstate+ndeath;j++) { */
                   3548:       /*           printf("%f ",oldm[i][j]); */
                   3549:       /*         } */
                   3550:       /*         printf("\n"); */
                   3551:       /*       } */
                   3552:       /* } */
1.126     brouard  3553:       savm=oldm;
                   3554:       oldm=newm;
                   3555:     }
                   3556:     for(i=1; i<=nlstate+ndeath; i++)
                   3557:       for(j=1;j<=nlstate+ndeath;j++) {
1.267     brouard  3558:        po[i][j][h]=newm[i][j];
                   3559:        /*if(h==nhstepm) printf("po[%d][%d][%d]=%f ",i,j,h,po[i][j][h]);*/
1.126     brouard  3560:       }
1.128     brouard  3561:     /*printf("h=%d ",h);*/
1.126     brouard  3562:   } /* end h */
1.267     brouard  3563:   /*     printf("\n H=%d \n",h); */
1.126     brouard  3564:   return po;
                   3565: }
                   3566: 
1.217     brouard  3567: /************* Higher Back Matrix Product ***************/
1.218     brouard  3568: /* 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  3569: 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  3570: {
1.266     brouard  3571:   /* For a combination of dummy covariate ij, computes the transition matrix starting at age 'age' over
1.217     brouard  3572:      'nhstepm*hstepm*stepm' months (i.e. until
1.218     brouard  3573:      age (in years)  age+nhstepm*hstepm*stepm/12) by multiplying
                   3574:      nhstepm*hstepm matrices.
                   3575:      Output is stored in matrix po[i][j][h] for h every 'hstepm' step
                   3576:      (typically every 2 years instead of every month which is too big
1.217     brouard  3577:      for the memory).
1.218     brouard  3578:      Model is determined by parameters x and covariates have to be
1.266     brouard  3579:      included manually here. Then we use a call to bmij(x and cov)
                   3580:      The addresss of po (p3mat allocated to the dimension of nhstepm) should be stored for output
1.222     brouard  3581:   */
1.217     brouard  3582: 
                   3583:   int i, j, d, h, k;
1.266     brouard  3584:   double **out, cov[NCOVMAX+1], **bmij();
                   3585:   double **newm, ***newmm;
1.217     brouard  3586:   double agexact;
                   3587:   double agebegin, ageend;
1.222     brouard  3588:   double **oldm, **savm;
1.217     brouard  3589: 
1.266     brouard  3590:   newmm=po; /* To be saved */
                   3591:   oldm=oldms;savm=savms; /* Global pointers */
1.217     brouard  3592:   /* Hstepm could be zero and should return the unit matrix */
                   3593:   for (i=1;i<=nlstate+ndeath;i++)
                   3594:     for (j=1;j<=nlstate+ndeath;j++){
                   3595:       oldm[i][j]=(i==j ? 1.0 : 0.0);
                   3596:       po[i][j][0]=(i==j ? 1.0 : 0.0);
                   3597:     }
                   3598:   /* Even if hstepm = 1, at least one multiplication by the unit matrix */
                   3599:   for(h=1; h <=nhstepm; h++){
                   3600:     for(d=1; d <=hstepm; d++){
                   3601:       newm=savm;
                   3602:       /* Covariates have to be included here again */
                   3603:       cov[1]=1.;
1.271     brouard  3604:       agexact=age-( (h-1)*hstepm + (d)  )*stepm/YEARM; /* age just before transition, d or d-1? */
1.217     brouard  3605:       /* agexact=age+((h-1)*hstepm + (d-1))*stepm/YEARM; /\* age just before transition *\/ */
1.318     brouard  3606:         /* Debug */
                   3607:       /* printf("hBxij age=%lf, agexact=%lf\n", age, agexact); */
1.217     brouard  3608:       cov[2]=agexact;
                   3609:       if(nagesqr==1)
1.222     brouard  3610:        cov[3]= agexact*agexact;
1.325     brouard  3611:       for (k=1; k<=nsd;k++){ /* For single dummy covariates only *//* cptcovn error */
1.266     brouard  3612:       /*       cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,k)]; */
                   3613:       /* /\* cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,Tvar[k])]; *\/ */
1.330   ! brouard  3614:        cov[2+nagesqr+TvarsDind[k]]=nbcode[TvarsD[k]][codtabm(ij,TvarsD[k])];/* Bug valgrind */
1.266     brouard  3615:         /* 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)); */
                   3616:       }
1.267     brouard  3617:       for (k=1; k<=nsq;k++) { /* For single varying covariates only */
                   3618:        /* Here comes the value of quantitative after renumbering k with single quantitative covariates */
                   3619:        cov[2+nagesqr+TvarsQind[k]]=Tqresult[nres][k]; 
                   3620:        /* 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]); */
                   3621:       }
1.319     brouard  3622:       for (k=1; k<=cptcovage;k++){ /* Should start at cptcovn+1 *//* For product with age */
                   3623:        /* if(Dummy[Tvar[Tage[k]]]== 2){ /\* dummy with age error!!!*\/ */
                   3624:        if(Dummy[Tage[k]]== 2){ /* dummy with age */
1.330   ! brouard  3625:          cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,Tvar[Tage[k]])]*cov[2];
1.319     brouard  3626:        } else if(Dummy[Tage[k]]== 3){ /* quantitative with age */
1.267     brouard  3627:          cov[2+nagesqr+Tage[k]]=Tqresult[nres][k]; 
                   3628:        }
                   3629:        /* 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]); */
                   3630:       }
                   3631:       for (k=1; k<=cptcovprod;k++){ /* Useless because included in cptcovn */
1.330   ! brouard  3632:        cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,Tvard[k][1])]*nbcode[Tvard[k][2]][codtabm(ij,Tvard[k][2])];
1.329     brouard  3633:        if(Dummy[Tvard[k][1]]==0){
                   3634:          if(Dummy[Tvard[k][2]]==0){
1.330   ! brouard  3635:            cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,Tvard[k][1])] * nbcode[Tvard[k][2]][codtabm(ij,Tvard[k][1])];
1.325     brouard  3636:          }else{
1.330   ! brouard  3637:            cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,Tvard[k][1])] * Tqresult[nres][k];
1.325     brouard  3638:          }
                   3639:        }else{
1.329     brouard  3640:          if(Dummy[Tvard[k][2]]==0){
1.330   ! brouard  3641:            cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][2]][codtabm(ij,Tvard[k][2])] * Tqinvresult[nres][Tvard[k][1]];
1.325     brouard  3642:          }else{
                   3643:            cov[2+nagesqr+Tprod[k]]=Tqinvresult[nres][Tvard[k][1]]*  Tqinvresult[nres][Tvard[k][2]];
                   3644:          }
                   3645:        }
1.267     brouard  3646:       }                        
1.217     brouard  3647:       /*printf("hxi cptcov=%d cptcode=%d\n",cptcov,cptcode);*/
                   3648:       /*printf("h=%d d=%d age=%f cov=%f\n",h,d,age,cov[2]);*/
1.267     brouard  3649: 
1.218     brouard  3650:       /* Careful transposed matrix */
1.266     brouard  3651:       /* age is in cov[2], prevacurrent at beginning of transition. */
1.218     brouard  3652:       /* out=matprod2(newm, bmij(pmmij,cov,ncovmodel,x,nlstate,prevacurrent, dnewm, doldm, dsavm,ij),\ */
1.222     brouard  3653:       /*                                                1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm); */
1.218     brouard  3654:       out=matprod2(newm, bmij(pmmij,cov,ncovmodel,x,nlstate,prevacurrent,ij),\
1.325     brouard  3655:                   1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm);/* Bug valgrind */
1.217     brouard  3656:       /* if((int)age == 70){ */
                   3657:       /*       printf(" Backward hbxij age=%d agexact=%f d=%d nhstepm=%d hstepm=%d\n", (int) age, agexact, d, nhstepm, hstepm); */
                   3658:       /*       for(i=1; i<=nlstate+ndeath; i++) { */
                   3659:       /*         printf("%d pmmij ",i); */
                   3660:       /*         for(j=1;j<=nlstate+ndeath;j++) { */
                   3661:       /*           printf("%f ",pmmij[i][j]); */
                   3662:       /*         } */
                   3663:       /*         printf(" oldm "); */
                   3664:       /*         for(j=1;j<=nlstate+ndeath;j++) { */
                   3665:       /*           printf("%f ",oldm[i][j]); */
                   3666:       /*         } */
                   3667:       /*         printf("\n"); */
                   3668:       /*       } */
                   3669:       /* } */
                   3670:       savm=oldm;
                   3671:       oldm=newm;
                   3672:     }
                   3673:     for(i=1; i<=nlstate+ndeath; i++)
                   3674:       for(j=1;j<=nlstate+ndeath;j++) {
1.222     brouard  3675:        po[i][j][h]=newm[i][j];
1.268     brouard  3676:        /* if(h==nhstepm) */
                   3677:        /*   printf("po[%d][%d][%d]=%f ",i,j,h,po[i][j][h]); */
1.217     brouard  3678:       }
1.268     brouard  3679:     /* printf("h=%d %.1f ",h, agexact); */
1.217     brouard  3680:   } /* end h */
1.268     brouard  3681:   /* printf("\n H=%d nhs=%d \n",h, nhstepm); */
1.217     brouard  3682:   return po;
                   3683: }
                   3684: 
                   3685: 
1.162     brouard  3686: #ifdef NLOPT
                   3687:   double  myfunc(unsigned n, const double *p1, double *grad, void *pd){
                   3688:   double fret;
                   3689:   double *xt;
                   3690:   int j;
                   3691:   myfunc_data *d2 = (myfunc_data *) pd;
                   3692: /* xt = (p1-1); */
                   3693:   xt=vector(1,n); 
                   3694:   for (j=1;j<=n;j++)   xt[j]=p1[j-1]; /* xt[1]=p1[0] */
                   3695: 
                   3696:   fret=(d2->function)(xt); /*  p xt[1]@8 is fine */
                   3697:   /* fret=(*func)(xt); /\*  p xt[1]@8 is fine *\/ */
                   3698:   printf("Function = %.12lf ",fret);
                   3699:   for (j=1;j<=n;j++) printf(" %d %.8lf", j, xt[j]); 
                   3700:   printf("\n");
                   3701:  free_vector(xt,1,n);
                   3702:   return fret;
                   3703: }
                   3704: #endif
1.126     brouard  3705: 
                   3706: /*************** log-likelihood *************/
                   3707: double func( double *x)
                   3708: {
1.226     brouard  3709:   int i, ii, j, k, mi, d, kk;
                   3710:   int ioffset=0;
                   3711:   double l, ll[NLSTATEMAX+1], cov[NCOVMAX+1];
                   3712:   double **out;
                   3713:   double lli; /* Individual log likelihood */
                   3714:   int s1, s2;
1.228     brouard  3715:   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  3716:   double bbh, survp;
                   3717:   long ipmx;
                   3718:   double agexact;
                   3719:   /*extern weight */
                   3720:   /* We are differentiating ll according to initial status */
                   3721:   /*  for (i=1;i<=npar;i++) printf("%f ", x[i]);*/
                   3722:   /*for(i=1;i<imx;i++) 
                   3723:     printf(" %d\n",s[4][i]);
                   3724:   */
1.162     brouard  3725: 
1.226     brouard  3726:   ++countcallfunc;
1.162     brouard  3727: 
1.226     brouard  3728:   cov[1]=1.;
1.126     brouard  3729: 
1.226     brouard  3730:   for(k=1; k<=nlstate; k++) ll[k]=0.;
1.224     brouard  3731:   ioffset=0;
1.226     brouard  3732:   if(mle==1){
                   3733:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
                   3734:       /* Computes the values of the ncovmodel covariates of the model
                   3735:         depending if the covariates are fixed or varying (age dependent) and stores them in cov[]
                   3736:         Then computes with function pmij which return a matrix p[i][j] giving the elementary probability
                   3737:         to be observed in j being in i according to the model.
                   3738:       */
1.243     brouard  3739:       ioffset=2+nagesqr ;
1.233     brouard  3740:    /* Fixed */
1.319     brouard  3741:       for (k=1; k<=ncovf;k++){ /* For each fixed covariate dummu or quant or prod */
                   3742:        /* # V1=sex, V2=raedyrs Quant Fixed, State=livarnb4..livarnb11, V3=iadl4..iald11, V4=adlw4..adlw11, V5=r4bmi..r11bmi */
                   3743:         /*             V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
                   3744:        /*  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  3745:         /* TvarFind;  TvarFind[1]=6,  TvarFind[2]=7, TvarFind[3]=9 *//* Inverse V2(6) is first fixed (single or prod)  */
1.319     brouard  3746:        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)*/
                   3747:        /* V1*V2 (7)  TvarFind[2]=7, TvarFind[3]=9 */
1.234     brouard  3748:       }
1.226     brouard  3749:       /* In model V2+V1*V4+age*V3+V3*V2 Tvar[1] is V2, Tvar[2=V1*V4] 
1.319     brouard  3750:         is 5, Tvar[3=age*V3] should not be computed because of age Tvar[4=V3*V2]=6 
1.226     brouard  3751:         has been calculated etc */
                   3752:       /* For an individual i, wav[i] gives the number of effective waves */
                   3753:       /* We compute the contribution to Likelihood of each effective transition
                   3754:         mw[mi][i] is real wave of the mi th effectve wave */
                   3755:       /* Then statuses are computed at each begin and end of an effective wave s1=s[ mw[mi][i] ][i];
                   3756:         s2=s[mw[mi+1][i]][i];
                   3757:         And the iv th varying covariate is the cotvar[mw[mi+1][i]][iv][i]
                   3758:         But if the variable is not in the model TTvar[iv] is the real variable effective in the model:
                   3759:         meaning that decodemodel should be used cotvar[mw[mi+1][i]][TTvar[iv]][i]
                   3760:       */
                   3761:       for(mi=1; mi<= wav[i]-1; mi++){
1.319     brouard  3762:        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*/
                   3763:          /* cov[ioffset+TvarVind[k]]=cotvar[mw[mi][i]][Tvar[TvarVind[k]]][i]; but where is the crossproduct? */
1.242     brouard  3764:          cov[ioffset+TvarVind[k]]=cotvar[mw[mi][i]][Tvar[TvarVind[k]]-ncovcol-nqv][i];
1.234     brouard  3765:        }
                   3766:        for (ii=1;ii<=nlstate+ndeath;ii++)
                   3767:          for (j=1;j<=nlstate+ndeath;j++){
                   3768:            oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   3769:            savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   3770:          }
                   3771:        for(d=0; d<dh[mi][i]; d++){
                   3772:          newm=savm;
                   3773:          agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
                   3774:          cov[2]=agexact;
                   3775:          if(nagesqr==1)
                   3776:            cov[3]= agexact*agexact;  /* Should be changed here */
                   3777:          for (kk=1; kk<=cptcovage;kk++) {
1.318     brouard  3778:            if(!FixedV[Tvar[Tage[kk]]])
                   3779:              cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact; /* Tage[kk] gives the data-covariate associated with age */
                   3780:            else
                   3781:              cov[Tage[kk]+2+nagesqr]=cotvar[mw[mi][i]][Tvar[Tage[kk]]-ncovcol-nqv][i]*agexact;
1.234     brouard  3782:          }
                   3783:          out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   3784:                       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   3785:          savm=oldm;
                   3786:          oldm=newm;
                   3787:        } /* end mult */
                   3788:        
                   3789:        /*lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]);*/ /* Original formula */
                   3790:        /* But now since version 0.9 we anticipate for bias at large stepm.
                   3791:         * If stepm is larger than one month (smallest stepm) and if the exact delay 
                   3792:         * (in months) between two waves is not a multiple of stepm, we rounded to 
                   3793:         * the nearest (and in case of equal distance, to the lowest) interval but now
                   3794:         * we keep into memory the bias bh[mi][i] and also the previous matrix product
                   3795:         * (i.e to dh[mi][i]-1) saved in 'savm'. Then we inter(extra)polate the
                   3796:         * probability in order to take into account the bias as a fraction of the way
1.231     brouard  3797:                                 * from savm to out if bh is negative or even beyond if bh is positive. bh varies
                   3798:                                 * -stepm/2 to stepm/2 .
                   3799:                                 * For stepm=1 the results are the same as for previous versions of Imach.
                   3800:                                 * For stepm > 1 the results are less biased than in previous versions. 
                   3801:                                 */
1.234     brouard  3802:        s1=s[mw[mi][i]][i];
                   3803:        s2=s[mw[mi+1][i]][i];
                   3804:        bbh=(double)bh[mi][i]/(double)stepm; 
                   3805:        /* bias bh is positive if real duration
                   3806:         * is higher than the multiple of stepm and negative otherwise.
                   3807:         */
                   3808:        /* lli= (savm[s1][s2]>1.e-8 ?(1.+bbh)*log(out[s1][s2])- bbh*log(savm[s1][s2]):log((1.+bbh)*out[s1][s2]));*/
                   3809:        if( s2 > nlstate){ 
                   3810:          /* i.e. if s2 is a death state and if the date of death is known 
                   3811:             then the contribution to the likelihood is the probability to 
                   3812:             die between last step unit time and current  step unit time, 
                   3813:             which is also equal to probability to die before dh 
                   3814:             minus probability to die before dh-stepm . 
                   3815:             In version up to 0.92 likelihood was computed
                   3816:             as if date of death was unknown. Death was treated as any other
                   3817:             health state: the date of the interview describes the actual state
                   3818:             and not the date of a change in health state. The former idea was
                   3819:             to consider that at each interview the state was recorded
                   3820:             (healthy, disable or death) and IMaCh was corrected; but when we
                   3821:             introduced the exact date of death then we should have modified
                   3822:             the contribution of an exact death to the likelihood. This new
                   3823:             contribution is smaller and very dependent of the step unit
                   3824:             stepm. It is no more the probability to die between last interview
                   3825:             and month of death but the probability to survive from last
                   3826:             interview up to one month before death multiplied by the
                   3827:             probability to die within a month. Thanks to Chris
                   3828:             Jackson for correcting this bug.  Former versions increased
                   3829:             mortality artificially. The bad side is that we add another loop
                   3830:             which slows down the processing. The difference can be up to 10%
                   3831:             lower mortality.
                   3832:          */
                   3833:          /* If, at the beginning of the maximization mostly, the
                   3834:             cumulative probability or probability to be dead is
                   3835:             constant (ie = 1) over time d, the difference is equal to
                   3836:             0.  out[s1][3] = savm[s1][3]: probability, being at state
                   3837:             s1 at precedent wave, to be dead a month before current
                   3838:             wave is equal to probability, being at state s1 at
                   3839:             precedent wave, to be dead at mont of the current
                   3840:             wave. Then the observed probability (that this person died)
                   3841:             is null according to current estimated parameter. In fact,
                   3842:             it should be very low but not zero otherwise the log go to
                   3843:             infinity.
                   3844:          */
1.183     brouard  3845: /* #ifdef INFINITYORIGINAL */
                   3846: /*         lli=log(out[s1][s2] - savm[s1][s2]); */
                   3847: /* #else */
                   3848: /*       if ((out[s1][s2] - savm[s1][s2]) < mytinydouble)  */
                   3849: /*         lli=log(mytinydouble); */
                   3850: /*       else */
                   3851: /*         lli=log(out[s1][s2] - savm[s1][s2]); */
                   3852: /* #endif */
1.226     brouard  3853:          lli=log(out[s1][s2] - savm[s1][s2]);
1.216     brouard  3854:          
1.226     brouard  3855:        } else if  ( s2==-1 ) { /* alive */
                   3856:          for (j=1,survp=0. ; j<=nlstate; j++) 
                   3857:            survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
                   3858:          /*survp += out[s1][j]; */
                   3859:          lli= log(survp);
                   3860:        }
                   3861:        else if  (s2==-4) { 
                   3862:          for (j=3,survp=0. ; j<=nlstate; j++)  
                   3863:            survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
                   3864:          lli= log(survp); 
                   3865:        } 
                   3866:        else if  (s2==-5) { 
                   3867:          for (j=1,survp=0. ; j<=2; j++)  
                   3868:            survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
                   3869:          lli= log(survp); 
                   3870:        } 
                   3871:        else{
                   3872:          lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */
                   3873:          /*  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 */
                   3874:        } 
                   3875:        /*lli=(1.+bbh)*log(out[s1][s2])- bbh*log(savm[s1][s2]);*/
                   3876:        /*if(lli ==000.0)*/
                   3877:        /*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); */
                   3878:        ipmx +=1;
                   3879:        sw += weight[i];
                   3880:        ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
                   3881:        /* if (lli < log(mytinydouble)){ */
                   3882:        /*   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); */
                   3883:        /*   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]); */
                   3884:        /* } */
                   3885:       } /* end of wave */
                   3886:     } /* end of individual */
                   3887:   }  else if(mle==2){
                   3888:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
1.319     brouard  3889:       ioffset=2+nagesqr ;
                   3890:       for (k=1; k<=ncovf;k++)
                   3891:        cov[ioffset+TvarFind[k]]=covar[Tvar[TvarFind[k]]][i];
1.226     brouard  3892:       for(mi=1; mi<= wav[i]-1; mi++){
1.319     brouard  3893:        for(k=1; k <= ncovv ; k++){
                   3894:          cov[ioffset+TvarVind[k]]=cotvar[mw[mi][i]][Tvar[TvarVind[k]]-ncovcol-nqv][i];
                   3895:        }
1.226     brouard  3896:        for (ii=1;ii<=nlstate+ndeath;ii++)
                   3897:          for (j=1;j<=nlstate+ndeath;j++){
                   3898:            oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   3899:            savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   3900:          }
                   3901:        for(d=0; d<=dh[mi][i]; d++){
                   3902:          newm=savm;
                   3903:          agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
                   3904:          cov[2]=agexact;
                   3905:          if(nagesqr==1)
                   3906:            cov[3]= agexact*agexact;
                   3907:          for (kk=1; kk<=cptcovage;kk++) {
                   3908:            cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact;
                   3909:          }
                   3910:          out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   3911:                       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   3912:          savm=oldm;
                   3913:          oldm=newm;
                   3914:        } /* end mult */
                   3915:       
                   3916:        s1=s[mw[mi][i]][i];
                   3917:        s2=s[mw[mi+1][i]][i];
                   3918:        bbh=(double)bh[mi][i]/(double)stepm; 
                   3919:        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 */
                   3920:        ipmx +=1;
                   3921:        sw += weight[i];
                   3922:        ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
                   3923:       } /* end of wave */
                   3924:     } /* end of individual */
                   3925:   }  else if(mle==3){  /* exponential inter-extrapolation */
                   3926:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
                   3927:       for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i];
                   3928:       for(mi=1; mi<= wav[i]-1; mi++){
                   3929:        for (ii=1;ii<=nlstate+ndeath;ii++)
                   3930:          for (j=1;j<=nlstate+ndeath;j++){
                   3931:            oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   3932:            savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   3933:          }
                   3934:        for(d=0; d<dh[mi][i]; d++){
                   3935:          newm=savm;
                   3936:          agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
                   3937:          cov[2]=agexact;
                   3938:          if(nagesqr==1)
                   3939:            cov[3]= agexact*agexact;
                   3940:          for (kk=1; kk<=cptcovage;kk++) {
                   3941:            cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact;
                   3942:          }
                   3943:          out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   3944:                       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   3945:          savm=oldm;
                   3946:          oldm=newm;
                   3947:        } /* end mult */
                   3948:       
                   3949:        s1=s[mw[mi][i]][i];
                   3950:        s2=s[mw[mi+1][i]][i];
                   3951:        bbh=(double)bh[mi][i]/(double)stepm; 
                   3952:        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 */
                   3953:        ipmx +=1;
                   3954:        sw += weight[i];
                   3955:        ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
                   3956:       } /* end of wave */
                   3957:     } /* end of individual */
                   3958:   }else if (mle==4){  /* ml=4 no inter-extrapolation */
                   3959:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
                   3960:       for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i];
                   3961:       for(mi=1; mi<= wav[i]-1; mi++){
                   3962:        for (ii=1;ii<=nlstate+ndeath;ii++)
                   3963:          for (j=1;j<=nlstate+ndeath;j++){
                   3964:            oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   3965:            savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   3966:          }
                   3967:        for(d=0; d<dh[mi][i]; d++){
                   3968:          newm=savm;
                   3969:          agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
                   3970:          cov[2]=agexact;
                   3971:          if(nagesqr==1)
                   3972:            cov[3]= agexact*agexact;
                   3973:          for (kk=1; kk<=cptcovage;kk++) {
                   3974:            cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact;
                   3975:          }
1.126     brouard  3976:        
1.226     brouard  3977:          out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   3978:                       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   3979:          savm=oldm;
                   3980:          oldm=newm;
                   3981:        } /* end mult */
                   3982:       
                   3983:        s1=s[mw[mi][i]][i];
                   3984:        s2=s[mw[mi+1][i]][i];
                   3985:        if( s2 > nlstate){ 
                   3986:          lli=log(out[s1][s2] - savm[s1][s2]);
                   3987:        } else if  ( s2==-1 ) { /* alive */
                   3988:          for (j=1,survp=0. ; j<=nlstate; j++) 
                   3989:            survp += out[s1][j];
                   3990:          lli= log(survp);
                   3991:        }else{
                   3992:          lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]); /* Original formula */
                   3993:        }
                   3994:        ipmx +=1;
                   3995:        sw += weight[i];
                   3996:        ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
1.126     brouard  3997: /*     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  3998:       } /* end of wave */
                   3999:     } /* end of individual */
                   4000:   }else{  /* ml=5 no inter-extrapolation no jackson =0.8a */
                   4001:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
                   4002:       for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i];
                   4003:       for(mi=1; mi<= wav[i]-1; mi++){
                   4004:        for (ii=1;ii<=nlstate+ndeath;ii++)
                   4005:          for (j=1;j<=nlstate+ndeath;j++){
                   4006:            oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   4007:            savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   4008:          }
                   4009:        for(d=0; d<dh[mi][i]; d++){
                   4010:          newm=savm;
                   4011:          agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
                   4012:          cov[2]=agexact;
                   4013:          if(nagesqr==1)
                   4014:            cov[3]= agexact*agexact;
                   4015:          for (kk=1; kk<=cptcovage;kk++) {
                   4016:            cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact;
                   4017:          }
1.126     brouard  4018:        
1.226     brouard  4019:          out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   4020:                       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   4021:          savm=oldm;
                   4022:          oldm=newm;
                   4023:        } /* end mult */
                   4024:       
                   4025:        s1=s[mw[mi][i]][i];
                   4026:        s2=s[mw[mi+1][i]][i];
                   4027:        lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]); /* Original formula */
                   4028:        ipmx +=1;
                   4029:        sw += weight[i];
                   4030:        ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
                   4031:        /*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]);*/
                   4032:       } /* end of wave */
                   4033:     } /* end of individual */
                   4034:   } /* End of if */
                   4035:   for(k=1,l=0.; k<=nlstate; k++) l += ll[k];
                   4036:   /* printf("l1=%f l2=%f ",ll[1],ll[2]); */
                   4037:   l= l*ipmx/sw; /* To get the same order of magnitude as if weight=1 for every body */
                   4038:   return -l;
1.126     brouard  4039: }
                   4040: 
                   4041: /*************** log-likelihood *************/
                   4042: double funcone( double *x)
                   4043: {
1.228     brouard  4044:   /* Same as func but slower because of a lot of printf and if */
1.126     brouard  4045:   int i, ii, j, k, mi, d, kk;
1.228     brouard  4046:   int ioffset=0;
1.131     brouard  4047:   double l, ll[NLSTATEMAX+1], cov[NCOVMAX+1];
1.126     brouard  4048:   double **out;
                   4049:   double lli; /* Individual log likelihood */
                   4050:   double llt;
                   4051:   int s1, s2;
1.228     brouard  4052:   int iv=0, iqv=0, itv=0, iqtv=0 ; /* Index of varying covariate, fixed quantitative cov, time varying covariate, quantitative time varying covariate */
                   4053: 
1.126     brouard  4054:   double bbh, survp;
1.187     brouard  4055:   double agexact;
1.214     brouard  4056:   double agebegin, ageend;
1.126     brouard  4057:   /*extern weight */
                   4058:   /* We are differentiating ll according to initial status */
                   4059:   /*  for (i=1;i<=npar;i++) printf("%f ", x[i]);*/
                   4060:   /*for(i=1;i<imx;i++) 
                   4061:     printf(" %d\n",s[4][i]);
                   4062:   */
                   4063:   cov[1]=1.;
                   4064: 
                   4065:   for(k=1; k<=nlstate; k++) ll[k]=0.;
1.224     brouard  4066:   ioffset=0;
                   4067:   for (i=1,ipmx=0, sw=0.; i<=imx; i++){
1.243     brouard  4068:     /* ioffset=2+nagesqr+cptcovage; */
                   4069:     ioffset=2+nagesqr;
1.232     brouard  4070:     /* Fixed */
1.224     brouard  4071:     /* for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i]; */
1.232     brouard  4072:     /* for (k=1; k<=ncoveff;k++){ /\* Simple and product fixed Dummy covariates without age* products *\/ */
1.311     brouard  4073:     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  4074:       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)*/
                   4075: /*    cov[ioffset+TvarFind[1]]=covar[Tvar[TvarFind[1]]][i];  */
                   4076: /*    cov[2+6]=covar[Tvar[6]][i];  */
                   4077: /*    cov[2+6]=covar[2][i]; V2  */
                   4078: /*    cov[TvarFind[2]]=covar[Tvar[TvarFind[2]]][i];  */
                   4079: /*    cov[2+7]=covar[Tvar[7]][i];  */
                   4080: /*    cov[2+7]=covar[7][i]; V7=V1*V2  */
                   4081: /*    cov[TvarFind[3]]=covar[Tvar[TvarFind[3]]][i];  */
                   4082: /*    cov[2+9]=covar[Tvar[9]][i];  */
                   4083: /*    cov[2+9]=covar[1][i]; V1  */
1.225     brouard  4084:     }
1.232     brouard  4085:     /* for (k=1; k<=nqfveff;k++){ /\* Simple and product fixed Quantitative covariates without age* products *\/ */
                   4086:     /*   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?)*\/ */
                   4087:     /* } */
1.231     brouard  4088:     /* for(iqv=1; iqv <= nqfveff; iqv++){ /\* Quantitative fixed covariates *\/ */
                   4089:     /*   cov[++ioffset]=coqvar[Tvar[iqv]][i]; /\* Only V2 k=6 and V1*V2 7 *\/ */
                   4090:     /* } */
1.225     brouard  4091:     
1.233     brouard  4092: 
                   4093:     for(mi=1; mi<= wav[i]-1; mi++){  /* Varying with waves */
1.232     brouard  4094:     /* Wave varying (but not age varying) */
                   4095:       for(k=1; k <= ncovv ; k++){ /* Varying  covariates (single and product but no age )*/
1.242     brouard  4096:        /* cov[ioffset+TvarVind[k]]=cotvar[mw[mi][i]][Tvar[TvarVind[k]]][i]; */
                   4097:        cov[ioffset+TvarVind[k]]=cotvar[mw[mi][i]][Tvar[TvarVind[k]]-ncovcol-nqv][i];
                   4098:       }
1.232     brouard  4099:       /* for(itv=1; itv <= ntveff; itv++){ /\* Varying dummy covariates (single??)*\/ */
1.242     brouard  4100:       /* iv= Tvar[Tmodelind[ioffset-2-nagesqr-cptcovage+itv]]-ncovcol-nqv; /\* Counting the # varying covariate from 1 to ntveff *\/ */
                   4101:       /* cov[ioffset+iv]=cotvar[mw[mi][i]][iv][i]; */
                   4102:       /* k=ioffset-2-nagesqr-cptcovage+itv; /\* position in simple model *\/ */
                   4103:       /* cov[ioffset+itv]=cotvar[mw[mi][i]][TmodelInvind[itv]][i]; */
                   4104:       /* 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  4105:       /* for(iqtv=1; iqtv <= nqtveff; iqtv++){ /\* Varying quantitatives covariates *\/ */
1.242     brouard  4106:       /*       iv=TmodelInvQind[iqtv]; /\* Counting the # varying covariate from 1 to ntveff *\/ */
                   4107:       /*       /\* 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]); *\/ */
                   4108:       /*       cov[ioffset+ntveff+iqtv]=cotqvar[mw[mi][i]][TmodelInvQind[iqtv]][i]; */
1.232     brouard  4109:       /* } */
1.126     brouard  4110:       for (ii=1;ii<=nlstate+ndeath;ii++)
1.242     brouard  4111:        for (j=1;j<=nlstate+ndeath;j++){
                   4112:          oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   4113:          savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   4114:        }
1.214     brouard  4115:       
                   4116:       agebegin=agev[mw[mi][i]][i]; /* Age at beginning of effective wave */
                   4117:       ageend=agev[mw[mi][i]][i] + (dh[mi][i])*stepm/YEARM; /* Age at end of effective wave and at the end of transition */
                   4118:       for(d=0; d<dh[mi][i]; d++){  /* Delay between two effective waves */
1.247     brouard  4119:       /* for(d=0; d<=0; d++){  /\* Delay between two effective waves Only one matrix to speed up*\/ */
1.242     brouard  4120:        /*dh[m][i] or dh[mw[mi][i]][i] is the delay between two effective waves m=mw[mi][i]
                   4121:          and mw[mi+1][i]. dh depends on stepm.*/
                   4122:        newm=savm;
1.247     brouard  4123:        agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;  /* Here d is needed */
1.242     brouard  4124:        cov[2]=agexact;
                   4125:        if(nagesqr==1)
                   4126:          cov[3]= agexact*agexact;
                   4127:        for (kk=1; kk<=cptcovage;kk++) {
                   4128:          if(!FixedV[Tvar[Tage[kk]]])
                   4129:            cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact;
                   4130:          else
                   4131:            cov[Tage[kk]+2+nagesqr]=cotvar[mw[mi][i]][Tvar[Tage[kk]]-ncovcol-nqv][i]*agexact;
                   4132:        }
                   4133:        /* printf("i=%d,mi=%d,d=%d,mw[mi][i]=%d\n",i, mi,d,mw[mi][i]); */
                   4134:        /* savm=pmij(pmmij,cov,ncovmodel,x,nlstate); */
                   4135:        out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   4136:                     1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   4137:        /* out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath, */
                   4138:        /*           1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate)); */
                   4139:        savm=oldm;
                   4140:        oldm=newm;
1.126     brouard  4141:       } /* end mult */
                   4142:       
                   4143:       s1=s[mw[mi][i]][i];
                   4144:       s2=s[mw[mi+1][i]][i];
1.217     brouard  4145:       /* if(s2==-1){ */
1.268     brouard  4146:       /*       printf(" ERROR s1=%d, s2=%d i=%d \n", s1, s2, i); */
1.217     brouard  4147:       /*       /\* exit(1); *\/ */
                   4148:       /* } */
1.126     brouard  4149:       bbh=(double)bh[mi][i]/(double)stepm; 
                   4150:       /* bias is positive if real duration
                   4151:        * is higher than the multiple of stepm and negative otherwise.
                   4152:        */
                   4153:       if( s2 > nlstate && (mle <5) ){  /* Jackson */
1.242     brouard  4154:        lli=log(out[s1][s2] - savm[s1][s2]);
1.216     brouard  4155:       } else if  ( s2==-1 ) { /* alive */
1.242     brouard  4156:        for (j=1,survp=0. ; j<=nlstate; j++) 
                   4157:          survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
                   4158:        lli= log(survp);
1.126     brouard  4159:       }else if (mle==1){
1.242     brouard  4160:        lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */
1.126     brouard  4161:       } else if(mle==2){
1.242     brouard  4162:        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  4163:       } else if(mle==3){  /* exponential inter-extrapolation */
1.242     brouard  4164:        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  4165:       } else if (mle==4){  /* mle=4 no inter-extrapolation */
1.242     brouard  4166:        lli=log(out[s1][s2]); /* Original formula */
1.136     brouard  4167:       } else{  /* mle=0 back to 1 */
1.242     brouard  4168:        lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */
                   4169:        /*lli=log(out[s1][s2]); */ /* Original formula */
1.126     brouard  4170:       } /* End of if */
                   4171:       ipmx +=1;
                   4172:       sw += weight[i];
                   4173:       ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
1.132     brouard  4174:       /*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  4175:       if(globpr){
1.246     brouard  4176:        fprintf(ficresilk,"%09ld %6.1f %6.1f %6d %2d %2d %2d %2d %3d %15.6f %8.4f %8.3f\
1.126     brouard  4177:  %11.6f %11.6f %11.6f ", \
1.242     brouard  4178:                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  4179:                2*weight[i]*lli,(s2==-1? -1: out[s1][s2]),(s2==-1? -1: savm[s1][s2]));
1.242     brouard  4180:        for(k=1,llt=0.,l=0.; k<=nlstate; k++){
                   4181:          llt +=ll[k]*gipmx/gsw;
                   4182:          fprintf(ficresilk," %10.6f",-ll[k]*gipmx/gsw);
                   4183:        }
                   4184:        fprintf(ficresilk," %10.6f\n", -llt);
1.126     brouard  4185:       }
1.232     brouard  4186:        } /* end of wave */
                   4187: } /* end of individual */
                   4188: for(k=1,l=0.; k<=nlstate; k++) l += ll[k];
                   4189: /* printf("l1=%f l2=%f ",ll[1],ll[2]); */
                   4190: l= l*ipmx/sw; /* To get the same order of magnitude as if weight=1 for every body */
                   4191: if(globpr==0){ /* First time we count the contributions and weights */
                   4192:        gipmx=ipmx;
                   4193:        gsw=sw;
                   4194: }
                   4195: return -l;
1.126     brouard  4196: }
                   4197: 
                   4198: 
                   4199: /*************** function likelione ***********/
1.292     brouard  4200: void likelione(FILE *ficres,double p[], int npar, int nlstate, int *globpri, long *ipmx, double *sw, double *fretone, double (*func)(double []))
1.126     brouard  4201: {
                   4202:   /* This routine should help understanding what is done with 
                   4203:      the selection of individuals/waves and
                   4204:      to check the exact contribution to the likelihood.
                   4205:      Plotting could be done.
                   4206:    */
                   4207:   int k;
                   4208: 
                   4209:   if(*globpri !=0){ /* Just counts and sums, no printings */
1.201     brouard  4210:     strcpy(fileresilk,"ILK_"); 
1.202     brouard  4211:     strcat(fileresilk,fileresu);
1.126     brouard  4212:     if((ficresilk=fopen(fileresilk,"w"))==NULL) {
                   4213:       printf("Problem with resultfile: %s\n", fileresilk);
                   4214:       fprintf(ficlog,"Problem with resultfile: %s\n", fileresilk);
                   4215:     }
1.214     brouard  4216:     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");
                   4217:     fprintf(ficresilk, "#num_i ageb agend i s1 s2 mi mw dh likeli weight %%weight 2wlli out sav ");
1.126     brouard  4218:     /*         i,s1,s2,mi,mw[mi][i],dh[mi][i],exp(lli),weight[i],2*weight[i]*lli,out[s1][s2],savm[s1][s2]); */
                   4219:     for(k=1; k<=nlstate; k++) 
                   4220:       fprintf(ficresilk," -2*gipw/gsw*weight*ll[%d]++",k);
                   4221:     fprintf(ficresilk," -2*gipw/gsw*weight*ll(total)\n");
                   4222:   }
                   4223: 
1.292     brouard  4224:   *fretone=(*func)(p);
1.126     brouard  4225:   if(*globpri !=0){
                   4226:     fclose(ficresilk);
1.205     brouard  4227:     if (mle ==0)
                   4228:       fprintf(fichtm,"\n<br>File of contributions to the likelihood computed with initial parameters and mle = %d.",mle);
                   4229:     else if(mle >=1)
                   4230:       fprintf(fichtm,"\n<br>File of contributions to the likelihood computed with optimized parameters mle = %d.",mle);
                   4231:     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  4232:     fprintf(fichtm,"\n<br>Equation of the model: <b>model=1+age+%s</b><br>\n",model); 
1.208     brouard  4233:       
                   4234:     for (k=1; k<= nlstate ; k++) {
1.211     brouard  4235:       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  4236: <img src=\"%s-p%dj.png\">",k,k,subdirf2(optionfilefiname,"ILK_"),k,subdirf2(optionfilefiname,"ILK_"),k,subdirf2(optionfilefiname,"ILK_"),k);
                   4237:     }
1.207     brouard  4238:     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  4239: <img src=\"%s-ori.png\">",subdirf2(optionfilefiname,"ILK_"),subdirf2(optionfilefiname,"ILK_"),subdirf2(optionfilefiname,"ILK_"));
1.207     brouard  4240:     fprintf(fichtm,"<br>- and by state of destination <a href=\"%s-dest.png\">%s-dest.png</a><br> \
1.204     brouard  4241: <img src=\"%s-dest.png\">",subdirf2(optionfilefiname,"ILK_"),subdirf2(optionfilefiname,"ILK_"),subdirf2(optionfilefiname,"ILK_"));
1.207     brouard  4242:     fflush(fichtm);
1.205     brouard  4243:   }
1.126     brouard  4244:   return;
                   4245: }
                   4246: 
                   4247: 
                   4248: /*********** Maximum Likelihood Estimation ***************/
                   4249: 
                   4250: void mlikeli(FILE *ficres,double p[], int npar, int ncovmodel, int nlstate, double ftol, double (*func)(double []))
                   4251: {
1.319     brouard  4252:   int i,j,k, jk, jkk=0, iter=0;
1.126     brouard  4253:   double **xi;
                   4254:   double fret;
                   4255:   double fretone; /* Only one call to likelihood */
                   4256:   /*  char filerespow[FILENAMELENGTH];*/
1.162     brouard  4257: 
                   4258: #ifdef NLOPT
                   4259:   int creturn;
                   4260:   nlopt_opt opt;
                   4261:   /* double lb[9] = { -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL }; /\* lower bounds *\/ */
                   4262:   double *lb;
                   4263:   double minf; /* the minimum objective value, upon return */
                   4264:   double * p1; /* Shifted parameters from 0 instead of 1 */
                   4265:   myfunc_data dinst, *d = &dinst;
                   4266: #endif
                   4267: 
                   4268: 
1.126     brouard  4269:   xi=matrix(1,npar,1,npar);
                   4270:   for (i=1;i<=npar;i++)
                   4271:     for (j=1;j<=npar;j++)
                   4272:       xi[i][j]=(i==j ? 1.0 : 0.0);
                   4273:   printf("Powell\n");  fprintf(ficlog,"Powell\n");
1.201     brouard  4274:   strcpy(filerespow,"POW_"); 
1.126     brouard  4275:   strcat(filerespow,fileres);
                   4276:   if((ficrespow=fopen(filerespow,"w"))==NULL) {
                   4277:     printf("Problem with resultfile: %s\n", filerespow);
                   4278:     fprintf(ficlog,"Problem with resultfile: %s\n", filerespow);
                   4279:   }
                   4280:   fprintf(ficrespow,"# Powell\n# iter -2*LL");
                   4281:   for (i=1;i<=nlstate;i++)
                   4282:     for(j=1;j<=nlstate+ndeath;j++)
                   4283:       if(j!=i)fprintf(ficrespow," p%1d%1d",i,j);
                   4284:   fprintf(ficrespow,"\n");
1.162     brouard  4285: #ifdef POWELL
1.319     brouard  4286: #ifdef LINMINORIGINAL
                   4287: #else /* LINMINORIGINAL */
                   4288:   
                   4289:   flatdir=ivector(1,npar); 
                   4290:   for (j=1;j<=npar;j++) flatdir[j]=0; 
                   4291: #endif /*LINMINORIGINAL */
                   4292: 
                   4293: #ifdef FLATSUP
                   4294:   powell(p,xi,npar,ftol,&iter,&fret,flatdir,func);
                   4295:   /* reorganizing p by suppressing flat directions */
                   4296:   for(i=1, jk=1; i <=nlstate; i++){
                   4297:     for(k=1; k <=(nlstate+ndeath); k++){
                   4298:       if (k != i) {
                   4299:         printf("%d%d flatdir[%d]=%d",i,k,jk, flatdir[jk]);
                   4300:         if(flatdir[jk]==1){
                   4301:           printf(" To be skipped %d%d flatdir[%d]=%d ",i,k,jk, flatdir[jk]);
                   4302:         }
                   4303:         for(j=1; j <=ncovmodel; j++){
                   4304:           printf("%12.7f ",p[jk]);
                   4305:           jk++; 
                   4306:         }
                   4307:         printf("\n");
                   4308:       }
                   4309:     }
                   4310:   }
                   4311: /* skipping */
                   4312:   /* for(i=1, jk=1, jkk=1;(flatdir[jk]==0)&& (i <=nlstate); i++){ */
                   4313:   for(i=1, jk=1, jkk=1;i <=nlstate; i++){
                   4314:     for(k=1; k <=(nlstate+ndeath); k++){
                   4315:       if (k != i) {
                   4316:         printf("%d%d flatdir[%d]=%d",i,k,jk, flatdir[jk]);
                   4317:         if(flatdir[jk]==1){
                   4318:           printf(" To be skipped %d%d flatdir[%d]=%d jk=%d p[%d] ",i,k,jk, flatdir[jk],jk, jk);
                   4319:           for(j=1; j <=ncovmodel;  jk++,j++){
                   4320:             printf(" p[%d]=%12.7f",jk, p[jk]);
                   4321:             /*q[jjk]=p[jk];*/
                   4322:           }
                   4323:         }else{
                   4324:           printf(" To be kept %d%d flatdir[%d]=%d jk=%d q[%d]=p[%d] ",i,k,jk, flatdir[jk],jk, jkk, jk);
                   4325:           for(j=1; j <=ncovmodel;  jk++,jkk++,j++){
                   4326:             printf(" p[%d]=%12.7f=q[%d]",jk, p[jk],jkk);
                   4327:             /*q[jjk]=p[jk];*/
                   4328:           }
                   4329:         }
                   4330:         printf("\n");
                   4331:       }
                   4332:       fflush(stdout);
                   4333:     }
                   4334:   }
                   4335:   powell(p,xi,npar,ftol,&iter,&fret,flatdir,func);
                   4336: #else  /* FLATSUP */
1.126     brouard  4337:   powell(p,xi,npar,ftol,&iter,&fret,func);
1.319     brouard  4338: #endif  /* FLATSUP */
                   4339: 
                   4340: #ifdef LINMINORIGINAL
                   4341: #else
                   4342:       free_ivector(flatdir,1,npar); 
                   4343: #endif  /* LINMINORIGINAL*/
                   4344: #endif /* POWELL */
1.126     brouard  4345: 
1.162     brouard  4346: #ifdef NLOPT
                   4347: #ifdef NEWUOA
                   4348:   opt = nlopt_create(NLOPT_LN_NEWUOA,npar);
                   4349: #else
                   4350:   opt = nlopt_create(NLOPT_LN_BOBYQA,npar);
                   4351: #endif
                   4352:   lb=vector(0,npar-1);
                   4353:   for (i=0;i<npar;i++) lb[i]= -HUGE_VAL;
                   4354:   nlopt_set_lower_bounds(opt, lb);
                   4355:   nlopt_set_initial_step1(opt, 0.1);
                   4356:   
                   4357:   p1= (p+1); /*  p *(p+1)@8 and p *(p1)@8 are equal p1[0]=p[1] */
                   4358:   d->function = func;
                   4359:   printf(" Func %.12lf \n",myfunc(npar,p1,NULL,d));
                   4360:   nlopt_set_min_objective(opt, myfunc, d);
                   4361:   nlopt_set_xtol_rel(opt, ftol);
                   4362:   if ((creturn=nlopt_optimize(opt, p1, &minf)) < 0) {
                   4363:     printf("nlopt failed! %d\n",creturn); 
                   4364:   }
                   4365:   else {
                   4366:     printf("found minimum after %d evaluations (NLOPT=%d)\n", countcallfunc ,NLOPT);
                   4367:     printf("found minimum at f(%g,%g) = %0.10g\n", p[0], p[1], minf);
                   4368:     iter=1; /* not equal */
                   4369:   }
                   4370:   nlopt_destroy(opt);
                   4371: #endif
1.319     brouard  4372: #ifdef FLATSUP
                   4373:   /* npared = npar -flatd/ncovmodel; */
                   4374:   /* xired= matrix(1,npared,1,npared); */
                   4375:   /* paramred= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel); */
                   4376:   /* powell(pred,xired,npared,ftol,&iter,&fret,flatdir,func); */
                   4377:   /* free_matrix(xire,1,npared,1,npared); */
                   4378: #else  /* FLATSUP */
                   4379: #endif /* FLATSUP */
1.126     brouard  4380:   free_matrix(xi,1,npar,1,npar);
                   4381:   fclose(ficrespow);
1.203     brouard  4382:   printf("\n#Number of iterations & function calls = %d & %d, -2 Log likelihood = %.12f\n",iter, countcallfunc,func(p));
                   4383:   fprintf(ficlog,"\n#Number of iterations & function calls = %d & %d, -2 Log likelihood = %.12f\n",iter, countcallfunc,func(p));
1.180     brouard  4384:   fprintf(ficres,"#Number of iterations & function calls = %d & %d, -2 Log likelihood = %.12f\n",iter, countcallfunc,func(p));
1.126     brouard  4385: 
                   4386: }
                   4387: 
                   4388: /**** Computes Hessian and covariance matrix ***/
1.203     brouard  4389: void hesscov(double **matcov, double **hess, double p[], int npar, double delti[], double ftolhess, double (*func)(double []))
1.126     brouard  4390: {
                   4391:   double  **a,**y,*x,pd;
1.203     brouard  4392:   /* double **hess; */
1.164     brouard  4393:   int i, j;
1.126     brouard  4394:   int *indx;
                   4395: 
                   4396:   double hessii(double p[], double delta, int theta, double delti[],double (*func)(double []),int npar);
1.203     brouard  4397:   double hessij(double p[], double **hess, double delti[], int i, int j,double (*func)(double []),int npar);
1.126     brouard  4398:   void lubksb(double **a, int npar, int *indx, double b[]) ;
                   4399:   void ludcmp(double **a, int npar, int *indx, double *d) ;
                   4400:   double gompertz(double p[]);
1.203     brouard  4401:   /* hess=matrix(1,npar,1,npar); */
1.126     brouard  4402: 
                   4403:   printf("\nCalculation of the hessian matrix. Wait...\n");
                   4404:   fprintf(ficlog,"\nCalculation of the hessian matrix. Wait...\n");
                   4405:   for (i=1;i<=npar;i++){
1.203     brouard  4406:     printf("%d-",i);fflush(stdout);
                   4407:     fprintf(ficlog,"%d-",i);fflush(ficlog);
1.126     brouard  4408:    
                   4409:      hess[i][i]=hessii(p,ftolhess,i,delti,func,npar);
                   4410:     
                   4411:     /*  printf(" %f ",p[i]);
                   4412:        printf(" %lf %lf %lf",hess[i][i],ftolhess,delti[i]);*/
                   4413:   }
                   4414:   
                   4415:   for (i=1;i<=npar;i++) {
                   4416:     for (j=1;j<=npar;j++)  {
                   4417:       if (j>i) { 
1.203     brouard  4418:        printf(".%d-%d",i,j);fflush(stdout);
                   4419:        fprintf(ficlog,".%d-%d",i,j);fflush(ficlog);
                   4420:        hess[i][j]=hessij(p,hess, delti,i,j,func,npar);
1.126     brouard  4421:        
                   4422:        hess[j][i]=hess[i][j];    
                   4423:        /*printf(" %lf ",hess[i][j]);*/
                   4424:       }
                   4425:     }
                   4426:   }
                   4427:   printf("\n");
                   4428:   fprintf(ficlog,"\n");
                   4429: 
                   4430:   printf("\nInverting the hessian to get the covariance matrix. Wait...\n");
                   4431:   fprintf(ficlog,"\nInverting the hessian to get the covariance matrix. Wait...\n");
                   4432:   
                   4433:   a=matrix(1,npar,1,npar);
                   4434:   y=matrix(1,npar,1,npar);
                   4435:   x=vector(1,npar);
                   4436:   indx=ivector(1,npar);
                   4437:   for (i=1;i<=npar;i++)
                   4438:     for (j=1;j<=npar;j++) a[i][j]=hess[i][j];
                   4439:   ludcmp(a,npar,indx,&pd);
                   4440: 
                   4441:   for (j=1;j<=npar;j++) {
                   4442:     for (i=1;i<=npar;i++) x[i]=0;
                   4443:     x[j]=1;
                   4444:     lubksb(a,npar,indx,x);
                   4445:     for (i=1;i<=npar;i++){ 
                   4446:       matcov[i][j]=x[i];
                   4447:     }
                   4448:   }
                   4449: 
                   4450:   printf("\n#Hessian matrix#\n");
                   4451:   fprintf(ficlog,"\n#Hessian matrix#\n");
                   4452:   for (i=1;i<=npar;i++) { 
                   4453:     for (j=1;j<=npar;j++) { 
1.203     brouard  4454:       printf("%.6e ",hess[i][j]);
                   4455:       fprintf(ficlog,"%.6e ",hess[i][j]);
1.126     brouard  4456:     }
                   4457:     printf("\n");
                   4458:     fprintf(ficlog,"\n");
                   4459:   }
                   4460: 
1.203     brouard  4461:   /* printf("\n#Covariance matrix#\n"); */
                   4462:   /* fprintf(ficlog,"\n#Covariance matrix#\n"); */
                   4463:   /* for (i=1;i<=npar;i++) {  */
                   4464:   /*   for (j=1;j<=npar;j++) {  */
                   4465:   /*     printf("%.6e ",matcov[i][j]); */
                   4466:   /*     fprintf(ficlog,"%.6e ",matcov[i][j]); */
                   4467:   /*   } */
                   4468:   /*   printf("\n"); */
                   4469:   /*   fprintf(ficlog,"\n"); */
                   4470:   /* } */
                   4471: 
1.126     brouard  4472:   /* Recompute Inverse */
1.203     brouard  4473:   /* for (i=1;i<=npar;i++) */
                   4474:   /*   for (j=1;j<=npar;j++) a[i][j]=matcov[i][j]; */
                   4475:   /* ludcmp(a,npar,indx,&pd); */
                   4476: 
                   4477:   /*  printf("\n#Hessian matrix recomputed#\n"); */
                   4478: 
                   4479:   /* for (j=1;j<=npar;j++) { */
                   4480:   /*   for (i=1;i<=npar;i++) x[i]=0; */
                   4481:   /*   x[j]=1; */
                   4482:   /*   lubksb(a,npar,indx,x); */
                   4483:   /*   for (i=1;i<=npar;i++){  */
                   4484:   /*     y[i][j]=x[i]; */
                   4485:   /*     printf("%.3e ",y[i][j]); */
                   4486:   /*     fprintf(ficlog,"%.3e ",y[i][j]); */
                   4487:   /*   } */
                   4488:   /*   printf("\n"); */
                   4489:   /*   fprintf(ficlog,"\n"); */
                   4490:   /* } */
                   4491: 
                   4492:   /* Verifying the inverse matrix */
                   4493: #ifdef DEBUGHESS
                   4494:   y=matprod2(y,hess,1,npar,1,npar,1,npar,matcov);
1.126     brouard  4495: 
1.203     brouard  4496:    printf("\n#Verification: multiplying the matrix of covariance by the Hessian matrix, should be unity:#\n");
                   4497:    fprintf(ficlog,"\n#Verification: multiplying the matrix of covariance by the Hessian matrix. Should be unity:#\n");
1.126     brouard  4498: 
                   4499:   for (j=1;j<=npar;j++) {
                   4500:     for (i=1;i<=npar;i++){ 
1.203     brouard  4501:       printf("%.2f ",y[i][j]);
                   4502:       fprintf(ficlog,"%.2f ",y[i][j]);
1.126     brouard  4503:     }
                   4504:     printf("\n");
                   4505:     fprintf(ficlog,"\n");
                   4506:   }
1.203     brouard  4507: #endif
1.126     brouard  4508: 
                   4509:   free_matrix(a,1,npar,1,npar);
                   4510:   free_matrix(y,1,npar,1,npar);
                   4511:   free_vector(x,1,npar);
                   4512:   free_ivector(indx,1,npar);
1.203     brouard  4513:   /* free_matrix(hess,1,npar,1,npar); */
1.126     brouard  4514: 
                   4515: 
                   4516: }
                   4517: 
                   4518: /*************** hessian matrix ****************/
                   4519: double hessii(double x[], double delta, int theta, double delti[], double (*func)(double []), int npar)
1.203     brouard  4520: { /* Around values of x, computes the function func and returns the scales delti and hessian */
1.126     brouard  4521:   int i;
                   4522:   int l=1, lmax=20;
1.203     brouard  4523:   double k1,k2, res, fx;
1.132     brouard  4524:   double p2[MAXPARM+1]; /* identical to x */
1.126     brouard  4525:   double delt=0.0001, delts, nkhi=10.,nkhif=1., khi=1.e-4;
                   4526:   int k=0,kmax=10;
                   4527:   double l1;
                   4528: 
                   4529:   fx=func(x);
                   4530:   for (i=1;i<=npar;i++) p2[i]=x[i];
1.145     brouard  4531:   for(l=0 ; l <=lmax; l++){  /* Enlarging the zone around the Maximum */
1.126     brouard  4532:     l1=pow(10,l);
                   4533:     delts=delt;
                   4534:     for(k=1 ; k <kmax; k=k+1){
                   4535:       delt = delta*(l1*k);
                   4536:       p2[theta]=x[theta] +delt;
1.145     brouard  4537:       k1=func(p2)-fx;   /* Might be negative if too close to the theoretical maximum */
1.126     brouard  4538:       p2[theta]=x[theta]-delt;
                   4539:       k2=func(p2)-fx;
                   4540:       /*res= (k1-2.0*fx+k2)/delt/delt; */
1.203     brouard  4541:       res= (k1+k2)/delt/delt/2.; /* Divided by 2 because L and not 2*L */
1.126     brouard  4542:       
1.203     brouard  4543: #ifdef DEBUGHESSII
1.126     brouard  4544:       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);
                   4545:       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);
                   4546: #endif
                   4547:       /*if(fabs(k1-2.0*fx+k2) <1.e-13){ */
                   4548:       if((k1 <khi/nkhi/2.) || (k2 <khi/nkhi/2.)){
                   4549:        k=kmax;
                   4550:       }
                   4551:       else if((k1 >khi/nkhif) || (k2 >khi/nkhif)){ /* Keeps lastvalue before 3.84/2 KHI2 5% 1d.f. */
1.164     brouard  4552:        k=kmax; l=lmax*10;
1.126     brouard  4553:       }
                   4554:       else if((k1 >khi/nkhi) || (k2 >khi/nkhi)){ 
                   4555:        delts=delt;
                   4556:       }
1.203     brouard  4557:     } /* End loop k */
1.126     brouard  4558:   }
                   4559:   delti[theta]=delts;
                   4560:   return res; 
                   4561:   
                   4562: }
                   4563: 
1.203     brouard  4564: double hessij( double x[], double **hess, double delti[], int thetai,int thetaj,double (*func)(double []),int npar)
1.126     brouard  4565: {
                   4566:   int i;
1.164     brouard  4567:   int l=1, lmax=20;
1.126     brouard  4568:   double k1,k2,k3,k4,res,fx;
1.132     brouard  4569:   double p2[MAXPARM+1];
1.203     brouard  4570:   int k, kmax=1;
                   4571:   double v1, v2, cv12, lc1, lc2;
1.208     brouard  4572: 
                   4573:   int firstime=0;
1.203     brouard  4574:   
1.126     brouard  4575:   fx=func(x);
1.203     brouard  4576:   for (k=1; k<=kmax; k=k+10) {
1.126     brouard  4577:     for (i=1;i<=npar;i++) p2[i]=x[i];
1.203     brouard  4578:     p2[thetai]=x[thetai]+delti[thetai]*k;
                   4579:     p2[thetaj]=x[thetaj]+delti[thetaj]*k;
1.126     brouard  4580:     k1=func(p2)-fx;
                   4581:   
1.203     brouard  4582:     p2[thetai]=x[thetai]+delti[thetai]*k;
                   4583:     p2[thetaj]=x[thetaj]-delti[thetaj]*k;
1.126     brouard  4584:     k2=func(p2)-fx;
                   4585:   
1.203     brouard  4586:     p2[thetai]=x[thetai]-delti[thetai]*k;
                   4587:     p2[thetaj]=x[thetaj]+delti[thetaj]*k;
1.126     brouard  4588:     k3=func(p2)-fx;
                   4589:   
1.203     brouard  4590:     p2[thetai]=x[thetai]-delti[thetai]*k;
                   4591:     p2[thetaj]=x[thetaj]-delti[thetaj]*k;
1.126     brouard  4592:     k4=func(p2)-fx;
1.203     brouard  4593:     res=(k1-k2-k3+k4)/4.0/delti[thetai]/k/delti[thetaj]/k/2.; /* Because of L not 2*L */
                   4594:     if(k1*k2*k3*k4 <0.){
1.208     brouard  4595:       firstime=1;
1.203     brouard  4596:       kmax=kmax+10;
1.208     brouard  4597:     }
                   4598:     if(kmax >=10 || firstime ==1){
1.246     brouard  4599:       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);
                   4600:       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  4601:       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);
                   4602:       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);
                   4603:     }
                   4604: #ifdef DEBUGHESSIJ
                   4605:     v1=hess[thetai][thetai];
                   4606:     v2=hess[thetaj][thetaj];
                   4607:     cv12=res;
                   4608:     /* Computing eigen value of Hessian matrix */
                   4609:     lc1=((v1+v2)+sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
                   4610:     lc2=((v1+v2)-sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
                   4611:     if ((lc2 <0) || (lc1 <0) ){
                   4612:       printf("Warning: sub Hessian matrix '%d%d' does not have positive eigen values \n",thetai,thetaj);
                   4613:       fprintf(ficlog, "Warning: sub Hessian matrix '%d%d' does not have positive eigen values \n",thetai,thetaj);
                   4614:       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);
                   4615:       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);
                   4616:     }
1.126     brouard  4617: #endif
                   4618:   }
                   4619:   return res;
                   4620: }
                   4621: 
1.203     brouard  4622:     /* Not done yet: Was supposed to fix if not exactly at the maximum */
                   4623: /* double hessij( double x[], double delti[], int thetai,int thetaj,double (*func)(double []),int npar) */
                   4624: /* { */
                   4625: /*   int i; */
                   4626: /*   int l=1, lmax=20; */
                   4627: /*   double k1,k2,k3,k4,res,fx; */
                   4628: /*   double p2[MAXPARM+1]; */
                   4629: /*   double delt=0.0001, delts, nkhi=10.,nkhif=1., khi=1.e-4; */
                   4630: /*   int k=0,kmax=10; */
                   4631: /*   double l1; */
                   4632:   
                   4633: /*   fx=func(x); */
                   4634: /*   for(l=0 ; l <=lmax; l++){  /\* Enlarging the zone around the Maximum *\/ */
                   4635: /*     l1=pow(10,l); */
                   4636: /*     delts=delt; */
                   4637: /*     for(k=1 ; k <kmax; k=k+1){ */
                   4638: /*       delt = delti*(l1*k); */
                   4639: /*       for (i=1;i<=npar;i++) p2[i]=x[i]; */
                   4640: /*       p2[thetai]=x[thetai]+delti[thetai]/k; */
                   4641: /*       p2[thetaj]=x[thetaj]+delti[thetaj]/k; */
                   4642: /*       k1=func(p2)-fx; */
                   4643:       
                   4644: /*       p2[thetai]=x[thetai]+delti[thetai]/k; */
                   4645: /*       p2[thetaj]=x[thetaj]-delti[thetaj]/k; */
                   4646: /*       k2=func(p2)-fx; */
                   4647:       
                   4648: /*       p2[thetai]=x[thetai]-delti[thetai]/k; */
                   4649: /*       p2[thetaj]=x[thetaj]+delti[thetaj]/k; */
                   4650: /*       k3=func(p2)-fx; */
                   4651:       
                   4652: /*       p2[thetai]=x[thetai]-delti[thetai]/k; */
                   4653: /*       p2[thetaj]=x[thetaj]-delti[thetaj]/k; */
                   4654: /*       k4=func(p2)-fx; */
                   4655: /*       res=(k1-k2-k3+k4)/4.0/delti[thetai]*k/delti[thetaj]*k/2.; /\* Because of L not 2*L *\/ */
                   4656: /* #ifdef DEBUGHESSIJ */
                   4657: /*       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); */
                   4658: /*       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); */
                   4659: /* #endif */
                   4660: /*       if((k1 <khi/nkhi/2.) || (k2 <khi/nkhi/2.)|| (k4 <khi/nkhi/2.)|| (k4 <khi/nkhi/2.)){ */
                   4661: /*     k=kmax; */
                   4662: /*       } */
                   4663: /*       else if((k1 >khi/nkhif) || (k2 >khi/nkhif) || (k4 >khi/nkhif) || (k4 >khi/nkhif)){ /\* Keeps lastvalue before 3.84/2 KHI2 5% 1d.f. *\/ */
                   4664: /*     k=kmax; l=lmax*10; */
                   4665: /*       } */
                   4666: /*       else if((k1 >khi/nkhi) || (k2 >khi/nkhi)){  */
                   4667: /*     delts=delt; */
                   4668: /*       } */
                   4669: /*     } /\* End loop k *\/ */
                   4670: /*   } */
                   4671: /*   delti[theta]=delts; */
                   4672: /*   return res;  */
                   4673: /* } */
                   4674: 
                   4675: 
1.126     brouard  4676: /************** Inverse of matrix **************/
                   4677: void ludcmp(double **a, int n, int *indx, double *d) 
                   4678: { 
                   4679:   int i,imax,j,k; 
                   4680:   double big,dum,sum,temp; 
                   4681:   double *vv; 
                   4682:  
                   4683:   vv=vector(1,n); 
                   4684:   *d=1.0; 
                   4685:   for (i=1;i<=n;i++) { 
                   4686:     big=0.0; 
                   4687:     for (j=1;j<=n;j++) 
                   4688:       if ((temp=fabs(a[i][j])) > big) big=temp; 
1.256     brouard  4689:     if (big == 0.0){
                   4690:       printf(" Singular Hessian matrix at row %d:\n",i);
                   4691:       for (j=1;j<=n;j++) {
                   4692:        printf(" a[%d][%d]=%f,",i,j,a[i][j]);
                   4693:        fprintf(ficlog," a[%d][%d]=%f,",i,j,a[i][j]);
                   4694:       }
                   4695:       fflush(ficlog);
                   4696:       fclose(ficlog);
                   4697:       nrerror("Singular matrix in routine ludcmp"); 
                   4698:     }
1.126     brouard  4699:     vv[i]=1.0/big; 
                   4700:   } 
                   4701:   for (j=1;j<=n;j++) { 
                   4702:     for (i=1;i<j;i++) { 
                   4703:       sum=a[i][j]; 
                   4704:       for (k=1;k<i;k++) sum -= a[i][k]*a[k][j]; 
                   4705:       a[i][j]=sum; 
                   4706:     } 
                   4707:     big=0.0; 
                   4708:     for (i=j;i<=n;i++) { 
                   4709:       sum=a[i][j]; 
                   4710:       for (k=1;k<j;k++) 
                   4711:        sum -= a[i][k]*a[k][j]; 
                   4712:       a[i][j]=sum; 
                   4713:       if ( (dum=vv[i]*fabs(sum)) >= big) { 
                   4714:        big=dum; 
                   4715:        imax=i; 
                   4716:       } 
                   4717:     } 
                   4718:     if (j != imax) { 
                   4719:       for (k=1;k<=n;k++) { 
                   4720:        dum=a[imax][k]; 
                   4721:        a[imax][k]=a[j][k]; 
                   4722:        a[j][k]=dum; 
                   4723:       } 
                   4724:       *d = -(*d); 
                   4725:       vv[imax]=vv[j]; 
                   4726:     } 
                   4727:     indx[j]=imax; 
                   4728:     if (a[j][j] == 0.0) a[j][j]=TINY; 
                   4729:     if (j != n) { 
                   4730:       dum=1.0/(a[j][j]); 
                   4731:       for (i=j+1;i<=n;i++) a[i][j] *= dum; 
                   4732:     } 
                   4733:   } 
                   4734:   free_vector(vv,1,n);  /* Doesn't work */
                   4735: ;
                   4736: } 
                   4737: 
                   4738: void lubksb(double **a, int n, int *indx, double b[]) 
                   4739: { 
                   4740:   int i,ii=0,ip,j; 
                   4741:   double sum; 
                   4742:  
                   4743:   for (i=1;i<=n;i++) { 
                   4744:     ip=indx[i]; 
                   4745:     sum=b[ip]; 
                   4746:     b[ip]=b[i]; 
                   4747:     if (ii) 
                   4748:       for (j=ii;j<=i-1;j++) sum -= a[i][j]*b[j]; 
                   4749:     else if (sum) ii=i; 
                   4750:     b[i]=sum; 
                   4751:   } 
                   4752:   for (i=n;i>=1;i--) { 
                   4753:     sum=b[i]; 
                   4754:     for (j=i+1;j<=n;j++) sum -= a[i][j]*b[j]; 
                   4755:     b[i]=sum/a[i][i]; 
                   4756:   } 
                   4757: } 
                   4758: 
                   4759: void pstamp(FILE *fichier)
                   4760: {
1.196     brouard  4761:   fprintf(fichier,"# %s.%s\n#IMaCh version %s, %s\n#%s\n# %s", optionfilefiname,optionfilext,version,copyright, fullversion, strstart);
1.126     brouard  4762: }
                   4763: 
1.297     brouard  4764: void date2dmy(double date,double *day, double *month, double *year){
                   4765:   double yp=0., yp1=0., yp2=0.;
                   4766:   
                   4767:   yp1=modf(date,&yp);/* extracts integral of date in yp  and
                   4768:                        fractional in yp1 */
                   4769:   *year=yp;
                   4770:   yp2=modf((yp1*12),&yp);
                   4771:   *month=yp;
                   4772:   yp1=modf((yp2*30.5),&yp);
                   4773:   *day=yp;
                   4774:   if(*day==0) *day=1;
                   4775:   if(*month==0) *month=1;
                   4776: }
                   4777: 
1.253     brouard  4778: 
                   4779: 
1.126     brouard  4780: /************ Frequencies ********************/
1.251     brouard  4781: void  freqsummary(char fileres[], double p[], double pstart[], int iagemin, int iagemax, int **s, double **agev, int nlstate, int imx, \
1.226     brouard  4782:                  int *Tvaraff, int *invalidvarcomb, int **nbcode, int *ncodemax,double **mint,double **anint, char strstart[], \
                   4783:                  int firstpass,  int lastpass, int stepm, int weightopt, char model[])
1.250     brouard  4784: {  /* Some frequencies as well as proposing some starting values */
1.226     brouard  4785:   
1.265     brouard  4786:   int i, m, jk, j1, bool, z1,j, nj, nl, k, iv, jj=0, s1=1, s2=1;
1.226     brouard  4787:   int iind=0, iage=0;
                   4788:   int mi; /* Effective wave */
                   4789:   int first;
                   4790:   double ***freq; /* Frequencies */
1.268     brouard  4791:   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 */
                   4792:   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  4793:   double *meanq, *stdq, *idq;
1.226     brouard  4794:   double **meanqt;
                   4795:   double *pp, **prop, *posprop, *pospropt;
                   4796:   double pos=0., posproptt=0., pospropta=0., k2, dateintsum=0,k2cpt=0;
                   4797:   char fileresp[FILENAMELENGTH], fileresphtm[FILENAMELENGTH], fileresphtmfr[FILENAMELENGTH];
                   4798:   double agebegin, ageend;
                   4799:     
                   4800:   pp=vector(1,nlstate);
1.251     brouard  4801:   prop=matrix(1,nlstate,iagemin-AGEMARGE,iagemax+4+AGEMARGE); 
1.226     brouard  4802:   posprop=vector(1,nlstate); /* Counting the number of transition starting from a live state per age */ 
                   4803:   pospropt=vector(1,nlstate); /* Counting the number of transition starting from a live state */ 
                   4804:   /* prop=matrix(1,nlstate,iagemin,iagemax+3); */
                   4805:   meanq=vector(1,nqfveff); /* Number of Quantitative Fixed Variables Effective */
1.284     brouard  4806:   stdq=vector(1,nqfveff); /* Number of Quantitative Fixed Variables Effective */
1.283     brouard  4807:   idq=vector(1,nqfveff); /* Number of Quantitative Fixed Variables Effective */
1.226     brouard  4808:   meanqt=matrix(1,lastpass,1,nqtveff);
                   4809:   strcpy(fileresp,"P_");
                   4810:   strcat(fileresp,fileresu);
                   4811:   /*strcat(fileresphtm,fileresu);*/
                   4812:   if((ficresp=fopen(fileresp,"w"))==NULL) {
                   4813:     printf("Problem with prevalence resultfile: %s\n", fileresp);
                   4814:     fprintf(ficlog,"Problem with prevalence resultfile: %s\n", fileresp);
                   4815:     exit(0);
                   4816:   }
1.240     brouard  4817:   
1.226     brouard  4818:   strcpy(fileresphtm,subdirfext(optionfilefiname,"PHTM_",".htm"));
                   4819:   if((ficresphtm=fopen(fileresphtm,"w"))==NULL) {
                   4820:     printf("Problem with prevalence HTM resultfile '%s' with errno='%s'\n",fileresphtm,strerror(errno));
                   4821:     fprintf(ficlog,"Problem with prevalence HTM resultfile '%s' with errno='%s'\n",fileresphtm,strerror(errno));
                   4822:     fflush(ficlog);
                   4823:     exit(70); 
                   4824:   }
                   4825:   else{
                   4826:     fprintf(ficresphtm,"<html><head>\n<title>IMaCh PHTM_ %s</title></head>\n <body><font size=\"2\">%s <br> %s</font> \
1.240     brouard  4827: <hr size=\"2\" color=\"#EC5E5E\"> \n                                   \
1.214     brouard  4828: Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=1+age+%s<br>\n",\
1.226     brouard  4829:            fileresphtm,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model);
                   4830:   }
1.319     brouard  4831:   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  4832:   
1.226     brouard  4833:   strcpy(fileresphtmfr,subdirfext(optionfilefiname,"PHTMFR_",".htm"));
                   4834:   if((ficresphtmfr=fopen(fileresphtmfr,"w"))==NULL) {
                   4835:     printf("Problem with frequency table HTM resultfile '%s' with errno='%s'\n",fileresphtmfr,strerror(errno));
                   4836:     fprintf(ficlog,"Problem with frequency table HTM resultfile '%s' with errno='%s'\n",fileresphtmfr,strerror(errno));
                   4837:     fflush(ficlog);
                   4838:     exit(70); 
1.240     brouard  4839:   } else{
1.226     brouard  4840:     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  4841: ,<hr size=\"2\" color=\"#EC5E5E\"> \n                                  \
1.214     brouard  4842: Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=1+age+%s<br>\n",\
1.226     brouard  4843:            fileresphtmfr,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model);
                   4844:   }
1.319     brouard  4845:   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  4846:   
1.253     brouard  4847:   y= vector(iagemin-AGEMARGE,iagemax+4+AGEMARGE);
                   4848:   x= vector(iagemin-AGEMARGE,iagemax+4+AGEMARGE);
1.251     brouard  4849:   freq= ma3x(-5,nlstate+ndeath,-5,nlstate+ndeath,iagemin-AGEMARGE,iagemax+4+AGEMARGE);
1.226     brouard  4850:   j1=0;
1.126     brouard  4851:   
1.227     brouard  4852:   /* j=ncoveff;  /\* Only fixed dummy covariates *\/ */
                   4853:   j=cptcoveff;  /* Only dummy covariates of the model */
1.330   ! brouard  4854:   /* j=cptcovn;  /\* Only dummy covariates of the model *\/ */
1.226     brouard  4855:   if (cptcovn<1) {j=1;ncodemax[1]=1;}
1.240     brouard  4856:   
                   4857:   
1.226     brouard  4858:   /* Detects if a combination j1 is empty: for a multinomial variable like 3 education levels:
                   4859:      reference=low_education V1=0,V2=0
                   4860:      med_educ                V1=1 V2=0, 
                   4861:      high_educ               V1=0 V2=1
1.330   ! brouard  4862:      Then V1=1 and V2=1 is a noisy combination that we want to exclude for the list 2**cptcovn 
1.226     brouard  4863:   */
1.249     brouard  4864:   dateintsum=0;
                   4865:   k2cpt=0;
                   4866: 
1.253     brouard  4867:   if(cptcoveff == 0 )
1.265     brouard  4868:     nl=1;  /* Constant and age model only */
1.253     brouard  4869:   else
                   4870:     nl=2;
1.265     brouard  4871: 
                   4872:   /* if a constant only model, one pass to compute frequency tables and to write it on ficresp */
                   4873:   /* Loop on nj=1 or 2 if dummy covariates j!=0
1.330   ! brouard  4874:    *   Loop on j1(1 to 2**cptcovn) covariate combination
1.265     brouard  4875:    *     freq[s1][s2][iage] =0.
                   4876:    *     Loop on iind
                   4877:    *       ++freq[s1][s2][iage] weighted
                   4878:    *     end iind
                   4879:    *     if covariate and j!0
                   4880:    *       headers Variable on one line
                   4881:    *     endif cov j!=0
                   4882:    *     header of frequency table by age
                   4883:    *     Loop on age
                   4884:    *       pp[s1]+=freq[s1][s2][iage] weighted
                   4885:    *       pos+=freq[s1][s2][iage] weighted
                   4886:    *       Loop on s1 initial state
                   4887:    *         fprintf(ficresp
                   4888:    *       end s1
                   4889:    *     end age
                   4890:    *     if j!=0 computes starting values
                   4891:    *     end compute starting values
                   4892:    *   end j1
                   4893:    * end nl 
                   4894:    */
1.253     brouard  4895:   for (nj = 1; nj <= nl; nj++){   /* nj= 1 constant model, nl number of loops. */
                   4896:     if(nj==1)
                   4897:       j=0;  /* First pass for the constant */
1.265     brouard  4898:     else{
1.330   ! brouard  4899:       j=cptcovs; /* Other passes for the covariate values */
1.265     brouard  4900:     }
1.251     brouard  4901:     first=1;
1.265     brouard  4902:     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  4903:       posproptt=0.;
1.330   ! brouard  4904:       /*printf("cptcovn=%d Tvaraff=%d", cptcovn,Tvaraff[1]);
1.251     brouard  4905:        scanf("%d", i);*/
                   4906:       for (i=-5; i<=nlstate+ndeath; i++)  
1.265     brouard  4907:        for (s2=-5; s2<=nlstate+ndeath; s2++)  
1.251     brouard  4908:          for(m=iagemin; m <= iagemax+3; m++)
1.265     brouard  4909:            freq[i][s2][m]=0;
1.251     brouard  4910:       
                   4911:       for (i=1; i<=nlstate; i++)  {
1.240     brouard  4912:        for(m=iagemin; m <= iagemax+3; m++)
1.251     brouard  4913:          prop[i][m]=0;
                   4914:        posprop[i]=0;
                   4915:        pospropt[i]=0;
                   4916:       }
1.283     brouard  4917:       for (z1=1; z1<= nqfveff; z1++) { /* zeroing for each combination j1 as well as for the total */
1.284     brouard  4918:         idq[z1]=0.;
                   4919:         meanq[z1]=0.;
                   4920:         stdq[z1]=0.;
1.283     brouard  4921:       }
                   4922:       /* for (z1=1; z1<= nqtveff; z1++) { */
1.251     brouard  4923:       /*   for(m=1;m<=lastpass;m++){ */
1.283     brouard  4924:       /*         meanqt[m][z1]=0.; */
                   4925:       /*       } */
                   4926:       /* }       */
1.251     brouard  4927:       /* dateintsum=0; */
                   4928:       /* k2cpt=0; */
                   4929:       
1.265     brouard  4930:       /* For that combination of covariates j1 (V4=1 V3=0 for example), we count and print the frequencies in one pass */
1.251     brouard  4931:       for (iind=1; iind<=imx; iind++) { /* For each individual iind */
                   4932:        bool=1;
                   4933:        if(j !=0){
                   4934:          if(anyvaryingduminmodel==0){ /* If All fixed covariates */
1.330   ! brouard  4935:            if (cptcovn >0) { /* Filter is here: Must be looked at for model=V1+V2+V3+V4 */
        !          4936:              for (z1=1; z1<=cptcovn; z1++) { /* loops on covariates in the model */
1.251     brouard  4937:                /* if(Tvaraff[z1] ==-20){ */
                   4938:                /*       /\* sumnew+=cotvar[mw[mi][iind]][z1][iind]; *\/ */
                   4939:                /* }else  if(Tvaraff[z1] ==-10){ */
                   4940:                /*       /\* sumnew+=coqvar[z1][iind]; *\/ */
1.330   ! brouard  4941:                /* }else  */ /* TODO TODO codtabm(j1,z1) or codtabm(j1,Tvaraff[z1]]z1)*/
        !          4942:                if (covar[Tvaraff[z1]][iind]!= nbcode[Tvaraff[z1]][codtabm(j1,Tvaraff[z1])]){ /* for combination j1 of covariates */
1.265     brouard  4943:                  /* Tests if the value of the covariate z1 for this individual iind responded to combination j1 (V4=1 V3=0) */
1.251     brouard  4944:                  bool=0; /* bool should be equal to 1 to be selected, one covariate value failed */
                   4945:                  /* 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", 
                   4946:                     bool,i,z1, z1, Tvaraff[z1],i,covar[Tvaraff[z1]][i],j1,z1,codtabm(j1,z1),
                   4947:                     j1,z1,nbcode[Tvaraff[z1]][codtabm(j1,z1)],j1);*/
                   4948:                  /* For j1=7 in V1+V2+V3+V4 = 0 1 1 0 and codtabm(7,3)=1 and nbcde[3][?]=1*/
                   4949:                } /* Onlyf fixed */
                   4950:              } /* end z1 */
                   4951:            } /* cptcovn > 0 */
                   4952:          } /* end any */
                   4953:        }/* end j==0 */
1.265     brouard  4954:        if (bool==1){ /* We selected an individual iind satisfying combination j1 (V4=1 V3=0) or all fixed covariates */
1.251     brouard  4955:          /* for(m=firstpass; m<=lastpass; m++){ */
1.284     brouard  4956:          for(mi=1; mi<wav[iind];mi++){ /* For each wave */
1.251     brouard  4957:            m=mw[mi][iind];
                   4958:            if(j!=0){
                   4959:              if(anyvaryingduminmodel==1){ /* Some are varying covariates */
1.330   ! brouard  4960:                for (z1=1; z1<=cptcovn; z1++) {
1.251     brouard  4961:                  if( Fixed[Tmodelind[z1]]==1){
                   4962:                    iv= Tvar[Tmodelind[z1]]-ncovcol-nqv;
1.330   ! brouard  4963:                    if (cotvar[m][iv][iind]!= nbcode[Tvaraff[z1]][codtabm(j1,Tvaraff[z1])]) /* iv=1 to ntv, right modality. If covariate's 
1.251     brouard  4964:                                                                                      value is -1, we don't select. It differs from the 
                   4965:                                                                                      constant and age model which counts them. */
                   4966:                      bool=0; /* not selected */
                   4967:                  }else if( Fixed[Tmodelind[z1]]== 0) { /* fixed */
1.330   ! brouard  4968:                    if (covar[Tvaraff[z1]][iind]!= nbcode[Tvaraff[z1]][codtabm(j1,Tvaraff[z1])]) {
1.251     brouard  4969:                      bool=0;
                   4970:                    }
                   4971:                  }
                   4972:                }
                   4973:              }/* Some are varying covariates, we tried to speed up if all fixed covariates in the model, avoiding waves loop  */
                   4974:            } /* end j==0 */
                   4975:            /* bool =0 we keep that guy which corresponds to the combination of dummy values */
1.284     brouard  4976:            if(bool==1){ /*Selected */
1.251     brouard  4977:              /* dh[m][iind] or dh[mw[mi][iind]][iind] is the delay between two effective (mi) waves m=mw[mi][iind]
                   4978:                 and mw[mi+1][iind]. dh depends on stepm. */
                   4979:              agebegin=agev[m][iind]; /* Age at beginning of wave before transition*/
                   4980:              ageend=agev[m][iind]+(dh[m][iind])*stepm/YEARM; /* Age at end of wave and transition */
                   4981:              if(m >=firstpass && m <=lastpass){
                   4982:                k2=anint[m][iind]+(mint[m][iind]/12.);
                   4983:                /*if ((k2>=dateprev1) && (k2<=dateprev2)) {*/
                   4984:                if(agev[m][iind]==0) agev[m][iind]=iagemax+1;  /* All ages equal to 0 are in iagemax+1 */
                   4985:                if(agev[m][iind]==1) agev[m][iind]=iagemax+2;  /* All ages equal to 1 are in iagemax+2 */
                   4986:                if (s[m][iind]>0 && s[m][iind]<=nlstate)  /* If status at wave m is known and a live state */
                   4987:                  prop[s[m][iind]][(int)agev[m][iind]] += weight[iind];  /* At age of beginning of transition, where status is known */
                   4988:                if (m<lastpass) {
                   4989:                  /* if(s[m][iind]==4 && s[m+1][iind]==4) */
                   4990:                  /*   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]); */
                   4991:                  if(s[m][iind]==-1)
                   4992:                    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.));
                   4993:                  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  4994:                  for (z1=1; z1<= nqfveff; z1++) { /* Quantitative variables, calculating mean on known values only */
                   4995:                    if(!isnan(covar[ncovcol+z1][iind])){
                   4996:                        idq[z1]=idq[z1]+weight[iind];
                   4997:                        meanq[z1]+=covar[ncovcol+z1][iind]*weight[iind];  /* Computes mean of quantitative with selected filter */
                   4998:                        /* stdq[z1]+=covar[ncovcol+z1][iind]*covar[ncovcol+z1][iind]*weight[iind]*weight[iind]; *//*error*/
                   4999:                        stdq[z1]+=covar[ncovcol+z1][iind]*covar[ncovcol+z1][iind]*weight[iind]; /* *weight[iind];*/  /* Computes mean of quantitative with selected filter */
                   5000:                    }
1.284     brouard  5001:                  }
1.251     brouard  5002:                  /* if((int)agev[m][iind] == 55) */
                   5003:                  /*   printf("j=%d, j1=%d Age %d, iind=%d, num=%09ld m=%d\n",j,j1,(int)agev[m][iind],iind, num[iind],m); */
                   5004:                  /* freq[s[m][iind]][s[m+1][iind]][(int)((agebegin+ageend)/2.)] += weight[iind]; */
                   5005:                  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  5006:                }
1.251     brouard  5007:              } /* end if between passes */  
                   5008:              if ((agev[m][iind]>1) && (agev[m][iind]< (iagemax+3)) && (anint[m][iind]!=9999) && (mint[m][iind]!=99) && (j==0)) {
                   5009:                dateintsum=dateintsum+k2; /* on all covariates ?*/
                   5010:                k2cpt++;
                   5011:                /* printf("iind=%ld dateintmean = %lf dateintsum=%lf k2cpt=%lf k2=%lf\n",iind, dateintsum/k2cpt, dateintsum,k2cpt, k2); */
1.234     brouard  5012:              }
1.251     brouard  5013:            }else{
                   5014:              bool=1;
                   5015:            }/* end bool 2 */
                   5016:          } /* end m */
1.284     brouard  5017:          /* for (z1=1; z1<= nqfveff; z1++) { /\* Quantitative variables, calculating mean *\/ */
                   5018:          /*   idq[z1]=idq[z1]+weight[iind]; */
                   5019:          /*   meanq[z1]+=covar[ncovcol+z1][iind]*weight[iind];  /\* Computes mean of quantitative with selected filter *\/ */
                   5020:          /*   stdq[z1]+=covar[ncovcol+z1][iind]*covar[ncovcol+z1][iind]*weight[iind]*weight[iind]; /\* *weight[iind];*\/  /\* Computes mean of quantitative with selected filter *\/ */
                   5021:          /* } */
1.251     brouard  5022:        } /* end bool */
                   5023:       } /* end iind = 1 to imx */
1.319     brouard  5024:       /* prop[s][age] is fed for any initial and valid live state as well as
1.251     brouard  5025:         freq[s1][s2][age] at single age of beginning the transition, for a combination j1 */
                   5026:       
                   5027:       
                   5028:       /*      fprintf(ficresp, "#Count between %.lf/%.lf/%.lf and %.lf/%.lf/%.lf\n",jprev1, mprev1,anprev1,jprev2, mprev2,anprev2);*/
1.330   ! brouard  5029:       if(cptcovn==0 && nj==1) /* no covariate and first pass */
1.265     brouard  5030:         pstamp(ficresp);
1.330   ! brouard  5031:       if  (cptcovn>0 && j!=0){
1.265     brouard  5032:         pstamp(ficresp);
1.251     brouard  5033:        printf( "\n#********** Variable "); 
                   5034:        fprintf(ficresp, "\n#********** Variable "); 
                   5035:        fprintf(ficresphtm, "\n<br/><br/><h3>********** Variable "); 
                   5036:        fprintf(ficresphtmfr, "\n<br/><br/><h3>********** Variable "); 
                   5037:        fprintf(ficlog, "\n#********** Variable "); 
1.330   ! brouard  5038:        for (z1=1; z1<=cptcovs; z1++){
1.251     brouard  5039:          if(!FixedV[Tvaraff[z1]]){
1.330   ! brouard  5040:            printf( "V%d(fixed)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]);
        !          5041:            fprintf(ficresp, "V%d(fixed)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]);
        !          5042:            fprintf(ficresphtm, "V%d(fixed)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]);
        !          5043:            fprintf(ficresphtmfr, "V%d(fixed)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]);
        !          5044:            fprintf(ficlog, "V%d(fixed)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]);
1.250     brouard  5045:          }else{
1.330   ! brouard  5046:            printf( "V%d(varying)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]);
        !          5047:            fprintf(ficresp, "V%d(varying)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]);
        !          5048:            fprintf(ficresphtm, "V%d(varying)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]);
        !          5049:            fprintf(ficresphtmfr, "V%d(varying)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]);
        !          5050:            fprintf(ficlog, "V%d(varying)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]);
1.251     brouard  5051:          }
                   5052:        }
                   5053:        printf( "**********\n#");
                   5054:        fprintf(ficresp, "**********\n#");
                   5055:        fprintf(ficresphtm, "**********</h3>\n");
                   5056:        fprintf(ficresphtmfr, "**********</h3>\n");
                   5057:        fprintf(ficlog, "**********\n");
                   5058:       }
1.284     brouard  5059:       /*
                   5060:        Printing means of quantitative variables if any
                   5061:       */
                   5062:       for (z1=1; z1<= nqfveff; z1++) {
1.311     brouard  5063:        fprintf(ficlog,"Mean of fixed quantitative variable V%d on %.3g (weighted) individuals sum=%f", ncovcol+z1, idq[z1], meanq[z1]);
1.312     brouard  5064:        fprintf(ficlog,", mean=%.3g\n",meanq[z1]/idq[z1]);
1.284     brouard  5065:        if(weightopt==1){
                   5066:          printf(" Weighted mean and standard deviation of");
                   5067:          fprintf(ficlog," Weighted mean and standard deviation of");
                   5068:          fprintf(ficresphtmfr," Weighted mean and standard deviation of");
                   5069:        }
1.311     brouard  5070:        /* mu = \frac{w x}{\sum w}
                   5071:            var = \frac{\sum w (x-mu)^2}{\sum w} = \frac{w x^2}{\sum w} - mu^2 
                   5072:        */
                   5073:        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]));
                   5074:        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]));
                   5075:        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  5076:       }
                   5077:       /* for (z1=1; z1<= nqtveff; z1++) { */
                   5078:       /*       for(m=1;m<=lastpass;m++){ */
                   5079:       /*         fprintf(ficresphtmfr,"V quantitative id %d, pass id=%d, mean=%f<p>\n", z1, m, meanqt[m][z1]); */
                   5080:       /*   } */
                   5081:       /* } */
1.283     brouard  5082: 
1.251     brouard  5083:       fprintf(ficresphtm,"<table style=\"text-align:center; border: 1px solid\">");
1.330   ! brouard  5084:       if((cptcovn==0 && nj==1)|| nj==2 ) /* no covariate and first pass */
1.265     brouard  5085:         fprintf(ficresp, " Age");
1.330   ! brouard  5086:       if(nj==2) for (z1=1; z1<=cptcovn; z1++) fprintf(ficresp, " V%d=%d",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,Tvaraff[z1])]);
1.251     brouard  5087:       for(i=1; i<=nlstate;i++) {
1.330   ! brouard  5088:        if((cptcovn==0 && nj==1)|| nj==2 ) fprintf(ficresp," Prev(%d)  N(%d)  N  ",i,i);
1.251     brouard  5089:        fprintf(ficresphtm, "<th>Age</th><th>Prev(%d)</th><th>N(%d)</th><th>N</th>",i,i);
                   5090:       }
1.330   ! brouard  5091:       if((cptcovn==0 && nj==1)|| nj==2 ) fprintf(ficresp, "\n");
1.251     brouard  5092:       fprintf(ficresphtm, "\n");
                   5093:       
                   5094:       /* Header of frequency table by age */
                   5095:       fprintf(ficresphtmfr,"<table style=\"text-align:center; border: 1px solid\">");
                   5096:       fprintf(ficresphtmfr,"<th>Age</th> ");
1.265     brouard  5097:       for(s2=-1; s2 <=nlstate+ndeath; s2++){
1.251     brouard  5098:        for(m=-1; m <=nlstate+ndeath; m++){
1.265     brouard  5099:          if(s2!=0 && m!=0)
                   5100:            fprintf(ficresphtmfr,"<th>%d%d</th> ",s2,m);
1.240     brouard  5101:        }
1.226     brouard  5102:       }
1.251     brouard  5103:       fprintf(ficresphtmfr, "\n");
                   5104:     
                   5105:       /* For each age */
                   5106:       for(iage=iagemin; iage <= iagemax+3; iage++){
                   5107:        fprintf(ficresphtm,"<tr>");
                   5108:        if(iage==iagemax+1){
                   5109:          fprintf(ficlog,"1");
                   5110:          fprintf(ficresphtmfr,"<tr><th>0</th> ");
                   5111:        }else if(iage==iagemax+2){
                   5112:          fprintf(ficlog,"0");
                   5113:          fprintf(ficresphtmfr,"<tr><th>Unknown</th> ");
                   5114:        }else if(iage==iagemax+3){
                   5115:          fprintf(ficlog,"Total");
                   5116:          fprintf(ficresphtmfr,"<tr><th>Total</th> ");
                   5117:        }else{
1.240     brouard  5118:          if(first==1){
1.251     brouard  5119:            first=0;
                   5120:            printf("See log file for details...\n");
                   5121:          }
                   5122:          fprintf(ficresphtmfr,"<tr><th>%d</th> ",iage);
                   5123:          fprintf(ficlog,"Age %d", iage);
                   5124:        }
1.265     brouard  5125:        for(s1=1; s1 <=nlstate ; s1++){
                   5126:          for(m=-1, pp[s1]=0; m <=nlstate+ndeath ; m++)
                   5127:            pp[s1] += freq[s1][m][iage]; 
1.251     brouard  5128:        }
1.265     brouard  5129:        for(s1=1; s1 <=nlstate ; s1++){
1.251     brouard  5130:          for(m=-1, pos=0; m <=0 ; m++)
1.265     brouard  5131:            pos += freq[s1][m][iage];
                   5132:          if(pp[s1]>=1.e-10){
1.251     brouard  5133:            if(first==1){
1.265     brouard  5134:              printf(" %d.=%.0f loss[%d]=%.1f%%",s1,pp[s1],s1,100*pos/pp[s1]);
1.251     brouard  5135:            }
1.265     brouard  5136:            fprintf(ficlog," %d.=%.0f loss[%d]=%.1f%%",s1,pp[s1],s1,100*pos/pp[s1]);
1.251     brouard  5137:          }else{
                   5138:            if(first==1)
1.265     brouard  5139:              printf(" %d.=%.0f loss[%d]=NaNQ%%",s1,pp[s1],s1);
                   5140:            fprintf(ficlog," %d.=%.0f loss[%d]=NaNQ%%",s1,pp[s1],s1);
1.240     brouard  5141:          }
                   5142:        }
                   5143:       
1.265     brouard  5144:        for(s1=1; s1 <=nlstate ; s1++){ 
                   5145:          /* posprop[s1]=0; */
                   5146:          for(m=0, pp[s1]=0; m <=nlstate+ndeath; m++)/* Summing on all ages */
                   5147:            pp[s1] += freq[s1][m][iage];
                   5148:        }       /* pp[s1] is the total number of transitions starting from state s1 and any ending status until this age */
                   5149:       
                   5150:        for(s1=1,pos=0, pospropta=0.; s1 <=nlstate ; s1++){
                   5151:          pos += pp[s1]; /* pos is the total number of transitions until this age */
                   5152:          posprop[s1] += prop[s1][iage]; /* prop is the number of transitions from a live state
                   5153:                                            from s1 at age iage prop[s[m][iind]][(int)agev[m][iind]] += weight[iind] */
                   5154:          pospropta += prop[s1][iage]; /* prop is the number of transitions from a live state
                   5155:                                          from s1 at age iage prop[s[m][iind]][(int)agev[m][iind]] += weight[iind] */
                   5156:        }
                   5157:        
                   5158:        /* Writing ficresp */
1.330   ! brouard  5159:        if(cptcovn==0 && nj==1){ /* no covariate and first pass */
1.265     brouard  5160:           if( iage <= iagemax){
                   5161:            fprintf(ficresp," %d",iage);
                   5162:           }
                   5163:         }else if( nj==2){
                   5164:           if( iage <= iagemax){
                   5165:            fprintf(ficresp," %d",iage);
1.330   ! brouard  5166:             for (z1=1; z1<=cptcovn; z1++) fprintf(ficresp, " %d %d",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,Tvaraff[z1])]);
1.265     brouard  5167:           }
1.240     brouard  5168:        }
1.265     brouard  5169:        for(s1=1; s1 <=nlstate ; s1++){
1.240     brouard  5170:          if(pos>=1.e-5){
1.251     brouard  5171:            if(first==1)
1.265     brouard  5172:              printf(" %d.=%.0f prev[%d]=%.1f%%",s1,pp[s1],s1,100*pp[s1]/pos);
                   5173:            fprintf(ficlog," %d.=%.0f prev[%d]=%.1f%%",s1,pp[s1],s1,100*pp[s1]/pos);
1.251     brouard  5174:          }else{
                   5175:            if(first==1)
1.265     brouard  5176:              printf(" %d.=%.0f prev[%d]=NaNQ%%",s1,pp[s1],s1);
                   5177:            fprintf(ficlog," %d.=%.0f prev[%d]=NaNQ%%",s1,pp[s1],s1);
1.251     brouard  5178:          }
                   5179:          if( iage <= iagemax){
                   5180:            if(pos>=1.e-5){
1.330   ! brouard  5181:              if(cptcovn==0 && nj==1){ /* no covariate and first pass */
1.265     brouard  5182:                fprintf(ficresp," %.5f %.0f %.0f",prop[s1][iage]/pospropta, prop[s1][iage],pospropta);
                   5183:               }else if( nj==2){
                   5184:                fprintf(ficresp," %.5f %.0f %.0f",prop[s1][iage]/pospropta, prop[s1][iage],pospropta);
                   5185:               }
                   5186:              fprintf(ficresphtm,"<th>%d</th><td>%.5f</td><td>%.0f</td><td>%.0f</td>",iage,prop[s1][iage]/pospropta, prop[s1][iage],pospropta);
                   5187:              /*probs[iage][s1][j1]= pp[s1]/pos;*/
                   5188:              /*printf("\niage=%d s1=%d j1=%d %.5f %.0f %.0f %f",iage,s1,j1,pp[s1]/pos, pp[s1],pos,probs[iage][s1][j1]);*/
                   5189:            } else{
1.330   ! brouard  5190:              if((cptcovn==0 && nj==1)|| nj==2 ) fprintf(ficresp," NaNq %.0f %.0f",prop[s1][iage],pospropta);
1.265     brouard  5191:              fprintf(ficresphtm,"<th>%d</th><td>NaNq</td><td>%.0f</td><td>%.0f</td>",iage, prop[s1][iage],pospropta);
1.251     brouard  5192:            }
1.240     brouard  5193:          }
1.265     brouard  5194:          pospropt[s1] +=posprop[s1];
                   5195:        } /* end loop s1 */
1.251     brouard  5196:        /* pospropt=0.; */
1.265     brouard  5197:        for(s1=-1; s1 <=nlstate+ndeath; s1++){
1.251     brouard  5198:          for(m=-1; m <=nlstate+ndeath; m++){
1.265     brouard  5199:            if(freq[s1][m][iage] !=0 ) { /* minimizing output */
1.251     brouard  5200:              if(first==1){
1.265     brouard  5201:                printf(" %d%d=%.0f",s1,m,freq[s1][m][iage]);
1.251     brouard  5202:              }
1.265     brouard  5203:              /* printf(" %d%d=%.0f",s1,m,freq[s1][m][iage]); */
                   5204:              fprintf(ficlog," %d%d=%.0f",s1,m,freq[s1][m][iage]);
1.251     brouard  5205:            }
1.265     brouard  5206:            if(s1!=0 && m!=0)
                   5207:              fprintf(ficresphtmfr,"<td>%.0f</td> ",freq[s1][m][iage]);
1.240     brouard  5208:          }
1.265     brouard  5209:        } /* end loop s1 */
1.251     brouard  5210:        posproptt=0.; 
1.265     brouard  5211:        for(s1=1; s1 <=nlstate; s1++){
                   5212:          posproptt += pospropt[s1];
1.251     brouard  5213:        }
                   5214:        fprintf(ficresphtmfr,"</tr>\n ");
1.265     brouard  5215:        fprintf(ficresphtm,"</tr>\n");
1.330   ! brouard  5216:        if((cptcovn==0 && nj==1)|| nj==2 ) {
1.265     brouard  5217:          if(iage <= iagemax)
                   5218:            fprintf(ficresp,"\n");
1.240     brouard  5219:        }
1.251     brouard  5220:        if(first==1)
                   5221:          printf("Others in log...\n");
                   5222:        fprintf(ficlog,"\n");
                   5223:       } /* end loop age iage */
1.265     brouard  5224:       
1.251     brouard  5225:       fprintf(ficresphtm,"<tr><th>Tot</th>");
1.265     brouard  5226:       for(s1=1; s1 <=nlstate ; s1++){
1.251     brouard  5227:        if(posproptt < 1.e-5){
1.265     brouard  5228:          fprintf(ficresphtm,"<td>Nanq</td><td>%.0f</td><td>%.0f</td>",pospropt[s1],posproptt); 
1.251     brouard  5229:        }else{
1.265     brouard  5230:          fprintf(ficresphtm,"<td>%.5f</td><td>%.0f</td><td>%.0f</td>",pospropt[s1]/posproptt,pospropt[s1],posproptt);  
1.240     brouard  5231:        }
1.226     brouard  5232:       }
1.251     brouard  5233:       fprintf(ficresphtm,"</tr>\n");
                   5234:       fprintf(ficresphtm,"</table>\n");
                   5235:       fprintf(ficresphtmfr,"</table>\n");
1.226     brouard  5236:       if(posproptt < 1.e-5){
1.251     brouard  5237:        fprintf(ficresphtm,"\n <p><b> This combination (%d) is not valid and no result will be produced</b></p>",j1);
                   5238:        fprintf(ficresphtmfr,"\n <p><b> This combination (%d) is not valid and no result will be produced</b></p>",j1);
1.260     brouard  5239:        fprintf(ficlog,"#  This combination (%d) is not valid and no result will be produced\n",j1);
                   5240:        printf("#  This combination (%d) is not valid and no result will be produced\n",j1);
1.251     brouard  5241:        invalidvarcomb[j1]=1;
1.226     brouard  5242:       }else{
1.251     brouard  5243:        fprintf(ficresphtm,"\n <p> This combination (%d) is valid and result will be produced.</p>",j1);
                   5244:        invalidvarcomb[j1]=0;
1.226     brouard  5245:       }
1.251     brouard  5246:       fprintf(ficresphtmfr,"</table>\n");
                   5247:       fprintf(ficlog,"\n");
                   5248:       if(j!=0){
                   5249:        printf("#Freqsummary: Starting values for combination j1=%d:\n", j1);
1.265     brouard  5250:        for(i=1,s1=1; i <=nlstate; i++){
1.251     brouard  5251:          for(k=1; k <=(nlstate+ndeath); k++){
                   5252:            if (k != i) {
1.265     brouard  5253:              for(jj=1; jj <=ncovmodel; jj++){ /* For counting s1 */
1.253     brouard  5254:                if(jj==1){  /* Constant case (in fact cste + age) */
1.251     brouard  5255:                  if(j1==1){ /* All dummy covariates to zero */
                   5256:                    freq[i][k][iagemax+4]=freq[i][k][iagemax+3]; /* Stores case 0 0 0 */
                   5257:                    freq[i][i][iagemax+4]=freq[i][i][iagemax+3]; /* Stores case 0 0 0 */
1.252     brouard  5258:                    printf("%d%d ",i,k);
                   5259:                    fprintf(ficlog,"%d%d ",i,k);
1.265     brouard  5260:                    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]));
                   5261:                    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]));
                   5262:                    pstart[s1]= log(freq[i][k][iagemax+3]/freq[i][i][iagemax+3]);
1.251     brouard  5263:                  }
1.253     brouard  5264:                }else if((j1==1) && (jj==2 || nagesqr==1)){ /* age or age*age parameter without covariate V4*age (to be done later) */
                   5265:                  for(iage=iagemin; iage <= iagemax+3; iage++){
                   5266:                    x[iage]= (double)iage;
                   5267:                    y[iage]= log(freq[i][k][iage]/freq[i][i][iage]);
1.265     brouard  5268:                    /* 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  5269:                  }
1.268     brouard  5270:                  /* Some are not finite, but linreg will ignore these ages */
                   5271:                  no=0;
1.253     brouard  5272:                  linreg(iagemin,iagemax,&no,x,y,&a,&b,&r, &sa, &sb ); /* y= a+b*x with standard errors */
1.265     brouard  5273:                  pstart[s1]=b;
                   5274:                  pstart[s1-1]=a;
1.252     brouard  5275:                }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 */ 
                   5276:                  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]);
                   5277:                  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  5278:                  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  5279:                  printf("%d%d ",i,k);
                   5280:                  fprintf(ficlog,"%d%d ",i,k);
1.265     brouard  5281:                  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  5282:                }else{ /* Other cases, like quantitative fixed or varying covariates */
                   5283:                  ;
                   5284:                }
                   5285:                /* printf("%12.7f )", param[i][jj][k]); */
                   5286:                /* fprintf(ficlog,"%12.7f )", param[i][jj][k]); */
1.265     brouard  5287:                s1++; 
1.251     brouard  5288:              } /* end jj */
                   5289:            } /* end k!= i */
                   5290:          } /* end k */
1.265     brouard  5291:        } /* end i, s1 */
1.251     brouard  5292:       } /* end j !=0 */
                   5293:     } /* end selected combination of covariate j1 */
                   5294:     if(j==0){ /* We can estimate starting values from the occurences in each case */
                   5295:       printf("#Freqsummary: Starting values for the constants:\n");
                   5296:       fprintf(ficlog,"\n");
1.265     brouard  5297:       for(i=1,s1=1; i <=nlstate; i++){
1.251     brouard  5298:        for(k=1; k <=(nlstate+ndeath); k++){
                   5299:          if (k != i) {
                   5300:            printf("%d%d ",i,k);
                   5301:            fprintf(ficlog,"%d%d ",i,k);
                   5302:            for(jj=1; jj <=ncovmodel; jj++){
1.265     brouard  5303:              pstart[s1]=p[s1]; /* Setting pstart to p values by default */
1.253     brouard  5304:              if(jj==1){ /* Age has to be done */
1.265     brouard  5305:                pstart[s1]= log(freq[i][k][iagemax+3]/freq[i][i][iagemax+3]);
                   5306:                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]));
                   5307:                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  5308:              }
                   5309:              /* printf("%12.7f )", param[i][jj][k]); */
                   5310:              /* fprintf(ficlog,"%12.7f )", param[i][jj][k]); */
1.265     brouard  5311:              s1++; 
1.250     brouard  5312:            }
1.251     brouard  5313:            printf("\n");
                   5314:            fprintf(ficlog,"\n");
1.250     brouard  5315:          }
                   5316:        }
1.284     brouard  5317:       } /* end of state i */
1.251     brouard  5318:       printf("#Freqsummary\n");
                   5319:       fprintf(ficlog,"\n");
1.265     brouard  5320:       for(s1=-1; s1 <=nlstate+ndeath; s1++){
                   5321:        for(s2=-1; s2 <=nlstate+ndeath; s2++){
                   5322:          /* param[i]|j][k]= freq[s1][s2][iagemax+3] */
                   5323:          printf(" %d%d=%.0f",s1,s2,freq[s1][s2][iagemax+3]);
                   5324:          fprintf(ficlog," %d%d=%.0f",s1,s2,freq[s1][s2][iagemax+3]);
                   5325:          /* if(freq[s1][s2][iage] !=0 ) { /\* minimizing output *\/ */
                   5326:          /*   printf(" %d%d=%.0f",s1,s2,freq[s1][s2][iagemax+3]); */
                   5327:          /*   fprintf(ficlog," %d%d=%.0f",s1,s2,freq[s1][s2][iagemax+3]); */
1.251     brouard  5328:          /* } */
                   5329:        }
1.265     brouard  5330:       } /* end loop s1 */
1.251     brouard  5331:       
                   5332:       printf("\n");
                   5333:       fprintf(ficlog,"\n");
                   5334:     } /* end j=0 */
1.249     brouard  5335:   } /* end j */
1.252     brouard  5336: 
1.253     brouard  5337:   if(mle == -2){  /* We want to use these values as starting values */
1.252     brouard  5338:     for(i=1, jk=1; i <=nlstate; i++){
                   5339:       for(j=1; j <=nlstate+ndeath; j++){
                   5340:        if(j!=i){
                   5341:          /*ca[0]= k+'a'-1;ca[1]='\0';*/
                   5342:          printf("%1d%1d",i,j);
                   5343:          fprintf(ficparo,"%1d%1d",i,j);
                   5344:          for(k=1; k<=ncovmodel;k++){
                   5345:            /*    printf(" %lf",param[i][j][k]); */
                   5346:            /*    fprintf(ficparo," %lf",param[i][j][k]); */
                   5347:            p[jk]=pstart[jk];
                   5348:            printf(" %f ",pstart[jk]);
                   5349:            fprintf(ficparo," %f ",pstart[jk]);
                   5350:            jk++;
                   5351:          }
                   5352:          printf("\n");
                   5353:          fprintf(ficparo,"\n");
                   5354:        }
                   5355:       }
                   5356:     }
                   5357:   } /* end mle=-2 */
1.226     brouard  5358:   dateintmean=dateintsum/k2cpt; 
1.296     brouard  5359:   date2dmy(dateintmean,&jintmean,&mintmean,&aintmean);
1.240     brouard  5360:   
1.226     brouard  5361:   fclose(ficresp);
                   5362:   fclose(ficresphtm);
                   5363:   fclose(ficresphtmfr);
1.283     brouard  5364:   free_vector(idq,1,nqfveff);
1.226     brouard  5365:   free_vector(meanq,1,nqfveff);
1.284     brouard  5366:   free_vector(stdq,1,nqfveff);
1.226     brouard  5367:   free_matrix(meanqt,1,lastpass,1,nqtveff);
1.253     brouard  5368:   free_vector(x, iagemin-AGEMARGE, iagemax+4+AGEMARGE);
                   5369:   free_vector(y, iagemin-AGEMARGE, iagemax+4+AGEMARGE);
1.251     brouard  5370:   free_ma3x(freq,-5,nlstate+ndeath,-5,nlstate+ndeath, iagemin-AGEMARGE, iagemax+4+AGEMARGE);
1.226     brouard  5371:   free_vector(pospropt,1,nlstate);
                   5372:   free_vector(posprop,1,nlstate);
1.251     brouard  5373:   free_matrix(prop,1,nlstate,iagemin-AGEMARGE, iagemax+4+AGEMARGE);
1.226     brouard  5374:   free_vector(pp,1,nlstate);
                   5375:   /* End of freqsummary */
                   5376: }
1.126     brouard  5377: 
1.268     brouard  5378: /* Simple linear regression */
                   5379: int linreg(int ifi, int ila, int *no, const double x[], const double y[], double* a, double* b, double* r, double* sa, double * sb) {
                   5380: 
                   5381:   /* y=a+bx regression */
                   5382:   double   sumx = 0.0;                        /* sum of x                      */
                   5383:   double   sumx2 = 0.0;                       /* sum of x**2                   */
                   5384:   double   sumxy = 0.0;                       /* sum of x * y                  */
                   5385:   double   sumy = 0.0;                        /* sum of y                      */
                   5386:   double   sumy2 = 0.0;                       /* sum of y**2                   */
                   5387:   double   sume2 = 0.0;                       /* sum of square or residuals */
                   5388:   double yhat;
                   5389:   
                   5390:   double denom=0;
                   5391:   int i;
                   5392:   int ne=*no;
                   5393:   
                   5394:   for ( i=ifi, ne=0;i<=ila;i++) {
                   5395:     if(!isfinite(x[i]) || !isfinite(y[i])){
                   5396:       /* printf(" x[%d]=%f, y[%d]=%f\n",i,x[i],i,y[i]); */
                   5397:       continue;
                   5398:     }
                   5399:     ne=ne+1;
                   5400:     sumx  += x[i];       
                   5401:     sumx2 += x[i]*x[i];  
                   5402:     sumxy += x[i] * y[i];
                   5403:     sumy  += y[i];      
                   5404:     sumy2 += y[i]*y[i]; 
                   5405:     denom = (ne * sumx2 - sumx*sumx);
                   5406:     /* 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); */
                   5407:   } 
                   5408:   
                   5409:   denom = (ne * sumx2 - sumx*sumx);
                   5410:   if (denom == 0) {
                   5411:     // vertical, slope m is infinity
                   5412:     *b = INFINITY;
                   5413:     *a = 0;
                   5414:     if (r) *r = 0;
                   5415:     return 1;
                   5416:   }
                   5417:   
                   5418:   *b = (ne * sumxy  -  sumx * sumy) / denom;
                   5419:   *a = (sumy * sumx2  -  sumx * sumxy) / denom;
                   5420:   if (r!=NULL) {
                   5421:     *r = (sumxy - sumx * sumy / ne) /          /* compute correlation coeff     */
                   5422:       sqrt((sumx2 - sumx*sumx/ne) *
                   5423:           (sumy2 - sumy*sumy/ne));
                   5424:   }
                   5425:   *no=ne;
                   5426:   for ( i=ifi, ne=0;i<=ila;i++) {
                   5427:     if(!isfinite(x[i]) || !isfinite(y[i])){
                   5428:       /* printf(" x[%d]=%f, y[%d]=%f\n",i,x[i],i,y[i]); */
                   5429:       continue;
                   5430:     }
                   5431:     ne=ne+1;
                   5432:     yhat = y[i] - *a -*b* x[i];
                   5433:     sume2  += yhat * yhat ;       
                   5434:     
                   5435:     denom = (ne * sumx2 - sumx*sumx);
                   5436:     /* 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); */
                   5437:   } 
                   5438:   *sb = sqrt(sume2/(double)(ne-2)/(sumx2 - sumx * sumx /(double)ne));
                   5439:   *sa= *sb * sqrt(sumx2/ne);
                   5440:   
                   5441:   return 0; 
                   5442: }
                   5443: 
1.126     brouard  5444: /************ Prevalence ********************/
1.227     brouard  5445: 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)
                   5446: {  
                   5447:   /* Compute observed prevalence between dateprev1 and dateprev2 by counting the number of people
                   5448:      in each health status at the date of interview (if between dateprev1 and dateprev2).
                   5449:      We still use firstpass and lastpass as another selection.
                   5450:   */
1.126     brouard  5451:  
1.227     brouard  5452:   int i, m, jk, j1, bool, z1,j, iv;
                   5453:   int mi; /* Effective wave */
                   5454:   int iage;
                   5455:   double agebegin, ageend;
                   5456: 
                   5457:   double **prop;
                   5458:   double posprop; 
                   5459:   double  y2; /* in fractional years */
                   5460:   int iagemin, iagemax;
                   5461:   int first; /** to stop verbosity which is redirected to log file */
                   5462: 
                   5463:   iagemin= (int) agemin;
                   5464:   iagemax= (int) agemax;
                   5465:   /*pp=vector(1,nlstate);*/
1.251     brouard  5466:   prop=matrix(1,nlstate,iagemin-AGEMARGE,iagemax+4+AGEMARGE); 
1.227     brouard  5467:   /*  freq=ma3x(-1,nlstate+ndeath,-1,nlstate+ndeath,iagemin,iagemax+3);*/
                   5468:   j1=0;
1.222     brouard  5469:   
1.227     brouard  5470:   /*j=cptcoveff;*/
                   5471:   if (cptcovn<1) {j=1;ncodemax[1]=1;}
1.222     brouard  5472:   
1.288     brouard  5473:   first=0;
1.227     brouard  5474:   for(j1=1; j1<= (int) pow(2,cptcoveff);j1++){ /* For each combination of covariate */
                   5475:     for (i=1; i<=nlstate; i++)  
1.251     brouard  5476:       for(iage=iagemin-AGEMARGE; iage <= iagemax+4+AGEMARGE; iage++)
1.227     brouard  5477:        prop[i][iage]=0.0;
                   5478:     printf("Prevalence combination of varying and fixed dummies %d\n",j1);
                   5479:     /* fprintf(ficlog," V%d=%d ",Tvaraff[j1],nbcode[Tvaraff[j1]][codtabm(k,j1)]); */
                   5480:     fprintf(ficlog,"Prevalence combination of varying and fixed dummies %d\n",j1);
                   5481:     
                   5482:     for (i=1; i<=imx; i++) { /* Each individual */
                   5483:       bool=1;
                   5484:       /* for(m=firstpass; m<=lastpass; m++){/\* Other selection (we can limit to certain interviews*\/ */
                   5485:       for(mi=1; mi<wav[i];mi++){ /* For this wave too look where individual can be counted V4=0 V3=0 */
                   5486:        m=mw[mi][i];
                   5487:        /* Tmodelind[z1]=k is the position of the varying covariate in the model, but which # within 1 to ntv? */
                   5488:        /* Tvar[Tmodelind[z1]] is the n of Vn; n-ncovcol-nqv is the first time varying covariate or iv */
                   5489:        for (z1=1; z1<=cptcoveff; z1++){
                   5490:          if( Fixed[Tmodelind[z1]]==1){
                   5491:            iv= Tvar[Tmodelind[z1]]-ncovcol-nqv;
1.330   ! brouard  5492:            if (cotvar[m][iv][i]!= nbcode[Tvaraff[z1]][codtabm(j1,Tvaraff[z1])]) /* iv=1 to ntv, right modality */
1.227     brouard  5493:              bool=0;
                   5494:          }else if( Fixed[Tmodelind[z1]]== 0)  /* fixed */
1.330   ! brouard  5495:            if (covar[Tvaraff[z1]][i]!= nbcode[Tvaraff[z1]][codtabm(j1,Tvaraff[z1])]) {
1.227     brouard  5496:              bool=0;
                   5497:            }
                   5498:        }
                   5499:        if(bool==1){ /* Otherwise we skip that wave/person */
                   5500:          agebegin=agev[m][i]; /* Age at beginning of wave before transition*/
                   5501:          /* ageend=agev[m][i]+(dh[m][i])*stepm/YEARM; /\* Age at end of wave and transition *\/ */
                   5502:          if(m >=firstpass && m <=lastpass){
                   5503:            y2=anint[m][i]+(mint[m][i]/12.); /* Fractional date in year */
                   5504:            if ((y2>=dateprev1) && (y2<=dateprev2)) { /* Here is the main selection (fractional years) */
                   5505:              if(agev[m][i]==0) agev[m][i]=iagemax+1;
                   5506:              if(agev[m][i]==1) agev[m][i]=iagemax+2;
1.251     brouard  5507:              if((int)agev[m][i] <iagemin-AGEMARGE || (int)agev[m][i] >iagemax+4+AGEMARGE){
1.227     brouard  5508:                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); 
                   5509:                exit(1);
                   5510:              }
                   5511:              if (s[m][i]>0 && s[m][i]<=nlstate) { 
                   5512:                /*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]]);*/
                   5513:                prop[s[m][i]][(int)agev[m][i]] += weight[i];/* At age of beginning of transition, where status is known */
                   5514:                prop[s[m][i]][iagemax+3] += weight[i]; 
                   5515:              } /* end valid statuses */ 
                   5516:            } /* end selection of dates */
                   5517:          } /* end selection of waves */
                   5518:        } /* end bool */
                   5519:       } /* end wave */
                   5520:     } /* end individual */
                   5521:     for(i=iagemin; i <= iagemax+3; i++){  
                   5522:       for(jk=1,posprop=0; jk <=nlstate ; jk++) { 
                   5523:        posprop += prop[jk][i]; 
                   5524:       } 
                   5525:       
                   5526:       for(jk=1; jk <=nlstate ; jk++){      
                   5527:        if( i <=  iagemax){ 
                   5528:          if(posprop>=1.e-5){ 
                   5529:            probs[i][jk][j1]= prop[jk][i]/posprop;
                   5530:          } else{
1.288     brouard  5531:            if(!first){
                   5532:              first=1;
1.266     brouard  5533:              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]);
                   5534:            }else{
1.288     brouard  5535:              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  5536:            }
                   5537:          }
                   5538:        } 
                   5539:       }/* end jk */ 
                   5540:     }/* end i */ 
1.222     brouard  5541:      /*} *//* end i1 */
1.227     brouard  5542:   } /* end j1 */
1.222     brouard  5543:   
1.227     brouard  5544:   /*  free_ma3x(freq,-1,nlstate+ndeath,-1,nlstate+ndeath, iagemin, iagemax+3);*/
                   5545:   /*free_vector(pp,1,nlstate);*/
1.251     brouard  5546:   free_matrix(prop,1,nlstate, iagemin-AGEMARGE,iagemax+4+AGEMARGE);
1.227     brouard  5547: }  /* End of prevalence */
1.126     brouard  5548: 
                   5549: /************* Waves Concatenation ***************/
                   5550: 
                   5551: 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)
                   5552: {
1.298     brouard  5553:   /* 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  5554:      Death is a valid wave (if date is known).
                   5555:      mw[mi][i] is the mi (mi=1 to wav[i])  effective wave of individual i
                   5556:      dh[m][i] or dh[mw[mi][i]][i] is the delay between two effective waves m=mw[mi][i]
1.298     brouard  5557:      and mw[mi+1][i]. dh depends on stepm. s[m][i] exists for any wave from firstpass to lastpass
1.227     brouard  5558:   */
1.126     brouard  5559: 
1.224     brouard  5560:   int i=0, mi=0, m=0, mli=0;
1.126     brouard  5561:   /* int j, k=0,jk, ju, jl,jmin=1e+5, jmax=-1;
                   5562:      double sum=0., jmean=0.;*/
1.224     brouard  5563:   int first=0, firstwo=0, firsthree=0, firstfour=0, firstfiv=0;
1.126     brouard  5564:   int j, k=0,jk, ju, jl;
                   5565:   double sum=0.;
                   5566:   first=0;
1.214     brouard  5567:   firstwo=0;
1.217     brouard  5568:   firsthree=0;
1.218     brouard  5569:   firstfour=0;
1.164     brouard  5570:   jmin=100000;
1.126     brouard  5571:   jmax=-1;
                   5572:   jmean=0.;
1.224     brouard  5573: 
                   5574: /* Treating live states */
1.214     brouard  5575:   for(i=1; i<=imx; i++){  /* For simple cases and if state is death */
1.224     brouard  5576:     mi=0;  /* First valid wave */
1.227     brouard  5577:     mli=0; /* Last valid wave */
1.309     brouard  5578:     m=firstpass;  /* Loop on waves */
                   5579:     while(s[m][i] <= nlstate){  /* a live state or unknown state  */
1.227     brouard  5580:       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 */
                   5581:        mli=m-1;/* mw[++mi][i]=m-1; */
                   5582:       }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  5583:        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  5584:        mli=m;
1.224     brouard  5585:       } /* else might be a useless wave  -1 and mi is not incremented and mw[mi] not updated */
                   5586:       if(m < lastpass){ /* m < lastpass, standard case */
1.227     brouard  5587:        m++; /* mi gives the "effective" current wave, m the current wave, go to next wave by incrementing m */
1.216     brouard  5588:       }
1.309     brouard  5589:       else{ /* m = lastpass, eventual special issue with warning */
1.224     brouard  5590: #ifdef UNKNOWNSTATUSNOTCONTRIBUTING
1.227     brouard  5591:        break;
1.224     brouard  5592: #else
1.317     brouard  5593:        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  5594:          if(firsthree == 0){
1.302     brouard  5595:            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  5596:            firsthree=1;
1.317     brouard  5597:          }else if(firsthree >=1 && firsthree < 10){
                   5598:            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);
                   5599:            firsthree++;
                   5600:          }else if(firsthree == 10){
                   5601:            printf("Information, too many Information flags: no more reported to log either\n");
                   5602:            fprintf(ficlog,"Information, too many Information flags: no more reported to log either\n");
                   5603:            firsthree++;
                   5604:          }else{
                   5605:            firsthree++;
1.227     brouard  5606:          }
1.309     brouard  5607:          mw[++mi][i]=m; /* Valid transition with unknown status */
1.227     brouard  5608:          mli=m;
                   5609:        }
                   5610:        if(s[m][i]==-2){ /* Vital status is really unknown */
                   5611:          nbwarn++;
1.309     brouard  5612:          if((int)anint[m][i] == 9999){  /*  Has the vital status really been verified?not a transition */
1.227     brouard  5613:            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);
                   5614:            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);
                   5615:          }
                   5616:          break;
                   5617:        }
                   5618:        break;
1.224     brouard  5619: #endif
1.227     brouard  5620:       }/* End m >= lastpass */
1.126     brouard  5621:     }/* end while */
1.224     brouard  5622: 
1.227     brouard  5623:     /* 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  5624:     /* After last pass */
1.224     brouard  5625: /* Treating death states */
1.214     brouard  5626:     if (s[m][i] > nlstate){  /* In a death state */
1.227     brouard  5627:       /* if( mint[m][i]==mdc[m][i] && anint[m][i]==andc[m][i]){ /\* same date of death and date of interview *\/ */
                   5628:       /* } */
1.126     brouard  5629:       mi++;    /* Death is another wave */
                   5630:       /* if(mi==0)  never been interviewed correctly before death */
1.227     brouard  5631:       /* Only death is a correct wave */
1.126     brouard  5632:       mw[mi][i]=m;
1.257     brouard  5633:     } /* else not in a death state */
1.224     brouard  5634: #ifndef DISPATCHINGKNOWNDEATHAFTERLASTWAVE
1.257     brouard  5635:     else if ((int) andc[i] != 9999) {  /* Date of death is known */
1.218     brouard  5636:       if ((int)anint[m][i]!= 9999) { /* date of last interview is known */
1.309     brouard  5637:        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  5638:          nbwarn++;
                   5639:          if(firstfiv==0){
1.309     brouard  5640:            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  5641:            firstfiv=1;
                   5642:          }else{
1.309     brouard  5643:            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  5644:          }
1.309     brouard  5645:            s[m][i]=nlstate+1; /* Fixing the status as death. Be careful if multiple death states */
                   5646:        }else{ /* Month of Death occured afer last wave month, potential bias */
1.227     brouard  5647:          nberr++;
                   5648:          if(firstwo==0){
1.309     brouard  5649:            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  5650:            firstwo=1;
                   5651:          }
1.309     brouard  5652:          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  5653:        }
1.257     brouard  5654:       }else{ /* if date of interview is unknown */
1.227     brouard  5655:        /* death is known but not confirmed by death status at any wave */
                   5656:        if(firstfour==0){
1.309     brouard  5657:          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  5658:          firstfour=1;
                   5659:        }
1.309     brouard  5660:        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  5661:       }
1.224     brouard  5662:     } /* end if date of death is known */
                   5663: #endif
1.309     brouard  5664:     wav[i]=mi; /* mi should be the last effective wave (or mli),  */
                   5665:     /* wav[i]=mw[mi][i];   */
1.126     brouard  5666:     if(mi==0){
                   5667:       nbwarn++;
                   5668:       if(first==0){
1.227     brouard  5669:        printf("Warning! No valid information for individual %ld line=%d (skipped) and may be others, see log file\n",num[i],i);
                   5670:        first=1;
1.126     brouard  5671:       }
                   5672:       if(first==1){
1.227     brouard  5673:        fprintf(ficlog,"Warning! No valid information for individual %ld line=%d (skipped)\n",num[i],i);
1.126     brouard  5674:       }
                   5675:     } /* end mi==0 */
                   5676:   } /* End individuals */
1.214     brouard  5677:   /* wav and mw are no more changed */
1.223     brouard  5678:        
1.317     brouard  5679:   printf("Information, you have to check %d informations which haven't been logged!\n",firsthree);
                   5680:   fprintf(ficlog,"Information, you have to check %d informations which haven't been logged!\n",firsthree);
                   5681: 
                   5682: 
1.126     brouard  5683:   for(i=1; i<=imx; i++){
                   5684:     for(mi=1; mi<wav[i];mi++){
                   5685:       if (stepm <=0)
1.227     brouard  5686:        dh[mi][i]=1;
1.126     brouard  5687:       else{
1.260     brouard  5688:        if (s[mw[mi+1][i]][i] > nlstate) { /* A death, but what if date is unknown? */
1.227     brouard  5689:          if (agedc[i] < 2*AGESUP) {
                   5690:            j= rint(agedc[i]*12-agev[mw[mi][i]][i]*12); 
                   5691:            if(j==0) j=1;  /* Survives at least one month after exam */
                   5692:            else if(j<0){
                   5693:              nberr++;
                   5694:              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]);
                   5695:              j=1; /* Temporary Dangerous patch */
                   5696:              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);
                   5697:              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]);
                   5698:              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);
                   5699:            }
                   5700:            k=k+1;
                   5701:            if (j >= jmax){
                   5702:              jmax=j;
                   5703:              ijmax=i;
                   5704:            }
                   5705:            if (j <= jmin){
                   5706:              jmin=j;
                   5707:              ijmin=i;
                   5708:            }
                   5709:            sum=sum+j;
                   5710:            /*if (j<0) printf("j=%d num=%d \n",j,i);*/
                   5711:            /*    printf("%d %d %d %d\n", s[mw[mi][i]][i] ,s[mw[mi+1][i]][i],j,i);*/
                   5712:          }
                   5713:        }
                   5714:        else{
                   5715:          j= rint( (agev[mw[mi+1][i]][i]*12 - agev[mw[mi][i]][i]*12));
1.126     brouard  5716: /*       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  5717:                                        
1.227     brouard  5718:          k=k+1;
                   5719:          if (j >= jmax) {
                   5720:            jmax=j;
                   5721:            ijmax=i;
                   5722:          }
                   5723:          else if (j <= jmin){
                   5724:            jmin=j;
                   5725:            ijmin=i;
                   5726:          }
                   5727:          /*        if (j<10) printf("j=%d jmin=%d num=%d ",j,jmin,i); */
                   5728:          /*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]);*/
                   5729:          if(j<0){
                   5730:            nberr++;
                   5731:            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]);
                   5732:            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]);
                   5733:          }
                   5734:          sum=sum+j;
                   5735:        }
                   5736:        jk= j/stepm;
                   5737:        jl= j -jk*stepm;
                   5738:        ju= j -(jk+1)*stepm;
                   5739:        if(mle <=1){ /* only if we use a the linear-interpoloation pseudo-likelihood */
                   5740:          if(jl==0){
                   5741:            dh[mi][i]=jk;
                   5742:            bh[mi][i]=0;
                   5743:          }else{ /* We want a negative bias in order to only have interpolation ie
                   5744:                  * to avoid the price of an extra matrix product in likelihood */
                   5745:            dh[mi][i]=jk+1;
                   5746:            bh[mi][i]=ju;
                   5747:          }
                   5748:        }else{
                   5749:          if(jl <= -ju){
                   5750:            dh[mi][i]=jk;
                   5751:            bh[mi][i]=jl;       /* bias is positive if real duration
                   5752:                                 * is higher than the multiple of stepm and negative otherwise.
                   5753:                                 */
                   5754:          }
                   5755:          else{
                   5756:            dh[mi][i]=jk+1;
                   5757:            bh[mi][i]=ju;
                   5758:          }
                   5759:          if(dh[mi][i]==0){
                   5760:            dh[mi][i]=1; /* At least one step */
                   5761:            bh[mi][i]=ju; /* At least one step */
                   5762:            /*  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);*/
                   5763:          }
                   5764:        } /* end if mle */
1.126     brouard  5765:       }
                   5766:     } /* end wave */
                   5767:   }
                   5768:   jmean=sum/k;
                   5769:   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  5770:   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  5771: }
1.126     brouard  5772: 
                   5773: /*********** Tricode ****************************/
1.220     brouard  5774:  void tricode(int *cptcov, int *Tvar, int **nbcode, int imx, int *Ndum)
1.242     brouard  5775:  {
                   5776:    /**< Uses cptcovn+2*cptcovprod as the number of covariates */
                   5777:    /*    Tvar[i]=atoi(stre);  find 'n' in Vn and stores in Tvar. If model=V2+V1 Tvar[1]=2 and Tvar[2]=1 
                   5778:     * Boring subroutine which should only output nbcode[Tvar[j]][k]
                   5779:     * Tvar[5] in V2+V1+V3*age+V2*V4 is 4 (V4) even it is a time varying or quantitative variable
                   5780:     * nbcode[Tvar[5]][1]= nbcode[4][1]=0, nbcode[4][2]=1 (usually);
                   5781:     */
1.130     brouard  5782: 
1.242     brouard  5783:    int ij=1, k=0, j=0, i=0, maxncov=NCOVMAX;
                   5784:    int modmaxcovj=0; /* Modality max of covariates j */
                   5785:    int cptcode=0; /* Modality max of covariates j */
                   5786:    int modmincovj=0; /* Modality min of covariates j */
1.145     brouard  5787: 
                   5788: 
1.242     brouard  5789:    /* cptcoveff=0;  */
                   5790:    /* *cptcov=0; */
1.126     brouard  5791:  
1.242     brouard  5792:    for (k=1; k <= maxncov; k++) ncodemax[k]=0; /* Horrible constant again replaced by NCOVMAX */
1.285     brouard  5793:    for (k=1; k <= maxncov; k++)
                   5794:      for(j=1; j<=2; j++)
                   5795:        nbcode[k][j]=0; /* Valgrind */
1.126     brouard  5796: 
1.242     brouard  5797:    /* Loop on covariates without age and products and no quantitative variable */
                   5798:    for (k=1; k<=cptcovt; k++) { /* From model V1 + V2*age + V3 + V3*V4 keeps V1 + V3 = 2 only */
                   5799:      for (j=-1; (j < maxncov); j++) Ndum[j]=0;
                   5800:      if(Dummy[k]==0 && Typevar[k] !=1){ /* Dummy covariate and not age product */ 
                   5801:        switch(Fixed[k]) {
                   5802:        case 0: /* Testing on fixed dummy covariate, simple or product of fixed */
1.311     brouard  5803:         modmaxcovj=0;
                   5804:         modmincovj=0;
1.242     brouard  5805:         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*/
                   5806:           ij=(int)(covar[Tvar[k]][i]);
                   5807:           /* ij=0 or 1 or -1. Value of the covariate Tvar[j] for individual i
                   5808:            * If product of Vn*Vm, still boolean *:
                   5809:            * If it was coded 1, 2, 3, 4 should be splitted into 3 boolean variables
                   5810:            * 1 => 0 0 0, 2 => 0 0 1, 3 => 0 1 1, 4=1 0 0   */
                   5811:           /* Finds for covariate j, n=Tvar[j] of Vn . ij is the
                   5812:              modality of the nth covariate of individual i. */
                   5813:           if (ij > modmaxcovj)
                   5814:             modmaxcovj=ij; 
                   5815:           else if (ij < modmincovj) 
                   5816:             modmincovj=ij; 
1.287     brouard  5817:           if (ij <0 || ij >1 ){
1.311     brouard  5818:             printf("ERROR, IMaCh doesn't treat covariate with missing values V%d=-1, individual %d will be skipped.\n",Tvar[k],i);
                   5819:             fprintf(ficlog,"ERROR, currently IMaCh doesn't treat covariate with missing values V%d=-1, individual %d will be skipped.\n",Tvar[k],i);
                   5820:             fflush(ficlog);
                   5821:             exit(1);
1.287     brouard  5822:           }
                   5823:           if ((ij < -1) || (ij > NCOVMAX)){
1.242     brouard  5824:             printf( "Error: minimal is less than -1 or maximal is bigger than %d. Exiting. \n", NCOVMAX );
                   5825:             exit(1);
                   5826:           }else
                   5827:             Ndum[ij]++; /*counts and stores the occurence of this modality 0, 1, -1*/
                   5828:           /*  If coded 1, 2, 3 , counts the number of 1 Ndum[1], number of 2, Ndum[2], etc */
                   5829:           /*printf("i=%d ij=%d Ndum[ij]=%d imx=%d",i,ij,Ndum[ij],imx);*/
                   5830:           /* getting the maximum value of the modality of the covariate
                   5831:              (should be 0 or 1 now) Tvar[j]. If V=sex and male is coded 0 and
                   5832:              female ies 1, then modmaxcovj=1.
                   5833:           */
                   5834:         } /* end for loop on individuals i */
                   5835:         printf(" Minimal and maximal values of %d th (fixed) covariate V%d: min=%d max=%d \n", k, Tvar[k], modmincovj, modmaxcovj);
                   5836:         fprintf(ficlog," Minimal and maximal values of %d th (fixed) covariate V%d: min=%d max=%d \n", k, Tvar[k], modmincovj, modmaxcovj);
                   5837:         cptcode=modmaxcovj;
                   5838:         /* Ndum[0] = frequency of 0 for model-covariate j, Ndum[1] frequency of 1 etc. */
                   5839:         /*for (i=0; i<=cptcode; i++) {*/
                   5840:         for (j=modmincovj;  j<=modmaxcovj; j++) { /* j=-1 ? 0 and 1*//* For each value j of the modality of model-cov k */
                   5841:           printf("Frequencies of (fixed) covariate %d ie V%d with value %d: %d\n", k, Tvar[k], j, Ndum[j]);
                   5842:           fprintf(ficlog, "Frequencies of (fixed) covariate %d ie V%d with value %d: %d\n", k, Tvar[k], j, Ndum[j]);
                   5843:           if( Ndum[j] != 0 ){ /* Counts if nobody answered modality j ie empty modality, we skip it and reorder */
                   5844:             if( j != -1){
                   5845:               ncodemax[k]++;  /* ncodemax[k]= Number of modalities of the k th
                   5846:                                  covariate for which somebody answered excluding 
                   5847:                                  undefined. Usually 2: 0 and 1. */
                   5848:             }
                   5849:             ncodemaxwundef[k]++; /* ncodemax[j]= Number of modalities of the k th
                   5850:                                     covariate for which somebody answered including 
                   5851:                                     undefined. Usually 3: -1, 0 and 1. */
                   5852:           }    /* In fact  ncodemax[k]=2 (dichotom. variables only) but it could be more for
                   5853:                 * historical reasons: 3 if coded 1, 2, 3 and 4 and Ndum[2]=0 */
                   5854:         } /* Ndum[-1] number of undefined modalities */
1.231     brouard  5855:                        
1.242     brouard  5856:         /* j is a covariate, n=Tvar[j] of Vn; Fills nbcode */
                   5857:         /* For covariate j, modalities could be 1, 2, 3, 4, 5, 6, 7. */
                   5858:         /* If Ndum[1]=0, Ndum[2]=0, Ndum[3]= 635, Ndum[4]=0, Ndum[5]=0, Ndum[6]=27, Ndum[7]=125; */
                   5859:         /* modmincovj=3; modmaxcovj = 7; */
                   5860:         /* There are only 3 modalities non empty 3, 6, 7 (or 2 if 27 is too few) : ncodemax[j]=3; */
                   5861:         /* which will be coded 0, 1, 2 which in binary on 2=3-1 digits are 0=00 1=01, 2=10; */
                   5862:         /*              defining two dummy variables: variables V1_1 and V1_2.*/
                   5863:         /* nbcode[Tvar[j]][ij]=k; */
                   5864:         /* nbcode[Tvar[j]][1]=0; */
                   5865:         /* nbcode[Tvar[j]][2]=1; */
                   5866:         /* nbcode[Tvar[j]][3]=2; */
                   5867:         /* To be continued (not working yet). */
                   5868:         ij=0; /* ij is similar to i but can jump over null modalities */
1.287     brouard  5869: 
                   5870:         /* 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*/
                   5871:         /* Skipping the case of missing values by reducing nbcode to 0 and 1 and not -1, 0, 1 */
                   5872:         /* model=V1+V2+V3, if V2=-1, 0 or 1, then nbcode[2][1]=0 and nbcode[2][2]=1 instead of
                   5873:          * nbcode[2][1]=-1, nbcode[2][2]=0 and nbcode[2][3]=1 */
                   5874:         /*, could be restored in the future */
                   5875:         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  5876:           if (Ndum[i] == 0) { /* If nobody responded to this modality k */
                   5877:             break;
                   5878:           }
                   5879:           ij++;
1.287     brouard  5880:           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  5881:           cptcode = ij; /* New max modality for covar j */
                   5882:         } /* end of loop on modality i=-1 to 1 or more */
                   5883:         break;
                   5884:        case 1: /* Testing on varying covariate, could be simple and
                   5885:                * should look at waves or product of fixed *
                   5886:                * varying. No time to test -1, assuming 0 and 1 only */
                   5887:         ij=0;
                   5888:         for(i=0; i<=1;i++){
                   5889:           nbcode[Tvar[k]][++ij]=i;
                   5890:         }
                   5891:         break;
                   5892:        default:
                   5893:         break;
                   5894:        } /* end switch */
                   5895:      } /* end dummy test */
1.311     brouard  5896:      if(Dummy[k]==1 && Typevar[k] !=1){ /* Dummy covariate and not age product */ 
                   5897:        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*/
                   5898:         if(isnan(covar[Tvar[k]][i])){
                   5899:           printf("ERROR, IMaCh doesn't treat fixed quantitative covariate with missing values V%d=., individual %d will be skipped.\n",Tvar[k],i);
                   5900:           fprintf(ficlog,"ERROR, currently IMaCh doesn't treat covariate with missing values V%d=., individual %d will be skipped.\n",Tvar[k],i);
                   5901:           fflush(ficlog);
                   5902:           exit(1);
                   5903:          }
                   5904:        }
                   5905:      }
1.287     brouard  5906:    } /* 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  5907:   
                   5908:    for (k=-1; k< maxncov; k++) Ndum[k]=0; 
                   5909:    /* Look at fixed dummy (single or product) covariates to check empty modalities */
                   5910:    for (i=1; i<=ncovmodel-2-nagesqr; i++) { /* -2, cste and age and eventually age*age */ 
                   5911:      /* Listing of all covariables in statement model to see if some covariates appear twice. For example, V1 appears twice in V1+V1*V2.*/ 
                   5912:      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 */ 
                   5913:      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 */
                   5914:      /* V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1,  {2, 1, 1, 1, 2, 1, 1, 0, 0} */
                   5915:    } /* V4+V3+V5, Ndum[1]@5={0, 0, 1, 1, 1} */
                   5916:   
                   5917:    ij=0;
                   5918:    /* for (i=0; i<=  maxncov-1; i++) { /\* modmaxcovj is unknown here. Only Ndum[2(V2),3(age*V3), 5(V3*V2) 6(V1*V4) *\/ */
                   5919:    for (k=1; k<=  cptcovt; k++) { /* modmaxcovj is unknown here. Only Ndum[2(V2),3(age*V3), 5(V3*V2) 6(V1*V4) */
                   5920:      /*printf("Ndum[%d]=%d\n",i, Ndum[i]);*/
                   5921:      /* if((Ndum[i]!=0) && (i<=ncovcol)){  /\* Tvar[i] <= ncovmodel ? *\/ */
                   5922:      if(Ndum[Tvar[k]]!=0 && Dummy[k] == 0 && Typevar[k]==0){  /* Only Dummy and non empty in the model */
                   5923:        /* If product not in single variable we don't print results */
                   5924:        /*printf("diff Ndum[%d]=%d\n",i, Ndum[i]);*/
                   5925:        ++ij;/* V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1, */
                   5926:        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*/
                   5927:        Tmodelind[ij]=k; /* Tmodelind: index in model of dummies Tmodelind[1]=2 V4: pos=2; V3: pos=3, V1=9 {2, 3, 9, ?, ?,} */
                   5928:        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 */
                   5929:        if(Fixed[k]!=0)
                   5930:         anyvaryingduminmodel=1;
                   5931:        /* }else if((Ndum[i]!=0) && (i<=ncovcol+nqv)){ */
                   5932:        /*   Tvaraff[++ij]=-10; /\* Dont'n know how to treat quantitative variables yet *\/ */
                   5933:        /* }else if((Ndum[i]!=0) && (i<=ncovcol+nqv+ntv)){ */
                   5934:        /*   Tvaraff[++ij]=i; /\*For printing (unclear) *\/ */
                   5935:        /* }else if((Ndum[i]!=0) && (i<=ncovcol+nqv+ntv+nqtv)){ */
                   5936:        /*   Tvaraff[++ij]=-20; /\* Dont'n know how to treat quantitative variables yet *\/ */
                   5937:      } 
                   5938:    } /* Tvaraff[1]@5 {3, 4, -20, 0, 0} Very strange */
                   5939:    /* ij--; */
                   5940:    /* cptcoveff=ij; /\*Number of total covariates*\/ */
1.330   ! brouard  5941:    *cptcov=ij; /* cptcov= Number of total real effective covariates: effective (used as cptcoveff in other functions)
1.242     brouard  5942:                * because they can be excluded from the model and real
                   5943:                * if in the model but excluded because missing values, but how to get k from ij?*/
                   5944:    for(j=ij+1; j<= cptcovt; j++){
                   5945:      Tvaraff[j]=0;
                   5946:      Tmodelind[j]=0;
                   5947:    }
                   5948:    for(j=ntveff+1; j<= cptcovt; j++){
                   5949:      TmodelInvind[j]=0;
                   5950:    }
                   5951:    /* To be sorted */
                   5952:    ;
                   5953:  }
1.126     brouard  5954: 
1.145     brouard  5955: 
1.126     brouard  5956: /*********** Health Expectancies ****************/
                   5957: 
1.235     brouard  5958:  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  5959: 
                   5960: {
                   5961:   /* Health expectancies, no variances */
1.329     brouard  5962:   /* cij is the combination in the list of combination of dummy covariates */
                   5963:   /* strstart is a string of time at start of computing */
1.164     brouard  5964:   int i, j, nhstepm, hstepm, h, nstepm;
1.126     brouard  5965:   int nhstepma, nstepma; /* Decreasing with age */
                   5966:   double age, agelim, hf;
                   5967:   double ***p3mat;
                   5968:   double eip;
                   5969: 
1.238     brouard  5970:   /* pstamp(ficreseij); */
1.126     brouard  5971:   fprintf(ficreseij,"# (a) Life expectancies by health status at initial age and (b) health expectancies by health status at initial age\n");
                   5972:   fprintf(ficreseij,"# Age");
                   5973:   for(i=1; i<=nlstate;i++){
                   5974:     for(j=1; j<=nlstate;j++){
                   5975:       fprintf(ficreseij," e%1d%1d ",i,j);
                   5976:     }
                   5977:     fprintf(ficreseij," e%1d. ",i);
                   5978:   }
                   5979:   fprintf(ficreseij,"\n");
                   5980: 
                   5981:   
                   5982:   if(estepm < stepm){
                   5983:     printf ("Problem %d lower than %d\n",estepm, stepm);
                   5984:   }
                   5985:   else  hstepm=estepm;   
                   5986:   /* We compute the life expectancy from trapezoids spaced every estepm months
                   5987:    * This is mainly to measure the difference between two models: for example
                   5988:    * if stepm=24 months pijx are given only every 2 years and by summing them
                   5989:    * we are calculating an estimate of the Life Expectancy assuming a linear 
                   5990:    * progression in between and thus overestimating or underestimating according
                   5991:    * to the curvature of the survival function. If, for the same date, we 
                   5992:    * estimate the model with stepm=1 month, we can keep estepm to 24 months
                   5993:    * to compare the new estimate of Life expectancy with the same linear 
                   5994:    * hypothesis. A more precise result, taking into account a more precise
                   5995:    * curvature will be obtained if estepm is as small as stepm. */
                   5996: 
                   5997:   /* For example we decided to compute the life expectancy with the smallest unit */
                   5998:   /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm. 
                   5999:      nhstepm is the number of hstepm from age to agelim 
                   6000:      nstepm is the number of stepm from age to agelin. 
1.270     brouard  6001:      Look at hpijx to understand the reason which relies in memory size consideration
1.126     brouard  6002:      and note for a fixed period like estepm months */
                   6003:   /* We decided (b) to get a life expectancy respecting the most precise curvature of the
                   6004:      survival function given by stepm (the optimization length). Unfortunately it
                   6005:      means that if the survival funtion is printed only each two years of age and if
                   6006:      you sum them up and add 1 year (area under the trapezoids) you won't get the same 
                   6007:      results. So we changed our mind and took the option of the best precision.
                   6008:   */
                   6009:   hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */ 
                   6010: 
                   6011:   agelim=AGESUP;
                   6012:   /* If stepm=6 months */
                   6013:     /* Computed by stepm unit matrices, product of hstepm matrices, stored
                   6014:        in an array of nhstepm length: nhstepm=10, hstepm=4, stepm=6 months */
                   6015:     
                   6016: /* nhstepm age range expressed in number of stepm */
                   6017:   nstepm=(int) rint((agelim-bage)*YEARM/stepm); /* Biggest nstepm */
                   6018:   /* Typically if 20 years nstepm = 20*12/6=40 stepm */ 
                   6019:   /* if (stepm >= YEARM) hstepm=1;*/
                   6020:   nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
                   6021:   p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   6022: 
                   6023:   for (age=bage; age<=fage; age ++){ 
                   6024:     nstepma=(int) rint((agelim-bage)*YEARM/stepm); /* Biggest nstepm */
                   6025:     /* Typically if 20 years nstepm = 20*12/6=40 stepm */ 
                   6026:     /* if (stepm >= YEARM) hstepm=1;*/
                   6027:     nhstepma = nstepma/hstepm;/* Expressed in hstepm, typically nhstepma=40/4=10 */
                   6028: 
                   6029:     /* If stepm=6 months */
                   6030:     /* Computed by stepm unit matrices, product of hstepma matrices, stored
                   6031:        in an array of nhstepma length: nhstepma=10, hstepm=4, stepm=6 months */
1.330   ! brouard  6032:     /* printf("HELLO evsij Entering hpxij age=%d cij=%d hstepm=%d x[1]=%f nres=%d\n",(int) age, cij, hstepm, x[1], nres); */
1.235     brouard  6033:     hpxij(p3mat,nhstepma,age,hstepm,x,nlstate,stepm,oldm, savm, cij, nres);  
1.126     brouard  6034:     
                   6035:     hf=hstepm*stepm/YEARM;  /* Duration of hstepm expressed in year unit. */
                   6036:     
                   6037:     printf("%d|",(int)age);fflush(stdout);
                   6038:     fprintf(ficlog,"%d|",(int)age);fflush(ficlog);
                   6039:     
                   6040:     /* Computing expectancies */
                   6041:     for(i=1; i<=nlstate;i++)
                   6042:       for(j=1; j<=nlstate;j++)
                   6043:        for (h=0, eij[i][j][(int)age]=0; h<=nhstepm-1; h++){
                   6044:          eij[i][j][(int)age] += (p3mat[i][j][h]+p3mat[i][j][h+1])/2.0*hf;
                   6045:          
                   6046:          /* 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]);*/
                   6047: 
                   6048:        }
                   6049: 
                   6050:     fprintf(ficreseij,"%3.0f",age );
                   6051:     for(i=1; i<=nlstate;i++){
                   6052:       eip=0;
                   6053:       for(j=1; j<=nlstate;j++){
                   6054:        eip +=eij[i][j][(int)age];
                   6055:        fprintf(ficreseij,"%9.4f", eij[i][j][(int)age] );
                   6056:       }
                   6057:       fprintf(ficreseij,"%9.4f", eip );
                   6058:     }
                   6059:     fprintf(ficreseij,"\n");
                   6060:     
                   6061:   }
                   6062:   free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   6063:   printf("\n");
                   6064:   fprintf(ficlog,"\n");
                   6065:   
                   6066: }
                   6067: 
1.235     brouard  6068:  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  6069: 
                   6070: {
                   6071:   /* Covariances of health expectancies eij and of total life expectancies according
1.222     brouard  6072:      to initial status i, ei. .
1.126     brouard  6073:   */
                   6074:   int i, j, nhstepm, hstepm, h, nstepm, k, cptj, cptj2, i2, j2, ij, ji;
                   6075:   int nhstepma, nstepma; /* Decreasing with age */
                   6076:   double age, agelim, hf;
                   6077:   double ***p3matp, ***p3matm, ***varhe;
                   6078:   double **dnewm,**doldm;
                   6079:   double *xp, *xm;
                   6080:   double **gp, **gm;
                   6081:   double ***gradg, ***trgradg;
                   6082:   int theta;
                   6083: 
                   6084:   double eip, vip;
                   6085: 
                   6086:   varhe=ma3x(1,nlstate*nlstate,1,nlstate*nlstate,(int) bage, (int) fage);
                   6087:   xp=vector(1,npar);
                   6088:   xm=vector(1,npar);
                   6089:   dnewm=matrix(1,nlstate*nlstate,1,npar);
                   6090:   doldm=matrix(1,nlstate*nlstate,1,nlstate*nlstate);
                   6091:   
                   6092:   pstamp(ficresstdeij);
                   6093:   fprintf(ficresstdeij,"# Health expectancies with standard errors\n");
                   6094:   fprintf(ficresstdeij,"# Age");
                   6095:   for(i=1; i<=nlstate;i++){
                   6096:     for(j=1; j<=nlstate;j++)
                   6097:       fprintf(ficresstdeij," e%1d%1d (SE)",i,j);
                   6098:     fprintf(ficresstdeij," e%1d. ",i);
                   6099:   }
                   6100:   fprintf(ficresstdeij,"\n");
                   6101: 
                   6102:   pstamp(ficrescveij);
                   6103:   fprintf(ficrescveij,"# Subdiagonal matrix of covariances of health expectancies by age: cov(eij,ekl)\n");
                   6104:   fprintf(ficrescveij,"# Age");
                   6105:   for(i=1; i<=nlstate;i++)
                   6106:     for(j=1; j<=nlstate;j++){
                   6107:       cptj= (j-1)*nlstate+i;
                   6108:       for(i2=1; i2<=nlstate;i2++)
                   6109:        for(j2=1; j2<=nlstate;j2++){
                   6110:          cptj2= (j2-1)*nlstate+i2;
                   6111:          if(cptj2 <= cptj)
                   6112:            fprintf(ficrescveij,"  %1d%1d,%1d%1d",i,j,i2,j2);
                   6113:        }
                   6114:     }
                   6115:   fprintf(ficrescveij,"\n");
                   6116:   
                   6117:   if(estepm < stepm){
                   6118:     printf ("Problem %d lower than %d\n",estepm, stepm);
                   6119:   }
                   6120:   else  hstepm=estepm;   
                   6121:   /* We compute the life expectancy from trapezoids spaced every estepm months
                   6122:    * This is mainly to measure the difference between two models: for example
                   6123:    * if stepm=24 months pijx are given only every 2 years and by summing them
                   6124:    * we are calculating an estimate of the Life Expectancy assuming a linear 
                   6125:    * progression in between and thus overestimating or underestimating according
                   6126:    * to the curvature of the survival function. If, for the same date, we 
                   6127:    * estimate the model with stepm=1 month, we can keep estepm to 24 months
                   6128:    * to compare the new estimate of Life expectancy with the same linear 
                   6129:    * hypothesis. A more precise result, taking into account a more precise
                   6130:    * curvature will be obtained if estepm is as small as stepm. */
                   6131: 
                   6132:   /* For example we decided to compute the life expectancy with the smallest unit */
                   6133:   /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm. 
                   6134:      nhstepm is the number of hstepm from age to agelim 
                   6135:      nstepm is the number of stepm from age to agelin. 
                   6136:      Look at hpijx to understand the reason of that which relies in memory size
                   6137:      and note for a fixed period like estepm months */
                   6138:   /* We decided (b) to get a life expectancy respecting the most precise curvature of the
                   6139:      survival function given by stepm (the optimization length). Unfortunately it
                   6140:      means that if the survival funtion is printed only each two years of age and if
                   6141:      you sum them up and add 1 year (area under the trapezoids) you won't get the same 
                   6142:      results. So we changed our mind and took the option of the best precision.
                   6143:   */
                   6144:   hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */ 
                   6145: 
                   6146:   /* If stepm=6 months */
                   6147:   /* nhstepm age range expressed in number of stepm */
                   6148:   agelim=AGESUP;
                   6149:   nstepm=(int) rint((agelim-bage)*YEARM/stepm); 
                   6150:   /* Typically if 20 years nstepm = 20*12/6=40 stepm */ 
                   6151:   /* if (stepm >= YEARM) hstepm=1;*/
                   6152:   nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
                   6153:   
                   6154:   p3matp=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   6155:   p3matm=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   6156:   gradg=ma3x(0,nhstepm,1,npar,1,nlstate*nlstate);
                   6157:   trgradg =ma3x(0,nhstepm,1,nlstate*nlstate,1,npar);
                   6158:   gp=matrix(0,nhstepm,1,nlstate*nlstate);
                   6159:   gm=matrix(0,nhstepm,1,nlstate*nlstate);
                   6160: 
                   6161:   for (age=bage; age<=fage; age ++){ 
                   6162:     nstepma=(int) rint((agelim-bage)*YEARM/stepm); /* Biggest nstepm */
                   6163:     /* Typically if 20 years nstepm = 20*12/6=40 stepm */ 
                   6164:     /* if (stepm >= YEARM) hstepm=1;*/
                   6165:     nhstepma = nstepma/hstepm;/* Expressed in hstepm, typically nhstepma=40/4=10 */
1.218     brouard  6166:                
1.126     brouard  6167:     /* If stepm=6 months */
                   6168:     /* Computed by stepm unit matrices, product of hstepma matrices, stored
                   6169:        in an array of nhstepma length: nhstepma=10, hstepm=4, stepm=6 months */
                   6170:     
                   6171:     hf=hstepm*stepm/YEARM;  /* Duration of hstepm expressed in year unit. */
1.218     brouard  6172:                
1.126     brouard  6173:     /* Computing  Variances of health expectancies */
                   6174:     /* Gradient is computed with plus gp and minus gm. Code is duplicated in order to
                   6175:        decrease memory allocation */
                   6176:     for(theta=1; theta <=npar; theta++){
                   6177:       for(i=1; i<=npar; i++){ 
1.222     brouard  6178:        xp[i] = x[i] + (i==theta ?delti[theta]:0);
                   6179:        xm[i] = x[i] - (i==theta ?delti[theta]:0);
1.126     brouard  6180:       }
1.235     brouard  6181:       hpxij(p3matp,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, cij, nres);  
                   6182:       hpxij(p3matm,nhstepm,age,hstepm,xm,nlstate,stepm,oldm,savm, cij, nres);  
1.218     brouard  6183:                        
1.126     brouard  6184:       for(j=1; j<= nlstate; j++){
1.222     brouard  6185:        for(i=1; i<=nlstate; i++){
                   6186:          for(h=0; h<=nhstepm-1; h++){
                   6187:            gp[h][(j-1)*nlstate + i] = (p3matp[i][j][h]+p3matp[i][j][h+1])/2.;
                   6188:            gm[h][(j-1)*nlstate + i] = (p3matm[i][j][h]+p3matm[i][j][h+1])/2.;
                   6189:          }
                   6190:        }
1.126     brouard  6191:       }
1.218     brouard  6192:                        
1.126     brouard  6193:       for(ij=1; ij<= nlstate*nlstate; ij++)
1.222     brouard  6194:        for(h=0; h<=nhstepm-1; h++){
                   6195:          gradg[h][theta][ij]= (gp[h][ij]-gm[h][ij])/2./delti[theta];
                   6196:        }
1.126     brouard  6197:     }/* End theta */
                   6198:     
                   6199:     
                   6200:     for(h=0; h<=nhstepm-1; h++)
                   6201:       for(j=1; j<=nlstate*nlstate;j++)
1.222     brouard  6202:        for(theta=1; theta <=npar; theta++)
                   6203:          trgradg[h][j][theta]=gradg[h][theta][j];
1.126     brouard  6204:     
1.218     brouard  6205:                
1.222     brouard  6206:     for(ij=1;ij<=nlstate*nlstate;ij++)
1.126     brouard  6207:       for(ji=1;ji<=nlstate*nlstate;ji++)
1.222     brouard  6208:        varhe[ij][ji][(int)age] =0.;
1.218     brouard  6209:                
1.222     brouard  6210:     printf("%d|",(int)age);fflush(stdout);
                   6211:     fprintf(ficlog,"%d|",(int)age);fflush(ficlog);
                   6212:     for(h=0;h<=nhstepm-1;h++){
1.126     brouard  6213:       for(k=0;k<=nhstepm-1;k++){
1.222     brouard  6214:        matprod2(dnewm,trgradg[h],1,nlstate*nlstate,1,npar,1,npar,matcov);
                   6215:        matprod2(doldm,dnewm,1,nlstate*nlstate,1,npar,1,nlstate*nlstate,gradg[k]);
                   6216:        for(ij=1;ij<=nlstate*nlstate;ij++)
                   6217:          for(ji=1;ji<=nlstate*nlstate;ji++)
                   6218:            varhe[ij][ji][(int)age] += doldm[ij][ji]*hf*hf;
1.126     brouard  6219:       }
                   6220:     }
1.320     brouard  6221:     /* if((int)age ==50){ */
                   6222:     /*   printf(" age=%d cij=%d nres=%d varhe[%d][%d]=%f ",(int)age, cij, nres, 1,2,varhe[1][2]); */
                   6223:     /* } */
1.126     brouard  6224:     /* Computing expectancies */
1.235     brouard  6225:     hpxij(p3matm,nhstepm,age,hstepm,x,nlstate,stepm,oldm, savm, cij,nres);  
1.126     brouard  6226:     for(i=1; i<=nlstate;i++)
                   6227:       for(j=1; j<=nlstate;j++)
1.222     brouard  6228:        for (h=0, eij[i][j][(int)age]=0; h<=nhstepm-1; h++){
                   6229:          eij[i][j][(int)age] += (p3matm[i][j][h]+p3matm[i][j][h+1])/2.0*hf;
1.218     brouard  6230:                                        
1.222     brouard  6231:          /* 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  6232:                                        
1.222     brouard  6233:        }
1.269     brouard  6234: 
                   6235:     /* Standard deviation of expectancies ij */                
1.126     brouard  6236:     fprintf(ficresstdeij,"%3.0f",age );
                   6237:     for(i=1; i<=nlstate;i++){
                   6238:       eip=0.;
                   6239:       vip=0.;
                   6240:       for(j=1; j<=nlstate;j++){
1.222     brouard  6241:        eip += eij[i][j][(int)age];
                   6242:        for(k=1; k<=nlstate;k++) /* Sum on j and k of cov(eij,eik) */
                   6243:          vip += varhe[(j-1)*nlstate+i][(k-1)*nlstate+i][(int)age];
                   6244:        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  6245:       }
                   6246:       fprintf(ficresstdeij," %9.4f (%.4f)", eip, sqrt(vip));
                   6247:     }
                   6248:     fprintf(ficresstdeij,"\n");
1.218     brouard  6249:                
1.269     brouard  6250:     /* Variance of expectancies ij */          
1.126     brouard  6251:     fprintf(ficrescveij,"%3.0f",age );
                   6252:     for(i=1; i<=nlstate;i++)
                   6253:       for(j=1; j<=nlstate;j++){
1.222     brouard  6254:        cptj= (j-1)*nlstate+i;
                   6255:        for(i2=1; i2<=nlstate;i2++)
                   6256:          for(j2=1; j2<=nlstate;j2++){
                   6257:            cptj2= (j2-1)*nlstate+i2;
                   6258:            if(cptj2 <= cptj)
                   6259:              fprintf(ficrescveij," %.4f", varhe[cptj][cptj2][(int)age]);
                   6260:          }
1.126     brouard  6261:       }
                   6262:     fprintf(ficrescveij,"\n");
1.218     brouard  6263:                
1.126     brouard  6264:   }
                   6265:   free_matrix(gm,0,nhstepm,1,nlstate*nlstate);
                   6266:   free_matrix(gp,0,nhstepm,1,nlstate*nlstate);
                   6267:   free_ma3x(gradg,0,nhstepm,1,npar,1,nlstate*nlstate);
                   6268:   free_ma3x(trgradg,0,nhstepm,1,nlstate*nlstate,1,npar);
                   6269:   free_ma3x(p3matm,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   6270:   free_ma3x(p3matp,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   6271:   printf("\n");
                   6272:   fprintf(ficlog,"\n");
1.218     brouard  6273:        
1.126     brouard  6274:   free_vector(xm,1,npar);
                   6275:   free_vector(xp,1,npar);
                   6276:   free_matrix(dnewm,1,nlstate*nlstate,1,npar);
                   6277:   free_matrix(doldm,1,nlstate*nlstate,1,nlstate*nlstate);
                   6278:   free_ma3x(varhe,1,nlstate*nlstate,1,nlstate*nlstate,(int) bage, (int)fage);
                   6279: }
1.218     brouard  6280:  
1.126     brouard  6281: /************ Variance ******************/
1.235     brouard  6282:  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  6283:  {
1.279     brouard  6284:    /** Variance of health expectancies 
                   6285:     *  double **prevalim(double **prlim, int nlstate, double *xp, double age, double **oldm, double ** savm,double ftolpl);
                   6286:     * double **newm;
                   6287:     * int movingaverage(double ***probs, double bage,double fage, double ***mobaverage, int mobilav) 
                   6288:     */
1.218     brouard  6289:   
                   6290:    /* int movingaverage(); */
                   6291:    double **dnewm,**doldm;
                   6292:    double **dnewmp,**doldmp;
                   6293:    int i, j, nhstepm, hstepm, h, nstepm ;
1.288     brouard  6294:    int first=0;
1.218     brouard  6295:    int k;
                   6296:    double *xp;
1.279     brouard  6297:    double **gp, **gm;  /**< for var eij */
                   6298:    double ***gradg, ***trgradg; /**< for var eij */
                   6299:    double **gradgp, **trgradgp; /**< for var p point j */
                   6300:    double *gpp, *gmp; /**< for var p point j */
                   6301:    double **varppt; /**< for var p point j nlstate to nlstate+ndeath */
1.218     brouard  6302:    double ***p3mat;
                   6303:    double age,agelim, hf;
                   6304:    /* double ***mobaverage; */
                   6305:    int theta;
                   6306:    char digit[4];
                   6307:    char digitp[25];
                   6308: 
                   6309:    char fileresprobmorprev[FILENAMELENGTH];
                   6310: 
                   6311:    if(popbased==1){
                   6312:      if(mobilav!=0)
                   6313:        strcpy(digitp,"-POPULBASED-MOBILAV_");
                   6314:      else strcpy(digitp,"-POPULBASED-NOMOBIL_");
                   6315:    }
                   6316:    else 
                   6317:      strcpy(digitp,"-STABLBASED_");
1.126     brouard  6318: 
1.218     brouard  6319:    /* if (mobilav!=0) { */
                   6320:    /*   mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX); */
                   6321:    /*   if (movingaverage(probs, bage, fage, mobaverage,mobilav)!=0){ */
                   6322:    /*     fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav); */
                   6323:    /*     printf(" Error in movingaverage mobilav=%d\n",mobilav); */
                   6324:    /*   } */
                   6325:    /* } */
                   6326: 
                   6327:    strcpy(fileresprobmorprev,"PRMORPREV-"); 
                   6328:    sprintf(digit,"%-d",ij);
                   6329:    /*printf("DIGIT=%s, ij=%d ijr=%-d|\n",digit, ij,ij);*/
                   6330:    strcat(fileresprobmorprev,digit); /* Tvar to be done */
                   6331:    strcat(fileresprobmorprev,digitp); /* Popbased or not, mobilav or not */
                   6332:    strcat(fileresprobmorprev,fileresu);
                   6333:    if((ficresprobmorprev=fopen(fileresprobmorprev,"w"))==NULL) {
                   6334:      printf("Problem with resultfile: %s\n", fileresprobmorprev);
                   6335:      fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobmorprev);
                   6336:    }
                   6337:    printf("Computing total mortality p.j=w1*p1j+w2*p2j+..: result on file '%s' \n",fileresprobmorprev);
                   6338:    fprintf(ficlog,"Computing total mortality p.j=w1*p1j+w2*p2j+..: result on file '%s' \n",fileresprobmorprev);
                   6339:    pstamp(ficresprobmorprev);
                   6340:    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  6341:    fprintf(ficresprobmorprev,"# Selected quantitative variables and dummies");
                   6342:    for (j=1; j<= nsq; j++){ /* For each selected (single) quantitative value */
                   6343:      fprintf(ficresprobmorprev," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]);
                   6344:    }
                   6345:    for(j=1;j<=cptcoveff;j++) 
1.330   ! brouard  6346:      fprintf(ficresprobmorprev,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(ij,Tvaraff[j])]);
1.238     brouard  6347:    fprintf(ficresprobmorprev,"\n");
                   6348: 
1.218     brouard  6349:    fprintf(ficresprobmorprev,"# Age cov=%-d",ij);
                   6350:    for(j=nlstate+1; j<=(nlstate+ndeath);j++){
                   6351:      fprintf(ficresprobmorprev," p.%-d SE",j);
                   6352:      for(i=1; i<=nlstate;i++)
                   6353:        fprintf(ficresprobmorprev," w%1d p%-d%-d",i,i,j);
                   6354:    }  
                   6355:    fprintf(ficresprobmorprev,"\n");
                   6356:   
                   6357:    fprintf(ficgp,"\n# Routine varevsij");
                   6358:    fprintf(ficgp,"\nunset title \n");
                   6359:    /* fprintf(fichtm, "#Local time at start: %s", strstart);*/
                   6360:    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");
                   6361:    fprintf(fichtm,"\n<br>%s  <br>\n",digitp);
1.279     brouard  6362: 
1.218     brouard  6363:    varppt = matrix(nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
                   6364:    pstamp(ficresvij);
                   6365:    fprintf(ficresvij,"# Variance and covariance of health expectancies e.j \n#  (weighted average of eij where weights are ");
                   6366:    if(popbased==1)
                   6367:      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);
                   6368:    else
                   6369:      fprintf(ficresvij,"the age specific period (stable) prevalences in each health state \n");
                   6370:    fprintf(ficresvij,"# Age");
                   6371:    for(i=1; i<=nlstate;i++)
                   6372:      for(j=1; j<=nlstate;j++)
                   6373:        fprintf(ficresvij," Cov(e.%1d, e.%1d)",i,j);
                   6374:    fprintf(ficresvij,"\n");
                   6375: 
                   6376:    xp=vector(1,npar);
                   6377:    dnewm=matrix(1,nlstate,1,npar);
                   6378:    doldm=matrix(1,nlstate,1,nlstate);
                   6379:    dnewmp= matrix(nlstate+1,nlstate+ndeath,1,npar);
                   6380:    doldmp= matrix(nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
                   6381: 
                   6382:    gradgp=matrix(1,npar,nlstate+1,nlstate+ndeath);
                   6383:    gpp=vector(nlstate+1,nlstate+ndeath);
                   6384:    gmp=vector(nlstate+1,nlstate+ndeath);
                   6385:    trgradgp =matrix(nlstate+1,nlstate+ndeath,1,npar); /* mu or p point j*/
1.126     brouard  6386:   
1.218     brouard  6387:    if(estepm < stepm){
                   6388:      printf ("Problem %d lower than %d\n",estepm, stepm);
                   6389:    }
                   6390:    else  hstepm=estepm;   
                   6391:    /* For example we decided to compute the life expectancy with the smallest unit */
                   6392:    /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm. 
                   6393:       nhstepm is the number of hstepm from age to agelim 
                   6394:       nstepm is the number of stepm from age to agelim. 
                   6395:       Look at function hpijx to understand why because of memory size limitations, 
                   6396:       we decided (b) to get a life expectancy respecting the most precise curvature of the
                   6397:       survival function given by stepm (the optimization length). Unfortunately it
                   6398:       means that if the survival funtion is printed every two years of age and if
                   6399:       you sum them up and add 1 year (area under the trapezoids) you won't get the same 
                   6400:       results. So we changed our mind and took the option of the best precision.
                   6401:    */
                   6402:    hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */ 
                   6403:    agelim = AGESUP;
                   6404:    for (age=bage; age<=fage; age ++){ /* If stepm=6 months */
                   6405:      nstepm=(int) rint((agelim-age)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */ 
                   6406:      nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
                   6407:      p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   6408:      gradg=ma3x(0,nhstepm,1,npar,1,nlstate);
                   6409:      gp=matrix(0,nhstepm,1,nlstate);
                   6410:      gm=matrix(0,nhstepm,1,nlstate);
                   6411:                
                   6412:                
                   6413:      for(theta=1; theta <=npar; theta++){
                   6414:        for(i=1; i<=npar; i++){ /* Computes gradient x + delta*/
                   6415:         xp[i] = x[i] + (i==theta ?delti[theta]:0);
                   6416:        }
1.279     brouard  6417:        /**< Computes the prevalence limit with parameter theta shifted of delta up to ftolpl precision and 
                   6418:        * returns into prlim .
1.288     brouard  6419:        */
1.242     brouard  6420:        prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp,ij, nres);
1.279     brouard  6421: 
                   6422:        /* If popbased = 1 we use crossection prevalences. Previous step is useless but prlim is created */
1.218     brouard  6423:        if (popbased==1) {
                   6424:         if(mobilav ==0){
                   6425:           for(i=1; i<=nlstate;i++)
                   6426:             prlim[i][i]=probs[(int)age][i][ij];
                   6427:         }else{ /* mobilav */ 
                   6428:           for(i=1; i<=nlstate;i++)
                   6429:             prlim[i][i]=mobaverage[(int)age][i][ij];
                   6430:         }
                   6431:        }
1.295     brouard  6432:        /**< Computes the shifted transition matrix \f$ {}{h}_p^{ij}x\f$ at horizon h.
1.279     brouard  6433:        */                      
                   6434:        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  6435:        /**< 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  6436:        * at horizon h in state j including mortality.
                   6437:        */
1.218     brouard  6438:        for(j=1; j<= nlstate; j++){
                   6439:         for(h=0; h<=nhstepm; h++){
                   6440:           for(i=1, gp[h][j]=0.;i<=nlstate;i++)
                   6441:             gp[h][j] += prlim[i][i]*p3mat[i][j][h];
                   6442:         }
                   6443:        }
1.279     brouard  6444:        /* Next for computing shifted+ probability of death (h=1 means
1.218     brouard  6445:          computed over hstepm matrices product = hstepm*stepm months) 
1.279     brouard  6446:          as a weighted average of prlim(i) * p(i,j) p.3=w1*p13 + w2*p23 .
1.218     brouard  6447:        */
                   6448:        for(j=nlstate+1;j<=nlstate+ndeath;j++){
                   6449:         for(i=1,gpp[j]=0.; i<= nlstate; i++)
                   6450:           gpp[j] += prlim[i][i]*p3mat[i][j][1];
1.279     brouard  6451:        }
                   6452:        
                   6453:        /* Again with minus shift */
1.218     brouard  6454:                        
                   6455:        for(i=1; i<=npar; i++) /* Computes gradient x - delta */
                   6456:         xp[i] = x[i] - (i==theta ?delti[theta]:0);
1.288     brouard  6457: 
1.242     brouard  6458:        prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp, ij, nres);
1.218     brouard  6459:                        
                   6460:        if (popbased==1) {
                   6461:         if(mobilav ==0){
                   6462:           for(i=1; i<=nlstate;i++)
                   6463:             prlim[i][i]=probs[(int)age][i][ij];
                   6464:         }else{ /* mobilav */ 
                   6465:           for(i=1; i<=nlstate;i++)
                   6466:             prlim[i][i]=mobaverage[(int)age][i][ij];
                   6467:         }
                   6468:        }
                   6469:                        
1.235     brouard  6470:        hpxij(p3mat,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, ij,nres);  
1.218     brouard  6471:                        
                   6472:        for(j=1; j<= nlstate; j++){  /* Sum of wi * eij = e.j */
                   6473:         for(h=0; h<=nhstepm; h++){
                   6474:           for(i=1, gm[h][j]=0.;i<=nlstate;i++)
                   6475:             gm[h][j] += prlim[i][i]*p3mat[i][j][h];
                   6476:         }
                   6477:        }
                   6478:        /* This for computing probability of death (h=1 means
                   6479:          computed over hstepm matrices product = hstepm*stepm months) 
                   6480:          as a weighted average of prlim.
                   6481:        */
                   6482:        for(j=nlstate+1;j<=nlstate+ndeath;j++){
                   6483:         for(i=1,gmp[j]=0.; i<= nlstate; i++)
                   6484:           gmp[j] += prlim[i][i]*p3mat[i][j][1];
                   6485:        }    
1.279     brouard  6486:        /* end shifting computations */
                   6487: 
                   6488:        /**< Computing gradient matrix at horizon h 
                   6489:        */
1.218     brouard  6490:        for(j=1; j<= nlstate; j++) /* vareij */
                   6491:         for(h=0; h<=nhstepm; h++){
                   6492:           gradg[h][theta][j]= (gp[h][j]-gm[h][j])/2./delti[theta];
                   6493:         }
1.279     brouard  6494:        /**< Gradient of overall mortality p.3 (or p.j) 
                   6495:        */
                   6496:        for(j=nlstate+1; j<= nlstate+ndeath; j++){ /* var mu mortality from j */
1.218     brouard  6497:         gradgp[theta][j]= (gpp[j]-gmp[j])/2./delti[theta];
                   6498:        }
                   6499:                        
                   6500:      } /* End theta */
1.279     brouard  6501:      
                   6502:      /* We got the gradient matrix for each theta and state j */               
1.218     brouard  6503:      trgradg =ma3x(0,nhstepm,1,nlstate,1,npar); /* veij */
                   6504:                
                   6505:      for(h=0; h<=nhstepm; h++) /* veij */
                   6506:        for(j=1; j<=nlstate;j++)
                   6507:         for(theta=1; theta <=npar; theta++)
                   6508:           trgradg[h][j][theta]=gradg[h][theta][j];
                   6509:                
                   6510:      for(j=nlstate+1; j<=nlstate+ndeath;j++) /* mu */
                   6511:        for(theta=1; theta <=npar; theta++)
                   6512:         trgradgp[j][theta]=gradgp[theta][j];
1.279     brouard  6513:      /**< as well as its transposed matrix 
                   6514:       */               
1.218     brouard  6515:                
                   6516:      hf=hstepm*stepm/YEARM;  /* Duration of hstepm expressed in year unit. */
                   6517:      for(i=1;i<=nlstate;i++)
                   6518:        for(j=1;j<=nlstate;j++)
                   6519:         vareij[i][j][(int)age] =0.;
1.279     brouard  6520: 
                   6521:      /* Computing trgradg by matcov by gradg at age and summing over h
                   6522:       * and k (nhstepm) formula 15 of article
                   6523:       * Lievre-Brouard-Heathcote
                   6524:       */
                   6525:      
1.218     brouard  6526:      for(h=0;h<=nhstepm;h++){
                   6527:        for(k=0;k<=nhstepm;k++){
                   6528:         matprod2(dnewm,trgradg[h],1,nlstate,1,npar,1,npar,matcov);
                   6529:         matprod2(doldm,dnewm,1,nlstate,1,npar,1,nlstate,gradg[k]);
                   6530:         for(i=1;i<=nlstate;i++)
                   6531:           for(j=1;j<=nlstate;j++)
                   6532:             vareij[i][j][(int)age] += doldm[i][j]*hf*hf;
                   6533:        }
                   6534:      }
                   6535:                
1.279     brouard  6536:      /* pptj is p.3 or p.j = trgradgp by cov by gradgp, variance of
                   6537:       * p.j overall mortality formula 49 but computed directly because
                   6538:       * we compute the grad (wix pijx) instead of grad (pijx),even if
                   6539:       * wix is independent of theta.
                   6540:       */
1.218     brouard  6541:      matprod2(dnewmp,trgradgp,nlstate+1,nlstate+ndeath,1,npar,1,npar,matcov);
                   6542:      matprod2(doldmp,dnewmp,nlstate+1,nlstate+ndeath,1,npar,nlstate+1,nlstate+ndeath,gradgp);
                   6543:      for(j=nlstate+1;j<=nlstate+ndeath;j++)
                   6544:        for(i=nlstate+1;i<=nlstate+ndeath;i++)
                   6545:         varppt[j][i]=doldmp[j][i];
                   6546:      /* end ppptj */
                   6547:      /*  x centered again */
                   6548:                
1.242     brouard  6549:      prevalim(prlim,nlstate,x,age,oldm,savm,ftolpl,ncvyearp,ij, nres);
1.218     brouard  6550:                
                   6551:      if (popbased==1) {
                   6552:        if(mobilav ==0){
                   6553:         for(i=1; i<=nlstate;i++)
                   6554:           prlim[i][i]=probs[(int)age][i][ij];
                   6555:        }else{ /* mobilav */ 
                   6556:         for(i=1; i<=nlstate;i++)
                   6557:           prlim[i][i]=mobaverage[(int)age][i][ij];
                   6558:        }
                   6559:      }
                   6560:                
                   6561:      /* This for computing probability of death (h=1 means
                   6562:        computed over hstepm (estepm) matrices product = hstepm*stepm months) 
                   6563:        as a weighted average of prlim.
                   6564:      */
1.235     brouard  6565:      hpxij(p3mat,nhstepm,age,hstepm,x,nlstate,stepm,oldm,savm, ij, nres);  
1.218     brouard  6566:      for(j=nlstate+1;j<=nlstate+ndeath;j++){
                   6567:        for(i=1,gmp[j]=0.;i<= nlstate; i++) 
                   6568:         gmp[j] += prlim[i][i]*p3mat[i][j][1]; 
                   6569:      }    
                   6570:      /* end probability of death */
                   6571:                
                   6572:      fprintf(ficresprobmorprev,"%3d %d ",(int) age, ij);
                   6573:      for(j=nlstate+1; j<=(nlstate+ndeath);j++){
                   6574:        fprintf(ficresprobmorprev," %11.3e %11.3e",gmp[j], sqrt(varppt[j][j]));
                   6575:        for(i=1; i<=nlstate;i++){
                   6576:         fprintf(ficresprobmorprev," %11.3e %11.3e ",prlim[i][i],p3mat[i][j][1]);
                   6577:        }
                   6578:      } 
                   6579:      fprintf(ficresprobmorprev,"\n");
                   6580:                
                   6581:      fprintf(ficresvij,"%.0f ",age );
                   6582:      for(i=1; i<=nlstate;i++)
                   6583:        for(j=1; j<=nlstate;j++){
                   6584:         fprintf(ficresvij," %.4f", vareij[i][j][(int)age]);
                   6585:        }
                   6586:      fprintf(ficresvij,"\n");
                   6587:      free_matrix(gp,0,nhstepm,1,nlstate);
                   6588:      free_matrix(gm,0,nhstepm,1,nlstate);
                   6589:      free_ma3x(gradg,0,nhstepm,1,npar,1,nlstate);
                   6590:      free_ma3x(trgradg,0,nhstepm,1,nlstate,1,npar);
                   6591:      free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   6592:    } /* End age */
                   6593:    free_vector(gpp,nlstate+1,nlstate+ndeath);
                   6594:    free_vector(gmp,nlstate+1,nlstate+ndeath);
                   6595:    free_matrix(gradgp,1,npar,nlstate+1,nlstate+ndeath);
                   6596:    free_matrix(trgradgp,nlstate+1,nlstate+ndeath,1,npar); /* mu or p point j*/
                   6597:    /* fprintf(ficgp,"\nunset parametric;unset label; set ter png small size 320, 240"); */
                   6598:    fprintf(ficgp,"\nunset parametric;unset label; set ter svg size 640, 480");
                   6599:    /* for(j=nlstate+1; j<= nlstate+ndeath; j++){ *//* Only the first actually */
                   6600:    fprintf(ficgp,"\n set log y; unset log x;set xlabel \"Age\"; set ylabel \"Force of mortality (year-1)\";");
                   6601:    fprintf(ficgp,"\nset out \"%s%s.svg\";",subdirf3(optionfilefiname,"VARMUPTJGR-",digitp),digit);
                   6602:    /*   fprintf(ficgp,"\n plot \"%s\"  u 1:($3*%6.3f) not w l 1 ",fileresprobmorprev,YEARM/estepm); */
                   6603:    /*   fprintf(ficgp,"\n replot \"%s\"  u 1:(($3+1.96*$4)*%6.3f) t \"95\%% interval\" w l 2 ",fileresprobmorprev,YEARM/estepm); */
                   6604:    /*   fprintf(ficgp,"\n replot \"%s\"  u 1:(($3-1.96*$4)*%6.3f) not w l 2 ",fileresprobmorprev,YEARM/estepm); */
                   6605:    fprintf(ficgp,"\n plot \"%s\"  u 1:($3) not w l lt 1 ",subdirf(fileresprobmorprev));
                   6606:    fprintf(ficgp,"\n replot \"%s\"  u 1:(($3+1.96*$4)) t \"95%% interval\" w l lt 2 ",subdirf(fileresprobmorprev));
                   6607:    fprintf(ficgp,"\n replot \"%s\"  u 1:(($3-1.96*$4)) not w l lt 2 ",subdirf(fileresprobmorprev));
                   6608:    fprintf(fichtm,"\n<br> File (multiple files are possible if covariates are present): <A href=\"%s\">%s</a>\n",subdirf(fileresprobmorprev),subdirf(fileresprobmorprev));
                   6609:    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);
                   6610:    /*  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  6611:     */
1.218     brouard  6612:    /*   fprintf(ficgp,"\nset out \"varmuptjgr%s%s%s.svg\";replot;",digitp,optionfilefiname,digit); */
                   6613:    fprintf(ficgp,"\nset out;\nset out \"%s%s.svg\";replot;set out;\n",subdirf3(optionfilefiname,"VARMUPTJGR-",digitp),digit);
1.126     brouard  6614: 
1.218     brouard  6615:    free_vector(xp,1,npar);
                   6616:    free_matrix(doldm,1,nlstate,1,nlstate);
                   6617:    free_matrix(dnewm,1,nlstate,1,npar);
                   6618:    free_matrix(doldmp,nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
                   6619:    free_matrix(dnewmp,nlstate+1,nlstate+ndeath,1,npar);
                   6620:    free_matrix(varppt,nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
                   6621:    /* if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX); */
                   6622:    fclose(ficresprobmorprev);
                   6623:    fflush(ficgp);
                   6624:    fflush(fichtm); 
                   6625:  }  /* end varevsij */
1.126     brouard  6626: 
                   6627: /************ Variance of prevlim ******************/
1.269     brouard  6628:  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  6629: {
1.205     brouard  6630:   /* Variance of prevalence limit  for each state ij using current parameters x[] and estimates of neighbourhood give by delti*/
1.126     brouard  6631:   /*  double **prevalim(double **prlim, int nlstate, double *xp, double age, double **oldm, double **savm,double ftolpl);*/
1.164     brouard  6632: 
1.268     brouard  6633:   double **dnewmpar,**doldm;
1.126     brouard  6634:   int i, j, nhstepm, hstepm;
                   6635:   double *xp;
                   6636:   double *gp, *gm;
                   6637:   double **gradg, **trgradg;
1.208     brouard  6638:   double **mgm, **mgp;
1.126     brouard  6639:   double age,agelim;
                   6640:   int theta;
                   6641:   
                   6642:   pstamp(ficresvpl);
1.288     brouard  6643:   fprintf(ficresvpl,"# Standard deviation of period (forward stable) prevalences \n");
1.241     brouard  6644:   fprintf(ficresvpl,"# Age ");
                   6645:   if(nresult >=1)
                   6646:     fprintf(ficresvpl," Result# ");
1.126     brouard  6647:   for(i=1; i<=nlstate;i++)
                   6648:       fprintf(ficresvpl," %1d-%1d",i,i);
                   6649:   fprintf(ficresvpl,"\n");
                   6650: 
                   6651:   xp=vector(1,npar);
1.268     brouard  6652:   dnewmpar=matrix(1,nlstate,1,npar);
1.126     brouard  6653:   doldm=matrix(1,nlstate,1,nlstate);
                   6654:   
                   6655:   hstepm=1*YEARM; /* Every year of age */
                   6656:   hstepm=hstepm/stepm; /* Typically in stepm units, if j= 2 years, = 2/6 months = 4 */ 
                   6657:   agelim = AGESUP;
                   6658:   for (age=bage; age<=fage; age ++){ /* If stepm=6 months */
                   6659:     nhstepm=(int) rint((agelim-age)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */ 
                   6660:     if (stepm >= YEARM) hstepm=1;
                   6661:     nhstepm = nhstepm/hstepm; /* Typically 40/4=10 */
                   6662:     gradg=matrix(1,npar,1,nlstate);
1.208     brouard  6663:     mgp=matrix(1,npar,1,nlstate);
                   6664:     mgm=matrix(1,npar,1,nlstate);
1.126     brouard  6665:     gp=vector(1,nlstate);
                   6666:     gm=vector(1,nlstate);
                   6667: 
                   6668:     for(theta=1; theta <=npar; theta++){
                   6669:       for(i=1; i<=npar; i++){ /* Computes gradient */
                   6670:        xp[i] = x[i] + (i==theta ?delti[theta]:0);
                   6671:       }
1.288     brouard  6672:       /* if((int)age==79 ||(int)age== 80 ||(int)age== 81 ) */
                   6673:       /*       prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp,ij,nres); */
                   6674:       /* else */
                   6675:       prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp,ij,nres);
1.208     brouard  6676:       for(i=1;i<=nlstate;i++){
1.126     brouard  6677:        gp[i] = prlim[i][i];
1.208     brouard  6678:        mgp[theta][i] = prlim[i][i];
                   6679:       }
1.126     brouard  6680:       for(i=1; i<=npar; i++) /* Computes gradient */
                   6681:        xp[i] = x[i] - (i==theta ?delti[theta]:0);
1.288     brouard  6682:       /* if((int)age==79 ||(int)age== 80 ||(int)age== 81 ) */
                   6683:       /*       prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp,ij,nres); */
                   6684:       /* else */
                   6685:       prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp,ij,nres);
1.208     brouard  6686:       for(i=1;i<=nlstate;i++){
1.126     brouard  6687:        gm[i] = prlim[i][i];
1.208     brouard  6688:        mgm[theta][i] = prlim[i][i];
                   6689:       }
1.126     brouard  6690:       for(i=1;i<=nlstate;i++)
                   6691:        gradg[theta][i]= (gp[i]-gm[i])/2./delti[theta];
1.209     brouard  6692:       /* gradg[theta][2]= -gradg[theta][1]; */ /* For testing if nlstate=2 */
1.126     brouard  6693:     } /* End theta */
                   6694: 
                   6695:     trgradg =matrix(1,nlstate,1,npar);
                   6696: 
                   6697:     for(j=1; j<=nlstate;j++)
                   6698:       for(theta=1; theta <=npar; theta++)
                   6699:        trgradg[j][theta]=gradg[theta][j];
1.209     brouard  6700:     /* if((int)age==79 ||(int)age== 80 ||(int)age== 81 ){ */
                   6701:     /*   printf("\nmgm mgp %d ",(int)age); */
                   6702:     /*   for(j=1; j<=nlstate;j++){ */
                   6703:     /*         printf(" %d ",j); */
                   6704:     /*         for(theta=1; theta <=npar; theta++) */
                   6705:     /*           printf(" %d %lf %lf",theta,mgm[theta][j],mgp[theta][j]); */
                   6706:     /*         printf("\n "); */
                   6707:     /*   } */
                   6708:     /* } */
                   6709:     /* if((int)age==79 ||(int)age== 80 ||(int)age== 81 ){ */
                   6710:     /*   printf("\n gradg %d ",(int)age); */
                   6711:     /*   for(j=1; j<=nlstate;j++){ */
                   6712:     /*         printf("%d ",j); */
                   6713:     /*         for(theta=1; theta <=npar; theta++) */
                   6714:     /*           printf("%d %lf ",theta,gradg[theta][j]); */
                   6715:     /*         printf("\n "); */
                   6716:     /*   } */
                   6717:     /* } */
1.126     brouard  6718: 
                   6719:     for(i=1;i<=nlstate;i++)
                   6720:       varpl[i][(int)age] =0.;
1.209     brouard  6721:     if((int)age==79 ||(int)age== 80  ||(int)age== 81){
1.268     brouard  6722:     matprod2(dnewmpar,trgradg,1,nlstate,1,npar,1,npar,matcov);
                   6723:     matprod2(doldm,dnewmpar,1,nlstate,1,npar,1,nlstate,gradg);
1.205     brouard  6724:     }else{
1.268     brouard  6725:     matprod2(dnewmpar,trgradg,1,nlstate,1,npar,1,npar,matcov);
                   6726:     matprod2(doldm,dnewmpar,1,nlstate,1,npar,1,nlstate,gradg);
1.205     brouard  6727:     }
1.126     brouard  6728:     for(i=1;i<=nlstate;i++)
                   6729:       varpl[i][(int)age] = doldm[i][i]; /* Covariances are useless */
                   6730: 
                   6731:     fprintf(ficresvpl,"%.0f ",age );
1.241     brouard  6732:     if(nresult >=1)
                   6733:       fprintf(ficresvpl,"%d ",nres );
1.288     brouard  6734:     for(i=1; i<=nlstate;i++){
1.126     brouard  6735:       fprintf(ficresvpl," %.5f (%.5f)",prlim[i][i],sqrt(varpl[i][(int)age]));
1.288     brouard  6736:       /* for(j=1;j<=nlstate;j++) */
                   6737:       /*       fprintf(ficresvpl," %d %.5f ",j,prlim[j][i]); */
                   6738:     }
1.126     brouard  6739:     fprintf(ficresvpl,"\n");
                   6740:     free_vector(gp,1,nlstate);
                   6741:     free_vector(gm,1,nlstate);
1.208     brouard  6742:     free_matrix(mgm,1,npar,1,nlstate);
                   6743:     free_matrix(mgp,1,npar,1,nlstate);
1.126     brouard  6744:     free_matrix(gradg,1,npar,1,nlstate);
                   6745:     free_matrix(trgradg,1,nlstate,1,npar);
                   6746:   } /* End age */
                   6747: 
                   6748:   free_vector(xp,1,npar);
                   6749:   free_matrix(doldm,1,nlstate,1,npar);
1.268     brouard  6750:   free_matrix(dnewmpar,1,nlstate,1,nlstate);
                   6751: 
                   6752: }
                   6753: 
                   6754: 
                   6755: /************ Variance of backprevalence limit ******************/
1.269     brouard  6756:  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  6757: {
                   6758:   /* Variance of backward prevalence limit  for each state ij using current parameters x[] and estimates of neighbourhood give by delti*/
                   6759:   /*  double **prevalim(double **prlim, int nlstate, double *xp, double age, double **oldm, double **savm,double ftolpl);*/
                   6760: 
                   6761:   double **dnewmpar,**doldm;
                   6762:   int i, j, nhstepm, hstepm;
                   6763:   double *xp;
                   6764:   double *gp, *gm;
                   6765:   double **gradg, **trgradg;
                   6766:   double **mgm, **mgp;
                   6767:   double age,agelim;
                   6768:   int theta;
                   6769:   
                   6770:   pstamp(ficresvbl);
                   6771:   fprintf(ficresvbl,"# Standard deviation of back (stable) prevalences \n");
                   6772:   fprintf(ficresvbl,"# Age ");
                   6773:   if(nresult >=1)
                   6774:     fprintf(ficresvbl," Result# ");
                   6775:   for(i=1; i<=nlstate;i++)
                   6776:       fprintf(ficresvbl," %1d-%1d",i,i);
                   6777:   fprintf(ficresvbl,"\n");
                   6778: 
                   6779:   xp=vector(1,npar);
                   6780:   dnewmpar=matrix(1,nlstate,1,npar);
                   6781:   doldm=matrix(1,nlstate,1,nlstate);
                   6782:   
                   6783:   hstepm=1*YEARM; /* Every year of age */
                   6784:   hstepm=hstepm/stepm; /* Typically in stepm units, if j= 2 years, = 2/6 months = 4 */ 
                   6785:   agelim = AGEINF;
                   6786:   for (age=fage; age>=bage; age --){ /* If stepm=6 months */
                   6787:     nhstepm=(int) rint((age-agelim)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */ 
                   6788:     if (stepm >= YEARM) hstepm=1;
                   6789:     nhstepm = nhstepm/hstepm; /* Typically 40/4=10 */
                   6790:     gradg=matrix(1,npar,1,nlstate);
                   6791:     mgp=matrix(1,npar,1,nlstate);
                   6792:     mgm=matrix(1,npar,1,nlstate);
                   6793:     gp=vector(1,nlstate);
                   6794:     gm=vector(1,nlstate);
                   6795: 
                   6796:     for(theta=1; theta <=npar; theta++){
                   6797:       for(i=1; i<=npar; i++){ /* Computes gradient */
                   6798:        xp[i] = x[i] + (i==theta ?delti[theta]:0);
                   6799:       }
                   6800:       if(mobilavproj > 0 )
                   6801:        bprevalim(bprlim, mobaverage,nlstate,xp,age,ftolpl,ncvyearp,ij,nres);
                   6802:       else
                   6803:        bprevalim(bprlim, mobaverage,nlstate,xp,age,ftolpl,ncvyearp,ij,nres);
                   6804:       for(i=1;i<=nlstate;i++){
                   6805:        gp[i] = bprlim[i][i];
                   6806:        mgp[theta][i] = bprlim[i][i];
                   6807:       }
                   6808:      for(i=1; i<=npar; i++) /* Computes gradient */
                   6809:        xp[i] = x[i] - (i==theta ?delti[theta]:0);
                   6810:        if(mobilavproj > 0 )
                   6811:        bprevalim(bprlim, mobaverage,nlstate,xp,age,ftolpl,ncvyearp,ij,nres);
                   6812:        else
                   6813:        bprevalim(bprlim, mobaverage,nlstate,xp,age,ftolpl,ncvyearp,ij,nres);
                   6814:       for(i=1;i<=nlstate;i++){
                   6815:        gm[i] = bprlim[i][i];
                   6816:        mgm[theta][i] = bprlim[i][i];
                   6817:       }
                   6818:       for(i=1;i<=nlstate;i++)
                   6819:        gradg[theta][i]= (gp[i]-gm[i])/2./delti[theta];
                   6820:       /* gradg[theta][2]= -gradg[theta][1]; */ /* For testing if nlstate=2 */
                   6821:     } /* End theta */
                   6822: 
                   6823:     trgradg =matrix(1,nlstate,1,npar);
                   6824: 
                   6825:     for(j=1; j<=nlstate;j++)
                   6826:       for(theta=1; theta <=npar; theta++)
                   6827:        trgradg[j][theta]=gradg[theta][j];
                   6828:     /* if((int)age==79 ||(int)age== 80 ||(int)age== 81 ){ */
                   6829:     /*   printf("\nmgm mgp %d ",(int)age); */
                   6830:     /*   for(j=1; j<=nlstate;j++){ */
                   6831:     /*         printf(" %d ",j); */
                   6832:     /*         for(theta=1; theta <=npar; theta++) */
                   6833:     /*           printf(" %d %lf %lf",theta,mgm[theta][j],mgp[theta][j]); */
                   6834:     /*         printf("\n "); */
                   6835:     /*   } */
                   6836:     /* } */
                   6837:     /* if((int)age==79 ||(int)age== 80 ||(int)age== 81 ){ */
                   6838:     /*   printf("\n gradg %d ",(int)age); */
                   6839:     /*   for(j=1; j<=nlstate;j++){ */
                   6840:     /*         printf("%d ",j); */
                   6841:     /*         for(theta=1; theta <=npar; theta++) */
                   6842:     /*           printf("%d %lf ",theta,gradg[theta][j]); */
                   6843:     /*         printf("\n "); */
                   6844:     /*   } */
                   6845:     /* } */
                   6846: 
                   6847:     for(i=1;i<=nlstate;i++)
                   6848:       varbpl[i][(int)age] =0.;
                   6849:     if((int)age==79 ||(int)age== 80  ||(int)age== 81){
                   6850:     matprod2(dnewmpar,trgradg,1,nlstate,1,npar,1,npar,matcov);
                   6851:     matprod2(doldm,dnewmpar,1,nlstate,1,npar,1,nlstate,gradg);
                   6852:     }else{
                   6853:     matprod2(dnewmpar,trgradg,1,nlstate,1,npar,1,npar,matcov);
                   6854:     matprod2(doldm,dnewmpar,1,nlstate,1,npar,1,nlstate,gradg);
                   6855:     }
                   6856:     for(i=1;i<=nlstate;i++)
                   6857:       varbpl[i][(int)age] = doldm[i][i]; /* Covariances are useless */
                   6858: 
                   6859:     fprintf(ficresvbl,"%.0f ",age );
                   6860:     if(nresult >=1)
                   6861:       fprintf(ficresvbl,"%d ",nres );
                   6862:     for(i=1; i<=nlstate;i++)
                   6863:       fprintf(ficresvbl," %.5f (%.5f)",bprlim[i][i],sqrt(varbpl[i][(int)age]));
                   6864:     fprintf(ficresvbl,"\n");
                   6865:     free_vector(gp,1,nlstate);
                   6866:     free_vector(gm,1,nlstate);
                   6867:     free_matrix(mgm,1,npar,1,nlstate);
                   6868:     free_matrix(mgp,1,npar,1,nlstate);
                   6869:     free_matrix(gradg,1,npar,1,nlstate);
                   6870:     free_matrix(trgradg,1,nlstate,1,npar);
                   6871:   } /* End age */
                   6872: 
                   6873:   free_vector(xp,1,npar);
                   6874:   free_matrix(doldm,1,nlstate,1,npar);
                   6875:   free_matrix(dnewmpar,1,nlstate,1,nlstate);
1.126     brouard  6876: 
                   6877: }
                   6878: 
                   6879: /************ Variance of one-step probabilities  ******************/
                   6880: 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  6881:  {
                   6882:    int i, j=0,  k1, l1, tj;
                   6883:    int k2, l2, j1,  z1;
                   6884:    int k=0, l;
                   6885:    int first=1, first1, first2;
1.326     brouard  6886:    int nres=0; /* New */
1.222     brouard  6887:    double cv12, mu1, mu2, lc1, lc2, v12, v21, v11, v22,v1,v2, c12, tnalp;
                   6888:    double **dnewm,**doldm;
                   6889:    double *xp;
                   6890:    double *gp, *gm;
                   6891:    double **gradg, **trgradg;
                   6892:    double **mu;
                   6893:    double age, cov[NCOVMAX+1];
                   6894:    double std=2.0; /* Number of standard deviation wide of confidence ellipsoids */
                   6895:    int theta;
                   6896:    char fileresprob[FILENAMELENGTH];
                   6897:    char fileresprobcov[FILENAMELENGTH];
                   6898:    char fileresprobcor[FILENAMELENGTH];
                   6899:    double ***varpij;
                   6900: 
                   6901:    strcpy(fileresprob,"PROB_"); 
                   6902:    strcat(fileresprob,fileres);
                   6903:    if((ficresprob=fopen(fileresprob,"w"))==NULL) {
                   6904:      printf("Problem with resultfile: %s\n", fileresprob);
                   6905:      fprintf(ficlog,"Problem with resultfile: %s\n", fileresprob);
                   6906:    }
                   6907:    strcpy(fileresprobcov,"PROBCOV_"); 
                   6908:    strcat(fileresprobcov,fileresu);
                   6909:    if((ficresprobcov=fopen(fileresprobcov,"w"))==NULL) {
                   6910:      printf("Problem with resultfile: %s\n", fileresprobcov);
                   6911:      fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobcov);
                   6912:    }
                   6913:    strcpy(fileresprobcor,"PROBCOR_"); 
                   6914:    strcat(fileresprobcor,fileresu);
                   6915:    if((ficresprobcor=fopen(fileresprobcor,"w"))==NULL) {
                   6916:      printf("Problem with resultfile: %s\n", fileresprobcor);
                   6917:      fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobcor);
                   6918:    }
                   6919:    printf("Computing standard deviation of one-step probabilities: result on file '%s' \n",fileresprob);
                   6920:    fprintf(ficlog,"Computing standard deviation of one-step probabilities: result on file '%s' \n",fileresprob);
                   6921:    printf("Computing matrix of variance covariance of one-step probabilities: result on file '%s' \n",fileresprobcov);
                   6922:    fprintf(ficlog,"Computing matrix of variance covariance of one-step probabilities: result on file '%s' \n",fileresprobcov);
                   6923:    printf("and correlation matrix of one-step probabilities: result on file '%s' \n",fileresprobcor);
                   6924:    fprintf(ficlog,"and correlation matrix of one-step probabilities: result on file '%s' \n",fileresprobcor);
                   6925:    pstamp(ficresprob);
                   6926:    fprintf(ficresprob,"#One-step probabilities and stand. devi in ()\n");
                   6927:    fprintf(ficresprob,"# Age");
                   6928:    pstamp(ficresprobcov);
                   6929:    fprintf(ficresprobcov,"#One-step probabilities and covariance matrix\n");
                   6930:    fprintf(ficresprobcov,"# Age");
                   6931:    pstamp(ficresprobcor);
                   6932:    fprintf(ficresprobcor,"#One-step probabilities and correlation matrix\n");
                   6933:    fprintf(ficresprobcor,"# Age");
1.126     brouard  6934: 
                   6935: 
1.222     brouard  6936:    for(i=1; i<=nlstate;i++)
                   6937:      for(j=1; j<=(nlstate+ndeath);j++){
                   6938:        fprintf(ficresprob," p%1d-%1d (SE)",i,j);
                   6939:        fprintf(ficresprobcov," p%1d-%1d ",i,j);
                   6940:        fprintf(ficresprobcor," p%1d-%1d ",i,j);
                   6941:      }  
                   6942:    /* fprintf(ficresprob,"\n");
                   6943:       fprintf(ficresprobcov,"\n");
                   6944:       fprintf(ficresprobcor,"\n");
                   6945:    */
                   6946:    xp=vector(1,npar);
                   6947:    dnewm=matrix(1,(nlstate)*(nlstate+ndeath),1,npar);
                   6948:    doldm=matrix(1,(nlstate)*(nlstate+ndeath),1,(nlstate)*(nlstate+ndeath));
                   6949:    mu=matrix(1,(nlstate)*(nlstate+ndeath), (int) bage, (int)fage);
                   6950:    varpij=ma3x(1,nlstate*(nlstate+ndeath),1,nlstate*(nlstate+ndeath),(int) bage, (int) fage);
                   6951:    first=1;
                   6952:    fprintf(ficgp,"\n# Routine varprob");
                   6953:    fprintf(fichtm,"\n<li><h4> Computing and drawing one step probabilities with their confidence intervals</h4></li>\n");
                   6954:    fprintf(fichtm,"\n");
                   6955: 
1.288     brouard  6956:    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  6957:    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);
                   6958:    fprintf(fichtmcov,"\nEllipsoids of confidence centered on point (p<inf>ij</inf>, p<inf>kl</inf>) are estimated \
1.126     brouard  6959: and drawn. It helps understanding how is the covariance between two incidences.\
                   6960:  They are expressed in year<sup>-1</sup> in order to be less dependent of stepm.<br>\n");
1.222     brouard  6961:    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  6962: It can be understood this way: if pij and pkl where uncorrelated the (2x2) matrix of covariance \
                   6963: would have been (1/(var pij), 0 , 0, 1/(var pkl)), and the confidence interval would be 2 \
                   6964: standard deviations wide on each axis. <br>\
                   6965:  Now, if both incidences are correlated (usual case) we diagonalised the inverse of the covariance matrix\
                   6966:  and made the appropriate rotation to look at the uncorrelated principal directions.<br>\
                   6967: To be simple, these graphs help to understand the significativity of each parameter in relation to a second other one.<br> \n");
                   6968: 
1.222     brouard  6969:    cov[1]=1;
                   6970:    /* tj=cptcoveff; */
1.225     brouard  6971:    tj = (int) pow(2,cptcoveff);
1.222     brouard  6972:    if (cptcovn<1) {tj=1;ncodemax[1]=1;}
                   6973:    j1=0;
1.224     brouard  6974:    for(j1=1; j1<=tj;j1++){  /* For each valid combination of covariates or only once*/
1.326     brouard  6975:      for(nres=1;nres <=1; nres++){ /* For each resultline */
                   6976:      /* for(nres=1;nres <=nresult; nres++){ /\* For each resultline *\/ */
1.222     brouard  6977:      if  (cptcovn>0) {
                   6978:        fprintf(ficresprob, "\n#********** Variable "); 
1.330   ! brouard  6979:        for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresprob, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,Tvaraff[z1])]);
1.222     brouard  6980:        fprintf(ficresprob, "**********\n#\n");
                   6981:        fprintf(ficresprobcov, "\n#********** Variable "); 
1.330   ! brouard  6982:        for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresprobcov, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,Tvaraff[z1])]);
1.222     brouard  6983:        fprintf(ficresprobcov, "**********\n#\n");
1.220     brouard  6984:                        
1.222     brouard  6985:        fprintf(ficgp, "\n#********** Variable "); 
1.330   ! brouard  6986:        for (z1=1; z1<=cptcoveff; z1++) fprintf(ficgp, " V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,Tvaraff[z1])]);
1.222     brouard  6987:        fprintf(ficgp, "**********\n#\n");
1.220     brouard  6988:                        
                   6989:                        
1.222     brouard  6990:        fprintf(fichtmcov, "\n<hr  size=\"2\" color=\"#EC5E5E\">********** Variable "); 
1.319     brouard  6991:        /* for (z1=1; z1<=cptcoveff; z1++) fprintf(fichtm, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]); */
1.330   ! brouard  6992:        for (z1=1; z1<=cptcoveff; z1++) fprintf(fichtmcov, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,Tvaraff[z1])]);
1.222     brouard  6993:        fprintf(fichtmcov, "**********\n<hr size=\"2\" color=\"#EC5E5E\">");
1.220     brouard  6994:                        
1.222     brouard  6995:        fprintf(ficresprobcor, "\n#********** Variable ");    
1.330   ! brouard  6996:        for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresprobcor, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,Tvaraff[z1])]);
1.222     brouard  6997:        fprintf(ficresprobcor, "**********\n#");    
                   6998:        if(invalidvarcomb[j1]){
                   6999:         fprintf(ficgp,"\n#Combination (%d) ignored because no cases \n",j1); 
                   7000:         fprintf(fichtmcov,"\n<h3>Combination (%d) ignored because no cases </h3>\n",j1); 
                   7001:         continue;
                   7002:        }
                   7003:      }
                   7004:      gradg=matrix(1,npar,1,(nlstate)*(nlstate+ndeath));
                   7005:      trgradg=matrix(1,(nlstate)*(nlstate+ndeath),1,npar);
                   7006:      gp=vector(1,(nlstate)*(nlstate+ndeath));
                   7007:      gm=vector(1,(nlstate)*(nlstate+ndeath));
                   7008:      for (age=bage; age<=fage; age ++){ 
                   7009:        cov[2]=age;
                   7010:        if(nagesqr==1)
                   7011:         cov[3]= age*age;
1.326     brouard  7012:        /* for (k=1; k<=cptcovn;k++) { */
                   7013:        /*       cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(j1,k)]; */
                   7014:        for (k=1; k<=nsd;k++) { /* For single dummy covariates only */
                   7015:         /* Here comes the value of the covariate 'j1' after renumbering k with single dummy covariates */
1.330   ! brouard  7016:         cov[2+nagesqr+TvarsDind[k]]=nbcode[TvarsD[k]][codtabm(j1,TvarsD[k])];
1.222     brouard  7017:         /*cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(j1,Tvar[k])];*//* j1 1 2 3 4
                   7018:                                                                    * 1  1 1 1 1
                   7019:                                                                    * 2  2 1 1 1
                   7020:                                                                    * 3  1 2 1 1
                   7021:                                                                    */
                   7022:         /* nbcode[1][1]=0 nbcode[1][2]=1;*/
                   7023:        }
1.319     brouard  7024:        /* V2+V1+V4+V3*age Tvar[4]=3 ; V1+V2*age Tvar[2]=2; V1+V1*age Tvar[2]=1, Tage[1]=2 */
                   7025:        /* ) p nbcode[Tvar[Tage[k]]][(1 & (ij-1) >> (k-1))+1] */
                   7026:        /*for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2]; */
1.326     brouard  7027:        for (k=1; k<=cptcovage;k++){  /* For product with age */
                   7028:         if(Dummy[Tage[k]]==2){ /* dummy with age */
1.330   ! brouard  7029:           cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(j1,Tvar[Tage[k]])]*cov[2];
1.326     brouard  7030:           /* cov[++k1]=nbcode[Tvar[Tage[k]]][codtabm(ij,k)]*cov[2]; */
                   7031:         } else if(Dummy[Tage[k]]==3){ /* quantitative with age */
1.327     brouard  7032:           printf("Internal IMaCh error, don't know which value for quantitative covariate with age, Tage[k]%d, k=%d, Tvar[Tage[k]]=V%d, age=%d\n",Tage[k],k ,Tvar[Tage[k]], (int)cov[2]);
                   7033:           exit(1);
                   7034:             /* cov[2+nagesqr+Tage[k]]=meanq[k]/idq[k]*cov[2];/\* Using the mean of quantitative variable Tvar[Tage[k]] /\* Tqresult[nres][k]; *\/ */
1.326     brouard  7035:           /* cov[++k1]=Tqresult[nres][k];  */
                   7036:         }
                   7037:         /* cov[2+Tage[k]+nagesqr]=nbcode[Tvar[Tage[k]]][codtabm(ij,k)]*cov[2]; */
                   7038:        }
                   7039:        for (k=1; k<=cptcovprod;k++){/* For product without age */
1.329     brouard  7040:         if(Dummy[Tvard[k][1]]==0){
                   7041:           if(Dummy[Tvard[k][2]]==0){
1.330   ! brouard  7042:             cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(j1,Tvard[k][1])] * nbcode[Tvard[k][2]][codtabm(j1,Tvard[k][2])];
1.326     brouard  7043:             /* cov[++k1]=nbcode[Tvard[k][1]][codtabm(ij,k)] * nbcode[Tvard[k][2]][codtabm(ij,k)]; */
                   7044:           }else{ /* Should we use the mean of the quantitative variables? */
1.330   ! brouard  7045:             cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(j1,Tvard[k][1])] * Tqresult[nres][k];
1.326     brouard  7046:             /* cov[++k1]=nbcode[Tvard[k][1]][codtabm(ij,k)] * Tqresult[nres][k]; */
                   7047:           }
                   7048:         }else{
1.329     brouard  7049:           if(Dummy[Tvard[k][2]]==0){
1.330   ! brouard  7050:             cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][2]][codtabm(j1,Tvard[k][2])] * Tqinvresult[nres][Tvard[k][1]];
1.326     brouard  7051:             /* cov[++k1]=nbcode[Tvard[k][2]][codtabm(ij,k)] * Tqinvresult[nres][Tvard[k][1]]; */
                   7052:           }else{
                   7053:             cov[2+nagesqr+Tprod[k]]=Tqinvresult[nres][Tvard[k][1]]*  Tqinvresult[nres][Tvard[k][2]];
                   7054:             /* cov[++k1]=Tqinvresult[nres][Tvard[k][1]]*  Tqinvresult[nres][Tvard[k][2]]; */
                   7055:           }
                   7056:         }
                   7057:         /* cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)]*nbcode[Tvard[k][2]][codtabm(ij,k)]; */
                   7058:        }                       
                   7059: /* For each age and combination of dummy covariates we slightly move the parameters of delti in order to get the gradient*/                    
1.222     brouard  7060:        for(theta=1; theta <=npar; theta++){
                   7061:         for(i=1; i<=npar; i++)
                   7062:           xp[i] = x[i] + (i==theta ?delti[theta]:(double)0);
1.220     brouard  7063:                                
1.222     brouard  7064:         pmij(pmmij,cov,ncovmodel,xp,nlstate);
1.220     brouard  7065:                                
1.222     brouard  7066:         k=0;
                   7067:         for(i=1; i<= (nlstate); i++){
                   7068:           for(j=1; j<=(nlstate+ndeath);j++){
                   7069:             k=k+1;
                   7070:             gp[k]=pmmij[i][j];
                   7071:           }
                   7072:         }
1.220     brouard  7073:                                
1.222     brouard  7074:         for(i=1; i<=npar; i++)
                   7075:           xp[i] = x[i] - (i==theta ?delti[theta]:(double)0);
1.220     brouard  7076:                                
1.222     brouard  7077:         pmij(pmmij,cov,ncovmodel,xp,nlstate);
                   7078:         k=0;
                   7079:         for(i=1; i<=(nlstate); i++){
                   7080:           for(j=1; j<=(nlstate+ndeath);j++){
                   7081:             k=k+1;
                   7082:             gm[k]=pmmij[i][j];
                   7083:           }
                   7084:         }
1.220     brouard  7085:                                
1.222     brouard  7086:         for(i=1; i<= (nlstate)*(nlstate+ndeath); i++) 
                   7087:           gradg[theta][i]=(gp[i]-gm[i])/(double)2./delti[theta];  
                   7088:        }
1.126     brouard  7089: 
1.222     brouard  7090:        for(j=1; j<=(nlstate)*(nlstate+ndeath);j++)
                   7091:         for(theta=1; theta <=npar; theta++)
                   7092:           trgradg[j][theta]=gradg[theta][j];
1.220     brouard  7093:                        
1.222     brouard  7094:        matprod2(dnewm,trgradg,1,(nlstate)*(nlstate+ndeath),1,npar,1,npar,matcov); 
                   7095:        matprod2(doldm,dnewm,1,(nlstate)*(nlstate+ndeath),1,npar,1,(nlstate)*(nlstate+ndeath),gradg);
1.220     brouard  7096:                        
1.222     brouard  7097:        pmij(pmmij,cov,ncovmodel,x,nlstate);
1.220     brouard  7098:                        
1.222     brouard  7099:        k=0;
                   7100:        for(i=1; i<=(nlstate); i++){
                   7101:         for(j=1; j<=(nlstate+ndeath);j++){
                   7102:           k=k+1;
                   7103:           mu[k][(int) age]=pmmij[i][j];
                   7104:         }
                   7105:        }
                   7106:        for(i=1;i<=(nlstate)*(nlstate+ndeath);i++)
                   7107:         for(j=1;j<=(nlstate)*(nlstate+ndeath);j++)
                   7108:           varpij[i][j][(int)age] = doldm[i][j];
1.220     brouard  7109:                        
1.222     brouard  7110:        /*printf("\n%d ",(int)age);
                   7111:         for (i=1; i<=(nlstate)*(nlstate+ndeath);i++){
                   7112:         printf("%e [%e ;%e] ",gm[i],gm[i]-2*sqrt(doldm[i][i]),gm[i]+2*sqrt(doldm[i][i]));
                   7113:         fprintf(ficlog,"%e [%e ;%e] ",gm[i],gm[i]-2*sqrt(doldm[i][i]),gm[i]+2*sqrt(doldm[i][i]));
                   7114:         }*/
1.220     brouard  7115:                        
1.222     brouard  7116:        fprintf(ficresprob,"\n%d ",(int)age);
                   7117:        fprintf(ficresprobcov,"\n%d ",(int)age);
                   7118:        fprintf(ficresprobcor,"\n%d ",(int)age);
1.220     brouard  7119:                        
1.222     brouard  7120:        for (i=1; i<=(nlstate)*(nlstate+ndeath);i++)
                   7121:         fprintf(ficresprob,"%11.3e (%11.3e) ",mu[i][(int) age],sqrt(varpij[i][i][(int)age]));
                   7122:        for (i=1; i<=(nlstate)*(nlstate+ndeath);i++){
                   7123:         fprintf(ficresprobcov,"%11.3e ",mu[i][(int) age]);
                   7124:         fprintf(ficresprobcor,"%11.3e ",mu[i][(int) age]);
                   7125:        }
                   7126:        i=0;
                   7127:        for (k=1; k<=(nlstate);k++){
                   7128:         for (l=1; l<=(nlstate+ndeath);l++){ 
                   7129:           i++;
                   7130:           fprintf(ficresprobcov,"\n%d %d-%d",(int)age,k,l);
                   7131:           fprintf(ficresprobcor,"\n%d %d-%d",(int)age,k,l);
                   7132:           for (j=1; j<=i;j++){
                   7133:             /* printf(" k=%d l=%d i=%d j=%d\n",k,l,i,j);fflush(stdout); */
                   7134:             fprintf(ficresprobcov," %11.3e",varpij[i][j][(int)age]);
                   7135:             fprintf(ficresprobcor," %11.3e",varpij[i][j][(int) age]/sqrt(varpij[i][i][(int) age])/sqrt(varpij[j][j][(int)age]));
                   7136:           }
                   7137:         }
                   7138:        }/* end of loop for state */
                   7139:      } /* end of loop for age */
                   7140:      free_vector(gp,1,(nlstate+ndeath)*(nlstate+ndeath));
                   7141:      free_vector(gm,1,(nlstate+ndeath)*(nlstate+ndeath));
                   7142:      free_matrix(trgradg,1,(nlstate+ndeath)*(nlstate+ndeath),1,npar);
                   7143:      free_matrix(gradg,1,(nlstate+ndeath)*(nlstate+ndeath),1,npar);
                   7144:     
                   7145:      /* Confidence intervalle of pij  */
                   7146:      /*
                   7147:        fprintf(ficgp,"\nunset parametric;unset label");
                   7148:        fprintf(ficgp,"\nset log y;unset log x; set xlabel \"Age\";set ylabel \"probability (year-1)\"");
                   7149:        fprintf(ficgp,"\nset ter png small\nset size 0.65,0.65");
                   7150:        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);
                   7151:        fprintf(fichtm,"\n<br><img src=\"pijgr%s.png\"> ",optionfilefiname);
                   7152:        fprintf(ficgp,"\nset out \"pijgr%s.png\"",optionfilefiname);
                   7153:        fprintf(ficgp,"\nplot \"%s\" every :::%d::%d u 1:2 \"\%%lf",k1,k2,xfilevarprob);
                   7154:      */
                   7155:                
                   7156:      /* Drawing ellipsoids of confidence of two variables p(k1-l1,k2-l2)*/
                   7157:      first1=1;first2=2;
                   7158:      for (k2=1; k2<=(nlstate);k2++){
                   7159:        for (l2=1; l2<=(nlstate+ndeath);l2++){ 
                   7160:         if(l2==k2) continue;
                   7161:         j=(k2-1)*(nlstate+ndeath)+l2;
                   7162:         for (k1=1; k1<=(nlstate);k1++){
                   7163:           for (l1=1; l1<=(nlstate+ndeath);l1++){ 
                   7164:             if(l1==k1) continue;
                   7165:             i=(k1-1)*(nlstate+ndeath)+l1;
                   7166:             if(i<=j) continue;
                   7167:             for (age=bage; age<=fage; age ++){ 
                   7168:               if ((int)age %5==0){
                   7169:                 v1=varpij[i][i][(int)age]/stepm*YEARM/stepm*YEARM;
                   7170:                 v2=varpij[j][j][(int)age]/stepm*YEARM/stepm*YEARM;
                   7171:                 cv12=varpij[i][j][(int)age]/stepm*YEARM/stepm*YEARM;
                   7172:                 mu1=mu[i][(int) age]/stepm*YEARM ;
                   7173:                 mu2=mu[j][(int) age]/stepm*YEARM;
                   7174:                 c12=cv12/sqrt(v1*v2);
                   7175:                 /* Computing eigen value of matrix of covariance */
                   7176:                 lc1=((v1+v2)+sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
                   7177:                 lc2=((v1+v2)-sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
                   7178:                 if ((lc2 <0) || (lc1 <0) ){
                   7179:                   if(first2==1){
                   7180:                     first1=0;
                   7181:                     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);
                   7182:                   }
                   7183:                   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);
                   7184:                   /* lc1=fabs(lc1); */ /* If we want to have them positive */
                   7185:                   /* lc2=fabs(lc2); */
                   7186:                 }
1.220     brouard  7187:                                                                
1.222     brouard  7188:                 /* Eigen vectors */
1.280     brouard  7189:                 if(1+(v1-lc1)*(v1-lc1)/cv12/cv12 <1.e-5){
                   7190:                   printf(" Error sqrt of a negative number: %lf\n",1+(v1-lc1)*(v1-lc1)/cv12/cv12);
                   7191:                   fprintf(ficlog," Error sqrt of a negative number: %lf\n",1+(v1-lc1)*(v1-lc1)/cv12/cv12);
                   7192:                   v11=(1./sqrt(fabs(1+(v1-lc1)*(v1-lc1)/cv12/cv12)));
                   7193:                 }else
                   7194:                   v11=(1./sqrt(1+(v1-lc1)*(v1-lc1)/cv12/cv12));
1.222     brouard  7195:                 /*v21=sqrt(1.-v11*v11); *//* error */
                   7196:                 v21=(lc1-v1)/cv12*v11;
                   7197:                 v12=-v21;
                   7198:                 v22=v11;
                   7199:                 tnalp=v21/v11;
                   7200:                 if(first1==1){
                   7201:                   first1=0;
                   7202:                   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);
                   7203:                 }
                   7204:                 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);
                   7205:                 /*printf(fignu*/
                   7206:                 /* mu1+ v11*lc1*cost + v12*lc2*sin(t) */
                   7207:                 /* mu2+ v21*lc1*cost + v22*lc2*sin(t) */
                   7208:                 if(first==1){
                   7209:                   first=0;
                   7210:                   fprintf(ficgp,"\n# Ellipsoids of confidence\n#\n");
                   7211:                   fprintf(ficgp,"\nset parametric;unset label");
                   7212:                   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);
                   7213:                   fprintf(ficgp,"\nset ter svg size 640, 480");
1.266     brouard  7214:                   fprintf(fichtmcov,"\n<p><br>Ellipsoids of confidence cov(p%1d%1d,p%1d%1d) expressed in year<sup>-1</sup>\
1.220     brouard  7215:  :<a href=\"%s_%d%1d%1d-%1d%1d.svg\">                                                                                                                                          \
1.201     brouard  7216: %s_%d%1d%1d-%1d%1d.svg</A>, ",k1,l1,k2,l2,\
1.222     brouard  7217:                           subdirf2(optionfilefiname,"VARPIJGR_"), j1,k1,l1,k2,l2,      \
                   7218:                           subdirf2(optionfilefiname,"VARPIJGR_"), j1,k1,l1,k2,l2);
                   7219:                   fprintf(fichtmcov,"\n<br><img src=\"%s_%d%1d%1d-%1d%1d.svg\"> ",subdirf2(optionfilefiname,"VARPIJGR_"), j1,k1,l1,k2,l2);
                   7220:                   fprintf(fichtmcov,"\n<br> Correlation at age %d (%.3f),",(int) age, c12);
                   7221:                   fprintf(ficgp,"\nset out \"%s_%d%1d%1d-%1d%1d.svg\"",subdirf2(optionfilefiname,"VARPIJGR_"), j1,k1,l1,k2,l2);
                   7222:                   fprintf(ficgp,"\nset label \"%d\" at %11.3e,%11.3e center",(int) age, mu1,mu2);
                   7223:                   fprintf(ficgp,"\n# Age %d, p%1d%1d - p%1d%1d",(int) age, k1,l1,k2,l2);
                   7224:                   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  7225:                           mu1,std,v11,sqrt(fabs(lc1)),v12,sqrt(fabs(lc2)), \
                   7226:                           mu2,std,v21,sqrt(fabs(lc1)),v22,sqrt(fabs(lc2))); /* For gnuplot only */
1.222     brouard  7227:                 }else{
                   7228:                   first=0;
                   7229:                   fprintf(fichtmcov," %d (%.3f),",(int) age, c12);
                   7230:                   fprintf(ficgp,"\n# Age %d, p%1d%1d - p%1d%1d",(int) age, k1,l1,k2,l2);
                   7231:                   fprintf(ficgp,"\nset label \"%d\" at %11.3e,%11.3e center",(int) age, mu1,mu2);
                   7232:                   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  7233:                           mu1,std,v11,sqrt(lc1),v12,sqrt(fabs(lc2)),   \
                   7234:                           mu2,std,v21,sqrt(lc1),v22,sqrt(fabs(lc2)));
1.222     brouard  7235:                 }/* if first */
                   7236:               } /* age mod 5 */
                   7237:             } /* end loop age */
                   7238:             fprintf(ficgp,"\nset out;\nset out \"%s_%d%1d%1d-%1d%1d.svg\";replot;set out;",subdirf2(optionfilefiname,"VARPIJGR_"), j1,k1,l1,k2,l2);
                   7239:             first=1;
                   7240:           } /*l12 */
                   7241:         } /* k12 */
                   7242:        } /*l1 */
                   7243:      }/* k1 */
1.326     brouard  7244:    } /* loop on nres */
1.222     brouard  7245:    }  /* loop on combination of covariates j1 */
                   7246:    free_ma3x(varpij,1,nlstate,1,nlstate+ndeath,(int) bage, (int)fage);
                   7247:    free_matrix(mu,1,(nlstate+ndeath)*(nlstate+ndeath),(int) bage, (int)fage);
                   7248:    free_matrix(doldm,1,(nlstate)*(nlstate+ndeath),1,(nlstate)*(nlstate+ndeath));
                   7249:    free_matrix(dnewm,1,(nlstate)*(nlstate+ndeath),1,npar);
                   7250:    free_vector(xp,1,npar);
                   7251:    fclose(ficresprob);
                   7252:    fclose(ficresprobcov);
                   7253:    fclose(ficresprobcor);
                   7254:    fflush(ficgp);
                   7255:    fflush(fichtmcov);
                   7256:  }
1.126     brouard  7257: 
                   7258: 
                   7259: /******************* Printing html file ***********/
1.201     brouard  7260: void printinghtml(char fileresu[], char title[], char datafile[], int firstpass, \
1.126     brouard  7261:                  int lastpass, int stepm, int weightopt, char model[],\
                   7262:                  int imx,int jmin, int jmax, double jmeanint,char rfileres[],\
1.296     brouard  7263:                  int popforecast, int mobilav, int prevfcast, int mobilavproj, int prevbcast, int estepm , \
                   7264:                  double jprev1, double mprev1,double anprev1, double dateprev1, double dateprojd, double dateback1, \
                   7265:                  double jprev2, double mprev2,double anprev2, double dateprev2, double dateprojf, double dateback2){
1.237     brouard  7266:   int jj1, k1, i1, cpt, k4, nres;
1.319     brouard  7267:   /* In fact some results are already printed in fichtm which is open */
1.126     brouard  7268:    fprintf(fichtm,"<ul><li><a href='#firstorder'>Result files (first order: no variance)</a>\n \
                   7269:    <li><a href='#secondorder'>Result files (second order (variance)</a>\n \
                   7270: </ul>");
1.319     brouard  7271: /*    fprintf(fichtm,"<ul><li> model=1+age+%s\n \ */
                   7272: /* </ul>", model); */
1.214     brouard  7273:    fprintf(fichtm,"<ul><li><h4><a name='firstorder'>Result files (first order: no variance)</a></h4>\n");
                   7274:    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",
                   7275:           jprev1, mprev1,anprev1,jprev2, mprev2,anprev2,subdirfext3(optionfilefiname,"PHTMFR_",".htm"),subdirfext3(optionfilefiname,"PHTMFR_",".htm"));
                   7276:    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  7277:           jprev1, mprev1,anprev1,jprev2, mprev2,anprev2,subdirfext3(optionfilefiname,"PHTM_",".htm"),subdirfext3(optionfilefiname,"PHTM_",".htm"));
                   7278:    fprintf(fichtm,",  <a href=\"%s\">%s</a> (text file) <br>\n",subdirf2(fileresu,"P_"),subdirf2(fileresu,"P_"));
1.126     brouard  7279:    fprintf(fichtm,"\
                   7280:  - Estimated transition probabilities over %d (stepm) months: <a href=\"%s\">%s</a><br>\n ",
1.201     brouard  7281:           stepm,subdirf2(fileresu,"PIJ_"),subdirf2(fileresu,"PIJ_"));
1.126     brouard  7282:    fprintf(fichtm,"\
1.217     brouard  7283:  - Estimated back transition probabilities over %d (stepm) months: <a href=\"%s\">%s</a><br>\n ",
                   7284:           stepm,subdirf2(fileresu,"PIJB_"),subdirf2(fileresu,"PIJB_"));
                   7285:    fprintf(fichtm,"\
1.288     brouard  7286:  - Period (forward) prevalence in each health state: <a href=\"%s\">%s</a> <br>\n",
1.201     brouard  7287:           subdirf2(fileresu,"PL_"),subdirf2(fileresu,"PL_"));
1.126     brouard  7288:    fprintf(fichtm,"\
1.288     brouard  7289:  - Backward prevalence in each health state: <a href=\"%s\">%s</a> <br>\n",
1.217     brouard  7290:           subdirf2(fileresu,"PLB_"),subdirf2(fileresu,"PLB_"));
                   7291:    fprintf(fichtm,"\
1.211     brouard  7292:  - (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  7293:    <a href=\"%s\">%s</a> <br>\n",
1.201     brouard  7294:           estepm,subdirf2(fileresu,"E_"),subdirf2(fileresu,"E_"));
1.211     brouard  7295:    if(prevfcast==1){
                   7296:      fprintf(fichtm,"\
                   7297:  - Prevalence projections by age and states:                           \
1.201     brouard  7298:    <a href=\"%s\">%s</a> <br>\n</li>", subdirf2(fileresu,"F_"),subdirf2(fileresu,"F_"));
1.211     brouard  7299:    }
1.126     brouard  7300: 
                   7301: 
1.225     brouard  7302:    m=pow(2,cptcoveff);
1.222     brouard  7303:    if (cptcovn < 1) {m=1;ncodemax[1]=1;}
1.126     brouard  7304: 
1.317     brouard  7305:    fprintf(fichtm," \n<ul><li><b>Graphs (first order)</b></li><p>");
1.264     brouard  7306: 
                   7307:    jj1=0;
                   7308: 
                   7309:    fprintf(fichtm," \n<ul>");
                   7310:    for(nres=1; nres <= nresult; nres++) /* For each resultline */
                   7311:    for(k1=1; k1<=m;k1++){ /* For each combination of covariate */
                   7312:      if(m != 1 && TKresult[nres]!= k1)
                   7313:        continue;
                   7314:      jj1++;
                   7315:      if (cptcovn > 0) {
                   7316:        fprintf(fichtm,"\n<li><a  size=\"1\" color=\"#EC5E5E\" href=\"#rescov");
                   7317:        for (cpt=1; cpt<=cptcoveff;cpt++){ 
                   7318:         fprintf(fichtm,"_V%d=%d_",Tvresult[nres][cpt],(int)Tresult[nres][cpt]);
                   7319:        }
                   7320:        for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
                   7321:         fprintf(fichtm,"_V%d=%f_",Tvqresult[nres][k4],Tqresult[nres][k4]);
                   7322:        }
                   7323:        fprintf(fichtm,"\">");
                   7324:        
                   7325:        /* if(nqfveff+nqtveff 0) */ /* Test to be done */
                   7326:        fprintf(fichtm,"************ Results for covariates");
                   7327:        for (cpt=1; cpt<=cptcoveff;cpt++){ 
                   7328:         fprintf(fichtm," V%d=%d ",Tvresult[nres][cpt],(int)Tresult[nres][cpt]);
                   7329:        }
                   7330:        for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
                   7331:         fprintf(fichtm," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
                   7332:        }
                   7333:        if(invalidvarcomb[k1]){
                   7334:         fprintf(fichtm," Warning Combination (%d) ignored because no cases ",k1); 
                   7335:         continue;
                   7336:        }
                   7337:        fprintf(fichtm,"</a></li>");
                   7338:      } /* cptcovn >0 */
                   7339:    }
1.317     brouard  7340:    fprintf(fichtm," \n</ul>");
1.264     brouard  7341: 
1.222     brouard  7342:    jj1=0;
1.237     brouard  7343: 
                   7344:    for(nres=1; nres <= nresult; nres++) /* For each resultline */
1.241     brouard  7345:    for(k1=1; k1<=m;k1++){ /* For each combination of covariate */
1.253     brouard  7346:      if(m != 1 && TKresult[nres]!= k1)
1.237     brouard  7347:        continue;
1.220     brouard  7348: 
1.222     brouard  7349:      /* for(i1=1; i1<=ncodemax[k1];i1++){ */
                   7350:      jj1++;
                   7351:      if (cptcovn > 0) {
1.264     brouard  7352:        fprintf(fichtm,"\n<p><a name=\"rescov");
                   7353:        for (cpt=1; cpt<=cptcoveff;cpt++){ 
                   7354:         fprintf(fichtm,"_V%d=%d_",Tvresult[nres][cpt],(int)Tresult[nres][cpt]);
                   7355:        }
                   7356:        for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
                   7357:         fprintf(fichtm,"_V%d=%f_",Tvqresult[nres][k4],Tqresult[nres][k4]);
                   7358:        }
                   7359:        fprintf(fichtm,"\"</a>");
                   7360:  
1.222     brouard  7361:        fprintf(fichtm,"<hr  size=\"2\" color=\"#EC5E5E\">************ Results for covariates");
1.225     brouard  7362:        for (cpt=1; cpt<=cptcoveff;cpt++){ 
1.237     brouard  7363:         fprintf(fichtm," V%d=%d ",Tvresult[nres][cpt],(int)Tresult[nres][cpt]);
                   7364:         printf(" V%d=%d ",Tvresult[nres][cpt],Tresult[nres][cpt]);fflush(stdout);
                   7365:         /* fprintf(fichtm," V%d=%d ",Tvaraff[cpt],nbcode[Tvaraff[cpt]][codtabm(jj1,cpt)]); */
                   7366:         /* printf(" V%d=%d ",Tvaraff[cpt],nbcode[Tvaraff[cpt]][codtabm(jj1,cpt)]);fflush(stdout); */
1.222     brouard  7367:        }
1.237     brouard  7368:        for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
                   7369:        fprintf(fichtm," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
                   7370:        printf(" V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);fflush(stdout);
                   7371:       }
                   7372:        
1.230     brouard  7373:        /* if(nqfveff+nqtveff 0) */ /* Test to be done */
1.321     brouard  7374:        fprintf(fichtm," (model=%s) ************\n<hr size=\"2\" color=\"#EC5E5E\">",model);
1.222     brouard  7375:        if(invalidvarcomb[k1]){
                   7376:         fprintf(fichtm,"\n<h3>Combination (%d) ignored because no cases </h3>\n",k1); 
                   7377:         printf("\nCombination (%d) ignored because no cases \n",k1); 
                   7378:         continue;
                   7379:        }
                   7380:      }
                   7381:      /* aij, bij */
1.259     brouard  7382:      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  7383: <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  7384:      /* Pij */
1.241     brouard  7385:      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> \
                   7386: <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  7387:      /* Quasi-incidences */
                   7388:      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  7389:  before but expressed in per year i.e. quasi incidences if stepm is small and probabilities too, \
1.211     brouard  7390:  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  7391: 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> \
                   7392: <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  7393:      /* Survival functions (period) in state j */
                   7394:      for(cpt=1; cpt<=nlstate;cpt++){
1.329     brouard  7395:        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>", cpt, cpt, nlstate, subdirf2(optionfilefiname,"LIJ_"),cpt,k1,nres,subdirf2(optionfilefiname,"LIJ_"),cpt,k1,nres);
                   7396:        fprintf(fichtm," (data from text file  <a href=\"%s.txt\">%s.txt</a>)\n<br>",subdirf2(optionfilefiname,"PIJ_"),subdirf2(optionfilefiname,"PIJ_"));
                   7397:        fprintf(fichtm,"<img src=\"%s_%d-%d-%d.svg\">",subdirf2(optionfilefiname,"LIJ_"),cpt,k1,nres);
1.222     brouard  7398:      }
                   7399:      /* State specific survival functions (period) */
                   7400:      for(cpt=1; cpt<=nlstate;cpt++){
1.292     brouard  7401:        fprintf(fichtm,"<br>\n- Survival functions in state %d and in any other live state (total).\
                   7402:  And probability to be observed in various states (up to %d) being in state %d at different ages.      \
1.329     brouard  7403:  <a href=\"%s_%d-%d-%d.svg\">%s_%d-%d-%d.svg</a><br> ", cpt, nlstate, cpt, subdirf2(optionfilefiname,"LIJT_"),cpt,k1,nres,subdirf2(optionfilefiname,"LIJT_"),cpt,k1,nres);
                   7404:        fprintf(fichtm," (data from text file  <a href=\"%s.txt\">%s.txt</a>)\n<br>",subdirf2(optionfilefiname,"PIJ_"),subdirf2(optionfilefiname,"PIJ_"));
                   7405:        fprintf(fichtm,"<img src=\"%s_%d-%d-%d.svg\">",subdirf2(optionfilefiname,"LIJT_"),cpt,k1,nres);
1.222     brouard  7406:      }
1.288     brouard  7407:      /* Period (forward stable) prevalence in each health state */
1.222     brouard  7408:      for(cpt=1; cpt<=nlstate;cpt++){
1.329     brouard  7409:        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>", cpt, nlstate, cpt, subdirf2(optionfilefiname,"P_"),cpt,k1,nres,subdirf2(optionfilefiname,"P_"),cpt,k1,nres);
                   7410:        fprintf(fichtm," (data from text file  <a href=\"%s.txt\">%s.txt</a>)\n<br>",subdirf2(optionfilefiname,"P_"),subdirf2(optionfilefiname,"P_"));
                   7411:       fprintf(fichtm,"<img src=\"%s_%d-%d-%d.svg\">" ,subdirf2(optionfilefiname,"P_"),cpt,k1,nres);
1.222     brouard  7412:      }
1.296     brouard  7413:      if(prevbcast==1){
1.288     brouard  7414:        /* Backward prevalence in each health state */
1.222     brouard  7415:        for(cpt=1; cpt<=nlstate;cpt++){
1.264     brouard  7416:         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  7417: <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  7418:        }
1.217     brouard  7419:      }
1.222     brouard  7420:      if(prevfcast==1){
1.288     brouard  7421:        /* Projection of prevalence up to period (forward stable) prevalence in each health state */
1.222     brouard  7422:        for(cpt=1; cpt<=nlstate;cpt++){
1.314     brouard  7423:         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);
                   7424:         fprintf(fichtm," (data from text file  <a href=\"%s.txt\">%s.txt</a>)\n<br>",subdirf2(optionfilefiname,"F_"),subdirf2(optionfilefiname,"F_"));
                   7425:         fprintf(fichtm,"<img src=\"%s_%d-%d-%d.svg\">",
                   7426:                 subdirf2(optionfilefiname,"PROJ_"),cpt,k1,nres);
1.222     brouard  7427:        }
                   7428:      }
1.296     brouard  7429:      if(prevbcast==1){
1.268     brouard  7430:       /* Back projection of prevalence up to stable (mixed) back-prevalence in each health state */
                   7431:        for(cpt=1; cpt<=nlstate;cpt++){
1.273     brouard  7432:         fprintf(fichtm,"<br>\n- Back projection of cross-sectional prevalence (estimated with cases observed from %.1f to %.1f and mobil_average=%d), \
                   7433:  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 \
                   7434:  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  7435: 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);
                   7436:         fprintf(fichtm," (data from text file  <a href=\"%s.txt\">%s.txt</a>)\n<br>",subdirf2(optionfilefiname,"FB_"),subdirf2(optionfilefiname,"FB_"));
                   7437:         fprintf(fichtm," <img src=\"%s_%d-%d-%d.svg\">", subdirf2(optionfilefiname,"PROJB_"),cpt,k1,nres);
1.268     brouard  7438:        }
                   7439:      }
1.220     brouard  7440:         
1.222     brouard  7441:      for(cpt=1; cpt<=nlstate;cpt++) {
1.314     brouard  7442:        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);
                   7443:        fprintf(fichtm," (data from text file  <a href=\"%s.txt\"> %s.txt</a>)\n<br>",subdirf2(optionfilefiname,"E_"),subdirf2(optionfilefiname,"E_"));
                   7444:        fprintf(fichtm,"<img src=\"%s_%d-%d-%d.svg\">", subdirf2(optionfilefiname,"EXP_"),cpt,k1,nres );
1.222     brouard  7445:      }
                   7446:      /* } /\* end i1 *\/ */
                   7447:    }/* End k1 */
                   7448:    fprintf(fichtm,"</ul>");
1.126     brouard  7449: 
1.222     brouard  7450:    fprintf(fichtm,"\
1.126     brouard  7451: \n<br><li><h4> <a name='secondorder'>Result files (second order: variances)</a></h4>\n\
1.193     brouard  7452:  - Parameter file with estimated parameters and covariance matrix: <a href=\"%s\">%s</a> <br> \
1.203     brouard  7453:  - 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  7454: But because parameters are usually highly correlated (a higher incidence of disability \
                   7455: and a higher incidence of recovery can give very close observed transition) it might \
                   7456: be very useful to look not only at linear confidence intervals estimated from the \
                   7457: variances but at the covariance matrix. And instead of looking at the estimated coefficients \
                   7458: (parameters) of the logistic regression, it might be more meaningful to visualize the \
                   7459: covariance matrix of the one-step probabilities. \
                   7460: See page 'Matrix of variance-covariance of one-step probabilities' below. \n", rfileres,rfileres);
1.126     brouard  7461: 
1.222     brouard  7462:    fprintf(fichtm," - Standard deviation of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
                   7463:           subdirf2(fileresu,"PROB_"),subdirf2(fileresu,"PROB_"));
                   7464:    fprintf(fichtm,"\
1.126     brouard  7465:  - Variance-covariance of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
1.222     brouard  7466:           subdirf2(fileresu,"PROBCOV_"),subdirf2(fileresu,"PROBCOV_"));
1.126     brouard  7467: 
1.222     brouard  7468:    fprintf(fichtm,"\
1.126     brouard  7469:  - Correlation matrix of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
1.222     brouard  7470:           subdirf2(fileresu,"PROBCOR_"),subdirf2(fileresu,"PROBCOR_"));
                   7471:    fprintf(fichtm,"\
1.126     brouard  7472:  - 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): \
                   7473:    <a href=\"%s\">%s</a> <br>\n</li>",
1.201     brouard  7474:           estepm,subdirf2(fileresu,"CVE_"),subdirf2(fileresu,"CVE_"));
1.222     brouard  7475:    fprintf(fichtm,"\
1.126     brouard  7476:  - (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): \
                   7477:    <a href=\"%s\">%s</a> <br>\n</li>",
1.201     brouard  7478:           estepm,subdirf2(fileresu,"STDE_"),subdirf2(fileresu,"STDE_"));
1.222     brouard  7479:    fprintf(fichtm,"\
1.288     brouard  7480:  - 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  7481:           estepm, subdirf2(fileresu,"V_"),subdirf2(fileresu,"V_"));
                   7482:    fprintf(fichtm,"\
1.128     brouard  7483:  - 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  7484:           estepm, subdirf2(fileresu,"T_"),subdirf2(fileresu,"T_"));
                   7485:    fprintf(fichtm,"\
1.288     brouard  7486:  - Standard deviation of forward (period) prevalences: <a href=\"%s\">%s</a> <br>\n",\
1.222     brouard  7487:           subdirf2(fileresu,"VPL_"),subdirf2(fileresu,"VPL_"));
1.126     brouard  7488: 
                   7489: /*  if(popforecast==1) fprintf(fichtm,"\n */
                   7490: /*  - Prevalences forecasting: <a href=\"f%s\">f%s</a> <br>\n */
                   7491: /*  - Population forecasting (if popforecast=1): <a href=\"pop%s\">pop%s</a> <br>\n */
                   7492: /*     <br>",fileres,fileres,fileres,fileres); */
                   7493: /*  else  */
                   7494: /*    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  7495:    fflush(fichtm);
1.126     brouard  7496: 
1.225     brouard  7497:    m=pow(2,cptcoveff);
1.222     brouard  7498:    if (cptcovn < 1) {m=1;ncodemax[1]=1;}
1.126     brouard  7499: 
1.317     brouard  7500:    fprintf(fichtm," <ul><li><b>Graphs (second order)</b></li><p>");
                   7501: 
                   7502:   jj1=0;
                   7503: 
                   7504:    fprintf(fichtm," \n<ul>");
                   7505:    for(nres=1; nres <= nresult; nres++) /* For each resultline */
                   7506:    for(k1=1; k1<=m;k1++){ /* For each combination of covariate */
                   7507:      if(m != 1 && TKresult[nres]!= k1)
                   7508:        continue;
                   7509:      jj1++;
                   7510:      if (cptcovn > 0) {
                   7511:        fprintf(fichtm,"\n<li><a  size=\"1\" color=\"#EC5E5E\" href=\"#rescovsecond");
                   7512:        for (cpt=1; cpt<=cptcoveff;cpt++){ 
                   7513:         fprintf(fichtm,"_V%d=%d_",Tvresult[nres][cpt],(int)Tresult[nres][cpt]);
                   7514:        }
                   7515:        for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
                   7516:         fprintf(fichtm,"_V%d=%f_",Tvqresult[nres][k4],Tqresult[nres][k4]);
                   7517:        }
                   7518:        fprintf(fichtm,"\">");
                   7519:        
                   7520:        /* if(nqfveff+nqtveff 0) */ /* Test to be done */
                   7521:        fprintf(fichtm,"************ Results for covariates");
                   7522:        for (cpt=1; cpt<=cptcoveff;cpt++){ 
                   7523:         fprintf(fichtm," V%d=%d ",Tvresult[nres][cpt],(int)Tresult[nres][cpt]);
                   7524:        }
                   7525:        for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
                   7526:         fprintf(fichtm," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
                   7527:        }
                   7528:        if(invalidvarcomb[k1]){
                   7529:         fprintf(fichtm," Warning Combination (%d) ignored because no cases ",k1); 
                   7530:         continue;
                   7531:        }
                   7532:        fprintf(fichtm,"</a></li>");
                   7533:      } /* cptcovn >0 */
                   7534:    }
                   7535:    fprintf(fichtm," \n</ul>");
                   7536: 
1.222     brouard  7537:    jj1=0;
1.237     brouard  7538: 
1.241     brouard  7539:    for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.222     brouard  7540:    for(k1=1; k1<=m;k1++){
1.253     brouard  7541:      if(m != 1 && TKresult[nres]!= k1)
1.237     brouard  7542:        continue;
1.222     brouard  7543:      /* for(i1=1; i1<=ncodemax[k1];i1++){ */
                   7544:      jj1++;
1.126     brouard  7545:      if (cptcovn > 0) {
1.317     brouard  7546:        fprintf(fichtm,"\n<p><a name=\"rescovsecond");
                   7547:        for (cpt=1; cpt<=cptcoveff;cpt++){ 
                   7548:         fprintf(fichtm,"_V%d=%d_",Tvresult[nres][cpt],(int)Tresult[nres][cpt]);
                   7549:        }
                   7550:        for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
                   7551:         fprintf(fichtm,"_V%d=%f_",Tvqresult[nres][k4],Tqresult[nres][k4]);
                   7552:        }
                   7553:        fprintf(fichtm,"\"</a>");
                   7554:        
1.126     brouard  7555:        fprintf(fichtm,"<hr  size=\"2\" color=\"#EC5E5E\">************ Results for covariates");
1.317     brouard  7556:        for (cpt=1; cpt<=cptcoveff;cpt++){  /**< cptcoveff number of variables */
1.237     brouard  7557:         fprintf(fichtm," V%d=%d ",Tvresult[nres][cpt],Tresult[nres][cpt]);
1.317     brouard  7558:         printf(" V%d=%d ",Tvresult[nres][cpt],Tresult[nres][cpt]);fflush(stdout);
1.237     brouard  7559:         /* fprintf(fichtm," V%d=%d ",Tvaraff[cpt],nbcode[Tvaraff[cpt]][codtabm(jj1,cpt)]); */
1.317     brouard  7560:        }
1.237     brouard  7561:        for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
                   7562:        fprintf(fichtm," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
                   7563:       }
                   7564: 
1.321     brouard  7565:        fprintf(fichtm," (model=%s) ************\n<hr size=\"2\" color=\"#EC5E5E\">",model);
1.220     brouard  7566: 
1.222     brouard  7567:        if(invalidvarcomb[k1]){
                   7568:         fprintf(fichtm,"\n<h4>Combination (%d) ignored because no cases </h4>\n",k1); 
                   7569:         continue;
                   7570:        }
1.126     brouard  7571:      }
                   7572:      for(cpt=1; cpt<=nlstate;cpt++) {
1.258     brouard  7573:        fprintf(fichtm,"\n<br>- Observed (cross-sectional with mov_average=%d) and period (incidence based) \
1.314     brouard  7574: 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);
                   7575:        fprintf(fichtm," (data from text file  <a href=\"%s\">%s</a>)\n <br>",subdirf2(fileresu,"VPL_"),subdirf2(fileresu,"VPL_"));
                   7576:        fprintf(fichtm,"<img src=\"%s_%d-%d-%d.svg\">",subdirf2(optionfilefiname,"V_"), cpt,k1,nres);
1.126     brouard  7577:      }
                   7578:      fprintf(fichtm,"\n<br>- Total life expectancy by age and \
1.314     brouard  7579: health expectancies in each live states (1 to %d). If popbased=1 the smooth (due to the model) \
1.128     brouard  7580: true period expectancies (those weighted with period prevalences are also\
                   7581:  drawn in addition to the population based expectancies computed using\
1.314     brouard  7582:  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);
                   7583:      fprintf(fichtm," (data from text file <a href=\"%s.txt\">%s.txt</a>) \n<br>",subdirf2(optionfilefiname,"T_"),subdirf2(optionfilefiname,"T_"));
                   7584:      fprintf(fichtm,"<img src=\"%s_%d-%d.svg\">",subdirf2(optionfilefiname,"E_"),k1,nres);
1.222     brouard  7585:      /* } /\* end i1 *\/ */
                   7586:    }/* End k1 */
1.241     brouard  7587:   }/* End nres */
1.222     brouard  7588:    fprintf(fichtm,"</ul>");
                   7589:    fflush(fichtm);
1.126     brouard  7590: }
                   7591: 
                   7592: /******************* Gnuplot file **************/
1.296     brouard  7593: 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  7594: 
                   7595:   char dirfileres[132],optfileres[132];
1.264     brouard  7596:   char gplotcondition[132], gplotlabel[132];
1.237     brouard  7597:   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  7598:   int lv=0, vlv=0, kl=0;
1.130     brouard  7599:   int ng=0;
1.201     brouard  7600:   int vpopbased;
1.223     brouard  7601:   int ioffset; /* variable offset for columns */
1.270     brouard  7602:   int iyearc=1; /* variable column for year of projection  */
                   7603:   int iagec=1; /* variable column for age of projection  */
1.235     brouard  7604:   int nres=0; /* Index of resultline */
1.266     brouard  7605:   int istart=1; /* For starting graphs in projections */
1.219     brouard  7606: 
1.126     brouard  7607: /*   if((ficgp=fopen(optionfilegnuplot,"a"))==NULL) { */
                   7608: /*     printf("Problem with file %s",optionfilegnuplot); */
                   7609: /*     fprintf(ficlog,"Problem with file %s",optionfilegnuplot); */
                   7610: /*   } */
                   7611: 
                   7612:   /*#ifdef windows */
                   7613:   fprintf(ficgp,"cd \"%s\" \n",pathc);
1.223     brouard  7614:   /*#endif */
1.225     brouard  7615:   m=pow(2,cptcoveff);
1.126     brouard  7616: 
1.274     brouard  7617:   /* diagram of the model */
                   7618:   fprintf(ficgp,"\n#Diagram of the model \n");
                   7619:   fprintf(ficgp,"\ndelta=0.03;delta2=0.07;unset arrow;\n");
                   7620:   fprintf(ficgp,"yoff=(%d > 2? 0:1);\n",nlstate);
                   7621:   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);
                   7622: 
                   7623:   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);
                   7624:   fprintf(ficgp,"\n#show arrow\nunset label\n");
                   7625:   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);
                   7626:   fprintf(ficgp,"\nset label %d+1 sprintf(\"State %%d\",%d+1) center at 0.,0.  font \"helvetica, 16\" tc rgbcolor \"red\"\n",nlstate,nlstate);
                   7627:   fprintf(ficgp,"\n#show label\nunset border;unset xtics; unset ytics;\n");
                   7628:   fprintf(ficgp,"\n\nset ter svg size 640, 480;set out \"%s_.svg\" \n",subdirf2(optionfilefiname,"D_"));
                   7629:   fprintf(ficgp,"unset log y; plot [-1.2:1.2][yoff-1.2:1.2] 1/0 not; set out;reset;\n");
                   7630: 
1.202     brouard  7631:   /* Contribution to likelihood */
                   7632:   /* Plot the probability implied in the likelihood */
1.223     brouard  7633:   fprintf(ficgp,"\n# Contributions to the Likelihood, mle >=1. For mle=4 no interpolation, pure matrix products.\n#\n");
                   7634:   fprintf(ficgp,"\n set log y; unset log x;set xlabel \"Age\"; set ylabel \"Likelihood (-2Log(L))\";");
                   7635:   /* fprintf(ficgp,"\nset ter svg size 640, 480"); */ /* Too big for svg */
                   7636:   fprintf(ficgp,"\nset ter pngcairo size 640, 480");
1.204     brouard  7637: /* nice for mle=4 plot by number of matrix products.
1.202     brouard  7638:    replot  "rrtest1/toto.txt" u 2:($4 == 1 && $5==2 ? $9 : 1/0):5 t "p12" with point lc 1 */
                   7639: /* replot exp(p1+p2*x)/(1+exp(p1+p2*x)+exp(p3+p4*x)+exp(p5+p6*x)) t "p12(x)"  */
1.223     brouard  7640:   /* fprintf(ficgp,"\nset out \"%s.svg\";",subdirf2(optionfilefiname,"ILK_")); */
                   7641:   fprintf(ficgp,"\nset out \"%s-dest.png\";",subdirf2(optionfilefiname,"ILK_"));
                   7642:   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));
                   7643:   fprintf(ficgp,"\nset out \"%s-ori.png\";",subdirf2(optionfilefiname,"ILK_"));
                   7644:   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));
                   7645:   for (i=1; i<= nlstate ; i ++) {
                   7646:     fprintf(ficgp,"\nset out \"%s-p%dj.png\";set ylabel \"Probability for each individual/wave\";",subdirf2(optionfilefiname,"ILK_"),i);
                   7647:     fprintf(ficgp,"unset log;\n# plot weighted, mean weight should have point size of 0.5\n plot  \"%s\"",subdirf(fileresilk));
                   7648:     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);
                   7649:     for (j=2; j<= nlstate+ndeath ; j ++) {
                   7650:       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);
                   7651:     }
                   7652:     fprintf(ficgp,";\nset out; unset ylabel;\n"); 
                   7653:   }
                   7654:   /* 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 */               
                   7655:   /* fprintf(ficgp,"\nset log y;plot  \"%s\" u 2:(-$11):3 t \"All sample, all transitions\" with dots lc variable",subdirf(fileresilk)); */
                   7656:   /* fprintf(ficgp,"\nreplot  \"%s\" u 2:($3 <= 3 ? -$11 : 1/0):3 t \"First 3 individuals\" with line lc variable", subdirf(fileresilk)); */
                   7657:   fprintf(ficgp,"\nset out;unset log\n");
                   7658:   /* fprintf(ficgp,"\nset out \"%s.svg\"; replot; set out; # bug gnuplot",subdirf2(optionfilefiname,"ILK_")); */
1.202     brouard  7659: 
1.126     brouard  7660:   strcpy(dirfileres,optionfilefiname);
                   7661:   strcpy(optfileres,"vpl");
1.223     brouard  7662:   /* 1eme*/
1.238     brouard  7663:   for (cpt=1; cpt<= nlstate ; cpt ++){ /* For each live state */
                   7664:     for (k1=1; k1<= m ; k1 ++){ /* For each valid combination of covariate */
1.236     brouard  7665:       for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.238     brouard  7666:        /* plot [100000000000000000000:-100000000000000000000] "mysbiaspar/vplrmysbiaspar.txt to check */
1.253     brouard  7667:        if(m != 1 && TKresult[nres]!= k1)
1.238     brouard  7668:          continue;
                   7669:        /* We are interested in selected combination by the resultline */
1.246     brouard  7670:        /* printf("\n# 1st: Period (stable) prevalence with CI: 'VPL_' files and live state =%d ", cpt); */
1.288     brouard  7671:        fprintf(ficgp,"\n# 1st: Forward (stable period) prevalence with CI: 'VPL_' files  and live state =%d ", cpt);
1.264     brouard  7672:        strcpy(gplotlabel,"(");
1.238     brouard  7673:        for (k=1; k<=cptcoveff; k++){    /* For each covariate k get corresponding value lv for combination k1 */
                   7674:          lv= decodtabm(k1,k,cptcoveff); /* Should be the value of the covariate corresponding to k1 combination */
                   7675:          /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   7676:          /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   7677:          /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
                   7678:          vlv= nbcode[Tvaraff[k]][lv]; /* vlv is the value of the covariate lv, 0 or 1 */
                   7679:          /* For each combination of covariate k1 (V1=1, V3=0), we printed the current covariate k and its value vlv */
1.246     brouard  7680:          /* printf(" V%d=%d ",Tvaraff[k],vlv); */
1.238     brouard  7681:          fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv);
1.264     brouard  7682:          sprintf(gplotlabel+strlen(gplotlabel)," V%d=%d ",Tvaraff[k],vlv);
1.238     brouard  7683:        }
                   7684:        for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
1.246     brouard  7685:          /* printf(" V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]); */
1.238     brouard  7686:          fprintf(ficgp," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
1.264     brouard  7687:          sprintf(gplotlabel+strlen(gplotlabel)," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
                   7688:        }
                   7689:        strcpy(gplotlabel+strlen(gplotlabel),")");
1.246     brouard  7690:        /* printf("\n#\n"); */
1.238     brouard  7691:        fprintf(ficgp,"\n#\n");
                   7692:        if(invalidvarcomb[k1]){
1.260     brouard  7693:           /*k1=k1-1;*/ /* To be checked */
1.238     brouard  7694:          fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   7695:          continue;
                   7696:        }
1.235     brouard  7697:       
1.241     brouard  7698:        fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" \n",subdirf2(optionfilefiname,"V_"),cpt,k1,nres);
                   7699:        fprintf(ficgp,"\n#set out \"V_%s_%d-%d-%d.svg\" \n",optionfilefiname,cpt,k1,nres);
1.276     brouard  7700:        /* 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  7701:        fprintf(ficgp,"set title \"Alive state %d %s model=%s\" font \"Helvetica,12\"\n",cpt,gplotlabel,model);
1.260     brouard  7702:        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);
                   7703:        /* 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); */
                   7704:       /* k1-1 error should be nres-1*/
1.238     brouard  7705:        for (i=1; i<= nlstate ; i ++) {
                   7706:          if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
                   7707:          else        fprintf(ficgp," %%*lf (%%*lf)");
                   7708:        }
1.288     brouard  7709:        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  7710:        for (i=1; i<= nlstate ; i ++) {
                   7711:          if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
                   7712:          else fprintf(ficgp," %%*lf (%%*lf)");
                   7713:        } 
1.260     brouard  7714:        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  7715:        for (i=1; i<= nlstate ; i ++) {
                   7716:          if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
                   7717:          else fprintf(ficgp," %%*lf (%%*lf)");
                   7718:        }  
1.265     brouard  7719:        /* 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)); */
                   7720:        
                   7721:        fprintf(ficgp,"\" t\"\" w l lt 1,\"%s\" u 1:((",subdirf2(fileresu,"P_"));
                   7722:         if(cptcoveff ==0){
1.271     brouard  7723:          fprintf(ficgp,"$%d)) t 'Observed prevalence in state %d' with line lt 3",      2+3*(cpt-1),  cpt );
1.265     brouard  7724:        }else{
                   7725:          kl=0;
                   7726:          for (k=1; k<=cptcoveff; k++){    /* For each combination of covariate  */
                   7727:            lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate value corresponding to k1 combination and kth covariate */
                   7728:            /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   7729:            /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   7730:            /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
                   7731:            vlv= nbcode[Tvaraff[k]][lv];
                   7732:            kl++;
                   7733:            /* 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 *\/ */
                   7734:            /*6+(cpt-1)*(nlstate+1)+1+(i-1)+(nlstate+1)*nlstate; 6+(1-1)*(2+1)+1+(1-1) +(2+1)*2=13 */ 
                   7735:            /*6+1+(i-1)+(nlstate+1)*nlstate; 6+1+(1-1) +(2+1)*2=13 */ 
                   7736:            /* ''  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*/
                   7737:            if(k==cptcoveff){
                   7738:              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], \
                   7739:                      2+cptcoveff*2+3*(cpt-1),  cpt );  /* 4 or 6 ?*/
                   7740:            }else{
                   7741:              fprintf(ficgp,"$%d==%d && $%d==%d && ",kl+1, Tvaraff[k],kl+1+1,nbcode[Tvaraff[k]][lv]);
                   7742:              kl++;
                   7743:            }
                   7744:          } /* end covariate */
                   7745:        } /* end if no covariate */
                   7746: 
1.296     brouard  7747:        if(prevbcast==1){ /* We need to get the corresponding values of the covariates involved in this combination k1 */
1.238     brouard  7748:          /* 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  7749:          fprintf(ficgp,",\"%s\" u 1:((",subdirf2(fileresu,"PLB_")); /* Age is in 1, nres in 2 to be fixed */
1.238     brouard  7750:          if(cptcoveff ==0){
1.245     brouard  7751:            fprintf(ficgp,"$%d)) t 'Backward prevalence in state %d' with line lt 3",    2+(cpt-1),  cpt );
1.238     brouard  7752:          }else{
                   7753:            kl=0;
                   7754:            for (k=1; k<=cptcoveff; k++){    /* For each combination of covariate  */
                   7755:              lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate value corresponding to k1 combination and kth covariate */
                   7756:              /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   7757:              /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   7758:              /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
                   7759:              vlv= nbcode[Tvaraff[k]][lv];
1.223     brouard  7760:              kl++;
1.238     brouard  7761:              /* 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 *\/ */
                   7762:              /*6+(cpt-1)*(nlstate+1)+1+(i-1)+(nlstate+1)*nlstate; 6+(1-1)*(2+1)+1+(1-1) +(2+1)*2=13 */ 
                   7763:              /*6+1+(i-1)+(nlstate+1)*nlstate; 6+1+(1-1) +(2+1)*2=13 */ 
                   7764:              /* ''  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*/
                   7765:              if(k==cptcoveff){
1.245     brouard  7766:                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  7767:                        2+cptcoveff*2+(cpt-1),  cpt );  /* 4 or 6 ?*/
1.238     brouard  7768:              }else{
                   7769:                fprintf(ficgp,"$%d==%d && $%d==%d && ",kl+1, Tvaraff[k],kl+1+1,nbcode[Tvaraff[k]][lv]);
                   7770:                kl++;
                   7771:              }
                   7772:            } /* end covariate */
                   7773:          } /* end if no covariate */
1.296     brouard  7774:          if(prevbcast == 1){
1.268     brouard  7775:            fprintf(ficgp,", \"%s\" every :::%d::%d u 1:($2==%d ? $3:1/0) \"%%lf %%lf",subdirf2(fileresu,"VBL_"),nres-1,nres-1,nres);
                   7776:            /* k1-1 error should be nres-1*/
                   7777:            for (i=1; i<= nlstate ; i ++) {
                   7778:              if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
                   7779:              else        fprintf(ficgp," %%*lf (%%*lf)");
                   7780:            }
1.271     brouard  7781:            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  7782:            for (i=1; i<= nlstate ; i ++) {
                   7783:              if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
                   7784:              else fprintf(ficgp," %%*lf (%%*lf)");
                   7785:            } 
1.276     brouard  7786:            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  7787:            for (i=1; i<= nlstate ; i ++) {
                   7788:              if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
                   7789:              else fprintf(ficgp," %%*lf (%%*lf)");
                   7790:            } 
1.274     brouard  7791:            fprintf(ficgp,"\" t\"\" w l lt 4");
1.268     brouard  7792:          } /* end if backprojcast */
1.296     brouard  7793:        } /* end if prevbcast */
1.276     brouard  7794:        /* fprintf(ficgp,"\nset out ;unset label;\n"); */
                   7795:        fprintf(ficgp,"\nset out ;unset title;\n");
1.238     brouard  7796:       } /* nres */
1.201     brouard  7797:     } /* k1 */
                   7798:   } /* cpt */
1.235     brouard  7799: 
                   7800:   
1.126     brouard  7801:   /*2 eme*/
1.238     brouard  7802:   for (k1=1; k1<= m ; k1 ++){  
                   7803:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.253     brouard  7804:       if(m != 1 && TKresult[nres]!= k1)
1.238     brouard  7805:        continue;
                   7806:       fprintf(ficgp,"\n# 2nd: Total life expectancy with CI: 't' files ");
1.264     brouard  7807:       strcpy(gplotlabel,"(");
1.238     brouard  7808:       for (k=1; k<=cptcoveff; k++){    /* For each covariate and each value */
1.225     brouard  7809:        lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate number corresponding to k1 combination */
1.223     brouard  7810:        /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   7811:        /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   7812:        /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
                   7813:        vlv= nbcode[Tvaraff[k]][lv];
                   7814:        fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv);
1.264     brouard  7815:        sprintf(gplotlabel+strlen(gplotlabel)," V%d=%d ",Tvaraff[k],vlv);
1.211     brouard  7816:       }
1.237     brouard  7817:       /* for(k=1; k <= ncovds; k++){ */
1.236     brouard  7818:       for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
1.238     brouard  7819:        printf(" V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
1.236     brouard  7820:        fprintf(ficgp," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
1.264     brouard  7821:        sprintf(gplotlabel+strlen(gplotlabel)," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
1.238     brouard  7822:       }
1.264     brouard  7823:       strcpy(gplotlabel+strlen(gplotlabel),")");
1.211     brouard  7824:       fprintf(ficgp,"\n#\n");
1.223     brouard  7825:       if(invalidvarcomb[k1]){
                   7826:        fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   7827:        continue;
                   7828:       }
1.219     brouard  7829:                        
1.241     brouard  7830:       fprintf(ficgp,"\nset out \"%s_%d-%d.svg\" \n",subdirf2(optionfilefiname,"E_"),k1,nres);
1.238     brouard  7831:       for(vpopbased=0; vpopbased <= popbased; vpopbased++){ /* Done for vpopbased=0 and vpopbased=1 if popbased==1*/
1.264     brouard  7832:        fprintf(ficgp,"\nset label \"popbased %d %s\" at graph 0.98,0.5 center rotate font \"Helvetica,12\"\n",vpopbased,gplotlabel);
                   7833:        if(vpopbased==0){
1.238     brouard  7834:          fprintf(ficgp,"set ylabel \"Years\" \nset ter svg size 640, 480\nplot [%.f:%.f] ",ageminpar,fage);
1.264     brouard  7835:        }else
1.238     brouard  7836:          fprintf(ficgp,"\nreplot ");
                   7837:        for (i=1; i<= nlstate+1 ; i ++) {
                   7838:          k=2*i;
1.261     brouard  7839:          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  7840:          for (j=1; j<= nlstate+1 ; j ++) {
                   7841:            if (j==i) fprintf(ficgp," %%lf (%%lf)");
                   7842:            else fprintf(ficgp," %%*lf (%%*lf)");
                   7843:          }   
                   7844:          if (i== 1) fprintf(ficgp,"\" t\"TLE\" w l lt %d, \\\n",i);
                   7845:          else fprintf(ficgp,"\" t\"LE in state (%d)\" w l lt %d, \\\n",i-1,i+1);
1.261     brouard  7846:          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  7847:          for (j=1; j<= nlstate+1 ; j ++) {
                   7848:            if (j==i) fprintf(ficgp," %%lf (%%lf)");
                   7849:            else fprintf(ficgp," %%*lf (%%*lf)");
                   7850:          }   
                   7851:          fprintf(ficgp,"\" t\"\" w l lt 0,");
1.261     brouard  7852:          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  7853:          for (j=1; j<= nlstate+1 ; j ++) {
                   7854:            if (j==i) fprintf(ficgp," %%lf (%%lf)");
                   7855:            else fprintf(ficgp," %%*lf (%%*lf)");
                   7856:          }   
                   7857:          if (i== (nlstate+1)) fprintf(ficgp,"\" t\"\" w l lt 0");
                   7858:          else fprintf(ficgp,"\" t\"\" w l lt 0,\\\n");
                   7859:        } /* state */
                   7860:       } /* vpopbased */
1.264     brouard  7861:       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  7862:     } /* end nres */
                   7863:   } /* k1 end 2 eme*/
                   7864:        
                   7865:        
                   7866:   /*3eme*/
                   7867:   for (k1=1; k1<= m ; k1 ++){
                   7868:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.253     brouard  7869:       if(m != 1 && TKresult[nres]!= k1)
1.238     brouard  7870:        continue;
                   7871: 
                   7872:       for (cpt=1; cpt<= nlstate ; cpt ++) {
1.261     brouard  7873:        fprintf(ficgp,"\n\n# 3d: Life expectancy with EXP_ files:  combination=%d state=%d",k1, cpt);
1.264     brouard  7874:        strcpy(gplotlabel,"(");
1.238     brouard  7875:        for (k=1; k<=cptcoveff; k++){    /* For each covariate and each value */
                   7876:          lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate number corresponding to k1 combination */
                   7877:          /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   7878:          /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   7879:          /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
                   7880:          vlv= nbcode[Tvaraff[k]][lv];
                   7881:          fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv);
1.264     brouard  7882:          sprintf(gplotlabel+strlen(gplotlabel)," V%d=%d ",Tvaraff[k],vlv);
1.238     brouard  7883:        }
                   7884:        for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
                   7885:          fprintf(ficgp," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
1.264     brouard  7886:          sprintf(gplotlabel+strlen(gplotlabel)," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
1.238     brouard  7887:        }       
1.264     brouard  7888:        strcpy(gplotlabel+strlen(gplotlabel),")");
1.238     brouard  7889:        fprintf(ficgp,"\n#\n");
                   7890:        if(invalidvarcomb[k1]){
                   7891:          fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   7892:          continue;
                   7893:        }
                   7894:                        
                   7895:        /*       k=2+nlstate*(2*cpt-2); */
                   7896:        k=2+(nlstate+1)*(cpt-1);
1.241     brouard  7897:        fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" \n",subdirf2(optionfilefiname,"EXP_"),cpt,k1,nres);
1.264     brouard  7898:        fprintf(ficgp,"set label \"%s\" at graph 0.98,0.5 center rotate font \"Helvetica,12\"\n",gplotlabel);
1.238     brouard  7899:        fprintf(ficgp,"set ter svg size 640, 480\n\
1.261     brouard  7900: 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  7901:        /*fprintf(ficgp,",\"e%s\" every :::%d::%d u 1:($%d-2*$%d) \"\%%lf ",fileres,k1-1,k1-1,k,k+1);
                   7902:          for (i=1; i<= nlstate*2 ; i ++) fprintf(ficgp,"\%%lf (\%%lf) ");
                   7903:          fprintf(ficgp,"\" t \"e%d1\" w l",cpt);
                   7904:          fprintf(ficgp,",\"e%s\" every :::%d::%d u 1:($%d+2*$%d) \"\%%lf ",fileres,k1-1,k1-1,k,k+1);
                   7905:          for (i=1; i<= nlstate*2 ; i ++) fprintf(ficgp,"\%%lf (\%%lf) ");
                   7906:          fprintf(ficgp,"\" t \"e%d1\" w l",cpt);
1.219     brouard  7907:                                
1.238     brouard  7908:        */
                   7909:        for (i=1; i< nlstate ; i ++) {
1.261     brouard  7910:          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  7911:          /*    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  7912:                                
1.238     brouard  7913:        } 
1.261     brouard  7914:        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  7915:       }
1.264     brouard  7916:       fprintf(ficgp,"\nunset label;\n");
1.238     brouard  7917:     } /* end nres */
                   7918:   } /* end kl 3eme */
1.126     brouard  7919:   
1.223     brouard  7920:   /* 4eme */
1.201     brouard  7921:   /* Survival functions (period) from state i in state j by initial state i */
1.238     brouard  7922:   for (k1=1; k1<=m; k1++){    /* For each covariate and each value */
                   7923:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.253     brouard  7924:       if(m != 1 && TKresult[nres]!= k1)
1.223     brouard  7925:        continue;
1.238     brouard  7926:       for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each life state cpt*/
1.264     brouard  7927:        strcpy(gplotlabel,"(");
1.238     brouard  7928:        fprintf(ficgp,"\n#\n#\n# Survival functions in state j : 'LIJ_' files, cov=%d state=%d",k1, cpt);
                   7929:        for (k=1; k<=cptcoveff; k++){    /* For each covariate and each value */
                   7930:          lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate number corresponding to k1 combination */
                   7931:          /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   7932:          /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   7933:          /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
                   7934:          vlv= nbcode[Tvaraff[k]][lv];
                   7935:          fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv);
1.264     brouard  7936:          sprintf(gplotlabel+strlen(gplotlabel)," V%d=%d ",Tvaraff[k],vlv);
1.238     brouard  7937:        }
                   7938:        for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
                   7939:          fprintf(ficgp," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
1.264     brouard  7940:          sprintf(gplotlabel+strlen(gplotlabel)," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
1.238     brouard  7941:        }       
1.264     brouard  7942:        strcpy(gplotlabel+strlen(gplotlabel),")");
1.238     brouard  7943:        fprintf(ficgp,"\n#\n");
                   7944:        if(invalidvarcomb[k1]){
                   7945:          fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   7946:          continue;
1.223     brouard  7947:        }
1.238     brouard  7948:       
1.241     brouard  7949:        fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" \n",subdirf2(optionfilefiname,"LIJ_"),cpt,k1,nres);
1.264     brouard  7950:        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  7951:        fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Probability to be alive\" \n\
                   7952: set ter svg size 640, 480\nunset log y\nplot [%.f:%.f]  ", ageminpar, agemaxpar);
                   7953:        k=3;
                   7954:        for (i=1; i<= nlstate ; i ++){
                   7955:          if(i==1){
                   7956:            fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"PIJ_"));
                   7957:          }else{
                   7958:            fprintf(ficgp,", '' ");
                   7959:          }
                   7960:          l=(nlstate+ndeath)*(i-1)+1;
                   7961:          fprintf(ficgp," u ($1==%d ? ($3):1/0):($%d/($%d",k1,k+l+(cpt-1),k+l);
                   7962:          for (j=2; j<= nlstate+ndeath ; j ++)
                   7963:            fprintf(ficgp,"+$%d",k+l+j-1);
                   7964:          fprintf(ficgp,")) t \"l(%d,%d)\" w l",i,cpt);
                   7965:        } /* nlstate */
1.264     brouard  7966:        fprintf(ficgp,"\nset out; unset label;\n");
1.238     brouard  7967:       } /* end cpt state*/ 
                   7968:     } /* end nres */
                   7969:   } /* end covariate k1 */  
                   7970: 
1.220     brouard  7971: /* 5eme */
1.201     brouard  7972:   /* Survival functions (period) from state i in state j by final state j */
1.238     brouard  7973:   for (k1=1; k1<= m ; k1++){ /* For each covariate combination if any */
                   7974:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.253     brouard  7975:       if(m != 1 && TKresult[nres]!= k1)
1.227     brouard  7976:        continue;
1.238     brouard  7977:       for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each inital state  */
1.264     brouard  7978:        strcpy(gplotlabel,"(");
1.238     brouard  7979:        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);
                   7980:        for (k=1; k<=cptcoveff; k++){    /* For each covariate and each value */
                   7981:          lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate number corresponding to k1 combination */
                   7982:          /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   7983:          /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   7984:          /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
                   7985:          vlv= nbcode[Tvaraff[k]][lv];
                   7986:          fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv);
1.264     brouard  7987:          sprintf(gplotlabel+strlen(gplotlabel)," V%d=%d ",Tvaraff[k],vlv);
1.238     brouard  7988:        }
                   7989:        for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
                   7990:          fprintf(ficgp," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
1.264     brouard  7991:          sprintf(gplotlabel+strlen(gplotlabel)," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
1.238     brouard  7992:        }       
1.264     brouard  7993:        strcpy(gplotlabel+strlen(gplotlabel),")");
1.238     brouard  7994:        fprintf(ficgp,"\n#\n");
                   7995:        if(invalidvarcomb[k1]){
                   7996:          fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   7997:          continue;
                   7998:        }
1.227     brouard  7999:       
1.241     brouard  8000:        fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" \n",subdirf2(optionfilefiname,"LIJT_"),cpt,k1,nres);
1.264     brouard  8001:        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  8002:        fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Probability to be alive\" \n\
                   8003: set ter svg size 640, 480\nunset log y\nplot [%.f:%.f]  ", ageminpar, agemaxpar);
                   8004:        k=3;
                   8005:        for (j=1; j<= nlstate ; j ++){ /* Lived in state j */
                   8006:          if(j==1)
                   8007:            fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"PIJ_"));
                   8008:          else
                   8009:            fprintf(ficgp,", '' ");
                   8010:          l=(nlstate+ndeath)*(cpt-1) +j;
                   8011:          fprintf(ficgp," u (($1==%d && (floor($2)%%5 == 0)) ? ($3):1/0):($%d",k1,k+l);
                   8012:          /* for (i=2; i<= nlstate+ndeath ; i ++) */
                   8013:          /*   fprintf(ficgp,"+$%d",k+l+i-1); */
                   8014:          fprintf(ficgp,") t \"l(%d,%d)\" w l",cpt,j);
                   8015:        } /* nlstate */
                   8016:        fprintf(ficgp,", '' ");
                   8017:        fprintf(ficgp," u (($1==%d && (floor($2)%%5 == 0)) ? ($3):1/0):(",k1);
                   8018:        for (j=1; j<= nlstate ; j ++){ /* Lived in state j */
                   8019:          l=(nlstate+ndeath)*(cpt-1) +j;
                   8020:          if(j < nlstate)
                   8021:            fprintf(ficgp,"$%d +",k+l);
                   8022:          else
                   8023:            fprintf(ficgp,"$%d) t\"l(%d,.)\" w l",k+l,cpt);
                   8024:        }
1.264     brouard  8025:        fprintf(ficgp,"\nset out; unset label;\n");
1.238     brouard  8026:       } /* end cpt state*/ 
                   8027:     } /* end covariate */  
                   8028:   } /* end nres */
1.227     brouard  8029:   
1.220     brouard  8030: /* 6eme */
1.202     brouard  8031:   /* CV preval stable (period) for each covariate */
1.237     brouard  8032:   for (k1=1; k1<= m ; k1 ++) /* For each covariate combination if any */
                   8033:   for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.253     brouard  8034:     if(m != 1 && TKresult[nres]!= k1)
1.237     brouard  8035:       continue;
1.255     brouard  8036:     for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each life state of arrival */
1.264     brouard  8037:       strcpy(gplotlabel,"(");      
1.288     brouard  8038:       fprintf(ficgp,"\n#\n#\n#CV preval stable (forward): 'pij' files, covariatecombination#=%d state=%d",k1, cpt);
1.225     brouard  8039:       for (k=1; k<=cptcoveff; k++){    /* For each covariate and each value */
1.227     brouard  8040:        lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate number corresponding to k1 combination */
                   8041:        /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   8042:        /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   8043:        /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
                   8044:        vlv= nbcode[Tvaraff[k]][lv];
                   8045:        fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv);
1.264     brouard  8046:        sprintf(gplotlabel+strlen(gplotlabel)," V%d=%d ",Tvaraff[k],vlv);
1.211     brouard  8047:       }
1.237     brouard  8048:       for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
                   8049:        fprintf(ficgp," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
1.264     brouard  8050:        sprintf(gplotlabel+strlen(gplotlabel)," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
1.237     brouard  8051:       }        
1.264     brouard  8052:       strcpy(gplotlabel+strlen(gplotlabel),")");
1.211     brouard  8053:       fprintf(ficgp,"\n#\n");
1.223     brouard  8054:       if(invalidvarcomb[k1]){
1.227     brouard  8055:        fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   8056:        continue;
1.223     brouard  8057:       }
1.227     brouard  8058:       
1.241     brouard  8059:       fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" \n",subdirf2(optionfilefiname,"P_"),cpt,k1,nres);
1.264     brouard  8060:       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  8061:       fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Probability\" \n\
1.238     brouard  8062: set ter svg size 640, 480\nunset log y\nplot [%.f:%.f]  ", ageminpar, agemaxpar);
1.211     brouard  8063:       k=3; /* Offset */
1.255     brouard  8064:       for (i=1; i<= nlstate ; i ++){ /* State of origin */
1.227     brouard  8065:        if(i==1)
                   8066:          fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"PIJ_"));
                   8067:        else
                   8068:          fprintf(ficgp,", '' ");
1.255     brouard  8069:        l=(nlstate+ndeath)*(i-1)+1; /* 1, 1+ nlstate+ndeath, 1+2*(nlstate+ndeath) */
1.227     brouard  8070:        fprintf(ficgp," u ($1==%d ? ($3):1/0):($%d/($%d",k1,k+l+(cpt-1),k+l);
                   8071:        for (j=2; j<= nlstate ; j ++)
                   8072:          fprintf(ficgp,"+$%d",k+l+j-1);
                   8073:        fprintf(ficgp,")) t \"prev(%d,%d)\" w l",i,cpt);
1.153     brouard  8074:       } /* nlstate */
1.264     brouard  8075:       fprintf(ficgp,"\nset out; unset label;\n");
1.153     brouard  8076:     } /* end cpt state*/ 
                   8077:   } /* end covariate */  
1.227     brouard  8078:   
                   8079:   
1.220     brouard  8080: /* 7eme */
1.296     brouard  8081:   if(prevbcast == 1){
1.288     brouard  8082:     /* CV backward prevalence  for each covariate */
1.237     brouard  8083:     for (k1=1; k1<= m ; k1 ++) /* For each covariate combination if any */
                   8084:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.253     brouard  8085:       if(m != 1 && TKresult[nres]!= k1)
1.237     brouard  8086:        continue;
1.268     brouard  8087:       for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each life origin state */
1.264     brouard  8088:        strcpy(gplotlabel,"(");      
1.288     brouard  8089:        fprintf(ficgp,"\n#\n#\n#CV Backward stable prevalence: 'pijb' files, covariatecombination#=%d state=%d",k1, cpt);
1.227     brouard  8090:        for (k=1; k<=cptcoveff; k++){    /* For each covariate and each value */
                   8091:          lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate number corresponding to k1 combination */
                   8092:          /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   8093:          /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
1.223     brouard  8094:          /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
1.227     brouard  8095:          vlv= nbcode[Tvaraff[k]][lv];
                   8096:          fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv);
1.264     brouard  8097:          sprintf(gplotlabel+strlen(gplotlabel)," V%d=%d ",Tvaraff[k],vlv);
1.227     brouard  8098:        }
1.237     brouard  8099:        for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
                   8100:          fprintf(ficgp," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
1.264     brouard  8101:          sprintf(gplotlabel+strlen(gplotlabel)," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
1.237     brouard  8102:        }       
1.264     brouard  8103:        strcpy(gplotlabel+strlen(gplotlabel),")");
1.227     brouard  8104:        fprintf(ficgp,"\n#\n");
                   8105:        if(invalidvarcomb[k1]){
                   8106:          fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   8107:          continue;
                   8108:        }
                   8109:        
1.241     brouard  8110:        fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" \n",subdirf2(optionfilefiname,"PB_"),cpt,k1,nres);
1.268     brouard  8111:        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  8112:        fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Probability\" \n\
1.238     brouard  8113: set ter svg size 640, 480\nunset log y\nplot [%.f:%.f]  ", ageminpar, agemaxpar);
1.227     brouard  8114:        k=3; /* Offset */
1.268     brouard  8115:        for (i=1; i<= nlstate ; i ++){ /* State of arrival */
1.227     brouard  8116:          if(i==1)
                   8117:            fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"PIJB_"));
                   8118:          else
                   8119:            fprintf(ficgp,", '' ");
                   8120:          /* l=(nlstate+ndeath)*(i-1)+1; */
1.255     brouard  8121:          l=(nlstate+ndeath)*(cpt-1)+1; /* fixed for i; cpt=1 1, cpt=2 1+ nlstate+ndeath, 1+2*(nlstate+ndeath) */
1.324     brouard  8122:          /* fprintf(ficgp," u ($1==%d ? ($3):1/0):($%d/($%d",k1,k+l+(cpt-1),k+l); /\* a vérifier *\/ */
                   8123:          /* 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  8124:          fprintf(ficgp," u ($1==%d ? ($3):1/0):($%d",k1,k+l+i-1); /* To be verified */
1.227     brouard  8125:          /* for (j=2; j<= nlstate ; j ++) */
                   8126:          /*    fprintf(ficgp,"+$%d",k+l+j-1); */
                   8127:          /*    /\* fprintf(ficgp,"+$%d",k+l+j-1); *\/ */
1.268     brouard  8128:          fprintf(ficgp,") t \"bprev(%d,%d)\" w l",cpt,i);
1.227     brouard  8129:        } /* nlstate */
1.264     brouard  8130:        fprintf(ficgp,"\nset out; unset label;\n");
1.218     brouard  8131:       } /* end cpt state*/ 
                   8132:     } /* end covariate */  
1.296     brouard  8133:   } /* End if prevbcast */
1.218     brouard  8134:   
1.223     brouard  8135:   /* 8eme */
1.218     brouard  8136:   if(prevfcast==1){
1.288     brouard  8137:     /* Projection from cross-sectional to forward stable (period) prevalence for each covariate */
1.218     brouard  8138:     
1.237     brouard  8139:     for (k1=1; k1<= m ; k1 ++) /* For each covariate combination if any */
                   8140:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.253     brouard  8141:       if(m != 1 && TKresult[nres]!= k1)
1.237     brouard  8142:        continue;
1.211     brouard  8143:       for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each life state */
1.264     brouard  8144:        strcpy(gplotlabel,"(");      
1.288     brouard  8145:        fprintf(ficgp,"\n#\n#\n#Projection of prevalence to forward stable prevalence (period): 'PROJ_' files, covariatecombination#=%d state=%d",k1, cpt);
1.227     brouard  8146:        for (k=1; k<=cptcoveff; k++){    /* For each correspondig covariate value  */
                   8147:          lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate value corresponding to k1 combination and kth covariate */
                   8148:          /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   8149:          /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   8150:          /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
                   8151:          vlv= nbcode[Tvaraff[k]][lv];
                   8152:          fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv);
1.264     brouard  8153:          sprintf(gplotlabel+strlen(gplotlabel)," V%d=%d ",Tvaraff[k],vlv);
1.227     brouard  8154:        }
1.237     brouard  8155:        for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
                   8156:          fprintf(ficgp," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
1.264     brouard  8157:          sprintf(gplotlabel+strlen(gplotlabel)," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
1.237     brouard  8158:        }       
1.264     brouard  8159:        strcpy(gplotlabel+strlen(gplotlabel),")");
1.227     brouard  8160:        fprintf(ficgp,"\n#\n");
                   8161:        if(invalidvarcomb[k1]){
                   8162:          fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   8163:          continue;
                   8164:        }
                   8165:        
                   8166:        fprintf(ficgp,"# hpijx=probability over h years, hp.jx is weighted by observed prev\n ");
1.241     brouard  8167:        fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" \n",subdirf2(optionfilefiname,"PROJ_"),cpt,k1,nres);
1.264     brouard  8168:        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  8169:        fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Prevalence\" \n\
1.238     brouard  8170: set ter svg size 640, 480\nunset log y\nplot [%.f:%.f]  ", ageminpar, agemaxpar);
1.266     brouard  8171: 
                   8172:        /* for (i=1; i<= nlstate+1 ; i ++){  /\* nlstate +1 p11 p21 p.1 *\/ */
                   8173:        istart=nlstate+1; /* Could be one if by state, but nlstate+1 is w.i projection only */
                   8174:        /*istart=1;*/ /* Could be one if by state, but nlstate+1 is w.i projection only */
                   8175:        for (i=istart; i<= nlstate+1 ; i ++){  /* nlstate +1 p11 p21 p.1 */
1.227     brouard  8176:          /*#  V1  = 1  V2 =  0 yearproj age p11 p21 p.1 p12 p22 p.2 p13 p23 p.3*/
                   8177:          /*#   1    2   3    4    5      6  7   8   9   10   11 12  13   14  15 */   
                   8178:          /*# yearproj age p11 p21 p.1 p12 p22 p.2 p13 p23 p.3*/
                   8179:          /*#   1       2   3    4    5      6  7   8   9   10   11 12  13   14  15 */   
1.266     brouard  8180:          if(i==istart){
1.227     brouard  8181:            fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"F_"));
                   8182:          }else{
                   8183:            fprintf(ficgp,",\\\n '' ");
                   8184:          }
                   8185:          if(cptcoveff ==0){ /* No covariate */
                   8186:            ioffset=2; /* Age is in 2 */
                   8187:            /*# yearproj age p11 p21 p31 p.1 p12 p22 p32 p.2 p13 p23 p33 p.3 p14 p24 p34 p.4*/
                   8188:            /*#   1       2   3   4   5  6    7  8   9   10  11  12  13  14  15  16  17  18 */
                   8189:            /*# V1  = 1 yearproj age p11 p21 p31 p.1 p12 p22 p32 p.2 p13 p23 p33 p.3 p14 p24 p34 p.4*/
                   8190:            /*#  1    2        3   4   5  6    7  8   9   10  11  12  13  14  15  16  17  18 */
                   8191:            fprintf(ficgp," u %d:(", ioffset); 
1.266     brouard  8192:            if(i==nlstate+1){
1.270     brouard  8193:              fprintf(ficgp," $%d/(1.-$%d)):1 t 'pw.%d' with line lc variable ",        \
1.266     brouard  8194:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1),  ioffset+1+(i-1)+(nlstate+1)*nlstate,cpt );
                   8195:              fprintf(ficgp,",\\\n '' ");
                   8196:              fprintf(ficgp," u %d:(",ioffset); 
1.270     brouard  8197:              fprintf(ficgp," (($1-$2) == %d ) ? $%d/(1.-$%d) : 1/0):1 with labels center not ", \
1.266     brouard  8198:                     offyear,                           \
1.268     brouard  8199:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1),  ioffset+1+(i-1)+(nlstate+1)*nlstate );
1.266     brouard  8200:            }else
1.227     brouard  8201:              fprintf(ficgp," $%d/(1.-$%d)) t 'p%d%d' with line ",      \
                   8202:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1),  ioffset+1+(i-1)+(nlstate+1)*nlstate,i,cpt );
                   8203:          }else{ /* more than 2 covariates */
1.270     brouard  8204:            ioffset=2*cptcoveff+2; /* Age is in 4 or 6 or etc.*/
                   8205:            /*#  V1  = 1  V2 =  0 yearproj age p11 p21 p.1 p12 p22 p.2 p13 p23 p.3*/
                   8206:            /*#   1    2   3    4    5      6  7   8   9   10   11 12  13   14  15 */
                   8207:            iyearc=ioffset-1;
                   8208:            iagec=ioffset;
1.227     brouard  8209:            fprintf(ficgp," u %d:(",ioffset); 
                   8210:            kl=0;
                   8211:            strcpy(gplotcondition,"(");
                   8212:            for (k=1; k<=cptcoveff; k++){    /* For each covariate writing the chain of conditions */
                   8213:              lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate value corresponding to combination k1 and covariate k */
                   8214:              /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   8215:              /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   8216:              /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
                   8217:              vlv= nbcode[Tvaraff[k]][lv]; /* Value of the modality of Tvaraff[k] */
                   8218:              kl++;
                   8219:              sprintf(gplotcondition+strlen(gplotcondition),"$%d==%d && $%d==%d " ,kl,Tvaraff[k], kl+1, nbcode[Tvaraff[k]][lv]);
                   8220:              kl++;
                   8221:              if(k <cptcoveff && cptcoveff>1)
                   8222:                sprintf(gplotcondition+strlen(gplotcondition)," && ");
                   8223:            }
                   8224:            strcpy(gplotcondition+strlen(gplotcondition),")");
                   8225:            /* 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 *\/ */
                   8226:            /*6+(cpt-1)*(nlstate+1)+1+(i-1)+(nlstate+1)*nlstate; 6+(1-1)*(2+1)+1+(1-1) +(2+1)*2=13 */ 
                   8227:            /*6+1+(i-1)+(nlstate+1)*nlstate; 6+1+(1-1) +(2+1)*2=13 */ 
                   8228:            /* ''  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*/
                   8229:            if(i==nlstate+1){
1.270     brouard  8230:              fprintf(ficgp,"%s ? $%d/(1.-$%d) : 1/0):%d t 'p.%d' with line lc variable", gplotcondition, \
                   8231:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1),  ioffset+1+(i-1)+(nlstate+1)*nlstate,iyearc, cpt );
1.266     brouard  8232:              fprintf(ficgp,",\\\n '' ");
1.270     brouard  8233:              fprintf(ficgp," u %d:(",iagec); 
                   8234:              fprintf(ficgp,"%s && (($%d-$%d) == %d ) ? $%d/(1.-$%d) : 1/0):%d with labels center not ", gplotcondition, \
                   8235:                      iyearc, iagec, offyear,                           \
                   8236:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1),  ioffset+1+(i-1)+(nlstate+1)*nlstate, iyearc );
1.266     brouard  8237: /*  '' 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  8238:            }else{
                   8239:              fprintf(ficgp,"%s ? $%d/(1.-$%d) : 1/0) t 'p%d%d' with line ", gplotcondition, \
                   8240:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1), ioffset +1+(i-1)+(nlstate+1)*nlstate,i,cpt );
                   8241:            }
                   8242:          } /* end if covariate */
                   8243:        } /* nlstate */
1.264     brouard  8244:        fprintf(ficgp,"\nset out; unset label;\n");
1.223     brouard  8245:       } /* end cpt state*/
                   8246:     } /* end covariate */
                   8247:   } /* End if prevfcast */
1.227     brouard  8248:   
1.296     brouard  8249:   if(prevbcast==1){
1.268     brouard  8250:     /* Back projection from cross-sectional to stable (mixed) for each covariate */
                   8251:     
                   8252:     for (k1=1; k1<= m ; k1 ++) /* For each covariate combination if any */
                   8253:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
                   8254:       if(m != 1 && TKresult[nres]!= k1)
                   8255:        continue;
                   8256:       for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each life state */
                   8257:        strcpy(gplotlabel,"(");      
                   8258:        fprintf(ficgp,"\n#\n#\n#Back projection of prevalence to stable (mixed) back prevalence: 'BPROJ_' files, covariatecombination#=%d originstate=%d",k1, cpt);
                   8259:        for (k=1; k<=cptcoveff; k++){    /* For each correspondig covariate value  */
                   8260:          lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate value corresponding to k1 combination and kth covariate */
                   8261:          /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   8262:          /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   8263:          /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
                   8264:          vlv= nbcode[Tvaraff[k]][lv];
                   8265:          fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv);
                   8266:          sprintf(gplotlabel+strlen(gplotlabel)," V%d=%d ",Tvaraff[k],vlv);
                   8267:        }
                   8268:        for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
                   8269:          fprintf(ficgp," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
                   8270:          sprintf(gplotlabel+strlen(gplotlabel)," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
                   8271:        }       
                   8272:        strcpy(gplotlabel+strlen(gplotlabel),")");
                   8273:        fprintf(ficgp,"\n#\n");
                   8274:        if(invalidvarcomb[k1]){
                   8275:          fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   8276:          continue;
                   8277:        }
                   8278:        
                   8279:        fprintf(ficgp,"# hbijx=backprobability over h years, hb.jx is weighted by observed prev at destination state\n ");
                   8280:        fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" \n",subdirf2(optionfilefiname,"PROJB_"),cpt,k1,nres);
                   8281:        fprintf(ficgp,"set label \"Origin alive state %d %s\" at graph 0.98,0.5 center rotate font \"Helvetica,12\"\n",cpt,gplotlabel);
                   8282:        fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Prevalence\" \n\
                   8283: set ter svg size 640, 480\nunset log y\nplot [%.f:%.f]  ", ageminpar, agemaxpar);
                   8284: 
                   8285:        /* for (i=1; i<= nlstate+1 ; i ++){  /\* nlstate +1 p11 p21 p.1 *\/ */
                   8286:        istart=nlstate+1; /* Could be one if by state, but nlstate+1 is w.i projection only */
                   8287:        /*istart=1;*/ /* Could be one if by state, but nlstate+1 is w.i projection only */
                   8288:        for (i=istart; i<= nlstate+1 ; i ++){  /* nlstate +1 p11 p21 p.1 */
                   8289:          /*#  V1  = 1  V2 =  0 yearproj age p11 p21 p.1 p12 p22 p.2 p13 p23 p.3*/
                   8290:          /*#   1    2   3    4    5      6  7   8   9   10   11 12  13   14  15 */   
                   8291:          /*# yearproj age p11 p21 p.1 p12 p22 p.2 p13 p23 p.3*/
                   8292:          /*#   1       2   3    4    5      6  7   8   9   10   11 12  13   14  15 */   
                   8293:          if(i==istart){
                   8294:            fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"FB_"));
                   8295:          }else{
                   8296:            fprintf(ficgp,",\\\n '' ");
                   8297:          }
                   8298:          if(cptcoveff ==0){ /* No covariate */
                   8299:            ioffset=2; /* Age is in 2 */
                   8300:            /*# yearproj age p11 p21 p31 p.1 p12 p22 p32 p.2 p13 p23 p33 p.3 p14 p24 p34 p.4*/
                   8301:            /*#   1       2   3   4   5  6    7  8   9   10  11  12  13  14  15  16  17  18 */
                   8302:            /*# V1  = 1 yearproj age p11 p21 p31 p.1 p12 p22 p32 p.2 p13 p23 p33 p.3 p14 p24 p34 p.4*/
                   8303:            /*#  1    2        3   4   5  6    7  8   9   10  11  12  13  14  15  16  17  18 */
                   8304:            fprintf(ficgp," u %d:(", ioffset); 
                   8305:            if(i==nlstate+1){
1.270     brouard  8306:              fprintf(ficgp," $%d/(1.-$%d)):1 t 'bw%d' with line lc variable ", \
1.268     brouard  8307:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1),  ioffset+1+(i-1)+(nlstate+1)*nlstate,cpt );
                   8308:              fprintf(ficgp,",\\\n '' ");
                   8309:              fprintf(ficgp," u %d:(",ioffset); 
1.270     brouard  8310:              fprintf(ficgp," (($1-$2) == %d ) ? $%d : 1/0):1 with labels center not ", \
1.268     brouard  8311:                     offbyear,                          \
                   8312:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1) );
                   8313:            }else
                   8314:              fprintf(ficgp," $%d/(1.-$%d)) t 'b%d%d' with line ",      \
                   8315:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1),  ioffset+1+(i-1)+(nlstate+1)*nlstate,cpt,i );
                   8316:          }else{ /* more than 2 covariates */
1.270     brouard  8317:            ioffset=2*cptcoveff+2; /* Age is in 4 or 6 or etc.*/
                   8318:            /*#  V1  = 1  V2 =  0 yearproj age p11 p21 p.1 p12 p22 p.2 p13 p23 p.3*/
                   8319:            /*#   1    2   3    4    5      6  7   8   9   10   11 12  13   14  15 */
                   8320:            iyearc=ioffset-1;
                   8321:            iagec=ioffset;
1.268     brouard  8322:            fprintf(ficgp," u %d:(",ioffset); 
                   8323:            kl=0;
                   8324:            strcpy(gplotcondition,"(");
                   8325:            for (k=1; k<=cptcoveff; k++){    /* For each covariate writing the chain of conditions */
                   8326:              lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate value corresponding to combination k1 and covariate k */
                   8327:              /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   8328:              /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   8329:              /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
                   8330:              vlv= nbcode[Tvaraff[k]][lv]; /* Value of the modality of Tvaraff[k] */
                   8331:              kl++;
                   8332:              sprintf(gplotcondition+strlen(gplotcondition),"$%d==%d && $%d==%d " ,kl,Tvaraff[k], kl+1, nbcode[Tvaraff[k]][lv]);
                   8333:              kl++;
                   8334:              if(k <cptcoveff && cptcoveff>1)
                   8335:                sprintf(gplotcondition+strlen(gplotcondition)," && ");
                   8336:            }
                   8337:            strcpy(gplotcondition+strlen(gplotcondition),")");
                   8338:            /* 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 *\/ */
                   8339:            /*6+(cpt-1)*(nlstate+1)+1+(i-1)+(nlstate+1)*nlstate; 6+(1-1)*(2+1)+1+(1-1) +(2+1)*2=13 */ 
                   8340:            /*6+1+(i-1)+(nlstate+1)*nlstate; 6+1+(1-1) +(2+1)*2=13 */ 
                   8341:            /* ''  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*/
                   8342:            if(i==nlstate+1){
1.270     brouard  8343:              fprintf(ficgp,"%s ? $%d : 1/0):%d t 'bw%d' with line lc variable", gplotcondition, \
                   8344:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1),iyearc,cpt );
1.268     brouard  8345:              fprintf(ficgp,",\\\n '' ");
1.270     brouard  8346:              fprintf(ficgp," u %d:(",iagec); 
1.268     brouard  8347:              /* fprintf(ficgp,"%s && (($5-$6) == %d ) ? $%d/(1.-$%d) : 1/0):5 with labels center not ", gplotcondition, \ */
1.270     brouard  8348:              fprintf(ficgp,"%s && (($%d-$%d) == %d ) ? $%d : 1/0):%d with labels center not ", gplotcondition, \
                   8349:                      iyearc,iagec,offbyear,                            \
                   8350:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1), iyearc );
1.268     brouard  8351: /*  '' u 6:(($1==1 && $2==0  && $3==2 && $4==0) && (($5-$6) == 1947) ? $10/(1.-$22) : 1/0):5 with labels center boxed not*/
                   8352:            }else{
                   8353:              /* fprintf(ficgp,"%s ? $%d/(1.-$%d) : 1/0) t 'p%d%d' with line ", gplotcondition, \ */
                   8354:              fprintf(ficgp,"%s ? $%d : 1/0) t 'b%d%d' with line ", gplotcondition, \
                   8355:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1), cpt,i );
                   8356:            }
                   8357:          } /* end if covariate */
                   8358:        } /* nlstate */
                   8359:        fprintf(ficgp,"\nset out; unset label;\n");
                   8360:       } /* end cpt state*/
                   8361:     } /* end covariate */
1.296     brouard  8362:   } /* End if prevbcast */
1.268     brouard  8363:   
1.227     brouard  8364:   
1.238     brouard  8365:   /* 9eme writing MLE parameters */
                   8366:   fprintf(ficgp,"\n##############\n#9eme MLE estimated parameters\n#############\n");
1.126     brouard  8367:   for(i=1,jk=1; i <=nlstate; i++){
1.187     brouard  8368:     fprintf(ficgp,"# initial state %d\n",i);
1.126     brouard  8369:     for(k=1; k <=(nlstate+ndeath); k++){
                   8370:       if (k != i) {
1.227     brouard  8371:        fprintf(ficgp,"#   current state %d\n",k);
                   8372:        for(j=1; j <=ncovmodel; j++){
                   8373:          fprintf(ficgp,"p%d=%f; ",jk,p[jk]);
                   8374:          jk++; 
                   8375:        }
                   8376:        fprintf(ficgp,"\n");
1.126     brouard  8377:       }
                   8378:     }
1.223     brouard  8379:   }
1.187     brouard  8380:   fprintf(ficgp,"##############\n#\n");
1.227     brouard  8381:   
1.145     brouard  8382:   /*goto avoid;*/
1.238     brouard  8383:   /* 10eme Graphics of probabilities or incidences using written MLE parameters */
                   8384:   fprintf(ficgp,"\n##############\n#10eme Graphics of probabilities or incidences\n#############\n");
1.187     brouard  8385:   fprintf(ficgp,"# logi(p12/p11)=a12+b12*age+c12age*age+d12*V1+e12*V1*age\n");
                   8386:   fprintf(ficgp,"# logi(p12/p11)=p1 +p2*age +p3*age*age+ p4*V1+ p5*V1*age\n");
                   8387:   fprintf(ficgp,"# logi(p13/p11)=a13+b13*age+c13age*age+d13*V1+e13*V1*age\n");
                   8388:   fprintf(ficgp,"# logi(p13/p11)=p6 +p7*age +p8*age*age+ p9*V1+ p10*V1*age\n");
                   8389:   fprintf(ficgp,"# p12+p13+p14+p11=1=p11(1+exp(a12+b12*age+c12age*age+d12*V1+e12*V1*age)\n");
                   8390:   fprintf(ficgp,"#                      +exp(a13+b13*age+c13age*age+d13*V1+e13*V1*age)+...)\n");
                   8391:   fprintf(ficgp,"# p11=1/(1+exp(a12+b12*age+c12age*age+d12*V1+e12*V1*age)\n");
                   8392:   fprintf(ficgp,"#                      +exp(a13+b13*age+c13age*age+d13*V1+e13*V1*age)+...)\n");
                   8393:   fprintf(ficgp,"# p12=exp(a12+b12*age+c12age*age+d12*V1+e12*V1*age)/\n");
                   8394:   fprintf(ficgp,"#     (1+exp(a12+b12*age+c12age*age+d12*V1+e12*V1*age)\n");
                   8395:   fprintf(ficgp,"#       +exp(a13+b13*age+c13age*age+d13*V1+e13*V1*age))\n");
                   8396:   fprintf(ficgp,"#       +exp(a14+b14*age+c14age*age+d14*V1+e14*V1*age)+...)\n");
                   8397:   fprintf(ficgp,"#\n");
1.223     brouard  8398:   for(ng=1; ng<=3;ng++){ /* Number of graphics: first is logit, 2nd is probabilities, third is incidences per year*/
1.238     brouard  8399:     fprintf(ficgp,"#Number of graphics: first is logit, 2nd is probabilities, third is incidences per year\n");
1.237     brouard  8400:     fprintf(ficgp,"#model=%s \n",model);
1.238     brouard  8401:     fprintf(ficgp,"# Type of graphic ng=%d\n",ng);
1.264     brouard  8402:     fprintf(ficgp,"#   k1=1 to 2^%d=%d\n",cptcoveff,m);/* to be checked */
                   8403:     for(k1=1; k1 <=m; k1++)  /* For each combination of covariate */
1.237     brouard  8404:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.264     brouard  8405:       if(m != 1 && TKresult[nres]!= k1)
1.237     brouard  8406:        continue;
1.264     brouard  8407:       fprintf(ficgp,"\n\n# Combination of dummy  k1=%d which is ",k1);
                   8408:       strcpy(gplotlabel,"(");
1.276     brouard  8409:       /*sprintf(gplotlabel+strlen(gplotlabel)," Dummy combination %d ",k1);*/
1.264     brouard  8410:       for (k=1; k<=cptcoveff; k++){    /* For each correspondig covariate value  */
                   8411:        lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate value corresponding to k1 combination and kth covariate */
                   8412:        /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   8413:        /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   8414:        /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
                   8415:        vlv= nbcode[Tvaraff[k]][lv];
                   8416:        fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv);
                   8417:        sprintf(gplotlabel+strlen(gplotlabel)," V%d=%d ",Tvaraff[k],vlv);
                   8418:       }
1.237     brouard  8419:       for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
                   8420:        fprintf(ficgp," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
1.264     brouard  8421:        sprintf(gplotlabel+strlen(gplotlabel)," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
1.237     brouard  8422:       }        
1.264     brouard  8423:       strcpy(gplotlabel+strlen(gplotlabel),")");
1.237     brouard  8424:       fprintf(ficgp,"\n#\n");
1.264     brouard  8425:       fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" ",subdirf2(optionfilefiname,"PE_"),k1,ng,nres);
1.276     brouard  8426:       fprintf(ficgp,"\nset key outside ");
                   8427:       /* fprintf(ficgp,"\nset label \"%s\" at graph 1.2,0.5 center rotate font \"Helvetica,12\"\n",gplotlabel); */
                   8428:       fprintf(ficgp,"\nset title \"%s\" font \"Helvetica,12\"\n",gplotlabel);
1.223     brouard  8429:       fprintf(ficgp,"\nset ter svg size 640, 480 ");
                   8430:       if (ng==1){
                   8431:        fprintf(ficgp,"\nset ylabel \"Value of the logit of the model\"\n"); /* exp(a12+b12*x) could be nice */
                   8432:        fprintf(ficgp,"\nunset log y");
                   8433:       }else if (ng==2){
                   8434:        fprintf(ficgp,"\nset ylabel \"Probability\"\n");
                   8435:        fprintf(ficgp,"\nset log y");
                   8436:       }else if (ng==3){
                   8437:        fprintf(ficgp,"\nset ylabel \"Quasi-incidence per year\"\n");
                   8438:        fprintf(ficgp,"\nset log y");
                   8439:       }else
                   8440:        fprintf(ficgp,"\nunset title ");
                   8441:       fprintf(ficgp,"\nplot  [%.f:%.f] ",ageminpar,agemaxpar);
                   8442:       i=1;
                   8443:       for(k2=1; k2<=nlstate; k2++) {
                   8444:        k3=i;
                   8445:        for(k=1; k<=(nlstate+ndeath); k++) {
                   8446:          if (k != k2){
                   8447:            switch( ng) {
                   8448:            case 1:
                   8449:              if(nagesqr==0)
                   8450:                fprintf(ficgp," p%d+p%d*x",i,i+1);
                   8451:              else /* nagesqr =1 */
                   8452:                fprintf(ficgp," p%d+p%d*x+p%d*x*x",i,i+1,i+1+nagesqr);
                   8453:              break;
                   8454:            case 2: /* ng=2 */
                   8455:              if(nagesqr==0)
                   8456:                fprintf(ficgp," exp(p%d+p%d*x",i,i+1);
                   8457:              else /* nagesqr =1 */
                   8458:                fprintf(ficgp," exp(p%d+p%d*x+p%d*x*x",i,i+1,i+1+nagesqr);
                   8459:              break;
                   8460:            case 3:
                   8461:              if(nagesqr==0)
                   8462:                fprintf(ficgp," %f*exp(p%d+p%d*x",YEARM/stepm,i,i+1);
                   8463:              else /* nagesqr =1 */
                   8464:                fprintf(ficgp," %f*exp(p%d+p%d*x+p%d*x*x",YEARM/stepm,i,i+1,i+1+nagesqr);
                   8465:              break;
                   8466:            }
                   8467:            ij=1;/* To be checked else nbcode[0][0] wrong */
1.237     brouard  8468:            ijp=1; /* product no age */
                   8469:            /* for(j=3; j <=ncovmodel-nagesqr; j++) { */
                   8470:            for(j=1; j <=cptcovt; j++) { /* For each covariate of the simplified model */
1.223     brouard  8471:              /* printf("Tage[%d]=%d, j=%d\n", ij, Tage[ij], j); */
1.329     brouard  8472:              switch(Typevar[j]){
                   8473:              case 1:
                   8474:                if(cptcovage >0){ /* V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1, 2 V5 and V1 */
                   8475:                  if(j==Tage[ij]) { /* Product by age  To be looked at!!*//* Bug valgrind */
                   8476:                    if(ij <=cptcovage) { /* V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1, 2 V5 and V1 */
                   8477:                      if(DummyV[j]==0){/* Bug valgrind */
                   8478:                        fprintf(ficgp,"+p%d*%d*x",i+j+2+nagesqr-1,Tinvresult[nres][Tvar[j]]);;
                   8479:                      }else{ /* quantitative */
                   8480:                        fprintf(ficgp,"+p%d*%f*x",i+j+2+nagesqr-1,Tqinvresult[nres][Tvar[j]]); /* Tqinvresult in decoderesult */
                   8481:                        /* fprintf(ficgp,"+p%d*%d*x",i+j+nagesqr-1,nbcode[Tvar[j-2]][codtabm(k1,Tvar[j-2])]); */
                   8482:                      }
                   8483:                      ij++;
1.268     brouard  8484:                    }
1.237     brouard  8485:                  }
1.329     brouard  8486:                }
                   8487:                break;
                   8488:              case 2:
                   8489:                if(cptcovprod >0){
                   8490:                  if(j==Tprod[ijp]) { /* */ 
                   8491:                    /* printf("Tprod[%d]=%d, j=%d\n", ij, Tprod[ijp], j); */
                   8492:                    if(ijp <=cptcovprod) { /* Product */
                   8493:                      if(DummyV[Tvard[ijp][1]]==0){/* Vn is dummy */
                   8494:                        if(DummyV[Tvard[ijp][2]]==0){/* Vn and Vm are dummy */
                   8495:                          /* 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)]); */
                   8496:                          fprintf(ficgp,"+p%d*%d*%d",i+j+2+nagesqr-1,Tinvresult[nres][Tvard[ijp][1]],Tinvresult[nres][Tvard[ijp][2]]);
                   8497:                        }else{ /* Vn is dummy and Vm is quanti */
                   8498:                          /* fprintf(ficgp,"+p%d*%d*%f",i+j+2+nagesqr-1,nbcode[Tvard[ijp][1]][codtabm(k1,j)],Tqinvresult[nres][Tvard[ijp][2]]); */
                   8499:                          fprintf(ficgp,"+p%d*%d*%f",i+j+2+nagesqr-1,Tinvresult[nres][Tvard[ijp][1]],Tqinvresult[nres][Tvard[ijp][2]]);
                   8500:                        }
                   8501:                      }else{ /* Vn*Vm Vn is quanti */
                   8502:                        if(DummyV[Tvard[ijp][2]]==0){
                   8503:                          fprintf(ficgp,"+p%d*%d*%f",i+j+2+nagesqr-1,Tinvresult[nres][Tvard[ijp][2]],Tqinvresult[nres][Tvard[ijp][1]]);
                   8504:                        }else{ /* Both quanti */
                   8505:                          fprintf(ficgp,"+p%d*%f*%f",i+j+2+nagesqr-1,Tqinvresult[nres][Tvard[ijp][1]],Tqinvresult[nres][Tvard[ijp][2]]);
                   8506:                        }
1.268     brouard  8507:                      }
1.329     brouard  8508:                      ijp++;
1.237     brouard  8509:                    }
1.329     brouard  8510:                  } /* end Tprod */
                   8511:                }
                   8512:                break;
                   8513:              case 0:
                   8514:                /* simple covariate */
1.264     brouard  8515:                /* fprintf(ficgp,"+p%d*%d",i+j+2+nagesqr-1,nbcode[Tvar[j]][codtabm(k1,j)]); /\* Valgrind bug nbcode *\/ */
1.237     brouard  8516:                if(Dummy[j]==0){
                   8517:                  fprintf(ficgp,"+p%d*%d",i+j+2+nagesqr-1,Tinvresult[nres][Tvar[j]]); /*  */
                   8518:                }else{ /* quantitative */
                   8519:                  fprintf(ficgp,"+p%d*%f",i+j+2+nagesqr-1,Tqinvresult[nres][Tvar[j]]); /* */
1.264     brouard  8520:                  /* fprintf(ficgp,"+p%d*%d*x",i+j+nagesqr-1,nbcode[Tvar[j-2]][codtabm(k1,Tvar[j-2])]); */
1.223     brouard  8521:                }
1.329     brouard  8522:               /* end simple */
                   8523:                break;
                   8524:              default:
                   8525:                break;
                   8526:              } /* end switch */
1.237     brouard  8527:            } /* end j */
1.329     brouard  8528:          }else{ /* k=k2 */
                   8529:            if(ng !=1 ){ /* For logit formula of log p11 is more difficult to get */
                   8530:              fprintf(ficgp," (1.");i=i-ncovmodel;
                   8531:            }else
                   8532:              i=i-ncovmodel;
1.223     brouard  8533:          }
1.227     brouard  8534:          
1.223     brouard  8535:          if(ng != 1){
                   8536:            fprintf(ficgp,")/(1");
1.227     brouard  8537:            
1.264     brouard  8538:            for(cpt=1; cpt <=nlstate; cpt++){ 
1.223     brouard  8539:              if(nagesqr==0)
1.264     brouard  8540:                fprintf(ficgp,"+exp(p%d+p%d*x",k3+(cpt-1)*ncovmodel,k3+(cpt-1)*ncovmodel+1);
1.223     brouard  8541:              else /* nagesqr =1 */
1.264     brouard  8542:                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  8543:               
1.223     brouard  8544:              ij=1;
1.329     brouard  8545:              ijp=1;
                   8546:              /* for(j=3; j <=ncovmodel-nagesqr; j++){ */
                   8547:              for(j=1; j <=cptcovt; j++) { /* For each covariate of the simplified model */
                   8548:                switch(Typevar[j]){
                   8549:                case 1:
                   8550:                  if(cptcovage >0){ 
                   8551:                    if(j==Tage[ij]) { /* Bug valgrind */
                   8552:                      if(ij <=cptcovage) { /* Bug valgrind */
                   8553:                        if(DummyV[j]==0){/* Bug valgrind */
                   8554:                          /* fprintf(ficgp,"+p%d*%d*x",k3+(cpt-1)*ncovmodel+1+j-2+nagesqr,nbcode[Tvar[j-2]][codtabm(k1,j-2)]); */
                   8555:                          /* fprintf(ficgp,"+p%d*%d*x",k3+(cpt-1)*ncovmodel+1+j+nagesqr,nbcode[Tvar[j]][codtabm(k1,j)]); */
                   8556:                          fprintf(ficgp,"+p%d*%d*x",k3+(cpt-1)*ncovmodel+1+j+nagesqr,Tinvresult[nres][Tvar[j]]);
                   8557:                          /* fprintf(ficgp,"+p%d*%d*x",i+j+2+nagesqr-1,Tinvresult[nres][Tvar[j]]);; */
                   8558:                          /* fprintf(ficgp,"+p%d*%d*x",k3+(cpt-1)*ncovmodel+1+j-2+nagesqr,nbcode[Tvar[j-2]][codtabm(k1,Tvar[j-2])]); */
                   8559:                        }else{ /* quantitative */
                   8560:                          /* fprintf(ficgp,"+p%d*%f*x",i+j+2+nagesqr-1,Tqinvresult[nres][Tvar[j]]); /\* Tqinvresult in decoderesult *\/ */
                   8561:                          fprintf(ficgp,"+p%d*%f*x",k3+(cpt-1)*ncovmodel+1+j+nagesqr,Tqinvresult[nres][Tvar[j]]); /* Tqinvresult in decoderesult */
                   8562:                          /* fprintf(ficgp,"+p%d*%f*x",i+j+2+nagesqr-1,Tqinvresult[nres][Tvar[j]]); /\* Tqinvresult in decoderesult *\/ */
                   8563:                          /* fprintf(ficgp,"+p%d*%d*x",i+j+nagesqr-1,nbcode[Tvar[j-2]][codtabm(k1,Tvar[j-2])]); */
                   8564:                        }
                   8565:                        ij++;
                   8566:                      }
                   8567:                    }
                   8568:                  }
                   8569:                  break;
                   8570:                case 2:
                   8571:                  if(cptcovprod >0){
                   8572:                    if(j==Tprod[ijp]) { /* */ 
                   8573:                      /* printf("Tprod[%d]=%d, j=%d\n", ij, Tprod[ijp], j); */
                   8574:                      if(ijp <=cptcovprod) { /* Product */
                   8575:                        if(DummyV[Tvard[ijp][1]]==0){/* Vn is dummy */
                   8576:                          if(DummyV[Tvard[ijp][2]]==0){/* Vn and Vm are dummy */
                   8577:                            /* 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)]); */
                   8578:                            fprintf(ficgp,"+p%d*%d*%d",k3+(cpt-1)*ncovmodel+1+j+nagesqr,Tinvresult[nres][Tvard[ijp][1]],Tinvresult[nres][Tvard[ijp][2]]);
                   8579:                            /* fprintf(ficgp,"+p%d*%d*%d",i+j+2+nagesqr-1,Tinvresult[nres][Tvard[ijp][1]],Tinvresult[nres][Tvard[ijp][2]]); */
                   8580:                          }else{ /* Vn is dummy and Vm is quanti */
                   8581:                            /* fprintf(ficgp,"+p%d*%d*%f",i+j+2+nagesqr-1,nbcode[Tvard[ijp][1]][codtabm(k1,j)],Tqinvresult[nres][Tvard[ijp][2]]); */
                   8582:                            fprintf(ficgp,"+p%d*%d*%f",k3+(cpt-1)*ncovmodel+1+j+nagesqr,Tinvresult[nres][Tvard[ijp][1]],Tqinvresult[nres][Tvard[ijp][2]]);
                   8583:                            /* fprintf(ficgp,"+p%d*%d*%f",i+j+2+nagesqr-1,Tinvresult[nres][Tvard[ijp][1]],Tqinvresult[nres][Tvard[ijp][2]]); */
                   8584:                          }
                   8585:                        }else{ /* Vn*Vm Vn is quanti */
                   8586:                          if(DummyV[Tvard[ijp][2]]==0){
                   8587:                            fprintf(ficgp,"+p%d*%d*%f",k3+(cpt-1)*ncovmodel+1+j+nagesqr,Tinvresult[nres][Tvard[ijp][2]],Tqinvresult[nres][Tvard[ijp][1]]);
                   8588:                            /* fprintf(ficgp,"+p%d*%d*%f",i+j+2+nagesqr-1,Tinvresult[nres][Tvard[ijp][2]],Tqinvresult[nres][Tvard[ijp][1]]); */
                   8589:                          }else{ /* Both quanti */
                   8590:                            fprintf(ficgp,"+p%d*%f*%f",k3+(cpt-1)*ncovmodel+1+j+nagesqr,Tqinvresult[nres][Tvard[ijp][1]],Tqinvresult[nres][Tvard[ijp][2]]);
                   8591:                            /* fprintf(ficgp,"+p%d*%f*%f",i+j+2+nagesqr-1,Tqinvresult[nres][Tvard[ijp][1]],Tqinvresult[nres][Tvard[ijp][2]]); */
                   8592:                          } 
                   8593:                        }
                   8594:                        ijp++;
                   8595:                      }
                   8596:                    } /* end Tprod */
                   8597:                  } /* end if */
                   8598:                  break;
                   8599:                case 0: 
                   8600:                  /* simple covariate */
                   8601:                  /* fprintf(ficgp,"+p%d*%d",i+j+2+nagesqr-1,nbcode[Tvar[j]][codtabm(k1,j)]); /\* Valgrind bug nbcode *\/ */
                   8602:                  if(Dummy[j]==0){
                   8603:                    /* fprintf(ficgp,"+p%d*%d",i+j+2+nagesqr-1,Tinvresult[nres][Tvar[j]]); /\*  *\/ */
                   8604:                    fprintf(ficgp,"+p%d*%d",k3+(cpt-1)*ncovmodel+1+j+nagesqr,Tinvresult[nres][Tvar[j]]); /*  */
                   8605:                    /* fprintf(ficgp,"+p%d*%d",i+j+2+nagesqr-1,Tinvresult[nres][Tvar[j]]); /\*  *\/ */
                   8606:                  }else{ /* quantitative */
                   8607:                    fprintf(ficgp,"+p%d*%f",k3+(cpt-1)*ncovmodel+1+j+nagesqr,Tqinvresult[nres][Tvar[j]]); /* */
                   8608:                    /* fprintf(ficgp,"+p%d*%f",i+j+2+nagesqr-1,Tqinvresult[nres][Tvar[j]]); /\* *\/ */
                   8609:                    /* fprintf(ficgp,"+p%d*%d*x",i+j+nagesqr-1,nbcode[Tvar[j-2]][codtabm(k1,Tvar[j-2])]); */
                   8610:                  }
                   8611:                  /* end simple */
                   8612:                  /* fprintf(ficgp,"+p%d*%d",k3+(cpt-1)*ncovmodel+1+j-2+nagesqr,nbcode[Tvar[j-2]][codtabm(k1,j-2)]);/\* Valgrind bug nbcode *\/ */
                   8613:                  break;
                   8614:                default:
                   8615:                  break;
                   8616:                } /* end switch */
1.223     brouard  8617:              }
                   8618:              fprintf(ficgp,")");
                   8619:            }
                   8620:            fprintf(ficgp,")");
                   8621:            if(ng ==2)
1.276     brouard  8622:              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  8623:            else /* ng= 3 */
1.276     brouard  8624:              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.329     brouard  8625:           }else{ /* end ng <> 1 */
1.223     brouard  8626:            if( k !=k2) /* logit p11 is hard to draw */
1.276     brouard  8627:              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  8628:          }
                   8629:          if ((k+k2)!= (nlstate*2+ndeath) && ng != 1)
                   8630:            fprintf(ficgp,",");
                   8631:          if (ng == 1 && k!=k2 && (k+k2)!= (nlstate*2+ndeath))
                   8632:            fprintf(ficgp,",");
                   8633:          i=i+ncovmodel;
                   8634:        } /* end k */
                   8635:       } /* end k2 */
1.276     brouard  8636:       /* fprintf(ficgp,"\n set out; unset label;set key default;\n"); */
                   8637:       fprintf(ficgp,"\n set out; unset title;set key default;\n");
1.264     brouard  8638:     } /* end k1 */
1.223     brouard  8639:   } /* end ng */
                   8640:   /* avoid: */
                   8641:   fflush(ficgp); 
1.126     brouard  8642: }  /* end gnuplot */
                   8643: 
                   8644: 
                   8645: /*************** Moving average **************/
1.219     brouard  8646: /* int movingaverage(double ***probs, double bage, double fage, double ***mobaverage, int mobilav, double bageout, double fageout){ */
1.222     brouard  8647:  int movingaverage(double ***probs, double bage, double fage, double ***mobaverage, int mobilav){
1.218     brouard  8648:    
1.222     brouard  8649:    int i, cpt, cptcod;
                   8650:    int modcovmax =1;
                   8651:    int mobilavrange, mob;
                   8652:    int iage=0;
1.288     brouard  8653:    int firstA1=0, firstA2=0;
1.222     brouard  8654: 
1.266     brouard  8655:    double sum=0., sumr=0.;
1.222     brouard  8656:    double age;
1.266     brouard  8657:    double *sumnewp, *sumnewm, *sumnewmr;
                   8658:    double *agemingood, *agemaxgood; 
                   8659:    double *agemingoodr, *agemaxgoodr; 
1.222     brouard  8660:   
                   8661:   
1.278     brouard  8662:    /* modcovmax=2*cptcoveff;  Max number of modalities. We suppose  */
                   8663:    /*             a covariate has 2 modalities, should be equal to ncovcombmax   */
1.222     brouard  8664: 
                   8665:    sumnewp = vector(1,ncovcombmax);
                   8666:    sumnewm = vector(1,ncovcombmax);
1.266     brouard  8667:    sumnewmr = vector(1,ncovcombmax);
1.222     brouard  8668:    agemingood = vector(1,ncovcombmax); 
1.266     brouard  8669:    agemingoodr = vector(1,ncovcombmax);        
1.222     brouard  8670:    agemaxgood = vector(1,ncovcombmax);
1.266     brouard  8671:    agemaxgoodr = vector(1,ncovcombmax);
1.222     brouard  8672: 
                   8673:    for (cptcod=1;cptcod<=ncovcombmax;cptcod++){
1.266     brouard  8674:      sumnewm[cptcod]=0.; sumnewmr[cptcod]=0.;
1.222     brouard  8675:      sumnewp[cptcod]=0.;
1.266     brouard  8676:      agemingood[cptcod]=0, agemingoodr[cptcod]=0;
                   8677:      agemaxgood[cptcod]=0, agemaxgoodr[cptcod]=0;
1.222     brouard  8678:    }
                   8679:    if (cptcovn<1) ncovcombmax=1; /* At least 1 pass */
                   8680:   
1.266     brouard  8681:    if(mobilav==-1 || mobilav==1||mobilav ==3 ||mobilav==5 ||mobilav== 7){
                   8682:      if(mobilav==1 || mobilav==-1) mobilavrange=5; /* default */
1.222     brouard  8683:      else mobilavrange=mobilav;
                   8684:      for (age=bage; age<=fage; age++)
                   8685:        for (i=1; i<=nlstate;i++)
                   8686:         for (cptcod=1;cptcod<=ncovcombmax;cptcod++)
                   8687:           mobaverage[(int)age][i][cptcod]=probs[(int)age][i][cptcod];
                   8688:      /* We keep the original values on the extreme ages bage, fage and for 
                   8689:        fage+1 and bage-1 we use a 3 terms moving average; for fage+2 bage+2
                   8690:        we use a 5 terms etc. until the borders are no more concerned. 
                   8691:      */ 
                   8692:      for (mob=3;mob <=mobilavrange;mob=mob+2){
                   8693:        for (age=bage+(mob-1)/2; age<=fage-(mob-1)/2; age++){
1.266     brouard  8694:         for (cptcod=1;cptcod<=ncovcombmax;cptcod++){
                   8695:           sumnewm[cptcod]=0.;
                   8696:           for (i=1; i<=nlstate;i++){
1.222     brouard  8697:             mobaverage[(int)age][i][cptcod] =probs[(int)age][i][cptcod];
                   8698:             for (cpt=1;cpt<=(mob-1)/2;cpt++){
                   8699:               mobaverage[(int)age][i][cptcod] +=probs[(int)age-cpt][i][cptcod];
                   8700:               mobaverage[(int)age][i][cptcod] +=probs[(int)age+cpt][i][cptcod];
                   8701:             }
                   8702:             mobaverage[(int)age][i][cptcod]=mobaverage[(int)age][i][cptcod]/mob;
1.266     brouard  8703:             sumnewm[cptcod]+=mobaverage[(int)age][i][cptcod];
                   8704:           } /* end i */
                   8705:           if(sumnewm[cptcod] >1.e-3) mobaverage[(int)age][i][cptcod]=mobaverage[(int)age][i][cptcod]/sumnewm[cptcod]; /* Rescaling to sum one */
                   8706:         } /* end cptcod */
1.222     brouard  8707:        }/* end age */
                   8708:      }/* end mob */
1.266     brouard  8709:    }else{
                   8710:      printf("Error internal in movingaverage, mobilav=%d.\n",mobilav);
1.222     brouard  8711:      return -1;
1.266     brouard  8712:    }
                   8713: 
                   8714:    for (cptcod=1;cptcod<=ncovcombmax;cptcod++){ /* for each combination */
1.222     brouard  8715:      /* for (age=bage+(mob-1)/2; age<=fage-(mob-1)/2; age++){ */
                   8716:      if(invalidvarcomb[cptcod]){
                   8717:        printf("\nCombination (%d) ignored because no cases \n",cptcod); 
                   8718:        continue;
                   8719:      }
1.219     brouard  8720: 
1.266     brouard  8721:      for (age=fage-(mob-1)/2; age>=bage+(mob-1)/2; age--){ /*looking for the youngest and oldest good age */
                   8722:        sumnewm[cptcod]=0.;
                   8723:        sumnewmr[cptcod]=0.;
                   8724:        for (i=1; i<=nlstate;i++){
                   8725:         sumnewm[cptcod]+=mobaverage[(int)age][i][cptcod];
                   8726:         sumnewmr[cptcod]+=probs[(int)age][i][cptcod];
                   8727:        }
                   8728:        if(fabs(sumnewmr[cptcod] - 1.) <= 1.e-3) { /* good without smoothing */
                   8729:         agemingoodr[cptcod]=age;
                   8730:        }
                   8731:        if(fabs(sumnewm[cptcod] - 1.) <= 1.e-3) { /* good */
                   8732:           agemingood[cptcod]=age;
                   8733:        }
                   8734:      } /* age */
                   8735:      for (age=bage+(mob-1)/2; age<=fage-(mob-1)/2; age++){ /*looking for the youngest and oldest good age */
1.222     brouard  8736:        sumnewm[cptcod]=0.;
1.266     brouard  8737:        sumnewmr[cptcod]=0.;
1.222     brouard  8738:        for (i=1; i<=nlstate;i++){
                   8739:         sumnewm[cptcod]+=mobaverage[(int)age][i][cptcod];
1.266     brouard  8740:         sumnewmr[cptcod]+=probs[(int)age][i][cptcod];
                   8741:        }
                   8742:        if(fabs(sumnewmr[cptcod] - 1.) <= 1.e-3) { /* good without smoothing */
                   8743:         agemaxgoodr[cptcod]=age;
1.222     brouard  8744:        }
                   8745:        if(fabs(sumnewm[cptcod] - 1.) <= 1.e-3) { /* good */
1.266     brouard  8746:         agemaxgood[cptcod]=age;
                   8747:        }
                   8748:      } /* age */
                   8749:      /* Thus we have agemingood and agemaxgood as well as goodr for raw (preobs) */
                   8750:      /* but they will change */
1.288     brouard  8751:      firstA1=0;firstA2=0;
1.266     brouard  8752:      for (age=fage-(mob-1)/2; age>=bage; age--){/* From oldest to youngest, filling up to the youngest */
                   8753:        sumnewm[cptcod]=0.;
                   8754:        sumnewmr[cptcod]=0.;
                   8755:        for (i=1; i<=nlstate;i++){
                   8756:         sumnewm[cptcod]+=mobaverage[(int)age][i][cptcod];
                   8757:         sumnewmr[cptcod]+=probs[(int)age][i][cptcod];
                   8758:        }
                   8759:        if(mobilav==-1){ /* Forcing raw ages if good else agemingood */
                   8760:         if(fabs(sumnewmr[cptcod] - 1.) <= 1.e-3) { /* good without smoothing */
                   8761:           agemaxgoodr[cptcod]=age;  /* age min */
                   8762:           for (i=1; i<=nlstate;i++)
                   8763:             mobaverage[(int)age][i][cptcod]=probs[(int)age][i][cptcod];
                   8764:         }else{ /* bad we change the value with the values of good ages */
                   8765:           for (i=1; i<=nlstate;i++){
                   8766:             mobaverage[(int)age][i][cptcod]=mobaverage[(int)agemaxgoodr[cptcod]][i][cptcod];
                   8767:           } /* i */
                   8768:         } /* end bad */
                   8769:        }else{
                   8770:         if(fabs(sumnewm[cptcod] - 1.) <= 1.e-3) { /* good */
                   8771:           agemaxgood[cptcod]=age;
                   8772:         }else{ /* bad we change the value with the values of good ages */
                   8773:           for (i=1; i<=nlstate;i++){
                   8774:             mobaverage[(int)age][i][cptcod]=mobaverage[(int)agemaxgood[cptcod]][i][cptcod];
                   8775:           } /* i */
                   8776:         } /* end bad */
                   8777:        }/* end else */
                   8778:        sum=0.;sumr=0.;
                   8779:        for (i=1; i<=nlstate;i++){
                   8780:         sum+=mobaverage[(int)age][i][cptcod];
                   8781:         sumr+=probs[(int)age][i][cptcod];
                   8782:        }
                   8783:        if(fabs(sum - 1.) > 1.e-3) { /* bad */
1.288     brouard  8784:         if(!firstA1){
                   8785:           firstA1=1;
                   8786:           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);
                   8787:         }
                   8788:         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  8789:        } /* end bad */
                   8790:        /* else{ /\* We found some ages summing to one, we will smooth the oldest *\/ */
                   8791:        if(fabs(sumr - 1.) > 1.e-3) { /* bad */
1.288     brouard  8792:         if(!firstA2){
                   8793:           firstA2=1;
                   8794:           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);
                   8795:         }
                   8796:         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  8797:        } /* end bad */
                   8798:      }/* age */
1.266     brouard  8799: 
                   8800:      for (age=bage+(mob-1)/2; age<=fage; age++){/* From youngest, finding the oldest wrong */
1.222     brouard  8801:        sumnewm[cptcod]=0.;
1.266     brouard  8802:        sumnewmr[cptcod]=0.;
1.222     brouard  8803:        for (i=1; i<=nlstate;i++){
                   8804:         sumnewm[cptcod]+=mobaverage[(int)age][i][cptcod];
1.266     brouard  8805:         sumnewmr[cptcod]+=probs[(int)age][i][cptcod];
                   8806:        } 
                   8807:        if(mobilav==-1){ /* Forcing raw ages if good else agemingood */
                   8808:         if(fabs(sumnewmr[cptcod] - 1.) <= 1.e-3) { /* good */
                   8809:           agemingoodr[cptcod]=age;
                   8810:           for (i=1; i<=nlstate;i++)
                   8811:             mobaverage[(int)age][i][cptcod]=probs[(int)age][i][cptcod];
                   8812:         }else{ /* bad we change the value with the values of good ages */
                   8813:           for (i=1; i<=nlstate;i++){
                   8814:             mobaverage[(int)age][i][cptcod]=mobaverage[(int)agemingoodr[cptcod]][i][cptcod];
                   8815:           } /* i */
                   8816:         } /* end bad */
                   8817:        }else{
                   8818:         if(fabs(sumnewm[cptcod] - 1.) <= 1.e-3) { /* good */
                   8819:           agemingood[cptcod]=age;
                   8820:         }else{ /* bad */
                   8821:           for (i=1; i<=nlstate;i++){
                   8822:             mobaverage[(int)age][i][cptcod]=mobaverage[(int)agemingood[cptcod]][i][cptcod];
                   8823:           } /* i */
                   8824:         } /* end bad */
                   8825:        }/* end else */
                   8826:        sum=0.;sumr=0.;
                   8827:        for (i=1; i<=nlstate;i++){
                   8828:         sum+=mobaverage[(int)age][i][cptcod];
                   8829:         sumr+=mobaverage[(int)age][i][cptcod];
1.222     brouard  8830:        }
1.266     brouard  8831:        if(fabs(sum - 1.) > 1.e-3) { /* bad */
1.268     brouard  8832:         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  8833:        } /* end bad */
                   8834:        /* else{ /\* We found some ages summing to one, we will smooth the oldest *\/ */
                   8835:        if(fabs(sumr - 1.) > 1.e-3) { /* bad */
1.268     brouard  8836:         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  8837:        } /* end bad */
                   8838:      }/* age */
1.266     brouard  8839: 
1.222     brouard  8840:                
                   8841:      for (age=bage; age<=fage; age++){
1.235     brouard  8842:        /* printf("%d %d ", cptcod, (int)age); */
1.222     brouard  8843:        sumnewp[cptcod]=0.;
                   8844:        sumnewm[cptcod]=0.;
                   8845:        for (i=1; i<=nlstate;i++){
                   8846:         sumnewp[cptcod]+=probs[(int)age][i][cptcod];
                   8847:         sumnewm[cptcod]+=mobaverage[(int)age][i][cptcod];
                   8848:         /* printf("%.4f %.4f ",probs[(int)age][i][cptcod], mobaverage[(int)age][i][cptcod]); */
                   8849:        }
                   8850:        /* printf("%.4f %.4f \n",sumnewp[cptcod], sumnewm[cptcod]); */
                   8851:      }
                   8852:      /* printf("\n"); */
                   8853:      /* } */
1.266     brouard  8854: 
1.222     brouard  8855:      /* brutal averaging */
1.266     brouard  8856:      /* for (i=1; i<=nlstate;i++){ */
                   8857:      /*   for (age=1; age<=bage; age++){ */
                   8858:      /*         mobaverage[(int)age][i][cptcod]=mobaverage[(int)agemingood[cptcod]][i][cptcod]; */
                   8859:      /*         /\* printf("age=%d i=%d cptcod=%d mobaverage=%.4f \n",(int)age,i, cptcod, mobaverage[(int)age][i][cptcod]); *\/ */
                   8860:      /*   }     */
                   8861:      /*   for (age=fage; age<=AGESUP; age++){ */
                   8862:      /*         mobaverage[(int)age][i][cptcod]=mobaverage[(int)agemaxgood[cptcod]][i][cptcod]; */
                   8863:      /*         /\* printf("age=%d i=%d cptcod=%d mobaverage=%.4f \n",(int)age,i, cptcod, mobaverage[(int)age][i][cptcod]); *\/ */
                   8864:      /*   } */
                   8865:      /* } /\* end i status *\/ */
                   8866:      /* for (i=nlstate+1; i<=nlstate+ndeath;i++){ */
                   8867:      /*   for (age=1; age<=AGESUP; age++){ */
                   8868:      /*         /\*printf("i=%d, age=%d, cptcod=%d\n",i, (int)age, cptcod);*\/ */
                   8869:      /*         mobaverage[(int)age][i][cptcod]=0.; */
                   8870:      /*   } */
                   8871:      /* } */
1.222     brouard  8872:    }/* end cptcod */
1.266     brouard  8873:    free_vector(agemaxgoodr,1, ncovcombmax);
                   8874:    free_vector(agemaxgood,1, ncovcombmax);
                   8875:    free_vector(agemingood,1, ncovcombmax);
                   8876:    free_vector(agemingoodr,1, ncovcombmax);
                   8877:    free_vector(sumnewmr,1, ncovcombmax);
1.222     brouard  8878:    free_vector(sumnewm,1, ncovcombmax);
                   8879:    free_vector(sumnewp,1, ncovcombmax);
                   8880:    return 0;
                   8881:  }/* End movingaverage */
1.218     brouard  8882:  
1.126     brouard  8883: 
1.296     brouard  8884:  
1.126     brouard  8885: /************** Forecasting ******************/
1.296     brouard  8886: /* 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)*/
                   8887: 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){
                   8888:   /* dateintemean, mean date of interviews
                   8889:      dateprojd, year, month, day of starting projection 
                   8890:      dateprojf date of end of projection;year of end of projection (same day and month as proj1).
1.126     brouard  8891:      agemin, agemax range of age
                   8892:      dateprev1 dateprev2 range of dates during which prevalence is computed
                   8893:   */
1.296     brouard  8894:   /* double anprojd, mprojd, jprojd; */
                   8895:   /* double anprojf, mprojf, jprojf; */
1.267     brouard  8896:   int yearp, stepsize, hstepm, nhstepm, j, k, cptcod, i, h, i1, k4, nres=0;
1.126     brouard  8897:   double agec; /* generic age */
1.296     brouard  8898:   double agelim, ppij, yp,yp1,yp2;
1.126     brouard  8899:   double *popeffectif,*popcount;
                   8900:   double ***p3mat;
1.218     brouard  8901:   /* double ***mobaverage; */
1.126     brouard  8902:   char fileresf[FILENAMELENGTH];
                   8903: 
                   8904:   agelim=AGESUP;
1.211     brouard  8905:   /* Compute observed prevalence between dateprev1 and dateprev2 by counting the number of people
                   8906:      in each health status at the date of interview (if between dateprev1 and dateprev2).
                   8907:      We still use firstpass and lastpass as another selection.
                   8908:   */
1.214     brouard  8909:   /* freqsummary(fileres, agemin, agemax, s, agev, nlstate, imx,Tvaraff,nbcode, ncodemax,mint,anint,strstart,\ */
                   8910:   /*         firstpass, lastpass,  stepm,  weightopt, model); */
1.126     brouard  8911:  
1.201     brouard  8912:   strcpy(fileresf,"F_"); 
                   8913:   strcat(fileresf,fileresu);
1.126     brouard  8914:   if((ficresf=fopen(fileresf,"w"))==NULL) {
                   8915:     printf("Problem with forecast resultfile: %s\n", fileresf);
                   8916:     fprintf(ficlog,"Problem with forecast resultfile: %s\n", fileresf);
                   8917:   }
1.235     brouard  8918:   printf("\nComputing forecasting: result on file '%s', please wait... \n", fileresf);
                   8919:   fprintf(ficlog,"\nComputing forecasting: result on file '%s', please wait... \n", fileresf);
1.126     brouard  8920: 
1.225     brouard  8921:   if (cptcoveff==0) ncodemax[cptcoveff]=1;
1.126     brouard  8922: 
                   8923: 
                   8924:   stepsize=(int) (stepm+YEARM-1)/YEARM;
                   8925:   if (stepm<=12) stepsize=1;
                   8926:   if(estepm < stepm){
                   8927:     printf ("Problem %d lower than %d\n",estepm, stepm);
                   8928:   }
1.270     brouard  8929:   else{
                   8930:     hstepm=estepm;   
                   8931:   }
                   8932:   if(estepm > stepm){ /* Yes every two year */
                   8933:     stepsize=2;
                   8934:   }
1.296     brouard  8935:   hstepm=hstepm/stepm;
1.126     brouard  8936: 
1.296     brouard  8937:   
                   8938:   /* yp1=modf(dateintmean,&yp);/\* extracts integral of datemean in yp  and */
                   8939:   /*                              fractional in yp1 *\/ */
                   8940:   /* aintmean=yp; */
                   8941:   /* yp2=modf((yp1*12),&yp); */
                   8942:   /* mintmean=yp; */
                   8943:   /* yp1=modf((yp2*30.5),&yp); */
                   8944:   /* jintmean=yp; */
                   8945:   /* if(jintmean==0) jintmean=1; */
                   8946:   /* if(mintmean==0) mintmean=1; */
1.126     brouard  8947: 
1.296     brouard  8948: 
                   8949:   /* date2dmy(dateintmean,&jintmean,&mintmean,&aintmean); */
                   8950:   /* date2dmy(dateprojd,&jprojd, &mprojd, &anprojd); */
                   8951:   /* date2dmy(dateprojf,&jprojf, &mprojf, &anprojf); */
1.227     brouard  8952:   i1=pow(2,cptcoveff);
1.126     brouard  8953:   if (cptcovn < 1){i1=1;}
                   8954:   
1.296     brouard  8955:   fprintf(ficresf,"# Mean day of interviews %.lf/%.lf/%.lf (%.2f) between %.2f and %.2f \n",jintmean,mintmean,aintmean,dateintmean,dateprev1,dateprev2); 
1.126     brouard  8956:   
                   8957:   fprintf(ficresf,"#****** Routine prevforecast **\n");
1.227     brouard  8958:   
1.126     brouard  8959: /*           if (h==(int)(YEARM*yearp)){ */
1.235     brouard  8960:   for(nres=1; nres <= nresult; nres++) /* For each resultline */
                   8961:   for(k=1; k<=i1;k++){
1.253     brouard  8962:     if(i1 != 1 && TKresult[nres]!= k)
1.235     brouard  8963:       continue;
1.227     brouard  8964:     if(invalidvarcomb[k]){
                   8965:       printf("\nCombination (%d) projection ignored because no cases \n",k); 
                   8966:       continue;
                   8967:     }
                   8968:     fprintf(ficresf,"\n#****** hpijx=probability over h years, hp.jx is weighted by observed prev \n#");
                   8969:     for(j=1;j<=cptcoveff;j++) {
1.330   ! brouard  8970:       fprintf(ficresf," V%d (=) %d",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,Tvaraff[j])]);
1.227     brouard  8971:     }
1.235     brouard  8972:     for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
1.238     brouard  8973:       fprintf(ficresf," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
1.235     brouard  8974:     }
1.227     brouard  8975:     fprintf(ficresf," yearproj age");
                   8976:     for(j=1; j<=nlstate+ndeath;j++){ 
                   8977:       for(i=1; i<=nlstate;i++)               
                   8978:        fprintf(ficresf," p%d%d",i,j);
                   8979:       fprintf(ficresf," wp.%d",j);
                   8980:     }
1.296     brouard  8981:     for (yearp=0; yearp<=(anprojf-anprojd);yearp +=stepsize) {
1.227     brouard  8982:       fprintf(ficresf,"\n");
1.296     brouard  8983:       fprintf(ficresf,"\n# Forecasting at date %.lf/%.lf/%.lf ",jprojd,mprojd,anprojd+yearp);   
1.270     brouard  8984:       /* for (agec=fage; agec>=(ageminpar-1); agec--){  */
                   8985:       for (agec=fage; agec>=(bage); agec--){ 
1.227     brouard  8986:        nhstepm=(int) rint((agelim-agec)*YEARM/stepm); 
                   8987:        nhstepm = nhstepm/hstepm; 
                   8988:        p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   8989:        oldm=oldms;savm=savms;
1.268     brouard  8990:        /* We compute pii at age agec over nhstepm);*/
1.235     brouard  8991:        hpxij(p3mat,nhstepm,agec,hstepm,p,nlstate,stepm,oldm,savm, k,nres);
1.268     brouard  8992:        /* Then we print p3mat for h corresponding to the right agec+h*stepms=yearp */
1.227     brouard  8993:        for (h=0; h<=nhstepm; h++){
                   8994:          if (h*hstepm/YEARM*stepm ==yearp) {
1.268     brouard  8995:            break;
                   8996:          }
                   8997:        }
                   8998:        fprintf(ficresf,"\n");
                   8999:        for(j=1;j<=cptcoveff;j++) 
1.330   ! brouard  9000:          fprintf(ficresf,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,Tvaraff[j])]);
1.296     brouard  9001:        fprintf(ficresf,"%.f %.f ",anprojd+yearp,agec+h*hstepm/YEARM*stepm);
1.268     brouard  9002:        
                   9003:        for(j=1; j<=nlstate+ndeath;j++) {
                   9004:          ppij=0.;
                   9005:          for(i=1; i<=nlstate;i++) {
1.278     brouard  9006:            if (mobilav>=1)
                   9007:             ppij=ppij+p3mat[i][j][h]*prev[(int)agec][i][k];
                   9008:            else { /* even if mobilav==-1 we use mobaverage, probs may not sums to 1 */
                   9009:                ppij=ppij+p3mat[i][j][h]*probs[(int)(agec)][i][k];
                   9010:            }
1.268     brouard  9011:            fprintf(ficresf," %.3f", p3mat[i][j][h]);
                   9012:          } /* end i */
                   9013:          fprintf(ficresf," %.3f", ppij);
                   9014:        }/* end j */
1.227     brouard  9015:        free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   9016:       } /* end agec */
1.266     brouard  9017:       /* diffyear=(int) anproj1+yearp-ageminpar-1; */
                   9018:       /*printf("Prevforecast %d+%d-%d=diffyear=%d\n",(int) anproj1, (int)yearp,(int)ageminpar,(int) anproj1-(int)ageminpar);*/
1.227     brouard  9019:     } /* end yearp */
                   9020:   } /* end  k */
1.219     brouard  9021:        
1.126     brouard  9022:   fclose(ficresf);
1.215     brouard  9023:   printf("End of Computing forecasting \n");
                   9024:   fprintf(ficlog,"End of Computing forecasting\n");
                   9025: 
1.126     brouard  9026: }
                   9027: 
1.269     brouard  9028: /************** Back Forecasting ******************/
1.296     brouard  9029:  /* 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){ */
                   9030:  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){
                   9031:   /* back1, year, month, day of starting backprojection
1.267     brouard  9032:      agemin, agemax range of age
                   9033:      dateprev1 dateprev2 range of dates during which prevalence is computed
1.269     brouard  9034:      anback2 year of end of backprojection (same day and month as back1).
                   9035:      prevacurrent and prev are prevalences.
1.267     brouard  9036:   */
                   9037:   int yearp, stepsize, hstepm, nhstepm, j, k, cptcod, i, h, i1, k4, nres=0;
                   9038:   double agec; /* generic age */
1.302     brouard  9039:   double agelim, ppij, ppi, yp,yp1,yp2; /* ,jintmean,mintmean,aintmean;*/
1.267     brouard  9040:   double *popeffectif,*popcount;
                   9041:   double ***p3mat;
                   9042:   /* double ***mobaverage; */
                   9043:   char fileresfb[FILENAMELENGTH];
                   9044:  
1.268     brouard  9045:   agelim=AGEINF;
1.267     brouard  9046:   /* Compute observed prevalence between dateprev1 and dateprev2 by counting the number of people
                   9047:      in each health status at the date of interview (if between dateprev1 and dateprev2).
                   9048:      We still use firstpass and lastpass as another selection.
                   9049:   */
                   9050:   /* freqsummary(fileres, agemin, agemax, s, agev, nlstate, imx,Tvaraff,nbcode, ncodemax,mint,anint,strstart,\ */
                   9051:   /*         firstpass, lastpass,  stepm,  weightopt, model); */
                   9052: 
                   9053:   /*Do we need to compute prevalence again?*/
                   9054: 
                   9055:   /* prevalence(probs, ageminpar, agemax, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass); */
                   9056:   
                   9057:   strcpy(fileresfb,"FB_");
                   9058:   strcat(fileresfb,fileresu);
                   9059:   if((ficresfb=fopen(fileresfb,"w"))==NULL) {
                   9060:     printf("Problem with back forecast resultfile: %s\n", fileresfb);
                   9061:     fprintf(ficlog,"Problem with back forecast resultfile: %s\n", fileresfb);
                   9062:   }
                   9063:   printf("\nComputing back forecasting: result on file '%s', please wait... \n", fileresfb);
                   9064:   fprintf(ficlog,"\nComputing back forecasting: result on file '%s', please wait... \n", fileresfb);
                   9065:   
                   9066:   if (cptcoveff==0) ncodemax[cptcoveff]=1;
                   9067:   
                   9068:    
                   9069:   stepsize=(int) (stepm+YEARM-1)/YEARM;
                   9070:   if (stepm<=12) stepsize=1;
                   9071:   if(estepm < stepm){
                   9072:     printf ("Problem %d lower than %d\n",estepm, stepm);
                   9073:   }
1.270     brouard  9074:   else{
                   9075:     hstepm=estepm;   
                   9076:   }
                   9077:   if(estepm >= stepm){ /* Yes every two year */
                   9078:     stepsize=2;
                   9079:   }
1.267     brouard  9080:   
                   9081:   hstepm=hstepm/stepm;
1.296     brouard  9082:   /* yp1=modf(dateintmean,&yp);/\* extracts integral of datemean in yp  and */
                   9083:   /*                              fractional in yp1 *\/ */
                   9084:   /* aintmean=yp; */
                   9085:   /* yp2=modf((yp1*12),&yp); */
                   9086:   /* mintmean=yp; */
                   9087:   /* yp1=modf((yp2*30.5),&yp); */
                   9088:   /* jintmean=yp; */
                   9089:   /* if(jintmean==0) jintmean=1; */
                   9090:   /* if(mintmean==0) jintmean=1; */
1.267     brouard  9091:   
                   9092:   i1=pow(2,cptcoveff);
                   9093:   if (cptcovn < 1){i1=1;}
                   9094:   
1.296     brouard  9095:   fprintf(ficresfb,"# Mean day of interviews %.lf/%.lf/%.lf (%.2f) between %.2f and %.2f \n",jintmean,mintmean,aintmean,dateintmean,dateprev1,dateprev2);
                   9096:   printf("# Mean day of interviews %.lf/%.lf/%.lf (%.2f) between %.2f and %.2f \n",jintmean,mintmean,aintmean,dateintmean,dateprev1,dateprev2);
1.267     brouard  9097:   
                   9098:   fprintf(ficresfb,"#****** Routine prevbackforecast **\n");
                   9099:   
                   9100:   for(nres=1; nres <= nresult; nres++) /* For each resultline */
                   9101:   for(k=1; k<=i1;k++){
                   9102:     if(i1 != 1 && TKresult[nres]!= k)
                   9103:       continue;
                   9104:     if(invalidvarcomb[k]){
                   9105:       printf("\nCombination (%d) projection ignored because no cases \n",k); 
                   9106:       continue;
                   9107:     }
1.268     brouard  9108:     fprintf(ficresfb,"\n#****** hbijx=probability over h years, hb.jx is weighted by observed prev \n#");
1.267     brouard  9109:     for(j=1;j<=cptcoveff;j++) {
1.330   ! brouard  9110:       fprintf(ficresfb," V%d (=) %d",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,Tvaraff[j])]);
1.267     brouard  9111:     }
                   9112:     for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
                   9113:       fprintf(ficresf," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
                   9114:     }
                   9115:     fprintf(ficresfb," yearbproj age");
                   9116:     for(j=1; j<=nlstate+ndeath;j++){
                   9117:       for(i=1; i<=nlstate;i++)
1.268     brouard  9118:        fprintf(ficresfb," b%d%d",i,j);
                   9119:       fprintf(ficresfb," b.%d",j);
1.267     brouard  9120:     }
1.296     brouard  9121:     for (yearp=0; yearp>=(anbackf-anbackd);yearp -=stepsize) {
1.267     brouard  9122:       /* for (yearp=0; yearp<=(anproj2-anproj1);yearp +=stepsize) {  */
                   9123:       fprintf(ficresfb,"\n");
1.296     brouard  9124:       fprintf(ficresfb,"\n# Back Forecasting at date %.lf/%.lf/%.lf ",jbackd,mbackd,anbackd+yearp);
1.273     brouard  9125:       /* printf("\n# Back Forecasting at date %.lf/%.lf/%.lf ",jback1,mback1,anback1+yearp); */
1.270     brouard  9126:       /* for (agec=bage; agec<=agemax-1; agec++){  /\* testing *\/ */
                   9127:       for (agec=bage; agec<=fage; agec++){  /* testing */
1.268     brouard  9128:        /* We compute bij at age agec over nhstepm, nhstepm decreases when agec increases because of agemax;*/
1.271     brouard  9129:        nhstepm=(int) (agec-agelim) *YEARM/stepm;/*     nhstepm=(int) rint((agec-agelim)*YEARM/stepm);*/
1.267     brouard  9130:        nhstepm = nhstepm/hstepm;
                   9131:        p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   9132:        oldm=oldms;savm=savms;
1.268     brouard  9133:        /* computes hbxij at age agec over 1 to nhstepm */
1.271     brouard  9134:        /* printf("####prevbackforecast debug  agec=%.2f nhstepm=%d\n",agec, nhstepm);fflush(stdout); */
1.267     brouard  9135:        hbxij(p3mat,nhstepm,agec,hstepm,p,prevacurrent,nlstate,stepm, k, nres);
1.268     brouard  9136:        /* hpxij(p3mat,nhstepm,agec,hstepm,p,             nlstate,stepm,oldm,savm, k,nres); */
                   9137:        /* Then we print p3mat for h corresponding to the right agec+h*stepms=yearp */
                   9138:        /* printf(" agec=%.2f\n",agec);fflush(stdout); */
1.267     brouard  9139:        for (h=0; h<=nhstepm; h++){
1.268     brouard  9140:          if (h*hstepm/YEARM*stepm ==-yearp) {
                   9141:            break;
                   9142:          }
                   9143:        }
                   9144:        fprintf(ficresfb,"\n");
                   9145:        for(j=1;j<=cptcoveff;j++)
1.330   ! brouard  9146:          fprintf(ficresfb,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,Tvaraff[j])]);
1.296     brouard  9147:        fprintf(ficresfb,"%.f %.f ",anbackd+yearp,agec-h*hstepm/YEARM*stepm);
1.268     brouard  9148:        for(i=1; i<=nlstate+ndeath;i++) {
                   9149:          ppij=0.;ppi=0.;
                   9150:          for(j=1; j<=nlstate;j++) {
                   9151:            /* if (mobilav==1) */
1.269     brouard  9152:            ppij=ppij+p3mat[i][j][h]*prevacurrent[(int)agec][j][k];
                   9153:            ppi=ppi+prevacurrent[(int)agec][j][k];
                   9154:            /* ppij=ppij+p3mat[i][j][h]*mobaverage[(int)agec][j][k]; */
                   9155:            /* ppi=ppi+mobaverage[(int)agec][j][k]; */
1.267     brouard  9156:              /* else { */
                   9157:              /*        ppij=ppij+p3mat[i][j][h]*probs[(int)(agec)][i][k]; */
                   9158:              /* } */
1.268     brouard  9159:            fprintf(ficresfb," %.3f", p3mat[i][j][h]);
                   9160:          } /* end j */
                   9161:          if(ppi <0.99){
                   9162:            printf("Error in prevbackforecast, prevalence doesn't sum to 1 for state %d: %3f\n",i, ppi);
                   9163:            fprintf(ficlog,"Error in prevbackforecast, prevalence doesn't sum to 1 for state %d: %3f\n",i, ppi);
                   9164:          }
                   9165:          fprintf(ficresfb," %.3f", ppij);
                   9166:        }/* end j */
1.267     brouard  9167:        free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   9168:       } /* end agec */
                   9169:     } /* end yearp */
                   9170:   } /* end k */
1.217     brouard  9171:   
1.267     brouard  9172:   /* if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX); */
1.217     brouard  9173:   
1.267     brouard  9174:   fclose(ficresfb);
                   9175:   printf("End of Computing Back forecasting \n");
                   9176:   fprintf(ficlog,"End of Computing Back forecasting\n");
1.218     brouard  9177:        
1.267     brouard  9178: }
1.217     brouard  9179: 
1.269     brouard  9180: /* Variance of prevalence limit: varprlim */
                   9181:  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  9182:     /*------- Variance of forward period (stable) prevalence------*/   
1.269     brouard  9183:  
                   9184:    char fileresvpl[FILENAMELENGTH];  
                   9185:    FILE *ficresvpl;
                   9186:    double **oldm, **savm;
                   9187:    double **varpl; /* Variances of prevalence limits by age */   
                   9188:    int i1, k, nres, j ;
                   9189:    
                   9190:     strcpy(fileresvpl,"VPL_");
                   9191:     strcat(fileresvpl,fileresu);
                   9192:     if((ficresvpl=fopen(fileresvpl,"w"))==NULL) {
1.288     brouard  9193:       printf("Problem with variance of forward period (stable) prevalence  resultfile: %s\n", fileresvpl);
1.269     brouard  9194:       exit(0);
                   9195:     }
1.288     brouard  9196:     printf("Computing Variance-covariance of forward period (stable) prevalence: file '%s' ...", fileresvpl);fflush(stdout);
                   9197:     fprintf(ficlog, "Computing Variance-covariance of forward period (stable) prevalence: file '%s' ...", fileresvpl);fflush(ficlog);
1.269     brouard  9198:     
                   9199:     /*for(cptcov=1,k=0;cptcov<=i1;cptcov++){
                   9200:       for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*/
                   9201:     
                   9202:     i1=pow(2,cptcoveff);
                   9203:     if (cptcovn < 1){i1=1;}
                   9204: 
                   9205:     for(nres=1; nres <= nresult; nres++) /* For each resultline */
                   9206:     for(k=1; k<=i1;k++){
                   9207:       if(i1 != 1 && TKresult[nres]!= k)
                   9208:        continue;
                   9209:       fprintf(ficresvpl,"\n#****** ");
                   9210:       printf("\n#****** ");
                   9211:       fprintf(ficlog,"\n#****** ");
                   9212:       for(j=1;j<=cptcoveff;j++) {
1.330   ! brouard  9213:        fprintf(ficresvpl,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,Tvaraff[j])]);
        !          9214:        fprintf(ficlog,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,Tvaraff[j])]);
        !          9215:        printf("V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,Tvaraff[j])]);
1.269     brouard  9216:       }
                   9217:       for (j=1; j<= nsq; j++){ /* For each selected (single) quantitative value */
                   9218:        printf(" V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]);
                   9219:        fprintf(ficresvpl," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]);
                   9220:        fprintf(ficlog," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]);
                   9221:       }        
                   9222:       fprintf(ficresvpl,"******\n");
                   9223:       printf("******\n");
                   9224:       fprintf(ficlog,"******\n");
                   9225:       
                   9226:       varpl=matrix(1,nlstate,(int) bage, (int) fage);
                   9227:       oldm=oldms;savm=savms;
                   9228:       varprevlim(fileresvpl, ficresvpl, varpl, matcov, p, delti, nlstate, stepm, (int) bage, (int) fage, oldm, savm, prlim, ftolpl, ncvyearp, k, strstart, nres);
                   9229:       free_matrix(varpl,1,nlstate,(int) bage, (int)fage);
                   9230:       /*}*/
                   9231:     }
                   9232:     
                   9233:     fclose(ficresvpl);
1.288     brouard  9234:     printf("done variance-covariance of forward period prevalence\n");fflush(stdout);
                   9235:     fprintf(ficlog,"done variance-covariance of forward period prevalence\n");fflush(ficlog);
1.269     brouard  9236: 
                   9237:  }
                   9238: /* Variance of back prevalence: varbprlim */
                   9239:  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){
                   9240:       /*------- Variance of back (stable) prevalence------*/
                   9241: 
                   9242:    char fileresvbl[FILENAMELENGTH];  
                   9243:    FILE  *ficresvbl;
                   9244: 
                   9245:    double **oldm, **savm;
                   9246:    double **varbpl; /* Variances of back prevalence limits by age */   
                   9247:    int i1, k, nres, j ;
                   9248: 
                   9249:    strcpy(fileresvbl,"VBL_");
                   9250:    strcat(fileresvbl,fileresu);
                   9251:    if((ficresvbl=fopen(fileresvbl,"w"))==NULL) {
                   9252:      printf("Problem with variance of back (stable) prevalence  resultfile: %s\n", fileresvbl);
                   9253:      exit(0);
                   9254:    }
                   9255:    printf("Computing Variance-covariance of back (stable) prevalence: file '%s' ...", fileresvbl);fflush(stdout);
                   9256:    fprintf(ficlog, "Computing Variance-covariance of back (stable) prevalence: file '%s' ...", fileresvbl);fflush(ficlog);
                   9257:    
                   9258:    
                   9259:    i1=pow(2,cptcoveff);
                   9260:    if (cptcovn < 1){i1=1;}
                   9261:    
                   9262:    for(nres=1; nres <= nresult; nres++) /* For each resultline */
                   9263:      for(k=1; k<=i1;k++){
                   9264:        if(i1 != 1 && TKresult[nres]!= k)
                   9265:         continue;
                   9266:        fprintf(ficresvbl,"\n#****** ");
                   9267:        printf("\n#****** ");
                   9268:        fprintf(ficlog,"\n#****** ");
                   9269:        for(j=1;j<=cptcoveff;j++) {
1.330   ! brouard  9270:         fprintf(ficresvbl,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,Tvaraff[j])]);
        !          9271:         fprintf(ficlog,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,Tvaraff[j])]);
        !          9272:         printf("V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,Tvaraff[j])]);
1.269     brouard  9273:        }
                   9274:        for (j=1; j<= nsq; j++){ /* For each selected (single) quantitative value */
                   9275:         printf(" V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]);
                   9276:         fprintf(ficresvbl," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]);
                   9277:         fprintf(ficlog," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]);
                   9278:        }
                   9279:        fprintf(ficresvbl,"******\n");
                   9280:        printf("******\n");
                   9281:        fprintf(ficlog,"******\n");
                   9282:        
                   9283:        varbpl=matrix(1,nlstate,(int) bage, (int) fage);
                   9284:        oldm=oldms;savm=savms;
                   9285:        
                   9286:        varbrevlim(fileresvbl, ficresvbl, varbpl, matcov, p, delti, nlstate, stepm, (int) bage, (int) fage, oldm, savm, bprlim, ftolpl, mobilavproj, ncvyearp, k, strstart, nres);
                   9287:        free_matrix(varbpl,1,nlstate,(int) bage, (int)fage);
                   9288:        /*}*/
                   9289:      }
                   9290:    
                   9291:    fclose(ficresvbl);
                   9292:    printf("done variance-covariance of back prevalence\n");fflush(stdout);
                   9293:    fprintf(ficlog,"done variance-covariance of back prevalence\n");fflush(ficlog);
                   9294: 
                   9295:  } /* End of varbprlim */
                   9296: 
1.126     brouard  9297: /************** Forecasting *****not tested NB*************/
1.227     brouard  9298: /* 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  9299:   
1.227     brouard  9300: /*   int cpt, stepsize, hstepm, nhstepm, j,k,c, cptcod, i,h; */
                   9301: /*   int *popage; */
                   9302: /*   double calagedatem, agelim, kk1, kk2; */
                   9303: /*   double *popeffectif,*popcount; */
                   9304: /*   double ***p3mat,***tabpop,***tabpopprev; */
                   9305: /*   /\* double ***mobaverage; *\/ */
                   9306: /*   char filerespop[FILENAMELENGTH]; */
1.126     brouard  9307: 
1.227     brouard  9308: /*   tabpop= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX); */
                   9309: /*   tabpopprev= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX); */
                   9310: /*   agelim=AGESUP; */
                   9311: /*   calagedatem=(anpyram+mpyram/12.+jpyram/365.-dateintmean)*YEARM; */
1.126     brouard  9312:   
1.227     brouard  9313: /*   prevalence(probs, ageminpar, agemax, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass); */
1.126     brouard  9314:   
                   9315:   
1.227     brouard  9316: /*   strcpy(filerespop,"POP_");  */
                   9317: /*   strcat(filerespop,fileresu); */
                   9318: /*   if((ficrespop=fopen(filerespop,"w"))==NULL) { */
                   9319: /*     printf("Problem with forecast resultfile: %s\n", filerespop); */
                   9320: /*     fprintf(ficlog,"Problem with forecast resultfile: %s\n", filerespop); */
                   9321: /*   } */
                   9322: /*   printf("Computing forecasting: result on file '%s' \n", filerespop); */
                   9323: /*   fprintf(ficlog,"Computing forecasting: result on file '%s' \n", filerespop); */
1.126     brouard  9324: 
1.227     brouard  9325: /*   if (cptcoveff==0) ncodemax[cptcoveff]=1; */
1.126     brouard  9326: 
1.227     brouard  9327: /*   /\* if (mobilav!=0) { *\/ */
                   9328: /*   /\*   mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX); *\/ */
                   9329: /*   /\*   if (movingaverage(probs, ageminpar, fage, mobaverage,mobilav)!=0){ *\/ */
                   9330: /*   /\*     fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav); *\/ */
                   9331: /*   /\*     printf(" Error in movingaverage mobilav=%d\n",mobilav); *\/ */
                   9332: /*   /\*   } *\/ */
                   9333: /*   /\* } *\/ */
1.126     brouard  9334: 
1.227     brouard  9335: /*   stepsize=(int) (stepm+YEARM-1)/YEARM; */
                   9336: /*   if (stepm<=12) stepsize=1; */
1.126     brouard  9337:   
1.227     brouard  9338: /*   agelim=AGESUP; */
1.126     brouard  9339:   
1.227     brouard  9340: /*   hstepm=1; */
                   9341: /*   hstepm=hstepm/stepm;  */
1.218     brouard  9342:        
1.227     brouard  9343: /*   if (popforecast==1) { */
                   9344: /*     if((ficpop=fopen(popfile,"r"))==NULL) { */
                   9345: /*       printf("Problem with population file : %s\n",popfile);exit(0); */
                   9346: /*       fprintf(ficlog,"Problem with population file : %s\n",popfile);exit(0); */
                   9347: /*     }  */
                   9348: /*     popage=ivector(0,AGESUP); */
                   9349: /*     popeffectif=vector(0,AGESUP); */
                   9350: /*     popcount=vector(0,AGESUP); */
1.126     brouard  9351:     
1.227     brouard  9352: /*     i=1;    */
                   9353: /*     while ((c=fscanf(ficpop,"%d %lf\n",&popage[i],&popcount[i])) != EOF) i=i+1; */
1.218     brouard  9354:     
1.227     brouard  9355: /*     imx=i; */
                   9356: /*     for (i=1; i<imx;i++) popeffectif[popage[i]]=popcount[i]; */
                   9357: /*   } */
1.218     brouard  9358:   
1.227     brouard  9359: /*   for(cptcov=1,k=0;cptcov<=i2;cptcov++){ */
                   9360: /*     for(cptcod=1;cptcod<=ncodemax[cptcoveff];cptcod++){ */
                   9361: /*       k=k+1; */
                   9362: /*       fprintf(ficrespop,"\n#******"); */
                   9363: /*       for(j=1;j<=cptcoveff;j++) { */
                   9364: /*     fprintf(ficrespop," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]); */
                   9365: /*       } */
                   9366: /*       fprintf(ficrespop,"******\n"); */
                   9367: /*       fprintf(ficrespop,"# Age"); */
                   9368: /*       for(j=1; j<=nlstate+ndeath;j++) fprintf(ficrespop," P.%d",j); */
                   9369: /*       if (popforecast==1)  fprintf(ficrespop," [Population]"); */
1.126     brouard  9370:       
1.227     brouard  9371: /*       for (cpt=0; cpt<=0;cpt++) {  */
                   9372: /*     fprintf(ficrespop,"\n\n# Forecasting at date %.lf/%.lf/%.lf ",jpyram,mpyram,anpyram+cpt);    */
1.126     brouard  9373:        
1.227     brouard  9374: /*     for (agedeb=(fage-((int)calagedatem %12/12.)); agedeb>=(ageminpar-((int)calagedatem %12)/12.); agedeb--){  */
                   9375: /*       nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm);  */
                   9376: /*       nhstepm = nhstepm/hstepm;  */
1.126     brouard  9377:          
1.227     brouard  9378: /*       p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm); */
                   9379: /*       oldm=oldms;savm=savms; */
                   9380: /*       hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);   */
1.218     brouard  9381:          
1.227     brouard  9382: /*       for (h=0; h<=nhstepm; h++){ */
                   9383: /*         if (h==(int) (calagedatem+YEARM*cpt)) { */
                   9384: /*           fprintf(ficrespop,"\n %3.f ",agedeb+h*hstepm/YEARM*stepm); */
                   9385: /*         }  */
                   9386: /*         for(j=1; j<=nlstate+ndeath;j++) { */
                   9387: /*           kk1=0.;kk2=0; */
                   9388: /*           for(i=1; i<=nlstate;i++) {               */
                   9389: /*             if (mobilav==1)  */
                   9390: /*               kk1=kk1+p3mat[i][j][h]*mobaverage[(int)agedeb+1][i][cptcod]; */
                   9391: /*             else { */
                   9392: /*               kk1=kk1+p3mat[i][j][h]*probs[(int)(agedeb+1)][i][cptcod]; */
                   9393: /*             } */
                   9394: /*           } */
                   9395: /*           if (h==(int)(calagedatem+12*cpt)){ */
                   9396: /*             tabpop[(int)(agedeb)][j][cptcod]=kk1; */
                   9397: /*             /\*fprintf(ficrespop," %.3f", kk1); */
                   9398: /*               if (popforecast==1) fprintf(ficrespop," [%.f]", kk1*popeffectif[(int)agedeb+1]);*\/ */
                   9399: /*           } */
                   9400: /*         } */
                   9401: /*         for(i=1; i<=nlstate;i++){ */
                   9402: /*           kk1=0.; */
                   9403: /*           for(j=1; j<=nlstate;j++){ */
                   9404: /*             kk1= kk1+tabpop[(int)(agedeb)][j][cptcod];  */
                   9405: /*           } */
                   9406: /*           tabpopprev[(int)(agedeb)][i][cptcod]=tabpop[(int)(agedeb)][i][cptcod]/kk1*popeffectif[(int)(agedeb+(calagedatem+12*cpt)*hstepm/YEARM*stepm-1)]; */
                   9407: /*         } */
1.218     brouard  9408:            
1.227     brouard  9409: /*         if (h==(int)(calagedatem+12*cpt)) */
                   9410: /*           for(j=1; j<=nlstate;j++)  */
                   9411: /*             fprintf(ficrespop," %15.2f",tabpopprev[(int)(agedeb+1)][j][cptcod]); */
                   9412: /*       } */
                   9413: /*       free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm); */
                   9414: /*     } */
                   9415: /*       } */
1.218     brouard  9416:       
1.227     brouard  9417: /*       /\******\/ */
1.218     brouard  9418:       
1.227     brouard  9419: /*       for (cpt=1; cpt<=(anpyram1-anpyram);cpt++) {  */
                   9420: /*     fprintf(ficrespop,"\n\n# Forecasting at date %.lf/%.lf/%.lf ",jpyram,mpyram,anpyram+cpt);    */
                   9421: /*     for (agedeb=(fage-((int)calagedatem %12/12.)); agedeb>=(ageminpar-((int)calagedatem %12)/12.); agedeb--){  */
                   9422: /*       nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm);  */
                   9423: /*       nhstepm = nhstepm/hstepm;  */
1.126     brouard  9424:          
1.227     brouard  9425: /*       p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm); */
                   9426: /*       oldm=oldms;savm=savms; */
                   9427: /*       hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);   */
                   9428: /*       for (h=0; h<=nhstepm; h++){ */
                   9429: /*         if (h==(int) (calagedatem+YEARM*cpt)) { */
                   9430: /*           fprintf(ficresf,"\n %3.f ",agedeb+h*hstepm/YEARM*stepm); */
                   9431: /*         }  */
                   9432: /*         for(j=1; j<=nlstate+ndeath;j++) { */
                   9433: /*           kk1=0.;kk2=0; */
                   9434: /*           for(i=1; i<=nlstate;i++) {               */
                   9435: /*             kk1=kk1+p3mat[i][j][h]*tabpopprev[(int)agedeb+1][i][cptcod];     */
                   9436: /*           } */
                   9437: /*           if (h==(int)(calagedatem+12*cpt)) fprintf(ficresf," %15.2f", kk1);         */
                   9438: /*         } */
                   9439: /*       } */
                   9440: /*       free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm); */
                   9441: /*     } */
                   9442: /*       } */
                   9443: /*     }  */
                   9444: /*   } */
1.218     brouard  9445:   
1.227     brouard  9446: /*   /\* if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX); *\/ */
1.218     brouard  9447:   
1.227     brouard  9448: /*   if (popforecast==1) { */
                   9449: /*     free_ivector(popage,0,AGESUP); */
                   9450: /*     free_vector(popeffectif,0,AGESUP); */
                   9451: /*     free_vector(popcount,0,AGESUP); */
                   9452: /*   } */
                   9453: /*   free_ma3x(tabpop,1, AGESUP,1,NCOVMAX, 1,NCOVMAX); */
                   9454: /*   free_ma3x(tabpopprev,1, AGESUP,1,NCOVMAX, 1,NCOVMAX); */
                   9455: /*   fclose(ficrespop); */
                   9456: /* } /\* End of popforecast *\/ */
1.218     brouard  9457:  
1.126     brouard  9458: int fileappend(FILE *fichier, char *optionfich)
                   9459: {
                   9460:   if((fichier=fopen(optionfich,"a"))==NULL) {
                   9461:     printf("Problem with file: %s\n", optionfich);
                   9462:     fprintf(ficlog,"Problem with file: %s\n", optionfich);
                   9463:     return (0);
                   9464:   }
                   9465:   fflush(fichier);
                   9466:   return (1);
                   9467: }
                   9468: 
                   9469: 
                   9470: /**************** function prwizard **********************/
                   9471: void prwizard(int ncovmodel, int nlstate, int ndeath,  char model[], FILE *ficparo)
                   9472: {
                   9473: 
                   9474:   /* Wizard to print covariance matrix template */
                   9475: 
1.164     brouard  9476:   char ca[32], cb[32];
                   9477:   int i,j, k, li, lj, lk, ll, jj, npar, itimes;
1.126     brouard  9478:   int numlinepar;
                   9479: 
                   9480:   printf("# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
                   9481:   fprintf(ficparo,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
                   9482:   for(i=1; i <=nlstate; i++){
                   9483:     jj=0;
                   9484:     for(j=1; j <=nlstate+ndeath; j++){
                   9485:       if(j==i) continue;
                   9486:       jj++;
                   9487:       /*ca[0]= k+'a'-1;ca[1]='\0';*/
                   9488:       printf("%1d%1d",i,j);
                   9489:       fprintf(ficparo,"%1d%1d",i,j);
                   9490:       for(k=1; k<=ncovmodel;k++){
                   9491:        /*        printf(" %lf",param[i][j][k]); */
                   9492:        /*        fprintf(ficparo," %lf",param[i][j][k]); */
                   9493:        printf(" 0.");
                   9494:        fprintf(ficparo," 0.");
                   9495:       }
                   9496:       printf("\n");
                   9497:       fprintf(ficparo,"\n");
                   9498:     }
                   9499:   }
                   9500:   printf("# Scales (for hessian or gradient estimation)\n");
                   9501:   fprintf(ficparo,"# Scales (for hessian or gradient estimation)\n");
                   9502:   npar= (nlstate+ndeath-1)*nlstate*ncovmodel; /* Number of parameters*/ 
                   9503:   for(i=1; i <=nlstate; i++){
                   9504:     jj=0;
                   9505:     for(j=1; j <=nlstate+ndeath; j++){
                   9506:       if(j==i) continue;
                   9507:       jj++;
                   9508:       fprintf(ficparo,"%1d%1d",i,j);
                   9509:       printf("%1d%1d",i,j);
                   9510:       fflush(stdout);
                   9511:       for(k=1; k<=ncovmodel;k++){
                   9512:        /*      printf(" %le",delti3[i][j][k]); */
                   9513:        /*      fprintf(ficparo," %le",delti3[i][j][k]); */
                   9514:        printf(" 0.");
                   9515:        fprintf(ficparo," 0.");
                   9516:       }
                   9517:       numlinepar++;
                   9518:       printf("\n");
                   9519:       fprintf(ficparo,"\n");
                   9520:     }
                   9521:   }
                   9522:   printf("# Covariance matrix\n");
                   9523: /* # 121 Var(a12)\n\ */
                   9524: /* # 122 Cov(b12,a12) Var(b12)\n\ */
                   9525: /* # 131 Cov(a13,a12) Cov(a13,b12, Var(a13)\n\ */
                   9526: /* # 132 Cov(b13,a12) Cov(b13,b12, Cov(b13,a13) Var(b13)\n\ */
                   9527: /* # 212 Cov(a21,a12) Cov(a21,b12, Cov(a21,a13) Cov(a21,b13) Var(a21)\n\ */
                   9528: /* # 212 Cov(b21,a12) Cov(b21,b12, Cov(b21,a13) Cov(b21,b13) Cov(b21,a21) Var(b21)\n\ */
                   9529: /* # 232 Cov(a23,a12) Cov(a23,b12, Cov(a23,a13) Cov(a23,b13) Cov(a23,a21) Cov(a23,b21) Var(a23)\n\ */
                   9530: /* # 232 Cov(b23,a12) Cov(b23,b12) ... Var (b23)\n" */
                   9531:   fflush(stdout);
                   9532:   fprintf(ficparo,"# Covariance matrix\n");
                   9533:   /* # 121 Var(a12)\n\ */
                   9534:   /* # 122 Cov(b12,a12) Var(b12)\n\ */
                   9535:   /* #   ...\n\ */
                   9536:   /* # 232 Cov(b23,a12)  Cov(b23,b12) ... Var (b23)\n" */
                   9537:   
                   9538:   for(itimes=1;itimes<=2;itimes++){
                   9539:     jj=0;
                   9540:     for(i=1; i <=nlstate; i++){
                   9541:       for(j=1; j <=nlstate+ndeath; j++){
                   9542:        if(j==i) continue;
                   9543:        for(k=1; k<=ncovmodel;k++){
                   9544:          jj++;
                   9545:          ca[0]= k+'a'-1;ca[1]='\0';
                   9546:          if(itimes==1){
                   9547:            printf("#%1d%1d%d",i,j,k);
                   9548:            fprintf(ficparo,"#%1d%1d%d",i,j,k);
                   9549:          }else{
                   9550:            printf("%1d%1d%d",i,j,k);
                   9551:            fprintf(ficparo,"%1d%1d%d",i,j,k);
                   9552:            /*  printf(" %.5le",matcov[i][j]); */
                   9553:          }
                   9554:          ll=0;
                   9555:          for(li=1;li <=nlstate; li++){
                   9556:            for(lj=1;lj <=nlstate+ndeath; lj++){
                   9557:              if(lj==li) continue;
                   9558:              for(lk=1;lk<=ncovmodel;lk++){
                   9559:                ll++;
                   9560:                if(ll<=jj){
                   9561:                  cb[0]= lk +'a'-1;cb[1]='\0';
                   9562:                  if(ll<jj){
                   9563:                    if(itimes==1){
                   9564:                      printf(" Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
                   9565:                      fprintf(ficparo," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
                   9566:                    }else{
                   9567:                      printf(" 0.");
                   9568:                      fprintf(ficparo," 0.");
                   9569:                    }
                   9570:                  }else{
                   9571:                    if(itimes==1){
                   9572:                      printf(" Var(%s%1d%1d)",ca,i,j);
                   9573:                      fprintf(ficparo," Var(%s%1d%1d)",ca,i,j);
                   9574:                    }else{
                   9575:                      printf(" 0.");
                   9576:                      fprintf(ficparo," 0.");
                   9577:                    }
                   9578:                  }
                   9579:                }
                   9580:              } /* end lk */
                   9581:            } /* end lj */
                   9582:          } /* end li */
                   9583:          printf("\n");
                   9584:          fprintf(ficparo,"\n");
                   9585:          numlinepar++;
                   9586:        } /* end k*/
                   9587:       } /*end j */
                   9588:     } /* end i */
                   9589:   } /* end itimes */
                   9590: 
                   9591: } /* end of prwizard */
                   9592: /******************* Gompertz Likelihood ******************************/
                   9593: double gompertz(double x[])
                   9594: { 
1.302     brouard  9595:   double A=0.0,B=0.,L=0.0,sump=0.,num=0.;
1.126     brouard  9596:   int i,n=0; /* n is the size of the sample */
                   9597: 
1.220     brouard  9598:   for (i=1;i<=imx ; i++) {
1.126     brouard  9599:     sump=sump+weight[i];
                   9600:     /*    sump=sump+1;*/
                   9601:     num=num+1;
                   9602:   }
1.302     brouard  9603:   L=0.0;
                   9604:   /* agegomp=AGEGOMP; */
1.126     brouard  9605:   /* for (i=0; i<=imx; i++) 
                   9606:      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]);*/
                   9607: 
1.302     brouard  9608:   for (i=1;i<=imx ; i++) {
                   9609:     /* mu(a)=mu(agecomp)*exp(teta*(age-agegomp))
                   9610:        mu(a)=x[1]*exp(x[2]*(age-agegomp)); x[1] and x[2] are per year.
                   9611:      * L= Product mu(agedeces)exp(-\int_ageexam^agedc mu(u) du ) for a death between agedc (in month) 
                   9612:      *   and agedc +1 month, cens[i]=0: log(x[1]/YEARM)
                   9613:      * +
                   9614:      * exp(-\int_ageexam^agecens mu(u) du ) when censored, cens[i]=1
                   9615:      */
                   9616:      if (wav[i] > 1 || agedc[i] < AGESUP) {
                   9617:        if (cens[i] == 1){
                   9618:         A=-x[1]/(x[2])*(exp(x[2]*(agecens[i]-agegomp))-exp(x[2]*(ageexmed[i]-agegomp)));
                   9619:        } else if (cens[i] == 0){
1.126     brouard  9620:        A=-x[1]/(x[2])*(exp(x[2]*(agedc[i]-agegomp))-exp(x[2]*(ageexmed[i]-agegomp)))
1.302     brouard  9621:          +log(x[1]/YEARM) +x[2]*(agedc[i]-agegomp)+log(YEARM);
                   9622:       } else
                   9623:         printf("Gompertz cens[%d] neither 1 nor 0\n",i);
1.126     brouard  9624:       /*if (wav[i] > 1 && agecens[i] > 15) {*/ /* ??? */
1.302     brouard  9625:        L=L+A*weight[i];
1.126     brouard  9626:        /*      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  9627:      }
                   9628:   }
1.126     brouard  9629: 
1.302     brouard  9630:   /*printf("x1=%2.9f x2=%2.9f x3=%2.9f L=%f\n",x[1],x[2],x[3],L);*/
1.126     brouard  9631:  
                   9632:   return -2*L*num/sump;
                   9633: }
                   9634: 
1.136     brouard  9635: #ifdef GSL
                   9636: /******************* Gompertz_f Likelihood ******************************/
                   9637: double gompertz_f(const gsl_vector *v, void *params)
                   9638: { 
1.302     brouard  9639:   double A=0.,B=0.,LL=0.0,sump=0.,num=0.;
1.136     brouard  9640:   double *x= (double *) v->data;
                   9641:   int i,n=0; /* n is the size of the sample */
                   9642: 
                   9643:   for (i=0;i<=imx-1 ; i++) {
                   9644:     sump=sump+weight[i];
                   9645:     /*    sump=sump+1;*/
                   9646:     num=num+1;
                   9647:   }
                   9648:  
                   9649:  
                   9650:   /* for (i=0; i<=imx; i++) 
                   9651:      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]);*/
                   9652:   printf("x[0]=%lf x[1]=%lf\n",x[0],x[1]);
                   9653:   for (i=1;i<=imx ; i++)
                   9654:     {
                   9655:       if (cens[i] == 1 && wav[i]>1)
                   9656:        A=-x[0]/(x[1])*(exp(x[1]*(agecens[i]-agegomp))-exp(x[1]*(ageexmed[i]-agegomp)));
                   9657:       
                   9658:       if (cens[i] == 0 && wav[i]>1)
                   9659:        A=-x[0]/(x[1])*(exp(x[1]*(agedc[i]-agegomp))-exp(x[1]*(ageexmed[i]-agegomp)))
                   9660:             +log(x[0]/YEARM)+x[1]*(agedc[i]-agegomp)+log(YEARM);  
                   9661:       
                   9662:       /*if (wav[i] > 1 && agecens[i] > 15) {*/ /* ??? */
                   9663:       if (wav[i] > 1 ) { /* ??? */
                   9664:        LL=LL+A*weight[i];
                   9665:        /*      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]);*/
                   9666:       }
                   9667:     }
                   9668: 
                   9669:  /*printf("x1=%2.9f x2=%2.9f x3=%2.9f L=%f\n",x[1],x[2],x[3],L);*/
                   9670:   printf("x[0]=%lf x[1]=%lf -2*LL*num/sump=%lf\n",x[0],x[1],-2*LL*num/sump);
                   9671:  
                   9672:   return -2*LL*num/sump;
                   9673: }
                   9674: #endif
                   9675: 
1.126     brouard  9676: /******************* Printing html file ***********/
1.201     brouard  9677: void printinghtmlmort(char fileresu[], char title[], char datafile[], int firstpass, \
1.126     brouard  9678:                  int lastpass, int stepm, int weightopt, char model[],\
                   9679:                  int imx,  double p[],double **matcov,double agemortsup){
                   9680:   int i,k;
                   9681: 
                   9682:   fprintf(fichtm,"<ul><li><h4>Result files </h4>\n Force of mortality. Parameters of the Gompertz fit (with confidence interval in brackets):<br>");
                   9683:   fprintf(fichtm,"  mu(age) =%lf*exp(%lf*(age-%d)) per year<br><br>",p[1],p[2],agegomp);
                   9684:   for (i=1;i<=2;i++) 
                   9685:     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  9686:   fprintf(fichtm,"<br><br><img src=\"graphmort.svg\">");
1.126     brouard  9687:   fprintf(fichtm,"</ul>");
                   9688: 
                   9689: fprintf(fichtm,"<ul><li><h4>Life table</h4>\n <br>");
                   9690: 
                   9691:  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>");
                   9692: 
                   9693:  for (k=agegomp;k<(agemortsup-2);k++) 
                   9694:    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]);
                   9695: 
                   9696:  
                   9697:   fflush(fichtm);
                   9698: }
                   9699: 
                   9700: /******************* Gnuplot file **************/
1.201     brouard  9701: void printinggnuplotmort(char fileresu[], char optionfilefiname[], double ageminpar, double agemaxpar, double fage , char pathc[], double p[]){
1.126     brouard  9702: 
                   9703:   char dirfileres[132],optfileres[132];
1.164     brouard  9704: 
1.126     brouard  9705:   int ng;
                   9706: 
                   9707: 
                   9708:   /*#ifdef windows */
                   9709:   fprintf(ficgp,"cd \"%s\" \n",pathc);
                   9710:     /*#endif */
                   9711: 
                   9712: 
                   9713:   strcpy(dirfileres,optionfilefiname);
                   9714:   strcpy(optfileres,"vpl");
1.199     brouard  9715:   fprintf(ficgp,"set out \"graphmort.svg\"\n "); 
1.126     brouard  9716:   fprintf(ficgp,"set xlabel \"Age\"\n set ylabel \"Force of mortality (per year)\" \n "); 
1.199     brouard  9717:   fprintf(ficgp, "set ter svg size 640, 480\n set log y\n"); 
1.145     brouard  9718:   /* fprintf(ficgp, "set size 0.65,0.65\n"); */
1.126     brouard  9719:   fprintf(ficgp,"plot [%d:100] %lf*exp(%lf*(x-%d))",agegomp,p[1],p[2],agegomp);
                   9720: 
                   9721: } 
                   9722: 
1.136     brouard  9723: int readdata(char datafile[], int firstobs, int lastobs, int *imax)
                   9724: {
1.126     brouard  9725: 
1.136     brouard  9726:   /*-------- data file ----------*/
                   9727:   FILE *fic;
                   9728:   char dummy[]="                         ";
1.240     brouard  9729:   int i=0, j=0, n=0, iv=0, v;
1.223     brouard  9730:   int lstra;
1.136     brouard  9731:   int linei, month, year,iout;
1.302     brouard  9732:   int noffset=0; /* This is the offset if BOM data file */
1.136     brouard  9733:   char line[MAXLINE], linetmp[MAXLINE];
1.164     brouard  9734:   char stra[MAXLINE], strb[MAXLINE];
1.136     brouard  9735:   char *stratrunc;
1.223     brouard  9736: 
1.240     brouard  9737:   DummyV=ivector(1,NCOVMAX); /* 1 to 3 */
                   9738:   FixedV=ivector(1,NCOVMAX); /* 1 to 3 */
1.328     brouard  9739:   for(v=1;v<NCOVMAX;v++){
                   9740:     DummyV[v]=0;
                   9741:     FixedV[v]=0;
                   9742:   }
1.126     brouard  9743: 
1.240     brouard  9744:   for(v=1; v <=ncovcol;v++){
                   9745:     DummyV[v]=0;
                   9746:     FixedV[v]=0;
                   9747:   }
                   9748:   for(v=ncovcol+1; v <=ncovcol+nqv;v++){
                   9749:     DummyV[v]=1;
                   9750:     FixedV[v]=0;
                   9751:   }
                   9752:   for(v=ncovcol+nqv+1; v <=ncovcol+nqv+ntv;v++){
                   9753:     DummyV[v]=0;
                   9754:     FixedV[v]=1;
                   9755:   }
                   9756:   for(v=ncovcol+nqv+ntv+1; v <=ncovcol+nqv+ntv+nqtv;v++){
                   9757:     DummyV[v]=1;
                   9758:     FixedV[v]=1;
                   9759:   }
                   9760:   for(v=1; v <=ncovcol+nqv+ntv+nqtv;v++){
                   9761:     printf("Covariate type in the data: V%d, DummyV(V%d)=%d, FixedV(V%d)=%d\n",v,v,DummyV[v],v,FixedV[v]);
                   9762:     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]);
                   9763:   }
1.126     brouard  9764: 
1.136     brouard  9765:   if((fic=fopen(datafile,"r"))==NULL)    {
1.218     brouard  9766:     printf("Problem while opening datafile: %s with errno='%s'\n", datafile,strerror(errno));fflush(stdout);
                   9767:     fprintf(ficlog,"Problem while opening datafile: %s with errno='%s'\n", datafile,strerror(errno));fflush(ficlog);return 1;
1.136     brouard  9768:   }
1.126     brouard  9769: 
1.302     brouard  9770:     /* Is it a BOM UTF-8 Windows file? */
                   9771:   /* First data line */
                   9772:   linei=0;
                   9773:   while(fgets(line, MAXLINE, fic)) {
                   9774:     noffset=0;
                   9775:     if( line[0] == (char)0xEF && line[1] == (char)0xBB) /* EF BB BF */
                   9776:     {
                   9777:       noffset=noffset+3;
                   9778:       printf("# Data file '%s'  is an UTF8 BOM file, please convert to UTF8 or ascii file and rerun.\n",datafile);fflush(stdout);
                   9779:       fprintf(ficlog,"# Data file '%s'  is an UTF8 BOM file, please convert to UTF8 or ascii file and rerun.\n",datafile);
                   9780:       fflush(ficlog); return 1;
                   9781:     }
                   9782:     /*    else if( line[0] == (char)0xFE && line[1] == (char)0xFF)*/
                   9783:     else if( line[0] == (char)0xFF && line[1] == (char)0xFE)
                   9784:     {
                   9785:       noffset=noffset+2;
1.304     brouard  9786:       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);
                   9787:       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  9788:       fflush(ficlog); return 1;
                   9789:     }
                   9790:     else if( line[0] == 0 && line[1] == 0)
                   9791:     {
                   9792:       if( line[2] == (char)0xFE && line[3] == (char)0xFF){
                   9793:        noffset=noffset+4;
1.304     brouard  9794:        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);
                   9795:        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  9796:        fflush(ficlog); return 1;
                   9797:       }
                   9798:     } else{
                   9799:       ;/*printf(" Not a BOM file\n");*/
                   9800:     }
                   9801:         /* If line starts with a # it is a comment */
                   9802:     if (line[noffset] == '#') {
                   9803:       linei=linei+1;
                   9804:       break;
                   9805:     }else{
                   9806:       break;
                   9807:     }
                   9808:   }
                   9809:   fclose(fic);
                   9810:   if((fic=fopen(datafile,"r"))==NULL)    {
                   9811:     printf("Problem while opening datafile: %s with errno='%s'\n", datafile,strerror(errno));fflush(stdout);
                   9812:     fprintf(ficlog,"Problem while opening datafile: %s with errno='%s'\n", datafile,strerror(errno));fflush(ficlog);return 1;
                   9813:   }
                   9814:   /* Not a Bom file */
                   9815:   
1.136     brouard  9816:   i=1;
                   9817:   while ((fgets(line, MAXLINE, fic) != NULL) &&((i >= firstobs) && (i <=lastobs))) {
                   9818:     linei=linei+1;
                   9819:     for(j=strlen(line); j>=0;j--){  /* Untabifies line */
                   9820:       if(line[j] == '\t')
                   9821:        line[j] = ' ';
                   9822:     }
                   9823:     for(j=strlen(line)-1; (line[j]==' ')||(line[j]==10)||(line[j]==13);j--){
                   9824:       ;
                   9825:     };
                   9826:     line[j+1]=0;  /* Trims blanks at end of line */
                   9827:     if(line[0]=='#'){
                   9828:       fprintf(ficlog,"Comment line\n%s\n",line);
                   9829:       printf("Comment line\n%s\n",line);
                   9830:       continue;
                   9831:     }
                   9832:     trimbb(linetmp,line); /* Trims multiple blanks in line */
1.164     brouard  9833:     strcpy(line, linetmp);
1.223     brouard  9834:     
                   9835:     /* Loops on waves */
                   9836:     for (j=maxwav;j>=1;j--){
                   9837:       for (iv=nqtv;iv>=1;iv--){  /* Loop  on time varying quantitative variables */
1.238     brouard  9838:        cutv(stra, strb, line, ' '); 
                   9839:        if(strb[0]=='.') { /* Missing value */
                   9840:          lval=-1;
                   9841:          cotqvar[j][iv][i]=-1; /* 0.0/0.0 */
                   9842:          cotvar[j][ntv+iv][i]=-1; /* For performance reasons */
                   9843:          if(isalpha(strb[1])) { /* .m or .d Really Missing value */
                   9844:            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);
                   9845:            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);
                   9846:            return 1;
                   9847:          }
                   9848:        }else{
                   9849:          errno=0;
                   9850:          /* what_kind_of_number(strb); */
                   9851:          dval=strtod(strb,&endptr); 
                   9852:          /* if( strb[0]=='\0' || (*endptr != '\0')){ */
                   9853:          /* if(strb != endptr && *endptr == '\0') */
                   9854:          /*    dval=dlval; */
                   9855:          /* if (errno == ERANGE && (lval == LONG_MAX || lval == LONG_MIN)) */
                   9856:          if( strb[0]=='\0' || (*endptr != '\0')){
                   9857:            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);
                   9858:            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);
                   9859:            return 1;
                   9860:          }
                   9861:          cotqvar[j][iv][i]=dval; 
                   9862:          cotvar[j][ntv+iv][i]=dval; 
                   9863:        }
                   9864:        strcpy(line,stra);
1.223     brouard  9865:       }/* end loop ntqv */
1.225     brouard  9866:       
1.223     brouard  9867:       for (iv=ntv;iv>=1;iv--){  /* Loop  on time varying dummies */
1.238     brouard  9868:        cutv(stra, strb, line, ' '); 
                   9869:        if(strb[0]=='.') { /* Missing value */
                   9870:          lval=-1;
                   9871:        }else{
                   9872:          errno=0;
                   9873:          lval=strtol(strb,&endptr,10); 
                   9874:          /*    if (errno == ERANGE && (lval == LONG_MAX || lval == LONG_MIN))*/
                   9875:          if( strb[0]=='\0' || (*endptr != '\0')){
                   9876:            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);
                   9877:            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);
                   9878:            return 1;
                   9879:          }
                   9880:        }
                   9881:        if(lval <-1 || lval >1){
                   9882:          printf("Error reading data around '%ld' at line number %d for individual %d, '%s'\n \
1.319     brouard  9883:  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  9884:  for the alternative. IMaCh does not build design variables automatically, do it yourself.\n \
1.238     brouard  9885:  For example, for multinomial values like 1, 2 and 3,\n                        \
                   9886:  build V1=0 V2=0 for the reference value (1),\n                                \
                   9887:         V1=1 V2=0 for (2) \n                                           \
1.223     brouard  9888:  and V1=0 V2=1 for (3). V1=1 V2=1 should not exist and the corresponding\n \
1.238     brouard  9889:  output of IMaCh is often meaningless.\n                               \
1.319     brouard  9890:  Exiting.\n",lval,linei, i,line,iv,j);
1.238     brouard  9891:          fprintf(ficlog,"Error reading data around '%ld' at line number %d for individual %d, '%s'\n \
1.319     brouard  9892:  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  9893:  for the alternative. IMaCh does not build design variables automatically, do it yourself.\n \
1.238     brouard  9894:  For example, for multinomial values like 1, 2 and 3,\n                        \
                   9895:  build V1=0 V2=0 for the reference value (1),\n                                \
                   9896:         V1=1 V2=0 for (2) \n                                           \
1.223     brouard  9897:  and V1=0 V2=1 for (3). V1=1 V2=1 should not exist and the corresponding\n \
1.238     brouard  9898:  output of IMaCh is often meaningless.\n                               \
1.319     brouard  9899:  Exiting.\n",lval,linei, i,line,iv,j);fflush(ficlog);
1.238     brouard  9900:          return 1;
                   9901:        }
                   9902:        cotvar[j][iv][i]=(double)(lval);
                   9903:        strcpy(line,stra);
1.223     brouard  9904:       }/* end loop ntv */
1.225     brouard  9905:       
1.223     brouard  9906:       /* Statuses  at wave */
1.137     brouard  9907:       cutv(stra, strb, line, ' '); 
1.223     brouard  9908:       if(strb[0]=='.') { /* Missing value */
1.238     brouard  9909:        lval=-1;
1.136     brouard  9910:       }else{
1.238     brouard  9911:        errno=0;
                   9912:        lval=strtol(strb,&endptr,10); 
                   9913:        /*      if (errno == ERANGE && (lval == LONG_MAX || lval == LONG_MIN))*/
                   9914:        if( strb[0]=='\0' || (*endptr != '\0')){
                   9915:          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);
                   9916:          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);
                   9917:          return 1;
                   9918:        }
1.136     brouard  9919:       }
1.225     brouard  9920:       
1.136     brouard  9921:       s[j][i]=lval;
1.225     brouard  9922:       
1.223     brouard  9923:       /* Date of Interview */
1.136     brouard  9924:       strcpy(line,stra);
                   9925:       cutv(stra, strb,line,' ');
1.169     brouard  9926:       if( (iout=sscanf(strb,"%d/%d",&month, &year)) != 0){
1.136     brouard  9927:       }
1.169     brouard  9928:       else  if( (iout=sscanf(strb,"%s.",dummy)) != 0){
1.225     brouard  9929:        month=99;
                   9930:        year=9999;
1.136     brouard  9931:       }else{
1.225     brouard  9932:        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);
                   9933:        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);
                   9934:        return 1;
1.136     brouard  9935:       }
                   9936:       anint[j][i]= (double) year; 
1.302     brouard  9937:       mint[j][i]= (double)month;
                   9938:       /* if( (int)anint[j][i]+ (int)(mint[j][i])/12. < (int) (moisnais[i]/12.+annais[i])){ */
                   9939:       /*       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]); */
                   9940:       /*       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]); */
                   9941:       /* } */
1.136     brouard  9942:       strcpy(line,stra);
1.223     brouard  9943:     } /* End loop on waves */
1.225     brouard  9944:     
1.223     brouard  9945:     /* Date of death */
1.136     brouard  9946:     cutv(stra, strb,line,' '); 
1.169     brouard  9947:     if( (iout=sscanf(strb,"%d/%d",&month, &year)) != 0){
1.136     brouard  9948:     }
1.169     brouard  9949:     else  if( (iout=sscanf(strb,"%s.",dummy)) != 0){
1.136     brouard  9950:       month=99;
                   9951:       year=9999;
                   9952:     }else{
1.141     brouard  9953:       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  9954:       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);
                   9955:       return 1;
1.136     brouard  9956:     }
                   9957:     andc[i]=(double) year; 
                   9958:     moisdc[i]=(double) month; 
                   9959:     strcpy(line,stra);
                   9960:     
1.223     brouard  9961:     /* Date of birth */
1.136     brouard  9962:     cutv(stra, strb,line,' '); 
1.169     brouard  9963:     if( (iout=sscanf(strb,"%d/%d",&month, &year)) != 0){
1.136     brouard  9964:     }
1.169     brouard  9965:     else  if( (iout=sscanf(strb,"%s.", dummy)) != 0){
1.136     brouard  9966:       month=99;
                   9967:       year=9999;
                   9968:     }else{
1.141     brouard  9969:       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);
                   9970:       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  9971:       return 1;
1.136     brouard  9972:     }
                   9973:     if (year==9999) {
1.141     brouard  9974:       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);
                   9975:       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  9976:       return 1;
                   9977:       
1.136     brouard  9978:     }
                   9979:     annais[i]=(double)(year);
1.302     brouard  9980:     moisnais[i]=(double)(month);
                   9981:     for (j=1;j<=maxwav;j++){
                   9982:       if( (int)anint[j][i]+ (int)(mint[j][i])/12. < (int) (moisnais[i]/12.+annais[i])){
                   9983:        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]);
                   9984:        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]);
                   9985:       }
                   9986:     }
                   9987: 
1.136     brouard  9988:     strcpy(line,stra);
1.225     brouard  9989:     
1.223     brouard  9990:     /* Sample weight */
1.136     brouard  9991:     cutv(stra, strb,line,' '); 
                   9992:     errno=0;
                   9993:     dval=strtod(strb,&endptr); 
                   9994:     if( strb[0]=='\0' || (*endptr != '\0')){
1.141     brouard  9995:       printf("Error reading data around '%f' at line number %d, \"%s\" for individual %d\nShould be a weight.  Exiting.\n",dval, i,line,linei);
                   9996:       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  9997:       fflush(ficlog);
                   9998:       return 1;
                   9999:     }
                   10000:     weight[i]=dval; 
                   10001:     strcpy(line,stra);
1.225     brouard  10002:     
1.223     brouard  10003:     for (iv=nqv;iv>=1;iv--){  /* Loop  on fixed quantitative variables */
                   10004:       cutv(stra, strb, line, ' '); 
                   10005:       if(strb[0]=='.') { /* Missing value */
1.225     brouard  10006:        lval=-1;
1.311     brouard  10007:        coqvar[iv][i]=NAN; 
                   10008:        covar[ncovcol+iv][i]=NAN; /* including qvar in standard covar for performance reasons */ 
1.223     brouard  10009:       }else{
1.225     brouard  10010:        errno=0;
                   10011:        /* what_kind_of_number(strb); */
                   10012:        dval=strtod(strb,&endptr);
                   10013:        /* if(strb != endptr && *endptr == '\0') */
                   10014:        /*   dval=dlval; */
                   10015:        /* if (errno == ERANGE && (lval == LONG_MAX || lval == LONG_MIN)) */
                   10016:        if( strb[0]=='\0' || (*endptr != '\0')){
                   10017:          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);
                   10018:          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);
                   10019:          return 1;
                   10020:        }
                   10021:        coqvar[iv][i]=dval; 
1.226     brouard  10022:        covar[ncovcol+iv][i]=dval; /* including qvar in standard covar for performance reasons */ 
1.223     brouard  10023:       }
                   10024:       strcpy(line,stra);
                   10025:     }/* end loop nqv */
1.136     brouard  10026:     
1.223     brouard  10027:     /* Covariate values */
1.136     brouard  10028:     for (j=ncovcol;j>=1;j--){
                   10029:       cutv(stra, strb,line,' '); 
1.223     brouard  10030:       if(strb[0]=='.') { /* Missing covariate value */
1.225     brouard  10031:        lval=-1;
1.136     brouard  10032:       }else{
1.225     brouard  10033:        errno=0;
                   10034:        lval=strtol(strb,&endptr,10); 
                   10035:        if( strb[0]=='\0' || (*endptr != '\0')){
                   10036:          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);
                   10037:          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);
                   10038:          return 1;
                   10039:        }
1.136     brouard  10040:       }
                   10041:       if(lval <-1 || lval >1){
1.225     brouard  10042:        printf("Error reading data around '%ld' at line number %d for individual %d, '%s'\n \
1.136     brouard  10043:  Should be a value of %d(nth) covariate (0 should be the value for the reference and 1\n \
                   10044:  for the alternative. IMaCh does not build design variables automatically, do it yourself.\n \
1.225     brouard  10045:  For example, for multinomial values like 1, 2 and 3,\n                        \
                   10046:  build V1=0 V2=0 for the reference value (1),\n                                \
                   10047:         V1=1 V2=0 for (2) \n                                           \
1.136     brouard  10048:  and V1=0 V2=1 for (3). V1=1 V2=1 should not exist and the corresponding\n \
1.225     brouard  10049:  output of IMaCh is often meaningless.\n                               \
1.136     brouard  10050:  Exiting.\n",lval,linei, i,line,j);
1.225     brouard  10051:        fprintf(ficlog,"Error reading data around '%ld' at line number %d for individual %d, '%s'\n \
1.136     brouard  10052:  Should be a value of %d(nth) covariate (0 should be the value for the reference and 1\n \
                   10053:  for the alternative. IMaCh does not build design variables automatically, do it yourself.\n \
1.225     brouard  10054:  For example, for multinomial values like 1, 2 and 3,\n                        \
                   10055:  build V1=0 V2=0 for the reference value (1),\n                                \
                   10056:         V1=1 V2=0 for (2) \n                                           \
1.136     brouard  10057:  and V1=0 V2=1 for (3). V1=1 V2=1 should not exist and the corresponding\n \
1.225     brouard  10058:  output of IMaCh is often meaningless.\n                               \
1.136     brouard  10059:  Exiting.\n",lval,linei, i,line,j);fflush(ficlog);
1.225     brouard  10060:        return 1;
1.136     brouard  10061:       }
                   10062:       covar[j][i]=(double)(lval);
                   10063:       strcpy(line,stra);
                   10064:     }  
                   10065:     lstra=strlen(stra);
1.225     brouard  10066:     
1.136     brouard  10067:     if(lstra > 9){ /* More than 2**32 or max of what printf can write with %ld */
                   10068:       stratrunc = &(stra[lstra-9]);
                   10069:       num[i]=atol(stratrunc);
                   10070:     }
                   10071:     else
                   10072:       num[i]=atol(stra);
                   10073:     /*if((s[2][i]==2) && (s[3][i]==-1)&&(s[4][i]==9)){
                   10074:       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;}*/
                   10075:     
                   10076:     i=i+1;
                   10077:   } /* End loop reading  data */
1.225     brouard  10078:   
1.136     brouard  10079:   *imax=i-1; /* Number of individuals */
                   10080:   fclose(fic);
1.225     brouard  10081:   
1.136     brouard  10082:   return (0);
1.164     brouard  10083:   /* endread: */
1.225     brouard  10084:   printf("Exiting readdata: ");
                   10085:   fclose(fic);
                   10086:   return (1);
1.223     brouard  10087: }
1.126     brouard  10088: 
1.234     brouard  10089: void removefirstspace(char **stri){/*, char stro[]) {*/
1.230     brouard  10090:   char *p1 = *stri, *p2 = *stri;
1.235     brouard  10091:   while (*p2 == ' ')
1.234     brouard  10092:     p2++; 
                   10093:   /* while ((*p1++ = *p2++) !=0) */
                   10094:   /*   ; */
                   10095:   /* do */
                   10096:   /*   while (*p2 == ' ') */
                   10097:   /*     p2++; */
                   10098:   /* while (*p1++ == *p2++); */
                   10099:   *stri=p2; 
1.145     brouard  10100: }
                   10101: 
1.330   ! brouard  10102: int decoderesult( char resultline[], int nres)
1.230     brouard  10103: /**< This routine decode one result line and returns the combination # of dummy covariates only **/
                   10104: {
1.235     brouard  10105:   int j=0, k=0, k1=0, k2=0, k3=0, k4=0, match=0, k2q=0, k3q=0, k4q=0;
1.230     brouard  10106:   char resultsav[MAXLINE];
1.330   ! brouard  10107:   /* int resultmodel[MAXLINE]; */
1.234     brouard  10108:   int modelresult[MAXLINE];
1.230     brouard  10109:   char stra[80], strb[80], strc[80], strd[80],stre[80];
                   10110: 
1.234     brouard  10111:   removefirstspace(&resultline);
1.230     brouard  10112: 
                   10113:   if (strstr(resultline,"v") !=0){
                   10114:     printf("Error. 'v' must be in upper case 'V' result: %s ",resultline);
                   10115:     fprintf(ficlog,"Error. 'v' must be in upper case result: %s ",resultline);fflush(ficlog);
                   10116:     return 1;
                   10117:   }
                   10118:   trimbb(resultsav, resultline);
                   10119:   if (strlen(resultsav) >1){
                   10120:     j=nbocc(resultsav,'='); /**< j=Number of covariate values'=' */
                   10121:   }
1.253     brouard  10122:   if(j == 0){ /* Resultline but no = */
                   10123:     TKresult[nres]=0; /* Combination for the nresult and the model */
                   10124:     return (0);
                   10125:   }
1.234     brouard  10126:   if( j != cptcovs ){ /* Be careful if a variable is in a product but not single */
1.318     brouard  10127:     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  10128:     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  10129:   }
                   10130:   for(k=1; k<=j;k++){ /* Loop on any covariate of the result line */
                   10131:     if(nbocc(resultsav,'=') >1){
1.318     brouard  10132:       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" */
                   10133:       cutl(strc,strd,strb,'=');  /* strb:"V4=1" strc="1" strd="V4" */
1.234     brouard  10134:     }else
                   10135:       cutl(strc,strd,resultsav,'=');
1.318     brouard  10136:     Tvalsel[k]=atof(strc); /* 1 */ /* Tvalsel of k is the float value of the kth covariate appearing in this result line */
1.234     brouard  10137:     
1.230     brouard  10138:     cutl(strc,stre,strd,'V'); /* strd='V4' strc=4 stre='V' */;
1.318     brouard  10139:     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  10140:     /* Typevarsel[k]=1;  /\* 1 for age product *\/ */
                   10141:     /* cptcovsel++;     */
                   10142:     if (nbocc(stra,'=') >0)
                   10143:       strcpy(resultsav,stra); /* and analyzes it */
                   10144:   }
1.235     brouard  10145:   /* Checking for missing or useless values in comparison of current model needs */
1.318     brouard  10146:   for(k1=1; k1<= cptcovt ;k1++){ /* Loop on model. model line V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
                   10147:     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  10148:       match=0;
1.318     brouard  10149:       for(k2=1; k2 <=j;k2++){/* Loop on resultline. In result line V4=1 V5=24.1 V3=1  V2=8 V1=0 */
                   10150:        if(Tvar[k1]==Tvarsel[k2]) {/* Tvar is coming from the model, Tvarsel from the result. Tvar[1]=5 == Tvarsel[2]=5   */
1.236     brouard  10151:          modelresult[k2]=k1;/* modelresult[2]=1 modelresult[1]=2  modelresult[3]=3  modelresult[6]=4 modelresult[9]=5 */
1.318     brouard  10152:          match=1; /* modelresult of k2 variable of resultline is identical to k1 variable of the model good */
1.234     brouard  10153:          break;
                   10154:        }
                   10155:       }
                   10156:       if(match == 0){
1.310     brouard  10157:        printf("Error in result line: V%d is missing in result: %s according to model=%s\n",k1, resultline, model);
                   10158:        fprintf(ficlog,"Error in result line: V%d is missing in result: %s according to model=%s\n",k1, resultline, model);
                   10159:        return 1;
1.234     brouard  10160:       }
                   10161:     }
                   10162:   }
1.235     brouard  10163:   /* Checking for missing or useless values in comparison of current model needs */
1.318     brouard  10164:   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  10165:     match=0;
1.318     brouard  10166:     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  10167:       if(Typevar[k1]==0){ /* Single */
1.237     brouard  10168:        if(Tvar[k1]==Tvarsel[k2]) { /* Tvar[2]=4 == Tvarsel[1]=4   */
1.330   ! brouard  10169:          resultmodel[nres][k1]=k2;  /* k1th position in the model equation corresponds to k2th position in the result line. resultmodel[2]=1 resultmodel[1]=2  resultmodel[3]=3  resultmodel[6]=4 resultmodel[9]=5 */
1.234     brouard  10170:          ++match;
                   10171:        }
                   10172:       }
                   10173:     }
                   10174:     if(match == 0){
                   10175:       printf("Error in result line: %d value missing; result: %s, model=%s\n",k1, resultline, model);
1.310     brouard  10176:       fprintf(ficlog,"Error in result line: %d value missing; result: %s, model=%s\n",k1, resultline, model);
                   10177:       return 1;
1.234     brouard  10178:     }else if(match > 1){
                   10179:       printf("Error in result line: %d doubled; result: %s, model=%s\n",k2, resultline, model);
1.310     brouard  10180:       fprintf(ficlog,"Error in result line: %d doubled; result: %s, model=%s\n",k2, resultline, model);
                   10181:       return 1;
1.234     brouard  10182:     }
                   10183:   }
1.235     brouard  10184:       
1.234     brouard  10185:   /* We need to deduce which combination number is chosen and save quantitative values */
1.235     brouard  10186:   /* model line V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
1.330   ! brouard  10187:   /* nres=1st result line: V4=1 V5=25.1 V3=0  V2=8 V1=1 */
        !          10188:   /* should correspond to the combination 6 of dummy: V4=1, V3=0, V1=1 => V4*2**(0) + V3*2**(1) + V1*2**(2) = 1*1 + 0*2 + 1*4 = 5 + (1offset) = 6*/
        !          10189:   /* nres=2nd result line: V4=1 V5=24.1 V3=1  V2=8 V1=0 */
1.235     brouard  10190:   /* should give a combination of dummy V4=1, V3=1, V1=0 => V4*2**(0) + V3*2**(1) + V1*2**(2) = 3 + (1offset) = 4*/
                   10191:   /*    1 0 0 0 */
                   10192:   /*    2 1 0 0 */
                   10193:   /*    3 0 1 0 */ 
1.330   ! brouard  10194:   /*    4 1 1 0 */ /* V4=1, V3=1, V1=0 (nres=2)*/
1.235     brouard  10195:   /*    5 0 0 1 */
1.330   ! brouard  10196:   /*    6 1 0 1 */ /* V4=1, V3=0, V1=1 (nres=1)*/
1.235     brouard  10197:   /*    7 0 1 1 */
                   10198:   /*    8 1 1 1 */
1.237     brouard  10199:   /* V(Tvresult)=Tresult V4=1 V3=0 V1=1 Tresult[nres=1][2]=0 */
                   10200:   /* V(Tvqresult)=Tqresult V5=25.1 V2=8 Tqresult[nres=1][1]=25.1 */
                   10201:   /* V5*age V5 known which value for nres?  */
                   10202:   /* Tqinvresult[2]=8 Tqinvresult[1]=25.1  */
1.330   ! brouard  10203:   for(k1=1, k=0, k4=0, k4q=0; k1 <=cptcovt;k1++){ /* loop k1 on position in the model line (excluding product) */
1.235     brouard  10204:     if( Dummy[k1]==0 && Typevar[k1]==0 ){ /* Single dummy */
1.330   ! brouard  10205:       /* k4+1= position in the resultline V(Tvarsel)=Tvalsel=Tresult[nres][pos](value); V(Tvresult[nres][pos] (variable): V(variable)=value) */
        !          10206:       /* modelresult[k3]=k1: k3th position in the result line correspond to the k1 position in the model line */
        !          10207:       /* Value in the (current nres) resultline of the variable at the k1th position in the model equation resultmodel[nres][k1]= k3 */
        !          10208:       /* resultmodel[nres][k1]=k3: k1th position in the model correspond to the k3 position in the resultline */
        !          10209:       /*      k3 is the position in the nres result line of the k1th variable of the model equation                                          */
        !          10210:       /* Tvarsel: Name of the variable at the k3th position in the result line Tvarsel[k3].                                                  */
        !          10211:       /* Tvalsel: Value of the variable at the k3th position in the result line Tvarsel[k3].                                                 */
        !          10212:       /* Tresult[nres][result_position]= value of the dummy variable at the result_position in the nres resultline                                 */
        !          10213:       /* Tvresult[nres][result_position]= id of the dummy variable at the result_position in the nres resultline                                   */
        !          10214:       /* Tinvresult[nres][Name of a dummy variable]= value of the variable in the result line                                                      */
        !          10215:       /* TinvDoQresult[nres][Name of a Dummy or Q variable]= value of the variable in the result line                                                      */
        !          10216:       k3= resultmodel[nres][k1]; /* nres=1 k1=2 resultmodel[2(V4)] = 1=k3 ; k1=3 resultmodel[3(V3)] = 2=k3*/
        !          10217:       k2=(int)Tvarsel[k3]; /* nres=1 k1=2=>k3=1 Tvarsel[resultmodel[2]]= Tvarsel[1] = 4=k2 (V4); k1=3=>k3=2 Tvarsel[2]=3 (V3)*/
        !          10218:       k+=Tvalsel[k3]*pow(2,k4);  /* nres=1 k1=2 Tvalsel[1]=1 (V4=1); k1=3 k3=2 Tvalsel[2]=0 (V3=0) */
        !          10219:       Tresult[nres][k4+1]=Tvalsel[k3];/* Tresult[nres=2][1]=1(V4=1)  Tresult[nres=2][2]=0(V3=0) */
1.237     brouard  10220:       Tvresult[nres][k4+1]=(int)Tvarsel[k3];/* Tvresult[nres][1]=4 Tvresult[nres][3]=1 */
                   10221:       Tinvresult[nres][(int)Tvarsel[k3]]=Tvalsel[k3]; /* Tinvresult[nres][4]=1 */
1.330   ! brouard  10222:       TinvDoQresult[nres][(int)Tvarsel[k3]]=Tvalsel[k3]; /* Tinvresult[nres][4]=1 */
1.235     brouard  10223:       printf("Decoderesult Dummy k=%d, V(k2=V%d)= Tvalsel[%d]=%d, 2**(%d)\n",k, k2, k3, (int)Tvalsel[k3], k4);
                   10224:       k4++;;
                   10225:     }  else if( Dummy[k1]==1 && Typevar[k1]==0 ){ /* Single quantitative */
1.330   ! brouard  10226:       /* Tqresult[nres][result_position]= value of the variable at the result_position in the nres resultline                                 */
        !          10227:       /* Tqvresult[nres][result_position]= id of the variable at the result_position in the nres resultline                                 */
        !          10228:       /* Tqinvresult[nres][Name of a quantitative variable]= value of the variable in the result line                                                      */
        !          10229:       k3q= resultmodel[nres][k1]; /* resultmodel[1(V5)] = 25.1=k3q */
1.318     brouard  10230:       k2q=(int)Tvarsel[k3q]; /*  Tvarsel[resultmodel[1]]= Tvarsel[1] = 4=k2 */
1.237     brouard  10231:       Tqresult[nres][k4q+1]=Tvalsel[k3q]; /* Tqresult[nres][1]=25.1 */
                   10232:       Tvqresult[nres][k4q+1]=(int)Tvarsel[k3q]; /* Tvqresult[nres][1]=5 */
                   10233:       Tqinvresult[nres][(int)Tvarsel[k3q]]=Tvalsel[k3q]; /* Tqinvresult[nres][5]=25.1 */
1.330   ! brouard  10234:       TinvDoQresult[nres][(int)Tvarsel[k3q]]=Tvalsel[k3q]; /* Tqinvresult[nres][5]=25.1 */
1.235     brouard  10235:       printf("Decoderesult Quantitative nres=%d, V(k2q=V%d)= Tvalsel[%d]=%d, Tvarsel[%d]=%f\n",nres, k2q, k3q, Tvarsel[k3q], k3q, Tvalsel[k3q]);
                   10236:       k4q++;;
1.330   ! brouard  10237:     }else{
        !          10238:       printf("Decodemodel probably a product  Dummy[%d]==%d && Typevar[%d]==%d\n", k1, Dummy[k1], k1, Typevar[k1]);
        !          10239:       fprintf(ficlog,"Decodemodel probably a product  Dummy[%d]==%d && Typevar[%d]==%d\n", k1, Dummy[k1], k1, Typevar[k1]);
1.235     brouard  10240:     }
                   10241:   }
1.234     brouard  10242:   
1.235     brouard  10243:   TKresult[nres]=++k; /* Combination for the nresult and the model */
1.230     brouard  10244:   return (0);
                   10245: }
1.235     brouard  10246: 
1.230     brouard  10247: int decodemodel( char model[], int lastobs)
                   10248:  /**< This routine decodes the model and returns:
1.224     brouard  10249:        * Model  V1+V2+V3+V8+V7*V8+V5*V6+V8*age+V3*age+age*age
                   10250:        * - nagesqr = 1 if age*age in the model, otherwise 0.
                   10251:        * - cptcovt total number of covariates of the model nbocc(+)+1 = 8 excepting constant and age and age*age
                   10252:        * - cptcovn or number of covariates k of the models excluding age*products =6 and age*age
                   10253:        * - cptcovage number of covariates with age*products =2
                   10254:        * - cptcovs number of simple covariates
                   10255:        * - 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
                   10256:        *     which is a new column after the 9 (ncovcol) variables. 
1.319     brouard  10257:        * - if k is a product Vn*Vm, covar[k][i] is filled with correct values for each individual
1.224     brouard  10258:        * - Tprod[l] gives the kth covariates of the product Vn*Vm l=1 to cptcovprod-cptcovage
                   10259:        *    Tprod[1]@2 {5, 6}: position of first product V7*V8 is 5, and second V5*V6 is 6.
                   10260:        * - Tvard[k]  p Tvard[1][1]@4 {7, 8, 5, 6} for V7*V8 and V5*V6 .
                   10261:        */
1.319     brouard  10262: /* 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  10263: {
1.238     brouard  10264:   int i, j, k, ks, v;
1.227     brouard  10265:   int  j1, k1, k2, k3, k4;
1.136     brouard  10266:   char modelsav[80];
1.145     brouard  10267:   char stra[80], strb[80], strc[80], strd[80],stre[80];
1.187     brouard  10268:   char *strpt;
1.136     brouard  10269: 
1.145     brouard  10270:   /*removespace(model);*/
1.136     brouard  10271:   if (strlen(model) >1){ /* If there is at least 1 covariate */
1.145     brouard  10272:     j=0, j1=0, k1=0, k2=-1, ks=0, cptcovn=0;
1.137     brouard  10273:     if (strstr(model,"AGE") !=0){
1.192     brouard  10274:       printf("Error. AGE must be in lower case 'age' model=1+age+%s. ",model);
                   10275:       fprintf(ficlog,"Error. AGE must be in lower case model=1+age+%s. ",model);fflush(ficlog);
1.136     brouard  10276:       return 1;
                   10277:     }
1.141     brouard  10278:     if (strstr(model,"v") !=0){
                   10279:       printf("Error. 'v' must be in upper case 'V' model=%s ",model);
                   10280:       fprintf(ficlog,"Error. 'v' must be in upper case model=%s ",model);fflush(ficlog);
                   10281:       return 1;
                   10282:     }
1.187     brouard  10283:     strcpy(modelsav,model); 
                   10284:     if ((strpt=strstr(model,"age*age")) !=0){
                   10285:       printf(" strpt=%s, model=%s\n",strpt, model);
                   10286:       if(strpt != model){
1.234     brouard  10287:        printf("Error in model: 'model=%s'; 'age*age' should in first place before other covariates\n \
1.192     brouard  10288:  'model=1+age+age*age+V1.' or 'model=1+age+age*age+V1+V1*age.', please swap as well as \n \
1.187     brouard  10289:  corresponding column of parameters.\n",model);
1.234     brouard  10290:        fprintf(ficlog,"Error in model: 'model=%s'; 'age*age' should in first place before other covariates\n \
1.192     brouard  10291:  'model=1+age+age*age+V1.' or 'model=1+age+age*age+V1+V1*age.', please swap as well as \n \
1.187     brouard  10292:  corresponding column of parameters.\n",model); fflush(ficlog);
1.234     brouard  10293:        return 1;
1.225     brouard  10294:       }
1.187     brouard  10295:       nagesqr=1;
                   10296:       if (strstr(model,"+age*age") !=0)
1.234     brouard  10297:        substrchaine(modelsav, model, "+age*age");
1.187     brouard  10298:       else if (strstr(model,"age*age+") !=0)
1.234     brouard  10299:        substrchaine(modelsav, model, "age*age+");
1.187     brouard  10300:       else 
1.234     brouard  10301:        substrchaine(modelsav, model, "age*age");
1.187     brouard  10302:     }else
                   10303:       nagesqr=0;
                   10304:     if (strlen(modelsav) >1){
                   10305:       j=nbocc(modelsav,'+'); /**< j=Number of '+' */
                   10306:       j1=nbocc(modelsav,'*'); /**< j1=Number of '*' */
1.224     brouard  10307:       cptcovs=j+1-j1; /**<  Number of simple covariates V1+V1*age+V3 +V3*V4+age*age=> V1 + V3 =5-3=2  */
1.187     brouard  10308:       cptcovt= j+1; /* Number of total covariates in the model, not including
1.225     brouard  10309:                     * cst, age and age*age 
                   10310:                     * V1+V1*age+ V3 + V3*V4+age*age=> 3+1=4*/
                   10311:       /* including age products which are counted in cptcovage.
                   10312:        * but the covariates which are products must be treated 
                   10313:        * separately: ncovn=4- 2=2 (V1+V3). */
1.187     brouard  10314:       cptcovprod=j1; /**< Number of products  V1*V2 +v3*age = 2 */
                   10315:       cptcovprodnoage=0; /**< Number of covariate products without age: V3*V4 =1  */
1.225     brouard  10316:       
                   10317:       
1.187     brouard  10318:       /*   Design
                   10319:        *  V1   V2   V3   V4  V5  V6  V7  V8  V9 Weight
                   10320:        *  <          ncovcol=8                >
                   10321:        * Model V2 + V1 + V3*age + V3 + V5*V6 + V7*V8 + V8*age + V8
                   10322:        *   k=  1    2      3       4     5       6      7        8
                   10323:        *  cptcovn number of covariates (not including constant and age ) = # of + plus 1 = 7+1=8
                   10324:        *  covar[k,i], value of kth covariate if not including age for individual i:
1.224     brouard  10325:        *       covar[1][i]= (V1), covar[4][i]=(V4), covar[8][i]=(V8)
                   10326:        *  Tvar[k] # of the kth covariate:  Tvar[1]=2  Tvar[2]=1 Tvar[4]=3 Tvar[8]=8
1.187     brouard  10327:        *       if multiplied by age: V3*age Tvar[3=V3*age]=3 (V3) Tvar[7]=8 and 
                   10328:        *  Tage[++cptcovage]=k
                   10329:        *       if products, new covar are created after ncovcol with k1
                   10330:        *  Tvar[k]=ncovcol+k1; # of the kth covariate product:  Tvar[5]=ncovcol+1=10  Tvar[6]=ncovcol+1=11
                   10331:        *  Tprod[k1]=k; Tprod[1]=5 Tprod[2]= 6; gives the position of the k1th product
                   10332:        *  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
                   10333:        *  Tvar[cptcovn+k2]=Tvard[k1][1];Tvar[cptcovn+k2+1]=Tvard[k1][2];
                   10334:        *  Tvar[8+1]=5;Tvar[8+2]=6;Tvar[8+3]=7;Tvar[8+4]=8 inverted
                   10335:        *  V1   V2   V3   V4  V5  V6  V7  V8  V9  V10  V11
                   10336:        *  <          ncovcol=8                >
                   10337:        *       Model V2 + V1 + V3*age + V3 + V5*V6 + V7*V8 + V8*age + V8    d1   d1   d2  d2
                   10338:        *          k=  1    2      3       4     5       6      7        8    9   10   11  12
                   10339:        *     Tvar[k]= 2    1      3       3    10      11      8        8    5    6    7   8
1.319     brouard  10340:        * p Tvar[1]@12={2,   1,     3,      3,  11,     10,     8,       8,   7,   8,   5,  6}
1.187     brouard  10341:        * p Tprod[1]@2={                         6, 5}
                   10342:        *p Tvard[1][1]@4= {7, 8, 5, 6}
                   10343:        * covar[k][i]= V2   V1      ?      V3    V5*V6?   V7*V8?  ?       V8   
                   10344:        *  cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];
1.319     brouard  10345:        *How to reorganize? Tvars(orted)
1.187     brouard  10346:        * Model V1 + V2 + V3 + V8 + V5*V6 + V7*V8 + V3*age + V8*age
                   10347:        * Tvars {2,   1,     3,      3,   11,     10,     8,       8,   7,   8,   5,  6}
                   10348:        *       {2,   1,     4,      8,    5,      6,     3,       7}
                   10349:        * Struct []
                   10350:        */
1.225     brouard  10351:       
1.187     brouard  10352:       /* This loop fills the array Tvar from the string 'model'.*/
                   10353:       /* j is the number of + signs in the model V1+V2+V3 j=2 i=3 to 1 */
                   10354:       /*   modelsav=V2+V1+V4+age*V3 strb=age*V3 stra=V2+V1+V4  */
                   10355:       /*       k=4 (age*V3) Tvar[k=4]= 3 (from V3) Tage[cptcovage=1]=4 */
                   10356:       /*       k=3 V4 Tvar[k=3]= 4 (from V4) */
                   10357:       /*       k=2 V1 Tvar[k=2]= 1 (from V1) */
                   10358:       /*       k=1 Tvar[1]=2 (from V2) */
                   10359:       /*       k=5 Tvar[5] */
                   10360:       /* for (k=1; k<=cptcovn;k++) { */
1.198     brouard  10361:       /*       cov[2+k]=nbcode[Tvar[k]][codtabm(ij,Tvar[k])]; */
1.187     brouard  10362:       /*       } */
1.198     brouard  10363:       /* for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,Tvar[Tage[k])]]*cov[2]; */
1.187     brouard  10364:       /*
                   10365:        * Treating invertedly V2+V1+V3*age+V2*V4 is as if written V2*V4 +V3*age + V1 + V2 */
1.227     brouard  10366:       for(k=cptcovt; k>=1;k--){ /**< Number of covariates not including constant and age, neither age*age*/
                   10367:         Tvar[k]=0; Tprod[k]=0; Tposprod[k]=0;
                   10368:       }
1.187     brouard  10369:       cptcovage=0;
1.319     brouard  10370:       for(k=1; k<=cptcovt;k++){ /* Loop on total covariates of the model line */
                   10371:        cutl(stra,strb,modelsav,'+'); /* keeps in strb after the first '+' cutl from left to right
                   10372:                                         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" */
                   10373:        if (nbocc(modelsav,'+')==0)
                   10374:          strcpy(strb,modelsav); /* and analyzes it */
1.234     brouard  10375:        /*      printf("i=%d a=%s b=%s sav=%s\n",i, stra,strb,modelsav);*/
                   10376:        /*scanf("%d",i);*/
1.319     brouard  10377:        if (strchr(strb,'*')) {  /**< Model includes a product V2+V1+V5*age+ V4+V3*age strb=V3*age */
                   10378:          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  10379:          if (strcmp(strc,"age")==0) { /**< Model includes age: Vn*age */
                   10380:            /* covar is not filled and then is empty */
                   10381:            cptcovprod--;
                   10382:            cutl(stre,strb,strd,'V'); /* strd=V3(input): stre="3" */
1.319     brouard  10383:            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  10384:            Typevar[k]=1;  /* 1 for age product */
1.319     brouard  10385:            cptcovage++; /* Counts the number of covariates which include age as a product */
                   10386:            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  10387:            /*printf("stre=%s ", stre);*/
                   10388:          } else if (strcmp(strd,"age")==0) { /* or age*Vn */
                   10389:            cptcovprod--;
                   10390:            cutl(stre,strb,strc,'V');
                   10391:            Tvar[k]=atoi(stre);
                   10392:            Typevar[k]=1;  /* 1 for age product */
                   10393:            cptcovage++;
                   10394:            Tage[cptcovage]=k;
                   10395:          } else {  /* Age is not in the model product V2+V1+V1*V4+V3*age+V3*V2  strb=V3*V2*/
                   10396:            /* loops on k1=1 (V3*V2) and k1=2 V4*V3 */
                   10397:            cptcovn++;
                   10398:            cptcovprodnoage++;k1++;
                   10399:            cutl(stre,strb,strc,'V'); /* strc= Vn, stre is n; strb=V3*V2 stre=3 strc=*/
                   10400:            Tvar[k]=ncovcol+nqv+ntv+nqtv+k1; /* For model-covariate k tells which data-covariate to use but
                   10401:                                                because this model-covariate is a construction we invent a new column
                   10402:                                                which is after existing variables ncovcol+nqv+ntv+nqtv + k1
1.319     brouard  10403:                                                If already ncovcol=4 and model=V2 + V1 +V1*V4 +age*V3 +V3*V2
                   10404:                                                thus after V4 we invent V5 and V6 because age*V3 will be computed in 4
                   10405:                                                Tvar[3=V1*V4]=4+1=5 Tvar[5=V3*V2]=4 + 2= 6, Tvar[4=age*V3]=4 etc */
1.234     brouard  10406:            Typevar[k]=2;  /* 2 for double fixed dummy covariates */
                   10407:            cutl(strc,strb,strd,'V'); /* strd was Vm, strc is m */
                   10408:            Tprod[k1]=k;  /* Tprod[1]=3(=V1*V4) for V2+V1+V1*V4+age*V3+V3*V2  */
1.319     brouard  10409:            Tposprod[k]=k1; /* Tposprod[3]=1, Tposprod[2]=5 */
1.234     brouard  10410:            Tvard[k1][1] =atoi(strc); /* m 1 for V1*/
1.330   ! brouard  10411:            Tvardk[k][1] =atoi(strc); /* m 1 for V1*/
1.234     brouard  10412:            Tvard[k1][2] =atoi(stre); /* n 4 for V4*/
1.330   ! brouard  10413:            Tvardk[k][2] =atoi(stre); /* n 4 for V4*/
1.234     brouard  10414:            k2=k2+2;  /* k2 is initialize to -1, We want to store the n and m in Vn*Vm at the end of Tvar */
                   10415:            /* Tvar[cptcovt+k2]=Tvard[k1][1]; /\* Tvar[(cptcovt=4+k2=1)=5]= 1 (V1) *\/ */
                   10416:            /* Tvar[cptcovt+k2+1]=Tvard[k1][2];  /\* Tvar[(cptcovt=4+(k2=1)+1)=6]= 4 (V4) *\/ */
1.225     brouard  10417:             /*ncovcol=4 and model=V2+V1+V1*V4+age*V3+V3*V2, Tvar[3]=5, Tvar[4]=6, cptcovt=5 */
1.234     brouard  10418:            /*                     1  2   3      4     5 | Tvar[5+1)=1, Tvar[7]=2   */
                   10419:            for (i=1; i<=lastobs;i++){
                   10420:              /* Computes the new covariate which is a product of
                   10421:                 covar[n][i]* covar[m][i] and stores it at ncovol+k1 May not be defined */
                   10422:              covar[ncovcol+k1][i]=covar[atoi(stre)][i]*covar[atoi(strc)][i];
                   10423:            }
                   10424:          } /* End age is not in the model */
                   10425:        } /* End if model includes a product */
1.319     brouard  10426:        else { /* not a product */
1.234     brouard  10427:          /*printf("d=%s c=%s b=%s\n", strd,strc,strb);*/
                   10428:          /*  scanf("%d",i);*/
                   10429:          cutl(strd,strc,strb,'V');
                   10430:          ks++; /**< Number of simple covariates dummy or quantitative, fixe or varying */
                   10431:          cptcovn++; /** V4+V3+V5: V4 and V3 timevarying dummy covariates, V5 timevarying quantitative */
                   10432:          Tvar[k]=atoi(strd);
                   10433:          Typevar[k]=0;  /* 0 for simple covariates */
                   10434:        }
                   10435:        strcpy(modelsav,stra);  /* modelsav=V2+V1+V4 stra=V2+V1+V4 */ 
1.223     brouard  10436:                                /*printf("a=%s b=%s sav=%s\n", stra,strb,modelsav);
1.225     brouard  10437:                                  scanf("%d",i);*/
1.187     brouard  10438:       } /* end of loop + on total covariates */
                   10439:     } /* end if strlen(modelsave == 0) age*age might exist */
                   10440:   } /* end if strlen(model == 0) */
1.136     brouard  10441:   
                   10442:   /*The number n of Vn is stored in Tvar. cptcovage =number of age covariate. Tage gives the position of age. cptcovprod= number of products.
                   10443:     If model=V1+V1*age then Tvar[1]=1 Tvar[2]=1 cptcovage=1 Tage[1]=2 cptcovprod=0*/
1.225     brouard  10444:   
1.136     brouard  10445:   /* printf("tvar1=%d tvar2=%d tvar3=%d cptcovage=%d Tage=%d",Tvar[1],Tvar[2],Tvar[3],cptcovage,Tage[1]);
1.225     brouard  10446:      printf("cptcovprod=%d ", cptcovprod);
                   10447:      fprintf(ficlog,"cptcovprod=%d ", cptcovprod);
                   10448:      scanf("%d ",i);*/
                   10449: 
                   10450: 
1.230     brouard  10451: /* Until here, decodemodel knows only the grammar (simple, product, age*) of the model but not what kind
                   10452:    of variable (dummy vs quantitative, fixed vs time varying) is behind. But we know the # of each. */
1.226     brouard  10453: /* ncovcol= 1, nqv=1 | ntv=2, nqtv= 1  = 5 possible variables data: 2 fixed 3, varying
                   10454:    model=        V5 + V4 +V3 + V4*V3 + V5*age + V2 + V1*V2 + V1*age + V5*age, V1 is not used saving its place
                   10455:    k =           1    2   3     4       5       6      7      8        9
                   10456:    Tvar[k]=      5    4   3 1+1+2+1+1=6 5       2      7      1        5
1.319     brouard  10457:    Typevar[k]=   0    0   0     2       1       0      2      1        0
1.227     brouard  10458:    Fixed[k]      1    1   1     1       3       0    0 or 2   2        3
                   10459:    Dummy[k]      1    0   0     0       3       1      1      2        3
                   10460:          Tmodelind[combination of covar]=k;
1.225     brouard  10461: */  
                   10462: /* Dispatching between quantitative and time varying covariates */
1.226     brouard  10463:   /* If Tvar[k] >ncovcol it is a product */
1.225     brouard  10464:   /* 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  10465:        /* Computing effective variables, ie used by the model, that is from the cptcovt variables */
1.318     brouard  10466:   printf("Model=1+age+%s\n\
1.227     brouard  10467: Typevar: 0 for simple covariate (dummy, quantitative, fixed or varying), 1 for age product, 2 for  product \n\
                   10468: Fixed[k] 0=fixed (product or simple), 1 varying, 2 fixed with age product, 3 varying with age product \n\
                   10469: 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  10470:   fprintf(ficlog,"Model=1+age+%s\n\
1.227     brouard  10471: Typevar: 0 for simple covariate (dummy, quantitative, fixed or varying), 1 for age product, 2 for  product \n\
                   10472: Fixed[k] 0=fixed (product or simple), 1 varying, 2 fixed with age product, 3 varying with age product \n\
                   10473: 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  10474:   for(k=-1;k<=cptcovt; k++){ Fixed[k]=0; Dummy[k]=0;}
1.234     brouard  10475:   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 */
                   10476:     if (Tvar[k] <=ncovcol && Typevar[k]==0 ){ /* Simple fixed dummy (<=ncovcol) covariates */
1.227     brouard  10477:       Fixed[k]= 0;
                   10478:       Dummy[k]= 0;
1.225     brouard  10479:       ncoveff++;
1.232     brouard  10480:       ncovf++;
1.234     brouard  10481:       nsd++;
                   10482:       modell[k].maintype= FTYPE;
                   10483:       TvarsD[nsd]=Tvar[k];
                   10484:       TvarsDind[nsd]=k;
1.330   ! brouard  10485:       TnsdVar[Tvar[k]]=nsd;
1.234     brouard  10486:       TvarF[ncovf]=Tvar[k];
                   10487:       TvarFind[ncovf]=k;
                   10488:       TvarFD[ncoveff]=Tvar[k]; /* TvarFD[1]=V1 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
                   10489:       TvarFDind[ncoveff]=k; /* TvarFDind[1]=9 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
                   10490:     }else if( Tvar[k] <=ncovcol &&  Typevar[k]==2){ /* Product of fixed dummy (<=ncovcol) covariates */
                   10491:       Fixed[k]= 0;
                   10492:       Dummy[k]= 0;
                   10493:       ncoveff++;
                   10494:       ncovf++;
                   10495:       modell[k].maintype= FTYPE;
                   10496:       TvarF[ncovf]=Tvar[k];
1.330   ! brouard  10497:       /* TnsdVar[Tvar[k]]=nsd; */ /* To be done */
1.234     brouard  10498:       TvarFind[ncovf]=k;
1.230     brouard  10499:       TvarFD[ncoveff]=Tvar[k]; /* TvarFD[1]=V1 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
1.231     brouard  10500:       TvarFDind[ncoveff]=k; /* TvarFDind[1]=9 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
1.240     brouard  10501:     }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  10502:       Fixed[k]= 0;
                   10503:       Dummy[k]= 1;
1.230     brouard  10504:       nqfveff++;
1.234     brouard  10505:       modell[k].maintype= FTYPE;
                   10506:       modell[k].subtype= FQ;
                   10507:       nsq++;
                   10508:       TvarsQ[nsq]=Tvar[k];
                   10509:       TvarsQind[nsq]=k;
1.232     brouard  10510:       ncovf++;
1.234     brouard  10511:       TvarF[ncovf]=Tvar[k];
                   10512:       TvarFind[ncovf]=k;
1.231     brouard  10513:       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  10514:       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  10515:     }else if( Tvar[k] <=ncovcol+nqv+ntv && Typevar[k]==0){/* Only simple time varying dummy variables */
1.227     brouard  10516:       Fixed[k]= 1;
                   10517:       Dummy[k]= 0;
1.225     brouard  10518:       ntveff++; /* Only simple time varying dummy variable */
1.234     brouard  10519:       modell[k].maintype= VTYPE;
                   10520:       modell[k].subtype= VD;
                   10521:       nsd++;
                   10522:       TvarsD[nsd]=Tvar[k];
                   10523:       TvarsDind[nsd]=k;
1.330   ! brouard  10524:       TnsdVar[Tvar[k]]=nsd; /* To be verified */
1.234     brouard  10525:       ncovv++; /* Only simple time varying variables */
                   10526:       TvarV[ncovv]=Tvar[k];
1.242     brouard  10527:       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  10528:       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 */
                   10529:       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  10530:       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);
                   10531:       printf("Quasi TmodelInvind[%d]=%d\n",k,Tvar[k]- ncovcol-nqv);
1.231     brouard  10532:     }else if( Tvar[k] <=ncovcol+nqv+ntv+nqtv  && Typevar[k]==0){ /* Only simple time varying quantitative variable V5*/
1.234     brouard  10533:       Fixed[k]= 1;
                   10534:       Dummy[k]= 1;
                   10535:       nqtveff++;
                   10536:       modell[k].maintype= VTYPE;
                   10537:       modell[k].subtype= VQ;
                   10538:       ncovv++; /* Only simple time varying variables */
                   10539:       nsq++;
1.319     brouard  10540:       TvarsQ[nsq]=Tvar[k]; /* k=1 Tvar=5 nsq=1 TvarsQ[1]=5 */
1.234     brouard  10541:       TvarsQind[nsq]=k;
                   10542:       TvarV[ncovv]=Tvar[k];
1.242     brouard  10543:       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  10544:       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 */
                   10545:       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  10546:       TmodelInvQind[nqtveff]=Tvar[k]- ncovcol-nqv-ntv;/* Only simple time varying quantitative variable */
                   10547:       /* Tmodeliqind[k]=nqtveff;/\* Only simple time varying quantitative variable *\/ */
                   10548:       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  10549:       printf("Quasi TmodelInvQind[%d]=%d\n",k,Tvar[k]- ncovcol-nqv-ntv);
1.227     brouard  10550:     }else if (Typevar[k] == 1) {  /* product with age */
1.234     brouard  10551:       ncova++;
                   10552:       TvarA[ncova]=Tvar[k];
                   10553:       TvarAind[ncova]=k;
1.231     brouard  10554:       if (Tvar[k] <=ncovcol ){ /* Product age with fixed dummy covariatee */
1.240     brouard  10555:        Fixed[k]= 2;
                   10556:        Dummy[k]= 2;
                   10557:        modell[k].maintype= ATYPE;
                   10558:        modell[k].subtype= APFD;
                   10559:        /* ncoveff++; */
1.227     brouard  10560:       }else if( Tvar[k] <=ncovcol+nqv) { /* Remind that product Vn*Vm are added in k*/
1.240     brouard  10561:        Fixed[k]= 2;
                   10562:        Dummy[k]= 3;
                   10563:        modell[k].maintype= ATYPE;
                   10564:        modell[k].subtype= APFQ;                /*      Product age * fixed quantitative */
                   10565:        /* nqfveff++;  /\* Only simple fixed quantitative variable *\/ */
1.227     brouard  10566:       }else if( Tvar[k] <=ncovcol+nqv+ntv ){
1.240     brouard  10567:        Fixed[k]= 3;
                   10568:        Dummy[k]= 2;
                   10569:        modell[k].maintype= ATYPE;
                   10570:        modell[k].subtype= APVD;                /*      Product age * varying dummy */
                   10571:        /* ntveff++; /\* Only simple time varying dummy variable *\/ */
1.227     brouard  10572:       }else if( Tvar[k] <=ncovcol+nqv+ntv+nqtv){
1.240     brouard  10573:        Fixed[k]= 3;
                   10574:        Dummy[k]= 3;
                   10575:        modell[k].maintype= ATYPE;
                   10576:        modell[k].subtype= APVQ;                /*      Product age * varying quantitative */
                   10577:        /* nqtveff++;/\* Only simple time varying quantitative variable *\/ */
1.227     brouard  10578:       }
                   10579:     }else if (Typevar[k] == 2) {  /* product without age */
                   10580:       k1=Tposprod[k];
                   10581:       if(Tvard[k1][1] <=ncovcol){
1.240     brouard  10582:        if(Tvard[k1][2] <=ncovcol){
                   10583:          Fixed[k]= 1;
                   10584:          Dummy[k]= 0;
                   10585:          modell[k].maintype= FTYPE;
                   10586:          modell[k].subtype= FPDD;              /*      Product fixed dummy * fixed dummy */
                   10587:          ncovf++; /* Fixed variables without age */
                   10588:          TvarF[ncovf]=Tvar[k];
                   10589:          TvarFind[ncovf]=k;
                   10590:        }else if(Tvard[k1][2] <=ncovcol+nqv){
                   10591:          Fixed[k]= 0;  /* or 2 ?*/
                   10592:          Dummy[k]= 1;
                   10593:          modell[k].maintype= FTYPE;
                   10594:          modell[k].subtype= FPDQ;              /*      Product fixed dummy * fixed quantitative */
                   10595:          ncovf++; /* Varying variables without age */
                   10596:          TvarF[ncovf]=Tvar[k];
                   10597:          TvarFind[ncovf]=k;
                   10598:        }else if(Tvard[k1][2] <=ncovcol+nqv+ntv){
                   10599:          Fixed[k]= 1;
                   10600:          Dummy[k]= 0;
                   10601:          modell[k].maintype= VTYPE;
                   10602:          modell[k].subtype= VPDD;              /*      Product fixed dummy * varying dummy */
                   10603:          ncovv++; /* Varying variables without age */
                   10604:          TvarV[ncovv]=Tvar[k];
                   10605:          TvarVind[ncovv]=k;
                   10606:        }else if(Tvard[k1][2] <=ncovcol+nqv+ntv+nqtv){
                   10607:          Fixed[k]= 1;
                   10608:          Dummy[k]= 1;
                   10609:          modell[k].maintype= VTYPE;
                   10610:          modell[k].subtype= VPDQ;              /*      Product fixed dummy * varying quantitative */
                   10611:          ncovv++; /* Varying variables without age */
                   10612:          TvarV[ncovv]=Tvar[k];
                   10613:          TvarVind[ncovv]=k;
                   10614:        }
1.227     brouard  10615:       }else if(Tvard[k1][1] <=ncovcol+nqv){
1.240     brouard  10616:        if(Tvard[k1][2] <=ncovcol){
                   10617:          Fixed[k]= 0;  /* or 2 ?*/
                   10618:          Dummy[k]= 1;
                   10619:          modell[k].maintype= FTYPE;
                   10620:          modell[k].subtype= FPDQ;              /*      Product fixed quantitative * fixed dummy */
                   10621:          ncovf++; /* Fixed variables without age */
                   10622:          TvarF[ncovf]=Tvar[k];
                   10623:          TvarFind[ncovf]=k;
                   10624:        }else if(Tvard[k1][2] <=ncovcol+nqv+ntv){
                   10625:          Fixed[k]= 1;
                   10626:          Dummy[k]= 1;
                   10627:          modell[k].maintype= VTYPE;
                   10628:          modell[k].subtype= VPDQ;              /*      Product fixed quantitative * varying dummy */
                   10629:          ncovv++; /* Varying variables without age */
                   10630:          TvarV[ncovv]=Tvar[k];
                   10631:          TvarVind[ncovv]=k;
                   10632:        }else if(Tvard[k1][2] <=ncovcol+nqv+ntv+nqtv){
                   10633:          Fixed[k]= 1;
                   10634:          Dummy[k]= 1;
                   10635:          modell[k].maintype= VTYPE;
                   10636:          modell[k].subtype= VPQQ;              /*      Product fixed quantitative * varying quantitative */
                   10637:          ncovv++; /* Varying variables without age */
                   10638:          TvarV[ncovv]=Tvar[k];
                   10639:          TvarVind[ncovv]=k;
                   10640:          ncovv++; /* Varying variables without age */
                   10641:          TvarV[ncovv]=Tvar[k];
                   10642:          TvarVind[ncovv]=k;
                   10643:        }
1.227     brouard  10644:       }else if(Tvard[k1][1] <=ncovcol+nqv+ntv){
1.240     brouard  10645:        if(Tvard[k1][2] <=ncovcol){
                   10646:          Fixed[k]= 1;
                   10647:          Dummy[k]= 1;
                   10648:          modell[k].maintype= VTYPE;
                   10649:          modell[k].subtype= VPDD;              /*      Product time varying dummy * fixed dummy */
                   10650:          ncovv++; /* Varying variables without age */
                   10651:          TvarV[ncovv]=Tvar[k];
                   10652:          TvarVind[ncovv]=k;
                   10653:        }else if(Tvard[k1][2] <=ncovcol+nqv){
                   10654:          Fixed[k]= 1;
                   10655:          Dummy[k]= 1;
                   10656:          modell[k].maintype= VTYPE;
                   10657:          modell[k].subtype= VPDQ;              /*      Product time varying dummy * fixed quantitative */
                   10658:          ncovv++; /* Varying variables without age */
                   10659:          TvarV[ncovv]=Tvar[k];
                   10660:          TvarVind[ncovv]=k;
                   10661:        }else if(Tvard[k1][2] <=ncovcol+nqv+ntv){
                   10662:          Fixed[k]= 1;
                   10663:          Dummy[k]= 0;
                   10664:          modell[k].maintype= VTYPE;
                   10665:          modell[k].subtype= VPDD;              /*      Product time varying dummy * time varying dummy */
                   10666:          ncovv++; /* Varying variables without age */
                   10667:          TvarV[ncovv]=Tvar[k];
                   10668:          TvarVind[ncovv]=k;
                   10669:        }else if(Tvard[k1][2] <=ncovcol+nqv+ntv+nqtv){
                   10670:          Fixed[k]= 1;
                   10671:          Dummy[k]= 1;
                   10672:          modell[k].maintype= VTYPE;
                   10673:          modell[k].subtype= VPDQ;              /*      Product time varying dummy * time varying quantitative */
                   10674:          ncovv++; /* Varying variables without age */
                   10675:          TvarV[ncovv]=Tvar[k];
                   10676:          TvarVind[ncovv]=k;
                   10677:        }
1.227     brouard  10678:       }else if(Tvard[k1][1] <=ncovcol+nqv+ntv+nqtv){
1.240     brouard  10679:        if(Tvard[k1][2] <=ncovcol){
                   10680:          Fixed[k]= 1;
                   10681:          Dummy[k]= 1;
                   10682:          modell[k].maintype= VTYPE;
                   10683:          modell[k].subtype= VPDQ;              /*      Product time varying quantitative * fixed dummy */
                   10684:          ncovv++; /* Varying variables without age */
                   10685:          TvarV[ncovv]=Tvar[k];
                   10686:          TvarVind[ncovv]=k;
                   10687:        }else if(Tvard[k1][2] <=ncovcol+nqv){
                   10688:          Fixed[k]= 1;
                   10689:          Dummy[k]= 1;
                   10690:          modell[k].maintype= VTYPE;
                   10691:          modell[k].subtype= VPQQ;              /*      Product time varying quantitative * fixed quantitative */
                   10692:          ncovv++; /* Varying variables without age */
                   10693:          TvarV[ncovv]=Tvar[k];
                   10694:          TvarVind[ncovv]=k;
                   10695:        }else if(Tvard[k1][2] <=ncovcol+nqv+ntv){
                   10696:          Fixed[k]= 1;
                   10697:          Dummy[k]= 1;
                   10698:          modell[k].maintype= VTYPE;
                   10699:          modell[k].subtype= VPDQ;              /*      Product time varying quantitative * time varying dummy */
                   10700:          ncovv++; /* Varying variables without age */
                   10701:          TvarV[ncovv]=Tvar[k];
                   10702:          TvarVind[ncovv]=k;
                   10703:        }else if(Tvard[k1][2] <=ncovcol+nqv+ntv+nqtv){
                   10704:          Fixed[k]= 1;
                   10705:          Dummy[k]= 1;
                   10706:          modell[k].maintype= VTYPE;
                   10707:          modell[k].subtype= VPQQ;              /*      Product time varying quantitative * time varying quantitative */
                   10708:          ncovv++; /* Varying variables without age */
                   10709:          TvarV[ncovv]=Tvar[k];
                   10710:          TvarVind[ncovv]=k;
                   10711:        }
1.227     brouard  10712:       }else{
1.240     brouard  10713:        printf("Error unknown type of covariate: Tvard[%d][1]=%d,Tvard[%d][2]=%d\n",k1,Tvard[k1][1],k1,Tvard[k1][2]);
                   10714:        fprintf(ficlog,"Error unknown type of covariate: Tvard[%d][1]=%d,Tvard[%d][2]=%d\n",k1,Tvard[k1][1],k1,Tvard[k1][2]);
                   10715:       } /*end k1*/
1.225     brouard  10716:     }else{
1.226     brouard  10717:       printf("Error, current version can't treat for performance reasons, Tvar[%d]=%d, Typevar[%d]=%d\n", k, Tvar[k], k, Typevar[k]);
                   10718:       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  10719:     }
1.227     brouard  10720:     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  10721:     printf("           modell[%d].maintype=%d, modell[%d].subtype=%d\n",k,modell[k].maintype,k,modell[k].subtype);
1.227     brouard  10722:     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]);
                   10723:   }
                   10724:   /* Searching for doublons in the model */
                   10725:   for(k1=1; k1<= cptcovt;k1++){
                   10726:     for(k2=1; k2 <k1;k2++){
1.285     brouard  10727:       /* if((Typevar[k1]==Typevar[k2]) && (Fixed[Tvar[k1]]==Fixed[Tvar[k2]]) && (Dummy[Tvar[k1]]==Dummy[Tvar[k2]] )){ */
                   10728:       if((Typevar[k1]==Typevar[k2]) && (Fixed[k1]==Fixed[k2]) && (Dummy[k1]==Dummy[k2] )){
1.234     brouard  10729:        if((Typevar[k1] == 0 || Typevar[k1] == 1)){ /* Simple or age product */
                   10730:          if(Tvar[k1]==Tvar[k2]){
1.285     brouard  10731:            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]);
                   10732:            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  10733:            return(1);
                   10734:          }
                   10735:        }else if (Typevar[k1] ==2){
                   10736:          k3=Tposprod[k1];
                   10737:          k4=Tposprod[k2];
                   10738:          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])) ){
                   10739:            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]]);
                   10740:            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);
                   10741:            return(1);
                   10742:          }
                   10743:        }
1.227     brouard  10744:       }
                   10745:     }
1.225     brouard  10746:   }
                   10747:   printf("ncoveff=%d, nqfveff=%d, ntveff=%d, nqtveff=%d, cptcovn=%d\n",ncoveff,nqfveff,ntveff,nqtveff,cptcovn);
                   10748:   fprintf(ficlog,"ncoveff=%d, nqfveff=%d, ntveff=%d, nqtveff=%d, cptcovn=%d\n",ncoveff,nqfveff,ntveff,nqtveff,cptcovn);
1.234     brouard  10749:   printf("ncovf=%d, ncovv=%d, ncova=%d, nsd=%d, nsq=%d\n",ncovf,ncovv,ncova,nsd,nsq);
                   10750:   fprintf(ficlog,"ncovf=%d, ncovv=%d, ncova=%d, nsd=%d, nsq=%d\n",ncovf,ncovv,ncova,nsd, nsq);
1.137     brouard  10751:   return (0); /* with covar[new additional covariate if product] and Tage if age */ 
1.164     brouard  10752:   /*endread:*/
1.225     brouard  10753:   printf("Exiting decodemodel: ");
                   10754:   return (1);
1.136     brouard  10755: }
                   10756: 
1.169     brouard  10757: int calandcheckages(int imx, int maxwav, double *agemin, double *agemax, int *nberr, int *nbwarn )
1.248     brouard  10758: {/* Check ages at death */
1.136     brouard  10759:   int i, m;
1.218     brouard  10760:   int firstone=0;
                   10761:   
1.136     brouard  10762:   for (i=1; i<=imx; i++) {
                   10763:     for(m=2; (m<= maxwav); m++) {
                   10764:       if (((int)mint[m][i]== 99) && (s[m][i] <= nlstate)){
                   10765:        anint[m][i]=9999;
1.216     brouard  10766:        if (s[m][i] != -2) /* Keeping initial status of unknown vital status */
                   10767:          s[m][i]=-1;
1.136     brouard  10768:       }
                   10769:       if((int)moisdc[i]==99 && (int)andc[i]==9999 && s[m][i]>nlstate){
1.260     brouard  10770:        *nberr = *nberr + 1;
1.218     brouard  10771:        if(firstone == 0){
                   10772:          firstone=1;
1.260     brouard  10773:        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  10774:        }
1.262     brouard  10775:        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  10776:        s[m][i]=-1;  /* Droping the death status */
1.136     brouard  10777:       }
                   10778:       if((int)moisdc[i]==99 && (int)andc[i]!=9999 && s[m][i]>nlstate){
1.169     brouard  10779:        (*nberr)++;
1.259     brouard  10780:        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  10781:        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  10782:        s[m][i]=-2; /* We prefer to skip it (and to skip it in version 0.8a1 too */
1.136     brouard  10783:       }
                   10784:     }
                   10785:   }
                   10786: 
                   10787:   for (i=1; i<=imx; i++)  {
                   10788:     agedc[i]=(moisdc[i]/12.+andc[i])-(moisnais[i]/12.+annais[i]);
                   10789:     for(m=firstpass; (m<= lastpass); m++){
1.214     brouard  10790:       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  10791:        if (s[m][i] >= nlstate+1) {
1.169     brouard  10792:          if(agedc[i]>0){
                   10793:            if((int)moisdc[i]!=99 && (int)andc[i]!=9999){
1.136     brouard  10794:              agev[m][i]=agedc[i];
1.214     brouard  10795:              /*if(moisdc[i]==99 && andc[i]==9999) s[m][i]=-1;*/
1.169     brouard  10796:            }else {
1.136     brouard  10797:              if ((int)andc[i]!=9999){
                   10798:                nbwarn++;
                   10799:                printf("Warning negative age at death: %ld line:%d\n",num[i],i);
                   10800:                fprintf(ficlog,"Warning negative age at death: %ld line:%d\n",num[i],i);
                   10801:                agev[m][i]=-1;
                   10802:              }
                   10803:            }
1.169     brouard  10804:          } /* agedc > 0 */
1.214     brouard  10805:        } /* end if */
1.136     brouard  10806:        else if(s[m][i] !=9){ /* Standard case, age in fractional
                   10807:                                 years but with the precision of a month */
                   10808:          agev[m][i]=(mint[m][i]/12.+1./24.+anint[m][i])-(moisnais[i]/12.+1./24.+annais[i]);
                   10809:          if((int)mint[m][i]==99 || (int)anint[m][i]==9999)
                   10810:            agev[m][i]=1;
                   10811:          else if(agev[m][i] < *agemin){ 
                   10812:            *agemin=agev[m][i];
                   10813:            printf(" Min anint[%d][%d]=%.2f annais[%d]=%.2f, agemin=%.2f\n",m,i,anint[m][i], i,annais[i], *agemin);
                   10814:          }
                   10815:          else if(agev[m][i] >*agemax){
                   10816:            *agemax=agev[m][i];
1.156     brouard  10817:            /* printf(" Max anint[%d][%d]=%.0f annais[%d]=%.0f, agemax=%.2f\n",m,i,anint[m][i], i,annais[i], *agemax);*/
1.136     brouard  10818:          }
                   10819:          /*agev[m][i]=anint[m][i]-annais[i];*/
                   10820:          /*     agev[m][i] = age[i]+2*m;*/
1.214     brouard  10821:        } /* en if 9*/
1.136     brouard  10822:        else { /* =9 */
1.214     brouard  10823:          /* printf("Debug num[%d]=%ld s[%d][%d]=%d\n",i,num[i], m,i, s[m][i]); */
1.136     brouard  10824:          agev[m][i]=1;
                   10825:          s[m][i]=-1;
                   10826:        }
                   10827:       }
1.214     brouard  10828:       else if(s[m][i]==0) /*= 0 Unknown */
1.136     brouard  10829:        agev[m][i]=1;
1.214     brouard  10830:       else{
                   10831:        printf("Warning, num[%d]=%ld, s[%d][%d]=%d\n", i, num[i], m, i,s[m][i]); 
                   10832:        fprintf(ficlog, "Warning, num[%d]=%ld, s[%d][%d]=%d\n", i, num[i], m, i,s[m][i]); 
                   10833:        agev[m][i]=0;
                   10834:       }
                   10835:     } /* End for lastpass */
                   10836:   }
1.136     brouard  10837:     
                   10838:   for (i=1; i<=imx; i++)  {
                   10839:     for(m=firstpass; (m<=lastpass); m++){
                   10840:       if (s[m][i] > (nlstate+ndeath)) {
1.169     brouard  10841:        (*nberr)++;
1.136     brouard  10842:        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);     
                   10843:        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);     
                   10844:        return 1;
                   10845:       }
                   10846:     }
                   10847:   }
                   10848: 
                   10849:   /*for (i=1; i<=imx; i++){
                   10850:   for (m=firstpass; (m<lastpass); m++){
                   10851:      printf("%ld %d %.lf %d %d\n", num[i],(covar[1][i]),agev[m][i],s[m][i],s[m+1][i]);
                   10852: }
                   10853: 
                   10854: }*/
                   10855: 
                   10856: 
1.139     brouard  10857:   printf("Total number of individuals= %d, Agemin = %.2f, Agemax= %.2f\n\n", imx, *agemin, *agemax);
                   10858:   fprintf(ficlog,"Total number of individuals= %d, Agemin = %.2f, Agemax= %.2f\n\n", imx, *agemin, *agemax); 
1.136     brouard  10859: 
                   10860:   return (0);
1.164     brouard  10861:  /* endread:*/
1.136     brouard  10862:     printf("Exiting calandcheckages: ");
                   10863:     return (1);
                   10864: }
                   10865: 
1.172     brouard  10866: #if defined(_MSC_VER)
                   10867: /*printf("Visual C++ compiler: %s \n;", _MSC_FULL_VER);*/
                   10868: /*fprintf(ficlog, "Visual C++ compiler: %s \n;", _MSC_FULL_VER);*/
                   10869: //#include "stdafx.h"
                   10870: //#include <stdio.h>
                   10871: //#include <tchar.h>
                   10872: //#include <windows.h>
                   10873: //#include <iostream>
                   10874: typedef BOOL(WINAPI *LPFN_ISWOW64PROCESS) (HANDLE, PBOOL);
                   10875: 
                   10876: LPFN_ISWOW64PROCESS fnIsWow64Process;
                   10877: 
                   10878: BOOL IsWow64()
                   10879: {
                   10880:        BOOL bIsWow64 = FALSE;
                   10881: 
                   10882:        //typedef BOOL (APIENTRY *LPFN_ISWOW64PROCESS)
                   10883:        //  (HANDLE, PBOOL);
                   10884: 
                   10885:        //LPFN_ISWOW64PROCESS fnIsWow64Process;
                   10886: 
                   10887:        HMODULE module = GetModuleHandle(_T("kernel32"));
                   10888:        const char funcName[] = "IsWow64Process";
                   10889:        fnIsWow64Process = (LPFN_ISWOW64PROCESS)
                   10890:                GetProcAddress(module, funcName);
                   10891: 
                   10892:        if (NULL != fnIsWow64Process)
                   10893:        {
                   10894:                if (!fnIsWow64Process(GetCurrentProcess(),
                   10895:                        &bIsWow64))
                   10896:                        //throw std::exception("Unknown error");
                   10897:                        printf("Unknown error\n");
                   10898:        }
                   10899:        return bIsWow64 != FALSE;
                   10900: }
                   10901: #endif
1.177     brouard  10902: 
1.191     brouard  10903: void syscompilerinfo(int logged)
1.292     brouard  10904: {
                   10905: #include <stdint.h>
                   10906: 
                   10907:   /* #include "syscompilerinfo.h"*/
1.185     brouard  10908:    /* command line Intel compiler 32bit windows, XP compatible:*/
                   10909:    /* /GS /W3 /Gy
                   10910:       /Zc:wchar_t /Zi /O2 /Fd"Release\vc120.pdb" /D "WIN32" /D "NDEBUG" /D
                   10911:       "_CONSOLE" /D "_LIB" /D "_USING_V110_SDK71_" /D "_UNICODE" /D
                   10912:       "UNICODE" /Qipo /Zc:forScope /Gd /Oi /MT /Fa"Release\" /EHsc /nologo
1.186     brouard  10913:       /Fo"Release\" /Qprof-dir "Release\" /Fp"Release\IMaCh.pch"
                   10914:    */ 
                   10915:    /* 64 bits */
1.185     brouard  10916:    /*
                   10917:      /GS /W3 /Gy
                   10918:      /Zc:wchar_t /Zi /O2 /Fd"x64\Release\vc120.pdb" /D "WIN32" /D "NDEBUG"
                   10919:      /D "_CONSOLE" /D "_LIB" /D "_UNICODE" /D "UNICODE" /Qipo /Zc:forScope
                   10920:      /Oi /MD /Fa"x64\Release\" /EHsc /nologo /Fo"x64\Release\" /Qprof-dir
                   10921:      "x64\Release\" /Fp"x64\Release\IMaCh.pch" */
                   10922:    /* Optimization are useless and O3 is slower than O2 */
                   10923:    /*
                   10924:      /GS /W3 /Gy /Zc:wchar_t /Zi /O3 /Fd"x64\Release\vc120.pdb" /D "WIN32" 
                   10925:      /D "NDEBUG" /D "_CONSOLE" /D "_LIB" /D "_UNICODE" /D "UNICODE" /Qipo 
                   10926:      /Zc:forScope /Oi /MD /Fa"x64\Release\" /EHsc /nologo /Qparallel 
                   10927:      /Fo"x64\Release\" /Qprof-dir "x64\Release\" /Fp"x64\Release\IMaCh.pch" 
                   10928:    */
1.186     brouard  10929:    /* Link is */ /* /OUT:"visual studio
1.185     brouard  10930:       2013\Projects\IMaCh\Release\IMaCh.exe" /MANIFEST /NXCOMPAT
                   10931:       /PDB:"visual studio
                   10932:       2013\Projects\IMaCh\Release\IMaCh.pdb" /DYNAMICBASE
                   10933:       "kernel32.lib" "user32.lib" "gdi32.lib" "winspool.lib"
                   10934:       "comdlg32.lib" "advapi32.lib" "shell32.lib" "ole32.lib"
                   10935:       "oleaut32.lib" "uuid.lib" "odbc32.lib" "odbccp32.lib"
                   10936:       /MACHINE:X86 /OPT:REF /SAFESEH /INCREMENTAL:NO
                   10937:       /SUBSYSTEM:CONSOLE",5.01" /MANIFESTUAC:"level='asInvoker'
                   10938:       uiAccess='false'"
                   10939:       /ManifestFile:"Release\IMaCh.exe.intermediate.manifest" /OPT:ICF
                   10940:       /NOLOGO /TLBID:1
                   10941:    */
1.292     brouard  10942: 
                   10943: 
1.177     brouard  10944: #if defined __INTEL_COMPILER
1.178     brouard  10945: #if defined(__GNUC__)
                   10946:        struct utsname sysInfo;  /* For Intel on Linux and OS/X */
                   10947: #endif
1.177     brouard  10948: #elif defined(__GNUC__) 
1.179     brouard  10949: #ifndef  __APPLE__
1.174     brouard  10950: #include <gnu/libc-version.h>  /* Only on gnu */
1.179     brouard  10951: #endif
1.177     brouard  10952:    struct utsname sysInfo;
1.178     brouard  10953:    int cross = CROSS;
                   10954:    if (cross){
                   10955:           printf("Cross-");
1.191     brouard  10956:           if(logged) fprintf(ficlog, "Cross-");
1.178     brouard  10957:    }
1.174     brouard  10958: #endif
                   10959: 
1.191     brouard  10960:    printf("Compiled with:");if(logged)fprintf(ficlog,"Compiled with:");
1.169     brouard  10961: #if defined(__clang__)
1.191     brouard  10962:    printf(" Clang/LLVM");if(logged)fprintf(ficlog," Clang/LLVM");      /* Clang/LLVM. ---------------------------------------------- */
1.169     brouard  10963: #endif
                   10964: #if defined(__ICC) || defined(__INTEL_COMPILER)
1.191     brouard  10965:    printf(" Intel ICC/ICPC");if(logged)fprintf(ficlog," Intel ICC/ICPC");/* Intel ICC/ICPC. ------------------------------------------ */
1.169     brouard  10966: #endif
                   10967: #if defined(__GNUC__) || defined(__GNUG__)
1.191     brouard  10968:    printf(" GNU GCC/G++");if(logged)fprintf(ficlog," GNU GCC/G++");/* GNU GCC/G++. --------------------------------------------- */
1.169     brouard  10969: #endif
                   10970: #if defined(__HP_cc) || defined(__HP_aCC)
1.191     brouard  10971:    printf(" Hewlett-Packard C/aC++");if(logged)fprintf(fcilog," Hewlett-Packard C/aC++"); /* Hewlett-Packard C/aC++. ---------------------------------- */
1.169     brouard  10972: #endif
                   10973: #if defined(__IBMC__) || defined(__IBMCPP__)
1.191     brouard  10974:    printf(" IBM XL C/C++"); if(logged) fprintf(ficlog," IBM XL C/C++");/* IBM XL C/C++. -------------------------------------------- */
1.169     brouard  10975: #endif
                   10976: #if defined(_MSC_VER)
1.191     brouard  10977:    printf(" Microsoft Visual Studio");if(logged)fprintf(ficlog," Microsoft Visual Studio");/* Microsoft Visual Studio. --------------------------------- */
1.169     brouard  10978: #endif
                   10979: #if defined(__PGI)
1.191     brouard  10980:    printf(" Portland Group PGCC/PGCPP");if(logged) fprintf(ficlog," Portland Group PGCC/PGCPP");/* Portland Group PGCC/PGCPP. ------------------------------- */
1.169     brouard  10981: #endif
                   10982: #if defined(__SUNPRO_C) || defined(__SUNPRO_CC)
1.191     brouard  10983:    printf(" Oracle Solaris Studio");if(logged)fprintf(ficlog," Oracle Solaris Studio\n");/* Oracle Solaris Studio. ----------------------------------- */
1.167     brouard  10984: #endif
1.191     brouard  10985:    printf(" for "); if (logged) fprintf(ficlog, " for ");
1.169     brouard  10986:    
1.167     brouard  10987: // http://stackoverflow.com/questions/4605842/how-to-identify-platform-compiler-from-preprocessor-macros
                   10988: #ifdef _WIN32 // note the underscore: without it, it's not msdn official!
                   10989:     // Windows (x64 and x86)
1.191     brouard  10990:    printf("Windows (x64 and x86) ");if(logged) fprintf(ficlog,"Windows (x64 and x86) ");
1.167     brouard  10991: #elif __unix__ // all unices, not all compilers
                   10992:     // Unix
1.191     brouard  10993:    printf("Unix ");if(logged) fprintf(ficlog,"Unix ");
1.167     brouard  10994: #elif __linux__
                   10995:     // linux
1.191     brouard  10996:    printf("linux ");if(logged) fprintf(ficlog,"linux ");
1.167     brouard  10997: #elif __APPLE__
1.174     brouard  10998:     // Mac OS, not sure if this is covered by __posix__ and/or __unix__ though..
1.191     brouard  10999:    printf("Mac OS ");if(logged) fprintf(ficlog,"Mac OS ");
1.167     brouard  11000: #endif
                   11001: 
                   11002: /*  __MINGW32__          */
                   11003: /*  __CYGWIN__  */
                   11004: /* __MINGW64__  */
                   11005: // http://msdn.microsoft.com/en-us/library/b0084kay.aspx
                   11006: /* _MSC_VER  //the Visual C++ compiler is 17.00.51106.1, the _MSC_VER macro evaluates to 1700. Type cl /?  */
                   11007: /* _MSC_FULL_VER //the Visual C++ compiler is 15.00.20706.01, the _MSC_FULL_VER macro evaluates to 150020706 */
                   11008: /* _WIN64  // Defined for applications for Win64. */
                   11009: /* _M_X64 // Defined for compilations that target x64 processors. */
                   11010: /* _DEBUG // Defined when you compile with /LDd, /MDd, and /MTd. */
1.171     brouard  11011: 
1.167     brouard  11012: #if UINTPTR_MAX == 0xffffffff
1.191     brouard  11013:    printf(" 32-bit"); if(logged) fprintf(ficlog," 32-bit");/* 32-bit */
1.167     brouard  11014: #elif UINTPTR_MAX == 0xffffffffffffffff
1.191     brouard  11015:    printf(" 64-bit"); if(logged) fprintf(ficlog," 64-bit");/* 64-bit */
1.167     brouard  11016: #else
1.191     brouard  11017:    printf(" wtf-bit"); if(logged) fprintf(ficlog," wtf-bit");/* wtf */
1.167     brouard  11018: #endif
                   11019: 
1.169     brouard  11020: #if defined(__GNUC__)
                   11021: # if defined(__GNUC_PATCHLEVEL__)
                   11022: #  define __GNUC_VERSION__ (__GNUC__ * 10000 \
                   11023:                             + __GNUC_MINOR__ * 100 \
                   11024:                             + __GNUC_PATCHLEVEL__)
                   11025: # else
                   11026: #  define __GNUC_VERSION__ (__GNUC__ * 10000 \
                   11027:                             + __GNUC_MINOR__ * 100)
                   11028: # endif
1.174     brouard  11029:    printf(" using GNU C version %d.\n", __GNUC_VERSION__);
1.191     brouard  11030:    if(logged) fprintf(ficlog, " using GNU C version %d.\n", __GNUC_VERSION__);
1.176     brouard  11031: 
                   11032:    if (uname(&sysInfo) != -1) {
                   11033:      printf("Running on: %s %s %s %s %s\n",sysInfo.sysname, sysInfo.nodename, sysInfo.release, sysInfo.version, sysInfo.machine);
1.191     brouard  11034:         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  11035:    }
                   11036:    else
                   11037:       perror("uname() error");
1.179     brouard  11038:    //#ifndef __INTEL_COMPILER 
                   11039: #if !defined (__INTEL_COMPILER) && !defined(__APPLE__)
1.174     brouard  11040:    printf("GNU libc version: %s\n", gnu_get_libc_version()); 
1.191     brouard  11041:    if(logged) fprintf(ficlog,"GNU libc version: %s\n", gnu_get_libc_version());
1.177     brouard  11042: #endif
1.169     brouard  11043: #endif
1.172     brouard  11044: 
1.286     brouard  11045:    //   void main ()
1.172     brouard  11046:    //   {
1.169     brouard  11047: #if defined(_MSC_VER)
1.174     brouard  11048:    if (IsWow64()){
1.191     brouard  11049:           printf("\nThe program (probably compiled for 32bit) is running under WOW64 (64bit) emulation.\n");
                   11050:           if (logged) fprintf(ficlog, "\nThe program (probably compiled for 32bit) is running under WOW64 (64bit) emulation.\n");
1.174     brouard  11051:    }
                   11052:    else{
1.191     brouard  11053:           printf("\nThe program is not running under WOW64 (i.e probably on a 64bit Windows).\n");
                   11054:           if (logged) fprintf(ficlog, "\nThe programm is not running under WOW64 (i.e probably on a 64bit Windows).\n");
1.174     brouard  11055:    }
1.172     brouard  11056:    //     printf("\nPress Enter to continue...");
                   11057:    //     getchar();
                   11058:    //   }
                   11059: 
1.169     brouard  11060: #endif
                   11061:    
1.167     brouard  11062: 
1.219     brouard  11063: }
1.136     brouard  11064: 
1.219     brouard  11065: int prevalence_limit(double *p, double **prlim, double ageminpar, double agemaxpar, double ftolpl, int *ncvyearp){
1.288     brouard  11066:   /*--------------- Prevalence limit  (forward period or forward stable prevalence) --------------*/
1.235     brouard  11067:   int i, j, k, i1, k4=0, nres=0 ;
1.202     brouard  11068:   /* double ftolpl = 1.e-10; */
1.180     brouard  11069:   double age, agebase, agelim;
1.203     brouard  11070:   double tot;
1.180     brouard  11071: 
1.202     brouard  11072:   strcpy(filerespl,"PL_");
                   11073:   strcat(filerespl,fileresu);
                   11074:   if((ficrespl=fopen(filerespl,"w"))==NULL) {
1.288     brouard  11075:     printf("Problem with forward period (stable) prevalence resultfile: %s\n", filerespl);return 1;
                   11076:     fprintf(ficlog,"Problem with forward period (stable) prevalence resultfile: %s\n", filerespl);return 1;
1.202     brouard  11077:   }
1.288     brouard  11078:   printf("\nComputing forward period (stable) prevalence: result on file '%s' \n", filerespl);
                   11079:   fprintf(ficlog,"\nComputing forward period (stable) prevalence: result on file '%s' \n", filerespl);
1.202     brouard  11080:   pstamp(ficrespl);
1.288     brouard  11081:   fprintf(ficrespl,"# Forward period (stable) prevalence. Precision given by ftolpl=%g \n", ftolpl);
1.202     brouard  11082:   fprintf(ficrespl,"#Age ");
                   11083:   for(i=1; i<=nlstate;i++) fprintf(ficrespl,"%d-%d ",i,i);
                   11084:   fprintf(ficrespl,"\n");
1.180     brouard  11085:   
1.219     brouard  11086:   /* prlim=matrix(1,nlstate,1,nlstate);*/ /* back in main */
1.180     brouard  11087: 
1.219     brouard  11088:   agebase=ageminpar;
                   11089:   agelim=agemaxpar;
1.180     brouard  11090: 
1.227     brouard  11091:   /* i1=pow(2,ncoveff); */
1.234     brouard  11092:   i1=pow(2,cptcoveff); /* Number of combination of dummy covariates */
1.219     brouard  11093:   if (cptcovn < 1){i1=1;}
1.180     brouard  11094: 
1.238     brouard  11095:   for(k=1; k<=i1;k++){ /* For each combination k of dummy covariates in the model */
                   11096:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.253     brouard  11097:       if(i1 != 1 && TKresult[nres]!= k)
1.238     brouard  11098:        continue;
1.235     brouard  11099: 
1.238     brouard  11100:       /* for(cptcov=1,k=0;cptcov<=i1;cptcov++){ */
                   11101:       /* for(cptcov=1,k=0;cptcov<=1;cptcov++){ */
                   11102:       //for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){
                   11103:       /* k=k+1; */
                   11104:       /* to clean */
                   11105:       //printf("cptcov=%d cptcod=%d codtab=%d\n",cptcov, cptcod,codtabm(cptcod,cptcov));
                   11106:       fprintf(ficrespl,"#******");
                   11107:       printf("#******");
                   11108:       fprintf(ficlog,"#******");
                   11109:       for(j=1;j<=cptcoveff ;j++) {/* all covariates */
1.330   ! brouard  11110:        fprintf(ficrespl," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,Tvaraff[j])]); /* Here problem for varying dummy*/
        !          11111:        printf(" V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,Tvaraff[j])]);
        !          11112:        fprintf(ficlog," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,Tvaraff[j])]);
1.238     brouard  11113:       }
                   11114:       for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
                   11115:        printf(" V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
                   11116:        fprintf(ficrespl," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
                   11117:        fprintf(ficlog," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
                   11118:       }
                   11119:       fprintf(ficrespl,"******\n");
                   11120:       printf("******\n");
                   11121:       fprintf(ficlog,"******\n");
                   11122:       if(invalidvarcomb[k]){
                   11123:        printf("\nCombination (%d) ignored because no case \n",k); 
                   11124:        fprintf(ficrespl,"#Combination (%d) ignored because no case \n",k); 
                   11125:        fprintf(ficlog,"\nCombination (%d) ignored because no case \n",k); 
                   11126:        continue;
                   11127:       }
1.219     brouard  11128: 
1.238     brouard  11129:       fprintf(ficrespl,"#Age ");
                   11130:       for(j=1;j<=cptcoveff;j++) {
1.330   ! brouard  11131:        fprintf(ficrespl,"V%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,Tvaraff[j])]);
1.238     brouard  11132:       }
                   11133:       for(i=1; i<=nlstate;i++) fprintf(ficrespl,"  %d-%d   ",i,i);
                   11134:       fprintf(ficrespl,"Total Years_to_converge\n");
1.227     brouard  11135:     
1.238     brouard  11136:       for (age=agebase; age<=agelim; age++){
                   11137:        /* for (age=agebase; age<=agebase; age++){ */
                   11138:        prevalim(prlim, nlstate, p, age, oldm, savm, ftolpl, ncvyearp, k, nres);
                   11139:        fprintf(ficrespl,"%.0f ",age );
                   11140:        for(j=1;j<=cptcoveff;j++)
1.330   ! brouard  11141:          fprintf(ficrespl,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,Tvaraff[j])]);
1.238     brouard  11142:        tot=0.;
                   11143:        for(i=1; i<=nlstate;i++){
                   11144:          tot +=  prlim[i][i];
                   11145:          fprintf(ficrespl," %.5f", prlim[i][i]);
                   11146:        }
                   11147:        fprintf(ficrespl," %.3f %d\n", tot, *ncvyearp);
                   11148:       } /* Age */
                   11149:       /* was end of cptcod */
                   11150:     } /* cptcov */
                   11151:   } /* nres */
1.219     brouard  11152:   return 0;
1.180     brouard  11153: }
                   11154: 
1.218     brouard  11155: 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  11156:        /*--------------- Back Prevalence limit  (backward stable prevalence) --------------*/
1.218     brouard  11157:        
                   11158:        /* Computes the back prevalence limit  for any combination      of covariate values 
                   11159:    * at any age between ageminpar and agemaxpar
                   11160:         */
1.235     brouard  11161:   int i, j, k, i1, nres=0 ;
1.217     brouard  11162:   /* double ftolpl = 1.e-10; */
                   11163:   double age, agebase, agelim;
                   11164:   double tot;
1.218     brouard  11165:   /* double ***mobaverage; */
                   11166:   /* double     **dnewm, **doldm, **dsavm;  /\* for use *\/ */
1.217     brouard  11167: 
                   11168:   strcpy(fileresplb,"PLB_");
                   11169:   strcat(fileresplb,fileresu);
                   11170:   if((ficresplb=fopen(fileresplb,"w"))==NULL) {
1.288     brouard  11171:     printf("Problem with backward prevalence resultfile: %s\n", fileresplb);return 1;
                   11172:     fprintf(ficlog,"Problem with backward prevalence resultfile: %s\n", fileresplb);return 1;
1.217     brouard  11173:   }
1.288     brouard  11174:   printf("Computing backward prevalence: result on file '%s' \n", fileresplb);
                   11175:   fprintf(ficlog,"Computing backward prevalence: result on file '%s' \n", fileresplb);
1.217     brouard  11176:   pstamp(ficresplb);
1.288     brouard  11177:   fprintf(ficresplb,"# Backward prevalence. Precision given by ftolpl=%g \n", ftolpl);
1.217     brouard  11178:   fprintf(ficresplb,"#Age ");
                   11179:   for(i=1; i<=nlstate;i++) fprintf(ficresplb,"%d-%d ",i,i);
                   11180:   fprintf(ficresplb,"\n");
                   11181:   
1.218     brouard  11182:   
                   11183:   /* prlim=matrix(1,nlstate,1,nlstate);*/ /* back in main */
                   11184:   
                   11185:   agebase=ageminpar;
                   11186:   agelim=agemaxpar;
                   11187:   
                   11188:   
1.227     brouard  11189:   i1=pow(2,cptcoveff);
1.218     brouard  11190:   if (cptcovn < 1){i1=1;}
1.227     brouard  11191:   
1.238     brouard  11192:   for(nres=1; nres <= nresult; nres++){ /* For each resultline */
                   11193:     for(k=1; k<=i1;k++){ /* For any combination of dummy covariates, fixed and varying */
1.253     brouard  11194:      if(i1 != 1 && TKresult[nres]!= k)
1.238     brouard  11195:        continue;
                   11196:       //printf("cptcov=%d cptcod=%d codtab=%d\n",cptcov, cptcod,codtabm(cptcod,cptcov));
                   11197:       fprintf(ficresplb,"#******");
                   11198:       printf("#******");
                   11199:       fprintf(ficlog,"#******");
                   11200:       for(j=1;j<=cptcoveff ;j++) {/* all covariates */
1.330   ! brouard  11201:        fprintf(ficresplb," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,Tvaraff[j])]);
        !          11202:        printf(" V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,Tvaraff[j])]);
        !          11203:        fprintf(ficlog," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,Tvaraff[j])]);
1.238     brouard  11204:       }
                   11205:       for (j=1; j<= nsq; j++){ /* For each selected (single) quantitative value */
                   11206:        printf(" V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]);
                   11207:        fprintf(ficresplb," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]);
                   11208:        fprintf(ficlog," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]);
                   11209:       }
                   11210:       fprintf(ficresplb,"******\n");
                   11211:       printf("******\n");
                   11212:       fprintf(ficlog,"******\n");
                   11213:       if(invalidvarcomb[k]){
                   11214:        printf("\nCombination (%d) ignored because no cases \n",k); 
                   11215:        fprintf(ficresplb,"#Combination (%d) ignored because no cases \n",k); 
                   11216:        fprintf(ficlog,"\nCombination (%d) ignored because no cases \n",k); 
                   11217:        continue;
                   11218:       }
1.218     brouard  11219:     
1.238     brouard  11220:       fprintf(ficresplb,"#Age ");
                   11221:       for(j=1;j<=cptcoveff;j++) {
1.330   ! brouard  11222:        fprintf(ficresplb,"V%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,Tvaraff[j])]);
1.238     brouard  11223:       }
                   11224:       for(i=1; i<=nlstate;i++) fprintf(ficresplb,"  %d-%d   ",i,i);
                   11225:       fprintf(ficresplb,"Total Years_to_converge\n");
1.218     brouard  11226:     
                   11227:     
1.238     brouard  11228:       for (age=agebase; age<=agelim; age++){
                   11229:        /* for (age=agebase; age<=agebase; age++){ */
                   11230:        if(mobilavproj > 0){
                   11231:          /* bprevalim(bprlim, mobaverage, nlstate, p, age, ageminpar, agemaxpar, oldm, savm, doldm, dsavm, ftolpl, ncvyearp, k); */
                   11232:          /* bprevalim(bprlim, mobaverage, nlstate, p, age, oldm, savm, dnewm, doldm, dsavm, ftolpl, ncvyearp, k); */
1.242     brouard  11233:          bprevalim(bprlim, mobaverage, nlstate, p, age, ftolpl, ncvyearp, k, nres);
1.238     brouard  11234:        }else if (mobilavproj == 0){
                   11235:          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);
                   11236:          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);
                   11237:          exit(1);
                   11238:        }else{
                   11239:          /* bprevalim(bprlim, probs, nlstate, p, age, oldm, savm, dnewm, doldm, dsavm, ftolpl, ncvyearp, k); */
1.242     brouard  11240:          bprevalim(bprlim, probs, nlstate, p, age, ftolpl, ncvyearp, k,nres);
1.266     brouard  11241:          /* printf("TOTOT\n"); */
                   11242:           /* exit(1); */
1.238     brouard  11243:        }
                   11244:        fprintf(ficresplb,"%.0f ",age );
                   11245:        for(j=1;j<=cptcoveff;j++)
1.330   ! brouard  11246:          fprintf(ficresplb,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,Tvaraff[j])]);
1.238     brouard  11247:        tot=0.;
                   11248:        for(i=1; i<=nlstate;i++){
                   11249:          tot +=  bprlim[i][i];
                   11250:          fprintf(ficresplb," %.5f", bprlim[i][i]);
                   11251:        }
                   11252:        fprintf(ficresplb," %.3f %d\n", tot, *ncvyearp);
                   11253:       } /* Age */
                   11254:       /* was end of cptcod */
1.255     brouard  11255:       /*fprintf(ficresplb,"\n");*/ /* Seems to be necessary for gnuplot only if two result lines and no covariate. */
1.238     brouard  11256:     } /* end of any combination */
                   11257:   } /* end of nres */  
1.218     brouard  11258:   /* hBijx(p, bage, fage); */
                   11259:   /* fclose(ficrespijb); */
                   11260:   
                   11261:   return 0;
1.217     brouard  11262: }
1.218     brouard  11263:  
1.180     brouard  11264: int hPijx(double *p, int bage, int fage){
                   11265:     /*------------- h Pij x at various ages ------------*/
                   11266: 
                   11267:   int stepsize;
                   11268:   int agelim;
                   11269:   int hstepm;
                   11270:   int nhstepm;
1.235     brouard  11271:   int h, i, i1, j, k, k4, nres=0;
1.180     brouard  11272: 
                   11273:   double agedeb;
                   11274:   double ***p3mat;
                   11275: 
1.201     brouard  11276:     strcpy(filerespij,"PIJ_");  strcat(filerespij,fileresu);
1.180     brouard  11277:     if((ficrespij=fopen(filerespij,"w"))==NULL) {
                   11278:       printf("Problem with Pij resultfile: %s\n", filerespij); return 1;
                   11279:       fprintf(ficlog,"Problem with Pij resultfile: %s\n", filerespij); return 1;
                   11280:     }
                   11281:     printf("Computing pij: result on file '%s' \n", filerespij);
                   11282:     fprintf(ficlog,"Computing pij: result on file '%s' \n", filerespij);
                   11283:   
                   11284:     stepsize=(int) (stepm+YEARM-1)/YEARM;
                   11285:     /*if (stepm<=24) stepsize=2;*/
                   11286: 
                   11287:     agelim=AGESUP;
                   11288:     hstepm=stepsize*YEARM; /* Every year of age */
                   11289:     hstepm=hstepm/stepm; /* Typically 2 years, = 2/6 months = 4 */ 
1.218     brouard  11290:                
1.180     brouard  11291:     /* hstepm=1;   aff par mois*/
                   11292:     pstamp(ficrespij);
                   11293:     fprintf(ficrespij,"#****** h Pij x Probability to be in state j at age x+h being in i at x ");
1.227     brouard  11294:     i1= pow(2,cptcoveff);
1.218     brouard  11295:                /* for(cptcov=1,k=0;cptcov<=i1;cptcov++){ */
                   11296:                /*    /\*for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*\/ */
                   11297:                /*      k=k+1;  */
1.235     brouard  11298:     for(nres=1; nres <= nresult; nres++) /* For each resultline */
                   11299:     for(k=1; k<=i1;k++){
1.253     brouard  11300:       if(i1 != 1 && TKresult[nres]!= k)
1.235     brouard  11301:        continue;
1.183     brouard  11302:       fprintf(ficrespij,"\n#****** ");
1.227     brouard  11303:       for(j=1;j<=cptcoveff;j++) 
1.330   ! brouard  11304:        fprintf(ficrespij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,Tvaraff[j])]);
1.235     brouard  11305:       for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
                   11306:        printf(" V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
                   11307:        fprintf(ficrespij," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
                   11308:       }
1.183     brouard  11309:       fprintf(ficrespij,"******\n");
                   11310:       
                   11311:       for (agedeb=fage; agedeb>=bage; agedeb--){ /* If stepm=6 months */
                   11312:        nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */ 
                   11313:        nhstepm = nhstepm/hstepm; /* Typically 40/4=10 */
                   11314:        
                   11315:        /*        nhstepm=nhstepm*YEARM; aff par mois*/
1.180     brouard  11316:        
1.183     brouard  11317:        p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   11318:        oldm=oldms;savm=savms;
1.235     brouard  11319:        hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k, nres);  
1.183     brouard  11320:        fprintf(ficrespij,"# Cov Agex agex+h hpijx with i,j=");
                   11321:        for(i=1; i<=nlstate;i++)
                   11322:          for(j=1; j<=nlstate+ndeath;j++)
                   11323:            fprintf(ficrespij," %1d-%1d",i,j);
                   11324:        fprintf(ficrespij,"\n");
                   11325:        for (h=0; h<=nhstepm; h++){
                   11326:          /*agedebphstep = agedeb + h*hstepm/YEARM*stepm;*/
                   11327:          fprintf(ficrespij,"%d %3.f %3.f",k, agedeb, agedeb + h*hstepm/YEARM*stepm );
1.180     brouard  11328:          for(i=1; i<=nlstate;i++)
                   11329:            for(j=1; j<=nlstate+ndeath;j++)
1.183     brouard  11330:              fprintf(ficrespij," %.5f", p3mat[i][j][h]);
1.180     brouard  11331:          fprintf(ficrespij,"\n");
                   11332:        }
1.183     brouard  11333:        free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   11334:        fprintf(ficrespij,"\n");
                   11335:       }
1.180     brouard  11336:       /*}*/
                   11337:     }
1.218     brouard  11338:     return 0;
1.180     brouard  11339: }
1.218     brouard  11340:  
                   11341:  int hBijx(double *p, int bage, int fage, double ***prevacurrent){
1.217     brouard  11342:     /*------------- h Bij x at various ages ------------*/
                   11343: 
                   11344:   int stepsize;
1.218     brouard  11345:   /* int agelim; */
                   11346:        int ageminl;
1.217     brouard  11347:   int hstepm;
                   11348:   int nhstepm;
1.238     brouard  11349:   int h, i, i1, j, k, nres;
1.218     brouard  11350:        
1.217     brouard  11351:   double agedeb;
                   11352:   double ***p3mat;
1.218     brouard  11353:        
                   11354:   strcpy(filerespijb,"PIJB_");  strcat(filerespijb,fileresu);
                   11355:   if((ficrespijb=fopen(filerespijb,"w"))==NULL) {
                   11356:     printf("Problem with Pij back resultfile: %s\n", filerespijb); return 1;
                   11357:     fprintf(ficlog,"Problem with Pij back resultfile: %s\n", filerespijb); return 1;
                   11358:   }
                   11359:   printf("Computing pij back: result on file '%s' \n", filerespijb);
                   11360:   fprintf(ficlog,"Computing pij back: result on file '%s' \n", filerespijb);
                   11361:   
                   11362:   stepsize=(int) (stepm+YEARM-1)/YEARM;
                   11363:   /*if (stepm<=24) stepsize=2;*/
1.217     brouard  11364:   
1.218     brouard  11365:   /* agelim=AGESUP; */
1.289     brouard  11366:   ageminl=AGEINF; /* was 30 */
1.218     brouard  11367:   hstepm=stepsize*YEARM; /* Every year of age */
                   11368:   hstepm=hstepm/stepm; /* Typically 2 years, = 2/6 months = 4 */
                   11369:   
                   11370:   /* hstepm=1;   aff par mois*/
                   11371:   pstamp(ficrespijb);
1.255     brouard  11372:   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  11373:   i1= pow(2,cptcoveff);
1.218     brouard  11374:   /* for(cptcov=1,k=0;cptcov<=i1;cptcov++){ */
                   11375:   /*    /\*for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*\/ */
                   11376:   /*   k=k+1;  */
1.238     brouard  11377:   for(nres=1; nres <= nresult; nres++){ /* For each resultline */
                   11378:     for(k=1; k<=i1;k++){ /* For any combination of dummy covariates, fixed and varying */
1.253     brouard  11379:       if(i1 != 1 && TKresult[nres]!= k)
1.238     brouard  11380:        continue;
                   11381:       fprintf(ficrespijb,"\n#****** ");
                   11382:       for(j=1;j<=cptcoveff;j++)
1.330   ! brouard  11383:        fprintf(ficrespijb,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,Tvaraff[j])]);
1.238     brouard  11384:       for (j=1; j<= nsq; j++){ /* For each selected (single) quantitative value */
                   11385:        fprintf(ficrespijb," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]);
                   11386:       }
                   11387:       fprintf(ficrespijb,"******\n");
1.264     brouard  11388:       if(invalidvarcomb[k]){  /* Is it necessary here? */
1.238     brouard  11389:        fprintf(ficrespijb,"\n#Combination (%d) ignored because no cases \n",k); 
                   11390:        continue;
                   11391:       }
                   11392:       
                   11393:       /* for (agedeb=fage; agedeb>=bage; agedeb--){ /\* If stepm=6 months *\/ */
                   11394:       for (agedeb=bage; agedeb<=fage; agedeb++){ /* If stepm=6 months and estepm=24 (2 years) */
                   11395:        /* nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm); /\* Typically 20 years = 20*12/6=40 *\/ */
1.297     brouard  11396:        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 */
                   11397:        nhstepm = nhstepm/hstepm; /* Typically 40/4=10, because estepm=24 stepm=6 => hstepm=24/6=4 or 28*/
1.238     brouard  11398:        
                   11399:        /*        nhstepm=nhstepm*YEARM; aff par mois*/
                   11400:        
1.266     brouard  11401:        p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm); /* We can't have it at an upper level because of nhstepm */
                   11402:        /* and memory limitations if stepm is small */
                   11403: 
1.238     brouard  11404:        /* oldm=oldms;savm=savms; */
                   11405:        /* hbxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);   */
1.325     brouard  11406:        hbxij(p3mat,nhstepm,agedeb,hstepm,p,prevacurrent,nlstate,stepm, k, nres);/* Bug valgrind */
1.238     brouard  11407:        /* hbxij(p3mat,nhstepm,agedeb,hstepm,p,prevacurrent,nlstate,stepm,oldm,savm, dnewm, doldm, dsavm, k); */
1.255     brouard  11408:        fprintf(ficrespijb,"# Cov Agex agex-h hbijx with i,j=");
1.217     brouard  11409:        for(i=1; i<=nlstate;i++)
                   11410:          for(j=1; j<=nlstate+ndeath;j++)
1.238     brouard  11411:            fprintf(ficrespijb," %1d-%1d",i,j);
1.217     brouard  11412:        fprintf(ficrespijb,"\n");
1.238     brouard  11413:        for (h=0; h<=nhstepm; h++){
                   11414:          /*agedebphstep = agedeb + h*hstepm/YEARM*stepm;*/
                   11415:          fprintf(ficrespijb,"%d %3.f %3.f",k, agedeb, agedeb - h*hstepm/YEARM*stepm );
                   11416:          /* fprintf(ficrespijb,"%d %3.f %3.f",k, agedeb, agedeb + h*hstepm/YEARM*stepm ); */
                   11417:          for(i=1; i<=nlstate;i++)
                   11418:            for(j=1; j<=nlstate+ndeath;j++)
1.325     brouard  11419:              fprintf(ficrespijb," %.5f", p3mat[i][j][h]);/* Bug valgrind */
1.238     brouard  11420:          fprintf(ficrespijb,"\n");
                   11421:        }
                   11422:        free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   11423:        fprintf(ficrespijb,"\n");
                   11424:       } /* end age deb */
                   11425:     } /* end combination */
                   11426:   } /* end nres */
1.218     brouard  11427:   return 0;
                   11428:  } /*  hBijx */
1.217     brouard  11429: 
1.180     brouard  11430: 
1.136     brouard  11431: /***********************************************/
                   11432: /**************** Main Program *****************/
                   11433: /***********************************************/
                   11434: 
                   11435: int main(int argc, char *argv[])
                   11436: {
                   11437: #ifdef GSL
                   11438:   const gsl_multimin_fminimizer_type *T;
                   11439:   size_t iteri = 0, it;
                   11440:   int rval = GSL_CONTINUE;
                   11441:   int status = GSL_SUCCESS;
                   11442:   double ssval;
                   11443: #endif
                   11444:   int movingaverage(double ***probs, double bage,double fage, double ***mobaverage, int mobilav);
1.290     brouard  11445:   int i,j, k, iter=0,m,size=100, cptcod; /* Suppressing because nobs */
                   11446:   /* int i,j, k, n=MAXN,iter=0,m,size=100, cptcod; */
1.209     brouard  11447:   int ncvyear=0; /* Number of years needed for the period prevalence to converge */
1.164     brouard  11448:   int jj, ll, li, lj, lk;
1.136     brouard  11449:   int numlinepar=0; /* Current linenumber of parameter file */
1.197     brouard  11450:   int num_filled;
1.136     brouard  11451:   int itimes;
                   11452:   int NDIM=2;
                   11453:   int vpopbased=0;
1.235     brouard  11454:   int nres=0;
1.258     brouard  11455:   int endishere=0;
1.277     brouard  11456:   int noffset=0;
1.274     brouard  11457:   int ncurrv=0; /* Temporary variable */
                   11458:   
1.164     brouard  11459:   char ca[32], cb[32];
1.136     brouard  11460:   /*  FILE *fichtm; *//* Html File */
                   11461:   /* FILE *ficgp;*/ /*Gnuplot File */
                   11462:   struct stat info;
1.191     brouard  11463:   double agedeb=0.;
1.194     brouard  11464: 
                   11465:   double ageminpar=AGEOVERFLOW,agemin=AGEOVERFLOW, agemaxpar=-AGEOVERFLOW, agemax=-AGEOVERFLOW;
1.219     brouard  11466:   double ageminout=-AGEOVERFLOW,agemaxout=AGEOVERFLOW; /* Smaller Age range redefined after movingaverage */
1.136     brouard  11467: 
1.165     brouard  11468:   double fret;
1.191     brouard  11469:   double dum=0.; /* Dummy variable */
1.136     brouard  11470:   double ***p3mat;
1.218     brouard  11471:   /* double ***mobaverage; */
1.319     brouard  11472:   double wald;
1.164     brouard  11473: 
                   11474:   char line[MAXLINE];
1.197     brouard  11475:   char path[MAXLINE],pathc[MAXLINE],pathcd[MAXLINE],pathtot[MAXLINE];
                   11476: 
1.234     brouard  11477:   char  modeltemp[MAXLINE];
1.230     brouard  11478:   char resultline[MAXLINE];
                   11479:   
1.136     brouard  11480:   char pathr[MAXLINE], pathimach[MAXLINE]; 
1.164     brouard  11481:   char *tok, *val; /* pathtot */
1.290     brouard  11482:   int firstobs=1, lastobs=10; /* nobs = lastobs-firstobs declared globally ;*/
1.195     brouard  11483:   int c,  h , cpt, c2;
1.191     brouard  11484:   int jl=0;
                   11485:   int i1, j1, jk, stepsize=0;
1.194     brouard  11486:   int count=0;
                   11487: 
1.164     brouard  11488:   int *tab; 
1.136     brouard  11489:   int mobilavproj=0 , prevfcast=0 ; /* moving average of prev, If prevfcast=1 prevalence projection */
1.296     brouard  11490:   /* double anprojd, mprojd, jprojd; /\* For eventual projections *\/ */
                   11491:   /* double anprojf, mprojf, jprojf; */
                   11492:   /* double jintmean,mintmean,aintmean;   */
                   11493:   int prvforecast = 0; /* Might be 1 (date of beginning of projection is a choice or 2 is the dateintmean */
                   11494:   int prvbackcast = 0; /* Might be 1 (date of beginning of projection is a choice or 2 is the dateintmean */
                   11495:   double yrfproj= 10.0; /* Number of years of forward projections */
                   11496:   double yrbproj= 10.0; /* Number of years of backward projections */
                   11497:   int prevbcast=0; /* defined as global for mlikeli and mle, replacing backcast */
1.136     brouard  11498:   int mobilav=0,popforecast=0;
1.191     brouard  11499:   int hstepm=0, nhstepm=0;
1.136     brouard  11500:   int agemortsup;
                   11501:   float  sumlpop=0.;
                   11502:   double jprev1=1, mprev1=1,anprev1=2000,jprev2=1, mprev2=1,anprev2=2000;
                   11503:   double jpyram=1, mpyram=1,anpyram=2000,jpyram1=1, mpyram1=1,anpyram1=2000;
                   11504: 
1.191     brouard  11505:   double bage=0, fage=110., age, agelim=0., agebase=0.;
1.136     brouard  11506:   double ftolpl=FTOL;
                   11507:   double **prlim;
1.217     brouard  11508:   double **bprlim;
1.317     brouard  11509:   double ***param; /* Matrix of parameters, param[i][j][k] param=ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel) 
                   11510:                     state of origin, state of destination including death, for each covariate: constante, age, and V1 V2 etc. */
1.251     brouard  11511:   double ***paramstart; /* Matrix of starting parameter values */
                   11512:   double  *p, *pstart; /* p=param[1][1] pstart is for starting values guessed by freqsummary */
1.136     brouard  11513:   double **matcov; /* Matrix of covariance */
1.203     brouard  11514:   double **hess; /* Hessian matrix */
1.136     brouard  11515:   double ***delti3; /* Scale */
                   11516:   double *delti; /* Scale */
                   11517:   double ***eij, ***vareij;
                   11518:   double **varpl; /* Variances of prevalence limits by age */
1.269     brouard  11519: 
1.136     brouard  11520:   double *epj, vepp;
1.164     brouard  11521: 
1.273     brouard  11522:   double dateprev1, dateprev2;
1.296     brouard  11523:   double jproj1=1,mproj1=1,anproj1=2000,jproj2=1,mproj2=1,anproj2=2000, dateproj1=0, dateproj2=0, dateprojd=0, dateprojf=0;
                   11524:   double jback1=1,mback1=1,anback1=2000,jback2=1,mback2=1,anback2=2000, dateback1=0, dateback2=0, datebackd=0, datebackf=0;
                   11525: 
1.217     brouard  11526: 
1.136     brouard  11527:   double **ximort;
1.145     brouard  11528:   char *alph[]={"a","a","b","c","d","e"}, str[4]="1234";
1.136     brouard  11529:   int *dcwave;
                   11530: 
1.164     brouard  11531:   char z[1]="c";
1.136     brouard  11532: 
                   11533:   /*char  *strt;*/
                   11534:   char strtend[80];
1.126     brouard  11535: 
1.164     brouard  11536: 
1.126     brouard  11537: /*   setlocale (LC_ALL, ""); */
                   11538: /*   bindtextdomain (PACKAGE, LOCALEDIR); */
                   11539: /*   textdomain (PACKAGE); */
                   11540: /*   setlocale (LC_CTYPE, ""); */
                   11541: /*   setlocale (LC_MESSAGES, ""); */
                   11542: 
                   11543:   /*   gettimeofday(&start_time, (struct timezone*)0); */ /* at first time */
1.157     brouard  11544:   rstart_time = time(NULL);  
                   11545:   /*  (void) gettimeofday(&start_time,&tzp);*/
                   11546:   start_time = *localtime(&rstart_time);
1.126     brouard  11547:   curr_time=start_time;
1.157     brouard  11548:   /*tml = *localtime(&start_time.tm_sec);*/
                   11549:   /* strcpy(strstart,asctime(&tml)); */
                   11550:   strcpy(strstart,asctime(&start_time));
1.126     brouard  11551: 
                   11552: /*  printf("Localtime (at start)=%s",strstart); */
1.157     brouard  11553: /*  tp.tm_sec = tp.tm_sec +86400; */
                   11554: /*  tm = *localtime(&start_time.tm_sec); */
1.126     brouard  11555: /*   tmg.tm_year=tmg.tm_year +dsign*dyear; */
                   11556: /*   tmg.tm_mon=tmg.tm_mon +dsign*dmonth; */
                   11557: /*   tmg.tm_hour=tmg.tm_hour + 1; */
1.157     brouard  11558: /*   tp.tm_sec = mktime(&tmg); */
1.126     brouard  11559: /*   strt=asctime(&tmg); */
                   11560: /*   printf("Time(after) =%s",strstart);  */
                   11561: /*  (void) time (&time_value);
                   11562: *  printf("time=%d,t-=%d\n",time_value,time_value-86400);
                   11563: *  tm = *localtime(&time_value);
                   11564: *  strstart=asctime(&tm);
                   11565: *  printf("tim_value=%d,asctime=%s\n",time_value,strstart); 
                   11566: */
                   11567: 
                   11568:   nberr=0; /* Number of errors and warnings */
                   11569:   nbwarn=0;
1.184     brouard  11570: #ifdef WIN32
                   11571:   _getcwd(pathcd, size);
                   11572: #else
1.126     brouard  11573:   getcwd(pathcd, size);
1.184     brouard  11574: #endif
1.191     brouard  11575:   syscompilerinfo(0);
1.196     brouard  11576:   printf("\nIMaCh version %s, %s\n%s",version, copyright, fullversion);
1.126     brouard  11577:   if(argc <=1){
                   11578:     printf("\nEnter the parameter file name: ");
1.205     brouard  11579:     if(!fgets(pathr,FILENAMELENGTH,stdin)){
                   11580:       printf("ERROR Empty parameter file name\n");
                   11581:       goto end;
                   11582:     }
1.126     brouard  11583:     i=strlen(pathr);
                   11584:     if(pathr[i-1]=='\n')
                   11585:       pathr[i-1]='\0';
1.156     brouard  11586:     i=strlen(pathr);
1.205     brouard  11587:     if(i >= 1 && pathr[i-1]==' ') {/* This may happen when dragging on oS/X! */
1.156     brouard  11588:       pathr[i-1]='\0';
1.205     brouard  11589:     }
                   11590:     i=strlen(pathr);
                   11591:     if( i==0 ){
                   11592:       printf("ERROR Empty parameter file name\n");
                   11593:       goto end;
                   11594:     }
                   11595:     for (tok = pathr; tok != NULL; ){
1.126     brouard  11596:       printf("Pathr |%s|\n",pathr);
                   11597:       while ((val = strsep(&tok, "\"" )) != NULL && *val == '\0');
                   11598:       printf("val= |%s| pathr=%s\n",val,pathr);
                   11599:       strcpy (pathtot, val);
                   11600:       if(pathr[0] == '\0') break; /* Dirty */
                   11601:     }
                   11602:   }
1.281     brouard  11603:   else if (argc<=2){
                   11604:     strcpy(pathtot,argv[1]);
                   11605:   }
1.126     brouard  11606:   else{
                   11607:     strcpy(pathtot,argv[1]);
1.281     brouard  11608:     strcpy(z,argv[2]);
                   11609:     printf("\nargv[2]=%s z=%c\n",argv[2],z[0]);
1.126     brouard  11610:   }
                   11611:   /*if(getcwd(pathcd, MAXLINE)!= NULL)printf ("Error pathcd\n");*/
                   11612:   /*cygwin_split_path(pathtot,path,optionfile);
                   11613:     printf("pathtot=%s, path=%s, optionfile=%s\n",pathtot,path,optionfile);*/
                   11614:   /* cutv(path,optionfile,pathtot,'\\');*/
                   11615: 
                   11616:   /* Split argv[0], imach program to get pathimach */
                   11617:   printf("\nargv[0]=%s argv[1]=%s, \n",argv[0],argv[1]);
                   11618:   split(argv[0],pathimach,optionfile,optionfilext,optionfilefiname);
                   11619:   printf("\nargv[0]=%s pathimach=%s, \noptionfile=%s \noptionfilext=%s \noptionfilefiname=%s\n",argv[0],pathimach,optionfile,optionfilext,optionfilefiname);
                   11620:  /*   strcpy(pathimach,argv[0]); */
                   11621:   /* Split argv[1]=pathtot, parameter file name to get path, optionfile, extension and name */
                   11622:   split(pathtot,path,optionfile,optionfilext,optionfilefiname);
                   11623:   printf("\npathtot=%s,\npath=%s,\noptionfile=%s \noptionfilext=%s \noptionfilefiname=%s\n",pathtot,path,optionfile,optionfilext,optionfilefiname);
1.184     brouard  11624: #ifdef WIN32
                   11625:   _chdir(path); /* Can be a relative path */
                   11626:   if(_getcwd(pathcd,MAXLINE) > 0) /* So pathcd is the full path */
                   11627: #else
1.126     brouard  11628:   chdir(path); /* Can be a relative path */
1.184     brouard  11629:   if (getcwd(pathcd, MAXLINE) > 0) /* So pathcd is the full path */
                   11630: #endif
                   11631:   printf("Current directory %s!\n",pathcd);
1.126     brouard  11632:   strcpy(command,"mkdir ");
                   11633:   strcat(command,optionfilefiname);
                   11634:   if((outcmd=system(command)) != 0){
1.169     brouard  11635:     printf("Directory already exists (or can't create it) %s%s, err=%d\n",path,optionfilefiname,outcmd);
1.126     brouard  11636:     /* fprintf(ficlog,"Problem creating directory %s%s\n",path,optionfilefiname); */
                   11637:     /* fclose(ficlog); */
                   11638: /*     exit(1); */
                   11639:   }
                   11640: /*   if((imk=mkdir(optionfilefiname))<0){ */
                   11641: /*     perror("mkdir"); */
                   11642: /*   } */
                   11643: 
                   11644:   /*-------- arguments in the command line --------*/
                   11645: 
1.186     brouard  11646:   /* Main Log file */
1.126     brouard  11647:   strcat(filelog, optionfilefiname);
                   11648:   strcat(filelog,".log");    /* */
                   11649:   if((ficlog=fopen(filelog,"w"))==NULL)    {
                   11650:     printf("Problem with logfile %s\n",filelog);
                   11651:     goto end;
                   11652:   }
                   11653:   fprintf(ficlog,"Log filename:%s\n",filelog);
1.197     brouard  11654:   fprintf(ficlog,"Version %s %s",version,fullversion);
1.126     brouard  11655:   fprintf(ficlog,"\nEnter the parameter file name: \n");
                   11656:   fprintf(ficlog,"pathimach=%s\npathtot=%s\n\
                   11657:  path=%s \n\
                   11658:  optionfile=%s\n\
                   11659:  optionfilext=%s\n\
1.156     brouard  11660:  optionfilefiname='%s'\n",pathimach,pathtot,path,optionfile,optionfilext,optionfilefiname);
1.126     brouard  11661: 
1.197     brouard  11662:   syscompilerinfo(1);
1.167     brouard  11663: 
1.126     brouard  11664:   printf("Local time (at start):%s",strstart);
                   11665:   fprintf(ficlog,"Local time (at start): %s",strstart);
                   11666:   fflush(ficlog);
                   11667: /*   (void) gettimeofday(&curr_time,&tzp); */
1.157     brouard  11668: /*   printf("Elapsed time %d\n", asc_diff_time(curr_time.tm_sec-start_time.tm_sec,tmpout)); */
1.126     brouard  11669: 
                   11670:   /* */
                   11671:   strcpy(fileres,"r");
                   11672:   strcat(fileres, optionfilefiname);
1.201     brouard  11673:   strcat(fileresu, optionfilefiname); /* Without r in front */
1.126     brouard  11674:   strcat(fileres,".txt");    /* Other files have txt extension */
1.201     brouard  11675:   strcat(fileresu,".txt");    /* Other files have txt extension */
1.126     brouard  11676: 
1.186     brouard  11677:   /* Main ---------arguments file --------*/
1.126     brouard  11678: 
                   11679:   if((ficpar=fopen(optionfile,"r"))==NULL)    {
1.155     brouard  11680:     printf("Problem with optionfile '%s' with errno='%s'\n",optionfile,strerror(errno));
                   11681:     fprintf(ficlog,"Problem with optionfile '%s' with errno='%s'\n",optionfile,strerror(errno));
1.126     brouard  11682:     fflush(ficlog);
1.149     brouard  11683:     /* goto end; */
                   11684:     exit(70); 
1.126     brouard  11685:   }
                   11686: 
                   11687:   strcpy(filereso,"o");
1.201     brouard  11688:   strcat(filereso,fileresu);
1.126     brouard  11689:   if((ficparo=fopen(filereso,"w"))==NULL) { /* opened on subdirectory */
                   11690:     printf("Problem with Output resultfile: %s\n", filereso);
                   11691:     fprintf(ficlog,"Problem with Output resultfile: %s\n", filereso);
                   11692:     fflush(ficlog);
                   11693:     goto end;
                   11694:   }
1.278     brouard  11695:       /*-------- Rewriting parameter file ----------*/
                   11696:   strcpy(rfileres,"r");    /* "Rparameterfile */
                   11697:   strcat(rfileres,optionfilefiname);    /* Parameter file first name */
                   11698:   strcat(rfileres,".");    /* */
                   11699:   strcat(rfileres,optionfilext);    /* Other files have txt extension */
                   11700:   if((ficres =fopen(rfileres,"w"))==NULL) {
                   11701:     printf("Problem writing new parameter file: %s\n", rfileres);goto end;
                   11702:     fprintf(ficlog,"Problem writing new parameter file: %s\n", rfileres);goto end;
                   11703:     fflush(ficlog);
                   11704:     goto end;
                   11705:   }
                   11706:   fprintf(ficres,"#IMaCh %s\n",version);
1.126     brouard  11707: 
1.278     brouard  11708:                                      
1.126     brouard  11709:   /* Reads comments: lines beginning with '#' */
                   11710:   numlinepar=0;
1.277     brouard  11711:   /* Is it a BOM UTF-8 Windows file? */
                   11712:   /* First parameter line */
1.197     brouard  11713:   while(fgets(line, MAXLINE, ficpar)) {
1.277     brouard  11714:     noffset=0;
                   11715:     if( line[0] == (char)0xEF && line[1] == (char)0xBB) /* EF BB BF */
                   11716:     {
                   11717:       noffset=noffset+3;
                   11718:       printf("# File is an UTF8 Bom.\n"); // 0xBF
                   11719:     }
1.302     brouard  11720: /*    else if( line[0] == (char)0xFE && line[1] == (char)0xFF)*/
                   11721:     else if( line[0] == (char)0xFF && line[1] == (char)0xFE)
1.277     brouard  11722:     {
                   11723:       noffset=noffset+2;
                   11724:       printf("# File is an UTF16BE BOM file\n");
                   11725:     }
                   11726:     else if( line[0] == 0 && line[1] == 0)
                   11727:     {
                   11728:       if( line[2] == (char)0xFE && line[3] == (char)0xFF){
                   11729:        noffset=noffset+4;
                   11730:        printf("# File is an UTF16BE BOM file\n");
                   11731:       }
                   11732:     } else{
                   11733:       ;/*printf(" Not a BOM file\n");*/
                   11734:     }
                   11735:   
1.197     brouard  11736:     /* If line starts with a # it is a comment */
1.277     brouard  11737:     if (line[noffset] == '#') {
1.197     brouard  11738:       numlinepar++;
                   11739:       fputs(line,stdout);
                   11740:       fputs(line,ficparo);
1.278     brouard  11741:       fputs(line,ficres);
1.197     brouard  11742:       fputs(line,ficlog);
                   11743:       continue;
                   11744:     }else
                   11745:       break;
                   11746:   }
                   11747:   if((num_filled=sscanf(line,"title=%s datafile=%s lastobs=%d firstpass=%d lastpass=%d\n", \
                   11748:                        title, datafile, &lastobs, &firstpass,&lastpass)) !=EOF){
                   11749:     if (num_filled != 5) {
                   11750:       printf("Should be 5 parameters\n");
1.283     brouard  11751:       fprintf(ficlog,"Should be 5 parameters\n");
1.197     brouard  11752:     }
1.126     brouard  11753:     numlinepar++;
1.197     brouard  11754:     printf("title=%s datafile=%s lastobs=%d firstpass=%d lastpass=%d\n", title, datafile, lastobs, firstpass,lastpass);
1.283     brouard  11755:     fprintf(ficparo,"title=%s datafile=%s lastobs=%d firstpass=%d lastpass=%d\n", title, datafile, lastobs, firstpass,lastpass);
                   11756:     fprintf(ficres,"title=%s datafile=%s lastobs=%d firstpass=%d lastpass=%d\n", title, datafile, lastobs, firstpass,lastpass);
                   11757:     fprintf(ficlog,"title=%s datafile=%s lastobs=%d firstpass=%d lastpass=%d\n", title, datafile, lastobs, firstpass,lastpass);
1.197     brouard  11758:   }
                   11759:   /* Second parameter line */
                   11760:   while(fgets(line, MAXLINE, ficpar)) {
1.283     brouard  11761:     /* while(fscanf(ficpar,"%[^\n]", line)) { */
                   11762:     /* If line starts with a # it is a comment. Strangely fgets reads the EOL and fputs doesn't */
1.197     brouard  11763:     if (line[0] == '#') {
                   11764:       numlinepar++;
1.283     brouard  11765:       printf("%s",line);
                   11766:       fprintf(ficres,"%s",line);
                   11767:       fprintf(ficparo,"%s",line);
                   11768:       fprintf(ficlog,"%s",line);
1.197     brouard  11769:       continue;
                   11770:     }else
                   11771:       break;
                   11772:   }
1.223     brouard  11773:   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", \
                   11774:                        &ftol, &stepm, &ncovcol, &nqv, &ntv, &nqtv, &nlstate, &ndeath, &maxwav, &mle, &weightopt)) !=EOF){
                   11775:     if (num_filled != 11) {
                   11776:       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  11777:       printf("but line=%s\n",line);
1.283     brouard  11778:       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");
                   11779:       fprintf(ficlog,"but line=%s\n",line);
1.197     brouard  11780:     }
1.286     brouard  11781:     if( lastpass > maxwav){
                   11782:       printf("Error (lastpass = %d) > (maxwav = %d)\n",lastpass, maxwav);
                   11783:       fprintf(ficlog,"Error (lastpass = %d) > (maxwav = %d)\n",lastpass, maxwav);
                   11784:       fflush(ficlog);
                   11785:       goto end;
                   11786:     }
                   11787:       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  11788:     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  11789:     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  11790:     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  11791:   }
1.203     brouard  11792:   /* ftolpl=6*ftol*1.e5; /\* 6.e-3 make convergences in less than 80 loops for the prevalence limit *\/ */
1.209     brouard  11793:   /*ftolpl=6.e-4; *//* 6.e-3 make convergences in less than 80 loops for the prevalence limit */
1.197     brouard  11794:   /* Third parameter line */
                   11795:   while(fgets(line, MAXLINE, ficpar)) {
                   11796:     /* If line starts with a # it is a comment */
                   11797:     if (line[0] == '#') {
                   11798:       numlinepar++;
1.283     brouard  11799:       printf("%s",line);
                   11800:       fprintf(ficres,"%s",line);
                   11801:       fprintf(ficparo,"%s",line);
                   11802:       fprintf(ficlog,"%s",line);
1.197     brouard  11803:       continue;
                   11804:     }else
                   11805:       break;
                   11806:   }
1.201     brouard  11807:   if((num_filled=sscanf(line,"model=1+age%[^.\n]", model)) !=EOF){
1.279     brouard  11808:     if (num_filled != 1){
1.302     brouard  11809:       printf("ERROR %d: Model should be at minimum 'model=1+age+' instead of '%s'\n",num_filled, line);
                   11810:       fprintf(ficlog,"ERROR %d: Model should be at minimum 'model=1+age+' instead of '%s'\n",num_filled, line);
1.197     brouard  11811:       model[0]='\0';
                   11812:       goto end;
                   11813:     }
                   11814:     else{
                   11815:       if (model[0]=='+'){
                   11816:        for(i=1; i<=strlen(model);i++)
                   11817:          modeltemp[i-1]=model[i];
1.201     brouard  11818:        strcpy(model,modeltemp); 
1.197     brouard  11819:       }
                   11820:     }
1.199     brouard  11821:     /* printf(" model=1+age%s modeltemp= %s, model=%s\n",model, modeltemp, model);fflush(stdout); */
1.203     brouard  11822:     printf("model=1+age+%s\n",model);fflush(stdout);
1.283     brouard  11823:     fprintf(ficparo,"model=1+age+%s\n",model);fflush(stdout);
                   11824:     fprintf(ficres,"model=1+age+%s\n",model);fflush(stdout);
                   11825:     fprintf(ficlog,"model=1+age+%s\n",model);fflush(stdout);
1.197     brouard  11826:   }
                   11827:   /* 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); */
                   11828:   /* numlinepar=numlinepar+3; /\* In general *\/ */
                   11829:   /* 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  11830:   /* 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); */
                   11831:   /* 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  11832:   fflush(ficlog);
1.190     brouard  11833:   /* if(model[0]=='#'|| model[0]== '\0'){ */
                   11834:   if(model[0]=='#'){
1.279     brouard  11835:     printf("Error in 'model' line: model should start with 'model=1+age+' and end without space \n \
                   11836:  'model=1+age+' or 'model=1+age+V1.' or 'model=1+age+age*age+V1+V1*age' or \n \
                   11837:  'model=1+age+V1+V2' or 'model=1+age+V1+V2+V1*V2' etc. \n");           \
1.187     brouard  11838:     if(mle != -1){
1.279     brouard  11839:       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  11840:       exit(1);
                   11841:     }
                   11842:   }
1.126     brouard  11843:   while((c=getc(ficpar))=='#' && c!= EOF){
                   11844:     ungetc(c,ficpar);
                   11845:     fgets(line, MAXLINE, ficpar);
                   11846:     numlinepar++;
1.195     brouard  11847:     if(line[1]=='q'){ /* This #q will quit imach (the answer is q) */
                   11848:       z[0]=line[1];
                   11849:     }
                   11850:     /* printf("****line [1] = %c \n",line[1]); */
1.141     brouard  11851:     fputs(line, stdout);
                   11852:     //puts(line);
1.126     brouard  11853:     fputs(line,ficparo);
                   11854:     fputs(line,ficlog);
                   11855:   }
                   11856:   ungetc(c,ficpar);
                   11857: 
                   11858:    
1.290     brouard  11859:   covar=matrix(0,NCOVMAX,firstobs,lastobs);  /**< used in readdata */
                   11860:   if(nqv>=1)coqvar=matrix(1,nqv,firstobs,lastobs);  /**< Fixed quantitative covariate */
                   11861:   if(nqtv>=1)cotqvar=ma3x(1,maxwav,1,nqtv,firstobs,lastobs);  /**< Time varying quantitative covariate */
                   11862:   if(ntv+nqtv>=1)cotvar=ma3x(1,maxwav,1,ntv+nqtv,firstobs,lastobs);  /**< Time varying covariate (dummy and quantitative)*/
1.136     brouard  11863:   cptcovn=0; /*Number of covariates, i.e. number of '+' in model statement plus one, indepently of n in Vn*/
                   11864:   /* v1+v2+v3+v2*v4+v5*age makes cptcovn = 5
                   11865:      v1+v2*age+v2*v3 makes cptcovn = 3
                   11866:   */
                   11867:   if (strlen(model)>1) 
1.187     brouard  11868:     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  11869:   else
1.187     brouard  11870:     ncovmodel=2; /* Constant and age */
1.133     brouard  11871:   nforce= (nlstate+ndeath-1)*nlstate; /* Number of forces ij from state i to j */
                   11872:   npar= nforce*ncovmodel; /* Number of parameters like aij*/
1.131     brouard  11873:   if(npar >MAXPARM || nlstate >NLSTATEMAX || ndeath >NDEATHMAX || ncovmodel>NCOVMAX){
                   11874:     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);
                   11875:     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);
                   11876:     fflush(stdout);
                   11877:     fclose (ficlog);
                   11878:     goto end;
                   11879:   }
1.126     brouard  11880:   delti3= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
                   11881:   delti=delti3[1][1];
                   11882:   /*delti=vector(1,npar); *//* Scale of each paramater (output from hesscov)*/
                   11883:   if(mle==-1){ /* Print a wizard for help writing covariance matrix */
1.247     brouard  11884: /* We could also provide initial parameters values giving by simple logistic regression 
                   11885:  * only one way, that is without matrix product. We will have nlstate maximizations */
                   11886:       /* for(i=1;i<nlstate;i++){ */
                   11887:       /*       /\*reducing xi for 1 to npar to 1 to ncovmodel; *\/ */
                   11888:       /*    mlikeli(ficres,p, ncovmodel, ncovmodel, nlstate, ftol, funcnoprod); */
                   11889:       /* } */
1.126     brouard  11890:     prwizard(ncovmodel, nlstate, ndeath, model, ficparo);
1.191     brouard  11891:     printf(" You chose mle=-1, look at file %s for a template of covariance matrix \n",filereso);
                   11892:     fprintf(ficlog," You chose mle=-1, look at file %s for a template of covariance matrix \n",filereso);
1.126     brouard  11893:     free_ma3x(delti3,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel); 
                   11894:     fclose (ficparo);
                   11895:     fclose (ficlog);
                   11896:     goto end;
                   11897:     exit(0);
1.220     brouard  11898:   }  else if(mle==-5) { /* Main Wizard */
1.126     brouard  11899:     prwizard(ncovmodel, nlstate, ndeath, model, ficparo);
1.192     brouard  11900:     printf(" You chose mle=-3, look at file %s for a template of covariance matrix \n",filereso);
                   11901:     fprintf(ficlog," You chose mle=-3, look at file %s for a template of covariance matrix \n",filereso);
1.126     brouard  11902:     param= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
                   11903:     matcov=matrix(1,npar,1,npar);
1.203     brouard  11904:     hess=matrix(1,npar,1,npar);
1.220     brouard  11905:   }  else{ /* Begin of mle != -1 or -5 */
1.145     brouard  11906:     /* Read guessed parameters */
1.126     brouard  11907:     /* Reads comments: lines beginning with '#' */
                   11908:     while((c=getc(ficpar))=='#' && c!= EOF){
                   11909:       ungetc(c,ficpar);
                   11910:       fgets(line, MAXLINE, ficpar);
                   11911:       numlinepar++;
1.141     brouard  11912:       fputs(line,stdout);
1.126     brouard  11913:       fputs(line,ficparo);
                   11914:       fputs(line,ficlog);
                   11915:     }
                   11916:     ungetc(c,ficpar);
                   11917:     
                   11918:     param= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
1.251     brouard  11919:     paramstart= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
1.126     brouard  11920:     for(i=1; i <=nlstate; i++){
1.234     brouard  11921:       j=0;
1.126     brouard  11922:       for(jj=1; jj <=nlstate+ndeath; jj++){
1.234     brouard  11923:        if(jj==i) continue;
                   11924:        j++;
1.292     brouard  11925:        while((c=getc(ficpar))=='#' && c!= EOF){
                   11926:          ungetc(c,ficpar);
                   11927:          fgets(line, MAXLINE, ficpar);
                   11928:          numlinepar++;
                   11929:          fputs(line,stdout);
                   11930:          fputs(line,ficparo);
                   11931:          fputs(line,ficlog);
                   11932:        }
                   11933:        ungetc(c,ficpar);
1.234     brouard  11934:        fscanf(ficpar,"%1d%1d",&i1,&j1);
                   11935:        if ((i1 != i) || (j1 != jj)){
                   11936:          printf("Error in line parameters number %d, %1d%1d instead of %1d%1d \n \
1.126     brouard  11937: It might be a problem of design; if ncovcol and the model are correct\n \
                   11938: run imach with mle=-1 to get a correct template of the parameter file.\n",numlinepar, i,j, i1, j1);
1.234     brouard  11939:          exit(1);
                   11940:        }
                   11941:        fprintf(ficparo,"%1d%1d",i1,j1);
                   11942:        if(mle==1)
                   11943:          printf("%1d%1d",i,jj);
                   11944:        fprintf(ficlog,"%1d%1d",i,jj);
                   11945:        for(k=1; k<=ncovmodel;k++){
                   11946:          fscanf(ficpar," %lf",&param[i][j][k]);
                   11947:          if(mle==1){
                   11948:            printf(" %lf",param[i][j][k]);
                   11949:            fprintf(ficlog," %lf",param[i][j][k]);
                   11950:          }
                   11951:          else
                   11952:            fprintf(ficlog," %lf",param[i][j][k]);
                   11953:          fprintf(ficparo," %lf",param[i][j][k]);
                   11954:        }
                   11955:        fscanf(ficpar,"\n");
                   11956:        numlinepar++;
                   11957:        if(mle==1)
                   11958:          printf("\n");
                   11959:        fprintf(ficlog,"\n");
                   11960:        fprintf(ficparo,"\n");
1.126     brouard  11961:       }
                   11962:     }  
                   11963:     fflush(ficlog);
1.234     brouard  11964:     
1.251     brouard  11965:     /* Reads parameters values */
1.126     brouard  11966:     p=param[1][1];
1.251     brouard  11967:     pstart=paramstart[1][1];
1.126     brouard  11968:     
                   11969:     /* Reads comments: lines beginning with '#' */
                   11970:     while((c=getc(ficpar))=='#' && c!= EOF){
                   11971:       ungetc(c,ficpar);
                   11972:       fgets(line, MAXLINE, ficpar);
                   11973:       numlinepar++;
1.141     brouard  11974:       fputs(line,stdout);
1.126     brouard  11975:       fputs(line,ficparo);
                   11976:       fputs(line,ficlog);
                   11977:     }
                   11978:     ungetc(c,ficpar);
                   11979: 
                   11980:     for(i=1; i <=nlstate; i++){
                   11981:       for(j=1; j <=nlstate+ndeath-1; j++){
1.234     brouard  11982:        fscanf(ficpar,"%1d%1d",&i1,&j1);
                   11983:        if ( (i1-i) * (j1-j) != 0){
                   11984:          printf("Error in line parameters number %d, %1d%1d instead of %1d%1d \n",numlinepar, i,j, i1, j1);
                   11985:          exit(1);
                   11986:        }
                   11987:        printf("%1d%1d",i,j);
                   11988:        fprintf(ficparo,"%1d%1d",i1,j1);
                   11989:        fprintf(ficlog,"%1d%1d",i1,j1);
                   11990:        for(k=1; k<=ncovmodel;k++){
                   11991:          fscanf(ficpar,"%le",&delti3[i][j][k]);
                   11992:          printf(" %le",delti3[i][j][k]);
                   11993:          fprintf(ficparo," %le",delti3[i][j][k]);
                   11994:          fprintf(ficlog," %le",delti3[i][j][k]);
                   11995:        }
                   11996:        fscanf(ficpar,"\n");
                   11997:        numlinepar++;
                   11998:        printf("\n");
                   11999:        fprintf(ficparo,"\n");
                   12000:        fprintf(ficlog,"\n");
1.126     brouard  12001:       }
                   12002:     }
                   12003:     fflush(ficlog);
1.234     brouard  12004:     
1.145     brouard  12005:     /* Reads covariance matrix */
1.126     brouard  12006:     delti=delti3[1][1];
1.220     brouard  12007:                
                   12008:                
1.126     brouard  12009:     /* 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  12010:                
1.126     brouard  12011:     /* Reads comments: lines beginning with '#' */
                   12012:     while((c=getc(ficpar))=='#' && c!= EOF){
                   12013:       ungetc(c,ficpar);
                   12014:       fgets(line, MAXLINE, ficpar);
                   12015:       numlinepar++;
1.141     brouard  12016:       fputs(line,stdout);
1.126     brouard  12017:       fputs(line,ficparo);
                   12018:       fputs(line,ficlog);
                   12019:     }
                   12020:     ungetc(c,ficpar);
1.220     brouard  12021:                
1.126     brouard  12022:     matcov=matrix(1,npar,1,npar);
1.203     brouard  12023:     hess=matrix(1,npar,1,npar);
1.131     brouard  12024:     for(i=1; i <=npar; i++)
                   12025:       for(j=1; j <=npar; j++) matcov[i][j]=0.;
1.220     brouard  12026:                
1.194     brouard  12027:     /* Scans npar lines */
1.126     brouard  12028:     for(i=1; i <=npar; i++){
1.226     brouard  12029:       count=fscanf(ficpar,"%1d%1d%d",&i1,&j1,&jk);
1.194     brouard  12030:       if(count != 3){
1.226     brouard  12031:        printf("Error! Error in parameter file %s at line %d after line starting with %1d%1d%1d\n\
1.194     brouard  12032: This is probably because your covariance matrix doesn't \n  contain exactly %d lines corresponding to your model line '1+age+%s'.\n\
                   12033: Please run with mle=-1 to get a correct covariance matrix.\n",optionfile,numlinepar, i1,j1,jk, npar, model);
1.226     brouard  12034:        fprintf(ficlog,"Error! Error in parameter file %s at line %d after line starting with %1d%1d%1d\n\
1.194     brouard  12035: This is probably because your covariance matrix doesn't \n  contain exactly %d lines corresponding to your model line '1+age+%s'.\n\
                   12036: Please run with mle=-1 to get a correct covariance matrix.\n",optionfile,numlinepar, i1,j1,jk, npar, model);
1.226     brouard  12037:        exit(1);
1.220     brouard  12038:       }else{
1.226     brouard  12039:        if(mle==1)
                   12040:          printf("%1d%1d%d",i1,j1,jk);
                   12041:       }
                   12042:       fprintf(ficlog,"%1d%1d%d",i1,j1,jk);
                   12043:       fprintf(ficparo,"%1d%1d%d",i1,j1,jk);
1.126     brouard  12044:       for(j=1; j <=i; j++){
1.226     brouard  12045:        fscanf(ficpar," %le",&matcov[i][j]);
                   12046:        if(mle==1){
                   12047:          printf(" %.5le",matcov[i][j]);
                   12048:        }
                   12049:        fprintf(ficlog," %.5le",matcov[i][j]);
                   12050:        fprintf(ficparo," %.5le",matcov[i][j]);
1.126     brouard  12051:       }
                   12052:       fscanf(ficpar,"\n");
                   12053:       numlinepar++;
                   12054:       if(mle==1)
1.220     brouard  12055:                                printf("\n");
1.126     brouard  12056:       fprintf(ficlog,"\n");
                   12057:       fprintf(ficparo,"\n");
                   12058:     }
1.194     brouard  12059:     /* End of read covariance matrix npar lines */
1.126     brouard  12060:     for(i=1; i <=npar; i++)
                   12061:       for(j=i+1;j<=npar;j++)
1.226     brouard  12062:        matcov[i][j]=matcov[j][i];
1.126     brouard  12063:     
                   12064:     if(mle==1)
                   12065:       printf("\n");
                   12066:     fprintf(ficlog,"\n");
                   12067:     
                   12068:     fflush(ficlog);
                   12069:     
                   12070:   }    /* End of mle != -3 */
1.218     brouard  12071:   
1.186     brouard  12072:   /*  Main data
                   12073:    */
1.290     brouard  12074:   nobs=lastobs-firstobs+1; /* was = lastobs;*/
                   12075:   /* num=lvector(1,n); */
                   12076:   /* moisnais=vector(1,n); */
                   12077:   /* annais=vector(1,n); */
                   12078:   /* moisdc=vector(1,n); */
                   12079:   /* andc=vector(1,n); */
                   12080:   /* weight=vector(1,n); */
                   12081:   /* agedc=vector(1,n); */
                   12082:   /* cod=ivector(1,n); */
                   12083:   /* for(i=1;i<=n;i++){ */
                   12084:   num=lvector(firstobs,lastobs);
                   12085:   moisnais=vector(firstobs,lastobs);
                   12086:   annais=vector(firstobs,lastobs);
                   12087:   moisdc=vector(firstobs,lastobs);
                   12088:   andc=vector(firstobs,lastobs);
                   12089:   weight=vector(firstobs,lastobs);
                   12090:   agedc=vector(firstobs,lastobs);
                   12091:   cod=ivector(firstobs,lastobs);
                   12092:   for(i=firstobs;i<=lastobs;i++){
1.234     brouard  12093:     num[i]=0;
                   12094:     moisnais[i]=0;
                   12095:     annais[i]=0;
                   12096:     moisdc[i]=0;
                   12097:     andc[i]=0;
                   12098:     agedc[i]=0;
                   12099:     cod[i]=0;
                   12100:     weight[i]=1.0; /* Equal weights, 1 by default */
                   12101:   }
1.290     brouard  12102:   mint=matrix(1,maxwav,firstobs,lastobs);
                   12103:   anint=matrix(1,maxwav,firstobs,lastobs);
1.325     brouard  12104:   s=imatrix(1,maxwav+1,firstobs,lastobs); /* s[i][j] health state for wave i and individual j */
                   12105:   printf("BUG ncovmodel=%d NCOVMAX=%d 2**ncovmodel=%f BUG\n",ncovmodel,NCOVMAX,pow(2,ncovmodel));
1.126     brouard  12106:   tab=ivector(1,NCOVMAX);
1.144     brouard  12107:   ncodemax=ivector(1,NCOVMAX); /* Number of code per covariate; if O and 1 only, 2**ncov; V1+V2+V3+V4=>16 */
1.192     brouard  12108:   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  12109: 
1.136     brouard  12110:   /* Reads data from file datafile */
                   12111:   if (readdata(datafile, firstobs, lastobs, &imx)==1)
                   12112:     goto end;
                   12113: 
                   12114:   /* Calculation of the number of parameters from char model */
1.234     brouard  12115:   /*    modelsav=V2+V1+V4+age*V3 strb=age*V3 stra=V2+V1+V4 
1.137     brouard  12116:        k=4 (age*V3) Tvar[k=4]= 3 (from V3) Tag[cptcovage=1]=4
                   12117:        k=3 V4 Tvar[k=3]= 4 (from V4)
                   12118:        k=2 V1 Tvar[k=2]= 1 (from V1)
                   12119:        k=1 Tvar[1]=2 (from V2)
1.234     brouard  12120:   */
                   12121:   
                   12122:   Tvar=ivector(1,NCOVMAX); /* Was 15 changed to NCOVMAX. */
                   12123:   TvarsDind=ivector(1,NCOVMAX); /*  */
1.330   ! brouard  12124:   TnsdVar=ivector(1,NCOVMAX); /*  */
1.234     brouard  12125:   TvarsD=ivector(1,NCOVMAX); /*  */
                   12126:   TvarsQind=ivector(1,NCOVMAX); /*  */
                   12127:   TvarsQ=ivector(1,NCOVMAX); /*  */
1.232     brouard  12128:   TvarF=ivector(1,NCOVMAX); /*  */
                   12129:   TvarFind=ivector(1,NCOVMAX); /*  */
                   12130:   TvarV=ivector(1,NCOVMAX); /*  */
                   12131:   TvarVind=ivector(1,NCOVMAX); /*  */
                   12132:   TvarA=ivector(1,NCOVMAX); /*  */
                   12133:   TvarAind=ivector(1,NCOVMAX); /*  */
1.231     brouard  12134:   TvarFD=ivector(1,NCOVMAX); /*  */
                   12135:   TvarFDind=ivector(1,NCOVMAX); /*  */
                   12136:   TvarFQ=ivector(1,NCOVMAX); /*  */
                   12137:   TvarFQind=ivector(1,NCOVMAX); /*  */
                   12138:   TvarVD=ivector(1,NCOVMAX); /*  */
                   12139:   TvarVDind=ivector(1,NCOVMAX); /*  */
                   12140:   TvarVQ=ivector(1,NCOVMAX); /*  */
                   12141:   TvarVQind=ivector(1,NCOVMAX); /*  */
                   12142: 
1.230     brouard  12143:   Tvalsel=vector(1,NCOVMAX); /*  */
1.233     brouard  12144:   Tvarsel=ivector(1,NCOVMAX); /*  */
1.226     brouard  12145:   Typevar=ivector(-1,NCOVMAX); /* -1 to 2 */
                   12146:   Fixed=ivector(-1,NCOVMAX); /* -1 to 3 */
                   12147:   Dummy=ivector(-1,NCOVMAX); /* -1 to 3 */
1.137     brouard  12148:   /*  V2+V1+V4+age*V3 is a model with 4 covariates (3 plus signs). 
                   12149:       For each model-covariate stores the data-covariate id. Tvar[1]=2, Tvar[2]=1, Tvar[3]=4, 
                   12150:       Tvar[4=age*V3] is 3 and 'age' is recorded in Tage.
                   12151:   */
                   12152:   /* For model-covariate k tells which data-covariate to use but
                   12153:     because this model-covariate is a construction we invent a new column
                   12154:     ncovcol + k1
                   12155:     If already ncovcol=4 and model=V2+V1+V1*V4+age*V3
                   12156:     Tvar[3=V1*V4]=4+1 etc */
1.227     brouard  12157:   Tprod=ivector(1,NCOVMAX); /* Gives the k position of the k1 product */
                   12158:   Tposprod=ivector(1,NCOVMAX); /* Gives the k1 product from the k position */
1.137     brouard  12159:   /* Tprod[k1=1]=3(=V1*V4) for V2+V1+V1*V4+age*V3
                   12160:      if  V2+V1+V1*V4+age*V3+V3*V2   TProd[k1=2]=5 (V3*V2)
1.227     brouard  12161:      Tposprod[k]=k1 , Tposprod[3]=1, Tposprod[5]=2 
1.137     brouard  12162:   */
1.145     brouard  12163:   Tvaraff=ivector(1,NCOVMAX); /* Unclear */
                   12164:   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  12165:                            * For V3*V2 (in V2+V1+V1*V4+age*V3+V3*V2), V3*V2 position is 2nd. 
                   12166:                            * Tvard[k1=2][1]=3 (V3) Tvard[k1=2][2]=2(V2) */
1.330   ! brouard  12167:   Tvardk=imatrix(1,NCOVMAX,1,2);
1.145     brouard  12168:   Tage=ivector(1,NCOVMAX); /* Gives the covariate id of covariates associated with age: V2 + V1 + age*V4 + V3*age
1.137     brouard  12169:                         4 covariates (3 plus signs)
                   12170:                         Tage[1=V3*age]= 4; Tage[2=age*V4] = 3
1.328     brouard  12171:                           */  
                   12172:   for(i=1;i<NCOVMAX;i++)
                   12173:     Tage[i]=0;
1.230     brouard  12174:   Tmodelind=ivector(1,NCOVMAX);/** gives the k model position of an
1.227     brouard  12175:                                * individual dummy, fixed or varying:
                   12176:                                * Tmodelind[Tvaraff[3]]=9,Tvaraff[1]@9={4,
                   12177:                                * 3, 1, 0, 0, 0, 0, 0, 0},
1.230     brouard  12178:                                * model=V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 , 
                   12179:                                * V1 df, V2 qf, V3 & V4 dv, V5 qv
                   12180:                                * Tmodelind[1]@9={9,0,3,2,}*/
                   12181:   TmodelInvind=ivector(1,NCOVMAX); /* TmodelInvind=Tvar[k]- ncovcol-nqv={5-2-1=2,*/
                   12182:   TmodelInvQind=ivector(1,NCOVMAX);/** gives the k model position of an
1.228     brouard  12183:                                * individual quantitative, fixed or varying:
                   12184:                                * Tmodelqind[1]=1,Tvaraff[1]@9={4,
                   12185:                                * 3, 1, 0, 0, 0, 0, 0, 0},
                   12186:                                * model=V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1*/
1.186     brouard  12187: /* Main decodemodel */
                   12188: 
1.187     brouard  12189: 
1.223     brouard  12190:   if(decodemodel(model, lastobs) == 1) /* In order to get Tvar[k] V4+V3+V5 p Tvar[1]@3  = {4, 3, 5}*/
1.136     brouard  12191:     goto end;
                   12192: 
1.137     brouard  12193:   if((double)(lastobs-imx)/(double)imx > 1.10){
                   12194:     nbwarn++;
                   12195:     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); 
                   12196:     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); 
                   12197:   }
1.136     brouard  12198:     /*  if(mle==1){*/
1.137     brouard  12199:   if (weightopt != 1) { /* Maximisation without weights. We can have weights different from 1 but want no weight*/
                   12200:     for(i=1;i<=imx;i++) weight[i]=1.0; /* changed to imx */
1.136     brouard  12201:   }
                   12202: 
                   12203:     /*-calculation of age at interview from date of interview and age at death -*/
                   12204:   agev=matrix(1,maxwav,1,imx);
                   12205: 
                   12206:   if(calandcheckages(imx, maxwav, &agemin, &agemax, &nberr, &nbwarn) == 1)
                   12207:     goto end;
                   12208: 
1.126     brouard  12209: 
1.136     brouard  12210:   agegomp=(int)agemin;
1.290     brouard  12211:   free_vector(moisnais,firstobs,lastobs);
                   12212:   free_vector(annais,firstobs,lastobs);
1.126     brouard  12213:   /* free_matrix(mint,1,maxwav,1,n);
                   12214:      free_matrix(anint,1,maxwav,1,n);*/
1.215     brouard  12215:   /* free_vector(moisdc,1,n); */
                   12216:   /* free_vector(andc,1,n); */
1.145     brouard  12217:   /* */
                   12218:   
1.126     brouard  12219:   wav=ivector(1,imx);
1.214     brouard  12220:   /* dh=imatrix(1,lastpass-firstpass+1,1,imx); */
                   12221:   /* bh=imatrix(1,lastpass-firstpass+1,1,imx); */
                   12222:   /* mw=imatrix(1,lastpass-firstpass+1,1,imx); */
                   12223:   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.*/
                   12224:   bh=imatrix(1,lastpass-firstpass+2,1,imx);
                   12225:   mw=imatrix(1,lastpass-firstpass+2,1,imx);
1.126     brouard  12226:    
                   12227:   /* Concatenates waves */
1.214     brouard  12228:   /* Concatenates waves: wav[i] is the number of effective (useful waves) of individual i.
                   12229:      Death is a valid wave (if date is known).
                   12230:      mw[mi][i] is the number of (mi=1 to wav[i]) effective wave out of mi of individual i
                   12231:      dh[m][i] or dh[mw[mi][i]][i] is the delay between two effective waves m=mw[mi][i]
                   12232:      and mw[mi+1][i]. dh depends on stepm.
                   12233:   */
                   12234: 
1.126     brouard  12235:   concatwav(wav, dh, bh, mw, s, agedc, agev,  firstpass, lastpass, imx, nlstate, stepm);
1.248     brouard  12236:   /* Concatenates waves */
1.145     brouard  12237:  
1.290     brouard  12238:   free_vector(moisdc,firstobs,lastobs);
                   12239:   free_vector(andc,firstobs,lastobs);
1.215     brouard  12240: 
1.126     brouard  12241:   /* Routine tricode is to calculate cptcoveff (real number of unique covariates) and to associate covariable number and modality */
                   12242:   nbcode=imatrix(0,NCOVMAX,0,NCOVMAX); 
                   12243:   ncodemax[1]=1;
1.145     brouard  12244:   Ndum =ivector(-1,NCOVMAX);  
1.225     brouard  12245:   cptcoveff=0;
1.220     brouard  12246:   if (ncovmodel-nagesqr > 2 ){ /* That is if covariate other than cst, age and age*age */
                   12247:     tricode(&cptcoveff,Tvar,nbcode,imx, Ndum); /**< Fills nbcode[Tvar[j]][l]; */
1.227     brouard  12248:   }
                   12249:   
                   12250:   ncovcombmax=pow(2,cptcoveff);
                   12251:   invalidvarcomb=ivector(1, ncovcombmax); 
                   12252:   for(i=1;i<ncovcombmax;i++)
                   12253:     invalidvarcomb[i]=0;
                   12254:   
1.211     brouard  12255:   /* Nbcode gives the value of the lth modality (currently 1 to 2) of jth covariate, in
1.186     brouard  12256:      V2+V1*age, there are 3 covariates Tvar[2]=1 (V1).*/
1.211     brouard  12257:   /* 1 to ncodemax[j] which is the maximum value of this jth covariate */
1.227     brouard  12258:   
1.200     brouard  12259:   /*  codtab=imatrix(1,100,1,10);*/ /* codtab[h,k]=( (h-1) - mod(k-1,2**(k-1) )/2**(k-1) */
1.198     brouard  12260:   /*printf(" codtab[1,1],codtab[100,10]=%d,%d\n", codtab[1][1],codtabm(100,10));*/
1.186     brouard  12261:   /* codtab gives the value 1 or 2 of the hth combination of k covariates (1 or 2).*/
1.211     brouard  12262:   /* nbcode[Tvaraff[j]][codtabm(h,j)]) : if there are only 2 modalities for a covariate j, 
                   12263:    * codtabm(h,j) gives its value classified at position h and nbcode gives how it is coded 
                   12264:    * (currently 0 or 1) in the data.
                   12265:    * In a loop on h=1 to 2**k, and a loop on j (=1 to k), we get the value of 
                   12266:    * corresponding modality (h,j).
                   12267:    */
                   12268: 
1.145     brouard  12269:   h=0;
                   12270:   /*if (cptcovn > 0) */
1.126     brouard  12271:   m=pow(2,cptcoveff);
                   12272:  
1.144     brouard  12273:          /**< codtab(h,k)  k   = codtab[h,k]=( (h-1) - mod(k-1,2**(k-1) )/2**(k-1) + 1
1.211     brouard  12274:           * For k=4 covariates, h goes from 1 to m=2**k
                   12275:           * codtabm(h,k)=  (1 & (h-1) >> (k-1)) + 1;
                   12276:            * #define codtabm(h,k)  (1 & (h-1) >> (k-1))+1
1.329     brouard  12277:           *     h\k   1     2     3     4   *  h-1\k-1  4  3  2  1          
                   12278:           *______________________________   *______________________
                   12279:           *     1 i=1 1 i=1 1 i=1 1 i=1 1   *     0     0  0  0  0 
                   12280:           *     2     2     1     1     1   *     1     0  0  0  1 
                   12281:           *     3 i=2 1     2     1     1   *     2     0  0  1  0 
                   12282:           *     4     2     2     1     1   *     3     0  0  1  1 
                   12283:           *     5 i=3 1 i=2 1     2     1   *     4     0  1  0  0 
                   12284:           *     6     2     1     2     1   *     5     0  1  0  1 
                   12285:           *     7 i=4 1     2     2     1   *     6     0  1  1  0 
                   12286:           *     8     2     2     2     1   *     7     0  1  1  1 
                   12287:           *     9 i=5 1 i=3 1 i=2 1     2   *     8     1  0  0  0 
                   12288:           *    10     2     1     1     2   *     9     1  0  0  1 
                   12289:           *    11 i=6 1     2     1     2   *    10     1  0  1  0 
                   12290:           *    12     2     2     1     2   *    11     1  0  1  1 
                   12291:           *    13 i=7 1 i=4 1     2     2   *    12     1  1  0  0  
                   12292:           *    14     2     1     2     2   *    13     1  1  0  1 
                   12293:           *    15 i=8 1     2     2     2   *    14     1  1  1  0 
                   12294:           *    16     2     2     2     2   *    15     1  1  1  1          
                   12295:           */                                     
1.212     brouard  12296:   /* How to do the opposite? From combination h (=1 to 2**k) how to get the value on the covariates? */
1.211     brouard  12297:      /* from h=5 and m, we get then number of covariates k=log(m)/log(2)=4
                   12298:      * and the value of each covariate?
                   12299:      * V1=1, V2=1, V3=2, V4=1 ?
                   12300:      * h-1=4 and 4 is 0100 or reverse 0010, and +1 is 1121 ok.
                   12301:      * h=6, 6-1=5, 5 is 0101, 1010, 2121, V1=2nd, V2=1st, V3=2nd, V4=1st.
                   12302:      * In order to get the real value in the data, we use nbcode
                   12303:      * nbcode[Tvar[3][2nd]]=1 and nbcode[Tvar[4][1]]=0
                   12304:      * We are keeping this crazy system in order to be able (in the future?) 
                   12305:      * to have more than 2 values (0 or 1) for a covariate.
                   12306:      * #define codtabm(h,k)  (1 & (h-1) >> (k-1))+1
                   12307:      * h=6, k=2? h-1=5=0101, reverse 1010, +1=2121, k=2nd position: value is 1: codtabm(6,2)=1
                   12308:      *              bbbbbbbb
                   12309:      *              76543210     
                   12310:      *   h-1        00000101 (6-1=5)
1.219     brouard  12311:      *(h-1)>>(k-1)= 00000010 >> (2-1) = 1 right shift
1.211     brouard  12312:      *           &
                   12313:      *     1        00000001 (1)
1.219     brouard  12314:      *              00000000        = 1 & ((h-1) >> (k-1))
                   12315:      *          +1= 00000001 =1 
1.211     brouard  12316:      *
                   12317:      * h=14, k=3 => h'=h-1=13, k'=k-1=2
                   12318:      *          h'      1101 =2^3+2^2+0x2^1+2^0
                   12319:      *    >>k'            11
                   12320:      *          &   00000001
                   12321:      *            = 00000001
                   12322:      *      +1    = 00000010=2    =  codtabm(14,3)   
                   12323:      * Reverse h=6 and m=16?
                   12324:      * cptcoveff=log(16)/log(2)=4 covariate: 6-1=5=0101 reversed=1010 +1=2121 =>V1=2, V2=1, V3=2, V4=1.
                   12325:      * for (j=1 to cptcoveff) Vj=decodtabm(j,h,cptcoveff)
                   12326:      * decodtabm(h,j,cptcoveff)= (((h-1) >> (j-1)) & 1) +1 
                   12327:      * decodtabm(h,j,cptcoveff)= (h <= (1<<cptcoveff)?(((h-1) >> (j-1)) & 1) +1 : -1)
                   12328:      * V3=decodtabm(14,3,2**4)=2
                   12329:      *          h'=13   1101 =2^3+2^2+0x2^1+2^0
                   12330:      *(h-1) >> (j-1)    0011 =13 >> 2
                   12331:      *          &1 000000001
                   12332:      *           = 000000001
                   12333:      *         +1= 000000010 =2
                   12334:      *                  2211
                   12335:      *                  V1=1+1, V2=0+1, V3=1+1, V4=1+1
                   12336:      *                  V3=2
1.220     brouard  12337:                 * codtabm and decodtabm are identical
1.211     brouard  12338:      */
                   12339: 
1.145     brouard  12340: 
                   12341:  free_ivector(Ndum,-1,NCOVMAX);
                   12342: 
                   12343: 
1.126     brouard  12344:     
1.186     brouard  12345:   /* Initialisation of ----------- gnuplot -------------*/
1.126     brouard  12346:   strcpy(optionfilegnuplot,optionfilefiname);
                   12347:   if(mle==-3)
1.201     brouard  12348:     strcat(optionfilegnuplot,"-MORT_");
1.126     brouard  12349:   strcat(optionfilegnuplot,".gp");
                   12350: 
                   12351:   if((ficgp=fopen(optionfilegnuplot,"w"))==NULL) {
                   12352:     printf("Problem with file %s",optionfilegnuplot);
                   12353:   }
                   12354:   else{
1.204     brouard  12355:     fprintf(ficgp,"\n# IMaCh-%s\n", version); 
1.126     brouard  12356:     fprintf(ficgp,"# %s\n", optionfilegnuplot); 
1.141     brouard  12357:     //fprintf(ficgp,"set missing 'NaNq'\n");
                   12358:     fprintf(ficgp,"set datafile missing 'NaNq'\n");
1.126     brouard  12359:   }
                   12360:   /*  fclose(ficgp);*/
1.186     brouard  12361: 
                   12362: 
                   12363:   /* Initialisation of --------- index.htm --------*/
1.126     brouard  12364: 
                   12365:   strcpy(optionfilehtm,optionfilefiname); /* Main html file */
                   12366:   if(mle==-3)
1.201     brouard  12367:     strcat(optionfilehtm,"-MORT_");
1.126     brouard  12368:   strcat(optionfilehtm,".htm");
                   12369:   if((fichtm=fopen(optionfilehtm,"w"))==NULL)    {
1.131     brouard  12370:     printf("Problem with %s \n",optionfilehtm);
                   12371:     exit(0);
1.126     brouard  12372:   }
                   12373: 
                   12374:   strcpy(optionfilehtmcov,optionfilefiname); /* Only for matrix of covariance */
                   12375:   strcat(optionfilehtmcov,"-cov.htm");
                   12376:   if((fichtmcov=fopen(optionfilehtmcov,"w"))==NULL)    {
                   12377:     printf("Problem with %s \n",optionfilehtmcov), exit(0);
                   12378:   }
                   12379:   else{
                   12380:   fprintf(fichtmcov,"<html><head>\n<title>IMaCh Cov %s</title></head>\n <body><font size=\"2\">%s <br> %s</font> \
                   12381: <hr size=\"2\" color=\"#EC5E5E\"> \n\
1.204     brouard  12382: Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=1+age+%s<br>\n",\
1.126     brouard  12383:          optionfilehtmcov,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model);
                   12384:   }
                   12385: 
1.324     brouard  12386:   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  12387: <hr size=\"2\" color=\"#EC5E5E\"> \n\
                   12388: <font size=\"2\">IMaCh-%s <br> %s</font> \
1.126     brouard  12389: <hr size=\"2\" color=\"#EC5E5E\"> \n\
1.204     brouard  12390: Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=1+age+%s<br>\n\
1.126     brouard  12391: \n\
                   12392: <hr  size=\"2\" color=\"#EC5E5E\">\
                   12393:  <ul><li><h4>Parameter files</h4>\n\
                   12394:  - Parameter file: <a href=\"%s.%s\">%s.%s</a><br>\n\
                   12395:  - Copy of the parameter file: <a href=\"o%s\">o%s</a><br>\n\
                   12396:  - Log file of the run: <a href=\"%s\">%s</a><br>\n\
                   12397:  - Gnuplot file name: <a href=\"%s\">%s</a><br>\n\
                   12398:  - Date and time at start: %s</ul>\n",\
                   12399:          optionfilehtm,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model,\
                   12400:          optionfilefiname,optionfilext,optionfilefiname,optionfilext,\
                   12401:          fileres,fileres,\
                   12402:          filelog,filelog,optionfilegnuplot,optionfilegnuplot,strstart);
                   12403:   fflush(fichtm);
                   12404: 
                   12405:   strcpy(pathr,path);
                   12406:   strcat(pathr,optionfilefiname);
1.184     brouard  12407: #ifdef WIN32
                   12408:   _chdir(optionfilefiname); /* Move to directory named optionfile */
                   12409: #else
1.126     brouard  12410:   chdir(optionfilefiname); /* Move to directory named optionfile */
1.184     brouard  12411: #endif
                   12412:          
1.126     brouard  12413:   
1.220     brouard  12414:   /* Calculates basic frequencies. Computes observed prevalence at single age 
                   12415:                 and for any valid combination of covariates
1.126     brouard  12416:      and prints on file fileres'p'. */
1.251     brouard  12417:   freqsummary(fileres, p, pstart, agemin, agemax, s, agev, nlstate, imx, Tvaraff, invalidvarcomb, nbcode, ncodemax,mint,anint,strstart, \
1.227     brouard  12418:              firstpass, lastpass,  stepm,  weightopt, model);
1.126     brouard  12419: 
                   12420:   fprintf(fichtm,"\n");
1.286     brouard  12421:   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  12422:          ftol, stepm);
                   12423:   fprintf(fichtm,"\n<li>Number of fixed dummy covariates: ncovcol=%d ", ncovcol);
                   12424:   ncurrv=1;
                   12425:   for(i=ncurrv; i <=ncovcol; i++) fprintf(fichtm,"V%d ", i);
                   12426:   fprintf(fichtm,"\n<li> Number of fixed quantitative variables: nqv=%d ", nqv); 
                   12427:   ncurrv=i;
                   12428:   for(i=ncurrv; i <=ncurrv-1+nqv; i++) fprintf(fichtm,"V%d ", i);
1.290     brouard  12429:   fprintf(fichtm,"\n<li> Number of time varying (wave varying) dummy covariates: ntv=%d ", ntv);
1.274     brouard  12430:   ncurrv=i;
                   12431:   for(i=ncurrv; i <=ncurrv-1+ntv; i++) fprintf(fichtm,"V%d ", i);
1.290     brouard  12432:   fprintf(fichtm,"\n<li>Number of time varying  quantitative covariates: nqtv=%d ", nqtv);
1.274     brouard  12433:   ncurrv=i;
                   12434:   for(i=ncurrv; i <=ncurrv-1+nqtv; i++) fprintf(fichtm,"V%d ", i);
                   12435:   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", \
                   12436:           nlstate, ndeath, maxwav, mle, weightopt);
                   12437: 
                   12438:   fprintf(fichtm,"<h4> Diagram of states <a href=\"%s_.svg\">%s_.svg</a></h4> \n\
                   12439: <img src=\"%s_.svg\">", subdirf2(optionfilefiname,"D_"),subdirf2(optionfilefiname,"D_"),subdirf2(optionfilefiname,"D_"));
                   12440: 
                   12441:   
1.317     brouard  12442:   fprintf(fichtm,"\n<h4>Some descriptive statistics </h4>\n<br>Number of (used) observations=%d <br>\n\
1.126     brouard  12443: Youngest age at first (selected) pass %.2f, oldest age %.2f<br>\n\
                   12444: Interval (in months) between two waves: Min=%d Max=%d Mean=%.2lf<br>\n",\
1.274     brouard  12445:   imx,agemin,agemax,jmin,jmax,jmean);
1.126     brouard  12446:   pmmij= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
1.268     brouard  12447:   oldms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
                   12448:   newms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
                   12449:   savms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
                   12450:   oldm=oldms; newm=newms; savm=savms; /* Keeps fixed addresses to free */
1.218     brouard  12451: 
1.126     brouard  12452:   /* For Powell, parameters are in a vector p[] starting at p[1]
                   12453:      so we point p on param[1][1] so that p[1] maps on param[1][1][1] */
                   12454:   p=param[1][1]; /* *(*(*(param +1)+1)+0) */
                   12455: 
                   12456:   globpr=0; /* To get the number ipmx of contributions and the sum of weights*/
1.186     brouard  12457:   /* For mortality only */
1.126     brouard  12458:   if (mle==-3){
1.136     brouard  12459:     ximort=matrix(1,NDIM,1,NDIM); 
1.248     brouard  12460:     for(i=1;i<=NDIM;i++)
                   12461:       for(j=1;j<=NDIM;j++)
                   12462:        ximort[i][j]=0.;
1.186     brouard  12463:     /*     ximort=gsl_matrix_alloc(1,NDIM,1,NDIM); */
1.290     brouard  12464:     cens=ivector(firstobs,lastobs);
                   12465:     ageexmed=vector(firstobs,lastobs);
                   12466:     agecens=vector(firstobs,lastobs);
                   12467:     dcwave=ivector(firstobs,lastobs);
1.223     brouard  12468:                
1.126     brouard  12469:     for (i=1; i<=imx; i++){
                   12470:       dcwave[i]=-1;
                   12471:       for (m=firstpass; m<=lastpass; m++)
1.226     brouard  12472:        if (s[m][i]>nlstate) {
                   12473:          dcwave[i]=m;
                   12474:          /*    printf("i=%d j=%d s=%d dcwave=%d\n",i,j, s[j][i],dcwave[i]);*/
                   12475:          break;
                   12476:        }
1.126     brouard  12477:     }
1.226     brouard  12478:     
1.126     brouard  12479:     for (i=1; i<=imx; i++) {
                   12480:       if (wav[i]>0){
1.226     brouard  12481:        ageexmed[i]=agev[mw[1][i]][i];
                   12482:        j=wav[i];
                   12483:        agecens[i]=1.; 
                   12484:        
                   12485:        if (ageexmed[i]> 1 && wav[i] > 0){
                   12486:          agecens[i]=agev[mw[j][i]][i];
                   12487:          cens[i]= 1;
                   12488:        }else if (ageexmed[i]< 1) 
                   12489:          cens[i]= -1;
                   12490:        if (agedc[i]< AGESUP && agedc[i]>1 && dcwave[i]>firstpass && dcwave[i]<=lastpass)
                   12491:          cens[i]=0 ;
1.126     brouard  12492:       }
                   12493:       else cens[i]=-1;
                   12494:     }
                   12495:     
                   12496:     for (i=1;i<=NDIM;i++) {
                   12497:       for (j=1;j<=NDIM;j++)
1.226     brouard  12498:        ximort[i][j]=(i == j ? 1.0 : 0.0);
1.126     brouard  12499:     }
                   12500:     
1.302     brouard  12501:     p[1]=0.0268; p[NDIM]=0.083;
                   12502:     /* printf("%lf %lf", p[1], p[2]); */
1.126     brouard  12503:     
                   12504:     
1.136     brouard  12505: #ifdef GSL
                   12506:     printf("GSL optimization\n");  fprintf(ficlog,"Powell\n");
1.162     brouard  12507: #else
1.126     brouard  12508:     printf("Powell\n");  fprintf(ficlog,"Powell\n");
1.136     brouard  12509: #endif
1.201     brouard  12510:     strcpy(filerespow,"POW-MORT_"); 
                   12511:     strcat(filerespow,fileresu);
1.126     brouard  12512:     if((ficrespow=fopen(filerespow,"w"))==NULL) {
                   12513:       printf("Problem with resultfile: %s\n", filerespow);
                   12514:       fprintf(ficlog,"Problem with resultfile: %s\n", filerespow);
                   12515:     }
1.136     brouard  12516: #ifdef GSL
                   12517:     fprintf(ficrespow,"# GSL optimization\n# iter -2*LL");
1.162     brouard  12518: #else
1.126     brouard  12519:     fprintf(ficrespow,"# Powell\n# iter -2*LL");
1.136     brouard  12520: #endif
1.126     brouard  12521:     /*  for (i=1;i<=nlstate;i++)
                   12522:        for(j=1;j<=nlstate+ndeath;j++)
                   12523:        if(j!=i)fprintf(ficrespow," p%1d%1d",i,j);
                   12524:     */
                   12525:     fprintf(ficrespow,"\n");
1.136     brouard  12526: #ifdef GSL
                   12527:     /* gsl starts here */ 
                   12528:     T = gsl_multimin_fminimizer_nmsimplex;
                   12529:     gsl_multimin_fminimizer *sfm = NULL;
                   12530:     gsl_vector *ss, *x;
                   12531:     gsl_multimin_function minex_func;
                   12532: 
                   12533:     /* Initial vertex size vector */
                   12534:     ss = gsl_vector_alloc (NDIM);
                   12535:     
                   12536:     if (ss == NULL){
                   12537:       GSL_ERROR_VAL ("failed to allocate space for ss", GSL_ENOMEM, 0);
                   12538:     }
                   12539:     /* Set all step sizes to 1 */
                   12540:     gsl_vector_set_all (ss, 0.001);
                   12541: 
                   12542:     /* Starting point */
1.126     brouard  12543:     
1.136     brouard  12544:     x = gsl_vector_alloc (NDIM);
                   12545:     
                   12546:     if (x == NULL){
                   12547:       gsl_vector_free(ss);
                   12548:       GSL_ERROR_VAL ("failed to allocate space for x", GSL_ENOMEM, 0);
                   12549:     }
                   12550:   
                   12551:     /* Initialize method and iterate */
                   12552:     /*     p[1]=0.0268; p[NDIM]=0.083; */
1.186     brouard  12553:     /*     gsl_vector_set(x, 0, 0.0268); */
                   12554:     /*     gsl_vector_set(x, 1, 0.083); */
1.136     brouard  12555:     gsl_vector_set(x, 0, p[1]);
                   12556:     gsl_vector_set(x, 1, p[2]);
                   12557: 
                   12558:     minex_func.f = &gompertz_f;
                   12559:     minex_func.n = NDIM;
                   12560:     minex_func.params = (void *)&p; /* ??? */
                   12561:     
                   12562:     sfm = gsl_multimin_fminimizer_alloc (T, NDIM);
                   12563:     gsl_multimin_fminimizer_set (sfm, &minex_func, x, ss);
                   12564:     
                   12565:     printf("Iterations beginning .....\n\n");
                   12566:     printf("Iter. #    Intercept       Slope     -Log Likelihood     Simplex size\n");
                   12567: 
                   12568:     iteri=0;
                   12569:     while (rval == GSL_CONTINUE){
                   12570:       iteri++;
                   12571:       status = gsl_multimin_fminimizer_iterate(sfm);
                   12572:       
                   12573:       if (status) printf("error: %s\n", gsl_strerror (status));
                   12574:       fflush(0);
                   12575:       
                   12576:       if (status) 
                   12577:         break;
                   12578:       
                   12579:       rval = gsl_multimin_test_size (gsl_multimin_fminimizer_size (sfm), 1e-6);
                   12580:       ssval = gsl_multimin_fminimizer_size (sfm);
                   12581:       
                   12582:       if (rval == GSL_SUCCESS)
                   12583:         printf ("converged to a local maximum at\n");
                   12584:       
                   12585:       printf("%5d ", iteri);
                   12586:       for (it = 0; it < NDIM; it++){
                   12587:        printf ("%10.5f ", gsl_vector_get (sfm->x, it));
                   12588:       }
                   12589:       printf("f() = %-10.5f ssize = %.7f\n", sfm->fval, ssval);
                   12590:     }
                   12591:     
                   12592:     printf("\n\n Please note: Program should be run many times with varying starting points to detemine global maximum\n\n");
                   12593:     
                   12594:     gsl_vector_free(x); /* initial values */
                   12595:     gsl_vector_free(ss); /* inital step size */
                   12596:     for (it=0; it<NDIM; it++){
                   12597:       p[it+1]=gsl_vector_get(sfm->x,it);
                   12598:       fprintf(ficrespow," %.12lf", p[it]);
                   12599:     }
                   12600:     gsl_multimin_fminimizer_free (sfm); /* p *(sfm.x.data) et p *(sfm.x.data+1)  */
                   12601: #endif
                   12602: #ifdef POWELL
                   12603:      powell(p,ximort,NDIM,ftol,&iter,&fret,gompertz);
                   12604: #endif  
1.126     brouard  12605:     fclose(ficrespow);
                   12606:     
1.203     brouard  12607:     hesscov(matcov, hess, p, NDIM, delti, 1e-4, gompertz); 
1.126     brouard  12608: 
                   12609:     for(i=1; i <=NDIM; i++)
                   12610:       for(j=i+1;j<=NDIM;j++)
1.220     brouard  12611:                                matcov[i][j]=matcov[j][i];
1.126     brouard  12612:     
                   12613:     printf("\nCovariance matrix\n ");
1.203     brouard  12614:     fprintf(ficlog,"\nCovariance matrix\n ");
1.126     brouard  12615:     for(i=1; i <=NDIM; i++) {
                   12616:       for(j=1;j<=NDIM;j++){ 
1.220     brouard  12617:                                printf("%f ",matcov[i][j]);
                   12618:                                fprintf(ficlog,"%f ",matcov[i][j]);
1.126     brouard  12619:       }
1.203     brouard  12620:       printf("\n ");  fprintf(ficlog,"\n ");
1.126     brouard  12621:     }
                   12622:     
                   12623:     printf("iter=%d MLE=%f Eq=%lf*exp(%lf*(age-%d))\n",iter,-gompertz(p),p[1],p[2],agegomp);
1.193     brouard  12624:     for (i=1;i<=NDIM;i++) {
1.126     brouard  12625:       printf("%f [%f ; %f]\n",p[i],p[i]-2*sqrt(matcov[i][i]),p[i]+2*sqrt(matcov[i][i]));
1.193     brouard  12626:       fprintf(ficlog,"%f [%f ; %f]\n",p[i],p[i]-2*sqrt(matcov[i][i]),p[i]+2*sqrt(matcov[i][i]));
                   12627:     }
1.302     brouard  12628:     lsurv=vector(agegomp,AGESUP);
                   12629:     lpop=vector(agegomp,AGESUP);
                   12630:     tpop=vector(agegomp,AGESUP);
1.126     brouard  12631:     lsurv[agegomp]=100000;
                   12632:     
                   12633:     for (k=agegomp;k<=AGESUP;k++) {
                   12634:       agemortsup=k;
                   12635:       if (p[1]*exp(p[2]*(k-agegomp))>1) break;
                   12636:     }
                   12637:     
                   12638:     for (k=agegomp;k<agemortsup;k++)
                   12639:       lsurv[k+1]=lsurv[k]-lsurv[k]*(p[1]*exp(p[2]*(k-agegomp)));
                   12640:     
                   12641:     for (k=agegomp;k<agemortsup;k++){
                   12642:       lpop[k]=(lsurv[k]+lsurv[k+1])/2.;
                   12643:       sumlpop=sumlpop+lpop[k];
                   12644:     }
                   12645:     
                   12646:     tpop[agegomp]=sumlpop;
                   12647:     for (k=agegomp;k<(agemortsup-3);k++){
                   12648:       /*  tpop[k+1]=2;*/
                   12649:       tpop[k+1]=tpop[k]-lpop[k];
                   12650:     }
                   12651:     
                   12652:     
                   12653:     printf("\nAge   lx     qx    dx    Lx     Tx     e(x)\n");
                   12654:     for (k=agegomp;k<(agemortsup-2);k++) 
                   12655:       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]);
                   12656:     
                   12657:     
                   12658:     replace_back_to_slash(pathc,pathcd); /* Even gnuplot wants a / */
1.220     brouard  12659:                ageminpar=50;
                   12660:                agemaxpar=100;
1.194     brouard  12661:     if(ageminpar == AGEOVERFLOW ||agemaxpar == AGEOVERFLOW){
                   12662:        printf("Warning! Error in gnuplot file with ageminpar %f or agemaxpar %f overflow\n\
                   12663: This is probably because your parameter file doesn't \n  contain the exact number of lines (or columns) corresponding to your model line.\n\
                   12664: Please run with mle=-1 to get a correct covariance matrix.\n",ageminpar,agemaxpar);
                   12665:        fprintf(ficlog,"Warning! Error in gnuplot file with ageminpar %f or agemaxpar %f overflow\n\
                   12666: This is probably because your parameter file doesn't \n  contain the exact number of lines (or columns) corresponding to your model line.\n\
                   12667: Please run with mle=-1 to get a correct covariance matrix.\n",ageminpar,agemaxpar);
1.220     brouard  12668:     }else{
                   12669:                        printf("Warning! ageminpar %f and agemaxpar %f have been fixed because for simplification until it is fixed...\n\n",ageminpar,agemaxpar);
                   12670:                        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  12671:       printinggnuplotmort(fileresu, optionfilefiname,ageminpar,agemaxpar,fage, pathc,p);
1.220     brouard  12672:                }
1.201     brouard  12673:     printinghtmlmort(fileresu,title,datafile, firstpass, lastpass, \
1.126     brouard  12674:                     stepm, weightopt,\
                   12675:                     model,imx,p,matcov,agemortsup);
                   12676:     
1.302     brouard  12677:     free_vector(lsurv,agegomp,AGESUP);
                   12678:     free_vector(lpop,agegomp,AGESUP);
                   12679:     free_vector(tpop,agegomp,AGESUP);
1.220     brouard  12680:     free_matrix(ximort,1,NDIM,1,NDIM);
1.290     brouard  12681:     free_ivector(dcwave,firstobs,lastobs);
                   12682:     free_vector(agecens,firstobs,lastobs);
                   12683:     free_vector(ageexmed,firstobs,lastobs);
                   12684:     free_ivector(cens,firstobs,lastobs);
1.220     brouard  12685: #ifdef GSL
1.136     brouard  12686: #endif
1.186     brouard  12687:   } /* Endof if mle==-3 mortality only */
1.205     brouard  12688:   /* Standard  */
                   12689:   else{ /* For mle !=- 3, could be 0 or 1 or 4 etc. */
                   12690:     globpr=0;/* Computes sum of likelihood for globpr=1 and funcone */
                   12691:     /* Computes likelihood for initial parameters, uses funcone to compute gpimx and gsw */
1.132     brouard  12692:     likelione(ficres, p, npar, nlstate, &globpr, &ipmx, &sw, &fretone, funcone); /* Prints the contributions to the likelihood */
1.126     brouard  12693:     printf("First Likeli=%12.6f ipmx=%ld sw=%12.6f",fretone,ipmx,sw);
                   12694:     for (k=1; k<=npar;k++)
                   12695:       printf(" %d %8.5f",k,p[k]);
                   12696:     printf("\n");
1.205     brouard  12697:     if(mle>=1){ /* Could be 1 or 2, Real Maximization */
                   12698:       /* mlikeli uses func not funcone */
1.247     brouard  12699:       /* for(i=1;i<nlstate;i++){ */
                   12700:       /*       /\*reducing xi for 1 to npar to 1 to ncovmodel; *\/ */
                   12701:       /*    mlikeli(ficres,p, ncovmodel, ncovmodel, nlstate, ftol, funcnoprod); */
                   12702:       /* } */
1.205     brouard  12703:       mlikeli(ficres,p, npar, ncovmodel, nlstate, ftol, func);
                   12704:     }
                   12705:     if(mle==0) {/* No optimization, will print the likelihoods for the datafile */
                   12706:       globpr=0;/* Computes sum of likelihood for globpr=1 and funcone */
                   12707:       /* Computes likelihood for initial parameters, uses funcone to compute gpimx and gsw */
                   12708:       likelione(ficres, p, npar, nlstate, &globpr, &ipmx, &sw, &fretone, funcone); /* Prints the contributions to the likelihood */
                   12709:     }
                   12710:     globpr=1; /* again, to print the individual contributions using computed gpimx and gsw */
1.126     brouard  12711:     likelione(ficres, p, npar, nlstate, &globpr, &ipmx, &sw, &fretone, funcone); /* Prints the contributions to the likelihood */
                   12712:     printf("Second Likeli=%12.6f ipmx=%ld sw=%12.6f",fretone,ipmx,sw);
                   12713:     for (k=1; k<=npar;k++)
                   12714:       printf(" %d %8.5f",k,p[k]);
                   12715:     printf("\n");
                   12716:     
                   12717:     /*--------- results files --------------*/
1.283     brouard  12718:     /* 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  12719:     
                   12720:     
                   12721:     fprintf(ficres,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
1.319     brouard  12722:     printf("# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n"); /* Printing model equation */
1.126     brouard  12723:     fprintf(ficlog,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
1.319     brouard  12724: 
                   12725:     printf("#model=  1      +     age ");
                   12726:     fprintf(ficres,"#model=  1      +     age ");
                   12727:     fprintf(ficlog,"#model=  1      +     age ");
                   12728:     fprintf(fichtm,"\n<ul><li> model=1+age+%s\n \
                   12729: </ul>", model);
                   12730: 
                   12731:     fprintf(fichtm,"\n<table style=\"text-align:center; border: 1px solid\">\n");
                   12732:     fprintf(fichtm, "<tr><th>Model=</th><th>1</th><th>+ age</th>");
                   12733:     if(nagesqr==1){
                   12734:       printf("  + age*age  ");
                   12735:       fprintf(ficres,"  + age*age  ");
                   12736:       fprintf(ficlog,"  + age*age  ");
                   12737:       fprintf(fichtm, "<th>+ age*age</th>");
                   12738:     }
                   12739:     for(j=1;j <=ncovmodel-2;j++){
                   12740:       if(Typevar[j]==0) {
                   12741:        printf("  +      V%d  ",Tvar[j]);
                   12742:        fprintf(ficres,"  +      V%d  ",Tvar[j]);
                   12743:        fprintf(ficlog,"  +      V%d  ",Tvar[j]);
                   12744:        fprintf(fichtm, "<th>+ V%d</th>",Tvar[j]);
                   12745:       }else if(Typevar[j]==1) {
                   12746:        printf("  +    V%d*age ",Tvar[j]);
                   12747:        fprintf(ficres,"  +    V%d*age ",Tvar[j]);
                   12748:        fprintf(ficlog,"  +    V%d*age ",Tvar[j]);
                   12749:        fprintf(fichtm, "<th>+  V%d*age</th>",Tvar[j]);
                   12750:       }else if(Typevar[j]==2) {
                   12751:        printf("  +    V%d*V%d ",Tvard[Tposprod[j]][1],Tvard[Tposprod[j]][2]);
                   12752:        fprintf(ficres,"  +    V%d*V%d ",Tvard[Tposprod[j]][1],Tvard[Tposprod[j]][2]);
                   12753:        fprintf(ficlog,"  +    V%d*V%d ",Tvard[Tposprod[j]][1],Tvard[Tposprod[j]][2]);
                   12754:        fprintf(fichtm, "<th>+  V%d*V%d</th>",Tvard[Tposprod[j]][1],Tvard[Tposprod[j]][2]);
                   12755:       }
                   12756:     }
                   12757:     printf("\n");
                   12758:     fprintf(ficres,"\n");
                   12759:     fprintf(ficlog,"\n");
                   12760:     fprintf(fichtm, "</tr>");
                   12761:     fprintf(fichtm, "\n");
                   12762:     
                   12763:     
1.126     brouard  12764:     for(i=1,jk=1; i <=nlstate; i++){
                   12765:       for(k=1; k <=(nlstate+ndeath); k++){
1.225     brouard  12766:        if (k != i) {
1.319     brouard  12767:          fprintf(fichtm, "<tr>");
1.225     brouard  12768:          printf("%d%d ",i,k);
                   12769:          fprintf(ficlog,"%d%d ",i,k);
                   12770:          fprintf(ficres,"%1d%1d ",i,k);
1.319     brouard  12771:          fprintf(fichtm, "<td>%1d%1d</td>",i,k);
1.225     brouard  12772:          for(j=1; j <=ncovmodel; j++){
                   12773:            printf("%12.7f ",p[jk]);
                   12774:            fprintf(ficlog,"%12.7f ",p[jk]);
                   12775:            fprintf(ficres,"%12.7f ",p[jk]);
1.319     brouard  12776:            fprintf(fichtm, "<td>%12.7f</td>",p[jk]);
1.225     brouard  12777:            jk++; 
                   12778:          }
                   12779:          printf("\n");
                   12780:          fprintf(ficlog,"\n");
                   12781:          fprintf(ficres,"\n");
1.319     brouard  12782:          fprintf(fichtm, "</tr>\n");
1.225     brouard  12783:        }
1.126     brouard  12784:       }
                   12785:     }
1.319     brouard  12786:     /* fprintf(fichtm,"</tr>\n"); */
                   12787:     fprintf(fichtm,"</table>\n");
                   12788:     fprintf(fichtm, "\n");
                   12789: 
1.203     brouard  12790:     if(mle != 0){
                   12791:       /* Computing hessian and covariance matrix only at a peak of the Likelihood, that is after optimization */
1.126     brouard  12792:       ftolhess=ftol; /* Usually correct */
1.203     brouard  12793:       hesscov(matcov, hess, p, npar, delti, ftolhess, func);
                   12794:       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");
                   12795:       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  12796:       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  12797:       fprintf(fichtm,"\n<table style=\"text-align:center; border: 1px solid\">");
                   12798:       fprintf(fichtm, "\n<tr><th>Model=</th><th>1</th><th>+ age</th>");
                   12799:       if(nagesqr==1){
                   12800:        printf("  + age*age  ");
                   12801:        fprintf(ficres,"  + age*age  ");
                   12802:        fprintf(ficlog,"  + age*age  ");
                   12803:        fprintf(fichtm, "<th>+ age*age</th>");
                   12804:       }
                   12805:       for(j=1;j <=ncovmodel-2;j++){
                   12806:        if(Typevar[j]==0) {
                   12807:          printf("  +      V%d  ",Tvar[j]);
                   12808:          fprintf(fichtm, "<th>+ V%d</th>",Tvar[j]);
                   12809:        }else if(Typevar[j]==1) {
                   12810:          printf("  +    V%d*age ",Tvar[j]);
                   12811:          fprintf(fichtm, "<th>+  V%d*age</th>",Tvar[j]);
                   12812:        }else if(Typevar[j]==2) {
                   12813:          fprintf(fichtm, "<th>+  V%d*V%d</th>",Tvard[Tposprod[j]][1],Tvard[Tposprod[j]][2]);
                   12814:        }
                   12815:       }
                   12816:       fprintf(fichtm, "</tr>\n");
                   12817:  
1.203     brouard  12818:       for(i=1,jk=1; i <=nlstate; i++){
1.225     brouard  12819:        for(k=1; k <=(nlstate+ndeath); k++){
                   12820:          if (k != i) {
1.319     brouard  12821:            fprintf(fichtm, "<tr valign=top>");
1.225     brouard  12822:            printf("%d%d ",i,k);
                   12823:            fprintf(ficlog,"%d%d ",i,k);
1.319     brouard  12824:            fprintf(fichtm, "<td>%1d%1d</td>",i,k);
1.225     brouard  12825:            for(j=1; j <=ncovmodel; j++){
1.319     brouard  12826:              wald=p[jk]/sqrt(matcov[jk][jk]);
1.324     brouard  12827:              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]));
                   12828:              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  12829:              if(fabs(wald) > 1.96){
1.321     brouard  12830:                fprintf(fichtm, "<td><b>%12.7f</b></br> (%12.7f)</br>",p[jk],sqrt(matcov[jk][jk]));
1.319     brouard  12831:              }else{
                   12832:                fprintf(fichtm, "<td>%12.7f (%12.7f)</br>",p[jk],sqrt(matcov[jk][jk]));
                   12833:              }
1.324     brouard  12834:              fprintf(fichtm,"W=%8.3f</br>",wald);
1.319     brouard  12835:              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  12836:              jk++; 
                   12837:            }
                   12838:            printf("\n");
                   12839:            fprintf(ficlog,"\n");
1.319     brouard  12840:            fprintf(fichtm, "</tr>\n");
1.225     brouard  12841:          }
                   12842:        }
1.193     brouard  12843:       }
1.203     brouard  12844:     } /* end of hesscov and Wald tests */
1.319     brouard  12845:     fprintf(fichtm,"</table>\n");
1.225     brouard  12846:     
1.203     brouard  12847:     /*  */
1.126     brouard  12848:     fprintf(ficres,"# Scales (for hessian or gradient estimation)\n");
                   12849:     printf("# Scales (for hessian or gradient estimation)\n");
                   12850:     fprintf(ficlog,"# Scales (for hessian or gradient estimation)\n");
                   12851:     for(i=1,jk=1; i <=nlstate; i++){
                   12852:       for(j=1; j <=nlstate+ndeath; j++){
1.225     brouard  12853:        if (j!=i) {
                   12854:          fprintf(ficres,"%1d%1d",i,j);
                   12855:          printf("%1d%1d",i,j);
                   12856:          fprintf(ficlog,"%1d%1d",i,j);
                   12857:          for(k=1; k<=ncovmodel;k++){
                   12858:            printf(" %.5e",delti[jk]);
                   12859:            fprintf(ficlog," %.5e",delti[jk]);
                   12860:            fprintf(ficres," %.5e",delti[jk]);
                   12861:            jk++;
                   12862:          }
                   12863:          printf("\n");
                   12864:          fprintf(ficlog,"\n");
                   12865:          fprintf(ficres,"\n");
                   12866:        }
1.126     brouard  12867:       }
                   12868:     }
                   12869:     
                   12870:     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  12871:     if(mle >= 1) /* To big for the screen */
1.126     brouard  12872:       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");
                   12873:     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");
                   12874:     /* # 121 Var(a12)\n\ */
                   12875:     /* # 122 Cov(b12,a12) Var(b12)\n\ */
                   12876:     /* # 131 Cov(a13,a12) Cov(a13,b12, Var(a13)\n\ */
                   12877:     /* # 132 Cov(b13,a12) Cov(b13,b12, Cov(b13,a13) Var(b13)\n\ */
                   12878:     /* # 212 Cov(a21,a12) Cov(a21,b12, Cov(a21,a13) Cov(a21,b13) Var(a21)\n\ */
                   12879:     /* # 212 Cov(b21,a12) Cov(b21,b12, Cov(b21,a13) Cov(b21,b13) Cov(b21,a21) Var(b21)\n\ */
                   12880:     /* # 232 Cov(a23,a12) Cov(a23,b12, Cov(a23,a13) Cov(a23,b13) Cov(a23,a21) Cov(a23,b21) Var(a23)\n\ */
                   12881:     /* # 232 Cov(b23,a12) Cov(b23,b12) ... Var (b23)\n" */
                   12882:     
                   12883:     
                   12884:     /* Just to have a covariance matrix which will be more understandable
                   12885:        even is we still don't want to manage dictionary of variables
                   12886:     */
                   12887:     for(itimes=1;itimes<=2;itimes++){
                   12888:       jj=0;
                   12889:       for(i=1; i <=nlstate; i++){
1.225     brouard  12890:        for(j=1; j <=nlstate+ndeath; j++){
                   12891:          if(j==i) continue;
                   12892:          for(k=1; k<=ncovmodel;k++){
                   12893:            jj++;
                   12894:            ca[0]= k+'a'-1;ca[1]='\0';
                   12895:            if(itimes==1){
                   12896:              if(mle>=1)
                   12897:                printf("#%1d%1d%d",i,j,k);
                   12898:              fprintf(ficlog,"#%1d%1d%d",i,j,k);
                   12899:              fprintf(ficres,"#%1d%1d%d",i,j,k);
                   12900:            }else{
                   12901:              if(mle>=1)
                   12902:                printf("%1d%1d%d",i,j,k);
                   12903:              fprintf(ficlog,"%1d%1d%d",i,j,k);
                   12904:              fprintf(ficres,"%1d%1d%d",i,j,k);
                   12905:            }
                   12906:            ll=0;
                   12907:            for(li=1;li <=nlstate; li++){
                   12908:              for(lj=1;lj <=nlstate+ndeath; lj++){
                   12909:                if(lj==li) continue;
                   12910:                for(lk=1;lk<=ncovmodel;lk++){
                   12911:                  ll++;
                   12912:                  if(ll<=jj){
                   12913:                    cb[0]= lk +'a'-1;cb[1]='\0';
                   12914:                    if(ll<jj){
                   12915:                      if(itimes==1){
                   12916:                        if(mle>=1)
                   12917:                          printf(" Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
                   12918:                        fprintf(ficlog," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
                   12919:                        fprintf(ficres," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
                   12920:                      }else{
                   12921:                        if(mle>=1)
                   12922:                          printf(" %.5e",matcov[jj][ll]); 
                   12923:                        fprintf(ficlog," %.5e",matcov[jj][ll]); 
                   12924:                        fprintf(ficres," %.5e",matcov[jj][ll]); 
                   12925:                      }
                   12926:                    }else{
                   12927:                      if(itimes==1){
                   12928:                        if(mle>=1)
                   12929:                          printf(" Var(%s%1d%1d)",ca,i,j);
                   12930:                        fprintf(ficlog," Var(%s%1d%1d)",ca,i,j);
                   12931:                        fprintf(ficres," Var(%s%1d%1d)",ca,i,j);
                   12932:                      }else{
                   12933:                        if(mle>=1)
                   12934:                          printf(" %.7e",matcov[jj][ll]); 
                   12935:                        fprintf(ficlog," %.7e",matcov[jj][ll]); 
                   12936:                        fprintf(ficres," %.7e",matcov[jj][ll]); 
                   12937:                      }
                   12938:                    }
                   12939:                  }
                   12940:                } /* end lk */
                   12941:              } /* end lj */
                   12942:            } /* end li */
                   12943:            if(mle>=1)
                   12944:              printf("\n");
                   12945:            fprintf(ficlog,"\n");
                   12946:            fprintf(ficres,"\n");
                   12947:            numlinepar++;
                   12948:          } /* end k*/
                   12949:        } /*end j */
1.126     brouard  12950:       } /* end i */
                   12951:     } /* end itimes */
                   12952:     
                   12953:     fflush(ficlog);
                   12954:     fflush(ficres);
1.225     brouard  12955:     while(fgets(line, MAXLINE, ficpar)) {
                   12956:       /* If line starts with a # it is a comment */
                   12957:       if (line[0] == '#') {
                   12958:        numlinepar++;
                   12959:        fputs(line,stdout);
                   12960:        fputs(line,ficparo);
                   12961:        fputs(line,ficlog);
1.299     brouard  12962:        fputs(line,ficres);
1.225     brouard  12963:        continue;
                   12964:       }else
                   12965:        break;
                   12966:     }
                   12967:     
1.209     brouard  12968:     /* while((c=getc(ficpar))=='#' && c!= EOF){ */
                   12969:     /*   ungetc(c,ficpar); */
                   12970:     /*   fgets(line, MAXLINE, ficpar); */
                   12971:     /*   fputs(line,stdout); */
                   12972:     /*   fputs(line,ficparo); */
                   12973:     /* } */
                   12974:     /* ungetc(c,ficpar); */
1.126     brouard  12975:     
                   12976:     estepm=0;
1.209     brouard  12977:     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  12978:       
                   12979:       if (num_filled != 6) {
                   12980:        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);
                   12981:        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);
                   12982:        goto end;
                   12983:       }
                   12984:       printf("agemin=%lf agemax=%lf bage=%lf fage=%lf estepm=%d ftolpl=%lf\n",ageminpar,agemaxpar, bage, fage, estepm, ftolpl);
                   12985:     }
                   12986:     /* ftolpl=6*ftol*1.e5; /\* 6.e-3 make convergences in less than 80 loops for the prevalence limit *\/ */
                   12987:     /*ftolpl=6.e-4;*/ /* 6.e-3 make convergences in less than 80 loops for the prevalence limit */
                   12988:     
1.209     brouard  12989:     /* fscanf(ficpar,"agemin=%lf agemax=%lf bage=%lf fage=%lf estepm=%d ftolpl=%\n",&ageminpar,&agemaxpar, &bage, &fage, &estepm); */
1.126     brouard  12990:     if (estepm==0 || estepm < stepm) estepm=stepm;
                   12991:     if (fage <= 2) {
                   12992:       bage = ageminpar;
                   12993:       fage = agemaxpar;
                   12994:     }
                   12995:     
                   12996:     fprintf(ficres,"# agemin agemax for life expectancy, bage fage (if mle==0 ie no data nor Max likelihood).\n");
1.211     brouard  12997:     fprintf(ficres,"agemin=%.0f agemax=%.0f bage=%.0f fage=%.0f estepm=%d ftolpl=%e\n",ageminpar,agemaxpar,bage,fage, estepm, ftolpl);
                   12998:     fprintf(ficparo,"agemin=%.0f agemax=%.0f bage=%.0f fage=%.0f estepm=%d, ftolpl=%e\n",ageminpar,agemaxpar,bage,fage, estepm, ftolpl);
1.220     brouard  12999:                
1.186     brouard  13000:     /* Other stuffs, more or less useful */    
1.254     brouard  13001:     while(fgets(line, MAXLINE, ficpar)) {
                   13002:       /* If line starts with a # it is a comment */
                   13003:       if (line[0] == '#') {
                   13004:        numlinepar++;
                   13005:        fputs(line,stdout);
                   13006:        fputs(line,ficparo);
                   13007:        fputs(line,ficlog);
1.299     brouard  13008:        fputs(line,ficres);
1.254     brouard  13009:        continue;
                   13010:       }else
                   13011:        break;
                   13012:     }
                   13013: 
                   13014:     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){
                   13015:       
                   13016:       if (num_filled != 7) {
                   13017:        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);
                   13018:        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);
                   13019:        goto end;
                   13020:       }
                   13021:       printf("begin-prev-date=%.lf/%.lf/%.lf end-prev-date=%.lf/%.lf/%.lf mov_average=%d\n",jprev1, mprev1,anprev1,jprev2, mprev2,anprev2,mobilav);
                   13022:       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);
                   13023:       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);
                   13024:       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  13025:     }
1.254     brouard  13026: 
                   13027:     while(fgets(line, MAXLINE, ficpar)) {
                   13028:       /* If line starts with a # it is a comment */
                   13029:       if (line[0] == '#') {
                   13030:        numlinepar++;
                   13031:        fputs(line,stdout);
                   13032:        fputs(line,ficparo);
                   13033:        fputs(line,ficlog);
1.299     brouard  13034:        fputs(line,ficres);
1.254     brouard  13035:        continue;
                   13036:       }else
                   13037:        break;
1.126     brouard  13038:     }
                   13039:     
                   13040:     
                   13041:     dateprev1=anprev1+(mprev1-1)/12.+(jprev1-1)/365.;
                   13042:     dateprev2=anprev2+(mprev2-1)/12.+(jprev2-1)/365.;
                   13043:     
1.254     brouard  13044:     if((num_filled=sscanf(line,"pop_based=%d\n",&popbased)) !=EOF){
                   13045:       if (num_filled != 1) {
                   13046:        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);
                   13047:        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);
                   13048:        goto end;
                   13049:       }
                   13050:       printf("pop_based=%d\n",popbased);
                   13051:       fprintf(ficlog,"pop_based=%d\n",popbased);
                   13052:       fprintf(ficparo,"pop_based=%d\n",popbased);   
                   13053:       fprintf(ficres,"pop_based=%d\n",popbased);   
                   13054:     }
                   13055:      
1.258     brouard  13056:     /* Results */
1.307     brouard  13057:     endishere=0;
1.258     brouard  13058:     nresult=0;
1.308     brouard  13059:     parameterline=0;
1.258     brouard  13060:     do{
                   13061:       if(!fgets(line, MAXLINE, ficpar)){
                   13062:        endishere=1;
1.308     brouard  13063:        parameterline=15;
1.258     brouard  13064:       }else if (line[0] == '#') {
                   13065:        /* If line starts with a # it is a comment */
1.254     brouard  13066:        numlinepar++;
                   13067:        fputs(line,stdout);
                   13068:        fputs(line,ficparo);
                   13069:        fputs(line,ficlog);
1.299     brouard  13070:        fputs(line,ficres);
1.254     brouard  13071:        continue;
1.258     brouard  13072:       }else if(sscanf(line,"prevforecast=%[^\n]\n",modeltemp))
                   13073:        parameterline=11;
1.296     brouard  13074:       else if(sscanf(line,"prevbackcast=%[^\n]\n",modeltemp))
1.258     brouard  13075:        parameterline=12;
1.307     brouard  13076:       else if(sscanf(line,"result:%[^\n]\n",modeltemp)){
1.258     brouard  13077:        parameterline=13;
1.307     brouard  13078:       }
1.258     brouard  13079:       else{
                   13080:        parameterline=14;
1.254     brouard  13081:       }
1.308     brouard  13082:       switch (parameterline){ /* =0 only if only comments */
1.258     brouard  13083:       case 11:
1.296     brouard  13084:        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)){
                   13085:                  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  13086:          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);
                   13087:          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);
                   13088:          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);
                   13089:          /* day and month of proj2 are not used but only year anproj2.*/
1.273     brouard  13090:          dateproj1=anproj1+(mproj1-1)/12.+(jproj1-1)/365.;
                   13091:          dateproj2=anproj2+(mproj2-1)/12.+(jproj2-1)/365.;
1.296     brouard  13092:           prvforecast = 1;
                   13093:        } 
                   13094:        else if((num_filled=sscanf(line,"prevforecast=%d yearsfproj=%lf mobil_average=%d\n",&prevfcast,&yrfproj,&mobilavproj)) !=EOF){/* && (num_filled == 3))*/
1.313     brouard  13095:          printf("prevforecast=%d yearsfproj=%.2lf mobil_average=%d\n",prevfcast,yrfproj,mobilavproj);
                   13096:          fprintf(ficlog,"prevforecast=%d yearsfproj=%.2lf mobil_average=%d\n",prevfcast,yrfproj,mobilavproj);
                   13097:          fprintf(ficres,"prevforecast=%d yearsfproj=%.2lf mobil_average=%d\n",prevfcast,yrfproj,mobilavproj);
1.296     brouard  13098:           prvforecast = 2;
                   13099:        }
                   13100:        else {
                   13101:          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);
                   13102:          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);
                   13103:          goto end;
1.258     brouard  13104:        }
1.254     brouard  13105:        break;
1.258     brouard  13106:       case 12:
1.296     brouard  13107:        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)){
                   13108:           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);
                   13109:          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);
                   13110:          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);
                   13111:          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);
                   13112:          /* day and month of back2 are not used but only year anback2.*/
1.273     brouard  13113:          dateback1=anback1+(mback1-1)/12.+(jback1-1)/365.;
                   13114:          dateback2=anback2+(mback2-1)/12.+(jback2-1)/365.;
1.296     brouard  13115:           prvbackcast = 1;
                   13116:        } 
                   13117:        else if((num_filled=sscanf(line,"prevbackcast=%d yearsbproj=%lf mobil_average=%d\n",&prevbcast,&yrbproj,&mobilavproj)) ==3){/* && (num_filled == 3))*/
1.313     brouard  13118:          printf("prevbackcast=%d yearsbproj=%.2lf mobil_average=%d\n",prevbcast,yrbproj,mobilavproj);
                   13119:          fprintf(ficlog,"prevbackcast=%d yearsbproj=%.2lf mobil_average=%d\n",prevbcast,yrbproj,mobilavproj);
                   13120:          fprintf(ficres,"prevbackcast=%d yearsbproj=%.2lf mobil_average=%d\n",prevbcast,yrbproj,mobilavproj);
1.296     brouard  13121:           prvbackcast = 2;
                   13122:        }
                   13123:        else {
                   13124:          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);
                   13125:          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);
                   13126:          goto end;
1.258     brouard  13127:        }
1.230     brouard  13128:        break;
1.258     brouard  13129:       case 13:
1.307     brouard  13130:        num_filled=sscanf(line,"result:%[^\n]\n",resultline);
                   13131:        nresult++; /* Sum of resultlines */
                   13132:        printf("Result %d: result:%s\n",nresult, resultline);
1.318     brouard  13133:        if(nresult > MAXRESULTLINESPONE-1){
                   13134:          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);
                   13135:          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  13136:          goto end;
                   13137:        }
1.310     brouard  13138:        if(!decoderesult(resultline, nresult)){ /* Fills TKresult[nresult] combination and Tresult[nresult][k4+1] combination values */
1.314     brouard  13139:          fprintf(ficparo,"result: %s\n",resultline);
                   13140:          fprintf(ficres,"result: %s\n",resultline);
                   13141:          fprintf(ficlog,"result: %s\n",resultline);
1.310     brouard  13142:        } else
                   13143:          goto end;
1.307     brouard  13144:        break;
                   13145:       case 14:
                   13146:        printf("Error: Unknown command '%s'\n",line);
                   13147:        fprintf(ficlog,"Error: Unknown command '%s'\n",line);
1.314     brouard  13148:        if(line[0] == ' ' || line[0] == '\n'){
                   13149:          printf("It should not be an empty line '%s'\n",line);
                   13150:          fprintf(ficlog,"It should not be an empty line '%s'\n",line);
                   13151:        }         
1.307     brouard  13152:        if(ncovmodel >=2 && nresult==0 ){
                   13153:          printf("ERROR: no result lines! It should be at minimum 'result: V2=0 V1=1 or result:.' %s\n",line);
                   13154:          fprintf(ficlog,"ERROR: no result lines! It should be at minimum 'result: V2=0 V1=1 or result:.' %s\n",line);
1.258     brouard  13155:        }
1.307     brouard  13156:        /* goto end; */
                   13157:        break;
1.308     brouard  13158:       case 15:
                   13159:        printf("End of resultlines.\n");
                   13160:        fprintf(ficlog,"End of resultlines.\n");
                   13161:        break;
                   13162:       default: /* parameterline =0 */
1.307     brouard  13163:        nresult=1;
                   13164:        decoderesult(".",nresult ); /* No covariate */
1.258     brouard  13165:       } /* End switch parameterline */
                   13166:     }while(endishere==0); /* End do */
1.126     brouard  13167:     
1.230     brouard  13168:     /* freqsummary(fileres, agemin, agemax, s, agev, nlstate, imx,Tvaraff,nbcode, ncodemax,mint,anint); */
1.145     brouard  13169:     /* ,dateprev1,dateprev2,jprev1, mprev1,anprev1,jprev2, mprev2,anprev2); */
1.126     brouard  13170:     
                   13171:     replace_back_to_slash(pathc,pathcd); /* Even gnuplot wants a / */
1.194     brouard  13172:     if(ageminpar == AGEOVERFLOW ||agemaxpar == -AGEOVERFLOW){
1.230     brouard  13173:       printf("Warning! Error in gnuplot file with ageminpar %f or agemaxpar %f overflow\n\
1.194     brouard  13174: This is probably because your parameter file doesn't \n  contain the exact number of lines (or columns) corresponding to your model line.\n\
                   13175: Please run with mle=-1 to get a correct covariance matrix.\n",ageminpar,agemaxpar);
1.230     brouard  13176:       fprintf(ficlog,"Warning! Error in gnuplot file with ageminpar %f or agemaxpar %f overflow\n\
1.194     brouard  13177: This is probably because your parameter file doesn't \n  contain the exact number of lines (or columns) corresponding to your model line.\n\
                   13178: Please run with mle=-1 to get a correct covariance matrix.\n",ageminpar,agemaxpar);
1.220     brouard  13179:     }else{
1.270     brouard  13180:       /* printinggnuplot(fileresu, optionfilefiname,ageminpar,agemaxpar,fage, prevfcast, backcast, pathc,p, (int)anproj1-(int)agemin, (int)anback1-(int)agemax+1); */
1.296     brouard  13181:       /* It seems that anprojd which is computed from the mean year at interview which is known yet because of freqsummary */
                   13182:       /* date2dmy(dateintmean,&jintmean,&mintmean,&aintmean); */ /* Done in freqsummary */
                   13183:       if(prvforecast==1){
                   13184:         dateprojd=(jproj1+12*mproj1+365*anproj1)/365;
                   13185:         jprojd=jproj1;
                   13186:         mprojd=mproj1;
                   13187:         anprojd=anproj1;
                   13188:         dateprojf=(jproj2+12*mproj2+365*anproj2)/365;
                   13189:         jprojf=jproj2;
                   13190:         mprojf=mproj2;
                   13191:         anprojf=anproj2;
                   13192:       } else if(prvforecast == 2){
                   13193:         dateprojd=dateintmean;
                   13194:         date2dmy(dateprojd,&jprojd, &mprojd, &anprojd);
                   13195:         dateprojf=dateintmean+yrfproj;
                   13196:         date2dmy(dateprojf,&jprojf, &mprojf, &anprojf);
                   13197:       }
                   13198:       if(prvbackcast==1){
                   13199:         datebackd=(jback1+12*mback1+365*anback1)/365;
                   13200:         jbackd=jback1;
                   13201:         mbackd=mback1;
                   13202:         anbackd=anback1;
                   13203:         datebackf=(jback2+12*mback2+365*anback2)/365;
                   13204:         jbackf=jback2;
                   13205:         mbackf=mback2;
                   13206:         anbackf=anback2;
                   13207:       } else if(prvbackcast == 2){
                   13208:         datebackd=dateintmean;
                   13209:         date2dmy(datebackd,&jbackd, &mbackd, &anbackd);
                   13210:         datebackf=dateintmean-yrbproj;
                   13211:         date2dmy(datebackf,&jbackf, &mbackf, &anbackf);
                   13212:       }
                   13213:       
                   13214:       printinggnuplot(fileresu, optionfilefiname,ageminpar,agemaxpar,bage, fage, prevfcast, prevbcast, pathc,p, (int)anprojd-bage, (int)anbackd-fage);
1.220     brouard  13215:     }
                   13216:     printinghtml(fileresu,title,datafile, firstpass, lastpass, stepm, weightopt, \
1.296     brouard  13217:                 model,imx,jmin,jmax,jmean,rfileres,popforecast,mobilav,prevfcast,mobilavproj,prevbcast, estepm, \
                   13218:                 jprev1,mprev1,anprev1,dateprev1, dateprojd, datebackd,jprev2,mprev2,anprev2,dateprev2,dateprojf, datebackf);
1.220     brouard  13219:                
1.225     brouard  13220:     /*------------ free_vector  -------------*/
                   13221:     /*  chdir(path); */
1.220     brouard  13222:                
1.215     brouard  13223:     /* free_ivector(wav,1,imx); */  /* Moved after last prevalence call */
                   13224:     /* free_imatrix(dh,1,lastpass-firstpass+2,1,imx); */
                   13225:     /* free_imatrix(bh,1,lastpass-firstpass+2,1,imx); */
                   13226:     /* free_imatrix(mw,1,lastpass-firstpass+2,1,imx);    */
1.290     brouard  13227:     free_lvector(num,firstobs,lastobs);
                   13228:     free_vector(agedc,firstobs,lastobs);
1.126     brouard  13229:     /*free_matrix(covar,0,NCOVMAX,1,n);*/
                   13230:     /*free_matrix(covar,1,NCOVMAX,1,n);*/
                   13231:     fclose(ficparo);
                   13232:     fclose(ficres);
1.220     brouard  13233:                
                   13234:                
1.186     brouard  13235:     /* Other results (useful)*/
1.220     brouard  13236:                
                   13237:                
1.126     brouard  13238:     /*--------------- Prevalence limit  (period or stable prevalence) --------------*/
1.180     brouard  13239:     /*#include "prevlim.h"*/  /* Use ficrespl, ficlog */
                   13240:     prlim=matrix(1,nlstate,1,nlstate);
1.209     brouard  13241:     prevalence_limit(p, prlim,  ageminpar, agemaxpar, ftolpl, &ncvyear);
1.126     brouard  13242:     fclose(ficrespl);
                   13243: 
                   13244:     /*------------- h Pij x at various ages ------------*/
1.180     brouard  13245:     /*#include "hpijx.h"*/
                   13246:     hPijx(p, bage, fage);
1.145     brouard  13247:     fclose(ficrespij);
1.227     brouard  13248:     
1.220     brouard  13249:     /* ncovcombmax=  pow(2,cptcoveff); */
1.219     brouard  13250:     /*-------------- Variance of one-step probabilities---*/
1.145     brouard  13251:     k=1;
1.126     brouard  13252:     varprob(optionfilefiname, matcov, p, delti, nlstate, bage, fage,k,Tvar,nbcode, ncodemax,strstart);
1.227     brouard  13253:     
1.269     brouard  13254:     /* Prevalence for each covariate combination in probs[age][status][cov] */
                   13255:     probs= ma3x(AGEINF,AGESUP,1,nlstate+ndeath, 1,ncovcombmax);
                   13256:     for(i=AGEINF;i<=AGESUP;i++)
1.219     brouard  13257:       for(j=1;j<=nlstate+ndeath;j++) /* ndeath is useless but a necessity to be compared with mobaverages */
1.225     brouard  13258:        for(k=1;k<=ncovcombmax;k++)
                   13259:          probs[i][j][k]=0.;
1.269     brouard  13260:     prevalence(probs, ageminpar, agemaxpar, s, agev, nlstate, imx, Tvar, nbcode, 
                   13261:               ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass);
1.219     brouard  13262:     if (mobilav!=0 ||mobilavproj !=0 ) {
1.269     brouard  13263:       mobaverages= ma3x(AGEINF, AGESUP,1,nlstate+ndeath, 1,ncovcombmax);
                   13264:       for(i=AGEINF;i<=AGESUP;i++)
1.268     brouard  13265:        for(j=1;j<=nlstate+ndeath;j++)
1.227     brouard  13266:          for(k=1;k<=ncovcombmax;k++)
                   13267:            mobaverages[i][j][k]=0.;
1.219     brouard  13268:       mobaverage=mobaverages;
                   13269:       if (mobilav!=0) {
1.235     brouard  13270:        printf("Movingaveraging observed prevalence\n");
1.258     brouard  13271:        fprintf(ficlog,"Movingaveraging observed prevalence\n");
1.227     brouard  13272:        if (movingaverage(probs, ageminpar, agemaxpar, mobaverage, mobilav)!=0){
                   13273:          fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);
                   13274:          printf(" Error in movingaverage mobilav=%d\n",mobilav);
                   13275:        }
1.269     brouard  13276:       } else if (mobilavproj !=0) {
1.235     brouard  13277:        printf("Movingaveraging projected observed prevalence\n");
1.258     brouard  13278:        fprintf(ficlog,"Movingaveraging projected observed prevalence\n");
1.227     brouard  13279:        if (movingaverage(probs, ageminpar, agemaxpar, mobaverage, mobilavproj)!=0){
                   13280:          fprintf(ficlog," Error in movingaverage mobilavproj=%d\n",mobilavproj);
                   13281:          printf(" Error in movingaverage mobilavproj=%d\n",mobilavproj);
                   13282:        }
1.269     brouard  13283:       }else{
                   13284:        printf("Internal error moving average\n");
                   13285:        fflush(stdout);
                   13286:        exit(1);
1.219     brouard  13287:       }
                   13288:     }/* end if moving average */
1.227     brouard  13289:     
1.126     brouard  13290:     /*---------- Forecasting ------------------*/
1.296     brouard  13291:     if(prevfcast==1){ 
                   13292:       /*   /\*    if(stepm ==1){*\/ */
                   13293:       /*   /\*  anproj1, mproj1, jproj1 either read explicitly or yrfproj *\/ */
                   13294:       /*This done previously after freqsummary.*/
                   13295:       /*   dateprojd=(jproj1+12*mproj1+365*anproj1)/365; */
                   13296:       /*   dateprojf=(jproj2+12*mproj2+365*anproj2)/365; */
                   13297:       
                   13298:       /* } else if (prvforecast==2){ */
                   13299:       /*   /\*    if(stepm ==1){*\/ */
                   13300:       /*   /\*  anproj1, mproj1, jproj1 either read explicitly or yrfproj *\/ */
                   13301:       /* } */
                   13302:       /*prevforecast(fileresu, dateintmean, anproj1, mproj1, jproj1, agemin, agemax, dateprev1, dateprev2, mobilavproj, mobaverage, bage, fage, firstpass, lastpass, anproj2, p, cptcoveff);*/
                   13303:       prevforecast(fileresu,dateintmean, dateprojd, dateprojf, agemin, agemax, dateprev1, dateprev2, mobilavproj, mobaverage, bage, fage, firstpass, lastpass, p, cptcoveff);
1.126     brouard  13304:     }
1.269     brouard  13305: 
1.296     brouard  13306:     /* Prevbcasting */
                   13307:     if(prevbcast==1){
1.219     brouard  13308:       ddnewms=matrix(1,nlstate+ndeath,1,nlstate+ndeath);       
                   13309:       ddoldms=matrix(1,nlstate+ndeath,1,nlstate+ndeath);       
                   13310:       ddsavms=matrix(1,nlstate+ndeath,1,nlstate+ndeath);
                   13311: 
                   13312:       /*--------------- Back Prevalence limit  (period or stable prevalence) --------------*/
                   13313: 
                   13314:       bprlim=matrix(1,nlstate,1,nlstate);
1.269     brouard  13315: 
1.219     brouard  13316:       back_prevalence_limit(p, bprlim,  ageminpar, agemaxpar, ftolpl, &ncvyear, dateprev1, dateprev2, firstpass, lastpass, mobilavproj);
                   13317:       fclose(ficresplb);
                   13318: 
1.222     brouard  13319:       hBijx(p, bage, fage, mobaverage);
                   13320:       fclose(ficrespijb);
1.219     brouard  13321: 
1.296     brouard  13322:       /* /\* prevbackforecast(fileresu, mobaverage, anback1, mback1, jback1, agemin, agemax, dateprev1, dateprev2, *\/ */
                   13323:       /* /\*                  mobilavproj, bage, fage, firstpass, lastpass, anback2, p, cptcoveff); *\/ */
                   13324:       /* prevbackforecast(fileresu, mobaverage, anback1, mback1, jback1, agemin, agemax, dateprev1, dateprev2, */
                   13325:       /*                      mobilavproj, bage, fage, firstpass, lastpass, anback2, p, cptcoveff); */
                   13326:       prevbackforecast(fileresu, mobaverage, dateintmean, dateprojd, dateprojf, agemin, agemax, dateprev1, dateprev2,
                   13327:                       mobilavproj, bage, fage, firstpass, lastpass, p, cptcoveff);
                   13328: 
                   13329:       
1.269     brouard  13330:       varbprlim(fileresu, nresult, mobaverage, mobilavproj, bage, fage, bprlim, &ncvyear, ftolpl, p, matcov, delti, stepm, cptcoveff);
1.268     brouard  13331: 
                   13332:       
1.269     brouard  13333:       free_matrix(bprlim,1,nlstate,1,nlstate); /*here or after loop ? */
1.219     brouard  13334:       free_matrix(ddnewms, 1, nlstate+ndeath, 1, nlstate+ndeath);
                   13335:       free_matrix(ddsavms, 1, nlstate+ndeath, 1, nlstate+ndeath);
                   13336:       free_matrix(ddoldms, 1, nlstate+ndeath, 1, nlstate+ndeath);
1.296     brouard  13337:     }    /* end  Prevbcasting */
1.268     brouard  13338:  
1.186     brouard  13339:  
                   13340:     /* ------ Other prevalence ratios------------ */
1.126     brouard  13341: 
1.215     brouard  13342:     free_ivector(wav,1,imx);
                   13343:     free_imatrix(dh,1,lastpass-firstpass+2,1,imx);
                   13344:     free_imatrix(bh,1,lastpass-firstpass+2,1,imx);
                   13345:     free_imatrix(mw,1,lastpass-firstpass+2,1,imx);   
1.218     brouard  13346:                
                   13347:                
1.127     brouard  13348:     /*---------- Health expectancies, no variances ------------*/
1.218     brouard  13349:                
1.201     brouard  13350:     strcpy(filerese,"E_");
                   13351:     strcat(filerese,fileresu);
1.126     brouard  13352:     if((ficreseij=fopen(filerese,"w"))==NULL) {
                   13353:       printf("Problem with Health Exp. resultfile: %s\n", filerese); exit(0);
                   13354:       fprintf(ficlog,"Problem with Health Exp. resultfile: %s\n", filerese); exit(0);
                   13355:     }
1.208     brouard  13356:     printf("Computing Health Expectancies: result on file '%s' ...", filerese);fflush(stdout);
                   13357:     fprintf(ficlog,"Computing Health Expectancies: result on file '%s' ...", filerese);fflush(ficlog);
1.238     brouard  13358: 
                   13359:     pstamp(ficreseij);
1.219     brouard  13360:                
1.235     brouard  13361:     i1=pow(2,cptcoveff); /* Number of combination of dummy covariates */
                   13362:     if (cptcovn < 1){i1=1;}
                   13363:     
                   13364:     for(nres=1; nres <= nresult; nres++) /* For each resultline */
                   13365:     for(k=1; k<=i1;k++){ /* For any combination of dummy covariates, fixed and varying */
1.253     brouard  13366:       if(i1 != 1 && TKresult[nres]!= k)
1.235     brouard  13367:        continue;
1.219     brouard  13368:       fprintf(ficreseij,"\n#****** ");
1.235     brouard  13369:       printf("\n#****** ");
1.225     brouard  13370:       for(j=1;j<=cptcoveff;j++) {
1.330   ! brouard  13371:        fprintf(ficreseij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,Tvaraff[j])]);
        !          13372:        printf("V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,Tvaraff[j])]);
1.235     brouard  13373:       }
                   13374:       for (j=1; j<= nsq; j++){ /* For each selected (single) quantitative value */
                   13375:        printf(" V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]);
                   13376:        fprintf(ficreseij," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]);
1.219     brouard  13377:       }
                   13378:       fprintf(ficreseij,"******\n");
1.235     brouard  13379:       printf("******\n");
1.219     brouard  13380:       
                   13381:       eij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
                   13382:       oldm=oldms;savm=savms;
1.330   ! brouard  13383:       /* printf("HELLO Entering evsij bage=%d fage=%d k=%d estepm=%d nres=%d\n",(int) bage, (int)fage, k, estepm, nres); */
1.235     brouard  13384:       evsij(eij, p, nlstate, stepm, (int) bage, (int)fage, oldm, savm, k, estepm, strstart, nres);  
1.127     brouard  13385:       
1.219     brouard  13386:       free_ma3x(eij,1,nlstate,1,nlstate,(int) bage, (int)fage);
1.127     brouard  13387:     }
                   13388:     fclose(ficreseij);
1.208     brouard  13389:     printf("done evsij\n");fflush(stdout);
                   13390:     fprintf(ficlog,"done evsij\n");fflush(ficlog);
1.269     brouard  13391: 
1.218     brouard  13392:                
1.227     brouard  13393:     /*---------- State-specific expectancies and variances ------------*/
1.218     brouard  13394:                
1.201     brouard  13395:     strcpy(filerest,"T_");
                   13396:     strcat(filerest,fileresu);
1.127     brouard  13397:     if((ficrest=fopen(filerest,"w"))==NULL) {
                   13398:       printf("Problem with total LE resultfile: %s\n", filerest);goto end;
                   13399:       fprintf(ficlog,"Problem with total LE resultfile: %s\n", filerest);goto end;
                   13400:     }
1.208     brouard  13401:     printf("Computing Total Life expectancies with their standard errors: file '%s' ...\n", filerest); fflush(stdout);
                   13402:     fprintf(ficlog,"Computing Total Life expectancies with their standard errors: file '%s' ...\n", filerest); fflush(ficlog);
1.201     brouard  13403:     strcpy(fileresstde,"STDE_");
                   13404:     strcat(fileresstde,fileresu);
1.126     brouard  13405:     if((ficresstdeij=fopen(fileresstde,"w"))==NULL) {
1.227     brouard  13406:       printf("Problem with State specific Exp. and std errors resultfile: %s\n", fileresstde); exit(0);
                   13407:       fprintf(ficlog,"Problem with State specific Exp. and std errors resultfile: %s\n", fileresstde); exit(0);
1.126     brouard  13408:     }
1.227     brouard  13409:     printf("  Computing State-specific Expectancies and standard errors: result on file '%s' \n", fileresstde);
                   13410:     fprintf(ficlog,"  Computing State-specific Expectancies and standard errors: result on file '%s' \n", fileresstde);
1.126     brouard  13411: 
1.201     brouard  13412:     strcpy(filerescve,"CVE_");
                   13413:     strcat(filerescve,fileresu);
1.126     brouard  13414:     if((ficrescveij=fopen(filerescve,"w"))==NULL) {
1.227     brouard  13415:       printf("Problem with Covar. State-specific Exp. resultfile: %s\n", filerescve); exit(0);
                   13416:       fprintf(ficlog,"Problem with Covar. State-specific Exp. resultfile: %s\n", filerescve); exit(0);
1.126     brouard  13417:     }
1.227     brouard  13418:     printf("    Computing Covar. of State-specific Expectancies: result on file '%s' \n", filerescve);
                   13419:     fprintf(ficlog,"    Computing Covar. of State-specific Expectancies: result on file '%s' \n", filerescve);
1.126     brouard  13420: 
1.201     brouard  13421:     strcpy(fileresv,"V_");
                   13422:     strcat(fileresv,fileresu);
1.126     brouard  13423:     if((ficresvij=fopen(fileresv,"w"))==NULL) {
                   13424:       printf("Problem with variance resultfile: %s\n", fileresv);exit(0);
                   13425:       fprintf(ficlog,"Problem with variance resultfile: %s\n", fileresv);exit(0);
                   13426:     }
1.227     brouard  13427:     printf("      Computing Variance-covariance of State-specific Expectancies: file '%s' ... ", fileresv);fflush(stdout);
                   13428:     fprintf(ficlog,"      Computing Variance-covariance of State-specific Expectancies: file '%s' ... ", fileresv);fflush(ficlog);
1.126     brouard  13429: 
1.235     brouard  13430:     i1=pow(2,cptcoveff); /* Number of combination of dummy covariates */
                   13431:     if (cptcovn < 1){i1=1;}
                   13432:     
                   13433:     for(nres=1; nres <= nresult; nres++) /* For each resultline */
                   13434:     for(k=1; k<=i1;k++){ /* For any combination of dummy covariates, fixed and varying */
1.253     brouard  13435:       if(i1 != 1 && TKresult[nres]!= k)
1.235     brouard  13436:        continue;
1.321     brouard  13437:       printf("\n# model %s \n#****** Result for:", model);
                   13438:       fprintf(ficrest,"\n# model %s \n#****** Result for:", model);
                   13439:       fprintf(ficlog,"\n# model %s \n#****** Result for:", model);
1.227     brouard  13440:       for(j=1;j<=cptcoveff;j++){ 
1.330   ! brouard  13441:        printf("V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,Tvaraff[j])]);
        !          13442:        fprintf(ficrest,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,Tvaraff[j])]);
        !          13443:        fprintf(ficlog,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,Tvaraff[j])]);
1.227     brouard  13444:       }
1.235     brouard  13445:       for (j=1; j<= nsq; j++){ /* For each selected (single) quantitative value */
                   13446:        printf(" V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]);
                   13447:        fprintf(ficrest," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]);
                   13448:        fprintf(ficlog," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]);
                   13449:       }        
1.208     brouard  13450:       fprintf(ficrest,"******\n");
1.227     brouard  13451:       fprintf(ficlog,"******\n");
                   13452:       printf("******\n");
1.208     brouard  13453:       
                   13454:       fprintf(ficresstdeij,"\n#****** ");
                   13455:       fprintf(ficrescveij,"\n#****** ");
1.225     brouard  13456:       for(j=1;j<=cptcoveff;j++) {
1.330   ! brouard  13457:        fprintf(ficresstdeij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,Tvaraff[j])]);
        !          13458:        fprintf(ficrescveij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,Tvaraff[j])]);
1.208     brouard  13459:       }
1.235     brouard  13460:       for (j=1; j<= nsq; j++){ /* For each selected (single) quantitative value */
                   13461:        fprintf(ficresstdeij," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]);
                   13462:        fprintf(ficrescveij," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]);
                   13463:       }        
1.208     brouard  13464:       fprintf(ficresstdeij,"******\n");
                   13465:       fprintf(ficrescveij,"******\n");
                   13466:       
                   13467:       fprintf(ficresvij,"\n#****** ");
1.238     brouard  13468:       /* pstamp(ficresvij); */
1.225     brouard  13469:       for(j=1;j<=cptcoveff;j++) 
1.330   ! brouard  13470:        fprintf(ficresvij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,Tvaraff[j])]);
1.235     brouard  13471:       for (j=1; j<= nsq; j++){ /* For each selected (single) quantitative value */
                   13472:        fprintf(ficresvij," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]);
                   13473:       }        
1.208     brouard  13474:       fprintf(ficresvij,"******\n");
                   13475:       
                   13476:       eij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
                   13477:       oldm=oldms;savm=savms;
1.235     brouard  13478:       printf(" cvevsij ");
                   13479:       fprintf(ficlog, " cvevsij ");
                   13480:       cvevsij(eij, p, nlstate, stepm, (int) bage, (int)fage, oldm, savm, k, estepm, delti, matcov, strstart, nres);
1.208     brouard  13481:       printf(" end cvevsij \n ");
                   13482:       fprintf(ficlog, " end cvevsij \n ");
                   13483:       
                   13484:       /*
                   13485:        */
                   13486:       /* goto endfree; */
                   13487:       
                   13488:       vareij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
                   13489:       pstamp(ficrest);
                   13490:       
1.269     brouard  13491:       epj=vector(1,nlstate+1);
1.208     brouard  13492:       for(vpopbased=0; vpopbased <= popbased; vpopbased++){ /* Done for vpopbased=0 and vpopbased=1 if popbased==1*/
1.227     brouard  13493:        oldm=oldms;savm=savms; /* ZZ Segmentation fault */
                   13494:        cptcod= 0; /* To be deleted */
                   13495:        printf("varevsij vpopbased=%d \n",vpopbased);
                   13496:        fprintf(ficlog, "varevsij vpopbased=%d \n",vpopbased);
1.235     brouard  13497:        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  13498:        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 ");
                   13499:        if(vpopbased==1)
                   13500:          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);
                   13501:        else
1.288     brouard  13502:          fprintf(ficrest,"the age specific forward period (stable) prevalences in each health state \n");
1.227     brouard  13503:        fprintf(ficrest,"# Age popbased mobilav e.. (std) ");
                   13504:        for (i=1;i<=nlstate;i++) fprintf(ficrest,"e.%d (std) ",i);
                   13505:        fprintf(ficrest,"\n");
                   13506:        /* printf("Which p?\n"); for(i=1;i<=npar;i++)printf("p[i=%d]=%lf,",i,p[i]);printf("\n"); */
1.288     brouard  13507:        printf("Computing age specific forward period (stable) prevalences in each health state \n");
                   13508:        fprintf(ficlog,"Computing age specific forward period (stable) prevalences in each health state \n");
1.227     brouard  13509:        for(age=bage; age <=fage ;age++){
1.235     brouard  13510:          prevalim(prlim, nlstate, p, age, oldm, savm, ftolpl, &ncvyear, k, nres); /*ZZ Is it the correct prevalim */
1.227     brouard  13511:          if (vpopbased==1) {
                   13512:            if(mobilav ==0){
                   13513:              for(i=1; i<=nlstate;i++)
                   13514:                prlim[i][i]=probs[(int)age][i][k];
                   13515:            }else{ /* mobilav */ 
                   13516:              for(i=1; i<=nlstate;i++)
                   13517:                prlim[i][i]=mobaverage[(int)age][i][k];
                   13518:            }
                   13519:          }
1.219     brouard  13520:          
1.227     brouard  13521:          fprintf(ficrest," %4.0f %d %d",age, vpopbased, mobilav);
                   13522:          /* fprintf(ficrest," %4.0f %d %d %d %d",age, vpopbased, mobilav,Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]); */ /* to be done */
                   13523:          /* printf(" age %4.0f ",age); */
                   13524:          for(j=1, epj[nlstate+1]=0.;j <=nlstate;j++){
                   13525:            for(i=1, epj[j]=0.;i <=nlstate;i++) {
                   13526:              epj[j] += prlim[i][i]*eij[i][j][(int)age];
                   13527:              /*ZZZ  printf("%lf %lf ", prlim[i][i] ,eij[i][j][(int)age]);*/
                   13528:              /* printf("%lf %lf ", prlim[i][i] ,eij[i][j][(int)age]); */
                   13529:            }
                   13530:            epj[nlstate+1] +=epj[j];
                   13531:          }
                   13532:          /* printf(" age %4.0f \n",age); */
1.219     brouard  13533:          
1.227     brouard  13534:          for(i=1, vepp=0.;i <=nlstate;i++)
                   13535:            for(j=1;j <=nlstate;j++)
                   13536:              vepp += vareij[i][j][(int)age];
                   13537:          fprintf(ficrest," %7.3f (%7.3f)", epj[nlstate+1],sqrt(vepp));
                   13538:          for(j=1;j <=nlstate;j++){
                   13539:            fprintf(ficrest," %7.3f (%7.3f)", epj[j],sqrt(vareij[j][j][(int)age]));
                   13540:          }
                   13541:          fprintf(ficrest,"\n");
                   13542:        }
1.208     brouard  13543:       } /* End vpopbased */
1.269     brouard  13544:       free_vector(epj,1,nlstate+1);
1.208     brouard  13545:       free_ma3x(eij,1,nlstate,1,nlstate,(int) bage, (int)fage);
                   13546:       free_ma3x(vareij,1,nlstate,1,nlstate,(int) bage, (int)fage);
1.235     brouard  13547:       printf("done selection\n");fflush(stdout);
                   13548:       fprintf(ficlog,"done selection\n");fflush(ficlog);
1.208     brouard  13549:       
1.235     brouard  13550:     } /* End k selection */
1.227     brouard  13551: 
                   13552:     printf("done State-specific expectancies\n");fflush(stdout);
                   13553:     fprintf(ficlog,"done State-specific expectancies\n");fflush(ficlog);
                   13554: 
1.288     brouard  13555:     /* variance-covariance of forward period prevalence*/
1.269     brouard  13556:     varprlim(fileresu, nresult, mobaverage, mobilavproj, bage, fage, prlim, &ncvyear, ftolpl, p, matcov, delti, stepm, cptcoveff);
1.268     brouard  13557: 
1.227     brouard  13558:     
1.290     brouard  13559:     free_vector(weight,firstobs,lastobs);
1.330   ! brouard  13560:     free_imatrix(Tvardk,1,NCOVMAX,1,2);
1.227     brouard  13561:     free_imatrix(Tvard,1,NCOVMAX,1,2);
1.290     brouard  13562:     free_imatrix(s,1,maxwav+1,firstobs,lastobs);
                   13563:     free_matrix(anint,1,maxwav,firstobs,lastobs); 
                   13564:     free_matrix(mint,1,maxwav,firstobs,lastobs);
                   13565:     free_ivector(cod,firstobs,lastobs);
1.227     brouard  13566:     free_ivector(tab,1,NCOVMAX);
                   13567:     fclose(ficresstdeij);
                   13568:     fclose(ficrescveij);
                   13569:     fclose(ficresvij);
                   13570:     fclose(ficrest);
                   13571:     fclose(ficpar);
                   13572:     
                   13573:     
1.126     brouard  13574:     /*---------- End : free ----------------*/
1.219     brouard  13575:     if (mobilav!=0 ||mobilavproj !=0)
1.269     brouard  13576:       free_ma3x(mobaverages,AGEINF, AGESUP,1,nlstate+ndeath, 1,ncovcombmax); /* We need to have a squared matrix with prevalence of the dead! */
                   13577:     free_ma3x(probs,AGEINF,AGESUP,1,nlstate+ndeath, 1,ncovcombmax);
1.220     brouard  13578:     free_matrix(prlim,1,nlstate,1,nlstate); /*here or after loop ? */
                   13579:     free_matrix(pmmij,1,nlstate+ndeath,1,nlstate+ndeath);
1.126     brouard  13580:   }  /* mle==-3 arrives here for freeing */
1.227     brouard  13581:   /* endfree:*/
                   13582:   free_matrix(oldms, 1,nlstate+ndeath,1,nlstate+ndeath);
                   13583:   free_matrix(newms, 1,nlstate+ndeath,1,nlstate+ndeath);
                   13584:   free_matrix(savms, 1,nlstate+ndeath,1,nlstate+ndeath);
1.290     brouard  13585:   if(ntv+nqtv>=1)free_ma3x(cotvar,1,maxwav,1,ntv+nqtv,firstobs,lastobs);
                   13586:   if(nqtv>=1)free_ma3x(cotqvar,1,maxwav,1,nqtv,firstobs,lastobs);
                   13587:   if(nqv>=1)free_matrix(coqvar,1,nqv,firstobs,lastobs);
                   13588:   free_matrix(covar,0,NCOVMAX,firstobs,lastobs);
1.227     brouard  13589:   free_matrix(matcov,1,npar,1,npar);
                   13590:   free_matrix(hess,1,npar,1,npar);
                   13591:   /*free_vector(delti,1,npar);*/
                   13592:   free_ma3x(delti3,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel); 
                   13593:   free_matrix(agev,1,maxwav,1,imx);
1.269     brouard  13594:   free_ma3x(paramstart,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel);
1.227     brouard  13595:   free_ma3x(param,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel);
                   13596:   
                   13597:   free_ivector(ncodemax,1,NCOVMAX);
                   13598:   free_ivector(ncodemaxwundef,1,NCOVMAX);
                   13599:   free_ivector(Dummy,-1,NCOVMAX);
                   13600:   free_ivector(Fixed,-1,NCOVMAX);
1.238     brouard  13601:   free_ivector(DummyV,1,NCOVMAX);
                   13602:   free_ivector(FixedV,1,NCOVMAX);
1.227     brouard  13603:   free_ivector(Typevar,-1,NCOVMAX);
                   13604:   free_ivector(Tvar,1,NCOVMAX);
1.234     brouard  13605:   free_ivector(TvarsQ,1,NCOVMAX);
                   13606:   free_ivector(TvarsQind,1,NCOVMAX);
                   13607:   free_ivector(TvarsD,1,NCOVMAX);
1.330   ! brouard  13608:   free_ivector(TnsdVar,1,NCOVMAX);
1.234     brouard  13609:   free_ivector(TvarsDind,1,NCOVMAX);
1.231     brouard  13610:   free_ivector(TvarFD,1,NCOVMAX);
                   13611:   free_ivector(TvarFDind,1,NCOVMAX);
1.232     brouard  13612:   free_ivector(TvarF,1,NCOVMAX);
                   13613:   free_ivector(TvarFind,1,NCOVMAX);
                   13614:   free_ivector(TvarV,1,NCOVMAX);
                   13615:   free_ivector(TvarVind,1,NCOVMAX);
                   13616:   free_ivector(TvarA,1,NCOVMAX);
                   13617:   free_ivector(TvarAind,1,NCOVMAX);
1.231     brouard  13618:   free_ivector(TvarFQ,1,NCOVMAX);
                   13619:   free_ivector(TvarFQind,1,NCOVMAX);
                   13620:   free_ivector(TvarVD,1,NCOVMAX);
                   13621:   free_ivector(TvarVDind,1,NCOVMAX);
                   13622:   free_ivector(TvarVQ,1,NCOVMAX);
                   13623:   free_ivector(TvarVQind,1,NCOVMAX);
1.230     brouard  13624:   free_ivector(Tvarsel,1,NCOVMAX);
                   13625:   free_vector(Tvalsel,1,NCOVMAX);
1.227     brouard  13626:   free_ivector(Tposprod,1,NCOVMAX);
                   13627:   free_ivector(Tprod,1,NCOVMAX);
                   13628:   free_ivector(Tvaraff,1,NCOVMAX);
                   13629:   free_ivector(invalidvarcomb,1,ncovcombmax);
                   13630:   free_ivector(Tage,1,NCOVMAX);
                   13631:   free_ivector(Tmodelind,1,NCOVMAX);
1.228     brouard  13632:   free_ivector(TmodelInvind,1,NCOVMAX);
                   13633:   free_ivector(TmodelInvQind,1,NCOVMAX);
1.227     brouard  13634:   
                   13635:   free_imatrix(nbcode,0,NCOVMAX,0,NCOVMAX);
                   13636:   /* free_imatrix(codtab,1,100,1,10); */
1.126     brouard  13637:   fflush(fichtm);
                   13638:   fflush(ficgp);
                   13639:   
1.227     brouard  13640:   
1.126     brouard  13641:   if((nberr >0) || (nbwarn>0)){
1.216     brouard  13642:     printf("End of Imach with %d errors and/or %d warnings. Please look at the log file for details.\n",nberr,nbwarn);
                   13643:     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  13644:   }else{
                   13645:     printf("End of Imach\n");
                   13646:     fprintf(ficlog,"End of Imach\n");
                   13647:   }
                   13648:   printf("See log file on %s\n",filelog);
                   13649:   /*  gettimeofday(&end_time, (struct timezone*)0);*/  /* after time */
1.157     brouard  13650:   /*(void) gettimeofday(&end_time,&tzp);*/
                   13651:   rend_time = time(NULL);  
                   13652:   end_time = *localtime(&rend_time);
                   13653:   /* tml = *localtime(&end_time.tm_sec); */
                   13654:   strcpy(strtend,asctime(&end_time));
1.126     brouard  13655:   printf("Local time at start %s\nLocal time at end   %s",strstart, strtend); 
                   13656:   fprintf(ficlog,"Local time at start %s\nLocal time at end   %s\n",strstart, strtend); 
1.157     brouard  13657:   printf("Total time used %s\n", asc_diff_time(rend_time -rstart_time,tmpout));
1.227     brouard  13658:   
1.157     brouard  13659:   printf("Total time was %.0lf Sec.\n", difftime(rend_time,rstart_time));
                   13660:   fprintf(ficlog,"Total time used %s\n", asc_diff_time(rend_time -rstart_time,tmpout));
                   13661:   fprintf(ficlog,"Total time was %.0lf Sec.\n", difftime(rend_time,rstart_time));
1.126     brouard  13662:   /*  printf("Total time was %d uSec.\n", total_usecs);*/
                   13663: /*   if(fileappend(fichtm,optionfilehtm)){ */
                   13664:   fprintf(fichtm,"<br>Local time at start %s<br>Local time at end   %s<br>\n</body></html>",strstart, strtend);
                   13665:   fclose(fichtm);
                   13666:   fprintf(fichtmcov,"<br>Local time at start %s<br>Local time at end   %s<br>\n</body></html>",strstart, strtend);
                   13667:   fclose(fichtmcov);
                   13668:   fclose(ficgp);
                   13669:   fclose(ficlog);
                   13670:   /*------ End -----------*/
1.227     brouard  13671:   
1.281     brouard  13672: 
                   13673: /* Executes gnuplot */
1.227     brouard  13674:   
                   13675:   printf("Before Current directory %s!\n",pathcd);
1.184     brouard  13676: #ifdef WIN32
1.227     brouard  13677:   if (_chdir(pathcd) != 0)
                   13678:     printf("Can't move to directory %s!\n",path);
                   13679:   if(_getcwd(pathcd,MAXLINE) > 0)
1.184     brouard  13680: #else
1.227     brouard  13681:     if(chdir(pathcd) != 0)
                   13682:       printf("Can't move to directory %s!\n", path);
                   13683:   if (getcwd(pathcd, MAXLINE) > 0)
1.184     brouard  13684: #endif 
1.126     brouard  13685:     printf("Current directory %s!\n",pathcd);
                   13686:   /*strcat(plotcmd,CHARSEPARATOR);*/
                   13687:   sprintf(plotcmd,"gnuplot");
1.157     brouard  13688: #ifdef _WIN32
1.126     brouard  13689:   sprintf(plotcmd,"\"%sgnuplot.exe\"",pathimach);
                   13690: #endif
                   13691:   if(!stat(plotcmd,&info)){
1.158     brouard  13692:     printf("Error or gnuplot program not found: '%s'\n",plotcmd);fflush(stdout);
1.126     brouard  13693:     if(!stat(getenv("GNUPLOTBIN"),&info)){
1.158     brouard  13694:       printf("Error or gnuplot program not found: '%s' Environment GNUPLOTBIN not set.\n",plotcmd);fflush(stdout);
1.126     brouard  13695:     }else
                   13696:       strcpy(pplotcmd,plotcmd);
1.157     brouard  13697: #ifdef __unix
1.126     brouard  13698:     strcpy(plotcmd,GNUPLOTPROGRAM);
                   13699:     if(!stat(plotcmd,&info)){
1.158     brouard  13700:       printf("Error gnuplot program not found: '%s'\n",plotcmd);fflush(stdout);
1.126     brouard  13701:     }else
                   13702:       strcpy(pplotcmd,plotcmd);
                   13703: #endif
                   13704:   }else
                   13705:     strcpy(pplotcmd,plotcmd);
                   13706:   
                   13707:   sprintf(plotcmd,"%s %s",pplotcmd, optionfilegnuplot);
1.158     brouard  13708:   printf("Starting graphs with: '%s'\n",plotcmd);fflush(stdout);
1.292     brouard  13709:   strcpy(pplotcmd,plotcmd);
1.227     brouard  13710:   
1.126     brouard  13711:   if((outcmd=system(plotcmd)) != 0){
1.292     brouard  13712:     printf("Error in gnuplot, command might not be in your path: '%s', err=%d\n", plotcmd, outcmd);
1.154     brouard  13713:     printf("\n Trying if gnuplot resides on the same directory that IMaCh\n");
1.152     brouard  13714:     sprintf(plotcmd,"%sgnuplot %s", pathimach, optionfilegnuplot);
1.292     brouard  13715:     if((outcmd=system(plotcmd)) != 0){
1.153     brouard  13716:       printf("\n Still a problem with gnuplot command %s, err=%d\n", plotcmd, outcmd);
1.292     brouard  13717:       strcpy(plotcmd,pplotcmd);
                   13718:     }
1.126     brouard  13719:   }
1.158     brouard  13720:   printf(" Successful, please wait...");
1.126     brouard  13721:   while (z[0] != 'q') {
                   13722:     /* chdir(path); */
1.154     brouard  13723:     printf("\nType e to edit results with your browser, g to graph again and q for exit: ");
1.126     brouard  13724:     scanf("%s",z);
                   13725: /*     if (z[0] == 'c') system("./imach"); */
                   13726:     if (z[0] == 'e') {
1.158     brouard  13727: #ifdef __APPLE__
1.152     brouard  13728:       sprintf(pplotcmd, "open %s", optionfilehtm);
1.157     brouard  13729: #elif __linux
                   13730:       sprintf(pplotcmd, "xdg-open %s", optionfilehtm);
1.153     brouard  13731: #else
1.152     brouard  13732:       sprintf(pplotcmd, "%s", optionfilehtm);
1.153     brouard  13733: #endif
                   13734:       printf("Starting browser with: %s",pplotcmd);fflush(stdout);
                   13735:       system(pplotcmd);
1.126     brouard  13736:     }
                   13737:     else if (z[0] == 'g') system(plotcmd);
                   13738:     else if (z[0] == 'q') exit(0);
                   13739:   }
1.227     brouard  13740: end:
1.126     brouard  13741:   while (z[0] != 'q') {
1.195     brouard  13742:     printf("\nType  q for exiting: "); fflush(stdout);
1.126     brouard  13743:     scanf("%s",z);
                   13744:   }
1.283     brouard  13745:   printf("End\n");
1.282     brouard  13746:   exit(0);
1.126     brouard  13747: }

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