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

1.336   ! brouard     1: /* $Id: imach.c,v 1.335 2022/08/31 08:23:16 brouard Exp $
1.126     brouard     2:   $State: Exp $
1.163     brouard     3:   $Log: imach.c,v $
1.336   ! brouard     4:   Revision 1.335  2022/08/31 08:23:16  brouard
        !             5:   Summary: improvements...
        !             6: 
1.335     brouard     7:   Revision 1.334  2022/08/25 09:08:41  brouard
                      8:   Summary: In progress for quantitative
                      9: 
1.334     brouard    10:   Revision 1.333  2022/08/21 09:10:30  brouard
                     11:   * src/imach.c (Module): Version 0.99r33 A lot of changes in
                     12:   reassigning covariates: my first idea was that people will always
                     13:   use the first covariate V1 into the model but in fact they are
                     14:   producing data with many covariates and can use an equation model
                     15:   with some of the covariate; it means that in a model V2+V3 instead
                     16:   of codtabm(k,Tvaraff[j]) which calculates for combination k, for
                     17:   three covariates (V1, V2, V3) the value of Tvaraff[j], but in fact
                     18:   the equation model is restricted to two variables only (V2, V3)
                     19:   and the combination for V2 should be codtabm(k,1) instead of
                     20:   (codtabm(k,2), and the code should be
                     21:   codtabm(k,TnsdVar[Tvaraff[j]]. Many many changes have been
                     22:   made. All of these should be simplified once a day like we did in
                     23:   hpxij() for example by using precov[nres] which is computed in
                     24:   decoderesult for each nres of each resultline. Loop should be done
                     25:   on the equation model globally by distinguishing only product with
                     26:   age (which are changing with age) and no more on type of
                     27:   covariates, single dummies, single covariates.
                     28: 
1.333     brouard    29:   Revision 1.332  2022/08/21 09:06:25  brouard
                     30:   Summary: Version 0.99r33
                     31: 
                     32:   * src/imach.c (Module): Version 0.99r33 A lot of changes in
                     33:   reassigning covariates: my first idea was that people will always
                     34:   use the first covariate V1 into the model but in fact they are
                     35:   producing data with many covariates and can use an equation model
                     36:   with some of the covariate; it means that in a model V2+V3 instead
                     37:   of codtabm(k,Tvaraff[j]) which calculates for combination k, for
                     38:   three covariates (V1, V2, V3) the value of Tvaraff[j], but in fact
                     39:   the equation model is restricted to two variables only (V2, V3)
                     40:   and the combination for V2 should be codtabm(k,1) instead of
                     41:   (codtabm(k,2), and the code should be
                     42:   codtabm(k,TnsdVar[Tvaraff[j]]. Many many changes have been
                     43:   made. All of these should be simplified once a day like we did in
                     44:   hpxij() for example by using precov[nres] which is computed in
                     45:   decoderesult for each nres of each resultline. Loop should be done
                     46:   on the equation model globally by distinguishing only product with
                     47:   age (which are changing with age) and no more on type of
                     48:   covariates, single dummies, single covariates.
                     49: 
1.332     brouard    50:   Revision 1.331  2022/08/07 05:40:09  brouard
                     51:   *** empty log message ***
                     52: 
1.331     brouard    53:   Revision 1.330  2022/08/06 07:18:25  brouard
                     54:   Summary: last 0.99r31
                     55: 
                     56:   *  imach.c (Module): Version of imach using partly decoderesult to rebuild xpxij function
                     57: 
1.330     brouard    58:   Revision 1.329  2022/08/03 17:29:54  brouard
                     59:   *  imach.c (Module): Many errors in graphs fixed with Vn*age covariates.
                     60: 
1.329     brouard    61:   Revision 1.328  2022/07/27 17:40:48  brouard
                     62:   Summary: valgrind bug fixed by initializing to zero DummyV as well as Tage
                     63: 
1.328     brouard    64:   Revision 1.327  2022/07/27 14:47:35  brouard
                     65:   Summary: Still a problem for one-step probabilities in case of quantitative variables
                     66: 
1.327     brouard    67:   Revision 1.326  2022/07/26 17:33:55  brouard
                     68:   Summary: some test with nres=1
                     69: 
1.326     brouard    70:   Revision 1.325  2022/07/25 14:27:23  brouard
                     71:   Summary: r30
                     72: 
                     73:   * imach.c (Module): Error cptcovn instead of nsd in bmij (was
                     74:   coredumped, revealed by Feiuno, thank you.
                     75: 
1.325     brouard    76:   Revision 1.324  2022/07/23 17:44:26  brouard
                     77:   *** empty log message ***
                     78: 
1.324     brouard    79:   Revision 1.323  2022/07/22 12:30:08  brouard
                     80:   *  imach.c (Module): Output of Wald test in the htm file and not only in the log.
                     81: 
1.323     brouard    82:   Revision 1.322  2022/07/22 12:27:48  brouard
                     83:   *  imach.c (Module): Output of Wald test in the htm file and not only in the log.
                     84: 
1.322     brouard    85:   Revision 1.321  2022/07/22 12:04:24  brouard
                     86:   Summary: r28
                     87: 
                     88:   *  imach.c (Module): Output of Wald test in the htm file and not only in the log.
                     89: 
1.321     brouard    90:   Revision 1.320  2022/06/02 05:10:11  brouard
                     91:   *** empty log message ***
                     92: 
1.320     brouard    93:   Revision 1.319  2022/06/02 04:45:11  brouard
                     94:   * imach.c (Module): Adding the Wald tests from the log to the main
                     95:   htm for better display of the maximum likelihood estimators.
                     96: 
1.319     brouard    97:   Revision 1.318  2022/05/24 08:10:59  brouard
                     98:   * imach.c (Module): Some attempts to find a bug of wrong estimates
                     99:   of confidencce intervals with product in the equation modelC
                    100: 
1.318     brouard   101:   Revision 1.317  2022/05/15 15:06:23  brouard
                    102:   * imach.c (Module):  Some minor improvements
                    103: 
1.317     brouard   104:   Revision 1.316  2022/05/11 15:11:31  brouard
                    105:   Summary: r27
                    106: 
1.316     brouard   107:   Revision 1.315  2022/05/11 15:06:32  brouard
                    108:   *** empty log message ***
                    109: 
1.315     brouard   110:   Revision 1.314  2022/04/13 17:43:09  brouard
                    111:   * imach.c (Module): Adding link to text data files
                    112: 
1.314     brouard   113:   Revision 1.313  2022/04/11 15:57:42  brouard
                    114:   * imach.c (Module): Error in rewriting the 'r' file with yearsfproj or yearsbproj fixed
                    115: 
1.313     brouard   116:   Revision 1.312  2022/04/05 21:24:39  brouard
                    117:   *** empty log message ***
                    118: 
1.312     brouard   119:   Revision 1.311  2022/04/05 21:03:51  brouard
                    120:   Summary: Fixed quantitative covariates
                    121: 
                    122:          Fixed covariates (dummy or quantitative)
                    123:        with missing values have never been allowed but are ERRORS and
                    124:        program quits. Standard deviations of fixed covariates were
                    125:        wrongly computed. Mean and standard deviations of time varying
                    126:        covariates are still not computed.
                    127: 
1.311     brouard   128:   Revision 1.310  2022/03/17 08:45:53  brouard
                    129:   Summary: 99r25
                    130: 
                    131:   Improving detection of errors: result lines should be compatible with
                    132:   the model.
                    133: 
1.310     brouard   134:   Revision 1.309  2021/05/20 12:39:14  brouard
                    135:   Summary: Version 0.99r24
                    136: 
1.309     brouard   137:   Revision 1.308  2021/03/31 13:11:57  brouard
                    138:   Summary: Version 0.99r23
                    139: 
                    140: 
                    141:   * imach.c (Module): Still bugs in the result loop. Thank to Holly Benett
                    142: 
1.308     brouard   143:   Revision 1.307  2021/03/08 18:11:32  brouard
                    144:   Summary: 0.99r22 fixed bug on result:
                    145: 
1.307     brouard   146:   Revision 1.306  2021/02/20 15:44:02  brouard
                    147:   Summary: Version 0.99r21
                    148: 
                    149:   * imach.c (Module): Fix bug on quitting after result lines!
                    150:   (Module): Version 0.99r21
                    151: 
1.306     brouard   152:   Revision 1.305  2021/02/20 15:28:30  brouard
                    153:   * imach.c (Module): Fix bug on quitting after result lines!
                    154: 
1.305     brouard   155:   Revision 1.304  2021/02/12 11:34:20  brouard
                    156:   * imach.c (Module): The use of a Windows BOM (huge) file is now an error
                    157: 
1.304     brouard   158:   Revision 1.303  2021/02/11 19:50:15  brouard
                    159:   *  (Module): imach.c Someone entered 'results:' instead of 'result:'. Now it is an error which is printed.
                    160: 
1.303     brouard   161:   Revision 1.302  2020/02/22 21:00:05  brouard
                    162:   *  (Module): imach.c Update mle=-3 (for computing Life expectancy
                    163:   and life table from the data without any state)
                    164: 
1.302     brouard   165:   Revision 1.301  2019/06/04 13:51:20  brouard
                    166:   Summary: Error in 'r'parameter file backcast yearsbproj instead of yearsfproj
                    167: 
1.301     brouard   168:   Revision 1.300  2019/05/22 19:09:45  brouard
                    169:   Summary: version 0.99r19 of May 2019
                    170: 
1.300     brouard   171:   Revision 1.299  2019/05/22 18:37:08  brouard
                    172:   Summary: Cleaned 0.99r19
                    173: 
1.299     brouard   174:   Revision 1.298  2019/05/22 18:19:56  brouard
                    175:   *** empty log message ***
                    176: 
1.298     brouard   177:   Revision 1.297  2019/05/22 17:56:10  brouard
                    178:   Summary: Fix bug by moving date2dmy and nhstepm which gaefin=-1
                    179: 
1.297     brouard   180:   Revision 1.296  2019/05/20 13:03:18  brouard
                    181:   Summary: Projection syntax simplified
                    182: 
                    183: 
                    184:   We can now start projections, forward or backward, from the mean date
                    185:   of inteviews up to or down to a number of years of projection:
                    186:   prevforecast=1 yearsfproj=15.3 mobil_average=0
                    187:   or
                    188:   prevforecast=1 starting-proj-date=1/1/2007 final-proj-date=12/31/2017 mobil_average=0
                    189:   or
                    190:   prevbackcast=1 yearsbproj=12.3 mobil_average=1
                    191:   or
                    192:   prevbackcast=1 starting-back-date=1/10/1999 final-back-date=1/1/1985 mobil_average=1
                    193: 
1.296     brouard   194:   Revision 1.295  2019/05/18 09:52:50  brouard
                    195:   Summary: doxygen tex bug
                    196: 
1.295     brouard   197:   Revision 1.294  2019/05/16 14:54:33  brouard
                    198:   Summary: There was some wrong lines added
                    199: 
1.294     brouard   200:   Revision 1.293  2019/05/09 15:17:34  brouard
                    201:   *** empty log message ***
                    202: 
1.293     brouard   203:   Revision 1.292  2019/05/09 14:17:20  brouard
                    204:   Summary: Some updates
                    205: 
1.292     brouard   206:   Revision 1.291  2019/05/09 13:44:18  brouard
                    207:   Summary: Before ncovmax
                    208: 
1.291     brouard   209:   Revision 1.290  2019/05/09 13:39:37  brouard
                    210:   Summary: 0.99r18 unlimited number of individuals
                    211: 
                    212:   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.
                    213: 
1.290     brouard   214:   Revision 1.289  2018/12/13 09:16:26  brouard
                    215:   Summary: Bug for young ages (<-30) will be in r17
                    216: 
1.289     brouard   217:   Revision 1.288  2018/05/02 20:58:27  brouard
                    218:   Summary: Some bugs fixed
                    219: 
1.288     brouard   220:   Revision 1.287  2018/05/01 17:57:25  brouard
                    221:   Summary: Bug fixed by providing frequencies only for non missing covariates
                    222: 
1.287     brouard   223:   Revision 1.286  2018/04/27 14:27:04  brouard
                    224:   Summary: some minor bugs
                    225: 
1.286     brouard   226:   Revision 1.285  2018/04/21 21:02:16  brouard
                    227:   Summary: Some bugs fixed, valgrind tested
                    228: 
1.285     brouard   229:   Revision 1.284  2018/04/20 05:22:13  brouard
                    230:   Summary: Computing mean and stdeviation of fixed quantitative variables
                    231: 
1.284     brouard   232:   Revision 1.283  2018/04/19 14:49:16  brouard
                    233:   Summary: Some minor bugs fixed
                    234: 
1.283     brouard   235:   Revision 1.282  2018/02/27 22:50:02  brouard
                    236:   *** empty log message ***
                    237: 
1.282     brouard   238:   Revision 1.281  2018/02/27 19:25:23  brouard
                    239:   Summary: Adding second argument for quitting
                    240: 
1.281     brouard   241:   Revision 1.280  2018/02/21 07:58:13  brouard
                    242:   Summary: 0.99r15
                    243: 
                    244:   New Makefile with recent VirtualBox 5.26. Bug in sqrt negatve in imach.c
                    245: 
1.280     brouard   246:   Revision 1.279  2017/07/20 13:35:01  brouard
                    247:   Summary: temporary working
                    248: 
1.279     brouard   249:   Revision 1.278  2017/07/19 14:09:02  brouard
                    250:   Summary: Bug for mobil_average=0 and prevforecast fixed(?)
                    251: 
1.278     brouard   252:   Revision 1.277  2017/07/17 08:53:49  brouard
                    253:   Summary: BOM files can be read now
                    254: 
1.277     brouard   255:   Revision 1.276  2017/06/30 15:48:31  brouard
                    256:   Summary: Graphs improvements
                    257: 
1.276     brouard   258:   Revision 1.275  2017/06/30 13:39:33  brouard
                    259:   Summary: Saito's color
                    260: 
1.275     brouard   261:   Revision 1.274  2017/06/29 09:47:08  brouard
                    262:   Summary: Version 0.99r14
                    263: 
1.274     brouard   264:   Revision 1.273  2017/06/27 11:06:02  brouard
                    265:   Summary: More documentation on projections
                    266: 
1.273     brouard   267:   Revision 1.272  2017/06/27 10:22:40  brouard
                    268:   Summary: Color of backprojection changed from 6 to 5(yellow)
                    269: 
1.272     brouard   270:   Revision 1.271  2017/06/27 10:17:50  brouard
                    271:   Summary: Some bug with rint
                    272: 
1.271     brouard   273:   Revision 1.270  2017/05/24 05:45:29  brouard
                    274:   *** empty log message ***
                    275: 
1.270     brouard   276:   Revision 1.269  2017/05/23 08:39:25  brouard
                    277:   Summary: Code into subroutine, cleanings
                    278: 
1.269     brouard   279:   Revision 1.268  2017/05/18 20:09:32  brouard
                    280:   Summary: backprojection and confidence intervals of backprevalence
                    281: 
1.268     brouard   282:   Revision 1.267  2017/05/13 10:25:05  brouard
                    283:   Summary: temporary save for backprojection
                    284: 
1.267     brouard   285:   Revision 1.266  2017/05/13 07:26:12  brouard
                    286:   Summary: Version 0.99r13 (improvements and bugs fixed)
                    287: 
1.266     brouard   288:   Revision 1.265  2017/04/26 16:22:11  brouard
                    289:   Summary: imach 0.99r13 Some bugs fixed
                    290: 
1.265     brouard   291:   Revision 1.264  2017/04/26 06:01:29  brouard
                    292:   Summary: Labels in graphs
                    293: 
1.264     brouard   294:   Revision 1.263  2017/04/24 15:23:15  brouard
                    295:   Summary: to save
                    296: 
1.263     brouard   297:   Revision 1.262  2017/04/18 16:48:12  brouard
                    298:   *** empty log message ***
                    299: 
1.262     brouard   300:   Revision 1.261  2017/04/05 10:14:09  brouard
                    301:   Summary: Bug in E_ as well as in T_ fixed nres-1 vs k1-1
                    302: 
1.261     brouard   303:   Revision 1.260  2017/04/04 17:46:59  brouard
                    304:   Summary: Gnuplot indexations fixed (humm)
                    305: 
1.260     brouard   306:   Revision 1.259  2017/04/04 13:01:16  brouard
                    307:   Summary: Some errors to warnings only if date of death is unknown but status is death we could set to pi3
                    308: 
1.259     brouard   309:   Revision 1.258  2017/04/03 10:17:47  brouard
                    310:   Summary: Version 0.99r12
                    311: 
                    312:   Some cleanings, conformed with updated documentation.
                    313: 
1.258     brouard   314:   Revision 1.257  2017/03/29 16:53:30  brouard
                    315:   Summary: Temp
                    316: 
1.257     brouard   317:   Revision 1.256  2017/03/27 05:50:23  brouard
                    318:   Summary: Temporary
                    319: 
1.256     brouard   320:   Revision 1.255  2017/03/08 16:02:28  brouard
                    321:   Summary: IMaCh version 0.99r10 bugs in gnuplot fixed
                    322: 
1.255     brouard   323:   Revision 1.254  2017/03/08 07:13:00  brouard
                    324:   Summary: Fixing data parameter line
                    325: 
1.254     brouard   326:   Revision 1.253  2016/12/15 11:59:41  brouard
                    327:   Summary: 0.99 in progress
                    328: 
1.253     brouard   329:   Revision 1.252  2016/09/15 21:15:37  brouard
                    330:   *** empty log message ***
                    331: 
1.252     brouard   332:   Revision 1.251  2016/09/15 15:01:13  brouard
                    333:   Summary: not working
                    334: 
1.251     brouard   335:   Revision 1.250  2016/09/08 16:07:27  brouard
                    336:   Summary: continue
                    337: 
1.250     brouard   338:   Revision 1.249  2016/09/07 17:14:18  brouard
                    339:   Summary: Starting values from frequencies
                    340: 
1.249     brouard   341:   Revision 1.248  2016/09/07 14:10:18  brouard
                    342:   *** empty log message ***
                    343: 
1.248     brouard   344:   Revision 1.247  2016/09/02 11:11:21  brouard
                    345:   *** empty log message ***
                    346: 
1.247     brouard   347:   Revision 1.246  2016/09/02 08:49:22  brouard
                    348:   *** empty log message ***
                    349: 
1.246     brouard   350:   Revision 1.245  2016/09/02 07:25:01  brouard
                    351:   *** empty log message ***
                    352: 
1.245     brouard   353:   Revision 1.244  2016/09/02 07:17:34  brouard
                    354:   *** empty log message ***
                    355: 
1.244     brouard   356:   Revision 1.243  2016/09/02 06:45:35  brouard
                    357:   *** empty log message ***
                    358: 
1.243     brouard   359:   Revision 1.242  2016/08/30 15:01:20  brouard
                    360:   Summary: Fixing a lots
                    361: 
1.242     brouard   362:   Revision 1.241  2016/08/29 17:17:25  brouard
                    363:   Summary: gnuplot problem in Back projection to fix
                    364: 
1.241     brouard   365:   Revision 1.240  2016/08/29 07:53:18  brouard
                    366:   Summary: Better
                    367: 
1.240     brouard   368:   Revision 1.239  2016/08/26 15:51:03  brouard
                    369:   Summary: Improvement in Powell output in order to copy and paste
                    370: 
                    371:   Author:
                    372: 
1.239     brouard   373:   Revision 1.238  2016/08/26 14:23:35  brouard
                    374:   Summary: Starting tests of 0.99
                    375: 
1.238     brouard   376:   Revision 1.237  2016/08/26 09:20:19  brouard
                    377:   Summary: to valgrind
                    378: 
1.237     brouard   379:   Revision 1.236  2016/08/25 10:50:18  brouard
                    380:   *** empty log message ***
                    381: 
1.236     brouard   382:   Revision 1.235  2016/08/25 06:59:23  brouard
                    383:   *** empty log message ***
                    384: 
1.235     brouard   385:   Revision 1.234  2016/08/23 16:51:20  brouard
                    386:   *** empty log message ***
                    387: 
1.234     brouard   388:   Revision 1.233  2016/08/23 07:40:50  brouard
                    389:   Summary: not working
                    390: 
1.233     brouard   391:   Revision 1.232  2016/08/22 14:20:21  brouard
                    392:   Summary: not working
                    393: 
1.232     brouard   394:   Revision 1.231  2016/08/22 07:17:15  brouard
                    395:   Summary: not working
                    396: 
1.231     brouard   397:   Revision 1.230  2016/08/22 06:55:53  brouard
                    398:   Summary: Not working
                    399: 
1.230     brouard   400:   Revision 1.229  2016/07/23 09:45:53  brouard
                    401:   Summary: Completing for func too
                    402: 
1.229     brouard   403:   Revision 1.228  2016/07/22 17:45:30  brouard
                    404:   Summary: Fixing some arrays, still debugging
                    405: 
1.227     brouard   406:   Revision 1.226  2016/07/12 18:42:34  brouard
                    407:   Summary: temp
                    408: 
1.226     brouard   409:   Revision 1.225  2016/07/12 08:40:03  brouard
                    410:   Summary: saving but not running
                    411: 
1.225     brouard   412:   Revision 1.224  2016/07/01 13:16:01  brouard
                    413:   Summary: Fixes
                    414: 
1.224     brouard   415:   Revision 1.223  2016/02/19 09:23:35  brouard
                    416:   Summary: temporary
                    417: 
1.223     brouard   418:   Revision 1.222  2016/02/17 08:14:50  brouard
                    419:   Summary: Probably last 0.98 stable version 0.98r6
                    420: 
1.222     brouard   421:   Revision 1.221  2016/02/15 23:35:36  brouard
                    422:   Summary: minor bug
                    423: 
1.220     brouard   424:   Revision 1.219  2016/02/15 00:48:12  brouard
                    425:   *** empty log message ***
                    426: 
1.219     brouard   427:   Revision 1.218  2016/02/12 11:29:23  brouard
                    428:   Summary: 0.99 Back projections
                    429: 
1.218     brouard   430:   Revision 1.217  2015/12/23 17:18:31  brouard
                    431:   Summary: Experimental backcast
                    432: 
1.217     brouard   433:   Revision 1.216  2015/12/18 17:32:11  brouard
                    434:   Summary: 0.98r4 Warning and status=-2
                    435: 
                    436:   Version 0.98r4 is now:
                    437:    - displaying an error when status is -1, date of interview unknown and date of death known;
                    438:    - permitting a status -2 when the vital status is unknown at a known date of right truncation.
                    439:   Older changes concerning s=-2, dating from 2005 have been supersed.
                    440: 
1.216     brouard   441:   Revision 1.215  2015/12/16 08:52:24  brouard
                    442:   Summary: 0.98r4 working
                    443: 
1.215     brouard   444:   Revision 1.214  2015/12/16 06:57:54  brouard
                    445:   Summary: temporary not working
                    446: 
1.214     brouard   447:   Revision 1.213  2015/12/11 18:22:17  brouard
                    448:   Summary: 0.98r4
                    449: 
1.213     brouard   450:   Revision 1.212  2015/11/21 12:47:24  brouard
                    451:   Summary: minor typo
                    452: 
1.212     brouard   453:   Revision 1.211  2015/11/21 12:41:11  brouard
                    454:   Summary: 0.98r3 with some graph of projected cross-sectional
                    455: 
                    456:   Author: Nicolas Brouard
                    457: 
1.211     brouard   458:   Revision 1.210  2015/11/18 17:41:20  brouard
1.252     brouard   459:   Summary: Start working on projected prevalences  Revision 1.209  2015/11/17 22:12:03  brouard
1.210     brouard   460:   Summary: Adding ftolpl parameter
                    461:   Author: N Brouard
                    462: 
                    463:   We had difficulties to get smoothed confidence intervals. It was due
                    464:   to the period prevalence which wasn't computed accurately. The inner
                    465:   parameter ftolpl is now an outer parameter of the .imach parameter
                    466:   file after estepm. If ftolpl is small 1.e-4 and estepm too,
                    467:   computation are long.
                    468: 
1.209     brouard   469:   Revision 1.208  2015/11/17 14:31:57  brouard
                    470:   Summary: temporary
                    471: 
1.208     brouard   472:   Revision 1.207  2015/10/27 17:36:57  brouard
                    473:   *** empty log message ***
                    474: 
1.207     brouard   475:   Revision 1.206  2015/10/24 07:14:11  brouard
                    476:   *** empty log message ***
                    477: 
1.206     brouard   478:   Revision 1.205  2015/10/23 15:50:53  brouard
                    479:   Summary: 0.98r3 some clarification for graphs on likelihood contributions
                    480: 
1.205     brouard   481:   Revision 1.204  2015/10/01 16:20:26  brouard
                    482:   Summary: Some new graphs of contribution to likelihood
                    483: 
1.204     brouard   484:   Revision 1.203  2015/09/30 17:45:14  brouard
                    485:   Summary: looking at better estimation of the hessian
                    486: 
                    487:   Also a better criteria for convergence to the period prevalence And
                    488:   therefore adding the number of years needed to converge. (The
                    489:   prevalence in any alive state shold sum to one
                    490: 
1.203     brouard   491:   Revision 1.202  2015/09/22 19:45:16  brouard
                    492:   Summary: Adding some overall graph on contribution to likelihood. Might change
                    493: 
1.202     brouard   494:   Revision 1.201  2015/09/15 17:34:58  brouard
                    495:   Summary: 0.98r0
                    496: 
                    497:   - Some new graphs like suvival functions
                    498:   - Some bugs fixed like model=1+age+V2.
                    499: 
1.201     brouard   500:   Revision 1.200  2015/09/09 16:53:55  brouard
                    501:   Summary: Big bug thanks to Flavia
                    502: 
                    503:   Even model=1+age+V2. did not work anymore
                    504: 
1.200     brouard   505:   Revision 1.199  2015/09/07 14:09:23  brouard
                    506:   Summary: 0.98q6 changing default small png format for graph to vectorized svg.
                    507: 
1.199     brouard   508:   Revision 1.198  2015/09/03 07:14:39  brouard
                    509:   Summary: 0.98q5 Flavia
                    510: 
1.198     brouard   511:   Revision 1.197  2015/09/01 18:24:39  brouard
                    512:   *** empty log message ***
                    513: 
1.197     brouard   514:   Revision 1.196  2015/08/18 23:17:52  brouard
                    515:   Summary: 0.98q5
                    516: 
1.196     brouard   517:   Revision 1.195  2015/08/18 16:28:39  brouard
                    518:   Summary: Adding a hack for testing purpose
                    519: 
                    520:   After reading the title, ftol and model lines, if the comment line has
                    521:   a q, starting with #q, the answer at the end of the run is quit. It
                    522:   permits to run test files in batch with ctest. The former workaround was
                    523:   $ echo q | imach foo.imach
                    524: 
1.195     brouard   525:   Revision 1.194  2015/08/18 13:32:00  brouard
                    526:   Summary:  Adding error when the covariance matrix doesn't contain the exact number of lines required by the model line.
                    527: 
1.194     brouard   528:   Revision 1.193  2015/08/04 07:17:42  brouard
                    529:   Summary: 0.98q4
                    530: 
1.193     brouard   531:   Revision 1.192  2015/07/16 16:49:02  brouard
                    532:   Summary: Fixing some outputs
                    533: 
1.192     brouard   534:   Revision 1.191  2015/07/14 10:00:33  brouard
                    535:   Summary: Some fixes
                    536: 
1.191     brouard   537:   Revision 1.190  2015/05/05 08:51:13  brouard
                    538:   Summary: Adding digits in output parameters (7 digits instead of 6)
                    539: 
                    540:   Fix 1+age+.
                    541: 
1.190     brouard   542:   Revision 1.189  2015/04/30 14:45:16  brouard
                    543:   Summary: 0.98q2
                    544: 
1.189     brouard   545:   Revision 1.188  2015/04/30 08:27:53  brouard
                    546:   *** empty log message ***
                    547: 
1.188     brouard   548:   Revision 1.187  2015/04/29 09:11:15  brouard
                    549:   *** empty log message ***
                    550: 
1.187     brouard   551:   Revision 1.186  2015/04/23 12:01:52  brouard
                    552:   Summary: V1*age is working now, version 0.98q1
                    553: 
                    554:   Some codes had been disabled in order to simplify and Vn*age was
                    555:   working in the optimization phase, ie, giving correct MLE parameters,
                    556:   but, as usual, outputs were not correct and program core dumped.
                    557: 
1.186     brouard   558:   Revision 1.185  2015/03/11 13:26:42  brouard
                    559:   Summary: Inclusion of compile and links command line for Intel Compiler
                    560: 
1.185     brouard   561:   Revision 1.184  2015/03/11 11:52:39  brouard
                    562:   Summary: Back from Windows 8. Intel Compiler
                    563: 
1.184     brouard   564:   Revision 1.183  2015/03/10 20:34:32  brouard
                    565:   Summary: 0.98q0, trying with directest, mnbrak fixed
                    566: 
                    567:   We use directest instead of original Powell test; probably no
                    568:   incidence on the results, but better justifications;
                    569:   We fixed Numerical Recipes mnbrak routine which was wrong and gave
                    570:   wrong results.
                    571: 
1.183     brouard   572:   Revision 1.182  2015/02/12 08:19:57  brouard
                    573:   Summary: Trying to keep directest which seems simpler and more general
                    574:   Author: Nicolas Brouard
                    575: 
1.182     brouard   576:   Revision 1.181  2015/02/11 23:22:24  brouard
                    577:   Summary: Comments on Powell added
                    578: 
                    579:   Author:
                    580: 
1.181     brouard   581:   Revision 1.180  2015/02/11 17:33:45  brouard
                    582:   Summary: Finishing move from main to function (hpijx and prevalence_limit)
                    583: 
1.180     brouard   584:   Revision 1.179  2015/01/04 09:57:06  brouard
                    585:   Summary: back to OS/X
                    586: 
1.179     brouard   587:   Revision 1.178  2015/01/04 09:35:48  brouard
                    588:   *** empty log message ***
                    589: 
1.178     brouard   590:   Revision 1.177  2015/01/03 18:40:56  brouard
                    591:   Summary: Still testing ilc32 on OSX
                    592: 
1.177     brouard   593:   Revision 1.176  2015/01/03 16:45:04  brouard
                    594:   *** empty log message ***
                    595: 
1.176     brouard   596:   Revision 1.175  2015/01/03 16:33:42  brouard
                    597:   *** empty log message ***
                    598: 
1.175     brouard   599:   Revision 1.174  2015/01/03 16:15:49  brouard
                    600:   Summary: Still in cross-compilation
                    601: 
1.174     brouard   602:   Revision 1.173  2015/01/03 12:06:26  brouard
                    603:   Summary: trying to detect cross-compilation
                    604: 
1.173     brouard   605:   Revision 1.172  2014/12/27 12:07:47  brouard
                    606:   Summary: Back from Visual Studio and Intel, options for compiling for Windows XP
                    607: 
1.172     brouard   608:   Revision 1.171  2014/12/23 13:26:59  brouard
                    609:   Summary: Back from Visual C
                    610: 
                    611:   Still problem with utsname.h on Windows
                    612: 
1.171     brouard   613:   Revision 1.170  2014/12/23 11:17:12  brouard
                    614:   Summary: Cleaning some \%% back to %%
                    615: 
                    616:   The escape was mandatory for a specific compiler (which one?), but too many warnings.
                    617: 
1.170     brouard   618:   Revision 1.169  2014/12/22 23:08:31  brouard
                    619:   Summary: 0.98p
                    620: 
                    621:   Outputs some informations on compiler used, OS etc. Testing on different platforms.
                    622: 
1.169     brouard   623:   Revision 1.168  2014/12/22 15:17:42  brouard
1.170     brouard   624:   Summary: update
1.169     brouard   625: 
1.168     brouard   626:   Revision 1.167  2014/12/22 13:50:56  brouard
                    627:   Summary: Testing uname and compiler version and if compiled 32 or 64
                    628: 
                    629:   Testing on Linux 64
                    630: 
1.167     brouard   631:   Revision 1.166  2014/12/22 11:40:47  brouard
                    632:   *** empty log message ***
                    633: 
1.166     brouard   634:   Revision 1.165  2014/12/16 11:20:36  brouard
                    635:   Summary: After compiling on Visual C
                    636: 
                    637:   * imach.c (Module): Merging 1.61 to 1.162
                    638: 
1.165     brouard   639:   Revision 1.164  2014/12/16 10:52:11  brouard
                    640:   Summary: Merging with Visual C after suppressing some warnings for unused variables. Also fixing Saito's bug 0.98Xn
                    641: 
                    642:   * imach.c (Module): Merging 1.61 to 1.162
                    643: 
1.164     brouard   644:   Revision 1.163  2014/12/16 10:30:11  brouard
                    645:   * imach.c (Module): Merging 1.61 to 1.162
                    646: 
1.163     brouard   647:   Revision 1.162  2014/09/25 11:43:39  brouard
                    648:   Summary: temporary backup 0.99!
                    649: 
1.162     brouard   650:   Revision 1.1  2014/09/16 11:06:58  brouard
                    651:   Summary: With some code (wrong) for nlopt
                    652: 
                    653:   Author:
                    654: 
                    655:   Revision 1.161  2014/09/15 20:41:41  brouard
                    656:   Summary: Problem with macro SQR on Intel compiler
                    657: 
1.161     brouard   658:   Revision 1.160  2014/09/02 09:24:05  brouard
                    659:   *** empty log message ***
                    660: 
1.160     brouard   661:   Revision 1.159  2014/09/01 10:34:10  brouard
                    662:   Summary: WIN32
                    663:   Author: Brouard
                    664: 
1.159     brouard   665:   Revision 1.158  2014/08/27 17:11:51  brouard
                    666:   *** empty log message ***
                    667: 
1.158     brouard   668:   Revision 1.157  2014/08/27 16:26:55  brouard
                    669:   Summary: Preparing windows Visual studio version
                    670:   Author: Brouard
                    671: 
                    672:   In order to compile on Visual studio, time.h is now correct and time_t
                    673:   and tm struct should be used. difftime should be used but sometimes I
                    674:   just make the differences in raw time format (time(&now).
                    675:   Trying to suppress #ifdef LINUX
                    676:   Add xdg-open for __linux in order to open default browser.
                    677: 
1.157     brouard   678:   Revision 1.156  2014/08/25 20:10:10  brouard
                    679:   *** empty log message ***
                    680: 
1.156     brouard   681:   Revision 1.155  2014/08/25 18:32:34  brouard
                    682:   Summary: New compile, minor changes
                    683:   Author: Brouard
                    684: 
1.155     brouard   685:   Revision 1.154  2014/06/20 17:32:08  brouard
                    686:   Summary: Outputs now all graphs of convergence to period prevalence
                    687: 
1.154     brouard   688:   Revision 1.153  2014/06/20 16:45:46  brouard
                    689:   Summary: If 3 live state, convergence to period prevalence on same graph
                    690:   Author: Brouard
                    691: 
1.153     brouard   692:   Revision 1.152  2014/06/18 17:54:09  brouard
                    693:   Summary: open browser, use gnuplot on same dir than imach if not found in the path
                    694: 
1.152     brouard   695:   Revision 1.151  2014/06/18 16:43:30  brouard
                    696:   *** empty log message ***
                    697: 
1.151     brouard   698:   Revision 1.150  2014/06/18 16:42:35  brouard
                    699:   Summary: If gnuplot is not in the path try on same directory than imach binary (OSX)
                    700:   Author: brouard
                    701: 
1.150     brouard   702:   Revision 1.149  2014/06/18 15:51:14  brouard
                    703:   Summary: Some fixes in parameter files errors
                    704:   Author: Nicolas Brouard
                    705: 
1.149     brouard   706:   Revision 1.148  2014/06/17 17:38:48  brouard
                    707:   Summary: Nothing new
                    708:   Author: Brouard
                    709: 
                    710:   Just a new packaging for OS/X version 0.98nS
                    711: 
1.148     brouard   712:   Revision 1.147  2014/06/16 10:33:11  brouard
                    713:   *** empty log message ***
                    714: 
1.147     brouard   715:   Revision 1.146  2014/06/16 10:20:28  brouard
                    716:   Summary: Merge
                    717:   Author: Brouard
                    718: 
                    719:   Merge, before building revised version.
                    720: 
1.146     brouard   721:   Revision 1.145  2014/06/10 21:23:15  brouard
                    722:   Summary: Debugging with valgrind
                    723:   Author: Nicolas Brouard
                    724: 
                    725:   Lot of changes in order to output the results with some covariates
                    726:   After the Edimburgh REVES conference 2014, it seems mandatory to
                    727:   improve the code.
                    728:   No more memory valgrind error but a lot has to be done in order to
                    729:   continue the work of splitting the code into subroutines.
                    730:   Also, decodemodel has been improved. Tricode is still not
                    731:   optimal. nbcode should be improved. Documentation has been added in
                    732:   the source code.
                    733: 
1.144     brouard   734:   Revision 1.143  2014/01/26 09:45:38  brouard
                    735:   Summary: Version 0.98nR (to be improved, but gives same optimization results as 0.98k. Nice, promising
                    736: 
                    737:   * imach.c (Module): Trying to merge old staffs together while being at Tokyo. Not tested...
                    738:   (Module): Version 0.98nR Running ok, but output format still only works for three covariates.
                    739: 
1.143     brouard   740:   Revision 1.142  2014/01/26 03:57:36  brouard
                    741:   Summary: gnuplot changed plot w l 1 has to be changed to plot w l lt 2
                    742: 
                    743:   * imach.c (Module): Trying to merge old staffs together while being at Tokyo. Not tested...
                    744: 
1.142     brouard   745:   Revision 1.141  2014/01/26 02:42:01  brouard
                    746:   * imach.c (Module): Trying to merge old staffs together while being at Tokyo. Not tested...
                    747: 
1.141     brouard   748:   Revision 1.140  2011/09/02 10:37:54  brouard
                    749:   Summary: times.h is ok with mingw32 now.
                    750: 
1.140     brouard   751:   Revision 1.139  2010/06/14 07:50:17  brouard
                    752:   After the theft of my laptop, I probably lost some lines of codes which were not uploaded to the CVS tree.
                    753:   I remember having already fixed agemin agemax which are pointers now but not cvs saved.
                    754: 
1.139     brouard   755:   Revision 1.138  2010/04/30 18:19:40  brouard
                    756:   *** empty log message ***
                    757: 
1.138     brouard   758:   Revision 1.137  2010/04/29 18:11:38  brouard
                    759:   (Module): Checking covariates for more complex models
                    760:   than V1+V2. A lot of change to be done. Unstable.
                    761: 
1.137     brouard   762:   Revision 1.136  2010/04/26 20:30:53  brouard
                    763:   (Module): merging some libgsl code. Fixing computation
                    764:   of likelione (using inter/intrapolation if mle = 0) in order to
                    765:   get same likelihood as if mle=1.
                    766:   Some cleaning of code and comments added.
                    767: 
1.136     brouard   768:   Revision 1.135  2009/10/29 15:33:14  brouard
                    769:   (Module): Now imach stops if date of birth, at least year of birth, is not given. Some cleaning of the code.
                    770: 
1.135     brouard   771:   Revision 1.134  2009/10/29 13:18:53  brouard
                    772:   (Module): Now imach stops if date of birth, at least year of birth, is not given. Some cleaning of the code.
                    773: 
1.134     brouard   774:   Revision 1.133  2009/07/06 10:21:25  brouard
                    775:   just nforces
                    776: 
1.133     brouard   777:   Revision 1.132  2009/07/06 08:22:05  brouard
                    778:   Many tings
                    779: 
1.132     brouard   780:   Revision 1.131  2009/06/20 16:22:47  brouard
                    781:   Some dimensions resccaled
                    782: 
1.131     brouard   783:   Revision 1.130  2009/05/26 06:44:34  brouard
                    784:   (Module): Max Covariate is now set to 20 instead of 8. A
                    785:   lot of cleaning with variables initialized to 0. Trying to make
                    786:   V2+V3*age+V1+V4 strb=V3*age+V1+V4 working better.
                    787: 
1.130     brouard   788:   Revision 1.129  2007/08/31 13:49:27  lievre
                    789:   Modification of the way of exiting when the covariate is not binary in order to see on the window the error message before exiting
                    790: 
1.129     lievre    791:   Revision 1.128  2006/06/30 13:02:05  brouard
                    792:   (Module): Clarifications on computing e.j
                    793: 
1.128     brouard   794:   Revision 1.127  2006/04/28 18:11:50  brouard
                    795:   (Module): Yes the sum of survivors was wrong since
                    796:   imach-114 because nhstepm was no more computed in the age
                    797:   loop. Now we define nhstepma in the age loop.
                    798:   (Module): In order to speed up (in case of numerous covariates) we
                    799:   compute health expectancies (without variances) in a first step
                    800:   and then all the health expectancies with variances or standard
                    801:   deviation (needs data from the Hessian matrices) which slows the
                    802:   computation.
                    803:   In the future we should be able to stop the program is only health
                    804:   expectancies and graph are needed without standard deviations.
                    805: 
1.127     brouard   806:   Revision 1.126  2006/04/28 17:23:28  brouard
                    807:   (Module): Yes the sum of survivors was wrong since
                    808:   imach-114 because nhstepm was no more computed in the age
                    809:   loop. Now we define nhstepma in the age loop.
                    810:   Version 0.98h
                    811: 
1.126     brouard   812:   Revision 1.125  2006/04/04 15:20:31  lievre
                    813:   Errors in calculation of health expectancies. Age was not initialized.
                    814:   Forecasting file added.
                    815: 
                    816:   Revision 1.124  2006/03/22 17:13:53  lievre
                    817:   Parameters are printed with %lf instead of %f (more numbers after the comma).
                    818:   The log-likelihood is printed in the log file
                    819: 
                    820:   Revision 1.123  2006/03/20 10:52:43  brouard
                    821:   * imach.c (Module): <title> changed, corresponds to .htm file
                    822:   name. <head> headers where missing.
                    823: 
                    824:   * imach.c (Module): Weights can have a decimal point as for
                    825:   English (a comma might work with a correct LC_NUMERIC environment,
                    826:   otherwise the weight is truncated).
                    827:   Modification of warning when the covariates values are not 0 or
                    828:   1.
                    829:   Version 0.98g
                    830: 
                    831:   Revision 1.122  2006/03/20 09:45:41  brouard
                    832:   (Module): Weights can have a decimal point as for
                    833:   English (a comma might work with a correct LC_NUMERIC environment,
                    834:   otherwise the weight is truncated).
                    835:   Modification of warning when the covariates values are not 0 or
                    836:   1.
                    837:   Version 0.98g
                    838: 
                    839:   Revision 1.121  2006/03/16 17:45:01  lievre
                    840:   * imach.c (Module): Comments concerning covariates added
                    841: 
                    842:   * imach.c (Module): refinements in the computation of lli if
                    843:   status=-2 in order to have more reliable computation if stepm is
                    844:   not 1 month. Version 0.98f
                    845: 
                    846:   Revision 1.120  2006/03/16 15:10:38  lievre
                    847:   (Module): refinements in the computation of lli if
                    848:   status=-2 in order to have more reliable computation if stepm is
                    849:   not 1 month. Version 0.98f
                    850: 
                    851:   Revision 1.119  2006/03/15 17:42:26  brouard
                    852:   (Module): Bug if status = -2, the loglikelihood was
                    853:   computed as likelihood omitting the logarithm. Version O.98e
                    854: 
                    855:   Revision 1.118  2006/03/14 18:20:07  brouard
                    856:   (Module): varevsij Comments added explaining the second
                    857:   table of variances if popbased=1 .
                    858:   (Module): Covariances of eij, ekl added, graphs fixed, new html link.
                    859:   (Module): Function pstamp added
                    860:   (Module): Version 0.98d
                    861: 
                    862:   Revision 1.117  2006/03/14 17:16:22  brouard
                    863:   (Module): varevsij Comments added explaining the second
                    864:   table of variances if popbased=1 .
                    865:   (Module): Covariances of eij, ekl added, graphs fixed, new html link.
                    866:   (Module): Function pstamp added
                    867:   (Module): Version 0.98d
                    868: 
                    869:   Revision 1.116  2006/03/06 10:29:27  brouard
                    870:   (Module): Variance-covariance wrong links and
                    871:   varian-covariance of ej. is needed (Saito).
                    872: 
                    873:   Revision 1.115  2006/02/27 12:17:45  brouard
                    874:   (Module): One freematrix added in mlikeli! 0.98c
                    875: 
                    876:   Revision 1.114  2006/02/26 12:57:58  brouard
                    877:   (Module): Some improvements in processing parameter
                    878:   filename with strsep.
                    879: 
                    880:   Revision 1.113  2006/02/24 14:20:24  brouard
                    881:   (Module): Memory leaks checks with valgrind and:
                    882:   datafile was not closed, some imatrix were not freed and on matrix
                    883:   allocation too.
                    884: 
                    885:   Revision 1.112  2006/01/30 09:55:26  brouard
                    886:   (Module): Back to gnuplot.exe instead of wgnuplot.exe
                    887: 
                    888:   Revision 1.111  2006/01/25 20:38:18  brouard
                    889:   (Module): Lots of cleaning and bugs added (Gompertz)
                    890:   (Module): Comments can be added in data file. Missing date values
                    891:   can be a simple dot '.'.
                    892: 
                    893:   Revision 1.110  2006/01/25 00:51:50  brouard
                    894:   (Module): Lots of cleaning and bugs added (Gompertz)
                    895: 
                    896:   Revision 1.109  2006/01/24 19:37:15  brouard
                    897:   (Module): Comments (lines starting with a #) are allowed in data.
                    898: 
                    899:   Revision 1.108  2006/01/19 18:05:42  lievre
                    900:   Gnuplot problem appeared...
                    901:   To be fixed
                    902: 
                    903:   Revision 1.107  2006/01/19 16:20:37  brouard
                    904:   Test existence of gnuplot in imach path
                    905: 
                    906:   Revision 1.106  2006/01/19 13:24:36  brouard
                    907:   Some cleaning and links added in html output
                    908: 
                    909:   Revision 1.105  2006/01/05 20:23:19  lievre
                    910:   *** empty log message ***
                    911: 
                    912:   Revision 1.104  2005/09/30 16:11:43  lievre
                    913:   (Module): sump fixed, loop imx fixed, and simplifications.
                    914:   (Module): If the status is missing at the last wave but we know
                    915:   that the person is alive, then we can code his/her status as -2
                    916:   (instead of missing=-1 in earlier versions) and his/her
                    917:   contributions to the likelihood is 1 - Prob of dying from last
                    918:   health status (= 1-p13= p11+p12 in the easiest case of somebody in
                    919:   the healthy state at last known wave). Version is 0.98
                    920: 
                    921:   Revision 1.103  2005/09/30 15:54:49  lievre
                    922:   (Module): sump fixed, loop imx fixed, and simplifications.
                    923: 
                    924:   Revision 1.102  2004/09/15 17:31:30  brouard
                    925:   Add the possibility to read data file including tab characters.
                    926: 
                    927:   Revision 1.101  2004/09/15 10:38:38  brouard
                    928:   Fix on curr_time
                    929: 
                    930:   Revision 1.100  2004/07/12 18:29:06  brouard
                    931:   Add version for Mac OS X. Just define UNIX in Makefile
                    932: 
                    933:   Revision 1.99  2004/06/05 08:57:40  brouard
                    934:   *** empty log message ***
                    935: 
                    936:   Revision 1.98  2004/05/16 15:05:56  brouard
                    937:   New version 0.97 . First attempt to estimate force of mortality
                    938:   directly from the data i.e. without the need of knowing the health
                    939:   state at each age, but using a Gompertz model: log u =a + b*age .
                    940:   This is the basic analysis of mortality and should be done before any
                    941:   other analysis, in order to test if the mortality estimated from the
                    942:   cross-longitudinal survey is different from the mortality estimated
                    943:   from other sources like vital statistic data.
                    944: 
                    945:   The same imach parameter file can be used but the option for mle should be -3.
                    946: 
1.324     brouard   947:   Agnès, who wrote this part of the code, tried to keep most of the
1.126     brouard   948:   former routines in order to include the new code within the former code.
                    949: 
                    950:   The output is very simple: only an estimate of the intercept and of
                    951:   the slope with 95% confident intervals.
                    952: 
                    953:   Current limitations:
                    954:   A) Even if you enter covariates, i.e. with the
                    955:   model= V1+V2 equation for example, the programm does only estimate a unique global model without covariates.
                    956:   B) There is no computation of Life Expectancy nor Life Table.
                    957: 
                    958:   Revision 1.97  2004/02/20 13:25:42  lievre
                    959:   Version 0.96d. Population forecasting command line is (temporarily)
                    960:   suppressed.
                    961: 
                    962:   Revision 1.96  2003/07/15 15:38:55  brouard
                    963:   * imach.c (Repository): Errors in subdirf, 2, 3 while printing tmpout is
                    964:   rewritten within the same printf. Workaround: many printfs.
                    965: 
                    966:   Revision 1.95  2003/07/08 07:54:34  brouard
                    967:   * imach.c (Repository):
                    968:   (Repository): Using imachwizard code to output a more meaningful covariance
                    969:   matrix (cov(a12,c31) instead of numbers.
                    970: 
                    971:   Revision 1.94  2003/06/27 13:00:02  brouard
                    972:   Just cleaning
                    973: 
                    974:   Revision 1.93  2003/06/25 16:33:55  brouard
                    975:   (Module): On windows (cygwin) function asctime_r doesn't
                    976:   exist so I changed back to asctime which exists.
                    977:   (Module): Version 0.96b
                    978: 
                    979:   Revision 1.92  2003/06/25 16:30:45  brouard
                    980:   (Module): On windows (cygwin) function asctime_r doesn't
                    981:   exist so I changed back to asctime which exists.
                    982: 
                    983:   Revision 1.91  2003/06/25 15:30:29  brouard
                    984:   * imach.c (Repository): Duplicated warning errors corrected.
                    985:   (Repository): Elapsed time after each iteration is now output. It
                    986:   helps to forecast when convergence will be reached. Elapsed time
                    987:   is stamped in powell.  We created a new html file for the graphs
                    988:   concerning matrix of covariance. It has extension -cov.htm.
                    989: 
                    990:   Revision 1.90  2003/06/24 12:34:15  brouard
                    991:   (Module): Some bugs corrected for windows. Also, when
                    992:   mle=-1 a template is output in file "or"mypar.txt with the design
                    993:   of the covariance matrix to be input.
                    994: 
                    995:   Revision 1.89  2003/06/24 12:30:52  brouard
                    996:   (Module): Some bugs corrected for windows. Also, when
                    997:   mle=-1 a template is output in file "or"mypar.txt with the design
                    998:   of the covariance matrix to be input.
                    999: 
                   1000:   Revision 1.88  2003/06/23 17:54:56  brouard
                   1001:   * 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.
                   1002: 
                   1003:   Revision 1.87  2003/06/18 12:26:01  brouard
                   1004:   Version 0.96
                   1005: 
                   1006:   Revision 1.86  2003/06/17 20:04:08  brouard
                   1007:   (Module): Change position of html and gnuplot routines and added
                   1008:   routine fileappend.
                   1009: 
                   1010:   Revision 1.85  2003/06/17 13:12:43  brouard
                   1011:   * imach.c (Repository): Check when date of death was earlier that
                   1012:   current date of interview. It may happen when the death was just
                   1013:   prior to the death. In this case, dh was negative and likelihood
                   1014:   was wrong (infinity). We still send an "Error" but patch by
                   1015:   assuming that the date of death was just one stepm after the
                   1016:   interview.
                   1017:   (Repository): Because some people have very long ID (first column)
                   1018:   we changed int to long in num[] and we added a new lvector for
                   1019:   memory allocation. But we also truncated to 8 characters (left
                   1020:   truncation)
                   1021:   (Repository): No more line truncation errors.
                   1022: 
                   1023:   Revision 1.84  2003/06/13 21:44:43  brouard
                   1024:   * imach.c (Repository): Replace "freqsummary" at a correct
                   1025:   place. It differs from routine "prevalence" which may be called
                   1026:   many times. Probs is memory consuming and must be used with
                   1027:   parcimony.
                   1028:   Version 0.95a3 (should output exactly the same maximization than 0.8a2)
                   1029: 
                   1030:   Revision 1.83  2003/06/10 13:39:11  lievre
                   1031:   *** empty log message ***
                   1032: 
                   1033:   Revision 1.82  2003/06/05 15:57:20  brouard
                   1034:   Add log in  imach.c and  fullversion number is now printed.
                   1035: 
                   1036: */
                   1037: /*
                   1038:    Interpolated Markov Chain
                   1039: 
                   1040:   Short summary of the programme:
                   1041:   
1.227     brouard  1042:   This program computes Healthy Life Expectancies or State-specific
                   1043:   (if states aren't health statuses) Expectancies from
                   1044:   cross-longitudinal data. Cross-longitudinal data consist in: 
                   1045: 
                   1046:   -1- a first survey ("cross") where individuals from different ages
                   1047:   are interviewed on their health status or degree of disability (in
                   1048:   the case of a health survey which is our main interest)
                   1049: 
                   1050:   -2- at least a second wave of interviews ("longitudinal") which
                   1051:   measure each change (if any) in individual health status.  Health
                   1052:   expectancies are computed from the time spent in each health state
                   1053:   according to a model. More health states you consider, more time is
                   1054:   necessary to reach the Maximum Likelihood of the parameters involved
                   1055:   in the model.  The simplest model is the multinomial logistic model
                   1056:   where pij is the probability to be observed in state j at the second
                   1057:   wave conditional to be observed in state i at the first
                   1058:   wave. Therefore the model is: log(pij/pii)= aij + bij*age+ cij*sex +
                   1059:   etc , where 'age' is age and 'sex' is a covariate. If you want to
                   1060:   have a more complex model than "constant and age", you should modify
                   1061:   the program where the markup *Covariates have to be included here
                   1062:   again* invites you to do it.  More covariates you add, slower the
1.126     brouard  1063:   convergence.
                   1064: 
                   1065:   The advantage of this computer programme, compared to a simple
                   1066:   multinomial logistic model, is clear when the delay between waves is not
                   1067:   identical for each individual. Also, if a individual missed an
                   1068:   intermediate interview, the information is lost, but taken into
                   1069:   account using an interpolation or extrapolation.  
                   1070: 
                   1071:   hPijx is the probability to be observed in state i at age x+h
                   1072:   conditional to the observed state i at age x. The delay 'h' can be
                   1073:   split into an exact number (nh*stepm) of unobserved intermediate
                   1074:   states. This elementary transition (by month, quarter,
                   1075:   semester or year) is modelled as a multinomial logistic.  The hPx
                   1076:   matrix is simply the matrix product of nh*stepm elementary matrices
                   1077:   and the contribution of each individual to the likelihood is simply
                   1078:   hPijx.
                   1079: 
                   1080:   Also this programme outputs the covariance matrix of the parameters but also
1.218     brouard  1081:   of the life expectancies. It also computes the period (stable) prevalence.
                   1082: 
                   1083: Back prevalence and projections:
1.227     brouard  1084: 
                   1085:  - back_prevalence_limit(double *p, double **bprlim, double ageminpar,
                   1086:    double agemaxpar, double ftolpl, int *ncvyearp, double
                   1087:    dateprev1,double dateprev2, int firstpass, int lastpass, int
                   1088:    mobilavproj)
                   1089: 
                   1090:     Computes the back prevalence limit for any combination of
                   1091:     covariate values k at any age between ageminpar and agemaxpar and
                   1092:     returns it in **bprlim. In the loops,
                   1093: 
                   1094:    - **bprevalim(**bprlim, ***mobaverage, nlstate, *p, age, **oldm,
                   1095:        **savm, **dnewm, **doldm, **dsavm, ftolpl, ncvyearp, k);
                   1096: 
                   1097:    - hBijx Back Probability to be in state i at age x-h being in j at x
1.218     brouard  1098:    Computes for any combination of covariates k and any age between bage and fage 
                   1099:    p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   1100:                        oldm=oldms;savm=savms;
1.227     brouard  1101: 
1.267     brouard  1102:    - hbxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k, nres);
1.218     brouard  1103:      Computes the transition matrix starting at age 'age' over
                   1104:      'nhstepm*hstepm*stepm' months (i.e. until
                   1105:      age (in years)  age+nhstepm*hstepm*stepm/12) by multiplying
1.227     brouard  1106:      nhstepm*hstepm matrices. 
                   1107: 
                   1108:      Returns p3mat[i][j][h] after calling
                   1109:      p3mat[i][j][h]=matprod2(newm,
                   1110:      bmij(pmmij,cov,ncovmodel,x,nlstate,prevacurrent, dnewm, doldm,
                   1111:      dsavm,ij),\ 1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath,
                   1112:      oldm);
1.226     brouard  1113: 
                   1114: Important routines
                   1115: 
                   1116: - func (or funcone), computes logit (pij) distinguishing
                   1117:   o fixed variables (single or product dummies or quantitative);
                   1118:   o varying variables by:
                   1119:    (1) wave (single, product dummies, quantitative), 
                   1120:    (2) by age (can be month) age (done), age*age (done), age*Vn where Vn can be:
                   1121:        % fixed dummy (treated) or quantitative (not done because time-consuming);
                   1122:        % varying dummy (not done) or quantitative (not done);
                   1123: - Tricode which tests the modality of dummy variables (in order to warn with wrong or empty modalities)
                   1124:   and returns the number of efficient covariates cptcoveff and modalities nbcode[Tvar[k]][1]= 0 and nbcode[Tvar[k]][2]= 1 usually.
                   1125: - printinghtml which outputs results like life expectancy in and from a state for a combination of modalities of dummy variables
1.325     brouard  1126:   o There are 2**cptcoveff combinations of (0,1) for cptcoveff variables. Outputting only combinations with people, éliminating 1 1 if
1.226     brouard  1127:     race White (0 0), Black vs White (1 0), Hispanic (0 1) and 1 1 being meaningless.
1.218     brouard  1128: 
1.226     brouard  1129: 
                   1130:   
1.324     brouard  1131:   Authors: Nicolas Brouard (brouard@ined.fr) and Agnès Lièvre (lievre@ined.fr).
                   1132:            Institut national d'études démographiques, Paris.
1.126     brouard  1133:   This software have been partly granted by Euro-REVES, a concerted action
                   1134:   from the European Union.
                   1135:   It is copyrighted identically to a GNU software product, ie programme and
                   1136:   software can be distributed freely for non commercial use. Latest version
                   1137:   can be accessed at http://euroreves.ined.fr/imach .
                   1138: 
                   1139:   Help to debug: LD_PRELOAD=/usr/local/lib/libnjamd.so ./imach foo.imach
                   1140:   or better on gdb : set env LD_PRELOAD=/usr/local/lib/libnjamd.so
                   1141:   
                   1142:   **********************************************************************/
                   1143: /*
                   1144:   main
                   1145:   read parameterfile
                   1146:   read datafile
                   1147:   concatwav
                   1148:   freqsummary
                   1149:   if (mle >= 1)
                   1150:     mlikeli
                   1151:   print results files
                   1152:   if mle==1 
                   1153:      computes hessian
                   1154:   read end of parameter file: agemin, agemax, bage, fage, estepm
                   1155:       begin-prev-date,...
                   1156:   open gnuplot file
                   1157:   open html file
1.145     brouard  1158:   period (stable) prevalence      | pl_nom    1-1 2-2 etc by covariate
                   1159:    for age prevalim()             | #****** V1=0  V2=1  V3=1  V4=0 ******
                   1160:                                   | 65 1 0 2 1 3 1 4 0  0.96326 0.03674
                   1161:     freexexit2 possible for memory heap.
                   1162: 
                   1163:   h Pij x                         | pij_nom  ficrestpij
                   1164:    # Cov Agex agex+h hpijx with i,j= 1-1 1-2     1-3     2-1     2-2     2-3
                   1165:        1  85   85    1.00000             0.00000 0.00000 0.00000 1.00000 0.00000
                   1166:        1  85   86    0.68299             0.22291 0.09410 0.71093 0.00000 0.28907
                   1167: 
                   1168:        1  65   99    0.00364             0.00322 0.99314 0.00350 0.00310 0.99340
                   1169:        1  65  100    0.00214             0.00204 0.99581 0.00206 0.00196 0.99597
                   1170:   variance of p one-step probabilities varprob  | prob_nom   ficresprob #One-step probabilities and stand. devi in ()
                   1171:    Standard deviation of one-step probabilities | probcor_nom   ficresprobcor #One-step probabilities and correlation matrix
                   1172:    Matrix of variance covariance of one-step probabilities |  probcov_nom ficresprobcov #One-step probabilities and covariance matrix
                   1173: 
1.126     brouard  1174:   forecasting if prevfcast==1 prevforecast call prevalence()
                   1175:   health expectancies
                   1176:   Variance-covariance of DFLE
                   1177:   prevalence()
                   1178:    movingaverage()
                   1179:   varevsij() 
                   1180:   if popbased==1 varevsij(,popbased)
                   1181:   total life expectancies
                   1182:   Variance of period (stable) prevalence
                   1183:  end
                   1184: */
                   1185: 
1.187     brouard  1186: /* #define DEBUG */
                   1187: /* #define DEBUGBRENT */
1.203     brouard  1188: /* #define DEBUGLINMIN */
                   1189: /* #define DEBUGHESS */
                   1190: #define DEBUGHESSIJ
1.224     brouard  1191: /* #define LINMINORIGINAL  /\* Don't use loop on scale in linmin (accepting nan) *\/ */
1.165     brouard  1192: #define POWELL /* Instead of NLOPT */
1.224     brouard  1193: #define POWELLNOF3INFF1TEST /* Skip test */
1.186     brouard  1194: /* #define POWELLORIGINAL /\* Don't use Directest to decide new direction but original Powell test *\/ */
                   1195: /* #define MNBRAKORIGINAL /\* Don't use mnbrak fix *\/ */
1.319     brouard  1196: /* #define FLATSUP  *//* Suppresses directions where likelihood is flat */
1.126     brouard  1197: 
                   1198: #include <math.h>
                   1199: #include <stdio.h>
                   1200: #include <stdlib.h>
                   1201: #include <string.h>
1.226     brouard  1202: #include <ctype.h>
1.159     brouard  1203: 
                   1204: #ifdef _WIN32
                   1205: #include <io.h>
1.172     brouard  1206: #include <windows.h>
                   1207: #include <tchar.h>
1.159     brouard  1208: #else
1.126     brouard  1209: #include <unistd.h>
1.159     brouard  1210: #endif
1.126     brouard  1211: 
                   1212: #include <limits.h>
                   1213: #include <sys/types.h>
1.171     brouard  1214: 
                   1215: #if defined(__GNUC__)
                   1216: #include <sys/utsname.h> /* Doesn't work on Windows */
                   1217: #endif
                   1218: 
1.126     brouard  1219: #include <sys/stat.h>
                   1220: #include <errno.h>
1.159     brouard  1221: /* extern int errno; */
1.126     brouard  1222: 
1.157     brouard  1223: /* #ifdef LINUX */
                   1224: /* #include <time.h> */
                   1225: /* #include "timeval.h" */
                   1226: /* #else */
                   1227: /* #include <sys/time.h> */
                   1228: /* #endif */
                   1229: 
1.126     brouard  1230: #include <time.h>
                   1231: 
1.136     brouard  1232: #ifdef GSL
                   1233: #include <gsl/gsl_errno.h>
                   1234: #include <gsl/gsl_multimin.h>
                   1235: #endif
                   1236: 
1.167     brouard  1237: 
1.162     brouard  1238: #ifdef NLOPT
                   1239: #include <nlopt.h>
                   1240: typedef struct {
                   1241:   double (* function)(double [] );
                   1242: } myfunc_data ;
                   1243: #endif
                   1244: 
1.126     brouard  1245: /* #include <libintl.h> */
                   1246: /* #define _(String) gettext (String) */
                   1247: 
1.251     brouard  1248: #define MAXLINE 2048 /* Was 256 and 1024. Overflow with 312 with 2 states and 4 covariates. Should be ok */
1.126     brouard  1249: 
                   1250: #define GNUPLOTPROGRAM "gnuplot"
                   1251: /*#define GNUPLOTPROGRAM "..\\gp37mgw\\wgnuplot"*/
1.329     brouard  1252: #define FILENAMELENGTH 256
1.126     brouard  1253: 
                   1254: #define        GLOCK_ERROR_NOPATH              -1      /* empty path */
                   1255: #define        GLOCK_ERROR_GETCWD              -2      /* cannot get cwd */
                   1256: 
1.144     brouard  1257: #define MAXPARM 128 /**< Maximum number of parameters for the optimization */
                   1258: #define NPARMAX 64 /**< (nlstate+ndeath-1)*nlstate*ncovmodel */
1.126     brouard  1259: 
                   1260: #define NINTERVMAX 8
1.144     brouard  1261: #define NLSTATEMAX 8 /**< Maximum number of live states (for func) */
                   1262: #define NDEATHMAX 8 /**< Maximum number of dead states (for func) */
1.325     brouard  1263: #define NCOVMAX 30  /**< Maximum number of covariates used in the model, including generated covariates V1*V2 or V1*age */
1.197     brouard  1264: #define codtabm(h,k)  (1 & (h-1) >> (k-1))+1
1.211     brouard  1265: /*#define decodtabm(h,k,cptcoveff)= (h <= (1<<cptcoveff)?(((h-1) >> (k-1)) & 1) +1 : -1)*/
                   1266: #define decodtabm(h,k,cptcoveff) (((h-1) >> (k-1)) & 1) +1 
1.290     brouard  1267: /*#define MAXN 20000 */ /* Should by replaced by nobs, real number of observations and unlimited */
1.144     brouard  1268: #define YEARM 12. /**< Number of months per year */
1.218     brouard  1269: /* #define AGESUP 130 */
1.288     brouard  1270: /* #define AGESUP 150 */
                   1271: #define AGESUP 200
1.268     brouard  1272: #define AGEINF 0
1.218     brouard  1273: #define AGEMARGE 25 /* Marge for agemin and agemax for(iage=agemin-AGEMARGE; iage <= agemax+3+AGEMARGE; iage++) */
1.126     brouard  1274: #define AGEBASE 40
1.194     brouard  1275: #define AGEOVERFLOW 1.e20
1.164     brouard  1276: #define AGEGOMP 10 /**< Minimal age for Gompertz adjustment */
1.157     brouard  1277: #ifdef _WIN32
                   1278: #define DIRSEPARATOR '\\'
                   1279: #define CHARSEPARATOR "\\"
                   1280: #define ODIRSEPARATOR '/'
                   1281: #else
1.126     brouard  1282: #define DIRSEPARATOR '/'
                   1283: #define CHARSEPARATOR "/"
                   1284: #define ODIRSEPARATOR '\\'
                   1285: #endif
                   1286: 
1.336   ! brouard  1287: /* $Id: imach.c,v 1.335 2022/08/31 08:23:16 brouard Exp $ */
1.126     brouard  1288: /* $State: Exp $ */
1.196     brouard  1289: #include "version.h"
                   1290: char version[]=__IMACH_VERSION__;
1.332     brouard  1291: char copyright[]="August 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.336   ! brouard  1292: char fullversion[]="$Revision: 1.335 $ $Date: 2022/08/31 08:23:16 $"; 
1.126     brouard  1293: char strstart[80];
                   1294: char optionfilext[10], optionfilefiname[FILENAMELENGTH];
1.130     brouard  1295: int erreur=0, nberr=0, nbwarn=0; /* Error number, number of errors number of warnings  */
1.187     brouard  1296: int nagesqr=0, nforce=0; /* nagesqr=1 if model is including age*age, number of forces */
1.330     brouard  1297: /* Number of covariates model (1)=V2+V1+ V3*age+V2*V4 */
                   1298: /* Model(2)  V1 + V2 + V3 + V8 + V7*V8 + V5*V6 + V8*age + V3*age + age*age */
1.335     brouard  1299: int cptcovn=0; /**< cptcovn decodemodel: number of covariates k of the models excluding age*products =6 and age*age but including products */
1.330     brouard  1300: int cptcovt=0; /**< cptcovt: total number of covariates of the model (2) nbocc(+)+1 = 8 excepting constant and age and age*age */
1.335     brouard  1301: int cptcovs=0; /**< cptcovs number of SIMPLE covariates in the model V2+V1 =2 (dummy or quantit or time varying) */
                   1302: int cptcovsnq=0; /**< cptcovsnq number of SIMPLE covariates in the model but non quantitative V2+V1 =2 */
1.145     brouard  1303: int cptcovage=0; /**< Number of covariates with age: V3*age only =1 */
                   1304: int cptcovprodnoage=0; /**< Number of covariate products without age */   
1.335     brouard  1305: int cptcoveff=0; /* Total number of single dummy covariates (fixed or time varying) to vary for printing results (2**cptcoveff combinations of dummies)(computed in tricode as cptcov) */
1.233     brouard  1306: int ncovf=0; /* Total number of effective fixed covariates (dummy or quantitative) in the model */
                   1307: int ncovv=0; /* Total number of effective (wave) varying covariates (dummy or quantitative) in the model */
1.232     brouard  1308: int ncova=0; /* Total number of effective (wave and stepm) varying with age covariates (dummy of quantitative) in the model */
1.234     brouard  1309: int nsd=0; /**< Total number of single dummy variables (output) */
                   1310: int nsq=0; /**< Total number of single quantitative variables (output) */
1.232     brouard  1311: int ncoveff=0; /* Total number of effective fixed dummy covariates in the model */
1.225     brouard  1312: int nqfveff=0; /**< nqfveff Number of Quantitative Fixed Variables Effective */
1.224     brouard  1313: int ntveff=0; /**< ntveff number of effective time varying variables */
                   1314: int nqtveff=0; /**< ntqveff number of effective time varying quantitative variables */
1.145     brouard  1315: int cptcov=0; /* Working variable */
1.334     brouard  1316: int firstobs=1, lastobs=10; /* nobs = lastobs-firstobs+1 declared globally ;*/
1.290     brouard  1317: int nobs=10;  /* Number of observations in the data lastobs-firstobs */
1.218     brouard  1318: int ncovcombmax=NCOVMAX; /* Maximum calculated number of covariate combination = pow(2, cptcoveff) */
1.302     brouard  1319: int npar=NPARMAX; /* Number of parameters (nlstate+ndeath-1)*nlstate*ncovmodel; */
1.126     brouard  1320: int nlstate=2; /* Number of live states */
                   1321: int ndeath=1; /* Number of dead states */
1.130     brouard  1322: int ncovmodel=0, ncovcol=0;     /* Total number of covariables including constant a12*1 +b12*x ncovmodel=2 */
1.223     brouard  1323: int  nqv=0, ntv=0, nqtv=0;    /* Total number of quantitative variables, time variable (dummy), quantitative and time variable */ 
1.126     brouard  1324: int popbased=0;
                   1325: 
                   1326: int *wav; /* Number of waves for this individuual 0 is possible */
1.130     brouard  1327: int maxwav=0; /* Maxim number of waves */
                   1328: int jmin=0, jmax=0; /* min, max spacing between 2 waves */
                   1329: int ijmin=0, ijmax=0; /* Individuals having jmin and jmax */ 
                   1330: int gipmx=0, gsw=0; /* Global variables on the number of contributions 
1.126     brouard  1331:                   to the likelihood and the sum of weights (done by funcone)*/
1.130     brouard  1332: int mle=1, weightopt=0;
1.126     brouard  1333: int **mw; /* mw[mi][i] is number of the mi wave for this individual */
                   1334: int **dh; /* dh[mi][i] is number of steps between mi,mi+1 for this individual */
                   1335: int **bh; /* bh[mi][i] is the bias (+ or -) for this individual if the delay between
                   1336:           * wave mi and wave mi+1 is not an exact multiple of stepm. */
1.162     brouard  1337: int countcallfunc=0;  /* Count the number of calls to func */
1.230     brouard  1338: int selected(int kvar); /* Is covariate kvar selected for printing results */
                   1339: 
1.130     brouard  1340: double jmean=1; /* Mean space between 2 waves */
1.145     brouard  1341: double **matprod2(); /* test */
1.126     brouard  1342: double **oldm, **newm, **savm; /* Working pointers to matrices */
                   1343: double **oldms, **newms, **savms; /* Fixed working pointers to matrices */
1.218     brouard  1344: double  **ddnewms, **ddoldms, **ddsavms; /* for freeing later */
                   1345: 
1.136     brouard  1346: /*FILE *fic ; */ /* Used in readdata only */
1.217     brouard  1347: FILE *ficpar, *ficparo,*ficres, *ficresp, *ficresphtm, *ficresphtmfr, *ficrespl, *ficresplb,*ficrespij, *ficrespijb, *ficrest,*ficresf, *ficresfb,*ficrespop;
1.126     brouard  1348: FILE *ficlog, *ficrespow;
1.130     brouard  1349: int globpr=0; /* Global variable for printing or not */
1.126     brouard  1350: double fretone; /* Only one call to likelihood */
1.130     brouard  1351: long ipmx=0; /* Number of contributions */
1.126     brouard  1352: double sw; /* Sum of weights */
                   1353: char filerespow[FILENAMELENGTH];
                   1354: char fileresilk[FILENAMELENGTH]; /* File of individual contributions to the likelihood */
                   1355: FILE *ficresilk;
                   1356: FILE *ficgp,*ficresprob,*ficpop, *ficresprobcov, *ficresprobcor;
                   1357: FILE *ficresprobmorprev;
                   1358: FILE *fichtm, *fichtmcov; /* Html File */
                   1359: FILE *ficreseij;
                   1360: char filerese[FILENAMELENGTH];
                   1361: FILE *ficresstdeij;
                   1362: char fileresstde[FILENAMELENGTH];
                   1363: FILE *ficrescveij;
                   1364: char filerescve[FILENAMELENGTH];
                   1365: FILE  *ficresvij;
                   1366: char fileresv[FILENAMELENGTH];
1.269     brouard  1367: 
1.126     brouard  1368: char title[MAXLINE];
1.234     brouard  1369: char model[MAXLINE]; /**< The model line */
1.217     brouard  1370: char optionfile[FILENAMELENGTH], datafile[FILENAMELENGTH],  filerespl[FILENAMELENGTH],  fileresplb[FILENAMELENGTH];
1.126     brouard  1371: char plotcmd[FILENAMELENGTH], pplotcmd[FILENAMELENGTH];
                   1372: char tmpout[FILENAMELENGTH],  tmpout2[FILENAMELENGTH]; 
                   1373: char command[FILENAMELENGTH];
                   1374: int  outcmd=0;
                   1375: 
1.217     brouard  1376: char fileres[FILENAMELENGTH], filerespij[FILENAMELENGTH], filerespijb[FILENAMELENGTH], filereso[FILENAMELENGTH], rfileres[FILENAMELENGTH];
1.202     brouard  1377: char fileresu[FILENAMELENGTH]; /* fileres without r in front */
1.126     brouard  1378: char filelog[FILENAMELENGTH]; /* Log file */
                   1379: char filerest[FILENAMELENGTH];
                   1380: char fileregp[FILENAMELENGTH];
                   1381: char popfile[FILENAMELENGTH];
                   1382: 
                   1383: char optionfilegnuplot[FILENAMELENGTH], optionfilehtm[FILENAMELENGTH], optionfilehtmcov[FILENAMELENGTH] ;
                   1384: 
1.157     brouard  1385: /* struct timeval start_time, end_time, curr_time, last_time, forecast_time; */
                   1386: /* struct timezone tzp; */
                   1387: /* extern int gettimeofday(); */
                   1388: struct tm tml, *gmtime(), *localtime();
                   1389: 
                   1390: extern time_t time();
                   1391: 
                   1392: struct tm start_time, end_time, curr_time, last_time, forecast_time;
                   1393: time_t  rstart_time, rend_time, rcurr_time, rlast_time, rforecast_time; /* raw time */
                   1394: struct tm tm;
                   1395: 
1.126     brouard  1396: char strcurr[80], strfor[80];
                   1397: 
                   1398: char *endptr;
                   1399: long lval;
                   1400: double dval;
                   1401: 
                   1402: #define NR_END 1
                   1403: #define FREE_ARG char*
                   1404: #define FTOL 1.0e-10
                   1405: 
                   1406: #define NRANSI 
1.240     brouard  1407: #define ITMAX 200
                   1408: #define ITPOWMAX 20 /* This is now multiplied by the number of parameters */ 
1.126     brouard  1409: 
                   1410: #define TOL 2.0e-4 
                   1411: 
                   1412: #define CGOLD 0.3819660 
                   1413: #define ZEPS 1.0e-10 
                   1414: #define SHFT(a,b,c,d) (a)=(b);(b)=(c);(c)=(d); 
                   1415: 
                   1416: #define GOLD 1.618034 
                   1417: #define GLIMIT 100.0 
                   1418: #define TINY 1.0e-20 
                   1419: 
                   1420: static double maxarg1,maxarg2;
                   1421: #define FMAX(a,b) (maxarg1=(a),maxarg2=(b),(maxarg1)>(maxarg2)? (maxarg1):(maxarg2))
                   1422: #define FMIN(a,b) (maxarg1=(a),maxarg2=(b),(maxarg1)<(maxarg2)? (maxarg1):(maxarg2))
                   1423:   
                   1424: #define SIGN(a,b) ((b)>0.0 ? fabs(a) : -fabs(a))
                   1425: #define rint(a) floor(a+0.5)
1.166     brouard  1426: /* http://www.thphys.uni-heidelberg.de/~robbers/cmbeasy/doc/html/myutils_8h-source.html */
1.183     brouard  1427: #define mytinydouble 1.0e-16
1.166     brouard  1428: /* #define DEQUAL(a,b) (fabs((a)-(b))<mytinydouble) */
                   1429: /* http://www.thphys.uni-heidelberg.de/~robbers/cmbeasy/doc/html/mynrutils_8h-source.html */
                   1430: /* static double dsqrarg; */
                   1431: /* #define DSQR(a) (DEQUAL((dsqrarg=(a)),0.0) ? 0.0 : dsqrarg*dsqrarg) */
1.126     brouard  1432: static double sqrarg;
                   1433: #define SQR(a) ((sqrarg=(a)) == 0.0 ? 0.0 :sqrarg*sqrarg)
                   1434: #define SWAP(a,b) {temp=(a);(a)=(b);(b)=temp;} 
                   1435: int agegomp= AGEGOMP;
                   1436: 
                   1437: int imx; 
                   1438: int stepm=1;
                   1439: /* Stepm, step in month: minimum step interpolation*/
                   1440: 
                   1441: int estepm;
                   1442: /* Estepm, step in month to interpolate survival function in order to approximate Life Expectancy*/
                   1443: 
                   1444: int m,nb;
                   1445: long *num;
1.197     brouard  1446: int firstpass=0, lastpass=4,*cod, *cens;
1.192     brouard  1447: int *ncodemax;  /* ncodemax[j]= Number of modalities of the j th
                   1448:                   covariate for which somebody answered excluding 
                   1449:                   undefined. Usually 2: 0 and 1. */
                   1450: int *ncodemaxwundef;  /* ncodemax[j]= Number of modalities of the j th
                   1451:                             covariate for which somebody answered including 
                   1452:                             undefined. Usually 3: -1, 0 and 1. */
1.126     brouard  1453: double **agev,*moisnais, *annais, *moisdc, *andc,**mint, **anint;
1.218     brouard  1454: double **pmmij, ***probs; /* Global pointer */
1.219     brouard  1455: double ***mobaverage, ***mobaverages; /* New global variable */
1.332     brouard  1456: double **precov; /* New global variable to store for each resultline, values of model covariates given by the resultlines (in order to speed up)  */
1.126     brouard  1457: double *ageexmed,*agecens;
                   1458: double dateintmean=0;
1.296     brouard  1459:   double anprojd, mprojd, jprojd; /* For eventual projections */
                   1460:   double anprojf, mprojf, jprojf;
1.126     brouard  1461: 
1.296     brouard  1462:   double anbackd, mbackd, jbackd; /* For eventual backprojections */
                   1463:   double anbackf, mbackf, jbackf;
                   1464:   double jintmean,mintmean,aintmean;  
1.126     brouard  1465: double *weight;
                   1466: int **s; /* Status */
1.141     brouard  1467: double *agedc;
1.145     brouard  1468: double  **covar; /**< covar[j,i], value of jth covariate for individual i,
1.141     brouard  1469:                  * covar=matrix(0,NCOVMAX,1,n); 
1.187     brouard  1470:                  * cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*age; */
1.268     brouard  1471: double **coqvar; /* Fixed quantitative covariate nqv */
                   1472: double ***cotvar; /* Time varying covariate ntv */
1.225     brouard  1473: double ***cotqvar; /* Time varying quantitative covariate itqv */
1.141     brouard  1474: double  idx; 
                   1475: int **nbcode, *Tvar; /**< model=V2 => Tvar[1]= 2 */
1.319     brouard  1476: /* Some documentation */
                   1477:       /*   Design original data
                   1478:        *  V1   V2   V3   V4  V5  V6  V7  V8  Weight ddb ddth d1st s1 V9 V10 V11 V12 s2 V9 V10 V11 V12 
                   1479:        *  <          ncovcol=6   >   nqv=2 (V7 V8)                   dv dv  dv  qtv    dv dv  dvv qtv
                   1480:        *                                                             ntv=3     nqtv=1
1.330     brouard  1481:        *  cptcovn number of covariates (not including constant and age or age*age) = number of plus sign + 1 = 10+1=11
1.319     brouard  1482:        * For time varying covariate, quanti or dummies
                   1483:        *       cotqvar[wav][iv(1 to nqtv)][i]= [1][12][i]=(V12) quanti
                   1484:        *       cotvar[wav][ntv+iv][i]= [3+(1 to nqtv)][i]=(V12) quanti
                   1485:        *       cotvar[wav][iv(1 to ntv)][i]= [1][1][i]=(V9) dummies at wav 1
                   1486:        *       cotvar[wav][iv(1 to ntv)][i]= [1][2][i]=(V10) dummies at wav 1
1.332     brouard  1487:        *       covar[Vk,i], value of the Vkth fixed covariate dummy or quanti for individual i:
1.319     brouard  1488:        *       covar[1][i]= (V1), covar[4][i]=(V4), covar[8][i]=(V8)
                   1489:        * Model V2 + V1 + V3*age + V3 + V5*V6 + V7*V8 + V8*age + V8 + V9 + V9*age + V10
                   1490:        *   k=  1    2      3       4     5       6      7        8   9     10       11 
                   1491:        */
                   1492: /* According to the model, more columns can be added to covar by the product of covariates */
1.318     brouard  1493: /* 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
                   1494:   # States 1=Coresidence, 2 Living alone, 3 Institution
                   1495:   # V1=sex, V2=raedyrs Quant Fixed, State=livarnb4..livarnb11, V3=iadl4..iald11, V4=adlw4..adlw11, V5=r4bmi..r11bmi
                   1496: */
1.319     brouard  1497: /*             V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
                   1498: /*    k        1  2   3   4     5    6    7     8    9 */
                   1499: /*Typevar[k]=  0  0   0   2     1    0    2     1    0 *//*0 for simple covariate (dummy, quantitative,*/
                   1500:                                                          /* fixed or varying), 1 for age product, 2 for*/
                   1501:                                                          /* product */
                   1502: /*Dummy[k]=    1  0   0   1     3    1    1     2    0 *//*Dummy[k] 0=dummy (0 1), 1 quantitative */
                   1503:                                                          /*(single or product without age), 2 dummy*/
                   1504:                                                          /* with age product, 3 quant with age product*/
                   1505: /*Tvar[k]=     5  4   3   6     5    2    7     1    1 */
                   1506: /*    nsd         1   2                              3 */ /* Counting single dummies covar fixed or tv */
1.330     brouard  1507: /*TnsdVar[Tvar]   1   2                              3 */ 
1.319     brouard  1508: /*TvarsD[nsd]     4   3                              1 */ /* ID of single dummy cova fixed or timevary*/
                   1509: /*TvarsDind[k]    2   3                              9 */ /* position K of single dummy cova */
                   1510: /*    nsq      1                     2                 */ /* Counting single quantit tv */
                   1511: /* TvarsQ[k]   5                     2                 */ /* Number of single quantitative cova */
                   1512: /* TvarsQind   1                     6                 */ /* position K of single quantitative cova */
                   1513: /* Tprod[i]=k             1               2            */ /* Position in model of the ith prod without age */
                   1514: /* cptcovage                    1               2      */ /* Counting cov*age in the model equation */
                   1515: /* Tage[cptcovage]=k            5               8      */ /* Position in the model of ith cov*age */
                   1516: /* Tvard[1][1]@4={4,3,1,2}    V4*V3 V1*V2              */ /* Position in model of the ith prod without age */
1.330     brouard  1517: /* 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  1518: /* 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  1519: /* TvarFind;  TvarFind[1]=6,  TvarFind[2]=7, TvarFind[3]=9 *//* Inverse V2(6) is first fixed (single or prod)  */
1.234     brouard  1520: /* Type                    */
                   1521: /* V         1  2  3  4  5 */
                   1522: /*           F  F  V  V  V */
                   1523: /*           D  Q  D  D  Q */
                   1524: /*                         */
                   1525: int *TvarsD;
1.330     brouard  1526: int *TnsdVar;
1.234     brouard  1527: int *TvarsDind;
                   1528: int *TvarsQ;
                   1529: int *TvarsQind;
                   1530: 
1.318     brouard  1531: #define MAXRESULTLINESPONE 10+1
1.235     brouard  1532: int nresult=0;
1.258     brouard  1533: int parameterline=0; /* # of the parameter (type) line */
1.334     brouard  1534: int TKresult[MAXRESULTLINESPONE]; /* TKresult[nres]=k for each resultline nres give the corresponding combination of dummies */
                   1535: int resultmodel[MAXRESULTLINESPONE][NCOVMAX];/* resultmodel[k1]=k3: k1th position in the model corresponds to the k3 position in the resultline */
                   1536: int modelresult[MAXRESULTLINESPONE][NCOVMAX];/* modelresult[k3]=k1: k1th position in the model corresponds to the k3 position in the resultline */
                   1537: int Tresult[MAXRESULTLINESPONE][NCOVMAX];/* Tresult[nres][result_position]= value of the dummy variable at the result_position in the nres resultline */
1.332     brouard  1538: int Tinvresult[MAXRESULTLINESPONE][NCOVMAX];/* Tinvresult[nres][Name of a dummy variable]= value of the variable in the result line  */
                   1539: double TinvDoQresult[MAXRESULTLINESPONE][NCOVMAX];/* TinvDoQresult[nres][Name of a Dummy or Q variable]= value of the variable in the result line */
1.334     brouard  1540: int Tvresult[MAXRESULTLINESPONE][NCOVMAX]; /* Tvresult[nres][result_position]= name of the dummy variable at the result_position in the nres resultline */
1.332     brouard  1541: double Tqresult[MAXRESULTLINESPONE][NCOVMAX]; /* Tqresult[nres][result_position]= value of the variable at the result_position in the nres resultline */
1.318     brouard  1542: double Tqinvresult[MAXRESULTLINESPONE][NCOVMAX]; /* For quantitative variable , value (output) */
1.332     brouard  1543: int Tvqresult[MAXRESULTLINESPONE][NCOVMAX]; /* Tvqresult[nres][result_position]= id of the variable at the result_position in the nres resultline */
1.318     brouard  1544: 
                   1545: /* 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
                   1546:   # States 1=Coresidence, 2 Living alone, 3 Institution
                   1547:   # V1=sex, V2=raedyrs Quant Fixed, State=livarnb4..livarnb11, V3=iadl4..iald11, V4=adlw4..adlw11, V5=r4bmi..r11bmi
                   1548: */
1.234     brouard  1549: /* 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  1550: 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 */
                   1551: 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 */
                   1552: 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 */
                   1553: int *TvarVind; /**< TvarVind[1]=1, TvarVind[2]=2  in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
                   1554: 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 */
                   1555: 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  1556: int *TvarFD; /**< TvarFD[1]=V1 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
                   1557: int *TvarFDind; /* TvarFDind[1]=9 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
                   1558: int *TvarFQ; /* TvarFQ[1]=V2 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */ /* Only simple fixed quantitative variable */
                   1559: int *TvarFQind; /* TvarFQind[1]=6 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */ /* Only simple fixed quantitative variable */
                   1560: int *TvarVD; /* TvarVD[1]=V5 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */ /* Only simple fixed quantitative variable */
                   1561: int *TvarVDind; /* TvarVDind[1]=1 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */ /* Only simple fixed quantitative variable */
                   1562: 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 */
                   1563: 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 */
                   1564: 
1.230     brouard  1565: int *Tvarsel; /**< Selected covariates for output */
                   1566: double *Tvalsel; /**< Selected modality value of covariate for output */
1.226     brouard  1567: int *Typevar; /**< 0 for simple covariate (dummy, quantitative, fixed or varying), 1 for age product, 2 for  product */
1.227     brouard  1568: int *Fixed; /** Fixed[k] 0=fixed, 1 varying, 2 fixed with age product, 3 varying with age product */ 
                   1569: 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  1570: int *DummyV; /** Dummy[v] 0=dummy (0 1), 1 quantitative */
                   1571: int *FixedV; /** FixedV[v] 0 fixed, 1 varying */
1.197     brouard  1572: int *Tage;
1.227     brouard  1573: int anyvaryingduminmodel=0; /**< Any varying dummy in Model=1 yes, 0 no, to avoid a loop on waves in freq */ 
1.228     brouard  1574: 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  1575: 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*/ 
                   1576: 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  1577: int *Ndum; /** Freq of modality (tricode */
1.200     brouard  1578: /* int **codtab;*/ /**< codtab=imatrix(1,100,1,10); */
1.227     brouard  1579: int **Tvard;
1.330     brouard  1580: int **Tvardk;
1.227     brouard  1581: int *Tprod;/**< Gives the k position of the k1 product */
1.238     brouard  1582: /* Tprod[k1=1]=3(=V1*V4) for V2+V1+V1*V4+age*V3  */
1.227     brouard  1583: int *Tposprod; /**< Gives the k1 product from the k position */
1.238     brouard  1584:    /* if  V2+V1+V1*V4+age*V3+V3*V2   TProd[k1=2]=5 (V3*V2) */
                   1585:    /* Tposprod[k]=k1 , Tposprod[3]=1, Tposprod[5(V3*V2)]=2 (2nd product without age) */
1.227     brouard  1586: int cptcovprod, *Tvaraff, *invalidvarcomb;
1.126     brouard  1587: double *lsurv, *lpop, *tpop;
                   1588: 
1.231     brouard  1589: #define FD 1; /* Fixed dummy covariate */
                   1590: #define FQ 2; /* Fixed quantitative covariate */
                   1591: #define FP 3; /* Fixed product covariate */
                   1592: #define FPDD 7; /* Fixed product dummy*dummy covariate */
                   1593: #define FPDQ 8; /* Fixed product dummy*quantitative covariate */
                   1594: #define FPQQ 9; /* Fixed product quantitative*quantitative covariate */
                   1595: #define VD 10; /* Varying dummy covariate */
                   1596: #define VQ 11; /* Varying quantitative covariate */
                   1597: #define VP 12; /* Varying product covariate */
                   1598: #define VPDD 13; /* Varying product dummy*dummy covariate */
                   1599: #define VPDQ 14; /* Varying product dummy*quantitative covariate */
                   1600: #define VPQQ 15; /* Varying product quantitative*quantitative covariate */
                   1601: #define APFD 16; /* Age product * fixed dummy covariate */
                   1602: #define APFQ 17; /* Age product * fixed quantitative covariate */
                   1603: #define APVD 18; /* Age product * varying dummy covariate */
                   1604: #define APVQ 19; /* Age product * varying quantitative covariate */
                   1605: 
                   1606: #define FTYPE 1; /* Fixed covariate */
                   1607: #define VTYPE 2; /* Varying covariate (loop in wave) */
                   1608: #define ATYPE 2; /* Age product covariate (loop in dh within wave)*/
                   1609: 
                   1610: struct kmodel{
                   1611:        int maintype; /* main type */
                   1612:        int subtype; /* subtype */
                   1613: };
                   1614: struct kmodel modell[NCOVMAX];
                   1615: 
1.143     brouard  1616: double ftol=FTOL; /**< Tolerance for computing Max Likelihood */
                   1617: double ftolhess; /**< Tolerance for computing hessian */
1.126     brouard  1618: 
                   1619: /**************** split *************************/
                   1620: static int split( char *path, char *dirc, char *name, char *ext, char *finame )
                   1621: {
                   1622:   /* From a file name with (full) path (either Unix or Windows) we extract the directory (dirc)
                   1623:      the name of the file (name), its extension only (ext) and its first part of the name (finame)
                   1624:   */ 
                   1625:   char *ss;                            /* pointer */
1.186     brouard  1626:   int  l1=0, l2=0;                             /* length counters */
1.126     brouard  1627: 
                   1628:   l1 = strlen(path );                  /* length of path */
                   1629:   if ( l1 == 0 ) return( GLOCK_ERROR_NOPATH );
                   1630:   ss= strrchr( path, DIRSEPARATOR );           /* find last / */
                   1631:   if ( ss == NULL ) {                  /* no directory, so determine current directory */
                   1632:     strcpy( name, path );              /* we got the fullname name because no directory */
                   1633:     /*if(strrchr(path, ODIRSEPARATOR )==NULL)
                   1634:       printf("Warning you should use %s as a separator\n",DIRSEPARATOR);*/
                   1635:     /* get current working directory */
                   1636:     /*    extern  char* getcwd ( char *buf , int len);*/
1.184     brouard  1637: #ifdef WIN32
                   1638:     if (_getcwd( dirc, FILENAME_MAX ) == NULL ) {
                   1639: #else
                   1640:        if (getcwd(dirc, FILENAME_MAX) == NULL) {
                   1641: #endif
1.126     brouard  1642:       return( GLOCK_ERROR_GETCWD );
                   1643:     }
                   1644:     /* got dirc from getcwd*/
                   1645:     printf(" DIRC = %s \n",dirc);
1.205     brouard  1646:   } else {                             /* strip directory from path */
1.126     brouard  1647:     ss++;                              /* after this, the filename */
                   1648:     l2 = strlen( ss );                 /* length of filename */
                   1649:     if ( l2 == 0 ) return( GLOCK_ERROR_NOPATH );
                   1650:     strcpy( name, ss );                /* save file name */
                   1651:     strncpy( dirc, path, l1 - l2 );    /* now the directory */
1.186     brouard  1652:     dirc[l1-l2] = '\0';                        /* add zero */
1.126     brouard  1653:     printf(" DIRC2 = %s \n",dirc);
                   1654:   }
                   1655:   /* We add a separator at the end of dirc if not exists */
                   1656:   l1 = strlen( dirc );                 /* length of directory */
                   1657:   if( dirc[l1-1] != DIRSEPARATOR ){
                   1658:     dirc[l1] =  DIRSEPARATOR;
                   1659:     dirc[l1+1] = 0; 
                   1660:     printf(" DIRC3 = %s \n",dirc);
                   1661:   }
                   1662:   ss = strrchr( name, '.' );           /* find last / */
                   1663:   if (ss >0){
                   1664:     ss++;
                   1665:     strcpy(ext,ss);                    /* save extension */
                   1666:     l1= strlen( name);
                   1667:     l2= strlen(ss)+1;
                   1668:     strncpy( finame, name, l1-l2);
                   1669:     finame[l1-l2]= 0;
                   1670:   }
                   1671: 
                   1672:   return( 0 );                         /* we're done */
                   1673: }
                   1674: 
                   1675: 
                   1676: /******************************************/
                   1677: 
                   1678: void replace_back_to_slash(char *s, char*t)
                   1679: {
                   1680:   int i;
                   1681:   int lg=0;
                   1682:   i=0;
                   1683:   lg=strlen(t);
                   1684:   for(i=0; i<= lg; i++) {
                   1685:     (s[i] = t[i]);
                   1686:     if (t[i]== '\\') s[i]='/';
                   1687:   }
                   1688: }
                   1689: 
1.132     brouard  1690: char *trimbb(char *out, char *in)
1.137     brouard  1691: { /* Trim multiple blanks in line but keeps first blanks if line starts with blanks */
1.132     brouard  1692:   char *s;
                   1693:   s=out;
                   1694:   while (*in != '\0'){
1.137     brouard  1695:     while( *in == ' ' && *(in+1) == ' '){ /* && *(in+1) != '\0'){*/
1.132     brouard  1696:       in++;
                   1697:     }
                   1698:     *out++ = *in++;
                   1699:   }
                   1700:   *out='\0';
                   1701:   return s;
                   1702: }
                   1703: 
1.187     brouard  1704: /* char *substrchaine(char *out, char *in, char *chain) */
                   1705: /* { */
                   1706: /*   /\* Substract chain 'chain' from 'in', return and output 'out' *\/ */
                   1707: /*   char *s, *t; */
                   1708: /*   t=in;s=out; */
                   1709: /*   while ((*in != *chain) && (*in != '\0')){ */
                   1710: /*     *out++ = *in++; */
                   1711: /*   } */
                   1712: 
                   1713: /*   /\* *in matches *chain *\/ */
                   1714: /*   while ((*in++ == *chain++) && (*in != '\0')){ */
                   1715: /*     printf("*in = %c, *out= %c *chain= %c \n", *in, *out, *chain);  */
                   1716: /*   } */
                   1717: /*   in--; chain--; */
                   1718: /*   while ( (*in != '\0')){ */
                   1719: /*     printf("Bef *in = %c, *out= %c *chain= %c \n", *in, *out, *chain);  */
                   1720: /*     *out++ = *in++; */
                   1721: /*     printf("Aft *in = %c, *out= %c *chain= %c \n", *in, *out, *chain);  */
                   1722: /*   } */
                   1723: /*   *out='\0'; */
                   1724: /*   out=s; */
                   1725: /*   return out; */
                   1726: /* } */
                   1727: char *substrchaine(char *out, char *in, char *chain)
                   1728: {
                   1729:   /* Substract chain 'chain' from 'in', return and output 'out' */
                   1730:   /* in="V1+V1*age+age*age+V2", chain="age*age" */
                   1731: 
                   1732:   char *strloc;
                   1733: 
                   1734:   strcpy (out, in); 
                   1735:   strloc = strstr(out, chain); /* strloc points to out at age*age+V2 */
                   1736:   printf("Bef strloc=%s chain=%s out=%s \n", strloc, chain, out);
                   1737:   if(strloc != NULL){ 
                   1738:     /* will affect out */ /* strloc+strlenc(chain)=+V2 */ /* Will also work in Unicode */
                   1739:     memmove(strloc,strloc+strlen(chain), strlen(strloc+strlen(chain))+1);
                   1740:     /* strcpy (strloc, strloc +strlen(chain));*/
                   1741:   }
                   1742:   printf("Aft strloc=%s chain=%s in=%s out=%s \n", strloc, chain, in, out);
                   1743:   return out;
                   1744: }
                   1745: 
                   1746: 
1.145     brouard  1747: char *cutl(char *blocc, char *alocc, char *in, char occ)
                   1748: {
1.187     brouard  1749:   /* cuts string in into blocc and alocc where blocc ends before FIRST occurence of char 'occ' 
1.145     brouard  1750:      and alocc starts after first occurence of char 'occ' : ex cutv(blocc,alocc,"abcdef2ghi2j",'2')
1.310     brouard  1751:      gives alocc="abcdef" and blocc="ghi2j".
1.145     brouard  1752:      If occ is not found blocc is null and alocc is equal to in. Returns blocc
                   1753:   */
1.160     brouard  1754:   char *s, *t;
1.145     brouard  1755:   t=in;s=in;
                   1756:   while ((*in != occ) && (*in != '\0')){
                   1757:     *alocc++ = *in++;
                   1758:   }
                   1759:   if( *in == occ){
                   1760:     *(alocc)='\0';
                   1761:     s=++in;
                   1762:   }
                   1763:  
                   1764:   if (s == t) {/* occ not found */
                   1765:     *(alocc-(in-s))='\0';
                   1766:     in=s;
                   1767:   }
                   1768:   while ( *in != '\0'){
                   1769:     *blocc++ = *in++;
                   1770:   }
                   1771: 
                   1772:   *blocc='\0';
                   1773:   return t;
                   1774: }
1.137     brouard  1775: char *cutv(char *blocc, char *alocc, char *in, char occ)
                   1776: {
1.187     brouard  1777:   /* cuts string in into blocc and alocc where blocc ends before LAST occurence of char 'occ' 
1.137     brouard  1778:      and alocc starts after last occurence of char 'occ' : ex cutv(blocc,alocc,"abcdef2ghi2j",'2')
                   1779:      gives blocc="abcdef2ghi" and alocc="j".
                   1780:      If occ is not found blocc is null and alocc is equal to in. Returns alocc
                   1781:   */
                   1782:   char *s, *t;
                   1783:   t=in;s=in;
                   1784:   while (*in != '\0'){
                   1785:     while( *in == occ){
                   1786:       *blocc++ = *in++;
                   1787:       s=in;
                   1788:     }
                   1789:     *blocc++ = *in++;
                   1790:   }
                   1791:   if (s == t) /* occ not found */
                   1792:     *(blocc-(in-s))='\0';
                   1793:   else
                   1794:     *(blocc-(in-s)-1)='\0';
                   1795:   in=s;
                   1796:   while ( *in != '\0'){
                   1797:     *alocc++ = *in++;
                   1798:   }
                   1799: 
                   1800:   *alocc='\0';
                   1801:   return s;
                   1802: }
                   1803: 
1.126     brouard  1804: int nbocc(char *s, char occ)
                   1805: {
                   1806:   int i,j=0;
                   1807:   int lg=20;
                   1808:   i=0;
                   1809:   lg=strlen(s);
                   1810:   for(i=0; i<= lg; i++) {
1.234     brouard  1811:     if  (s[i] == occ ) j++;
1.126     brouard  1812:   }
                   1813:   return j;
                   1814: }
                   1815: 
1.137     brouard  1816: /* void cutv(char *u,char *v, char*t, char occ) */
                   1817: /* { */
                   1818: /*   /\* cuts string t into u and v where u ends before last occurence of char 'occ'  */
                   1819: /*      and v starts after last occurence of char 'occ' : ex cutv(u,v,"abcdef2ghi2j",'2') */
                   1820: /*      gives u="abcdef2ghi" and v="j" *\/ */
                   1821: /*   int i,lg,j,p=0; */
                   1822: /*   i=0; */
                   1823: /*   lg=strlen(t); */
                   1824: /*   for(j=0; j<=lg-1; j++) { */
                   1825: /*     if((t[j]!= occ) && (t[j+1]== occ)) p=j+1; */
                   1826: /*   } */
1.126     brouard  1827: 
1.137     brouard  1828: /*   for(j=0; j<p; j++) { */
                   1829: /*     (u[j] = t[j]); */
                   1830: /*   } */
                   1831: /*      u[p]='\0'; */
1.126     brouard  1832: 
1.137     brouard  1833: /*    for(j=0; j<= lg; j++) { */
                   1834: /*     if (j>=(p+1))(v[j-p-1] = t[j]); */
                   1835: /*   } */
                   1836: /* } */
1.126     brouard  1837: 
1.160     brouard  1838: #ifdef _WIN32
                   1839: char * strsep(char **pp, const char *delim)
                   1840: {
                   1841:   char *p, *q;
                   1842:          
                   1843:   if ((p = *pp) == NULL)
                   1844:     return 0;
                   1845:   if ((q = strpbrk (p, delim)) != NULL)
                   1846:   {
                   1847:     *pp = q + 1;
                   1848:     *q = '\0';
                   1849:   }
                   1850:   else
                   1851:     *pp = 0;
                   1852:   return p;
                   1853: }
                   1854: #endif
                   1855: 
1.126     brouard  1856: /********************** nrerror ********************/
                   1857: 
                   1858: void nrerror(char error_text[])
                   1859: {
                   1860:   fprintf(stderr,"ERREUR ...\n");
                   1861:   fprintf(stderr,"%s\n",error_text);
                   1862:   exit(EXIT_FAILURE);
                   1863: }
                   1864: /*********************** vector *******************/
                   1865: double *vector(int nl, int nh)
                   1866: {
                   1867:   double *v;
                   1868:   v=(double *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(double)));
                   1869:   if (!v) nrerror("allocation failure in vector");
                   1870:   return v-nl+NR_END;
                   1871: }
                   1872: 
                   1873: /************************ free vector ******************/
                   1874: void free_vector(double*v, int nl, int nh)
                   1875: {
                   1876:   free((FREE_ARG)(v+nl-NR_END));
                   1877: }
                   1878: 
                   1879: /************************ivector *******************************/
                   1880: int *ivector(long nl,long nh)
                   1881: {
                   1882:   int *v;
                   1883:   v=(int *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(int)));
                   1884:   if (!v) nrerror("allocation failure in ivector");
                   1885:   return v-nl+NR_END;
                   1886: }
                   1887: 
                   1888: /******************free ivector **************************/
                   1889: void free_ivector(int *v, long nl, long nh)
                   1890: {
                   1891:   free((FREE_ARG)(v+nl-NR_END));
                   1892: }
                   1893: 
                   1894: /************************lvector *******************************/
                   1895: long *lvector(long nl,long nh)
                   1896: {
                   1897:   long *v;
                   1898:   v=(long *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(long)));
                   1899:   if (!v) nrerror("allocation failure in ivector");
                   1900:   return v-nl+NR_END;
                   1901: }
                   1902: 
                   1903: /******************free lvector **************************/
                   1904: void free_lvector(long *v, long nl, long nh)
                   1905: {
                   1906:   free((FREE_ARG)(v+nl-NR_END));
                   1907: }
                   1908: 
                   1909: /******************* imatrix *******************************/
                   1910: int **imatrix(long nrl, long nrh, long ncl, long nch) 
                   1911:      /* allocate a int matrix with subscript range m[nrl..nrh][ncl..nch] */ 
                   1912: { 
                   1913:   long i, nrow=nrh-nrl+1,ncol=nch-ncl+1; 
                   1914:   int **m; 
                   1915:   
                   1916:   /* allocate pointers to rows */ 
                   1917:   m=(int **) malloc((size_t)((nrow+NR_END)*sizeof(int*))); 
                   1918:   if (!m) nrerror("allocation failure 1 in matrix()"); 
                   1919:   m += NR_END; 
                   1920:   m -= nrl; 
                   1921:   
                   1922:   
                   1923:   /* allocate rows and set pointers to them */ 
                   1924:   m[nrl]=(int *) malloc((size_t)((nrow*ncol+NR_END)*sizeof(int))); 
                   1925:   if (!m[nrl]) nrerror("allocation failure 2 in matrix()"); 
                   1926:   m[nrl] += NR_END; 
                   1927:   m[nrl] -= ncl; 
                   1928:   
                   1929:   for(i=nrl+1;i<=nrh;i++) m[i]=m[i-1]+ncol; 
                   1930:   
                   1931:   /* return pointer to array of pointers to rows */ 
                   1932:   return m; 
                   1933: } 
                   1934: 
                   1935: /****************** free_imatrix *************************/
                   1936: void free_imatrix(m,nrl,nrh,ncl,nch)
                   1937:       int **m;
                   1938:       long nch,ncl,nrh,nrl; 
                   1939:      /* free an int matrix allocated by imatrix() */ 
                   1940: { 
                   1941:   free((FREE_ARG) (m[nrl]+ncl-NR_END)); 
                   1942:   free((FREE_ARG) (m+nrl-NR_END)); 
                   1943: } 
                   1944: 
                   1945: /******************* matrix *******************************/
                   1946: double **matrix(long nrl, long nrh, long ncl, long nch)
                   1947: {
                   1948:   long i, nrow=nrh-nrl+1, ncol=nch-ncl+1;
                   1949:   double **m;
                   1950: 
                   1951:   m=(double **) malloc((size_t)((nrow+NR_END)*sizeof(double*)));
                   1952:   if (!m) nrerror("allocation failure 1 in matrix()");
                   1953:   m += NR_END;
                   1954:   m -= nrl;
                   1955: 
                   1956:   m[nrl]=(double *) malloc((size_t)((nrow*ncol+NR_END)*sizeof(double)));
                   1957:   if (!m[nrl]) nrerror("allocation failure 2 in matrix()");
                   1958:   m[nrl] += NR_END;
                   1959:   m[nrl] -= ncl;
                   1960: 
                   1961:   for (i=nrl+1; i<=nrh; i++) m[i]=m[i-1]+ncol;
                   1962:   return m;
1.145     brouard  1963:   /* print *(*(m+1)+70) or print m[1][70]; print m+1 or print &(m[1]) or &(m[1][0])
                   1964: m[i] = address of ith row of the table. &(m[i]) is its value which is another adress
                   1965: that of m[i][0]. In order to get the value p m[i][0] but it is unitialized.
1.126     brouard  1966:    */
                   1967: }
                   1968: 
                   1969: /*************************free matrix ************************/
                   1970: void free_matrix(double **m, long nrl, long nrh, long ncl, long nch)
                   1971: {
                   1972:   free((FREE_ARG)(m[nrl]+ncl-NR_END));
                   1973:   free((FREE_ARG)(m+nrl-NR_END));
                   1974: }
                   1975: 
                   1976: /******************* ma3x *******************************/
                   1977: double ***ma3x(long nrl, long nrh, long ncl, long nch, long nll, long nlh)
                   1978: {
                   1979:   long i, j, nrow=nrh-nrl+1, ncol=nch-ncl+1, nlay=nlh-nll+1;
                   1980:   double ***m;
                   1981: 
                   1982:   m=(double ***) malloc((size_t)((nrow+NR_END)*sizeof(double*)));
                   1983:   if (!m) nrerror("allocation failure 1 in matrix()");
                   1984:   m += NR_END;
                   1985:   m -= nrl;
                   1986: 
                   1987:   m[nrl]=(double **) malloc((size_t)((nrow*ncol+NR_END)*sizeof(double)));
                   1988:   if (!m[nrl]) nrerror("allocation failure 2 in matrix()");
                   1989:   m[nrl] += NR_END;
                   1990:   m[nrl] -= ncl;
                   1991: 
                   1992:   for (i=nrl+1; i<=nrh; i++) m[i]=m[i-1]+ncol;
                   1993: 
                   1994:   m[nrl][ncl]=(double *) malloc((size_t)((nrow*ncol*nlay+NR_END)*sizeof(double)));
                   1995:   if (!m[nrl][ncl]) nrerror("allocation failure 3 in matrix()");
                   1996:   m[nrl][ncl] += NR_END;
                   1997:   m[nrl][ncl] -= nll;
                   1998:   for (j=ncl+1; j<=nch; j++) 
                   1999:     m[nrl][j]=m[nrl][j-1]+nlay;
                   2000:   
                   2001:   for (i=nrl+1; i<=nrh; i++) {
                   2002:     m[i][ncl]=m[i-1l][ncl]+ncol*nlay;
                   2003:     for (j=ncl+1; j<=nch; j++) 
                   2004:       m[i][j]=m[i][j-1]+nlay;
                   2005:   }
                   2006:   return m; 
                   2007:   /*  gdb: p *(m+1) <=> p m[1] and p (m+1) <=> p (m+1) <=> p &(m[1])
                   2008:            &(m[i][j][k]) <=> *((*(m+i) + j)+k)
                   2009:   */
                   2010: }
                   2011: 
                   2012: /*************************free ma3x ************************/
                   2013: void free_ma3x(double ***m, long nrl, long nrh, long ncl, long nch,long nll, long nlh)
                   2014: {
                   2015:   free((FREE_ARG)(m[nrl][ncl]+ nll-NR_END));
                   2016:   free((FREE_ARG)(m[nrl]+ncl-NR_END));
                   2017:   free((FREE_ARG)(m+nrl-NR_END));
                   2018: }
                   2019: 
                   2020: /*************** function subdirf ***********/
                   2021: char *subdirf(char fileres[])
                   2022: {
                   2023:   /* Caution optionfilefiname is hidden */
                   2024:   strcpy(tmpout,optionfilefiname);
                   2025:   strcat(tmpout,"/"); /* Add to the right */
                   2026:   strcat(tmpout,fileres);
                   2027:   return tmpout;
                   2028: }
                   2029: 
                   2030: /*************** function subdirf2 ***********/
                   2031: char *subdirf2(char fileres[], char *preop)
                   2032: {
1.314     brouard  2033:   /* Example subdirf2(optionfilefiname,"FB_") with optionfilefiname="texte", result="texte/FB_texte"
                   2034:  Errors in subdirf, 2, 3 while printing tmpout is
1.315     brouard  2035:  rewritten within the same printf. Workaround: many printfs */
1.126     brouard  2036:   /* Caution optionfilefiname is hidden */
                   2037:   strcpy(tmpout,optionfilefiname);
                   2038:   strcat(tmpout,"/");
                   2039:   strcat(tmpout,preop);
                   2040:   strcat(tmpout,fileres);
                   2041:   return tmpout;
                   2042: }
                   2043: 
                   2044: /*************** function subdirf3 ***********/
                   2045: char *subdirf3(char fileres[], char *preop, char *preop2)
                   2046: {
                   2047:   
                   2048:   /* Caution optionfilefiname is hidden */
                   2049:   strcpy(tmpout,optionfilefiname);
                   2050:   strcat(tmpout,"/");
                   2051:   strcat(tmpout,preop);
                   2052:   strcat(tmpout,preop2);
                   2053:   strcat(tmpout,fileres);
                   2054:   return tmpout;
                   2055: }
1.213     brouard  2056:  
                   2057: /*************** function subdirfext ***********/
                   2058: char *subdirfext(char fileres[], char *preop, char *postop)
                   2059: {
                   2060:   
                   2061:   strcpy(tmpout,preop);
                   2062:   strcat(tmpout,fileres);
                   2063:   strcat(tmpout,postop);
                   2064:   return tmpout;
                   2065: }
1.126     brouard  2066: 
1.213     brouard  2067: /*************** function subdirfext3 ***********/
                   2068: char *subdirfext3(char fileres[], char *preop, char *postop)
                   2069: {
                   2070:   
                   2071:   /* Caution optionfilefiname is hidden */
                   2072:   strcpy(tmpout,optionfilefiname);
                   2073:   strcat(tmpout,"/");
                   2074:   strcat(tmpout,preop);
                   2075:   strcat(tmpout,fileres);
                   2076:   strcat(tmpout,postop);
                   2077:   return tmpout;
                   2078: }
                   2079:  
1.162     brouard  2080: char *asc_diff_time(long time_sec, char ascdiff[])
                   2081: {
                   2082:   long sec_left, days, hours, minutes;
                   2083:   days = (time_sec) / (60*60*24);
                   2084:   sec_left = (time_sec) % (60*60*24);
                   2085:   hours = (sec_left) / (60*60) ;
                   2086:   sec_left = (sec_left) %(60*60);
                   2087:   minutes = (sec_left) /60;
                   2088:   sec_left = (sec_left) % (60);
                   2089:   sprintf(ascdiff,"%ld day(s) %ld hour(s) %ld minute(s) %ld second(s)",days, hours, minutes, sec_left);  
                   2090:   return ascdiff;
                   2091: }
                   2092: 
1.126     brouard  2093: /***************** f1dim *************************/
                   2094: extern int ncom; 
                   2095: extern double *pcom,*xicom;
                   2096: extern double (*nrfunc)(double []); 
                   2097:  
                   2098: double f1dim(double x) 
                   2099: { 
                   2100:   int j; 
                   2101:   double f;
                   2102:   double *xt; 
                   2103:  
                   2104:   xt=vector(1,ncom); 
                   2105:   for (j=1;j<=ncom;j++) xt[j]=pcom[j]+x*xicom[j]; 
                   2106:   f=(*nrfunc)(xt); 
                   2107:   free_vector(xt,1,ncom); 
                   2108:   return f; 
                   2109: } 
                   2110: 
                   2111: /*****************brent *************************/
                   2112: double brent(double ax, double bx, double cx, double (*f)(double), double tol,         double *xmin) 
1.187     brouard  2113: {
                   2114:   /* Given a function f, and given a bracketing triplet of abscissas ax, bx, cx (such that bx is
                   2115:    * between ax and cx, and f(bx) is less than both f(ax) and f(cx) ), this routine isolates
                   2116:    * the minimum to a fractional precision of about tol using Brent’s method. The abscissa of
                   2117:    * the minimum is returned as xmin, and the minimum function value is returned as brent , the
                   2118:    * returned function value. 
                   2119:   */
1.126     brouard  2120:   int iter; 
                   2121:   double a,b,d,etemp;
1.159     brouard  2122:   double fu=0,fv,fw,fx;
1.164     brouard  2123:   double ftemp=0.;
1.126     brouard  2124:   double p,q,r,tol1,tol2,u,v,w,x,xm; 
                   2125:   double e=0.0; 
                   2126:  
                   2127:   a=(ax < cx ? ax : cx); 
                   2128:   b=(ax > cx ? ax : cx); 
                   2129:   x=w=v=bx; 
                   2130:   fw=fv=fx=(*f)(x); 
                   2131:   for (iter=1;iter<=ITMAX;iter++) { 
                   2132:     xm=0.5*(a+b); 
                   2133:     tol2=2.0*(tol1=tol*fabs(x)+ZEPS); 
                   2134:     /*         if (2.0*fabs(fp-(*fret)) <= ftol*(fabs(fp)+fabs(*fret)))*/
                   2135:     printf(".");fflush(stdout);
                   2136:     fprintf(ficlog,".");fflush(ficlog);
1.162     brouard  2137: #ifdef DEBUGBRENT
1.126     brouard  2138:     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);
                   2139:     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);
                   2140:     /*         if ((fabs(x-xm) <= (tol2-0.5*(b-a)))||(2.0*fabs(fu-ftemp) <= ftol*1.e-2*(fabs(fu)+fabs(ftemp)))) { */
                   2141: #endif
                   2142:     if (fabs(x-xm) <= (tol2-0.5*(b-a))){ 
                   2143:       *xmin=x; 
                   2144:       return fx; 
                   2145:     } 
                   2146:     ftemp=fu;
                   2147:     if (fabs(e) > tol1) { 
                   2148:       r=(x-w)*(fx-fv); 
                   2149:       q=(x-v)*(fx-fw); 
                   2150:       p=(x-v)*q-(x-w)*r; 
                   2151:       q=2.0*(q-r); 
                   2152:       if (q > 0.0) p = -p; 
                   2153:       q=fabs(q); 
                   2154:       etemp=e; 
                   2155:       e=d; 
                   2156:       if (fabs(p) >= fabs(0.5*q*etemp) || p <= q*(a-x) || p >= q*(b-x)) 
1.224     brouard  2157:                                d=CGOLD*(e=(x >= xm ? a-x : b-x)); 
1.126     brouard  2158:       else { 
1.224     brouard  2159:                                d=p/q; 
                   2160:                                u=x+d; 
                   2161:                                if (u-a < tol2 || b-u < tol2) 
                   2162:                                        d=SIGN(tol1,xm-x); 
1.126     brouard  2163:       } 
                   2164:     } else { 
                   2165:       d=CGOLD*(e=(x >= xm ? a-x : b-x)); 
                   2166:     } 
                   2167:     u=(fabs(d) >= tol1 ? x+d : x+SIGN(tol1,d)); 
                   2168:     fu=(*f)(u); 
                   2169:     if (fu <= fx) { 
                   2170:       if (u >= x) a=x; else b=x; 
                   2171:       SHFT(v,w,x,u) 
1.183     brouard  2172:       SHFT(fv,fw,fx,fu) 
                   2173:     } else { 
                   2174:       if (u < x) a=u; else b=u; 
                   2175:       if (fu <= fw || w == x) { 
1.224     brouard  2176:                                v=w; 
                   2177:                                w=u; 
                   2178:                                fv=fw; 
                   2179:                                fw=fu; 
1.183     brouard  2180:       } else if (fu <= fv || v == x || v == w) { 
1.224     brouard  2181:                                v=u; 
                   2182:                                fv=fu; 
1.183     brouard  2183:       } 
                   2184:     } 
1.126     brouard  2185:   } 
                   2186:   nrerror("Too many iterations in brent"); 
                   2187:   *xmin=x; 
                   2188:   return fx; 
                   2189: } 
                   2190: 
                   2191: /****************** mnbrak ***********************/
                   2192: 
                   2193: void mnbrak(double *ax, double *bx, double *cx, double *fa, double *fb, double *fc, 
                   2194:            double (*func)(double)) 
1.183     brouard  2195: { /* Given a function func , and given distinct initial points ax and bx , this routine searches in
                   2196: the downhill direction (defined by the function as evaluated at the initial points) and returns
                   2197: new points ax , bx , cx that bracket a minimum of the function. Also returned are the function
                   2198: values at the three points, fa, fb , and fc such that fa > fb and fb < fc.
                   2199:    */
1.126     brouard  2200:   double ulim,u,r,q, dum;
                   2201:   double fu; 
1.187     brouard  2202: 
                   2203:   double scale=10.;
                   2204:   int iterscale=0;
                   2205: 
                   2206:   *fa=(*func)(*ax); /*  xta[j]=pcom[j]+(*ax)*xicom[j]; fa=f(xta[j])*/
                   2207:   *fb=(*func)(*bx); /*  xtb[j]=pcom[j]+(*bx)*xicom[j]; fb=f(xtb[j]) */
                   2208: 
                   2209: 
                   2210:   /* while(*fb != *fb){ /\* *ax should be ok, reducing distance to *ax *\/ */
                   2211:   /*   printf("Warning mnbrak *fb = %lf, *bx=%lf *ax=%lf *fa==%lf iter=%d\n",*fb, *bx, *ax, *fa, iterscale++); */
                   2212:   /*   *bx = *ax - (*ax - *bx)/scale; */
                   2213:   /*   *fb=(*func)(*bx);  /\*  xtb[j]=pcom[j]+(*bx)*xicom[j]; fb=f(xtb[j]) *\/ */
                   2214:   /* } */
                   2215: 
1.126     brouard  2216:   if (*fb > *fa) { 
                   2217:     SHFT(dum,*ax,*bx,dum) 
1.183     brouard  2218:     SHFT(dum,*fb,*fa,dum) 
                   2219:   } 
1.126     brouard  2220:   *cx=(*bx)+GOLD*(*bx-*ax); 
                   2221:   *fc=(*func)(*cx); 
1.183     brouard  2222: #ifdef DEBUG
1.224     brouard  2223:   printf("mnbrak0 a=%lf *fa=%lf, b=%lf *fb=%lf, c=%lf *fc=%lf\n",*ax,*fa,*bx,*fb,*cx, *fc);
                   2224:   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  2225: #endif
1.224     brouard  2226:   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  2227:     r=(*bx-*ax)*(*fb-*fc); 
1.224     brouard  2228:     q=(*bx-*cx)*(*fb-*fa); /* What if fa=inf */
1.126     brouard  2229:     u=(*bx)-((*bx-*cx)*q-(*bx-*ax)*r)/ 
1.183     brouard  2230:       (2.0*SIGN(FMAX(fabs(q-r),TINY),q-r)); /* Minimum abscissa of a parabolic estimated from (a,fa), (b,fb) and (c,fc). */
                   2231:     ulim=(*bx)+GLIMIT*(*cx-*bx); /* Maximum abscissa where function should be evaluated */
                   2232:     if ((*bx-u)*(u-*cx) > 0.0) { /* if u_p is between b and c */
1.126     brouard  2233:       fu=(*func)(u); 
1.163     brouard  2234: #ifdef DEBUG
                   2235:       /* f(x)=A(x-u)**2+f(u) */
                   2236:       double A, fparabu; 
                   2237:       A= (*fb - *fa)/(*bx-*ax)/(*bx+*ax-2*u);
                   2238:       fparabu= *fa - A*(*ax-u)*(*ax-u);
1.224     brouard  2239:       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);
                   2240:       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  2241:       /* And thus,it can be that fu > *fc even if fparabu < *fc */
                   2242:       /* mnbrak (*ax=7.666299858533, *fa=299039.693133272231), (*bx=8.595447774979, *fb=298976.598289369489),
                   2243:         (*cx=10.098840694817, *fc=298946.631474258087),  (*u=9.852501168332, fu=298948.773013752128, fparabu=298945.434711494134) */
                   2244:       /* In that case, there is no bracket in the output! Routine is wrong with many consequences.*/
1.163     brouard  2245: #endif 
1.184     brouard  2246: #ifdef MNBRAKORIGINAL
1.183     brouard  2247: #else
1.191     brouard  2248: /*       if (fu > *fc) { */
                   2249: /* #ifdef DEBUG */
                   2250: /*       printf("mnbrak4  fu > fc \n"); */
                   2251: /*       fprintf(ficlog, "mnbrak4 fu > fc\n"); */
                   2252: /* #endif */
                   2253: /*     /\* 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 *\\/  *\/ */
                   2254: /*     /\* SHFT(*fa,*fc,fu,*fc) /\\* (b, u, c) is a bracket while test fb > fc will be fu > fc  will exit *\\/ *\/ */
                   2255: /*     dum=u; /\* Shifting c and u *\/ */
                   2256: /*     u = *cx; */
                   2257: /*     *cx = dum; */
                   2258: /*     dum = fu; */
                   2259: /*     fu = *fc; */
                   2260: /*     *fc =dum; */
                   2261: /*       } else { /\* end *\/ */
                   2262: /* #ifdef DEBUG */
                   2263: /*       printf("mnbrak3  fu < fc \n"); */
                   2264: /*       fprintf(ficlog, "mnbrak3 fu < fc\n"); */
                   2265: /* #endif */
                   2266: /*     dum=u; /\* Shifting c and u *\/ */
                   2267: /*     u = *cx; */
                   2268: /*     *cx = dum; */
                   2269: /*     dum = fu; */
                   2270: /*     fu = *fc; */
                   2271: /*     *fc =dum; */
                   2272: /*       } */
1.224     brouard  2273: #ifdef DEBUGMNBRAK
                   2274:                 double A, fparabu; 
                   2275:      A= (*fb - *fa)/(*bx-*ax)/(*bx+*ax-2*u);
                   2276:      fparabu= *fa - A*(*ax-u)*(*ax-u);
                   2277:      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);
                   2278:      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  2279: #endif
1.191     brouard  2280:       dum=u; /* Shifting c and u */
                   2281:       u = *cx;
                   2282:       *cx = dum;
                   2283:       dum = fu;
                   2284:       fu = *fc;
                   2285:       *fc =dum;
1.183     brouard  2286: #endif
1.162     brouard  2287:     } else if ((*cx-u)*(u-ulim) > 0.0) { /* u is after c but before ulim */
1.183     brouard  2288: #ifdef DEBUG
1.224     brouard  2289:       printf("\nmnbrak2  u=%lf after c=%lf but before ulim\n",u,*cx);
                   2290:       fprintf(ficlog,"\nmnbrak2  u=%lf after c=%lf but before ulim\n",u,*cx);
1.183     brouard  2291: #endif
1.126     brouard  2292:       fu=(*func)(u); 
                   2293:       if (fu < *fc) { 
1.183     brouard  2294: #ifdef DEBUG
1.224     brouard  2295:                                printf("\nmnbrak2  u=%lf after c=%lf but before ulim=%lf AND fu=%lf < %lf=fc\n",u,*cx,ulim,fu, *fc);
                   2296:                          fprintf(ficlog,"\nmnbrak2  u=%lf after c=%lf but before ulim=%lf AND fu=%lf < %lf=fc\n",u,*cx,ulim,fu, *fc);
                   2297: #endif
                   2298:                          SHFT(*bx,*cx,u,*cx+GOLD*(*cx-*bx)) 
                   2299:                                SHFT(*fb,*fc,fu,(*func)(u)) 
                   2300: #ifdef DEBUG
                   2301:                                        printf("\nmnbrak2 shift GOLD c=%lf",*cx+GOLD*(*cx-*bx));
1.183     brouard  2302: #endif
                   2303:       } 
1.162     brouard  2304:     } else if ((u-ulim)*(ulim-*cx) >= 0.0) { /* u outside ulim (verifying that ulim is beyond c) */
1.183     brouard  2305: #ifdef DEBUG
1.224     brouard  2306:       printf("\nmnbrak2  u=%lf outside ulim=%lf (verifying that ulim is beyond c=%lf)\n",u,ulim,*cx);
                   2307:       fprintf(ficlog,"\nmnbrak2  u=%lf outside ulim=%lf (verifying that ulim is beyond c=%lf)\n",u,ulim,*cx);
1.183     brouard  2308: #endif
1.126     brouard  2309:       u=ulim; 
                   2310:       fu=(*func)(u); 
1.183     brouard  2311:     } else { /* u could be left to b (if r > q parabola has a maximum) */
                   2312: #ifdef DEBUG
1.224     brouard  2313:       printf("\nmnbrak2  u=%lf could be left to b=%lf (if r=%lf > q=%lf parabola has a maximum)\n",u,*bx,r,q);
                   2314:       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  2315: #endif
1.126     brouard  2316:       u=(*cx)+GOLD*(*cx-*bx); 
                   2317:       fu=(*func)(u); 
1.224     brouard  2318: #ifdef DEBUG
                   2319:       printf("\nmnbrak2 new u=%lf fu=%lf shifted gold left from c=%lf and b=%lf \n",u,fu,*cx,*bx);
                   2320:       fprintf(ficlog,"\nmnbrak2 new u=%lf fu=%lf shifted gold left from c=%lf and b=%lf \n",u,fu,*cx,*bx);
                   2321: #endif
1.183     brouard  2322:     } /* end tests */
1.126     brouard  2323:     SHFT(*ax,*bx,*cx,u) 
1.183     brouard  2324:     SHFT(*fa,*fb,*fc,fu) 
                   2325: #ifdef DEBUG
1.224     brouard  2326:       printf("\nmnbrak2 shift (*ax=%.12f, *fa=%.12lf), (*bx=%.12f, *fb=%.12lf), (*cx=%.12f, *fc=%.12lf)\n",*ax,*fa,*bx,*fb,*cx,*fc);
                   2327:       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  2328: #endif
                   2329:   } /* 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  2330: } 
                   2331: 
                   2332: /*************** linmin ************************/
1.162     brouard  2333: /* Given an n -dimensional point p[1..n] and an n -dimensional direction xi[1..n] , moves and
                   2334: resets p to where the function func(p) takes on a minimum along the direction xi from p ,
                   2335: and replaces xi by the actual vector displacement that p was moved. Also returns as fret
                   2336: the value of func at the returned location p . This is actually all accomplished by calling the
                   2337: routines mnbrak and brent .*/
1.126     brouard  2338: int ncom; 
                   2339: double *pcom,*xicom;
                   2340: double (*nrfunc)(double []); 
                   2341:  
1.224     brouard  2342: #ifdef LINMINORIGINAL
1.126     brouard  2343: void linmin(double p[], double xi[], int n, double *fret,double (*func)(double [])) 
1.224     brouard  2344: #else
                   2345: void linmin(double p[], double xi[], int n, double *fret,double (*func)(double []), int *flat) 
                   2346: #endif
1.126     brouard  2347: { 
                   2348:   double brent(double ax, double bx, double cx, 
                   2349:               double (*f)(double), double tol, double *xmin); 
                   2350:   double f1dim(double x); 
                   2351:   void mnbrak(double *ax, double *bx, double *cx, double *fa, double *fb, 
                   2352:              double *fc, double (*func)(double)); 
                   2353:   int j; 
                   2354:   double xx,xmin,bx,ax; 
                   2355:   double fx,fb,fa;
1.187     brouard  2356: 
1.203     brouard  2357: #ifdef LINMINORIGINAL
                   2358: #else
                   2359:   double scale=10., axs, xxs; /* Scale added for infinity */
                   2360: #endif
                   2361:   
1.126     brouard  2362:   ncom=n; 
                   2363:   pcom=vector(1,n); 
                   2364:   xicom=vector(1,n); 
                   2365:   nrfunc=func; 
                   2366:   for (j=1;j<=n;j++) { 
                   2367:     pcom[j]=p[j]; 
1.202     brouard  2368:     xicom[j]=xi[j]; /* Former scale xi[j] of currrent direction i */
1.126     brouard  2369:   } 
1.187     brouard  2370: 
1.203     brouard  2371: #ifdef LINMINORIGINAL
                   2372:   xx=1.;
                   2373: #else
                   2374:   axs=0.0;
                   2375:   xxs=1.;
                   2376:   do{
                   2377:     xx= xxs;
                   2378: #endif
1.187     brouard  2379:     ax=0.;
                   2380:     mnbrak(&ax,&xx,&bx,&fa,&fx,&fb,f1dim);  /* Outputs: xtx[j]=pcom[j]+(*xx)*xicom[j]; fx=f(xtx[j]) */
                   2381:     /* brackets with inputs ax=0 and xx=1, but points, pcom=p, and directions values, xicom=xi, are sent via f1dim(x) */
                   2382:     /* 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))   */
                   2383:     /* Outputs: fa=f(p(j)) and fx=f(p(j) + xxs * xi(j) ) and f(bx)= f(p(j)+ bx* xi(j)) */
                   2384:     /* Given input ax=axs and xx=xxs, xx might be too far from ax to get a finite f(xx) */
                   2385:     /* Searches on line, outputs (ax, xx, bx) such that fx < min(fa and fb) */
                   2386:     /* 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  2387: #ifdef LINMINORIGINAL
                   2388: #else
                   2389:     if (fx != fx){
1.224     brouard  2390:                        xxs=xxs/scale; /* Trying a smaller xx, closer to initial ax=0 */
                   2391:                        printf("|");
                   2392:                        fprintf(ficlog,"|");
1.203     brouard  2393: #ifdef DEBUGLINMIN
1.224     brouard  2394:                        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  2395: #endif
                   2396:     }
1.224     brouard  2397:   }while(fx != fx && xxs > 1.e-5);
1.203     brouard  2398: #endif
                   2399:   
1.191     brouard  2400: #ifdef DEBUGLINMIN
                   2401:   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  2402:   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  2403: #endif
1.224     brouard  2404: #ifdef LINMINORIGINAL
                   2405: #else
1.317     brouard  2406:   if(fb == fx){ /* Flat function in the direction */
                   2407:     xmin=xx;
1.224     brouard  2408:     *flat=1;
1.317     brouard  2409:   }else{
1.224     brouard  2410:     *flat=0;
                   2411: #endif
                   2412:                /*Flat mnbrak2 shift (*ax=0.000000000000, *fa=51626.272983130431), (*bx=-1.618034000000, *fb=51590.149499362531), (*cx=-4.236068025156, *fc=51590.149499362531) */
1.187     brouard  2413:   *fret=brent(ax,xx,bx,f1dim,TOL,&xmin); /* Giving a bracketting triplet (ax, xx, bx), find a minimum, xmin, according to f1dim, *fret(xmin),*/
                   2414:   /* fa = f(p[j] + ax * xi[j]), fx = f(p[j] + xx * xi[j]), fb = f(p[j] + bx * xi[j]) */
                   2415:   /* fmin = f(p[j] + xmin * xi[j]) */
                   2416:   /* P+lambda n in that direction (lambdamin), with TOL between abscisses */
                   2417:   /* f1dim(xmin): for (j=1;j<=ncom;j++) xt[j]=pcom[j]+xmin*xicom[j]; */
1.126     brouard  2418: #ifdef DEBUG
1.224     brouard  2419:   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);
                   2420:   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);
                   2421: #endif
                   2422: #ifdef LINMINORIGINAL
                   2423: #else
                   2424:                        }
1.126     brouard  2425: #endif
1.191     brouard  2426: #ifdef DEBUGLINMIN
                   2427:   printf("linmin end ");
1.202     brouard  2428:   fprintf(ficlog,"linmin end ");
1.191     brouard  2429: #endif
1.126     brouard  2430:   for (j=1;j<=n;j++) { 
1.203     brouard  2431: #ifdef LINMINORIGINAL
                   2432:     xi[j] *= xmin; 
                   2433: #else
                   2434: #ifdef DEBUGLINMIN
                   2435:     if(xxs <1.0)
                   2436:       printf(" before xi[%d]=%12.8f", j,xi[j]);
                   2437: #endif
                   2438:     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) */
                   2439: #ifdef DEBUGLINMIN
                   2440:     if(xxs <1.0)
                   2441:       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 );
                   2442: #endif
                   2443: #endif
1.187     brouard  2444:     p[j] += xi[j]; /* Parameters values are updated accordingly */
1.126     brouard  2445:   } 
1.191     brouard  2446: #ifdef DEBUGLINMIN
1.203     brouard  2447:   printf("\n");
1.191     brouard  2448:   printf("Comparing last *frec(xmin=%12.8f)=%12.8f from Brent and frec(0.)=%12.8f \n", xmin, *fret, (*func)(p));
1.202     brouard  2449:   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  2450:   for (j=1;j<=n;j++) { 
1.202     brouard  2451:     printf(" xi[%d]= %14.10f p[%d]= %12.7f",j,xi[j],j,p[j]);
                   2452:     fprintf(ficlog," xi[%d]= %14.10f p[%d]= %12.7f",j,xi[j],j,p[j]);
                   2453:     if(j % ncovmodel == 0){
1.191     brouard  2454:       printf("\n");
1.202     brouard  2455:       fprintf(ficlog,"\n");
                   2456:     }
1.191     brouard  2457:   }
1.203     brouard  2458: #else
1.191     brouard  2459: #endif
1.126     brouard  2460:   free_vector(xicom,1,n); 
                   2461:   free_vector(pcom,1,n); 
                   2462: } 
                   2463: 
                   2464: 
                   2465: /*************** powell ************************/
1.162     brouard  2466: /*
1.317     brouard  2467: Minimization of a function func of n variables. Input consists in an initial starting point
                   2468: p[1..n] ; an initial matrix xi[1..n][1..n]  whose columns contain the initial set of di-
                   2469: rections (usually the n unit vectors); and ftol, the fractional tolerance in the function value
                   2470: such that failure to decrease by more than this amount in one iteration signals doneness. On
1.162     brouard  2471: output, p is set to the best point found, xi is the then-current direction set, fret is the returned
                   2472: function value at p , and iter is the number of iterations taken. The routine linmin is used.
                   2473:  */
1.224     brouard  2474: #ifdef LINMINORIGINAL
                   2475: #else
                   2476:        int *flatdir; /* Function is vanishing in that direction */
1.225     brouard  2477:        int flat=0, flatd=0; /* Function is vanishing in that direction */
1.224     brouard  2478: #endif
1.126     brouard  2479: void powell(double p[], double **xi, int n, double ftol, int *iter, double *fret, 
                   2480:            double (*func)(double [])) 
                   2481: { 
1.224     brouard  2482: #ifdef LINMINORIGINAL
                   2483:  void linmin(double p[], double xi[], int n, double *fret, 
1.126     brouard  2484:              double (*func)(double [])); 
1.224     brouard  2485: #else 
1.241     brouard  2486:  void linmin(double p[], double xi[], int n, double *fret,
                   2487:             double (*func)(double []),int *flat); 
1.224     brouard  2488: #endif
1.239     brouard  2489:  int i,ibig,j,jk,k; 
1.126     brouard  2490:   double del,t,*pt,*ptt,*xit;
1.181     brouard  2491:   double directest;
1.126     brouard  2492:   double fp,fptt;
                   2493:   double *xits;
                   2494:   int niterf, itmp;
                   2495: 
                   2496:   pt=vector(1,n); 
                   2497:   ptt=vector(1,n); 
                   2498:   xit=vector(1,n); 
                   2499:   xits=vector(1,n); 
                   2500:   *fret=(*func)(p); 
                   2501:   for (j=1;j<=n;j++) pt[j]=p[j]; 
1.202     brouard  2502:   rcurr_time = time(NULL);  
1.126     brouard  2503:   for (*iter=1;;++(*iter)) { 
                   2504:     ibig=0; 
                   2505:     del=0.0; 
1.157     brouard  2506:     rlast_time=rcurr_time;
                   2507:     /* (void) gettimeofday(&curr_time,&tzp); */
                   2508:     rcurr_time = time(NULL);  
                   2509:     curr_time = *localtime(&rcurr_time);
1.324     brouard  2510:     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);
                   2511:     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  2512: /*     fprintf(ficrespow,"%d %.12f %ld",*iter,*fret,curr_time.tm_sec-start_time.tm_sec); */
1.324     brouard  2513:     fp=(*fret); /* From former iteration or initial value */
1.192     brouard  2514:     for (i=1;i<=n;i++) {
1.126     brouard  2515:       fprintf(ficrespow," %.12lf", p[i]);
                   2516:     }
1.239     brouard  2517:     fprintf(ficrespow,"\n");fflush(ficrespow);
                   2518:     printf("\n#model=  1      +     age ");
                   2519:     fprintf(ficlog,"\n#model=  1      +     age ");
                   2520:     if(nagesqr==1){
1.241     brouard  2521:        printf("  + age*age  ");
                   2522:        fprintf(ficlog,"  + age*age  ");
1.239     brouard  2523:     }
                   2524:     for(j=1;j <=ncovmodel-2;j++){
                   2525:       if(Typevar[j]==0) {
                   2526:        printf("  +      V%d  ",Tvar[j]);
                   2527:        fprintf(ficlog,"  +      V%d  ",Tvar[j]);
                   2528:       }else if(Typevar[j]==1) {
                   2529:        printf("  +    V%d*age ",Tvar[j]);
                   2530:        fprintf(ficlog,"  +    V%d*age ",Tvar[j]);
                   2531:       }else if(Typevar[j]==2) {
                   2532:        printf("  +    V%d*V%d ",Tvard[Tposprod[j]][1],Tvard[Tposprod[j]][2]);
                   2533:        fprintf(ficlog,"  +    V%d*V%d ",Tvard[Tposprod[j]][1],Tvard[Tposprod[j]][2]);
                   2534:       }
                   2535:     }
1.126     brouard  2536:     printf("\n");
1.239     brouard  2537: /*     printf("12   47.0114589    0.0154322   33.2424412    0.3279905    2.3731903  */
                   2538: /* 13  -21.5392400    0.1118147    1.2680506    1.2973408   -1.0663662  */
1.126     brouard  2539:     fprintf(ficlog,"\n");
1.239     brouard  2540:     for(i=1,jk=1; i <=nlstate; i++){
                   2541:       for(k=1; k <=(nlstate+ndeath); k++){
                   2542:        if (k != i) {
                   2543:          printf("%d%d ",i,k);
                   2544:          fprintf(ficlog,"%d%d ",i,k);
                   2545:          for(j=1; j <=ncovmodel; j++){
                   2546:            printf("%12.7f ",p[jk]);
                   2547:            fprintf(ficlog,"%12.7f ",p[jk]);
                   2548:            jk++; 
                   2549:          }
                   2550:          printf("\n");
                   2551:          fprintf(ficlog,"\n");
                   2552:        }
                   2553:       }
                   2554:     }
1.241     brouard  2555:     if(*iter <=3 && *iter >1){
1.157     brouard  2556:       tml = *localtime(&rcurr_time);
                   2557:       strcpy(strcurr,asctime(&tml));
                   2558:       rforecast_time=rcurr_time; 
1.126     brouard  2559:       itmp = strlen(strcurr);
                   2560:       if(strcurr[itmp-1]=='\n')  /* Windows outputs with a new line */
1.241     brouard  2561:        strcurr[itmp-1]='\0';
1.162     brouard  2562:       printf("\nConsidering the time needed for the last iteration #%d: %ld seconds,\n",*iter,rcurr_time-rlast_time);
1.157     brouard  2563:       fprintf(ficlog,"\nConsidering the time needed for this last iteration #%d: %ld seconds,\n",*iter,rcurr_time-rlast_time);
1.126     brouard  2564:       for(niterf=10;niterf<=30;niterf+=10){
1.241     brouard  2565:        rforecast_time=rcurr_time+(niterf-*iter)*(rcurr_time-rlast_time);
                   2566:        forecast_time = *localtime(&rforecast_time);
                   2567:        strcpy(strfor,asctime(&forecast_time));
                   2568:        itmp = strlen(strfor);
                   2569:        if(strfor[itmp-1]=='\n')
                   2570:          strfor[itmp-1]='\0';
                   2571:        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);
                   2572:        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  2573:       }
                   2574:     }
1.187     brouard  2575:     for (i=1;i<=n;i++) { /* For each direction i */
                   2576:       for (j=1;j<=n;j++) xit[j]=xi[j][i]; /* Directions stored from previous iteration with previous scales */
1.126     brouard  2577:       fptt=(*fret); 
                   2578: #ifdef DEBUG
1.203     brouard  2579:       printf("fret=%lf, %lf, %lf \n", *fret, *fret, *fret);
                   2580:       fprintf(ficlog, "fret=%lf, %lf, %lf \n", *fret, *fret, *fret);
1.126     brouard  2581: #endif
1.203     brouard  2582:       printf("%d",i);fflush(stdout); /* print direction (parameter) i */
1.126     brouard  2583:       fprintf(ficlog,"%d",i);fflush(ficlog);
1.224     brouard  2584: #ifdef LINMINORIGINAL
1.188     brouard  2585:       linmin(p,xit,n,fret,func); /* Point p[n]. xit[n] has been loaded for direction i as input.*/
1.224     brouard  2586: #else
                   2587:       linmin(p,xit,n,fret,func,&flat); /* Point p[n]. xit[n] has been loaded for direction i as input.*/
                   2588:                        flatdir[i]=flat; /* Function is vanishing in that direction i */
                   2589: #endif
                   2590:                        /* Outputs are fret(new point p) p is updated and xit rescaled */
1.188     brouard  2591:       if (fabs(fptt-(*fret)) > del) { /* We are keeping the max gain on each of the n directions */
1.224     brouard  2592:                                /* because that direction will be replaced unless the gain del is small */
                   2593:                                /* in comparison with the 'probable' gain, mu^2, with the last average direction. */
                   2594:                                /* Unless the n directions are conjugate some gain in the determinant may be obtained */
                   2595:                                /* with the new direction. */
                   2596:                                del=fabs(fptt-(*fret)); 
                   2597:                                ibig=i; 
1.126     brouard  2598:       } 
                   2599: #ifdef DEBUG
                   2600:       printf("%d %.12e",i,(*fret));
                   2601:       fprintf(ficlog,"%d %.12e",i,(*fret));
                   2602:       for (j=1;j<=n;j++) {
1.224     brouard  2603:                                xits[j]=FMAX(fabs(p[j]-pt[j]),1.e-5);
                   2604:                                printf(" x(%d)=%.12e",j,xit[j]);
                   2605:                                fprintf(ficlog," x(%d)=%.12e",j,xit[j]);
1.126     brouard  2606:       }
                   2607:       for(j=1;j<=n;j++) {
1.225     brouard  2608:                                printf(" p(%d)=%.12e",j,p[j]);
                   2609:                                fprintf(ficlog," p(%d)=%.12e",j,p[j]);
1.126     brouard  2610:       }
                   2611:       printf("\n");
                   2612:       fprintf(ficlog,"\n");
                   2613: #endif
1.187     brouard  2614:     } /* end loop on each direction i */
                   2615:     /* Convergence test will use last linmin estimation (fret) and compare former iteration (fp) */ 
1.188     brouard  2616:     /* But p and xit have been updated at the end of linmin, *fret corresponds to new p, xit  */
1.187     brouard  2617:     /* New value of last point Pn is not computed, P(n-1) */
1.319     brouard  2618:     for(j=1;j<=n;j++) {
                   2619:       if(flatdir[j] >0){
                   2620:         printf(" p(%d)=%lf flat=%d ",j,p[j],flatdir[j]);
                   2621:         fprintf(ficlog," p(%d)=%lf flat=%d ",j,p[j],flatdir[j]);
1.302     brouard  2622:       }
1.319     brouard  2623:       /* printf("\n"); */
                   2624:       /* fprintf(ficlog,"\n"); */
                   2625:     }
1.243     brouard  2626:     /* if (2.0*fabs(fp-(*fret)) <= ftol*(fabs(fp)+fabs(*fret))) { /\* Did we reach enough precision? *\/ */
                   2627:     if (2.0*fabs(fp-(*fret)) <= ftol) { /* Did we reach enough precision? */
1.188     brouard  2628:       /* We could compare with a chi^2. chisquare(0.95,ddl=1)=3.84 */
                   2629:       /* By adding age*age in a model, the new -2LL should be lower and the difference follows a */
                   2630:       /* a chisquare statistics with 1 degree. To be significant at the 95% level, it should have */
                   2631:       /* decreased of more than 3.84  */
                   2632:       /* By adding age*age and V1*age the gain (-2LL) should be more than 5.99 (ddl=2) */
                   2633:       /* By using V1+V2+V3, the gain should be  7.82, compared with basic 1+age. */
                   2634:       /* By adding 10 parameters more the gain should be 18.31 */
1.224     brouard  2635:                        
1.188     brouard  2636:       /* Starting the program with initial values given by a former maximization will simply change */
                   2637:       /* the scales of the directions and the directions, because the are reset to canonical directions */
                   2638:       /* Thus the first calls to linmin will give new points and better maximizations until fp-(*fret) is */
                   2639:       /* under the tolerance value. If the tolerance is very small 1.e-9, it could last long.  */
1.126     brouard  2640: #ifdef DEBUG
                   2641:       int k[2],l;
                   2642:       k[0]=1;
                   2643:       k[1]=-1;
                   2644:       printf("Max: %.12e",(*func)(p));
                   2645:       fprintf(ficlog,"Max: %.12e",(*func)(p));
                   2646:       for (j=1;j<=n;j++) {
                   2647:        printf(" %.12e",p[j]);
                   2648:        fprintf(ficlog," %.12e",p[j]);
                   2649:       }
                   2650:       printf("\n");
                   2651:       fprintf(ficlog,"\n");
                   2652:       for(l=0;l<=1;l++) {
                   2653:        for (j=1;j<=n;j++) {
                   2654:          ptt[j]=p[j]+(p[j]-pt[j])*k[l];
                   2655:          printf("l=%d j=%d ptt=%.12e, xits=%.12e, p=%.12e, xit=%.12e", l,j,ptt[j],xits[j],p[j],xit[j]);
                   2656:          fprintf(ficlog,"l=%d j=%d ptt=%.12e, xits=%.12e, p=%.12e, xit=%.12e", l,j,ptt[j],xits[j],p[j],xit[j]);
                   2657:        }
                   2658:        printf("func(ptt)=%.12e, deriv=%.12e\n",(*func)(ptt),(ptt[j]-p[j])/((*func)(ptt)-(*func)(p)));
                   2659:        fprintf(ficlog,"func(ptt)=%.12e, deriv=%.12e\n",(*func)(ptt),(ptt[j]-p[j])/((*func)(ptt)-(*func)(p)));
                   2660:       }
                   2661: #endif
                   2662: 
                   2663:       free_vector(xit,1,n); 
                   2664:       free_vector(xits,1,n); 
                   2665:       free_vector(ptt,1,n); 
                   2666:       free_vector(pt,1,n); 
                   2667:       return; 
1.192     brouard  2668:     } /* enough precision */ 
1.240     brouard  2669:     if (*iter == ITMAX*n) nrerror("powell exceeding maximum iterations."); 
1.181     brouard  2670:     for (j=1;j<=n;j++) { /* Computes the extrapolated point P_0 + 2 (P_n-P_0) */
1.126     brouard  2671:       ptt[j]=2.0*p[j]-pt[j]; 
                   2672:       xit[j]=p[j]-pt[j]; 
                   2673:       pt[j]=p[j]; 
                   2674:     } 
1.181     brouard  2675:     fptt=(*func)(ptt); /* f_3 */
1.224     brouard  2676: #ifdef NODIRECTIONCHANGEDUNTILNITER  /* No change in drections until some iterations are done */
                   2677:                if (*iter <=4) {
1.225     brouard  2678: #else
                   2679: #endif
1.224     brouard  2680: #ifdef POWELLNOF3INFF1TEST    /* skips test F3 <F1 */
1.192     brouard  2681: #else
1.161     brouard  2682:     if (fptt < fp) { /* If extrapolated point is better, decide if we keep that new direction or not */
1.192     brouard  2683: #endif
1.162     brouard  2684:       /* (x1 f1=fp), (x2 f2=*fret), (x3 f3=fptt), (xm fm) */
1.161     brouard  2685:       /* From x1 (P0) distance of x2 is at h and x3 is 2h */
1.162     brouard  2686:       /* Let f"(x2) be the 2nd derivative equal everywhere.  */
                   2687:       /* Then the parabolic through (x1,f1), (x2,f2) and (x3,f3) */
                   2688:       /* will reach at f3 = fm + h^2/2 f"m  ; f" = (f1 -2f2 +f3 ) / h**2 */
1.224     brouard  2689:       /* Conditional for using this new direction is that mu^2 = (f1-2f2+f3)^2 /2 < del or directest <0 */
                   2690:       /* also  lamda^2=(f1-f2)^2/mu² is a parasite solution of powell */
                   2691:       /* For powell, inclusion of this average direction is only if t(del)<0 or del inbetween mu^2 and lambda^2 */
1.161     brouard  2692:       /* t=2.0*(fp-2.0*(*fret)+fptt)*SQR(fp-(*fret)-del)-del*SQR(fp-fptt); */
1.224     brouard  2693:       /*  Even if f3 <f1, directest can be negative and t >0 */
                   2694:       /* mu² and del² are equal when f3=f1 */
                   2695:                        /* f3 < f1 : mu² < del <= lambda^2 both test are equivalent */
                   2696:                        /* f3 < f1 : mu² < lambda^2 < del then directtest is negative and powell t is positive */
                   2697:                        /* f3 > f1 : lambda² < mu^2 < del then t is negative and directest >0  */
                   2698:                        /* f3 > f1 : lambda² < del < mu^2 then t is positive and directest >0  */
1.183     brouard  2699: #ifdef NRCORIGINAL
                   2700:       t=2.0*(fp-2.0*(*fret)+fptt)*SQR(fp-(*fret)-del)- del*SQR(fp-fptt); /* Original Numerical Recipes in C*/
                   2701: #else
                   2702:       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  2703:       t= t- del*SQR(fp-fptt);
1.183     brouard  2704: #endif
1.202     brouard  2705:       directest = fp-2.0*(*fret)+fptt - 2.0 * del; /* If delta was big enough we change it for a new direction */
1.161     brouard  2706: #ifdef DEBUG
1.181     brouard  2707:       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);
                   2708:       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  2709:       printf("t3= %.12lf, t4= %.12lf, t3*= %.12lf, t4*= %.12lf\n",SQR(fp-(*fret)-del),SQR(fp-fptt),
                   2710:             (fp-(*fret)-del)*(fp-(*fret)-del),(fp-fptt)*(fp-fptt));
                   2711:       fprintf(ficlog,"t3= %.12lf, t4= %.12lf, t3*= %.12lf, t4*= %.12lf\n",SQR(fp-(*fret)-del),SQR(fp-fptt),
                   2712:             (fp-(*fret)-del)*(fp-(*fret)-del),(fp-fptt)*(fp-fptt));
                   2713:       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);
                   2714:       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);
                   2715: #endif
1.183     brouard  2716: #ifdef POWELLORIGINAL
                   2717:       if (t < 0.0) { /* Then we use it for new direction */
                   2718: #else
1.182     brouard  2719:       if (directest*t < 0.0) { /* Contradiction between both tests */
1.224     brouard  2720:                                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  2721:         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  2722:         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  2723:         fprintf(ficlog,"f1-2f2+f3= %.12lf, f1-f2-del= %.12lf, f1-f3= %.12lf\n",fp-2.0*(*fret)+fptt, fp -(*fret) -del, fp-fptt);
                   2724:       } 
1.181     brouard  2725:       if (directest < 0.0) { /* Then we use it for new direction */
                   2726: #endif
1.191     brouard  2727: #ifdef DEBUGLINMIN
1.234     brouard  2728:        printf("Before linmin in direction P%d-P0\n",n);
                   2729:        for (j=1;j<=n;j++) {
                   2730:          printf(" Before xit[%d]= %12.7f p[%d]= %12.7f",j,xit[j],j,p[j]);
                   2731:          fprintf(ficlog," Before xit[%d]= %12.7f p[%d]= %12.7f",j,xit[j],j,p[j]);
                   2732:          if(j % ncovmodel == 0){
                   2733:            printf("\n");
                   2734:            fprintf(ficlog,"\n");
                   2735:          }
                   2736:        }
1.224     brouard  2737: #endif
                   2738: #ifdef LINMINORIGINAL
1.234     brouard  2739:        linmin(p,xit,n,fret,func); /* computes minimum on the extrapolated direction: changes p and rescales xit.*/
1.224     brouard  2740: #else
1.234     brouard  2741:        linmin(p,xit,n,fret,func,&flat); /* computes minimum on the extrapolated direction: changes p and rescales xit.*/
                   2742:        flatdir[i]=flat; /* Function is vanishing in that direction i */
1.191     brouard  2743: #endif
1.234     brouard  2744:        
1.191     brouard  2745: #ifdef DEBUGLINMIN
1.234     brouard  2746:        for (j=1;j<=n;j++) { 
                   2747:          printf("After xit[%d]= %12.7f p[%d]= %12.7f",j,xit[j],j,p[j]);
                   2748:          fprintf(ficlog,"After xit[%d]= %12.7f p[%d]= %12.7f",j,xit[j],j,p[j]);
                   2749:          if(j % ncovmodel == 0){
                   2750:            printf("\n");
                   2751:            fprintf(ficlog,"\n");
                   2752:          }
                   2753:        }
1.224     brouard  2754: #endif
1.234     brouard  2755:        for (j=1;j<=n;j++) { 
                   2756:          xi[j][ibig]=xi[j][n]; /* Replace direction with biggest decrease by last direction n */
                   2757:          xi[j][n]=xit[j];      /* and this nth direction by the by the average p_0 p_n */
                   2758:        }
1.224     brouard  2759: #ifdef LINMINORIGINAL
                   2760: #else
1.234     brouard  2761:        for (j=1, flatd=0;j<=n;j++) {
                   2762:          if(flatdir[j]>0)
                   2763:            flatd++;
                   2764:        }
                   2765:        if(flatd >0){
1.255     brouard  2766:          printf("%d flat directions: ",flatd);
                   2767:          fprintf(ficlog,"%d flat directions :",flatd);
1.234     brouard  2768:          for (j=1;j<=n;j++) { 
                   2769:            if(flatdir[j]>0){
                   2770:              printf("%d ",j);
                   2771:              fprintf(ficlog,"%d ",j);
                   2772:            }
                   2773:          }
                   2774:          printf("\n");
                   2775:          fprintf(ficlog,"\n");
1.319     brouard  2776: #ifdef FLATSUP
                   2777:           free_vector(xit,1,n); 
                   2778:           free_vector(xits,1,n); 
                   2779:           free_vector(ptt,1,n); 
                   2780:           free_vector(pt,1,n); 
                   2781:           return;
                   2782: #endif
1.234     brouard  2783:        }
1.191     brouard  2784: #endif
1.234     brouard  2785:        printf("Gaining to use new average direction of P0 P%d instead of biggest increase direction %d :\n",n,ibig);
                   2786:        fprintf(ficlog,"Gaining to use new average direction of P0 P%d instead of biggest increase direction %d :\n",n,ibig);
                   2787:        
1.126     brouard  2788: #ifdef DEBUG
1.234     brouard  2789:        printf("Direction changed  last moved %d in place of ibig=%d, new last is the average:\n",n,ibig);
                   2790:        fprintf(ficlog,"Direction changed  last moved %d in place of ibig=%d, new last is the average:\n",n,ibig);
                   2791:        for(j=1;j<=n;j++){
                   2792:          printf(" %lf",xit[j]);
                   2793:          fprintf(ficlog," %lf",xit[j]);
                   2794:        }
                   2795:        printf("\n");
                   2796:        fprintf(ficlog,"\n");
1.126     brouard  2797: #endif
1.192     brouard  2798:       } /* end of t or directest negative */
1.224     brouard  2799: #ifdef POWELLNOF3INFF1TEST
1.192     brouard  2800: #else
1.234     brouard  2801:       } /* end if (fptt < fp)  */
1.192     brouard  2802: #endif
1.225     brouard  2803: #ifdef NODIRECTIONCHANGEDUNTILNITER  /* No change in drections until some iterations are done */
1.234     brouard  2804:     } /*NODIRECTIONCHANGEDUNTILNITER  No change in drections until some iterations are done */
1.225     brouard  2805: #else
1.224     brouard  2806: #endif
1.234     brouard  2807:                } /* loop iteration */ 
1.126     brouard  2808: } 
1.234     brouard  2809:   
1.126     brouard  2810: /**** Prevalence limit (stable or period prevalence)  ****************/
1.234     brouard  2811:   
1.235     brouard  2812:   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  2813:   {
1.279     brouard  2814:     /**< Computes the prevalence limit in each live state at age x and for covariate combination ij 
                   2815:      *   (and selected quantitative values in nres)
                   2816:      *  by left multiplying the unit
                   2817:      *  matrix by transitions matrix until convergence is reached with precision ftolpl 
                   2818:      * Wx= Wx-1 Px-1= Wx-2 Px-2 Px-1  = Wx-n Px-n ... Px-2 Px-1 I
                   2819:      * Wx is row vector: population in state 1, population in state 2, population dead
                   2820:      * or prevalence in state 1, prevalence in state 2, 0
                   2821:      * newm is the matrix after multiplications, its rows are identical at a factor.
                   2822:      * Inputs are the parameter, age, a tolerance for the prevalence limit ftolpl.
                   2823:      * Output is prlim.
                   2824:      * Initial matrix pimij 
                   2825:      */
1.206     brouard  2826:   /* {0.85204250825084937, 0.13044499163996345, 0.017512500109187184, */
                   2827:   /* 0.090851990222114765, 0.88271245433047185, 0.026435555447413338, */
                   2828:   /*  0,                   0                  , 1} */
                   2829:   /*
                   2830:    * and after some iteration: */
                   2831:   /* {0.45504275246439968, 0.42731458730878791, 0.11764266022681241, */
                   2832:   /*  0.45201005341706885, 0.42865420071559901, 0.11933574586733192, */
                   2833:   /*  0,                   0                  , 1} */
                   2834:   /* And prevalence by suppressing the deaths are close to identical rows in prlim: */
                   2835:   /* {0.51571254859325999, 0.4842874514067399, */
                   2836:   /*  0.51326036147820708, 0.48673963852179264} */
                   2837:   /* If we start from prlim again, prlim tends to a constant matrix */
1.234     brouard  2838:     
1.332     brouard  2839:     int i, ii,j,k, k1;
1.209     brouard  2840:   double *min, *max, *meandiff, maxmax,sumnew=0.;
1.145     brouard  2841:   /* double **matprod2(); */ /* test */
1.218     brouard  2842:   double **out, cov[NCOVMAX+1], **pmij(); /* **pmmij is a global variable feeded with oldms etc */
1.126     brouard  2843:   double **newm;
1.209     brouard  2844:   double agefin, delaymax=200. ; /* 100 Max number of years to converge */
1.203     brouard  2845:   int ncvloop=0;
1.288     brouard  2846:   int first=0;
1.169     brouard  2847:   
1.209     brouard  2848:   min=vector(1,nlstate);
                   2849:   max=vector(1,nlstate);
                   2850:   meandiff=vector(1,nlstate);
                   2851: 
1.218     brouard  2852:        /* Starting with matrix unity */
1.126     brouard  2853:   for (ii=1;ii<=nlstate+ndeath;ii++)
                   2854:     for (j=1;j<=nlstate+ndeath;j++){
                   2855:       oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   2856:     }
1.169     brouard  2857:   
                   2858:   cov[1]=1.;
                   2859:   
                   2860:   /* Even if hstepm = 1, at least one multiplication by the unit matrix */
1.202     brouard  2861:   /* Start at agefin= age, computes the matrix of passage and loops decreasing agefin until convergence is reached */
1.126     brouard  2862:   for(agefin=age-stepm/YEARM; agefin>=age-delaymax; agefin=agefin-stepm/YEARM){
1.202     brouard  2863:     ncvloop++;
1.126     brouard  2864:     newm=savm;
                   2865:     /* Covariates have to be included here again */
1.138     brouard  2866:     cov[2]=agefin;
1.319     brouard  2867:      if(nagesqr==1){
                   2868:       cov[3]= agefin*agefin;
                   2869:      }
1.332     brouard  2870:      /* Model(2)  V1 + V2 + V3 + V8 + V7*V8 + V5*V6 + V8*age + V3*age + age*age */
                   2871:      /* total number of covariates of the model nbocc(+)+1 = 8 excepting constant and age and age*age */
                   2872:      for(k1=1;k1<=cptcovt;k1++){ /* loop on model equation (including products) */ 
                   2873:        if(Typevar[k1]==1){ /* A product with age */
                   2874:         cov[2+nagesqr+k1]=precov[nres][k1]*cov[2];
                   2875:        }else{
                   2876:         cov[2+nagesqr+k1]=precov[nres][k1];
                   2877:        }
                   2878:      }/* End of loop on model equation */
                   2879:      
                   2880: /* Start of old code (replaced by a loop on position in the model equation */
                   2881:     /* for (k=1; k<=nsd;k++) { /\* For single dummy covariates only of the model *\/ */
                   2882:     /*                         /\* Here comes the value of the covariate 'ij' after renumbering k with single dummy covariates *\/ */
                   2883:     /*   /\* cov[2+nagesqr+TvarsDind[k]]=nbcode[TvarsD[k]][codtabm(ij,TvarsD[k])]; *\/ */
                   2884:     /*   cov[2+nagesqr+TvarsDind[k]]=nbcode[TvarsD[k]][codtabm(ij,TnsdVar[TvarsD[k]])]; */
                   2885:     /*   /\* model = 1 +age + V1*V3 + age*V1 + V2 + V1 + age*V2 + V3 + V3*age + V1*V2  */
                   2886:     /*    * k                  1        2      3    4      5      6     7        8 */
                   2887:     /*    *cov[]   1    2      3        4      5    6      7      8     9       10 */
                   2888:     /*    *TypeVar[k]          2        1      0    0      1      0     1        2 */
                   2889:     /*    *Dummy[k]            0        2      0    0      2      0     2        0 */
                   2890:     /*    *Tvar[k]             4        1      2    1      2      3     3        5 */
                   2891:     /*    *nsd=3                              (1)  (2)           (3) */
                   2892:     /*    *TvarsD[nsd]                      [1]=2    1             3 */
                   2893:     /*    *TnsdVar                          [2]=2 [1]=1         [3]=3 */
                   2894:     /*    *TvarsDind[nsd](=k)               [1]=3 [2]=4         [3]=6 */
                   2895:     /*    *Tage[]                  [1]=1                  [2]=2      [3]=3 */
                   2896:     /*    *Tvard[]       [1][1]=1                                           [2][1]=1 */
                   2897:     /*    *                   [1][2]=3                                           [2][2]=2 */
                   2898:     /*    *Tprod[](=k)     [1]=1                                              [2]=8 */
                   2899:     /*    *TvarsDp(=Tvar)   [1]=1            [2]=2             [3]=3          [4]=5 */
                   2900:     /*    *TvarD (=k)       [1]=1            [2]=3 [3]=4       [3]=6          [4]=6 */
                   2901:     /*    *TvarsDpType */
                   2902:     /*    *si model= 1 + age + V3 + V2*age + V2 + V3*age */
                   2903:     /*    * nsd=1              (1)           (2) */
                   2904:     /*    *TvarsD[nsd]          3             2 */
                   2905:     /*    *TnsdVar           (3)=1          (2)=2 */
                   2906:     /*    *TvarsDind[nsd](=k)  [1]=1        [2]=3 */
                   2907:     /*    *Tage[]                  [1]=2           [2]= 3    */
                   2908:     /*    *\/ */
                   2909:     /*   /\* cov[++k1]=nbcode[TvarsD[k]][codtabm(ij,k)]; *\/ */
                   2910:     /*   /\* 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)); *\/ */
                   2911:     /* } */
                   2912:     /* for (k=1; k<=nsq;k++) { /\* For single quantitative varying covariates only of the model *\/ */
                   2913:     /*                         /\* Here comes the value of quantitative after renumbering k with single quantitative covariates *\/ */
                   2914:     /*   /\* Tqresult[nres][result_position]= value of the variable at the result_position in the nres resultline                                 *\/ */
                   2915:     /*   /\* cov[2+nagesqr+TvarsQind[k]]=Tqresult[nres][k]; *\/ */
                   2916:     /*   cov[2+nagesqr+TvarsQind[k]]=Tqresult[nres][resultmodel[nres][k1]] */
                   2917:     /*   /\* cov[++k1]=Tqresult[nres][k];  *\/ */
                   2918:     /*   /\* 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]); *\/ */
                   2919:     /* } */
                   2920:     /* for (k=1; k<=cptcovage;k++){  /\* For product with age *\/ */
                   2921:     /*   if(Dummy[Tage[k]]==2){ /\* dummy with age *\/ */
                   2922:     /*         cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,Tvar[Tage[k]])]*cov[2]; */
                   2923:     /*         /\* cov[++k1]=nbcode[Tvar[Tage[k]]][codtabm(ij,k)]*cov[2]; *\/ */
                   2924:     /*   } else if(Dummy[Tage[k]]==3){ /\* quantitative with age *\/ */
                   2925:     /*         cov[2+nagesqr+Tage[k]]=Tqresult[nres][k]; */
                   2926:     /*         /\* cov[++k1]=Tqresult[nres][k];  *\/ */
                   2927:     /*   } */
                   2928:     /*   /\* 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]); *\/ */
                   2929:     /* } */
                   2930:     /* for (k=1; k<=cptcovprod;k++){ /\* For product without age *\/ */
                   2931:     /*   /\* 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]); *\/ */
                   2932:     /*   if(Dummy[Tvard[k][1]]==0){ */
                   2933:     /*         if(Dummy[Tvard[k][2]]==0){ */
                   2934:     /*           cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,Tvard[k][1])] * nbcode[Tvard[k][2]][codtabm(ij,Tvard[k][2])]; */
                   2935:     /*           /\* cov[++k1]=nbcode[Tvard[k][1]][codtabm(ij,k)] * nbcode[Tvard[k][2]][codtabm(ij,k)]; *\/ */
                   2936:     /*         }else{ */
                   2937:     /*           cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,Tvard[k][1])] * Tqresult[nres][k]; */
                   2938:     /*           /\* cov[++k1]=nbcode[Tvard[k][1]][codtabm(ij,k)] * Tqresult[nres][k]; *\/ */
                   2939:     /*         } */
                   2940:     /*   }else{ */
                   2941:     /*         if(Dummy[Tvard[k][2]]==0){ */
                   2942:     /*           cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][2]][codtabm(ij,Tvard[k][2])] * Tqinvresult[nres][Tvard[k][1]]; */
                   2943:     /*           /\* cov[++k1]=nbcode[Tvard[k][2]][codtabm(ij,k)] * Tqinvresult[nres][Tvard[k][1]]; *\/ */
                   2944:     /*         }else{ */
                   2945:     /*           cov[2+nagesqr+Tprod[k]]=Tqinvresult[nres][Tvard[k][1]]*  Tqinvresult[nres][Tvard[k][2]]; */
                   2946:     /*           /\* cov[++k1]=Tqinvresult[nres][Tvard[k][1]]*  Tqinvresult[nres][Tvard[k][2]]; *\/ */
                   2947:     /*         } */
                   2948:     /*   } */
                   2949:     /* } /\* End product without age *\/ */
                   2950: /* ENd of old code */
1.138     brouard  2951:     /*printf("ij=%d cptcovprod=%d tvar=%d ", ij, cptcovprod, Tvar[1]);*/
                   2952:     /*printf("ij=%d cov[3]=%lf cov[4]=%lf \n",ij, cov[3],cov[4]);*/
                   2953:     /*printf("ij=%d cov[3]=%lf \n",ij, cov[3]);*/
1.145     brouard  2954:     /* savm=pmij(pmmij,cov,ncovmodel,x,nlstate); */
                   2955:     /* out=matprod2(newm, pmij(pmmij,cov,ncovmodel,x,nlstate),1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm); /\* Bug Valgrind *\/ */
1.319     brouard  2956:     /* age and covariate values of ij are in 'cov' */
1.142     brouard  2957:     out=matprod2(newm, pmij(pmmij,cov,ncovmodel,x,nlstate),1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm); /* Bug Valgrind */
1.138     brouard  2958:     
1.126     brouard  2959:     savm=oldm;
                   2960:     oldm=newm;
1.209     brouard  2961: 
                   2962:     for(j=1; j<=nlstate; j++){
                   2963:       max[j]=0.;
                   2964:       min[j]=1.;
                   2965:     }
                   2966:     for(i=1;i<=nlstate;i++){
                   2967:       sumnew=0;
                   2968:       for(k=1; k<=ndeath; k++) sumnew+=newm[i][nlstate+k];
                   2969:       for(j=1; j<=nlstate; j++){ 
                   2970:        prlim[i][j]= newm[i][j]/(1-sumnew);
                   2971:        max[j]=FMAX(max[j],prlim[i][j]);
                   2972:        min[j]=FMIN(min[j],prlim[i][j]);
                   2973:       }
                   2974:     }
                   2975: 
1.126     brouard  2976:     maxmax=0.;
1.209     brouard  2977:     for(j=1; j<=nlstate; j++){
                   2978:       meandiff[j]=(max[j]-min[j])/(max[j]+min[j])*2.; /* mean difference for each column */
                   2979:       maxmax=FMAX(maxmax,meandiff[j]);
                   2980:       /* 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  2981:     } /* j loop */
1.203     brouard  2982:     *ncvyear= (int)age- (int)agefin;
1.208     brouard  2983:     /* 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  2984:     if(maxmax < ftolpl){
1.209     brouard  2985:       /* printf("maxmax=%lf ncvloop=%ld, age=%d, agefin=%d ncvyear=%d \n", maxmax, ncvloop, (int)age, (int)agefin, *ncvyear); */
                   2986:       free_vector(min,1,nlstate);
                   2987:       free_vector(max,1,nlstate);
                   2988:       free_vector(meandiff,1,nlstate);
1.126     brouard  2989:       return prlim;
                   2990:     }
1.288     brouard  2991:   } /* agefin loop */
1.208     brouard  2992:     /* After some age loop it doesn't converge */
1.288     brouard  2993:   if(!first){
                   2994:     first=1;
                   2995:     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  2996:     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);
                   2997:   }else if (first >=1 && first <10){
                   2998:     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);
                   2999:     first++;
                   3000:   }else if (first ==10){
                   3001:     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);
                   3002:     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");
                   3003:     fprintf(ficlog,"Warning: the stable prevalence no convergence; too many cases, giving up noticing, even in log file\n");
                   3004:     first++;
1.288     brouard  3005:   }
                   3006: 
1.209     brouard  3007:   /* 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); */
                   3008:   free_vector(min,1,nlstate);
                   3009:   free_vector(max,1,nlstate);
                   3010:   free_vector(meandiff,1,nlstate);
1.208     brouard  3011:   
1.169     brouard  3012:   return prlim; /* should not reach here */
1.126     brouard  3013: }
                   3014: 
1.217     brouard  3015: 
                   3016:  /**** Back Prevalence limit (stable or period prevalence)  ****************/
                   3017: 
1.218     brouard  3018:  /* 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) */
                   3019:  /* 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  3020:   double **bprevalim(double **bprlim, double ***prevacurrent, int nlstate, double x[], double age, double ftolpl, int *ncvyear, int ij, int nres)
1.217     brouard  3021: {
1.264     brouard  3022:   /* 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  3023:      matrix by transitions matrix until convergence is reached with precision ftolpl */
                   3024:   /* Wx= Wx-1 Px-1= Wx-2 Px-2 Px-1  = Wx-n Px-n ... Px-2 Px-1 I */
                   3025:   /* Wx is row vector: population in state 1, population in state 2, population dead */
                   3026:   /* or prevalence in state 1, prevalence in state 2, 0 */
                   3027:   /* newm is the matrix after multiplications, its rows are identical at a factor */
                   3028:   /* Initial matrix pimij */
                   3029:   /* {0.85204250825084937, 0.13044499163996345, 0.017512500109187184, */
                   3030:   /* 0.090851990222114765, 0.88271245433047185, 0.026435555447413338, */
                   3031:   /*  0,                   0                  , 1} */
                   3032:   /*
                   3033:    * and after some iteration: */
                   3034:   /* {0.45504275246439968, 0.42731458730878791, 0.11764266022681241, */
                   3035:   /*  0.45201005341706885, 0.42865420071559901, 0.11933574586733192, */
                   3036:   /*  0,                   0                  , 1} */
                   3037:   /* And prevalence by suppressing the deaths are close to identical rows in prlim: */
                   3038:   /* {0.51571254859325999, 0.4842874514067399, */
                   3039:   /*  0.51326036147820708, 0.48673963852179264} */
                   3040:   /* If we start from prlim again, prlim tends to a constant matrix */
                   3041: 
1.332     brouard  3042:   int i, ii,j,k, k1;
1.247     brouard  3043:   int first=0;
1.217     brouard  3044:   double *min, *max, *meandiff, maxmax,sumnew=0.;
                   3045:   /* double **matprod2(); */ /* test */
                   3046:   double **out, cov[NCOVMAX+1], **bmij();
                   3047:   double **newm;
1.218     brouard  3048:   double        **dnewm, **doldm, **dsavm;  /* for use */
                   3049:   double        **oldm, **savm;  /* for use */
                   3050: 
1.217     brouard  3051:   double agefin, delaymax=200. ; /* 100 Max number of years to converge */
                   3052:   int ncvloop=0;
                   3053:   
                   3054:   min=vector(1,nlstate);
                   3055:   max=vector(1,nlstate);
                   3056:   meandiff=vector(1,nlstate);
                   3057: 
1.266     brouard  3058:   dnewm=ddnewms; doldm=ddoldms; dsavm=ddsavms;
                   3059:   oldm=oldms; savm=savms;
                   3060:   
                   3061:   /* Starting with matrix unity */
                   3062:   for (ii=1;ii<=nlstate+ndeath;ii++)
                   3063:     for (j=1;j<=nlstate+ndeath;j++){
1.217     brouard  3064:       oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   3065:     }
                   3066:   
                   3067:   cov[1]=1.;
                   3068:   
                   3069:   /* Even if hstepm = 1, at least one multiplication by the unit matrix */
                   3070:   /* Start at agefin= age, computes the matrix of passage and loops decreasing agefin until convergence is reached */
1.218     brouard  3071:   /* for(agefin=age+stepm/YEARM; agefin<=age+delaymax; agefin=agefin+stepm/YEARM){ /\* A changer en age *\/ */
1.288     brouard  3072:   /* for(agefin=age; agefin<AGESUP; agefin=agefin+stepm/YEARM){ /\* A changer en age *\/ */
                   3073:   for(agefin=age; agefin<FMIN(AGESUP,age+delaymax); agefin=agefin+stepm/YEARM){ /* A changer en age */
1.217     brouard  3074:     ncvloop++;
1.218     brouard  3075:     newm=savm; /* oldm should be kept from previous iteration or unity at start */
                   3076:                /* newm points to the allocated table savm passed by the function it can be written, savm could be reallocated */
1.217     brouard  3077:     /* Covariates have to be included here again */
                   3078:     cov[2]=agefin;
1.319     brouard  3079:     if(nagesqr==1){
1.217     brouard  3080:       cov[3]= agefin*agefin;;
1.319     brouard  3081:     }
1.332     brouard  3082:     for(k1=1;k1<=cptcovt;k1++){ /* loop on model equation (including products) */ 
                   3083:       if(Typevar[k1]==1){ /* A product with age */
                   3084:        cov[2+nagesqr+k1]=precov[nres][k1]*cov[2];
1.242     brouard  3085:       }else{
1.332     brouard  3086:        cov[2+nagesqr+k1]=precov[nres][k1];
1.242     brouard  3087:       }
1.332     brouard  3088:     }/* End of loop on model equation */
                   3089: 
                   3090: /* Old code */ 
                   3091: 
                   3092:     /* for (k=1; k<=nsd;k++) { /\* For single dummy covariates only *\/ */
                   3093:     /*                         /\* Here comes the value of the covariate 'ij' after renumbering k with single dummy covariates *\/ */
                   3094:     /*   cov[2+nagesqr+TvarsDind[k]]=nbcode[TvarsD[k]][codtabm(ij,TvarsD[k])]; */
                   3095:     /*   /\* 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)); *\/ */
                   3096:     /* } */
                   3097:     /* /\* for (k=1; k<=cptcovn;k++) { *\/ */
                   3098:     /* /\*   /\\* cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,Tvar[k])]; *\\/ *\/ */
                   3099:     /* /\*   cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,k)]; *\/ */
                   3100:     /* /\*   /\\* 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])]); *\\/ *\/ */
                   3101:     /* /\* } *\/ */
                   3102:     /* for (k=1; k<=nsq;k++) { /\* For single varying covariates only *\/ */
                   3103:     /*                         /\* Here comes the value of quantitative after renumbering k with single quantitative covariates *\/ */
                   3104:     /*   cov[2+nagesqr+TvarsQind[k]]=Tqresult[nres][k];  */
                   3105:     /*   /\* 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]); *\/ */
                   3106:     /* } */
                   3107:     /* /\* for (k=1; k<=cptcovage;k++) cov[2+nagesqr+Tage[k]]=nbcode[Tvar[k]][codtabm(ij,k)]*cov[2]; *\/ */
                   3108:     /* /\* for (k=1; k<=cptcovprod;k++) /\\* Useless *\\/ *\/ */
                   3109:     /* /\*   /\\* cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,Tvard[k][1])] * nbcode[Tvard[k][2]][codtabm(ij,Tvard[k][2])]; *\\/ *\/ */
                   3110:     /* /\*   cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)] * nbcode[Tvard[k][2]][codtabm(ij,k)]; *\/ */
                   3111:     /* for (k=1; k<=cptcovage;k++){  /\* For product with age *\/ */
                   3112:     /*   /\* if(Dummy[Tvar[Tage[k]]]== 2){ /\\* dummy with age *\\/ ERROR ???*\/ */
                   3113:     /*   if(Dummy[Tage[k]]== 2){ /\* dummy with age *\/ */
                   3114:     /*         cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,Tvar[Tage[k]])]*cov[2]; */
                   3115:     /*   } else if(Dummy[Tage[k]]== 3){ /\* quantitative with age *\/ */
                   3116:     /*         cov[2+nagesqr+Tage[k]]=Tqresult[nres][k]; */
                   3117:     /*   } */
                   3118:     /*   /\* 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]); *\/ */
                   3119:     /* } */
                   3120:     /* for (k=1; k<=cptcovprod;k++){ /\* For product without age *\/ */
                   3121:     /*   /\* 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]); *\/ */
                   3122:     /*   if(Dummy[Tvard[k][1]]==0){ */
                   3123:     /*         if(Dummy[Tvard[k][2]]==0){ */
                   3124:     /*           cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,Tvard[k][1])] * nbcode[Tvard[k][2]][codtabm(ij,Tvard[k][2])]; */
                   3125:     /*         }else{ */
                   3126:     /*           cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,Tvard[k][1])] * Tqresult[nres][k]; */
                   3127:     /*         } */
                   3128:     /*   }else{ */
                   3129:     /*         if(Dummy[Tvard[k][2]]==0){ */
                   3130:     /*           cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][2]][codtabm(ij,Tvard[k][2])] * Tqinvresult[nres][Tvard[k][1]]; */
                   3131:     /*         }else{ */
                   3132:     /*           cov[2+nagesqr+Tprod[k]]=Tqinvresult[nres][Tvard[k][1]]*  Tqinvresult[nres][Tvard[k][2]]; */
                   3133:     /*         } */
                   3134:     /*   } */
                   3135:     /* } */
1.217     brouard  3136:     
                   3137:     /*printf("ij=%d cptcovprod=%d tvar=%d ", ij, cptcovprod, Tvar[1]);*/
                   3138:     /*printf("ij=%d cov[3]=%lf cov[4]=%lf \n",ij, cov[3],cov[4]);*/
                   3139:     /*printf("ij=%d cov[3]=%lf \n",ij, cov[3]);*/
                   3140:     /* savm=pmij(pmmij,cov,ncovmodel,x,nlstate); */
                   3141:     /* out=matprod2(newm, pmij(pmmij,cov,ncovmodel,x,nlstate),1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm); /\* Bug Valgrind *\/ */
1.218     brouard  3142:                /* ij should be linked to the correct index of cov */
                   3143:                /* age and covariate values ij are in 'cov', but we need to pass
                   3144:                 * ij for the observed prevalence at age and status and covariate
                   3145:                 * number:  prevacurrent[(int)agefin][ii][ij]
                   3146:                 */
                   3147:     /* 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 *\/ */
                   3148:     /* 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 *\/ */
                   3149:     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  3150:     /* if((int)age == 86 || (int)age == 87){ */
1.266     brouard  3151:     /*   printf(" Backward prevalim age=%d agefin=%d \n", (int) age, (int) agefin); */
                   3152:     /*   for(i=1; i<=nlstate+ndeath; i++) { */
                   3153:     /*         printf("%d newm= ",i); */
                   3154:     /*         for(j=1;j<=nlstate+ndeath;j++) { */
                   3155:     /*           printf("%f ",newm[i][j]); */
                   3156:     /*         } */
                   3157:     /*         printf("oldm * "); */
                   3158:     /*         for(j=1;j<=nlstate+ndeath;j++) { */
                   3159:     /*           printf("%f ",oldm[i][j]); */
                   3160:     /*         } */
1.268     brouard  3161:     /*         printf(" bmmij "); */
1.266     brouard  3162:     /*         for(j=1;j<=nlstate+ndeath;j++) { */
                   3163:     /*           printf("%f ",pmmij[i][j]); */
                   3164:     /*         } */
                   3165:     /*         printf("\n"); */
                   3166:     /*   } */
                   3167:     /* } */
1.217     brouard  3168:     savm=oldm;
                   3169:     oldm=newm;
1.266     brouard  3170: 
1.217     brouard  3171:     for(j=1; j<=nlstate; j++){
                   3172:       max[j]=0.;
                   3173:       min[j]=1.;
                   3174:     }
                   3175:     for(j=1; j<=nlstate; j++){ 
                   3176:       for(i=1;i<=nlstate;i++){
1.234     brouard  3177:        /* bprlim[i][j]= newm[i][j]/(1-sumnew); */
                   3178:        bprlim[i][j]= newm[i][j];
                   3179:        max[i]=FMAX(max[i],bprlim[i][j]); /* Max in line */
                   3180:        min[i]=FMIN(min[i],bprlim[i][j]);
1.217     brouard  3181:       }
                   3182:     }
1.218     brouard  3183:                
1.217     brouard  3184:     maxmax=0.;
                   3185:     for(i=1; i<=nlstate; i++){
1.318     brouard  3186:       meandiff[i]=(max[i]-min[i])/(max[i]+min[i])*2.; /* mean difference for each column, could be nan! */
1.217     brouard  3187:       maxmax=FMAX(maxmax,meandiff[i]);
                   3188:       /* 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  3189:     } /* i loop */
1.217     brouard  3190:     *ncvyear= -( (int)age- (int)agefin);
1.268     brouard  3191:     /* printf("Back maxmax=%lf ncvloop=%d, age=%d, agefin=%d ncvyear=%d \n", maxmax, ncvloop, (int)age, (int)agefin, *ncvyear); */
1.217     brouard  3192:     if(maxmax < ftolpl){
1.220     brouard  3193:       /* printf("OK Back maxmax=%lf ncvloop=%d, age=%d, agefin=%d ncvyear=%d \n", maxmax, ncvloop, (int)age, (int)agefin, *ncvyear); */
1.217     brouard  3194:       free_vector(min,1,nlstate);
                   3195:       free_vector(max,1,nlstate);
                   3196:       free_vector(meandiff,1,nlstate);
                   3197:       return bprlim;
                   3198:     }
1.288     brouard  3199:   } /* agefin loop */
1.217     brouard  3200:     /* After some age loop it doesn't converge */
1.288     brouard  3201:   if(!first){
1.247     brouard  3202:     first=1;
                   3203:     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\
                   3204: 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);
                   3205:   }
                   3206:   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  3207: 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);
                   3208:   /* 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); */
                   3209:   free_vector(min,1,nlstate);
                   3210:   free_vector(max,1,nlstate);
                   3211:   free_vector(meandiff,1,nlstate);
                   3212:   
                   3213:   return bprlim; /* should not reach here */
                   3214: }
                   3215: 
1.126     brouard  3216: /*************** transition probabilities ***************/ 
                   3217: 
                   3218: double **pmij(double **ps, double *cov, int ncovmodel, double *x, int nlstate )
                   3219: {
1.138     brouard  3220:   /* According to parameters values stored in x and the covariate's values stored in cov,
1.266     brouard  3221:      computes the probability to be observed in state j (after stepm years) being in state i by appying the
1.138     brouard  3222:      model to the ncovmodel covariates (including constant and age).
                   3223:      lnpijopii=ln(pij/pii)= aij+bij*age+cij*v1+dij*v2+... = sum_nc=1^ncovmodel xij(nc)*cov[nc]
                   3224:      and, according on how parameters are entered, the position of the coefficient xij(nc) of the
                   3225:      ncth covariate in the global vector x is given by the formula:
                   3226:      j<i nc+((i-1)*(nlstate+ndeath-1)+j-1)*ncovmodel
                   3227:      j>=i nc + ((i-1)*(nlstate+ndeath-1)+(j-2))*ncovmodel
                   3228:      Computes ln(pij/pii) (lnpijopii), deduces pij/pii by exponentiation,
                   3229:      sums on j different of i to get 1-pii/pii, deduces pii, and then all pij.
1.266     brouard  3230:      Outputs ps[i][j] or probability to be observed in j being in i according to
1.138     brouard  3231:      the values of the covariates cov[nc] and corresponding parameter values x[nc+shiftij]
1.266     brouard  3232:      Sum on j ps[i][j] should equal to 1.
1.138     brouard  3233:   */
                   3234:   double s1, lnpijopii;
1.126     brouard  3235:   /*double t34;*/
1.164     brouard  3236:   int i,j, nc, ii, jj;
1.126     brouard  3237: 
1.223     brouard  3238:   for(i=1; i<= nlstate; i++){
                   3239:     for(j=1; j<i;j++){
                   3240:       for (nc=1, lnpijopii=0.;nc <=ncovmodel; nc++){
                   3241:        /*lnpijopii += param[i][j][nc]*cov[nc];*/
                   3242:        lnpijopii += x[nc+((i-1)*(nlstate+ndeath-1)+j-1)*ncovmodel]*cov[nc];
                   3243:        /*       printf("Int j<i s1=%.17e, lnpijopii=%.17e\n",s1,lnpijopii); */
                   3244:       }
                   3245:       ps[i][j]=lnpijopii; /* In fact ln(pij/pii) */
1.330     brouard  3246:       /* printf("Debug pmij() i=%d j=%d nc=%d s1=%.17f, lnpijopii=%.17f\n",i,j,nc, s1,lnpijopii); */
1.223     brouard  3247:     }
                   3248:     for(j=i+1; j<=nlstate+ndeath;j++){
                   3249:       for (nc=1, lnpijopii=0.;nc <=ncovmodel; nc++){
                   3250:        /*lnpijopii += x[(i-1)*nlstate*ncovmodel+(j-2)*ncovmodel+nc+(i-1)*(ndeath-1)*ncovmodel]*cov[nc];*/
                   3251:        lnpijopii += x[nc + ((i-1)*(nlstate+ndeath-1)+(j-2))*ncovmodel]*cov[nc];
                   3252:        /*        printf("Int j>i s1=%.17e, lnpijopii=%.17e %lx %lx\n",s1,lnpijopii,s1,lnpijopii); */
                   3253:       }
                   3254:       ps[i][j]=lnpijopii; /* In fact ln(pij/pii) */
1.330     brouard  3255:       /* printf("Debug pmij() i=%d j=%d nc=%d s1=%.17f, lnpijopii=%.17f\n",i,j,nc, s1,lnpijopii); */
1.223     brouard  3256:     }
                   3257:   }
1.218     brouard  3258:   
1.223     brouard  3259:   for(i=1; i<= nlstate; i++){
                   3260:     s1=0;
                   3261:     for(j=1; j<i; j++){
                   3262:       s1+=exp(ps[i][j]); /* In fact sums pij/pii */
1.330     brouard  3263:       /* 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  3264:     }
                   3265:     for(j=i+1; j<=nlstate+ndeath; j++){
                   3266:       s1+=exp(ps[i][j]); /* In fact sums pij/pii */
1.330     brouard  3267:       /* 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  3268:     }
                   3269:     /* s1= sum_{j<>i} pij/pii=(1-pii)/pii and thus pii is known from s1 */
                   3270:     ps[i][i]=1./(s1+1.);
                   3271:     /* Computing other pijs */
                   3272:     for(j=1; j<i; j++)
1.325     brouard  3273:       ps[i][j]= exp(ps[i][j])*ps[i][i];/* Bug valgrind */
1.223     brouard  3274:     for(j=i+1; j<=nlstate+ndeath; j++)
                   3275:       ps[i][j]= exp(ps[i][j])*ps[i][i];
                   3276:     /* ps[i][nlstate+1]=1.-s1- ps[i][i];*/ /* Sum should be 1 */
                   3277:   } /* end i */
1.218     brouard  3278:   
1.223     brouard  3279:   for(ii=nlstate+1; ii<= nlstate+ndeath; ii++){
                   3280:     for(jj=1; jj<= nlstate+ndeath; jj++){
                   3281:       ps[ii][jj]=0;
                   3282:       ps[ii][ii]=1;
                   3283:     }
                   3284:   }
1.294     brouard  3285: 
                   3286: 
1.223     brouard  3287:   /* for(ii=1; ii<= nlstate+ndeath; ii++){ */
                   3288:   /*   for(jj=1; jj<= nlstate+ndeath; jj++){ */
                   3289:   /*   printf(" pmij  ps[%d][%d]=%lf ",ii,jj,ps[ii][jj]); */
                   3290:   /*   } */
                   3291:   /*   printf("\n "); */
                   3292:   /* } */
                   3293:   /* printf("\n ");printf("%lf ",cov[2]);*/
                   3294:   /*
                   3295:     for(i=1; i<= npar; i++) printf("%f ",x[i]);
1.218     brouard  3296:                goto end;*/
1.266     brouard  3297:   return ps; /* Pointer is unchanged since its call */
1.126     brouard  3298: }
                   3299: 
1.218     brouard  3300: /*************** backward transition probabilities ***************/ 
                   3301: 
                   3302:  /* 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 ) */
                   3303: /* double **bmij(double **ps, double *cov, int ncovmodel, double *x, int nlstate,  double ***prevacurrent, double ***dnewm, double **doldm, double **dsavm, int ij ) */
                   3304:  double **bmij(double **ps, double *cov, int ncovmodel, double *x, int nlstate,  double ***prevacurrent, int ij )
                   3305: {
1.302     brouard  3306:   /* 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  3307:    * 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  3308:    */
1.218     brouard  3309:   int i, ii, j,k;
1.222     brouard  3310:   
                   3311:   double **out, **pmij();
                   3312:   double sumnew=0.;
1.218     brouard  3313:   double agefin;
1.292     brouard  3314:   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  3315:   double **dnewm, **dsavm, **doldm;
                   3316:   double **bbmij;
                   3317:   
1.218     brouard  3318:   doldm=ddoldms; /* global pointers */
1.222     brouard  3319:   dnewm=ddnewms;
                   3320:   dsavm=ddsavms;
1.318     brouard  3321: 
                   3322:   /* Debug */
                   3323:   /* printf("Bmij ij=%d, cov[2}=%f\n", ij, cov[2]); */
1.222     brouard  3324:   agefin=cov[2];
1.268     brouard  3325:   /* Bx = Diag(w_x) P_x Diag(Sum_i w^i_x p^ij_x */
1.222     brouard  3326:   /* bmij *//* age is cov[2], ij is included in cov, but we need for
1.266     brouard  3327:      the observed prevalence (with this covariate ij) at beginning of transition */
                   3328:   /* dsavm=pmij(pmmij,cov,ncovmodel,x,nlstate); */
1.268     brouard  3329: 
                   3330:   /* P_x */
1.325     brouard  3331:   pmmij=pmij(pmmij,cov,ncovmodel,x,nlstate); /*This is forward probability from agefin to agefin + stepm *//* Bug valgrind */
1.268     brouard  3332:   /* outputs pmmij which is a stochastic matrix in row */
                   3333: 
                   3334:   /* Diag(w_x) */
1.292     brouard  3335:   /* Rescaling the cross-sectional prevalence: Problem with prevacurrent which can be zero */
1.268     brouard  3336:   sumnew=0.;
1.269     brouard  3337:   /*for (ii=1;ii<=nlstate+ndeath;ii++){*/
1.268     brouard  3338:   for (ii=1;ii<=nlstate;ii++){ /* Only on live states */
1.297     brouard  3339:     /* printf(" agefin=%d, ii=%d, ij=%d, prev=%f\n",(int)agefin,ii, ij, prevacurrent[(int)agefin][ii][ij]); */
1.268     brouard  3340:     sumnew+=prevacurrent[(int)agefin][ii][ij];
                   3341:   }
                   3342:   if(sumnew >0.01){  /* At least some value in the prevalence */
                   3343:     for (ii=1;ii<=nlstate+ndeath;ii++){
                   3344:       for (j=1;j<=nlstate+ndeath;j++)
1.269     brouard  3345:        doldm[ii][j]=(ii==j ? prevacurrent[(int)agefin][ii][ij]/sumnew : 0.0);
1.268     brouard  3346:     }
                   3347:   }else{
                   3348:     for (ii=1;ii<=nlstate+ndeath;ii++){
                   3349:       for (j=1;j<=nlstate+ndeath;j++)
                   3350:       doldm[ii][j]=(ii==j ? 1./nlstate : 0.0);
                   3351:     }
                   3352:     /* if(sumnew <0.9){ */
                   3353:     /*   printf("Problem internal bmij B: sum on i wi <0.9: j=%d, sum_i wi=%lf,agefin=%d\n",j,sumnew, (int)agefin); */
                   3354:     /* } */
                   3355:   }
                   3356:   k3=0.0;  /* We put the last diagonal to 0 */
                   3357:   for (ii=nlstate+1;ii<=nlstate+ndeath;ii++){
                   3358:       doldm[ii][ii]= k3;
                   3359:   }
                   3360:   /* End doldm, At the end doldm is diag[(w_i)] */
                   3361:   
1.292     brouard  3362:   /* Left product of this diag matrix by pmmij=Px (dnewm=dsavm*doldm): diag[(w_i)*Px */
                   3363:   bbmij=matprod2(dnewm, doldm,1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, pmmij); /* was a Bug Valgrind */
1.268     brouard  3364: 
1.292     brouard  3365:   /* Diag(Sum_i w^i_x p^ij_x, should be the prevalence at age x+stepm */
1.268     brouard  3366:   /* 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  3367:   for (j=1;j<=nlstate+ndeath;j++){
1.268     brouard  3368:     sumnew=0.;
1.222     brouard  3369:     for (ii=1;ii<=nlstate;ii++){
1.266     brouard  3370:       /* sumnew+=dsavm[ii][j]*prevacurrent[(int)agefin][ii][ij]; */
1.268     brouard  3371:       sumnew+=pmmij[ii][j]*doldm[ii][ii]; /* Yes prevalence at beginning of transition */
1.222     brouard  3372:     } /* sumnew is (N11+N21)/N..= N.1/N.. = sum on i of w_i pij */
1.268     brouard  3373:     for (ii=1;ii<=nlstate+ndeath;ii++){
1.222     brouard  3374:        /* if(agefin >= agemaxpar && agefin <= agemaxpar+stepm/YEARM){ */
1.268     brouard  3375:        /*      dsavm[ii][j]=(ii==j ? 1./sumnew : 0.0); */
1.222     brouard  3376:        /* }else if(agefin >= agemaxpar+stepm/YEARM){ */
1.268     brouard  3377:        /*      dsavm[ii][j]=(ii==j ? 1./sumnew : 0.0); */
1.222     brouard  3378:        /* }else */
1.268     brouard  3379:       dsavm[ii][j]=(ii==j ? 1./sumnew : 0.0);
                   3380:     } /*End ii */
                   3381:   } /* 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 */
                   3382: 
1.292     brouard  3383:   ps=matprod2(ps, dnewm,1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, dsavm); /* was a Bug Valgrind */
1.268     brouard  3384:   /* ps is now diag[w_i] * Px * diag [1/(w_1p1i+w_2 p2i)] */
1.222     brouard  3385:   /* end bmij */
1.266     brouard  3386:   return ps; /*pointer is unchanged */
1.218     brouard  3387: }
1.217     brouard  3388: /*************** transition probabilities ***************/ 
                   3389: 
1.218     brouard  3390: double **bpmij(double **ps, double *cov, int ncovmodel, double *x, int nlstate )
1.217     brouard  3391: {
                   3392:   /* According to parameters values stored in x and the covariate's values stored in cov,
                   3393:      computes the probability to be observed in state j being in state i by appying the
                   3394:      model to the ncovmodel covariates (including constant and age).
                   3395:      lnpijopii=ln(pij/pii)= aij+bij*age+cij*v1+dij*v2+... = sum_nc=1^ncovmodel xij(nc)*cov[nc]
                   3396:      and, according on how parameters are entered, the position of the coefficient xij(nc) of the
                   3397:      ncth covariate in the global vector x is given by the formula:
                   3398:      j<i nc+((i-1)*(nlstate+ndeath-1)+j-1)*ncovmodel
                   3399:      j>=i nc + ((i-1)*(nlstate+ndeath-1)+(j-2))*ncovmodel
                   3400:      Computes ln(pij/pii) (lnpijopii), deduces pij/pii by exponentiation,
                   3401:      sums on j different of i to get 1-pii/pii, deduces pii, and then all pij.
                   3402:      Outputs ps[i][j] the probability to be observed in j being in j according to
                   3403:      the values of the covariates cov[nc] and corresponding parameter values x[nc+shiftij]
                   3404:   */
                   3405:   double s1, lnpijopii;
                   3406:   /*double t34;*/
                   3407:   int i,j, nc, ii, jj;
                   3408: 
1.234     brouard  3409:   for(i=1; i<= nlstate; i++){
                   3410:     for(j=1; j<i;j++){
                   3411:       for (nc=1, lnpijopii=0.;nc <=ncovmodel; nc++){
                   3412:        /*lnpijopii += param[i][j][nc]*cov[nc];*/
                   3413:        lnpijopii += x[nc+((i-1)*(nlstate+ndeath-1)+j-1)*ncovmodel]*cov[nc];
                   3414:        /*       printf("Int j<i s1=%.17e, lnpijopii=%.17e\n",s1,lnpijopii); */
                   3415:       }
                   3416:       ps[i][j]=lnpijopii; /* In fact ln(pij/pii) */
                   3417:       /*       printf("s1=%.17e, lnpijopii=%.17e\n",s1,lnpijopii); */
                   3418:     }
                   3419:     for(j=i+1; j<=nlstate+ndeath;j++){
                   3420:       for (nc=1, lnpijopii=0.;nc <=ncovmodel; nc++){
                   3421:        /*lnpijopii += x[(i-1)*nlstate*ncovmodel+(j-2)*ncovmodel+nc+(i-1)*(ndeath-1)*ncovmodel]*cov[nc];*/
                   3422:        lnpijopii += x[nc + ((i-1)*(nlstate+ndeath-1)+(j-2))*ncovmodel]*cov[nc];
                   3423:        /*        printf("Int j>i s1=%.17e, lnpijopii=%.17e %lx %lx\n",s1,lnpijopii,s1,lnpijopii); */
                   3424:       }
                   3425:       ps[i][j]=lnpijopii; /* In fact ln(pij/pii) */
                   3426:     }
                   3427:   }
                   3428:   
                   3429:   for(i=1; i<= nlstate; i++){
                   3430:     s1=0;
                   3431:     for(j=1; j<i; j++){
                   3432:       s1+=exp(ps[i][j]); /* In fact sums pij/pii */
                   3433:       /*printf("debug1 %d %d ps=%lf exp(ps)=%lf s1+=%lf\n",i,j,ps[i][j],exp(ps[i][j]),s1); */
                   3434:     }
                   3435:     for(j=i+1; j<=nlstate+ndeath; j++){
                   3436:       s1+=exp(ps[i][j]); /* In fact sums pij/pii */
                   3437:       /*printf("debug2 %d %d ps=%lf exp(ps)=%lf s1+=%lf\n",i,j,ps[i][j],exp(ps[i][j]),s1); */
                   3438:     }
                   3439:     /* s1= sum_{j<>i} pij/pii=(1-pii)/pii and thus pii is known from s1 */
                   3440:     ps[i][i]=1./(s1+1.);
                   3441:     /* Computing other pijs */
                   3442:     for(j=1; j<i; j++)
                   3443:       ps[i][j]= exp(ps[i][j])*ps[i][i];
                   3444:     for(j=i+1; j<=nlstate+ndeath; j++)
                   3445:       ps[i][j]= exp(ps[i][j])*ps[i][i];
                   3446:     /* ps[i][nlstate+1]=1.-s1- ps[i][i];*/ /* Sum should be 1 */
                   3447:   } /* end i */
                   3448:   
                   3449:   for(ii=nlstate+1; ii<= nlstate+ndeath; ii++){
                   3450:     for(jj=1; jj<= nlstate+ndeath; jj++){
                   3451:       ps[ii][jj]=0;
                   3452:       ps[ii][ii]=1;
                   3453:     }
                   3454:   }
1.296     brouard  3455:   /* Added for prevbcast */ /* Transposed matrix too */
1.234     brouard  3456:   for(jj=1; jj<= nlstate+ndeath; jj++){
                   3457:     s1=0.;
                   3458:     for(ii=1; ii<= nlstate+ndeath; ii++){
                   3459:       s1+=ps[ii][jj];
                   3460:     }
                   3461:     for(ii=1; ii<= nlstate; ii++){
                   3462:       ps[ii][jj]=ps[ii][jj]/s1;
                   3463:     }
                   3464:   }
                   3465:   /* Transposition */
                   3466:   for(jj=1; jj<= nlstate+ndeath; jj++){
                   3467:     for(ii=jj; ii<= nlstate+ndeath; ii++){
                   3468:       s1=ps[ii][jj];
                   3469:       ps[ii][jj]=ps[jj][ii];
                   3470:       ps[jj][ii]=s1;
                   3471:     }
                   3472:   }
                   3473:   /* for(ii=1; ii<= nlstate+ndeath; ii++){ */
                   3474:   /*   for(jj=1; jj<= nlstate+ndeath; jj++){ */
                   3475:   /*   printf(" pmij  ps[%d][%d]=%lf ",ii,jj,ps[ii][jj]); */
                   3476:   /*   } */
                   3477:   /*   printf("\n "); */
                   3478:   /* } */
                   3479:   /* printf("\n ");printf("%lf ",cov[2]);*/
                   3480:   /*
                   3481:     for(i=1; i<= npar; i++) printf("%f ",x[i]);
                   3482:     goto end;*/
                   3483:   return ps;
1.217     brouard  3484: }
                   3485: 
                   3486: 
1.126     brouard  3487: /**************** Product of 2 matrices ******************/
                   3488: 
1.145     brouard  3489: double **matprod2(double **out, double **in,int nrl, int nrh, int ncl, int nch, int ncolol, int ncoloh, double **b)
1.126     brouard  3490: {
                   3491:   /* Computes the matrix product of in(1,nrh-nrl+1)(1,nch-ncl+1) times
                   3492:      b(1,nch-ncl+1)(1,ncoloh-ncolol+1) into out(...) */
                   3493:   /* in, b, out are matrice of pointers which should have been initialized 
                   3494:      before: only the contents of out is modified. The function returns
                   3495:      a pointer to pointers identical to out */
1.145     brouard  3496:   int i, j, k;
1.126     brouard  3497:   for(i=nrl; i<= nrh; i++)
1.145     brouard  3498:     for(k=ncolol; k<=ncoloh; k++){
                   3499:       out[i][k]=0.;
                   3500:       for(j=ncl; j<=nch; j++)
                   3501:        out[i][k] +=in[i][j]*b[j][k];
                   3502:     }
1.126     brouard  3503:   return out;
                   3504: }
                   3505: 
                   3506: 
                   3507: /************* Higher Matrix Product ***************/
                   3508: 
1.235     brouard  3509: 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  3510: {
1.336   ! brouard  3511:   /* Already optimized with precov.
        !          3512:      Computes the transition matrix starting at age 'age' and dummies values in each resultline (loop on ij to find the corresponding combination) to over 
1.126     brouard  3513:      'nhstepm*hstepm*stepm' months (i.e. until
                   3514:      age (in years)  age+nhstepm*hstepm*stepm/12) by multiplying 
                   3515:      nhstepm*hstepm matrices. 
                   3516:      Output is stored in matrix po[i][j][h] for h every 'hstepm' step 
                   3517:      (typically every 2 years instead of every month which is too big 
                   3518:      for the memory).
                   3519:      Model is determined by parameters x and covariates have to be 
                   3520:      included manually here. 
                   3521: 
                   3522:      */
                   3523: 
1.330     brouard  3524:   int i, j, d, h, k, k1;
1.131     brouard  3525:   double **out, cov[NCOVMAX+1];
1.126     brouard  3526:   double **newm;
1.187     brouard  3527:   double agexact;
1.214     brouard  3528:   double agebegin, ageend;
1.126     brouard  3529: 
                   3530:   /* Hstepm could be zero and should return the unit matrix */
                   3531:   for (i=1;i<=nlstate+ndeath;i++)
                   3532:     for (j=1;j<=nlstate+ndeath;j++){
                   3533:       oldm[i][j]=(i==j ? 1.0 : 0.0);
                   3534:       po[i][j][0]=(i==j ? 1.0 : 0.0);
                   3535:     }
                   3536:   /* Even if hstepm = 1, at least one multiplication by the unit matrix */
                   3537:   for(h=1; h <=nhstepm; h++){
                   3538:     for(d=1; d <=hstepm; d++){
                   3539:       newm=savm;
                   3540:       /* Covariates have to be included here again */
                   3541:       cov[1]=1.;
1.214     brouard  3542:       agexact=age+((h-1)*hstepm + (d-1))*stepm/YEARM; /* age just before transition */
1.187     brouard  3543:       cov[2]=agexact;
1.319     brouard  3544:       if(nagesqr==1){
1.227     brouard  3545:        cov[3]= agexact*agexact;
1.319     brouard  3546:       }
1.330     brouard  3547:       /* Model(2)  V1 + V2 + V3 + V8 + V7*V8 + V5*V6 + V8*age + V3*age + age*age */
                   3548:       /* total number of covariates of the model nbocc(+)+1 = 8 excepting constant and age and age*age */
                   3549:       for(k1=1;k1<=cptcovt;k1++){ /* loop on model equation (including products) */ 
1.332     brouard  3550:        if(Typevar[k1]==1){ /* A product with age */
                   3551:          cov[2+nagesqr+k1]=precov[nres][k1]*cov[2];
                   3552:        }else{
                   3553:          cov[2+nagesqr+k1]=precov[nres][k1];
                   3554:        }
                   3555:       }/* End of loop on model equation */
                   3556:        /* Old code */ 
                   3557: /*     if( Dummy[k1]==0 && Typevar[k1]==0 ){ /\* Single dummy  *\/ */
                   3558: /* /\*    V(Tvarsel)=Tvalsel=Tresult[nres][pos](value); V(Tvresult[nres][pos] (variable): V(variable)=value) *\/ */
                   3559: /* /\*       for (k=1; k<=nsd;k++) { /\\* For single dummy covariates only *\\/ *\/ */
                   3560: /* /\* /\\* Here comes the value of the covariate 'ij' after renumbering k with single dummy covariates *\\/ *\/ */
                   3561: /*     /\* codtabm(ij,k)  (1 & (ij-1) >> (k-1))+1 *\/ */
                   3562: /* /\*             V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 *\/ */
                   3563: /* /\*    k        1  2   3   4     5    6    7     8    9 *\/ */
                   3564: /* /\*Tvar[k]=     5  4   3   6     5    2    7     1    1 *\/ */
                   3565: /* /\*    nsd         1   2                              3 *\/ /\* Counting single dummies covar fixed or tv *\/ */
                   3566: /* /\*TvarsD[nsd]     4   3                              1 *\/ /\* ID of single dummy cova fixed or timevary*\/ */
                   3567: /* /\*TvarsDind[k]    2   3                              9 *\/ /\* position K of single dummy cova *\/ */
                   3568: /*       /\* cov[2+nagesqr+TvarsDind[k]]=nbcode[TvarsD[k]][codtabm(ij,k)];or [codtabm(ij,TnsdVar[TvarsD[k]] *\/ */
                   3569: /*       cov[2+nagesqr+k1]=Tresult[nres][resultmodel[nres][k1]]; */
                   3570: /*       /\* 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]])); *\/ */
                   3571: /*       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); */
                   3572: /*       printf("hpxij new Dummy precov[nres=%d][k1=%d]=%.4f\n", nres, k1, precov[nres][k1]); */
                   3573: /*     }else if( Dummy[k1]==1 && Typevar[k1]==0 ){ /\* Single quantitative variables  *\/ */
                   3574: /*       /\* resultmodel[nres][k1]=k3: k1th position in the model correspond to the k3 position in the resultline *\/ */
                   3575: /*       cov[2+nagesqr+k1]=Tqresult[nres][resultmodel[nres][k1]];  */
                   3576: /*       /\* for (k=1; k<=nsq;k++) { /\\* For single varying covariates only *\\/ *\/ */
                   3577: /*       /\*   /\\* Here comes the value of quantitative after renumbering k with single quantitative covariates *\\/ *\/ */
                   3578: /*       /\*   cov[2+nagesqr+TvarsQind[k]]=Tqresult[nres][k]; *\/ */
                   3579: /*       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]]); */
                   3580: /*       printf("hpxij new Quanti precov[nres=%d][k1=%d]=%.4f\n", nres, k1, precov[nres][k1]); */
                   3581: /*     }else if( Dummy[k1]==2 ){ /\* For dummy with age product *\/ */
                   3582: /*       /\* Tvar[k1] Variable in the age product age*V1 is 1 *\/ */
                   3583: /*       /\* [Tinvresult[nres][V1] is its value in the resultline nres *\/ */
                   3584: /*       cov[2+nagesqr+k1]=TinvDoQresult[nres][Tvar[k1]]*cov[2]; */
                   3585: /*       printf("DhPxij Dummy with age k1=%d Tvar[%d]=%d TinvDoQresult[nres=%d][%d]=%.f age=%.2f,cov[2+%d+%d]=%.3f\n",k1,k1,Tvar[k1],nres,TinvDoQresult[nres][Tvar[k1]],cov[2],nagesqr,k1,cov[2+nagesqr+k1]); */
                   3586: /*       printf("hpxij new Dummy with age product precov[nres=%d][k1=%d]=%.4f * age=%.2f\n", nres, k1, precov[nres][k1], cov[2]); */
                   3587: 
                   3588: /*       /\* cov[2+nagesqr+k1]=Tresult[nres][resultmodel[nres][k1]];    *\/ */
                   3589: /*       /\* for (k=1; k<=cptcovage;k++){ /\\* For product with age V1+V1*age +V4 +age*V3 *\\/ *\/ */
                   3590: /*       /\* 1+2 Tage[1]=2 TVar[2]=1 Dummy[2]=2, Tage[2]=4 TVar[4]=3 Dummy[4]=3 quant*\/ */
                   3591: /*       /\* *\/ */
1.330     brouard  3592: /* /\*             V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 *\/ */
                   3593: /* /\*    k        1  2   3   4     5    6    7     8    9 *\/ */
                   3594: /* /\*Tvar[k]=     5  4   3   6     5    2    7     1    1 *\/ */
1.332     brouard  3595: /* /\*cptcovage=2                   1               2      *\/ */
                   3596: /* /\*Tage[k]=                      5               8      *\/  */
                   3597: /*     }else if( Dummy[k1]==3 ){ /\* For quant with age product *\/ */
                   3598: /*       cov[2+nagesqr+k1]=Tresult[nres][resultmodel[nres][k1]];        */
                   3599: /*       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]]); */
                   3600: /*       printf("hpxij new Quanti with age product precov[nres=%d][k1=%d] * age=%.2f\n", nres, k1, precov[nres][k1], cov[2]); */
                   3601: /*       /\* if(Dummy[Tage[k]]== 2){ /\\* dummy with age *\\/ *\/ */
                   3602: /*       /\* /\\* if(Dummy[Tvar[Tage[k]]]== 2){ /\\\* dummy with age *\\\/ *\\/ *\/ */
                   3603: /*       /\*   /\\* cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,k)]*cov[2]; *\\/ *\/ */
                   3604: /*       /\*   /\\* cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,TnsdVar[TvarsD[Tvar[Tage[k]]]])]*cov[2]; *\\/ *\/ */
                   3605: /*       /\*   cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,TnsdVar[TvarsD[Tvar[Tage[k]]]])]*cov[2]; *\/ */
                   3606: /*       /\*   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); *\/ */
                   3607: /*       /\* } else if(Dummy[Tage[k]]== 3){ /\\* quantitative with age *\\/ *\/ */
                   3608: /*       /\*   cov[2+nagesqr+Tage[k]]=Tqresult[nres][k]; *\/ */
                   3609: /*       /\* } *\/ */
                   3610: /*       /\* 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]); *\/ */
                   3611: /*     }else if(Typevar[k1]==2 ){ /\* For product (not with age) *\/ */
                   3612: /* /\*       for (k=1; k<=cptcovprod;k++){ /\\*  For product without age *\\/ *\/ */
                   3613: /* /\* /\\*             V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 *\\/ *\/ */
                   3614: /* /\* /\\*    k        1  2   3   4     5    6    7     8    9 *\\/ *\/ */
                   3615: /* /\* /\\*Tvar[k]=     5  4   3   6     5    2    7     1    1 *\\/ *\/ */
                   3616: /* /\* /\\*cptcovprod=1            1               2            *\\/ *\/ */
                   3617: /* /\* /\\*Tprod[]=                4               7            *\\/ *\/ */
                   3618: /* /\* /\\*Tvard[][1]             4               1             *\\/ *\/ */
                   3619: /* /\* /\\*Tvard[][2]               3               2           *\\/ *\/ */
1.330     brouard  3620:          
1.332     brouard  3621: /*       /\* 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])]); *\/ */
                   3622: /*       /\* cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)] * nbcode[Tvard[k][2]][codtabm(ij,k)]; *\/ */
                   3623: /*       cov[2+nagesqr+k1]=TinvDoQresult[nres][Tvardk[k1][1]] * TinvDoQresult[nres][Tvardk[k1][2]];     */
                   3624: /*       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,Tvardk[k1][1], k1,Tvardk[k1][2], TinvDoQresult[nres][Tvardk[k1][1]], TinvDoQresult[nres][Tvardk[k1][2]]); */
                   3625: /*       printf("hpxij new Product no age product precov[nres=%d][k1=%d]=%.4f\n", nres, k1, precov[nres][k1]); */
                   3626: 
                   3627: /*       /\* if(Dummy[Tvardk[k1][1]]==0){ *\/ */
                   3628: /*       /\*   if(Dummy[Tvardk[k1][2]]==0){ /\\* Product of dummies *\\/ *\/ */
                   3629: /*           /\* cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)] * nbcode[Tvard[k][2]][codtabm(ij,k)]; *\/ */
                   3630: /*           /\* cov[2+nagesqr+k1]=Tinvresult[nres][Tvardk[k1][1]] * Tinvresult[nres][Tvardk[k1][2]];   *\/ */
                   3631: /*           /\* 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]])]; *\/ */
                   3632: /*         /\* }else{ /\\* Product of dummy by quantitative *\\/ *\/ */
                   3633: /*           /\* cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,TnsdVar[Tvard[k][1]])] * Tqresult[nres][k]; *\/ */
                   3634: /*           /\* cov[2+nagesqr+k1]=Tresult[nres][Tinvresult[nres][Tvardk[k1][1]]] * Tqresult[nres][Tinvresult[nres][Tvardk[k1][2]]]; *\/ */
                   3635: /*       /\*   } *\/ */
                   3636: /*       /\* }else{ /\\* Product of quantitative by...*\\/ *\/ */
                   3637: /*       /\*   if(Dummy[Tvard[k][2]]==0){  /\\* quant by dummy *\\/ *\/ */
                   3638: /*       /\*     /\\* cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][2]][codtabm(ij,TnsdVar[Tvard[k][2]])] * Tqinvresult[nres][Tvard[k][1]]; *\\/ *\/ */
                   3639: /*       /\*     cov[2+nagesqr+k1]=Tqresult[nres][Tinvresult[nres][Tvardk[k1][1]]] * Tresult[nres][Tinvresult[nres][Tvardk[k1][2]]]  ; *\/ */
                   3640: /*       /\*   }else{ /\\* Product of two quant *\\/ *\/ */
                   3641: /*       /\*     /\\* cov[2+nagesqr+Tprod[k]]=Tqinvresult[nres][Tvard[k][1]]*  Tqinvresult[nres][Tvard[k][2]]; *\\/ *\/ */
                   3642: /*       /\*     cov[2+nagesqr+k1]=Tqresult[nres][Tinvresult[nres][Tvardk[k1][1]]] * Tqresult[nres][Tinvresult[nres][Tvardk[k1][2]]]  ; *\/ */
                   3643: /*       /\*   } *\/ */
                   3644: /*       /\* }/\\*end of products quantitative *\\/ *\/ */
                   3645: /*     }/\*end of products *\/ */
                   3646:       /* } /\* End of loop on model equation *\/ */
1.235     brouard  3647:       /* for (k=1; k<=cptcovn;k++)  */
                   3648:       /*       cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,k)]; */
                   3649:       /* for (k=1; k<=cptcovage;k++) /\* Should start at cptcovn+1 *\/ */
                   3650:       /*       cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,k)]*cov[2]; */
                   3651:       /* for (k=1; k<=cptcovprod;k++) /\* Useless because included in cptcovn *\/ */
                   3652:       /*       cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)]*nbcode[Tvard[k][2]][codtabm(ij,k)]; */
1.227     brouard  3653:       
                   3654:       
1.126     brouard  3655:       /*printf("hxi cptcov=%d cptcode=%d\n",cptcov,cptcode);*/
                   3656:       /*printf("h=%d d=%d age=%f cov=%f\n",h,d,age,cov[2]);*/
1.319     brouard  3657:       /* right multiplication of oldm by the current matrix */
1.126     brouard  3658:       out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, 
                   3659:                   pmij(pmmij,cov,ncovmodel,x,nlstate));
1.217     brouard  3660:       /* if((int)age == 70){ */
                   3661:       /*       printf(" Forward hpxij age=%d agexact=%f d=%d nhstepm=%d hstepm=%d\n", (int) age, agexact, d, nhstepm, hstepm); */
                   3662:       /*       for(i=1; i<=nlstate+ndeath; i++) { */
                   3663:       /*         printf("%d pmmij ",i); */
                   3664:       /*         for(j=1;j<=nlstate+ndeath;j++) { */
                   3665:       /*           printf("%f ",pmmij[i][j]); */
                   3666:       /*         } */
                   3667:       /*         printf(" oldm "); */
                   3668:       /*         for(j=1;j<=nlstate+ndeath;j++) { */
                   3669:       /*           printf("%f ",oldm[i][j]); */
                   3670:       /*         } */
                   3671:       /*         printf("\n"); */
                   3672:       /*       } */
                   3673:       /* } */
1.126     brouard  3674:       savm=oldm;
                   3675:       oldm=newm;
                   3676:     }
                   3677:     for(i=1; i<=nlstate+ndeath; i++)
                   3678:       for(j=1;j<=nlstate+ndeath;j++) {
1.267     brouard  3679:        po[i][j][h]=newm[i][j];
                   3680:        /*if(h==nhstepm) printf("po[%d][%d][%d]=%f ",i,j,h,po[i][j][h]);*/
1.126     brouard  3681:       }
1.128     brouard  3682:     /*printf("h=%d ",h);*/
1.126     brouard  3683:   } /* end h */
1.267     brouard  3684:   /*     printf("\n H=%d \n",h); */
1.126     brouard  3685:   return po;
                   3686: }
                   3687: 
1.217     brouard  3688: /************* Higher Back Matrix Product ***************/
1.218     brouard  3689: /* 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  3690: 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  3691: {
1.332     brouard  3692:   /* For dummy covariates given in each resultline (for historical, computes the corresponding combination ij),
                   3693:      computes the transition matrix starting at age 'age' over
1.217     brouard  3694:      'nhstepm*hstepm*stepm' months (i.e. until
1.218     brouard  3695:      age (in years)  age+nhstepm*hstepm*stepm/12) by multiplying
                   3696:      nhstepm*hstepm matrices.
                   3697:      Output is stored in matrix po[i][j][h] for h every 'hstepm' step
                   3698:      (typically every 2 years instead of every month which is too big
1.217     brouard  3699:      for the memory).
1.218     brouard  3700:      Model is determined by parameters x and covariates have to be
1.266     brouard  3701:      included manually here. Then we use a call to bmij(x and cov)
                   3702:      The addresss of po (p3mat allocated to the dimension of nhstepm) should be stored for output
1.222     brouard  3703:   */
1.217     brouard  3704: 
1.332     brouard  3705:   int i, j, d, h, k, k1;
1.266     brouard  3706:   double **out, cov[NCOVMAX+1], **bmij();
                   3707:   double **newm, ***newmm;
1.217     brouard  3708:   double agexact;
                   3709:   double agebegin, ageend;
1.222     brouard  3710:   double **oldm, **savm;
1.217     brouard  3711: 
1.266     brouard  3712:   newmm=po; /* To be saved */
                   3713:   oldm=oldms;savm=savms; /* Global pointers */
1.217     brouard  3714:   /* Hstepm could be zero and should return the unit matrix */
                   3715:   for (i=1;i<=nlstate+ndeath;i++)
                   3716:     for (j=1;j<=nlstate+ndeath;j++){
                   3717:       oldm[i][j]=(i==j ? 1.0 : 0.0);
                   3718:       po[i][j][0]=(i==j ? 1.0 : 0.0);
                   3719:     }
                   3720:   /* Even if hstepm = 1, at least one multiplication by the unit matrix */
                   3721:   for(h=1; h <=nhstepm; h++){
                   3722:     for(d=1; d <=hstepm; d++){
                   3723:       newm=savm;
                   3724:       /* Covariates have to be included here again */
                   3725:       cov[1]=1.;
1.271     brouard  3726:       agexact=age-( (h-1)*hstepm + (d)  )*stepm/YEARM; /* age just before transition, d or d-1? */
1.217     brouard  3727:       /* agexact=age+((h-1)*hstepm + (d-1))*stepm/YEARM; /\* age just before transition *\/ */
1.318     brouard  3728:         /* Debug */
                   3729:       /* printf("hBxij age=%lf, agexact=%lf\n", age, agexact); */
1.217     brouard  3730:       cov[2]=agexact;
1.332     brouard  3731:       if(nagesqr==1){
1.222     brouard  3732:        cov[3]= agexact*agexact;
1.332     brouard  3733:       }
                   3734:       /** New code */
                   3735:       for(k1=1;k1<=cptcovt;k1++){ /* loop on model equation (including products) */ 
                   3736:        if(Typevar[k1]==1){ /* A product with age */
                   3737:          cov[2+nagesqr+k1]=precov[nres][k1]*cov[2];
1.325     brouard  3738:        }else{
1.332     brouard  3739:          cov[2+nagesqr+k1]=precov[nres][k1];
1.325     brouard  3740:        }
1.332     brouard  3741:       }/* End of loop on model equation */
                   3742:       /** End of new code */
                   3743:   /** This was old code */
                   3744:       /* for (k=1; k<=nsd;k++){ /\* For single dummy covariates only *\//\* cptcovn error *\/ */
                   3745:       /* /\*   cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,k)]; *\/ */
                   3746:       /* /\* /\\* cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,Tvar[k])]; *\\/ *\/ */
                   3747:       /*       cov[2+nagesqr+TvarsDind[k]]=nbcode[TvarsD[k]][codtabm(ij,TvarsD[k])];/\* Bug valgrind *\/ */
                   3748:       /*   /\* 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)); *\/ */
                   3749:       /* } */
                   3750:       /* for (k=1; k<=nsq;k++) { /\* For single varying covariates only *\/ */
                   3751:       /*       /\* Here comes the value of quantitative after renumbering k with single quantitative covariates *\/ */
                   3752:       /*       cov[2+nagesqr+TvarsQind[k]]=Tqresult[nres][k];  */
                   3753:       /*       /\* 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]); *\/ */
                   3754:       /* } */
                   3755:       /* for (k=1; k<=cptcovage;k++){ /\* Should start at cptcovn+1 *\//\* For product with age *\/ */
                   3756:       /*       /\* if(Dummy[Tvar[Tage[k]]]== 2){ /\\* dummy with age error!!!*\\/ *\/ */
                   3757:       /*       if(Dummy[Tage[k]]== 2){ /\* dummy with age *\/ */
                   3758:       /*         cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,Tvar[Tage[k]])]*cov[2]; */
                   3759:       /*       } else if(Dummy[Tage[k]]== 3){ /\* quantitative with age *\/ */
                   3760:       /*         cov[2+nagesqr+Tage[k]]=Tqresult[nres][k];  */
                   3761:       /*       } */
                   3762:       /*       /\* 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]); *\/ */
                   3763:       /* } */
                   3764:       /* for (k=1; k<=cptcovprod;k++){ /\* Useless because included in cptcovn *\/ */
                   3765:       /*       cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,Tvard[k][1])]*nbcode[Tvard[k][2]][codtabm(ij,Tvard[k][2])]; */
                   3766:       /*       if(Dummy[Tvard[k][1]]==0){ */
                   3767:       /*         if(Dummy[Tvard[k][2]]==0){ */
                   3768:       /*           cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,Tvard[k][1])] * nbcode[Tvard[k][2]][codtabm(ij,Tvard[k][1])]; */
                   3769:       /*         }else{ */
                   3770:       /*           cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,Tvard[k][1])] * Tqresult[nres][k]; */
                   3771:       /*         } */
                   3772:       /*       }else{ */
                   3773:       /*         if(Dummy[Tvard[k][2]]==0){ */
                   3774:       /*           cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][2]][codtabm(ij,Tvard[k][2])] * Tqinvresult[nres][Tvard[k][1]]; */
                   3775:       /*         }else{ */
                   3776:       /*           cov[2+nagesqr+Tprod[k]]=Tqinvresult[nres][Tvard[k][1]]*  Tqinvresult[nres][Tvard[k][2]]; */
                   3777:       /*         } */
                   3778:       /*       } */
                   3779:       /* }                      */
                   3780:       /* /\*printf("hxi cptcov=%d cptcode=%d\n",cptcov,cptcode);*\/ */
                   3781:       /* /\*printf("h=%d d=%d age=%f cov=%f\n",h,d,age,cov[2]);*\/ */
                   3782: /** End of old code */
                   3783:       
1.218     brouard  3784:       /* Careful transposed matrix */
1.266     brouard  3785:       /* age is in cov[2], prevacurrent at beginning of transition. */
1.218     brouard  3786:       /* out=matprod2(newm, bmij(pmmij,cov,ncovmodel,x,nlstate,prevacurrent, dnewm, doldm, dsavm,ij),\ */
1.222     brouard  3787:       /*                                                1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm); */
1.218     brouard  3788:       out=matprod2(newm, bmij(pmmij,cov,ncovmodel,x,nlstate,prevacurrent,ij),\
1.325     brouard  3789:                   1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm);/* Bug valgrind */
1.217     brouard  3790:       /* if((int)age == 70){ */
                   3791:       /*       printf(" Backward hbxij age=%d agexact=%f d=%d nhstepm=%d hstepm=%d\n", (int) age, agexact, d, nhstepm, hstepm); */
                   3792:       /*       for(i=1; i<=nlstate+ndeath; i++) { */
                   3793:       /*         printf("%d pmmij ",i); */
                   3794:       /*         for(j=1;j<=nlstate+ndeath;j++) { */
                   3795:       /*           printf("%f ",pmmij[i][j]); */
                   3796:       /*         } */
                   3797:       /*         printf(" oldm "); */
                   3798:       /*         for(j=1;j<=nlstate+ndeath;j++) { */
                   3799:       /*           printf("%f ",oldm[i][j]); */
                   3800:       /*         } */
                   3801:       /*         printf("\n"); */
                   3802:       /*       } */
                   3803:       /* } */
                   3804:       savm=oldm;
                   3805:       oldm=newm;
                   3806:     }
                   3807:     for(i=1; i<=nlstate+ndeath; i++)
                   3808:       for(j=1;j<=nlstate+ndeath;j++) {
1.222     brouard  3809:        po[i][j][h]=newm[i][j];
1.268     brouard  3810:        /* if(h==nhstepm) */
                   3811:        /*   printf("po[%d][%d][%d]=%f ",i,j,h,po[i][j][h]); */
1.217     brouard  3812:       }
1.268     brouard  3813:     /* printf("h=%d %.1f ",h, agexact); */
1.217     brouard  3814:   } /* end h */
1.268     brouard  3815:   /* printf("\n H=%d nhs=%d \n",h, nhstepm); */
1.217     brouard  3816:   return po;
                   3817: }
                   3818: 
                   3819: 
1.162     brouard  3820: #ifdef NLOPT
                   3821:   double  myfunc(unsigned n, const double *p1, double *grad, void *pd){
                   3822:   double fret;
                   3823:   double *xt;
                   3824:   int j;
                   3825:   myfunc_data *d2 = (myfunc_data *) pd;
                   3826: /* xt = (p1-1); */
                   3827:   xt=vector(1,n); 
                   3828:   for (j=1;j<=n;j++)   xt[j]=p1[j-1]; /* xt[1]=p1[0] */
                   3829: 
                   3830:   fret=(d2->function)(xt); /*  p xt[1]@8 is fine */
                   3831:   /* fret=(*func)(xt); /\*  p xt[1]@8 is fine *\/ */
                   3832:   printf("Function = %.12lf ",fret);
                   3833:   for (j=1;j<=n;j++) printf(" %d %.8lf", j, xt[j]); 
                   3834:   printf("\n");
                   3835:  free_vector(xt,1,n);
                   3836:   return fret;
                   3837: }
                   3838: #endif
1.126     brouard  3839: 
                   3840: /*************** log-likelihood *************/
                   3841: double func( double *x)
                   3842: {
1.336   ! brouard  3843:   int i, ii, j, k, mi, d, kk, kf=0;
1.226     brouard  3844:   int ioffset=0;
                   3845:   double l, ll[NLSTATEMAX+1], cov[NCOVMAX+1];
                   3846:   double **out;
                   3847:   double lli; /* Individual log likelihood */
                   3848:   int s1, s2;
1.228     brouard  3849:   int iv=0, iqv=0, itv=0, iqtv=0 ; /* Index of varying covariate, fixed quantitative cov, time varying covariate, quantitative time varying covariate */
1.336   ! brouard  3850: 
1.226     brouard  3851:   double bbh, survp;
                   3852:   double agexact;
1.336   ! brouard  3853:   double agebegin, ageend;
1.226     brouard  3854:   /*extern weight */
                   3855:   /* We are differentiating ll according to initial status */
                   3856:   /*  for (i=1;i<=npar;i++) printf("%f ", x[i]);*/
                   3857:   /*for(i=1;i<imx;i++) 
                   3858:     printf(" %d\n",s[4][i]);
                   3859:   */
1.162     brouard  3860: 
1.226     brouard  3861:   ++countcallfunc;
1.162     brouard  3862: 
1.226     brouard  3863:   cov[1]=1.;
1.126     brouard  3864: 
1.226     brouard  3865:   for(k=1; k<=nlstate; k++) ll[k]=0.;
1.224     brouard  3866:   ioffset=0;
1.226     brouard  3867:   if(mle==1){
                   3868:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
                   3869:       /* Computes the values of the ncovmodel covariates of the model
                   3870:         depending if the covariates are fixed or varying (age dependent) and stores them in cov[]
                   3871:         Then computes with function pmij which return a matrix p[i][j] giving the elementary probability
                   3872:         to be observed in j being in i according to the model.
                   3873:       */
1.243     brouard  3874:       ioffset=2+nagesqr ;
1.233     brouard  3875:    /* Fixed */
1.336   ! brouard  3876:       for (kf=1; kf<=ncovf;kf++){ /* For each fixed covariate dummu or quant or prod */
1.319     brouard  3877:        /* # V1=sex, V2=raedyrs Quant Fixed, State=livarnb4..livarnb11, V3=iadl4..iald11, V4=adlw4..adlw11, V5=r4bmi..r11bmi */
                   3878:         /*             V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
                   3879:        /*  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  3880:         /* TvarFind;  TvarFind[1]=6,  TvarFind[2]=7, TvarFind[3]=9 *//* Inverse V2(6) is first fixed (single or prod)  */
1.336   ! brouard  3881:        cov[ioffset+TvarFind[kf]]=covar[Tvar[TvarFind[kf]]][i];/* V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1, only V1 is fixed (TvarFind[1]=6)*/
1.319     brouard  3882:        /* V1*V2 (7)  TvarFind[2]=7, TvarFind[3]=9 */
1.234     brouard  3883:       }
1.226     brouard  3884:       /* In model V2+V1*V4+age*V3+V3*V2 Tvar[1] is V2, Tvar[2=V1*V4] 
1.319     brouard  3885:         is 5, Tvar[3=age*V3] should not be computed because of age Tvar[4=V3*V2]=6 
1.226     brouard  3886:         has been calculated etc */
                   3887:       /* For an individual i, wav[i] gives the number of effective waves */
                   3888:       /* We compute the contribution to Likelihood of each effective transition
                   3889:         mw[mi][i] is real wave of the mi th effectve wave */
                   3890:       /* Then statuses are computed at each begin and end of an effective wave s1=s[ mw[mi][i] ][i];
                   3891:         s2=s[mw[mi+1][i]][i];
                   3892:         And the iv th varying covariate is the cotvar[mw[mi+1][i]][iv][i]
                   3893:         But if the variable is not in the model TTvar[iv] is the real variable effective in the model:
                   3894:         meaning that decodemodel should be used cotvar[mw[mi+1][i]][TTvar[iv]][i]
                   3895:       */
1.336   ! brouard  3896:       for(mi=1; mi<= wav[i]-1; mi++){  /* Varying with waves */
        !          3897:       /* Wave varying (but not age varying) */
1.319     brouard  3898:        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*/
                   3899:          /* cov[ioffset+TvarVind[k]]=cotvar[mw[mi][i]][Tvar[TvarVind[k]]][i]; but where is the crossproduct? */
1.242     brouard  3900:          cov[ioffset+TvarVind[k]]=cotvar[mw[mi][i]][Tvar[TvarVind[k]]-ncovcol-nqv][i];
1.234     brouard  3901:        }
                   3902:        for (ii=1;ii<=nlstate+ndeath;ii++)
                   3903:          for (j=1;j<=nlstate+ndeath;j++){
                   3904:            oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   3905:            savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   3906:          }
1.336   ! brouard  3907: 
        !          3908:        agebegin=agev[mw[mi][i]][i]; /* Age at beginning of effective wave */
        !          3909:        ageend=agev[mw[mi][i]][i] + (dh[mi][i])*stepm/YEARM; /* Age at end of effective wave and at the end of transition */
1.234     brouard  3910:        for(d=0; d<dh[mi][i]; d++){
                   3911:          newm=savm;
                   3912:          agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
                   3913:          cov[2]=agexact;
                   3914:          if(nagesqr==1)
                   3915:            cov[3]= agexact*agexact;  /* Should be changed here */
                   3916:          for (kk=1; kk<=cptcovage;kk++) {
1.318     brouard  3917:            if(!FixedV[Tvar[Tage[kk]]])
                   3918:              cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact; /* Tage[kk] gives the data-covariate associated with age */
                   3919:            else
                   3920:              cov[Tage[kk]+2+nagesqr]=cotvar[mw[mi][i]][Tvar[Tage[kk]]-ncovcol-nqv][i]*agexact;
1.234     brouard  3921:          }
                   3922:          out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   3923:                       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   3924:          savm=oldm;
                   3925:          oldm=newm;
                   3926:        } /* end mult */
                   3927:        
                   3928:        /*lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]);*/ /* Original formula */
                   3929:        /* But now since version 0.9 we anticipate for bias at large stepm.
                   3930:         * If stepm is larger than one month (smallest stepm) and if the exact delay 
                   3931:         * (in months) between two waves is not a multiple of stepm, we rounded to 
                   3932:         * the nearest (and in case of equal distance, to the lowest) interval but now
                   3933:         * we keep into memory the bias bh[mi][i] and also the previous matrix product
                   3934:         * (i.e to dh[mi][i]-1) saved in 'savm'. Then we inter(extra)polate the
                   3935:         * probability in order to take into account the bias as a fraction of the way
1.231     brouard  3936:                                 * from savm to out if bh is negative or even beyond if bh is positive. bh varies
                   3937:                                 * -stepm/2 to stepm/2 .
                   3938:                                 * For stepm=1 the results are the same as for previous versions of Imach.
                   3939:                                 * For stepm > 1 the results are less biased than in previous versions. 
                   3940:                                 */
1.234     brouard  3941:        s1=s[mw[mi][i]][i];
                   3942:        s2=s[mw[mi+1][i]][i];
                   3943:        bbh=(double)bh[mi][i]/(double)stepm; 
                   3944:        /* bias bh is positive if real duration
                   3945:         * is higher than the multiple of stepm and negative otherwise.
                   3946:         */
                   3947:        /* lli= (savm[s1][s2]>1.e-8 ?(1.+bbh)*log(out[s1][s2])- bbh*log(savm[s1][s2]):log((1.+bbh)*out[s1][s2]));*/
                   3948:        if( s2 > nlstate){ 
                   3949:          /* i.e. if s2 is a death state and if the date of death is known 
                   3950:             then the contribution to the likelihood is the probability to 
                   3951:             die between last step unit time and current  step unit time, 
                   3952:             which is also equal to probability to die before dh 
                   3953:             minus probability to die before dh-stepm . 
                   3954:             In version up to 0.92 likelihood was computed
                   3955:             as if date of death was unknown. Death was treated as any other
                   3956:             health state: the date of the interview describes the actual state
                   3957:             and not the date of a change in health state. The former idea was
                   3958:             to consider that at each interview the state was recorded
                   3959:             (healthy, disable or death) and IMaCh was corrected; but when we
                   3960:             introduced the exact date of death then we should have modified
                   3961:             the contribution of an exact death to the likelihood. This new
                   3962:             contribution is smaller and very dependent of the step unit
                   3963:             stepm. It is no more the probability to die between last interview
                   3964:             and month of death but the probability to survive from last
                   3965:             interview up to one month before death multiplied by the
                   3966:             probability to die within a month. Thanks to Chris
                   3967:             Jackson for correcting this bug.  Former versions increased
                   3968:             mortality artificially. The bad side is that we add another loop
                   3969:             which slows down the processing. The difference can be up to 10%
                   3970:             lower mortality.
                   3971:          */
                   3972:          /* If, at the beginning of the maximization mostly, the
                   3973:             cumulative probability or probability to be dead is
                   3974:             constant (ie = 1) over time d, the difference is equal to
                   3975:             0.  out[s1][3] = savm[s1][3]: probability, being at state
                   3976:             s1 at precedent wave, to be dead a month before current
                   3977:             wave is equal to probability, being at state s1 at
                   3978:             precedent wave, to be dead at mont of the current
                   3979:             wave. Then the observed probability (that this person died)
                   3980:             is null according to current estimated parameter. In fact,
                   3981:             it should be very low but not zero otherwise the log go to
                   3982:             infinity.
                   3983:          */
1.183     brouard  3984: /* #ifdef INFINITYORIGINAL */
                   3985: /*         lli=log(out[s1][s2] - savm[s1][s2]); */
                   3986: /* #else */
                   3987: /*       if ((out[s1][s2] - savm[s1][s2]) < mytinydouble)  */
                   3988: /*         lli=log(mytinydouble); */
                   3989: /*       else */
                   3990: /*         lli=log(out[s1][s2] - savm[s1][s2]); */
                   3991: /* #endif */
1.226     brouard  3992:          lli=log(out[s1][s2] - savm[s1][s2]);
1.216     brouard  3993:          
1.226     brouard  3994:        } else if  ( s2==-1 ) { /* alive */
                   3995:          for (j=1,survp=0. ; j<=nlstate; j++) 
                   3996:            survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
                   3997:          /*survp += out[s1][j]; */
                   3998:          lli= log(survp);
                   3999:        }
1.336   ! brouard  4000:        /* else if  (s2==-4) {  */
        !          4001:        /*   for (j=3,survp=0. ; j<=nlstate; j++)   */
        !          4002:        /*     survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j]; */
        !          4003:        /*   lli= log(survp);  */
        !          4004:        /* }  */
        !          4005:        /* else if  (s2==-5) {  */
        !          4006:        /*   for (j=1,survp=0. ; j<=2; j++)   */
        !          4007:        /*     survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j]; */
        !          4008:        /*   lli= log(survp);  */
        !          4009:        /* }  */
1.226     brouard  4010:        else{
                   4011:          lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */
                   4012:          /*  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 */
                   4013:        } 
                   4014:        /*lli=(1.+bbh)*log(out[s1][s2])- bbh*log(savm[s1][s2]);*/
                   4015:        /*if(lli ==000.0)*/
                   4016:        /*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); */
                   4017:        ipmx +=1;
                   4018:        sw += weight[i];
                   4019:        ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
                   4020:        /* if (lli < log(mytinydouble)){ */
                   4021:        /*   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); */
                   4022:        /*   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]); */
                   4023:        /* } */
                   4024:       } /* end of wave */
                   4025:     } /* end of individual */
                   4026:   }  else if(mle==2){
                   4027:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
1.319     brouard  4028:       ioffset=2+nagesqr ;
                   4029:       for (k=1; k<=ncovf;k++)
                   4030:        cov[ioffset+TvarFind[k]]=covar[Tvar[TvarFind[k]]][i];
1.226     brouard  4031:       for(mi=1; mi<= wav[i]-1; mi++){
1.319     brouard  4032:        for(k=1; k <= ncovv ; k++){
                   4033:          cov[ioffset+TvarVind[k]]=cotvar[mw[mi][i]][Tvar[TvarVind[k]]-ncovcol-nqv][i];
                   4034:        }
1.226     brouard  4035:        for (ii=1;ii<=nlstate+ndeath;ii++)
                   4036:          for (j=1;j<=nlstate+ndeath;j++){
                   4037:            oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   4038:            savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   4039:          }
                   4040:        for(d=0; d<=dh[mi][i]; d++){
                   4041:          newm=savm;
                   4042:          agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
                   4043:          cov[2]=agexact;
                   4044:          if(nagesqr==1)
                   4045:            cov[3]= agexact*agexact;
                   4046:          for (kk=1; kk<=cptcovage;kk++) {
                   4047:            cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact;
                   4048:          }
                   4049:          out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   4050:                       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   4051:          savm=oldm;
                   4052:          oldm=newm;
                   4053:        } /* end mult */
                   4054:       
                   4055:        s1=s[mw[mi][i]][i];
                   4056:        s2=s[mw[mi+1][i]][i];
                   4057:        bbh=(double)bh[mi][i]/(double)stepm; 
                   4058:        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 */
                   4059:        ipmx +=1;
                   4060:        sw += weight[i];
                   4061:        ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
                   4062:       } /* end of wave */
                   4063:     } /* end of individual */
                   4064:   }  else if(mle==3){  /* exponential inter-extrapolation */
                   4065:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
                   4066:       for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i];
                   4067:       for(mi=1; mi<= wav[i]-1; mi++){
                   4068:        for (ii=1;ii<=nlstate+ndeath;ii++)
                   4069:          for (j=1;j<=nlstate+ndeath;j++){
                   4070:            oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   4071:            savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   4072:          }
                   4073:        for(d=0; d<dh[mi][i]; d++){
                   4074:          newm=savm;
                   4075:          agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
                   4076:          cov[2]=agexact;
                   4077:          if(nagesqr==1)
                   4078:            cov[3]= agexact*agexact;
                   4079:          for (kk=1; kk<=cptcovage;kk++) {
                   4080:            cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact;
                   4081:          }
                   4082:          out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   4083:                       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   4084:          savm=oldm;
                   4085:          oldm=newm;
                   4086:        } /* end mult */
                   4087:       
                   4088:        s1=s[mw[mi][i]][i];
                   4089:        s2=s[mw[mi+1][i]][i];
                   4090:        bbh=(double)bh[mi][i]/(double)stepm; 
                   4091:        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 */
                   4092:        ipmx +=1;
                   4093:        sw += weight[i];
                   4094:        ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
                   4095:       } /* end of wave */
                   4096:     } /* end of individual */
                   4097:   }else if (mle==4){  /* ml=4 no inter-extrapolation */
                   4098:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
                   4099:       for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i];
                   4100:       for(mi=1; mi<= wav[i]-1; mi++){
                   4101:        for (ii=1;ii<=nlstate+ndeath;ii++)
                   4102:          for (j=1;j<=nlstate+ndeath;j++){
                   4103:            oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   4104:            savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   4105:          }
                   4106:        for(d=0; d<dh[mi][i]; d++){
                   4107:          newm=savm;
                   4108:          agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
                   4109:          cov[2]=agexact;
                   4110:          if(nagesqr==1)
                   4111:            cov[3]= agexact*agexact;
                   4112:          for (kk=1; kk<=cptcovage;kk++) {
                   4113:            cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact;
                   4114:          }
1.126     brouard  4115:        
1.226     brouard  4116:          out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   4117:                       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   4118:          savm=oldm;
                   4119:          oldm=newm;
                   4120:        } /* end mult */
                   4121:       
                   4122:        s1=s[mw[mi][i]][i];
                   4123:        s2=s[mw[mi+1][i]][i];
                   4124:        if( s2 > nlstate){ 
                   4125:          lli=log(out[s1][s2] - savm[s1][s2]);
                   4126:        } else if  ( s2==-1 ) { /* alive */
                   4127:          for (j=1,survp=0. ; j<=nlstate; j++) 
                   4128:            survp += out[s1][j];
                   4129:          lli= log(survp);
                   4130:        }else{
                   4131:          lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]); /* Original formula */
                   4132:        }
                   4133:        ipmx +=1;
                   4134:        sw += weight[i];
                   4135:        ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
1.126     brouard  4136: /*     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  4137:       } /* end of wave */
                   4138:     } /* end of individual */
                   4139:   }else{  /* ml=5 no inter-extrapolation no jackson =0.8a */
                   4140:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
                   4141:       for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i];
                   4142:       for(mi=1; mi<= wav[i]-1; mi++){
                   4143:        for (ii=1;ii<=nlstate+ndeath;ii++)
                   4144:          for (j=1;j<=nlstate+ndeath;j++){
                   4145:            oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   4146:            savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   4147:          }
                   4148:        for(d=0; d<dh[mi][i]; d++){
                   4149:          newm=savm;
                   4150:          agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
                   4151:          cov[2]=agexact;
                   4152:          if(nagesqr==1)
                   4153:            cov[3]= agexact*agexact;
                   4154:          for (kk=1; kk<=cptcovage;kk++) {
                   4155:            cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact;
                   4156:          }
1.126     brouard  4157:        
1.226     brouard  4158:          out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   4159:                       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   4160:          savm=oldm;
                   4161:          oldm=newm;
                   4162:        } /* end mult */
                   4163:       
                   4164:        s1=s[mw[mi][i]][i];
                   4165:        s2=s[mw[mi+1][i]][i];
                   4166:        lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]); /* Original formula */
                   4167:        ipmx +=1;
                   4168:        sw += weight[i];
                   4169:        ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
                   4170:        /*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]);*/
                   4171:       } /* end of wave */
                   4172:     } /* end of individual */
                   4173:   } /* End of if */
                   4174:   for(k=1,l=0.; k<=nlstate; k++) l += ll[k];
                   4175:   /* printf("l1=%f l2=%f ",ll[1],ll[2]); */
                   4176:   l= l*ipmx/sw; /* To get the same order of magnitude as if weight=1 for every body */
                   4177:   return -l;
1.126     brouard  4178: }
                   4179: 
                   4180: /*************** log-likelihood *************/
                   4181: double funcone( double *x)
                   4182: {
1.228     brouard  4183:   /* Same as func but slower because of a lot of printf and if */
1.335     brouard  4184:   int i, ii, j, k, mi, d, kk, kf=0;
1.228     brouard  4185:   int ioffset=0;
1.131     brouard  4186:   double l, ll[NLSTATEMAX+1], cov[NCOVMAX+1];
1.126     brouard  4187:   double **out;
                   4188:   double lli; /* Individual log likelihood */
                   4189:   double llt;
                   4190:   int s1, s2;
1.228     brouard  4191:   int iv=0, iqv=0, itv=0, iqtv=0 ; /* Index of varying covariate, fixed quantitative cov, time varying covariate, quantitative time varying covariate */
                   4192: 
1.126     brouard  4193:   double bbh, survp;
1.187     brouard  4194:   double agexact;
1.214     brouard  4195:   double agebegin, ageend;
1.126     brouard  4196:   /*extern weight */
                   4197:   /* We are differentiating ll according to initial status */
                   4198:   /*  for (i=1;i<=npar;i++) printf("%f ", x[i]);*/
                   4199:   /*for(i=1;i<imx;i++) 
                   4200:     printf(" %d\n",s[4][i]);
                   4201:   */
                   4202:   cov[1]=1.;
                   4203: 
                   4204:   for(k=1; k<=nlstate; k++) ll[k]=0.;
1.224     brouard  4205:   ioffset=0;
                   4206:   for (i=1,ipmx=0, sw=0.; i<=imx; i++){
1.336   ! brouard  4207:     /* Computes the values of the ncovmodel covariates of the model
        !          4208:        depending if the covariates are fixed or varying (age dependent) and stores them in cov[]
        !          4209:        Then computes with function pmij which return a matrix p[i][j] giving the elementary probability
        !          4210:        to be observed in j being in i according to the model.
        !          4211:     */
1.243     brouard  4212:     /* ioffset=2+nagesqr+cptcovage; */
                   4213:     ioffset=2+nagesqr;
1.232     brouard  4214:     /* Fixed */
1.224     brouard  4215:     /* for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i]; */
1.232     brouard  4216:     /* for (k=1; k<=ncoveff;k++){ /\* Simple and product fixed Dummy covariates without age* products *\/ */
1.335     brouard  4217:     for (kf=1; kf<=ncovf;kf++){ /* Simple and product fixed covariates without age* products *//* Missing values are set to -1 but should be dropped */
                   4218:       cov[ioffset+TvarFind[kf]]=covar[Tvar[TvarFind[kf]]][i];/* V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1, only V1 is fixed (k=6)*/
1.232     brouard  4219: /*    cov[ioffset+TvarFind[1]]=covar[Tvar[TvarFind[1]]][i];  */
                   4220: /*    cov[2+6]=covar[Tvar[6]][i];  */
                   4221: /*    cov[2+6]=covar[2][i]; V2  */
                   4222: /*    cov[TvarFind[2]]=covar[Tvar[TvarFind[2]]][i];  */
                   4223: /*    cov[2+7]=covar[Tvar[7]][i];  */
                   4224: /*    cov[2+7]=covar[7][i]; V7=V1*V2  */
                   4225: /*    cov[TvarFind[3]]=covar[Tvar[TvarFind[3]]][i];  */
                   4226: /*    cov[2+9]=covar[Tvar[9]][i];  */
                   4227: /*    cov[2+9]=covar[1][i]; V1  */
1.225     brouard  4228:     }
1.336   ! brouard  4229:       /* In model V2+V1*V4+age*V3+V3*V2 Tvar[1] is V2, Tvar[2=V1*V4] 
        !          4230:         is 5, Tvar[3=age*V3] should not be computed because of age Tvar[4=V3*V2]=6 
        !          4231:         has been calculated etc */
        !          4232:       /* For an individual i, wav[i] gives the number of effective waves */
        !          4233:       /* We compute the contribution to Likelihood of each effective transition
        !          4234:         mw[mi][i] is real wave of the mi th effectve wave */
        !          4235:       /* Then statuses are computed at each begin and end of an effective wave s1=s[ mw[mi][i] ][i];
        !          4236:         s2=s[mw[mi+1][i]][i];
        !          4237:         And the iv th varying covariate is the cotvar[mw[mi+1][i]][iv][i]
        !          4238:         But if the variable is not in the model TTvar[iv] is the real variable effective in the model:
        !          4239:         meaning that decodemodel should be used cotvar[mw[mi+1][i]][TTvar[iv]][i]
        !          4240:       */
        !          4241:     /* This part may be useless now because everythin should be in covar */
1.232     brouard  4242:     /* for (k=1; k<=nqfveff;k++){ /\* Simple and product fixed Quantitative covariates without age* products *\/ */
                   4243:     /*   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?)*\/ */
                   4244:     /* } */
1.231     brouard  4245:     /* for(iqv=1; iqv <= nqfveff; iqv++){ /\* Quantitative fixed covariates *\/ */
                   4246:     /*   cov[++ioffset]=coqvar[Tvar[iqv]][i]; /\* Only V2 k=6 and V1*V2 7 *\/ */
                   4247:     /* } */
1.225     brouard  4248:     
1.233     brouard  4249: 
                   4250:     for(mi=1; mi<= wav[i]-1; mi++){  /* Varying with waves */
1.232     brouard  4251:     /* Wave varying (but not age varying) */
                   4252:       for(k=1; k <= ncovv ; k++){ /* Varying  covariates (single and product but no age )*/
1.242     brouard  4253:        /* cov[ioffset+TvarVind[k]]=cotvar[mw[mi][i]][Tvar[TvarVind[k]]][i]; */
                   4254:        cov[ioffset+TvarVind[k]]=cotvar[mw[mi][i]][Tvar[TvarVind[k]]-ncovcol-nqv][i];
                   4255:       }
1.232     brouard  4256:       /* for(itv=1; itv <= ntveff; itv++){ /\* Varying dummy covariates (single??)*\/ */
1.242     brouard  4257:       /* iv= Tvar[Tmodelind[ioffset-2-nagesqr-cptcovage+itv]]-ncovcol-nqv; /\* Counting the # varying covariate from 1 to ntveff *\/ */
                   4258:       /* cov[ioffset+iv]=cotvar[mw[mi][i]][iv][i]; */
                   4259:       /* k=ioffset-2-nagesqr-cptcovage+itv; /\* position in simple model *\/ */
                   4260:       /* cov[ioffset+itv]=cotvar[mw[mi][i]][TmodelInvind[itv]][i]; */
                   4261:       /* 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  4262:       /* for(iqtv=1; iqtv <= nqtveff; iqtv++){ /\* Varying quantitatives covariates *\/ */
1.242     brouard  4263:       /*       iv=TmodelInvQind[iqtv]; /\* Counting the # varying covariate from 1 to ntveff *\/ */
                   4264:       /*       /\* 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]); *\/ */
                   4265:       /*       cov[ioffset+ntveff+iqtv]=cotqvar[mw[mi][i]][TmodelInvQind[iqtv]][i]; */
1.232     brouard  4266:       /* } */
1.126     brouard  4267:       for (ii=1;ii<=nlstate+ndeath;ii++)
1.242     brouard  4268:        for (j=1;j<=nlstate+ndeath;j++){
                   4269:          oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   4270:          savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   4271:        }
1.214     brouard  4272:       
                   4273:       agebegin=agev[mw[mi][i]][i]; /* Age at beginning of effective wave */
                   4274:       ageend=agev[mw[mi][i]][i] + (dh[mi][i])*stepm/YEARM; /* Age at end of effective wave and at the end of transition */
                   4275:       for(d=0; d<dh[mi][i]; d++){  /* Delay between two effective waves */
1.247     brouard  4276:       /* for(d=0; d<=0; d++){  /\* Delay between two effective waves Only one matrix to speed up*\/ */
1.242     brouard  4277:        /*dh[m][i] or dh[mw[mi][i]][i] is the delay between two effective waves m=mw[mi][i]
                   4278:          and mw[mi+1][i]. dh depends on stepm.*/
                   4279:        newm=savm;
1.247     brouard  4280:        agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;  /* Here d is needed */
1.242     brouard  4281:        cov[2]=agexact;
                   4282:        if(nagesqr==1)
                   4283:          cov[3]= agexact*agexact;
                   4284:        for (kk=1; kk<=cptcovage;kk++) {
                   4285:          if(!FixedV[Tvar[Tage[kk]]])
                   4286:            cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact;
                   4287:          else
                   4288:            cov[Tage[kk]+2+nagesqr]=cotvar[mw[mi][i]][Tvar[Tage[kk]]-ncovcol-nqv][i]*agexact;
                   4289:        }
                   4290:        /* printf("i=%d,mi=%d,d=%d,mw[mi][i]=%d\n",i, mi,d,mw[mi][i]); */
                   4291:        /* savm=pmij(pmmij,cov,ncovmodel,x,nlstate); */
                   4292:        out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   4293:                     1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   4294:        /* out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath, */
                   4295:        /*           1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate)); */
                   4296:        savm=oldm;
                   4297:        oldm=newm;
1.126     brouard  4298:       } /* end mult */
1.336   ! brouard  4299:        /*lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]);*/ /* Original formula */
        !          4300:        /* But now since version 0.9 we anticipate for bias at large stepm.
        !          4301:         * If stepm is larger than one month (smallest stepm) and if the exact delay 
        !          4302:         * (in months) between two waves is not a multiple of stepm, we rounded to 
        !          4303:         * the nearest (and in case of equal distance, to the lowest) interval but now
        !          4304:         * we keep into memory the bias bh[mi][i] and also the previous matrix product
        !          4305:         * (i.e to dh[mi][i]-1) saved in 'savm'. Then we inter(extra)polate the
        !          4306:         * probability in order to take into account the bias as a fraction of the way
        !          4307:                                 * from savm to out if bh is negative or even beyond if bh is positive. bh varies
        !          4308:                                 * -stepm/2 to stepm/2 .
        !          4309:                                 * For stepm=1 the results are the same as for previous versions of Imach.
        !          4310:                                 * For stepm > 1 the results are less biased than in previous versions. 
        !          4311:                                 */
1.126     brouard  4312:       s1=s[mw[mi][i]][i];
                   4313:       s2=s[mw[mi+1][i]][i];
1.217     brouard  4314:       /* if(s2==-1){ */
1.268     brouard  4315:       /*       printf(" ERROR s1=%d, s2=%d i=%d \n", s1, s2, i); */
1.217     brouard  4316:       /*       /\* exit(1); *\/ */
                   4317:       /* } */
1.126     brouard  4318:       bbh=(double)bh[mi][i]/(double)stepm; 
                   4319:       /* bias is positive if real duration
                   4320:        * is higher than the multiple of stepm and negative otherwise.
                   4321:        */
                   4322:       if( s2 > nlstate && (mle <5) ){  /* Jackson */
1.242     brouard  4323:        lli=log(out[s1][s2] - savm[s1][s2]);
1.216     brouard  4324:       } else if  ( s2==-1 ) { /* alive */
1.242     brouard  4325:        for (j=1,survp=0. ; j<=nlstate; j++) 
                   4326:          survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
                   4327:        lli= log(survp);
1.126     brouard  4328:       }else if (mle==1){
1.242     brouard  4329:        lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */
1.126     brouard  4330:       } else if(mle==2){
1.242     brouard  4331:        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  4332:       } else if(mle==3){  /* exponential inter-extrapolation */
1.242     brouard  4333:        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  4334:       } else if (mle==4){  /* mle=4 no inter-extrapolation */
1.242     brouard  4335:        lli=log(out[s1][s2]); /* Original formula */
1.136     brouard  4336:       } else{  /* mle=0 back to 1 */
1.242     brouard  4337:        lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */
                   4338:        /*lli=log(out[s1][s2]); */ /* Original formula */
1.126     brouard  4339:       } /* End of if */
                   4340:       ipmx +=1;
                   4341:       sw += weight[i];
                   4342:       ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
1.335     brouard  4343:       /* printf("Funcone 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],(s2==-1? -1: out[s1][s2]),(s2==-1? -1: savm[s1][s2])); */
1.126     brouard  4344:       if(globpr){
1.246     brouard  4345:        fprintf(ficresilk,"%09ld %6.1f %6.1f %6d %2d %2d %2d %2d %3d %15.6f %8.4f %8.3f\
1.126     brouard  4346:  %11.6f %11.6f %11.6f ", \
1.242     brouard  4347:                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  4348:                2*weight[i]*lli,(s2==-1? -1: out[s1][s2]),(s2==-1? -1: savm[s1][s2]));
1.335     brouard  4349:  /*    printf("%09ld %6.1f %6.1f %6d %2d %2d %2d %2d %3d %15.6f %8.4f %8.3f\ */
                   4350:  /* %11.6f %11.6f %11.6f ", \ */
                   4351:  /*            num[i], agebegin, ageend, i,s1,s2,mi,mw[mi][i],dh[mi][i],exp(lli),weight[i],weight[i]*gipmx/gsw, */
                   4352:  /*            2*weight[i]*lli,(s2==-1? -1: out[s1][s2]),(s2==-1? -1: savm[s1][s2])); */
1.242     brouard  4353:        for(k=1,llt=0.,l=0.; k<=nlstate; k++){
                   4354:          llt +=ll[k]*gipmx/gsw;
                   4355:          fprintf(ficresilk," %10.6f",-ll[k]*gipmx/gsw);
1.335     brouard  4356:          /* printf(" %10.6f",-ll[k]*gipmx/gsw); */
1.242     brouard  4357:        }
                   4358:        fprintf(ficresilk," %10.6f\n", -llt);
1.335     brouard  4359:        /* printf(" %10.6f\n", -llt); */
1.126     brouard  4360:       }
1.335     brouard  4361:     } /* end of wave */
                   4362:   } /* end of individual */
                   4363:   for(k=1,l=0.; k<=nlstate; k++) l += ll[k];
1.232     brouard  4364: /* printf("l1=%f l2=%f ",ll[1],ll[2]); */
1.335     brouard  4365:   l= l*ipmx/sw; /* To get the same order of magnitude as if weight=1 for every body */
                   4366:   if(globpr==0){ /* First time we count the contributions and weights */
                   4367:     gipmx=ipmx;
                   4368:     gsw=sw;
                   4369:   }
1.232     brouard  4370: return -l;
1.126     brouard  4371: }
                   4372: 
                   4373: 
                   4374: /*************** function likelione ***********/
1.292     brouard  4375: void likelione(FILE *ficres,double p[], int npar, int nlstate, int *globpri, long *ipmx, double *sw, double *fretone, double (*func)(double []))
1.126     brouard  4376: {
                   4377:   /* This routine should help understanding what is done with 
                   4378:      the selection of individuals/waves and
                   4379:      to check the exact contribution to the likelihood.
                   4380:      Plotting could be done.
                   4381:    */
                   4382:   int k;
                   4383: 
                   4384:   if(*globpri !=0){ /* Just counts and sums, no printings */
1.201     brouard  4385:     strcpy(fileresilk,"ILK_"); 
1.202     brouard  4386:     strcat(fileresilk,fileresu);
1.126     brouard  4387:     if((ficresilk=fopen(fileresilk,"w"))==NULL) {
                   4388:       printf("Problem with resultfile: %s\n", fileresilk);
                   4389:       fprintf(ficlog,"Problem with resultfile: %s\n", fileresilk);
                   4390:     }
1.214     brouard  4391:     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");
                   4392:     fprintf(ficresilk, "#num_i ageb agend i s1 s2 mi mw dh likeli weight %%weight 2wlli out sav ");
1.126     brouard  4393:     /*         i,s1,s2,mi,mw[mi][i],dh[mi][i],exp(lli),weight[i],2*weight[i]*lli,out[s1][s2],savm[s1][s2]); */
                   4394:     for(k=1; k<=nlstate; k++) 
                   4395:       fprintf(ficresilk," -2*gipw/gsw*weight*ll[%d]++",k);
                   4396:     fprintf(ficresilk," -2*gipw/gsw*weight*ll(total)\n");
                   4397:   }
                   4398: 
1.292     brouard  4399:   *fretone=(*func)(p);
1.126     brouard  4400:   if(*globpri !=0){
                   4401:     fclose(ficresilk);
1.205     brouard  4402:     if (mle ==0)
                   4403:       fprintf(fichtm,"\n<br>File of contributions to the likelihood computed with initial parameters and mle = %d.",mle);
                   4404:     else if(mle >=1)
                   4405:       fprintf(fichtm,"\n<br>File of contributions to the likelihood computed with optimized parameters mle = %d.",mle);
                   4406:     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  4407:     fprintf(fichtm,"\n<br>Equation of the model: <b>model=1+age+%s</b><br>\n",model); 
1.208     brouard  4408:       
                   4409:     for (k=1; k<= nlstate ; k++) {
1.211     brouard  4410:       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  4411: <img src=\"%s-p%dj.png\">",k,k,subdirf2(optionfilefiname,"ILK_"),k,subdirf2(optionfilefiname,"ILK_"),k,subdirf2(optionfilefiname,"ILK_"),k);
                   4412:     }
1.207     brouard  4413:     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  4414: <img src=\"%s-ori.png\">",subdirf2(optionfilefiname,"ILK_"),subdirf2(optionfilefiname,"ILK_"),subdirf2(optionfilefiname,"ILK_"));
1.207     brouard  4415:     fprintf(fichtm,"<br>- and by state of destination <a href=\"%s-dest.png\">%s-dest.png</a><br> \
1.204     brouard  4416: <img src=\"%s-dest.png\">",subdirf2(optionfilefiname,"ILK_"),subdirf2(optionfilefiname,"ILK_"),subdirf2(optionfilefiname,"ILK_"));
1.207     brouard  4417:     fflush(fichtm);
1.205     brouard  4418:   }
1.126     brouard  4419:   return;
                   4420: }
                   4421: 
                   4422: 
                   4423: /*********** Maximum Likelihood Estimation ***************/
                   4424: 
                   4425: void mlikeli(FILE *ficres,double p[], int npar, int ncovmodel, int nlstate, double ftol, double (*func)(double []))
                   4426: {
1.319     brouard  4427:   int i,j,k, jk, jkk=0, iter=0;
1.126     brouard  4428:   double **xi;
                   4429:   double fret;
                   4430:   double fretone; /* Only one call to likelihood */
                   4431:   /*  char filerespow[FILENAMELENGTH];*/
1.162     brouard  4432: 
                   4433: #ifdef NLOPT
                   4434:   int creturn;
                   4435:   nlopt_opt opt;
                   4436:   /* double lb[9] = { -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL }; /\* lower bounds *\/ */
                   4437:   double *lb;
                   4438:   double minf; /* the minimum objective value, upon return */
                   4439:   double * p1; /* Shifted parameters from 0 instead of 1 */
                   4440:   myfunc_data dinst, *d = &dinst;
                   4441: #endif
                   4442: 
                   4443: 
1.126     brouard  4444:   xi=matrix(1,npar,1,npar);
                   4445:   for (i=1;i<=npar;i++)
                   4446:     for (j=1;j<=npar;j++)
                   4447:       xi[i][j]=(i==j ? 1.0 : 0.0);
                   4448:   printf("Powell\n");  fprintf(ficlog,"Powell\n");
1.201     brouard  4449:   strcpy(filerespow,"POW_"); 
1.126     brouard  4450:   strcat(filerespow,fileres);
                   4451:   if((ficrespow=fopen(filerespow,"w"))==NULL) {
                   4452:     printf("Problem with resultfile: %s\n", filerespow);
                   4453:     fprintf(ficlog,"Problem with resultfile: %s\n", filerespow);
                   4454:   }
                   4455:   fprintf(ficrespow,"# Powell\n# iter -2*LL");
                   4456:   for (i=1;i<=nlstate;i++)
                   4457:     for(j=1;j<=nlstate+ndeath;j++)
                   4458:       if(j!=i)fprintf(ficrespow," p%1d%1d",i,j);
                   4459:   fprintf(ficrespow,"\n");
1.162     brouard  4460: #ifdef POWELL
1.319     brouard  4461: #ifdef LINMINORIGINAL
                   4462: #else /* LINMINORIGINAL */
                   4463:   
                   4464:   flatdir=ivector(1,npar); 
                   4465:   for (j=1;j<=npar;j++) flatdir[j]=0; 
                   4466: #endif /*LINMINORIGINAL */
                   4467: 
                   4468: #ifdef FLATSUP
                   4469:   powell(p,xi,npar,ftol,&iter,&fret,flatdir,func);
                   4470:   /* reorganizing p by suppressing flat directions */
                   4471:   for(i=1, jk=1; i <=nlstate; i++){
                   4472:     for(k=1; k <=(nlstate+ndeath); k++){
                   4473:       if (k != i) {
                   4474:         printf("%d%d flatdir[%d]=%d",i,k,jk, flatdir[jk]);
                   4475:         if(flatdir[jk]==1){
                   4476:           printf(" To be skipped %d%d flatdir[%d]=%d ",i,k,jk, flatdir[jk]);
                   4477:         }
                   4478:         for(j=1; j <=ncovmodel; j++){
                   4479:           printf("%12.7f ",p[jk]);
                   4480:           jk++; 
                   4481:         }
                   4482:         printf("\n");
                   4483:       }
                   4484:     }
                   4485:   }
                   4486: /* skipping */
                   4487:   /* for(i=1, jk=1, jkk=1;(flatdir[jk]==0)&& (i <=nlstate); i++){ */
                   4488:   for(i=1, jk=1, jkk=1;i <=nlstate; i++){
                   4489:     for(k=1; k <=(nlstate+ndeath); k++){
                   4490:       if (k != i) {
                   4491:         printf("%d%d flatdir[%d]=%d",i,k,jk, flatdir[jk]);
                   4492:         if(flatdir[jk]==1){
                   4493:           printf(" To be skipped %d%d flatdir[%d]=%d jk=%d p[%d] ",i,k,jk, flatdir[jk],jk, jk);
                   4494:           for(j=1; j <=ncovmodel;  jk++,j++){
                   4495:             printf(" p[%d]=%12.7f",jk, p[jk]);
                   4496:             /*q[jjk]=p[jk];*/
                   4497:           }
                   4498:         }else{
                   4499:           printf(" To be kept %d%d flatdir[%d]=%d jk=%d q[%d]=p[%d] ",i,k,jk, flatdir[jk],jk, jkk, jk);
                   4500:           for(j=1; j <=ncovmodel;  jk++,jkk++,j++){
                   4501:             printf(" p[%d]=%12.7f=q[%d]",jk, p[jk],jkk);
                   4502:             /*q[jjk]=p[jk];*/
                   4503:           }
                   4504:         }
                   4505:         printf("\n");
                   4506:       }
                   4507:       fflush(stdout);
                   4508:     }
                   4509:   }
                   4510:   powell(p,xi,npar,ftol,&iter,&fret,flatdir,func);
                   4511: #else  /* FLATSUP */
1.126     brouard  4512:   powell(p,xi,npar,ftol,&iter,&fret,func);
1.319     brouard  4513: #endif  /* FLATSUP */
                   4514: 
                   4515: #ifdef LINMINORIGINAL
                   4516: #else
                   4517:       free_ivector(flatdir,1,npar); 
                   4518: #endif  /* LINMINORIGINAL*/
                   4519: #endif /* POWELL */
1.126     brouard  4520: 
1.162     brouard  4521: #ifdef NLOPT
                   4522: #ifdef NEWUOA
                   4523:   opt = nlopt_create(NLOPT_LN_NEWUOA,npar);
                   4524: #else
                   4525:   opt = nlopt_create(NLOPT_LN_BOBYQA,npar);
                   4526: #endif
                   4527:   lb=vector(0,npar-1);
                   4528:   for (i=0;i<npar;i++) lb[i]= -HUGE_VAL;
                   4529:   nlopt_set_lower_bounds(opt, lb);
                   4530:   nlopt_set_initial_step1(opt, 0.1);
                   4531:   
                   4532:   p1= (p+1); /*  p *(p+1)@8 and p *(p1)@8 are equal p1[0]=p[1] */
                   4533:   d->function = func;
                   4534:   printf(" Func %.12lf \n",myfunc(npar,p1,NULL,d));
                   4535:   nlopt_set_min_objective(opt, myfunc, d);
                   4536:   nlopt_set_xtol_rel(opt, ftol);
                   4537:   if ((creturn=nlopt_optimize(opt, p1, &minf)) < 0) {
                   4538:     printf("nlopt failed! %d\n",creturn); 
                   4539:   }
                   4540:   else {
                   4541:     printf("found minimum after %d evaluations (NLOPT=%d)\n", countcallfunc ,NLOPT);
                   4542:     printf("found minimum at f(%g,%g) = %0.10g\n", p[0], p[1], minf);
                   4543:     iter=1; /* not equal */
                   4544:   }
                   4545:   nlopt_destroy(opt);
                   4546: #endif
1.319     brouard  4547: #ifdef FLATSUP
                   4548:   /* npared = npar -flatd/ncovmodel; */
                   4549:   /* xired= matrix(1,npared,1,npared); */
                   4550:   /* paramred= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel); */
                   4551:   /* powell(pred,xired,npared,ftol,&iter,&fret,flatdir,func); */
                   4552:   /* free_matrix(xire,1,npared,1,npared); */
                   4553: #else  /* FLATSUP */
                   4554: #endif /* FLATSUP */
1.126     brouard  4555:   free_matrix(xi,1,npar,1,npar);
                   4556:   fclose(ficrespow);
1.203     brouard  4557:   printf("\n#Number of iterations & function calls = %d & %d, -2 Log likelihood = %.12f\n",iter, countcallfunc,func(p));
                   4558:   fprintf(ficlog,"\n#Number of iterations & function calls = %d & %d, -2 Log likelihood = %.12f\n",iter, countcallfunc,func(p));
1.180     brouard  4559:   fprintf(ficres,"#Number of iterations & function calls = %d & %d, -2 Log likelihood = %.12f\n",iter, countcallfunc,func(p));
1.126     brouard  4560: 
                   4561: }
                   4562: 
                   4563: /**** Computes Hessian and covariance matrix ***/
1.203     brouard  4564: void hesscov(double **matcov, double **hess, double p[], int npar, double delti[], double ftolhess, double (*func)(double []))
1.126     brouard  4565: {
                   4566:   double  **a,**y,*x,pd;
1.203     brouard  4567:   /* double **hess; */
1.164     brouard  4568:   int i, j;
1.126     brouard  4569:   int *indx;
                   4570: 
                   4571:   double hessii(double p[], double delta, int theta, double delti[],double (*func)(double []),int npar);
1.203     brouard  4572:   double hessij(double p[], double **hess, double delti[], int i, int j,double (*func)(double []),int npar);
1.126     brouard  4573:   void lubksb(double **a, int npar, int *indx, double b[]) ;
                   4574:   void ludcmp(double **a, int npar, int *indx, double *d) ;
                   4575:   double gompertz(double p[]);
1.203     brouard  4576:   /* hess=matrix(1,npar,1,npar); */
1.126     brouard  4577: 
                   4578:   printf("\nCalculation of the hessian matrix. Wait...\n");
                   4579:   fprintf(ficlog,"\nCalculation of the hessian matrix. Wait...\n");
                   4580:   for (i=1;i<=npar;i++){
1.203     brouard  4581:     printf("%d-",i);fflush(stdout);
                   4582:     fprintf(ficlog,"%d-",i);fflush(ficlog);
1.126     brouard  4583:    
                   4584:      hess[i][i]=hessii(p,ftolhess,i,delti,func,npar);
                   4585:     
                   4586:     /*  printf(" %f ",p[i]);
                   4587:        printf(" %lf %lf %lf",hess[i][i],ftolhess,delti[i]);*/
                   4588:   }
                   4589:   
                   4590:   for (i=1;i<=npar;i++) {
                   4591:     for (j=1;j<=npar;j++)  {
                   4592:       if (j>i) { 
1.203     brouard  4593:        printf(".%d-%d",i,j);fflush(stdout);
                   4594:        fprintf(ficlog,".%d-%d",i,j);fflush(ficlog);
                   4595:        hess[i][j]=hessij(p,hess, delti,i,j,func,npar);
1.126     brouard  4596:        
                   4597:        hess[j][i]=hess[i][j];    
                   4598:        /*printf(" %lf ",hess[i][j]);*/
                   4599:       }
                   4600:     }
                   4601:   }
                   4602:   printf("\n");
                   4603:   fprintf(ficlog,"\n");
                   4604: 
                   4605:   printf("\nInverting the hessian to get the covariance matrix. Wait...\n");
                   4606:   fprintf(ficlog,"\nInverting the hessian to get the covariance matrix. Wait...\n");
                   4607:   
                   4608:   a=matrix(1,npar,1,npar);
                   4609:   y=matrix(1,npar,1,npar);
                   4610:   x=vector(1,npar);
                   4611:   indx=ivector(1,npar);
                   4612:   for (i=1;i<=npar;i++)
                   4613:     for (j=1;j<=npar;j++) a[i][j]=hess[i][j];
                   4614:   ludcmp(a,npar,indx,&pd);
                   4615: 
                   4616:   for (j=1;j<=npar;j++) {
                   4617:     for (i=1;i<=npar;i++) x[i]=0;
                   4618:     x[j]=1;
                   4619:     lubksb(a,npar,indx,x);
                   4620:     for (i=1;i<=npar;i++){ 
                   4621:       matcov[i][j]=x[i];
                   4622:     }
                   4623:   }
                   4624: 
                   4625:   printf("\n#Hessian matrix#\n");
                   4626:   fprintf(ficlog,"\n#Hessian matrix#\n");
                   4627:   for (i=1;i<=npar;i++) { 
                   4628:     for (j=1;j<=npar;j++) { 
1.203     brouard  4629:       printf("%.6e ",hess[i][j]);
                   4630:       fprintf(ficlog,"%.6e ",hess[i][j]);
1.126     brouard  4631:     }
                   4632:     printf("\n");
                   4633:     fprintf(ficlog,"\n");
                   4634:   }
                   4635: 
1.203     brouard  4636:   /* printf("\n#Covariance matrix#\n"); */
                   4637:   /* fprintf(ficlog,"\n#Covariance matrix#\n"); */
                   4638:   /* for (i=1;i<=npar;i++) {  */
                   4639:   /*   for (j=1;j<=npar;j++) {  */
                   4640:   /*     printf("%.6e ",matcov[i][j]); */
                   4641:   /*     fprintf(ficlog,"%.6e ",matcov[i][j]); */
                   4642:   /*   } */
                   4643:   /*   printf("\n"); */
                   4644:   /*   fprintf(ficlog,"\n"); */
                   4645:   /* } */
                   4646: 
1.126     brouard  4647:   /* Recompute Inverse */
1.203     brouard  4648:   /* for (i=1;i<=npar;i++) */
                   4649:   /*   for (j=1;j<=npar;j++) a[i][j]=matcov[i][j]; */
                   4650:   /* ludcmp(a,npar,indx,&pd); */
                   4651: 
                   4652:   /*  printf("\n#Hessian matrix recomputed#\n"); */
                   4653: 
                   4654:   /* for (j=1;j<=npar;j++) { */
                   4655:   /*   for (i=1;i<=npar;i++) x[i]=0; */
                   4656:   /*   x[j]=1; */
                   4657:   /*   lubksb(a,npar,indx,x); */
                   4658:   /*   for (i=1;i<=npar;i++){  */
                   4659:   /*     y[i][j]=x[i]; */
                   4660:   /*     printf("%.3e ",y[i][j]); */
                   4661:   /*     fprintf(ficlog,"%.3e ",y[i][j]); */
                   4662:   /*   } */
                   4663:   /*   printf("\n"); */
                   4664:   /*   fprintf(ficlog,"\n"); */
                   4665:   /* } */
                   4666: 
                   4667:   /* Verifying the inverse matrix */
                   4668: #ifdef DEBUGHESS
                   4669:   y=matprod2(y,hess,1,npar,1,npar,1,npar,matcov);
1.126     brouard  4670: 
1.203     brouard  4671:    printf("\n#Verification: multiplying the matrix of covariance by the Hessian matrix, should be unity:#\n");
                   4672:    fprintf(ficlog,"\n#Verification: multiplying the matrix of covariance by the Hessian matrix. Should be unity:#\n");
1.126     brouard  4673: 
                   4674:   for (j=1;j<=npar;j++) {
                   4675:     for (i=1;i<=npar;i++){ 
1.203     brouard  4676:       printf("%.2f ",y[i][j]);
                   4677:       fprintf(ficlog,"%.2f ",y[i][j]);
1.126     brouard  4678:     }
                   4679:     printf("\n");
                   4680:     fprintf(ficlog,"\n");
                   4681:   }
1.203     brouard  4682: #endif
1.126     brouard  4683: 
                   4684:   free_matrix(a,1,npar,1,npar);
                   4685:   free_matrix(y,1,npar,1,npar);
                   4686:   free_vector(x,1,npar);
                   4687:   free_ivector(indx,1,npar);
1.203     brouard  4688:   /* free_matrix(hess,1,npar,1,npar); */
1.126     brouard  4689: 
                   4690: 
                   4691: }
                   4692: 
                   4693: /*************** hessian matrix ****************/
                   4694: double hessii(double x[], double delta, int theta, double delti[], double (*func)(double []), int npar)
1.203     brouard  4695: { /* Around values of x, computes the function func and returns the scales delti and hessian */
1.126     brouard  4696:   int i;
                   4697:   int l=1, lmax=20;
1.203     brouard  4698:   double k1,k2, res, fx;
1.132     brouard  4699:   double p2[MAXPARM+1]; /* identical to x */
1.126     brouard  4700:   double delt=0.0001, delts, nkhi=10.,nkhif=1., khi=1.e-4;
                   4701:   int k=0,kmax=10;
                   4702:   double l1;
                   4703: 
                   4704:   fx=func(x);
                   4705:   for (i=1;i<=npar;i++) p2[i]=x[i];
1.145     brouard  4706:   for(l=0 ; l <=lmax; l++){  /* Enlarging the zone around the Maximum */
1.126     brouard  4707:     l1=pow(10,l);
                   4708:     delts=delt;
                   4709:     for(k=1 ; k <kmax; k=k+1){
                   4710:       delt = delta*(l1*k);
                   4711:       p2[theta]=x[theta] +delt;
1.145     brouard  4712:       k1=func(p2)-fx;   /* Might be negative if too close to the theoretical maximum */
1.126     brouard  4713:       p2[theta]=x[theta]-delt;
                   4714:       k2=func(p2)-fx;
                   4715:       /*res= (k1-2.0*fx+k2)/delt/delt; */
1.203     brouard  4716:       res= (k1+k2)/delt/delt/2.; /* Divided by 2 because L and not 2*L */
1.126     brouard  4717:       
1.203     brouard  4718: #ifdef DEBUGHESSII
1.126     brouard  4719:       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);
                   4720:       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);
                   4721: #endif
                   4722:       /*if(fabs(k1-2.0*fx+k2) <1.e-13){ */
                   4723:       if((k1 <khi/nkhi/2.) || (k2 <khi/nkhi/2.)){
                   4724:        k=kmax;
                   4725:       }
                   4726:       else if((k1 >khi/nkhif) || (k2 >khi/nkhif)){ /* Keeps lastvalue before 3.84/2 KHI2 5% 1d.f. */
1.164     brouard  4727:        k=kmax; l=lmax*10;
1.126     brouard  4728:       }
                   4729:       else if((k1 >khi/nkhi) || (k2 >khi/nkhi)){ 
                   4730:        delts=delt;
                   4731:       }
1.203     brouard  4732:     } /* End loop k */
1.126     brouard  4733:   }
                   4734:   delti[theta]=delts;
                   4735:   return res; 
                   4736:   
                   4737: }
                   4738: 
1.203     brouard  4739: double hessij( double x[], double **hess, double delti[], int thetai,int thetaj,double (*func)(double []),int npar)
1.126     brouard  4740: {
                   4741:   int i;
1.164     brouard  4742:   int l=1, lmax=20;
1.126     brouard  4743:   double k1,k2,k3,k4,res,fx;
1.132     brouard  4744:   double p2[MAXPARM+1];
1.203     brouard  4745:   int k, kmax=1;
                   4746:   double v1, v2, cv12, lc1, lc2;
1.208     brouard  4747: 
                   4748:   int firstime=0;
1.203     brouard  4749:   
1.126     brouard  4750:   fx=func(x);
1.203     brouard  4751:   for (k=1; k<=kmax; k=k+10) {
1.126     brouard  4752:     for (i=1;i<=npar;i++) p2[i]=x[i];
1.203     brouard  4753:     p2[thetai]=x[thetai]+delti[thetai]*k;
                   4754:     p2[thetaj]=x[thetaj]+delti[thetaj]*k;
1.126     brouard  4755:     k1=func(p2)-fx;
                   4756:   
1.203     brouard  4757:     p2[thetai]=x[thetai]+delti[thetai]*k;
                   4758:     p2[thetaj]=x[thetaj]-delti[thetaj]*k;
1.126     brouard  4759:     k2=func(p2)-fx;
                   4760:   
1.203     brouard  4761:     p2[thetai]=x[thetai]-delti[thetai]*k;
                   4762:     p2[thetaj]=x[thetaj]+delti[thetaj]*k;
1.126     brouard  4763:     k3=func(p2)-fx;
                   4764:   
1.203     brouard  4765:     p2[thetai]=x[thetai]-delti[thetai]*k;
                   4766:     p2[thetaj]=x[thetaj]-delti[thetaj]*k;
1.126     brouard  4767:     k4=func(p2)-fx;
1.203     brouard  4768:     res=(k1-k2-k3+k4)/4.0/delti[thetai]/k/delti[thetaj]/k/2.; /* Because of L not 2*L */
                   4769:     if(k1*k2*k3*k4 <0.){
1.208     brouard  4770:       firstime=1;
1.203     brouard  4771:       kmax=kmax+10;
1.208     brouard  4772:     }
                   4773:     if(kmax >=10 || firstime ==1){
1.246     brouard  4774:       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);
                   4775:       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  4776:       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);
                   4777:       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);
                   4778:     }
                   4779: #ifdef DEBUGHESSIJ
                   4780:     v1=hess[thetai][thetai];
                   4781:     v2=hess[thetaj][thetaj];
                   4782:     cv12=res;
                   4783:     /* Computing eigen value of Hessian matrix */
                   4784:     lc1=((v1+v2)+sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
                   4785:     lc2=((v1+v2)-sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
                   4786:     if ((lc2 <0) || (lc1 <0) ){
                   4787:       printf("Warning: sub Hessian matrix '%d%d' does not have positive eigen values \n",thetai,thetaj);
                   4788:       fprintf(ficlog, "Warning: sub Hessian matrix '%d%d' does not have positive eigen values \n",thetai,thetaj);
                   4789:       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);
                   4790:       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);
                   4791:     }
1.126     brouard  4792: #endif
                   4793:   }
                   4794:   return res;
                   4795: }
                   4796: 
1.203     brouard  4797:     /* Not done yet: Was supposed to fix if not exactly at the maximum */
                   4798: /* double hessij( double x[], double delti[], int thetai,int thetaj,double (*func)(double []),int npar) */
                   4799: /* { */
                   4800: /*   int i; */
                   4801: /*   int l=1, lmax=20; */
                   4802: /*   double k1,k2,k3,k4,res,fx; */
                   4803: /*   double p2[MAXPARM+1]; */
                   4804: /*   double delt=0.0001, delts, nkhi=10.,nkhif=1., khi=1.e-4; */
                   4805: /*   int k=0,kmax=10; */
                   4806: /*   double l1; */
                   4807:   
                   4808: /*   fx=func(x); */
                   4809: /*   for(l=0 ; l <=lmax; l++){  /\* Enlarging the zone around the Maximum *\/ */
                   4810: /*     l1=pow(10,l); */
                   4811: /*     delts=delt; */
                   4812: /*     for(k=1 ; k <kmax; k=k+1){ */
                   4813: /*       delt = delti*(l1*k); */
                   4814: /*       for (i=1;i<=npar;i++) p2[i]=x[i]; */
                   4815: /*       p2[thetai]=x[thetai]+delti[thetai]/k; */
                   4816: /*       p2[thetaj]=x[thetaj]+delti[thetaj]/k; */
                   4817: /*       k1=func(p2)-fx; */
                   4818:       
                   4819: /*       p2[thetai]=x[thetai]+delti[thetai]/k; */
                   4820: /*       p2[thetaj]=x[thetaj]-delti[thetaj]/k; */
                   4821: /*       k2=func(p2)-fx; */
                   4822:       
                   4823: /*       p2[thetai]=x[thetai]-delti[thetai]/k; */
                   4824: /*       p2[thetaj]=x[thetaj]+delti[thetaj]/k; */
                   4825: /*       k3=func(p2)-fx; */
                   4826:       
                   4827: /*       p2[thetai]=x[thetai]-delti[thetai]/k; */
                   4828: /*       p2[thetaj]=x[thetaj]-delti[thetaj]/k; */
                   4829: /*       k4=func(p2)-fx; */
                   4830: /*       res=(k1-k2-k3+k4)/4.0/delti[thetai]*k/delti[thetaj]*k/2.; /\* Because of L not 2*L *\/ */
                   4831: /* #ifdef DEBUGHESSIJ */
                   4832: /*       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); */
                   4833: /*       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); */
                   4834: /* #endif */
                   4835: /*       if((k1 <khi/nkhi/2.) || (k2 <khi/nkhi/2.)|| (k4 <khi/nkhi/2.)|| (k4 <khi/nkhi/2.)){ */
                   4836: /*     k=kmax; */
                   4837: /*       } */
                   4838: /*       else if((k1 >khi/nkhif) || (k2 >khi/nkhif) || (k4 >khi/nkhif) || (k4 >khi/nkhif)){ /\* Keeps lastvalue before 3.84/2 KHI2 5% 1d.f. *\/ */
                   4839: /*     k=kmax; l=lmax*10; */
                   4840: /*       } */
                   4841: /*       else if((k1 >khi/nkhi) || (k2 >khi/nkhi)){  */
                   4842: /*     delts=delt; */
                   4843: /*       } */
                   4844: /*     } /\* End loop k *\/ */
                   4845: /*   } */
                   4846: /*   delti[theta]=delts; */
                   4847: /*   return res;  */
                   4848: /* } */
                   4849: 
                   4850: 
1.126     brouard  4851: /************** Inverse of matrix **************/
                   4852: void ludcmp(double **a, int n, int *indx, double *d) 
                   4853: { 
                   4854:   int i,imax,j,k; 
                   4855:   double big,dum,sum,temp; 
                   4856:   double *vv; 
                   4857:  
                   4858:   vv=vector(1,n); 
                   4859:   *d=1.0; 
                   4860:   for (i=1;i<=n;i++) { 
                   4861:     big=0.0; 
                   4862:     for (j=1;j<=n;j++) 
                   4863:       if ((temp=fabs(a[i][j])) > big) big=temp; 
1.256     brouard  4864:     if (big == 0.0){
                   4865:       printf(" Singular Hessian matrix at row %d:\n",i);
                   4866:       for (j=1;j<=n;j++) {
                   4867:        printf(" a[%d][%d]=%f,",i,j,a[i][j]);
                   4868:        fprintf(ficlog," a[%d][%d]=%f,",i,j,a[i][j]);
                   4869:       }
                   4870:       fflush(ficlog);
                   4871:       fclose(ficlog);
                   4872:       nrerror("Singular matrix in routine ludcmp"); 
                   4873:     }
1.126     brouard  4874:     vv[i]=1.0/big; 
                   4875:   } 
                   4876:   for (j=1;j<=n;j++) { 
                   4877:     for (i=1;i<j;i++) { 
                   4878:       sum=a[i][j]; 
                   4879:       for (k=1;k<i;k++) sum -= a[i][k]*a[k][j]; 
                   4880:       a[i][j]=sum; 
                   4881:     } 
                   4882:     big=0.0; 
                   4883:     for (i=j;i<=n;i++) { 
                   4884:       sum=a[i][j]; 
                   4885:       for (k=1;k<j;k++) 
                   4886:        sum -= a[i][k]*a[k][j]; 
                   4887:       a[i][j]=sum; 
                   4888:       if ( (dum=vv[i]*fabs(sum)) >= big) { 
                   4889:        big=dum; 
                   4890:        imax=i; 
                   4891:       } 
                   4892:     } 
                   4893:     if (j != imax) { 
                   4894:       for (k=1;k<=n;k++) { 
                   4895:        dum=a[imax][k]; 
                   4896:        a[imax][k]=a[j][k]; 
                   4897:        a[j][k]=dum; 
                   4898:       } 
                   4899:       *d = -(*d); 
                   4900:       vv[imax]=vv[j]; 
                   4901:     } 
                   4902:     indx[j]=imax; 
                   4903:     if (a[j][j] == 0.0) a[j][j]=TINY; 
                   4904:     if (j != n) { 
                   4905:       dum=1.0/(a[j][j]); 
                   4906:       for (i=j+1;i<=n;i++) a[i][j] *= dum; 
                   4907:     } 
                   4908:   } 
                   4909:   free_vector(vv,1,n);  /* Doesn't work */
                   4910: ;
                   4911: } 
                   4912: 
                   4913: void lubksb(double **a, int n, int *indx, double b[]) 
                   4914: { 
                   4915:   int i,ii=0,ip,j; 
                   4916:   double sum; 
                   4917:  
                   4918:   for (i=1;i<=n;i++) { 
                   4919:     ip=indx[i]; 
                   4920:     sum=b[ip]; 
                   4921:     b[ip]=b[i]; 
                   4922:     if (ii) 
                   4923:       for (j=ii;j<=i-1;j++) sum -= a[i][j]*b[j]; 
                   4924:     else if (sum) ii=i; 
                   4925:     b[i]=sum; 
                   4926:   } 
                   4927:   for (i=n;i>=1;i--) { 
                   4928:     sum=b[i]; 
                   4929:     for (j=i+1;j<=n;j++) sum -= a[i][j]*b[j]; 
                   4930:     b[i]=sum/a[i][i]; 
                   4931:   } 
                   4932: } 
                   4933: 
                   4934: void pstamp(FILE *fichier)
                   4935: {
1.196     brouard  4936:   fprintf(fichier,"# %s.%s\n#IMaCh version %s, %s\n#%s\n# %s", optionfilefiname,optionfilext,version,copyright, fullversion, strstart);
1.126     brouard  4937: }
                   4938: 
1.297     brouard  4939: void date2dmy(double date,double *day, double *month, double *year){
                   4940:   double yp=0., yp1=0., yp2=0.;
                   4941:   
                   4942:   yp1=modf(date,&yp);/* extracts integral of date in yp  and
                   4943:                        fractional in yp1 */
                   4944:   *year=yp;
                   4945:   yp2=modf((yp1*12),&yp);
                   4946:   *month=yp;
                   4947:   yp1=modf((yp2*30.5),&yp);
                   4948:   *day=yp;
                   4949:   if(*day==0) *day=1;
                   4950:   if(*month==0) *month=1;
                   4951: }
                   4952: 
1.253     brouard  4953: 
                   4954: 
1.126     brouard  4955: /************ Frequencies ********************/
1.251     brouard  4956: void  freqsummary(char fileres[], double p[], double pstart[], int iagemin, int iagemax, int **s, double **agev, int nlstate, int imx, \
1.226     brouard  4957:                  int *Tvaraff, int *invalidvarcomb, int **nbcode, int *ncodemax,double **mint,double **anint, char strstart[], \
                   4958:                  int firstpass,  int lastpass, int stepm, int weightopt, char model[])
1.250     brouard  4959: {  /* Some frequencies as well as proposing some starting values */
1.332     brouard  4960:   /* Frequencies of any combination of dummy covariate used in the model equation */ 
1.265     brouard  4961:   int i, m, jk, j1, bool, z1,j, nj, nl, k, iv, jj=0, s1=1, s2=1;
1.226     brouard  4962:   int iind=0, iage=0;
                   4963:   int mi; /* Effective wave */
                   4964:   int first;
                   4965:   double ***freq; /* Frequencies */
1.268     brouard  4966:   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 */
                   4967:   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  4968:   double *meanq, *stdq, *idq;
1.226     brouard  4969:   double **meanqt;
                   4970:   double *pp, **prop, *posprop, *pospropt;
                   4971:   double pos=0., posproptt=0., pospropta=0., k2, dateintsum=0,k2cpt=0;
                   4972:   char fileresp[FILENAMELENGTH], fileresphtm[FILENAMELENGTH], fileresphtmfr[FILENAMELENGTH];
                   4973:   double agebegin, ageend;
                   4974:     
                   4975:   pp=vector(1,nlstate);
1.251     brouard  4976:   prop=matrix(1,nlstate,iagemin-AGEMARGE,iagemax+4+AGEMARGE); 
1.226     brouard  4977:   posprop=vector(1,nlstate); /* Counting the number of transition starting from a live state per age */ 
                   4978:   pospropt=vector(1,nlstate); /* Counting the number of transition starting from a live state */ 
                   4979:   /* prop=matrix(1,nlstate,iagemin,iagemax+3); */
                   4980:   meanq=vector(1,nqfveff); /* Number of Quantitative Fixed Variables Effective */
1.284     brouard  4981:   stdq=vector(1,nqfveff); /* Number of Quantitative Fixed Variables Effective */
1.283     brouard  4982:   idq=vector(1,nqfveff); /* Number of Quantitative Fixed Variables Effective */
1.226     brouard  4983:   meanqt=matrix(1,lastpass,1,nqtveff);
                   4984:   strcpy(fileresp,"P_");
                   4985:   strcat(fileresp,fileresu);
                   4986:   /*strcat(fileresphtm,fileresu);*/
                   4987:   if((ficresp=fopen(fileresp,"w"))==NULL) {
                   4988:     printf("Problem with prevalence resultfile: %s\n", fileresp);
                   4989:     fprintf(ficlog,"Problem with prevalence resultfile: %s\n", fileresp);
                   4990:     exit(0);
                   4991:   }
1.240     brouard  4992:   
1.226     brouard  4993:   strcpy(fileresphtm,subdirfext(optionfilefiname,"PHTM_",".htm"));
                   4994:   if((ficresphtm=fopen(fileresphtm,"w"))==NULL) {
                   4995:     printf("Problem with prevalence HTM resultfile '%s' with errno='%s'\n",fileresphtm,strerror(errno));
                   4996:     fprintf(ficlog,"Problem with prevalence HTM resultfile '%s' with errno='%s'\n",fileresphtm,strerror(errno));
                   4997:     fflush(ficlog);
                   4998:     exit(70); 
                   4999:   }
                   5000:   else{
                   5001:     fprintf(ficresphtm,"<html><head>\n<title>IMaCh PHTM_ %s</title></head>\n <body><font size=\"2\">%s <br> %s</font> \
1.240     brouard  5002: <hr size=\"2\" color=\"#EC5E5E\"> \n                                   \
1.214     brouard  5003: Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=1+age+%s<br>\n",\
1.226     brouard  5004:            fileresphtm,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model);
                   5005:   }
1.319     brouard  5006:   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  5007:   
1.226     brouard  5008:   strcpy(fileresphtmfr,subdirfext(optionfilefiname,"PHTMFR_",".htm"));
                   5009:   if((ficresphtmfr=fopen(fileresphtmfr,"w"))==NULL) {
                   5010:     printf("Problem with frequency table HTM resultfile '%s' with errno='%s'\n",fileresphtmfr,strerror(errno));
                   5011:     fprintf(ficlog,"Problem with frequency table HTM resultfile '%s' with errno='%s'\n",fileresphtmfr,strerror(errno));
                   5012:     fflush(ficlog);
                   5013:     exit(70); 
1.240     brouard  5014:   } else{
1.226     brouard  5015:     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  5016: ,<hr size=\"2\" color=\"#EC5E5E\"> \n                                  \
1.214     brouard  5017: Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=1+age+%s<br>\n",\
1.226     brouard  5018:            fileresphtmfr,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model);
                   5019:   }
1.319     brouard  5020:   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  5021:   
1.253     brouard  5022:   y= vector(iagemin-AGEMARGE,iagemax+4+AGEMARGE);
                   5023:   x= vector(iagemin-AGEMARGE,iagemax+4+AGEMARGE);
1.251     brouard  5024:   freq= ma3x(-5,nlstate+ndeath,-5,nlstate+ndeath,iagemin-AGEMARGE,iagemax+4+AGEMARGE);
1.226     brouard  5025:   j1=0;
1.126     brouard  5026:   
1.227     brouard  5027:   /* j=ncoveff;  /\* Only fixed dummy covariates *\/ */
1.335     brouard  5028:   j=cptcoveff;  /* Only simple dummy covariates used in the model */
1.330     brouard  5029:   /* j=cptcovn;  /\* Only dummy covariates of the model *\/ */
1.226     brouard  5030:   if (cptcovn<1) {j=1;ncodemax[1]=1;}
1.240     brouard  5031:   
                   5032:   
1.226     brouard  5033:   /* Detects if a combination j1 is empty: for a multinomial variable like 3 education levels:
                   5034:      reference=low_education V1=0,V2=0
                   5035:      med_educ                V1=1 V2=0, 
                   5036:      high_educ               V1=0 V2=1
1.330     brouard  5037:      Then V1=1 and V2=1 is a noisy combination that we want to exclude for the list 2**cptcovn 
1.226     brouard  5038:   */
1.249     brouard  5039:   dateintsum=0;
                   5040:   k2cpt=0;
                   5041: 
1.253     brouard  5042:   if(cptcoveff == 0 )
1.265     brouard  5043:     nl=1;  /* Constant and age model only */
1.253     brouard  5044:   else
                   5045:     nl=2;
1.265     brouard  5046: 
                   5047:   /* if a constant only model, one pass to compute frequency tables and to write it on ficresp */
                   5048:   /* Loop on nj=1 or 2 if dummy covariates j!=0
1.335     brouard  5049:    *   Loop on j1(1 to 2**cptcoveff) covariate combination
1.265     brouard  5050:    *     freq[s1][s2][iage] =0.
                   5051:    *     Loop on iind
                   5052:    *       ++freq[s1][s2][iage] weighted
                   5053:    *     end iind
                   5054:    *     if covariate and j!0
                   5055:    *       headers Variable on one line
                   5056:    *     endif cov j!=0
                   5057:    *     header of frequency table by age
                   5058:    *     Loop on age
                   5059:    *       pp[s1]+=freq[s1][s2][iage] weighted
                   5060:    *       pos+=freq[s1][s2][iage] weighted
                   5061:    *       Loop on s1 initial state
                   5062:    *         fprintf(ficresp
                   5063:    *       end s1
                   5064:    *     end age
                   5065:    *     if j!=0 computes starting values
                   5066:    *     end compute starting values
                   5067:    *   end j1
                   5068:    * end nl 
                   5069:    */
1.253     brouard  5070:   for (nj = 1; nj <= nl; nj++){   /* nj= 1 constant model, nl number of loops. */
                   5071:     if(nj==1)
                   5072:       j=0;  /* First pass for the constant */
1.265     brouard  5073:     else{
1.335     brouard  5074:       j=cptcoveff; /* Other passes for the covariate values number of simple covariates in the model V2+V1 =2 (simple dummy fixed or time varying) */
1.265     brouard  5075:     }
1.251     brouard  5076:     first=1;
1.332     brouard  5077:     for (j1 = 1; j1 <= (int) pow(2,j); j1++){ /* Loop on all dummy covariates combination of the model, ie excluding quantitatives, V4=0, V3=0 for example, fixed or varying covariates */
1.251     brouard  5078:       posproptt=0.;
1.330     brouard  5079:       /*printf("cptcovn=%d Tvaraff=%d", cptcovn,Tvaraff[1]);
1.251     brouard  5080:        scanf("%d", i);*/
                   5081:       for (i=-5; i<=nlstate+ndeath; i++)  
1.265     brouard  5082:        for (s2=-5; s2<=nlstate+ndeath; s2++)  
1.251     brouard  5083:          for(m=iagemin; m <= iagemax+3; m++)
1.265     brouard  5084:            freq[i][s2][m]=0;
1.251     brouard  5085:       
                   5086:       for (i=1; i<=nlstate; i++)  {
1.240     brouard  5087:        for(m=iagemin; m <= iagemax+3; m++)
1.251     brouard  5088:          prop[i][m]=0;
                   5089:        posprop[i]=0;
                   5090:        pospropt[i]=0;
                   5091:       }
1.283     brouard  5092:       for (z1=1; z1<= nqfveff; z1++) { /* zeroing for each combination j1 as well as for the total */
1.284     brouard  5093:         idq[z1]=0.;
                   5094:         meanq[z1]=0.;
                   5095:         stdq[z1]=0.;
1.283     brouard  5096:       }
                   5097:       /* for (z1=1; z1<= nqtveff; z1++) { */
1.251     brouard  5098:       /*   for(m=1;m<=lastpass;m++){ */
1.283     brouard  5099:       /*         meanqt[m][z1]=0.; */
                   5100:       /*       } */
                   5101:       /* }       */
1.251     brouard  5102:       /* dateintsum=0; */
                   5103:       /* k2cpt=0; */
                   5104:       
1.265     brouard  5105:       /* For that combination of covariates j1 (V4=1 V3=0 for example), we count and print the frequencies in one pass */
1.251     brouard  5106:       for (iind=1; iind<=imx; iind++) { /* For each individual iind */
                   5107:        bool=1;
                   5108:        if(j !=0){
                   5109:          if(anyvaryingduminmodel==0){ /* If All fixed covariates */
1.335     brouard  5110:            if (cptcoveff >0) { /* Filter is here: Must be looked at for model=V1+V2+V3+V4 */
                   5111:              for (z1=1; z1<=cptcoveff; z1++) { /* loops on covariates in the model */
1.251     brouard  5112:                /* if(Tvaraff[z1] ==-20){ */
                   5113:                /*       /\* sumnew+=cotvar[mw[mi][iind]][z1][iind]; *\/ */
                   5114:                /* }else  if(Tvaraff[z1] ==-10){ */
                   5115:                /*       /\* sumnew+=coqvar[z1][iind]; *\/ */
1.330     brouard  5116:                /* }else  */ /* TODO TODO codtabm(j1,z1) or codtabm(j1,Tvaraff[z1]]z1)*/
1.335     brouard  5117:                /* if( iind >=imx-3) printf("Searching error iind=%d Tvaraff[z1]=%d covar[Tvaraff[z1]][iind]=%.f TnsdVar[Tvaraff[z1]]=%d, cptcoveff=%d, cptcovs=%d \n",iind, Tvaraff[z1], covar[Tvaraff[z1]][iind],TnsdVar[Tvaraff[z1]],cptcoveff, cptcovs); */
                   5118:                if(Tvaraff[z1]<1 || Tvaraff[z1]>=NCOVMAX)
                   5119:                  printf("Error Tvaraff[z1]=%d<1 or >=%d, cptcoveff=%d model=%s\n",Tvaraff[z1],NCOVMAX, cptcoveff, model);
1.332     brouard  5120:                if (covar[Tvaraff[z1]][iind]!= nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]){ /* for combination j1 of covariates */
1.265     brouard  5121:                  /* Tests if the value of the covariate z1 for this individual iind responded to combination j1 (V4=1 V3=0) */
1.251     brouard  5122:                  bool=0; /* bool should be equal to 1 to be selected, one covariate value failed */
1.332     brouard  5123:                  /* 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", */
                   5124:                  /*   bool,i,z1, z1, Tvaraff[z1],i,covar[Tvaraff[z1]][i],j1,z1,codtabm(j1,z1),*/
                   5125:                   /*   j1,z1,nbcode[Tvaraff[z1]][codtabm(j1,z1)],j1);*/
1.251     brouard  5126:                  /* For j1=7 in V1+V2+V3+V4 = 0 1 1 0 and codtabm(7,3)=1 and nbcde[3][?]=1*/
                   5127:                } /* Onlyf fixed */
                   5128:              } /* end z1 */
1.335     brouard  5129:            } /* cptcoveff > 0 */
1.251     brouard  5130:          } /* end any */
                   5131:        }/* end j==0 */
1.265     brouard  5132:        if (bool==1){ /* We selected an individual iind satisfying combination j1 (V4=1 V3=0) or all fixed covariates */
1.251     brouard  5133:          /* for(m=firstpass; m<=lastpass; m++){ */
1.284     brouard  5134:          for(mi=1; mi<wav[iind];mi++){ /* For each wave */
1.251     brouard  5135:            m=mw[mi][iind];
                   5136:            if(j!=0){
                   5137:              if(anyvaryingduminmodel==1){ /* Some are varying covariates */
1.335     brouard  5138:                for (z1=1; z1<=cptcoveff; z1++) {
1.251     brouard  5139:                  if( Fixed[Tmodelind[z1]]==1){
                   5140:                    iv= Tvar[Tmodelind[z1]]-ncovcol-nqv;
1.332     brouard  5141:                    if (cotvar[m][iv][iind]!= nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]) /* iv=1 to ntv, right modality. If covariate's 
1.251     brouard  5142:                                                                                      value is -1, we don't select. It differs from the 
                   5143:                                                                                      constant and age model which counts them. */
                   5144:                      bool=0; /* not selected */
                   5145:                  }else if( Fixed[Tmodelind[z1]]== 0) { /* fixed */
1.334     brouard  5146:                    /* i1=Tvaraff[z1]; */
                   5147:                    /* i2=TnsdVar[i1]; */
                   5148:                    /* i3=nbcode[i1][i2]; */
                   5149:                    /* i4=covar[i1][iind]; */
                   5150:                    /* if(i4 != i3){ */
                   5151:                    if (covar[Tvaraff[z1]][iind]!= nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]) { /* Bug valgrind */
1.251     brouard  5152:                      bool=0;
                   5153:                    }
                   5154:                  }
                   5155:                }
                   5156:              }/* Some are varying covariates, we tried to speed up if all fixed covariates in the model, avoiding waves loop  */
                   5157:            } /* end j==0 */
                   5158:            /* bool =0 we keep that guy which corresponds to the combination of dummy values */
1.284     brouard  5159:            if(bool==1){ /*Selected */
1.251     brouard  5160:              /* dh[m][iind] or dh[mw[mi][iind]][iind] is the delay between two effective (mi) waves m=mw[mi][iind]
                   5161:                 and mw[mi+1][iind]. dh depends on stepm. */
                   5162:              agebegin=agev[m][iind]; /* Age at beginning of wave before transition*/
                   5163:              ageend=agev[m][iind]+(dh[m][iind])*stepm/YEARM; /* Age at end of wave and transition */
                   5164:              if(m >=firstpass && m <=lastpass){
                   5165:                k2=anint[m][iind]+(mint[m][iind]/12.);
                   5166:                /*if ((k2>=dateprev1) && (k2<=dateprev2)) {*/
                   5167:                if(agev[m][iind]==0) agev[m][iind]=iagemax+1;  /* All ages equal to 0 are in iagemax+1 */
                   5168:                if(agev[m][iind]==1) agev[m][iind]=iagemax+2;  /* All ages equal to 1 are in iagemax+2 */
                   5169:                if (s[m][iind]>0 && s[m][iind]<=nlstate)  /* If status at wave m is known and a live state */
                   5170:                  prop[s[m][iind]][(int)agev[m][iind]] += weight[iind];  /* At age of beginning of transition, where status is known */
                   5171:                if (m<lastpass) {
                   5172:                  /* if(s[m][iind]==4 && s[m+1][iind]==4) */
                   5173:                  /*   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]); */
                   5174:                  if(s[m][iind]==-1)
                   5175:                    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.));
                   5176:                  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  5177:                  for (z1=1; z1<= nqfveff; z1++) { /* Quantitative variables, calculating mean on known values only */
                   5178:                    if(!isnan(covar[ncovcol+z1][iind])){
1.332     brouard  5179:                      idq[z1]=idq[z1]+weight[iind];
                   5180:                      meanq[z1]+=covar[ncovcol+z1][iind]*weight[iind];  /* Computes mean of quantitative with selected filter */
                   5181:                      /* stdq[z1]+=covar[ncovcol+z1][iind]*covar[ncovcol+z1][iind]*weight[iind]*weight[iind]; *//*error*/
                   5182:                      stdq[z1]+=covar[ncovcol+z1][iind]*covar[ncovcol+z1][iind]*weight[iind]; /* *weight[iind];*/  /* Computes mean of quantitative with selected filter */
1.311     brouard  5183:                    }
1.284     brouard  5184:                  }
1.251     brouard  5185:                  /* if((int)agev[m][iind] == 55) */
                   5186:                  /*   printf("j=%d, j1=%d Age %d, iind=%d, num=%09ld m=%d\n",j,j1,(int)agev[m][iind],iind, num[iind],m); */
                   5187:                  /* freq[s[m][iind]][s[m+1][iind]][(int)((agebegin+ageend)/2.)] += weight[iind]; */
                   5188:                  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  5189:                }
1.251     brouard  5190:              } /* end if between passes */  
                   5191:              if ((agev[m][iind]>1) && (agev[m][iind]< (iagemax+3)) && (anint[m][iind]!=9999) && (mint[m][iind]!=99) && (j==0)) {
                   5192:                dateintsum=dateintsum+k2; /* on all covariates ?*/
                   5193:                k2cpt++;
                   5194:                /* printf("iind=%ld dateintmean = %lf dateintsum=%lf k2cpt=%lf k2=%lf\n",iind, dateintsum/k2cpt, dateintsum,k2cpt, k2); */
1.234     brouard  5195:              }
1.251     brouard  5196:            }else{
                   5197:              bool=1;
                   5198:            }/* end bool 2 */
                   5199:          } /* end m */
1.284     brouard  5200:          /* for (z1=1; z1<= nqfveff; z1++) { /\* Quantitative variables, calculating mean *\/ */
                   5201:          /*   idq[z1]=idq[z1]+weight[iind]; */
                   5202:          /*   meanq[z1]+=covar[ncovcol+z1][iind]*weight[iind];  /\* Computes mean of quantitative with selected filter *\/ */
                   5203:          /*   stdq[z1]+=covar[ncovcol+z1][iind]*covar[ncovcol+z1][iind]*weight[iind]*weight[iind]; /\* *weight[iind];*\/  /\* Computes mean of quantitative with selected filter *\/ */
                   5204:          /* } */
1.251     brouard  5205:        } /* end bool */
                   5206:       } /* end iind = 1 to imx */
1.319     brouard  5207:       /* prop[s][age] is fed for any initial and valid live state as well as
1.251     brouard  5208:         freq[s1][s2][age] at single age of beginning the transition, for a combination j1 */
                   5209:       
                   5210:       
                   5211:       /*      fprintf(ficresp, "#Count between %.lf/%.lf/%.lf and %.lf/%.lf/%.lf\n",jprev1, mprev1,anprev1,jprev2, mprev2,anprev2);*/
1.335     brouard  5212:       if(cptcoveff==0 && nj==1) /* no covariate and first pass */
1.265     brouard  5213:         pstamp(ficresp);
1.335     brouard  5214:       if  (cptcoveff>0 && j!=0){
1.265     brouard  5215:         pstamp(ficresp);
1.251     brouard  5216:        printf( "\n#********** Variable "); 
                   5217:        fprintf(ficresp, "\n#********** Variable "); 
                   5218:        fprintf(ficresphtm, "\n<br/><br/><h3>********** Variable "); 
                   5219:        fprintf(ficresphtmfr, "\n<br/><br/><h3>********** Variable "); 
                   5220:        fprintf(ficlog, "\n#********** Variable "); 
1.330     brouard  5221:        for (z1=1; z1<=cptcovs; z1++){
1.251     brouard  5222:          if(!FixedV[Tvaraff[z1]]){
1.330     brouard  5223:            printf( "V%d(fixed)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]);
                   5224:            fprintf(ficresp, "V%d(fixed)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]);
                   5225:            fprintf(ficresphtm, "V%d(fixed)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]);
                   5226:            fprintf(ficresphtmfr, "V%d(fixed)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]);
                   5227:            fprintf(ficlog, "V%d(fixed)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]);
1.250     brouard  5228:          }else{
1.330     brouard  5229:            printf( "V%d(varying)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]);
                   5230:            fprintf(ficresp, "V%d(varying)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]);
                   5231:            fprintf(ficresphtm, "V%d(varying)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]);
                   5232:            fprintf(ficresphtmfr, "V%d(varying)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]);
                   5233:            fprintf(ficlog, "V%d(varying)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]);
1.251     brouard  5234:          }
                   5235:        }
                   5236:        printf( "**********\n#");
                   5237:        fprintf(ficresp, "**********\n#");
                   5238:        fprintf(ficresphtm, "**********</h3>\n");
                   5239:        fprintf(ficresphtmfr, "**********</h3>\n");
                   5240:        fprintf(ficlog, "**********\n");
                   5241:       }
1.284     brouard  5242:       /*
                   5243:        Printing means of quantitative variables if any
                   5244:       */
                   5245:       for (z1=1; z1<= nqfveff; z1++) {
1.311     brouard  5246:        fprintf(ficlog,"Mean of fixed quantitative variable V%d on %.3g (weighted) individuals sum=%f", ncovcol+z1, idq[z1], meanq[z1]);
1.312     brouard  5247:        fprintf(ficlog,", mean=%.3g\n",meanq[z1]/idq[z1]);
1.284     brouard  5248:        if(weightopt==1){
                   5249:          printf(" Weighted mean and standard deviation of");
                   5250:          fprintf(ficlog," Weighted mean and standard deviation of");
                   5251:          fprintf(ficresphtmfr," Weighted mean and standard deviation of");
                   5252:        }
1.311     brouard  5253:        /* mu = \frac{w x}{\sum w}
                   5254:            var = \frac{\sum w (x-mu)^2}{\sum w} = \frac{w x^2}{\sum w} - mu^2 
                   5255:        */
                   5256:        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]));
                   5257:        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]));
                   5258:        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  5259:       }
                   5260:       /* for (z1=1; z1<= nqtveff; z1++) { */
                   5261:       /*       for(m=1;m<=lastpass;m++){ */
                   5262:       /*         fprintf(ficresphtmfr,"V quantitative id %d, pass id=%d, mean=%f<p>\n", z1, m, meanqt[m][z1]); */
                   5263:       /*   } */
                   5264:       /* } */
1.283     brouard  5265: 
1.251     brouard  5266:       fprintf(ficresphtm,"<table style=\"text-align:center; border: 1px solid\">");
1.335     brouard  5267:       if((cptcoveff==0 && nj==1)|| nj==2 ) /* no covariate and first pass */
1.265     brouard  5268:         fprintf(ficresp, " Age");
1.335     brouard  5269:       if(nj==2) for (z1=1; z1<=cptcoveff; z1++) {
                   5270:          printf(" V%d=%d, z1=%d, Tvaraff[z1]=%d, j1=%d, TnsdVar[Tvaraff[%d]]=%d |",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])], z1, Tvaraff[z1], j1,z1,TnsdVar[Tvaraff[z1]]);
                   5271:          fprintf(ficresp, " V%d=%d",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]);
                   5272:        }
1.251     brouard  5273:       for(i=1; i<=nlstate;i++) {
1.335     brouard  5274:        if((cptcoveff==0 && nj==1)|| nj==2 ) fprintf(ficresp," Prev(%d)  N(%d)  N  ",i,i);
1.251     brouard  5275:        fprintf(ficresphtm, "<th>Age</th><th>Prev(%d)</th><th>N(%d)</th><th>N</th>",i,i);
                   5276:       }
1.335     brouard  5277:       if((cptcoveff==0 && nj==1)|| nj==2 ) fprintf(ficresp, "\n");
1.251     brouard  5278:       fprintf(ficresphtm, "\n");
                   5279:       
                   5280:       /* Header of frequency table by age */
                   5281:       fprintf(ficresphtmfr,"<table style=\"text-align:center; border: 1px solid\">");
                   5282:       fprintf(ficresphtmfr,"<th>Age</th> ");
1.265     brouard  5283:       for(s2=-1; s2 <=nlstate+ndeath; s2++){
1.251     brouard  5284:        for(m=-1; m <=nlstate+ndeath; m++){
1.265     brouard  5285:          if(s2!=0 && m!=0)
                   5286:            fprintf(ficresphtmfr,"<th>%d%d</th> ",s2,m);
1.240     brouard  5287:        }
1.226     brouard  5288:       }
1.251     brouard  5289:       fprintf(ficresphtmfr, "\n");
                   5290:     
                   5291:       /* For each age */
                   5292:       for(iage=iagemin; iage <= iagemax+3; iage++){
                   5293:        fprintf(ficresphtm,"<tr>");
                   5294:        if(iage==iagemax+1){
                   5295:          fprintf(ficlog,"1");
                   5296:          fprintf(ficresphtmfr,"<tr><th>0</th> ");
                   5297:        }else if(iage==iagemax+2){
                   5298:          fprintf(ficlog,"0");
                   5299:          fprintf(ficresphtmfr,"<tr><th>Unknown</th> ");
                   5300:        }else if(iage==iagemax+3){
                   5301:          fprintf(ficlog,"Total");
                   5302:          fprintf(ficresphtmfr,"<tr><th>Total</th> ");
                   5303:        }else{
1.240     brouard  5304:          if(first==1){
1.251     brouard  5305:            first=0;
                   5306:            printf("See log file for details...\n");
                   5307:          }
                   5308:          fprintf(ficresphtmfr,"<tr><th>%d</th> ",iage);
                   5309:          fprintf(ficlog,"Age %d", iage);
                   5310:        }
1.265     brouard  5311:        for(s1=1; s1 <=nlstate ; s1++){
                   5312:          for(m=-1, pp[s1]=0; m <=nlstate+ndeath ; m++)
                   5313:            pp[s1] += freq[s1][m][iage]; 
1.251     brouard  5314:        }
1.265     brouard  5315:        for(s1=1; s1 <=nlstate ; s1++){
1.251     brouard  5316:          for(m=-1, pos=0; m <=0 ; m++)
1.265     brouard  5317:            pos += freq[s1][m][iage];
                   5318:          if(pp[s1]>=1.e-10){
1.251     brouard  5319:            if(first==1){
1.265     brouard  5320:              printf(" %d.=%.0f loss[%d]=%.1f%%",s1,pp[s1],s1,100*pos/pp[s1]);
1.251     brouard  5321:            }
1.265     brouard  5322:            fprintf(ficlog," %d.=%.0f loss[%d]=%.1f%%",s1,pp[s1],s1,100*pos/pp[s1]);
1.251     brouard  5323:          }else{
                   5324:            if(first==1)
1.265     brouard  5325:              printf(" %d.=%.0f loss[%d]=NaNQ%%",s1,pp[s1],s1);
                   5326:            fprintf(ficlog," %d.=%.0f loss[%d]=NaNQ%%",s1,pp[s1],s1);
1.240     brouard  5327:          }
                   5328:        }
                   5329:       
1.265     brouard  5330:        for(s1=1; s1 <=nlstate ; s1++){ 
                   5331:          /* posprop[s1]=0; */
                   5332:          for(m=0, pp[s1]=0; m <=nlstate+ndeath; m++)/* Summing on all ages */
                   5333:            pp[s1] += freq[s1][m][iage];
                   5334:        }       /* pp[s1] is the total number of transitions starting from state s1 and any ending status until this age */
                   5335:       
                   5336:        for(s1=1,pos=0, pospropta=0.; s1 <=nlstate ; s1++){
                   5337:          pos += pp[s1]; /* pos is the total number of transitions until this age */
                   5338:          posprop[s1] += prop[s1][iage]; /* prop is the number of transitions from a live state
                   5339:                                            from s1 at age iage prop[s[m][iind]][(int)agev[m][iind]] += weight[iind] */
                   5340:          pospropta += prop[s1][iage]; /* prop is the number of transitions from a live state
                   5341:                                          from s1 at age iage prop[s[m][iind]][(int)agev[m][iind]] += weight[iind] */
                   5342:        }
                   5343:        
                   5344:        /* Writing ficresp */
1.335     brouard  5345:        if(cptcoveff==0 && nj==1){ /* no covariate and first pass */
1.265     brouard  5346:           if( iage <= iagemax){
                   5347:            fprintf(ficresp," %d",iage);
                   5348:           }
                   5349:         }else if( nj==2){
                   5350:           if( iage <= iagemax){
                   5351:            fprintf(ficresp," %d",iage);
1.335     brouard  5352:             for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresp, " %d %d",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]);
1.265     brouard  5353:           }
1.240     brouard  5354:        }
1.265     brouard  5355:        for(s1=1; s1 <=nlstate ; s1++){
1.240     brouard  5356:          if(pos>=1.e-5){
1.251     brouard  5357:            if(first==1)
1.265     brouard  5358:              printf(" %d.=%.0f prev[%d]=%.1f%%",s1,pp[s1],s1,100*pp[s1]/pos);
                   5359:            fprintf(ficlog," %d.=%.0f prev[%d]=%.1f%%",s1,pp[s1],s1,100*pp[s1]/pos);
1.251     brouard  5360:          }else{
                   5361:            if(first==1)
1.265     brouard  5362:              printf(" %d.=%.0f prev[%d]=NaNQ%%",s1,pp[s1],s1);
                   5363:            fprintf(ficlog," %d.=%.0f prev[%d]=NaNQ%%",s1,pp[s1],s1);
1.251     brouard  5364:          }
                   5365:          if( iage <= iagemax){
                   5366:            if(pos>=1.e-5){
1.335     brouard  5367:              if(cptcoveff==0 && nj==1){ /* no covariate and first pass */
1.265     brouard  5368:                fprintf(ficresp," %.5f %.0f %.0f",prop[s1][iage]/pospropta, prop[s1][iage],pospropta);
                   5369:               }else if( nj==2){
                   5370:                fprintf(ficresp," %.5f %.0f %.0f",prop[s1][iage]/pospropta, prop[s1][iage],pospropta);
                   5371:               }
                   5372:              fprintf(ficresphtm,"<th>%d</th><td>%.5f</td><td>%.0f</td><td>%.0f</td>",iage,prop[s1][iage]/pospropta, prop[s1][iage],pospropta);
                   5373:              /*probs[iage][s1][j1]= pp[s1]/pos;*/
                   5374:              /*printf("\niage=%d s1=%d j1=%d %.5f %.0f %.0f %f",iage,s1,j1,pp[s1]/pos, pp[s1],pos,probs[iage][s1][j1]);*/
                   5375:            } else{
1.335     brouard  5376:              if((cptcoveff==0 && nj==1)|| nj==2 ) fprintf(ficresp," NaNq %.0f %.0f",prop[s1][iage],pospropta);
1.265     brouard  5377:              fprintf(ficresphtm,"<th>%d</th><td>NaNq</td><td>%.0f</td><td>%.0f</td>",iage, prop[s1][iage],pospropta);
1.251     brouard  5378:            }
1.240     brouard  5379:          }
1.265     brouard  5380:          pospropt[s1] +=posprop[s1];
                   5381:        } /* end loop s1 */
1.251     brouard  5382:        /* pospropt=0.; */
1.265     brouard  5383:        for(s1=-1; s1 <=nlstate+ndeath; s1++){
1.251     brouard  5384:          for(m=-1; m <=nlstate+ndeath; m++){
1.265     brouard  5385:            if(freq[s1][m][iage] !=0 ) { /* minimizing output */
1.251     brouard  5386:              if(first==1){
1.265     brouard  5387:                printf(" %d%d=%.0f",s1,m,freq[s1][m][iage]);
1.251     brouard  5388:              }
1.265     brouard  5389:              /* printf(" %d%d=%.0f",s1,m,freq[s1][m][iage]); */
                   5390:              fprintf(ficlog," %d%d=%.0f",s1,m,freq[s1][m][iage]);
1.251     brouard  5391:            }
1.265     brouard  5392:            if(s1!=0 && m!=0)
                   5393:              fprintf(ficresphtmfr,"<td>%.0f</td> ",freq[s1][m][iage]);
1.240     brouard  5394:          }
1.265     brouard  5395:        } /* end loop s1 */
1.251     brouard  5396:        posproptt=0.; 
1.265     brouard  5397:        for(s1=1; s1 <=nlstate; s1++){
                   5398:          posproptt += pospropt[s1];
1.251     brouard  5399:        }
                   5400:        fprintf(ficresphtmfr,"</tr>\n ");
1.265     brouard  5401:        fprintf(ficresphtm,"</tr>\n");
1.335     brouard  5402:        if((cptcoveff==0 && nj==1)|| nj==2 ) {
1.265     brouard  5403:          if(iage <= iagemax)
                   5404:            fprintf(ficresp,"\n");
1.240     brouard  5405:        }
1.251     brouard  5406:        if(first==1)
                   5407:          printf("Others in log...\n");
                   5408:        fprintf(ficlog,"\n");
                   5409:       } /* end loop age iage */
1.265     brouard  5410:       
1.251     brouard  5411:       fprintf(ficresphtm,"<tr><th>Tot</th>");
1.265     brouard  5412:       for(s1=1; s1 <=nlstate ; s1++){
1.251     brouard  5413:        if(posproptt < 1.e-5){
1.265     brouard  5414:          fprintf(ficresphtm,"<td>Nanq</td><td>%.0f</td><td>%.0f</td>",pospropt[s1],posproptt); 
1.251     brouard  5415:        }else{
1.265     brouard  5416:          fprintf(ficresphtm,"<td>%.5f</td><td>%.0f</td><td>%.0f</td>",pospropt[s1]/posproptt,pospropt[s1],posproptt);  
1.240     brouard  5417:        }
1.226     brouard  5418:       }
1.251     brouard  5419:       fprintf(ficresphtm,"</tr>\n");
                   5420:       fprintf(ficresphtm,"</table>\n");
                   5421:       fprintf(ficresphtmfr,"</table>\n");
1.226     brouard  5422:       if(posproptt < 1.e-5){
1.251     brouard  5423:        fprintf(ficresphtm,"\n <p><b> This combination (%d) is not valid and no result will be produced</b></p>",j1);
                   5424:        fprintf(ficresphtmfr,"\n <p><b> This combination (%d) is not valid and no result will be produced</b></p>",j1);
1.260     brouard  5425:        fprintf(ficlog,"#  This combination (%d) is not valid and no result will be produced\n",j1);
                   5426:        printf("#  This combination (%d) is not valid and no result will be produced\n",j1);
1.251     brouard  5427:        invalidvarcomb[j1]=1;
1.226     brouard  5428:       }else{
1.251     brouard  5429:        fprintf(ficresphtm,"\n <p> This combination (%d) is valid and result will be produced.</p>",j1);
                   5430:        invalidvarcomb[j1]=0;
1.226     brouard  5431:       }
1.251     brouard  5432:       fprintf(ficresphtmfr,"</table>\n");
                   5433:       fprintf(ficlog,"\n");
                   5434:       if(j!=0){
                   5435:        printf("#Freqsummary: Starting values for combination j1=%d:\n", j1);
1.265     brouard  5436:        for(i=1,s1=1; i <=nlstate; i++){
1.251     brouard  5437:          for(k=1; k <=(nlstate+ndeath); k++){
                   5438:            if (k != i) {
1.265     brouard  5439:              for(jj=1; jj <=ncovmodel; jj++){ /* For counting s1 */
1.253     brouard  5440:                if(jj==1){  /* Constant case (in fact cste + age) */
1.251     brouard  5441:                  if(j1==1){ /* All dummy covariates to zero */
                   5442:                    freq[i][k][iagemax+4]=freq[i][k][iagemax+3]; /* Stores case 0 0 0 */
                   5443:                    freq[i][i][iagemax+4]=freq[i][i][iagemax+3]; /* Stores case 0 0 0 */
1.252     brouard  5444:                    printf("%d%d ",i,k);
                   5445:                    fprintf(ficlog,"%d%d ",i,k);
1.265     brouard  5446:                    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]));
                   5447:                    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]));
                   5448:                    pstart[s1]= log(freq[i][k][iagemax+3]/freq[i][i][iagemax+3]);
1.251     brouard  5449:                  }
1.253     brouard  5450:                }else if((j1==1) && (jj==2 || nagesqr==1)){ /* age or age*age parameter without covariate V4*age (to be done later) */
                   5451:                  for(iage=iagemin; iage <= iagemax+3; iage++){
                   5452:                    x[iage]= (double)iage;
                   5453:                    y[iage]= log(freq[i][k][iage]/freq[i][i][iage]);
1.265     brouard  5454:                    /* 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  5455:                  }
1.268     brouard  5456:                  /* Some are not finite, but linreg will ignore these ages */
                   5457:                  no=0;
1.253     brouard  5458:                  linreg(iagemin,iagemax,&no,x,y,&a,&b,&r, &sa, &sb ); /* y= a+b*x with standard errors */
1.265     brouard  5459:                  pstart[s1]=b;
                   5460:                  pstart[s1-1]=a;
1.252     brouard  5461:                }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 */ 
                   5462:                  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]);
                   5463:                  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  5464:                  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  5465:                  printf("%d%d ",i,k);
                   5466:                  fprintf(ficlog,"%d%d ",i,k);
1.265     brouard  5467:                  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  5468:                }else{ /* Other cases, like quantitative fixed or varying covariates */
                   5469:                  ;
                   5470:                }
                   5471:                /* printf("%12.7f )", param[i][jj][k]); */
                   5472:                /* fprintf(ficlog,"%12.7f )", param[i][jj][k]); */
1.265     brouard  5473:                s1++; 
1.251     brouard  5474:              } /* end jj */
                   5475:            } /* end k!= i */
                   5476:          } /* end k */
1.265     brouard  5477:        } /* end i, s1 */
1.251     brouard  5478:       } /* end j !=0 */
                   5479:     } /* end selected combination of covariate j1 */
                   5480:     if(j==0){ /* We can estimate starting values from the occurences in each case */
                   5481:       printf("#Freqsummary: Starting values for the constants:\n");
                   5482:       fprintf(ficlog,"\n");
1.265     brouard  5483:       for(i=1,s1=1; i <=nlstate; i++){
1.251     brouard  5484:        for(k=1; k <=(nlstate+ndeath); k++){
                   5485:          if (k != i) {
                   5486:            printf("%d%d ",i,k);
                   5487:            fprintf(ficlog,"%d%d ",i,k);
                   5488:            for(jj=1; jj <=ncovmodel; jj++){
1.265     brouard  5489:              pstart[s1]=p[s1]; /* Setting pstart to p values by default */
1.253     brouard  5490:              if(jj==1){ /* Age has to be done */
1.265     brouard  5491:                pstart[s1]= log(freq[i][k][iagemax+3]/freq[i][i][iagemax+3]);
                   5492:                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]));
                   5493:                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  5494:              }
                   5495:              /* printf("%12.7f )", param[i][jj][k]); */
                   5496:              /* fprintf(ficlog,"%12.7f )", param[i][jj][k]); */
1.265     brouard  5497:              s1++; 
1.250     brouard  5498:            }
1.251     brouard  5499:            printf("\n");
                   5500:            fprintf(ficlog,"\n");
1.250     brouard  5501:          }
                   5502:        }
1.284     brouard  5503:       } /* end of state i */
1.251     brouard  5504:       printf("#Freqsummary\n");
                   5505:       fprintf(ficlog,"\n");
1.265     brouard  5506:       for(s1=-1; s1 <=nlstate+ndeath; s1++){
                   5507:        for(s2=-1; s2 <=nlstate+ndeath; s2++){
                   5508:          /* param[i]|j][k]= freq[s1][s2][iagemax+3] */
                   5509:          printf(" %d%d=%.0f",s1,s2,freq[s1][s2][iagemax+3]);
                   5510:          fprintf(ficlog," %d%d=%.0f",s1,s2,freq[s1][s2][iagemax+3]);
                   5511:          /* if(freq[s1][s2][iage] !=0 ) { /\* minimizing output *\/ */
                   5512:          /*   printf(" %d%d=%.0f",s1,s2,freq[s1][s2][iagemax+3]); */
                   5513:          /*   fprintf(ficlog," %d%d=%.0f",s1,s2,freq[s1][s2][iagemax+3]); */
1.251     brouard  5514:          /* } */
                   5515:        }
1.265     brouard  5516:       } /* end loop s1 */
1.251     brouard  5517:       
                   5518:       printf("\n");
                   5519:       fprintf(ficlog,"\n");
                   5520:     } /* end j=0 */
1.249     brouard  5521:   } /* end j */
1.252     brouard  5522: 
1.253     brouard  5523:   if(mle == -2){  /* We want to use these values as starting values */
1.252     brouard  5524:     for(i=1, jk=1; i <=nlstate; i++){
                   5525:       for(j=1; j <=nlstate+ndeath; j++){
                   5526:        if(j!=i){
                   5527:          /*ca[0]= k+'a'-1;ca[1]='\0';*/
                   5528:          printf("%1d%1d",i,j);
                   5529:          fprintf(ficparo,"%1d%1d",i,j);
                   5530:          for(k=1; k<=ncovmodel;k++){
                   5531:            /*    printf(" %lf",param[i][j][k]); */
                   5532:            /*    fprintf(ficparo," %lf",param[i][j][k]); */
                   5533:            p[jk]=pstart[jk];
                   5534:            printf(" %f ",pstart[jk]);
                   5535:            fprintf(ficparo," %f ",pstart[jk]);
                   5536:            jk++;
                   5537:          }
                   5538:          printf("\n");
                   5539:          fprintf(ficparo,"\n");
                   5540:        }
                   5541:       }
                   5542:     }
                   5543:   } /* end mle=-2 */
1.226     brouard  5544:   dateintmean=dateintsum/k2cpt; 
1.296     brouard  5545:   date2dmy(dateintmean,&jintmean,&mintmean,&aintmean);
1.240     brouard  5546:   
1.226     brouard  5547:   fclose(ficresp);
                   5548:   fclose(ficresphtm);
                   5549:   fclose(ficresphtmfr);
1.283     brouard  5550:   free_vector(idq,1,nqfveff);
1.226     brouard  5551:   free_vector(meanq,1,nqfveff);
1.284     brouard  5552:   free_vector(stdq,1,nqfveff);
1.226     brouard  5553:   free_matrix(meanqt,1,lastpass,1,nqtveff);
1.253     brouard  5554:   free_vector(x, iagemin-AGEMARGE, iagemax+4+AGEMARGE);
                   5555:   free_vector(y, iagemin-AGEMARGE, iagemax+4+AGEMARGE);
1.251     brouard  5556:   free_ma3x(freq,-5,nlstate+ndeath,-5,nlstate+ndeath, iagemin-AGEMARGE, iagemax+4+AGEMARGE);
1.226     brouard  5557:   free_vector(pospropt,1,nlstate);
                   5558:   free_vector(posprop,1,nlstate);
1.251     brouard  5559:   free_matrix(prop,1,nlstate,iagemin-AGEMARGE, iagemax+4+AGEMARGE);
1.226     brouard  5560:   free_vector(pp,1,nlstate);
                   5561:   /* End of freqsummary */
                   5562: }
1.126     brouard  5563: 
1.268     brouard  5564: /* Simple linear regression */
                   5565: int linreg(int ifi, int ila, int *no, const double x[], const double y[], double* a, double* b, double* r, double* sa, double * sb) {
                   5566: 
                   5567:   /* y=a+bx regression */
                   5568:   double   sumx = 0.0;                        /* sum of x                      */
                   5569:   double   sumx2 = 0.0;                       /* sum of x**2                   */
                   5570:   double   sumxy = 0.0;                       /* sum of x * y                  */
                   5571:   double   sumy = 0.0;                        /* sum of y                      */
                   5572:   double   sumy2 = 0.0;                       /* sum of y**2                   */
                   5573:   double   sume2 = 0.0;                       /* sum of square or residuals */
                   5574:   double yhat;
                   5575:   
                   5576:   double denom=0;
                   5577:   int i;
                   5578:   int ne=*no;
                   5579:   
                   5580:   for ( i=ifi, ne=0;i<=ila;i++) {
                   5581:     if(!isfinite(x[i]) || !isfinite(y[i])){
                   5582:       /* printf(" x[%d]=%f, y[%d]=%f\n",i,x[i],i,y[i]); */
                   5583:       continue;
                   5584:     }
                   5585:     ne=ne+1;
                   5586:     sumx  += x[i];       
                   5587:     sumx2 += x[i]*x[i];  
                   5588:     sumxy += x[i] * y[i];
                   5589:     sumy  += y[i];      
                   5590:     sumy2 += y[i]*y[i]; 
                   5591:     denom = (ne * sumx2 - sumx*sumx);
                   5592:     /* 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); */
                   5593:   } 
                   5594:   
                   5595:   denom = (ne * sumx2 - sumx*sumx);
                   5596:   if (denom == 0) {
                   5597:     // vertical, slope m is infinity
                   5598:     *b = INFINITY;
                   5599:     *a = 0;
                   5600:     if (r) *r = 0;
                   5601:     return 1;
                   5602:   }
                   5603:   
                   5604:   *b = (ne * sumxy  -  sumx * sumy) / denom;
                   5605:   *a = (sumy * sumx2  -  sumx * sumxy) / denom;
                   5606:   if (r!=NULL) {
                   5607:     *r = (sumxy - sumx * sumy / ne) /          /* compute correlation coeff     */
                   5608:       sqrt((sumx2 - sumx*sumx/ne) *
                   5609:           (sumy2 - sumy*sumy/ne));
                   5610:   }
                   5611:   *no=ne;
                   5612:   for ( i=ifi, ne=0;i<=ila;i++) {
                   5613:     if(!isfinite(x[i]) || !isfinite(y[i])){
                   5614:       /* printf(" x[%d]=%f, y[%d]=%f\n",i,x[i],i,y[i]); */
                   5615:       continue;
                   5616:     }
                   5617:     ne=ne+1;
                   5618:     yhat = y[i] - *a -*b* x[i];
                   5619:     sume2  += yhat * yhat ;       
                   5620:     
                   5621:     denom = (ne * sumx2 - sumx*sumx);
                   5622:     /* 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); */
                   5623:   } 
                   5624:   *sb = sqrt(sume2/(double)(ne-2)/(sumx2 - sumx * sumx /(double)ne));
                   5625:   *sa= *sb * sqrt(sumx2/ne);
                   5626:   
                   5627:   return 0; 
                   5628: }
                   5629: 
1.126     brouard  5630: /************ Prevalence ********************/
1.227     brouard  5631: 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)
                   5632: {  
                   5633:   /* Compute observed prevalence between dateprev1 and dateprev2 by counting the number of people
                   5634:      in each health status at the date of interview (if between dateprev1 and dateprev2).
                   5635:      We still use firstpass and lastpass as another selection.
                   5636:   */
1.126     brouard  5637:  
1.227     brouard  5638:   int i, m, jk, j1, bool, z1,j, iv;
                   5639:   int mi; /* Effective wave */
                   5640:   int iage;
                   5641:   double agebegin, ageend;
                   5642: 
                   5643:   double **prop;
                   5644:   double posprop; 
                   5645:   double  y2; /* in fractional years */
                   5646:   int iagemin, iagemax;
                   5647:   int first; /** to stop verbosity which is redirected to log file */
                   5648: 
                   5649:   iagemin= (int) agemin;
                   5650:   iagemax= (int) agemax;
                   5651:   /*pp=vector(1,nlstate);*/
1.251     brouard  5652:   prop=matrix(1,nlstate,iagemin-AGEMARGE,iagemax+4+AGEMARGE); 
1.227     brouard  5653:   /*  freq=ma3x(-1,nlstate+ndeath,-1,nlstate+ndeath,iagemin,iagemax+3);*/
                   5654:   j1=0;
1.222     brouard  5655:   
1.227     brouard  5656:   /*j=cptcoveff;*/
                   5657:   if (cptcovn<1) {j=1;ncodemax[1]=1;}
1.222     brouard  5658:   
1.288     brouard  5659:   first=0;
1.335     brouard  5660:   for(j1=1; j1<= (int) pow(2,cptcoveff);j1++){ /* For each combination of simple dummy covariates */
1.227     brouard  5661:     for (i=1; i<=nlstate; i++)  
1.251     brouard  5662:       for(iage=iagemin-AGEMARGE; iage <= iagemax+4+AGEMARGE; iage++)
1.227     brouard  5663:        prop[i][iage]=0.0;
                   5664:     printf("Prevalence combination of varying and fixed dummies %d\n",j1);
                   5665:     /* fprintf(ficlog," V%d=%d ",Tvaraff[j1],nbcode[Tvaraff[j1]][codtabm(k,j1)]); */
                   5666:     fprintf(ficlog,"Prevalence combination of varying and fixed dummies %d\n",j1);
                   5667:     
                   5668:     for (i=1; i<=imx; i++) { /* Each individual */
                   5669:       bool=1;
                   5670:       /* for(m=firstpass; m<=lastpass; m++){/\* Other selection (we can limit to certain interviews*\/ */
                   5671:       for(mi=1; mi<wav[i];mi++){ /* For this wave too look where individual can be counted V4=0 V3=0 */
                   5672:        m=mw[mi][i];
                   5673:        /* Tmodelind[z1]=k is the position of the varying covariate in the model, but which # within 1 to ntv? */
                   5674:        /* Tvar[Tmodelind[z1]] is the n of Vn; n-ncovcol-nqv is the first time varying covariate or iv */
                   5675:        for (z1=1; z1<=cptcoveff; z1++){
                   5676:          if( Fixed[Tmodelind[z1]]==1){
                   5677:            iv= Tvar[Tmodelind[z1]]-ncovcol-nqv;
1.332     brouard  5678:            if (cotvar[m][iv][i]!= nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]) /* iv=1 to ntv, right modality */
1.227     brouard  5679:              bool=0;
                   5680:          }else if( Fixed[Tmodelind[z1]]== 0)  /* fixed */
1.332     brouard  5681:            if (covar[Tvaraff[z1]][i]!= nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]) {
1.227     brouard  5682:              bool=0;
                   5683:            }
                   5684:        }
                   5685:        if(bool==1){ /* Otherwise we skip that wave/person */
                   5686:          agebegin=agev[m][i]; /* Age at beginning of wave before transition*/
                   5687:          /* ageend=agev[m][i]+(dh[m][i])*stepm/YEARM; /\* Age at end of wave and transition *\/ */
                   5688:          if(m >=firstpass && m <=lastpass){
                   5689:            y2=anint[m][i]+(mint[m][i]/12.); /* Fractional date in year */
                   5690:            if ((y2>=dateprev1) && (y2<=dateprev2)) { /* Here is the main selection (fractional years) */
                   5691:              if(agev[m][i]==0) agev[m][i]=iagemax+1;
                   5692:              if(agev[m][i]==1) agev[m][i]=iagemax+2;
1.251     brouard  5693:              if((int)agev[m][i] <iagemin-AGEMARGE || (int)agev[m][i] >iagemax+4+AGEMARGE){
1.227     brouard  5694:                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); 
                   5695:                exit(1);
                   5696:              }
                   5697:              if (s[m][i]>0 && s[m][i]<=nlstate) { 
                   5698:                /*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]]);*/
                   5699:                prop[s[m][i]][(int)agev[m][i]] += weight[i];/* At age of beginning of transition, where status is known */
                   5700:                prop[s[m][i]][iagemax+3] += weight[i]; 
                   5701:              } /* end valid statuses */ 
                   5702:            } /* end selection of dates */
                   5703:          } /* end selection of waves */
                   5704:        } /* end bool */
                   5705:       } /* end wave */
                   5706:     } /* end individual */
                   5707:     for(i=iagemin; i <= iagemax+3; i++){  
                   5708:       for(jk=1,posprop=0; jk <=nlstate ; jk++) { 
                   5709:        posprop += prop[jk][i]; 
                   5710:       } 
                   5711:       
                   5712:       for(jk=1; jk <=nlstate ; jk++){      
                   5713:        if( i <=  iagemax){ 
                   5714:          if(posprop>=1.e-5){ 
                   5715:            probs[i][jk][j1]= prop[jk][i]/posprop;
                   5716:          } else{
1.288     brouard  5717:            if(!first){
                   5718:              first=1;
1.266     brouard  5719:              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]);
                   5720:            }else{
1.288     brouard  5721:              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  5722:            }
                   5723:          }
                   5724:        } 
                   5725:       }/* end jk */ 
                   5726:     }/* end i */ 
1.222     brouard  5727:      /*} *//* end i1 */
1.227     brouard  5728:   } /* end j1 */
1.222     brouard  5729:   
1.227     brouard  5730:   /*  free_ma3x(freq,-1,nlstate+ndeath,-1,nlstate+ndeath, iagemin, iagemax+3);*/
                   5731:   /*free_vector(pp,1,nlstate);*/
1.251     brouard  5732:   free_matrix(prop,1,nlstate, iagemin-AGEMARGE,iagemax+4+AGEMARGE);
1.227     brouard  5733: }  /* End of prevalence */
1.126     brouard  5734: 
                   5735: /************* Waves Concatenation ***************/
                   5736: 
                   5737: 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)
                   5738: {
1.298     brouard  5739:   /* 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  5740:      Death is a valid wave (if date is known).
                   5741:      mw[mi][i] is the mi (mi=1 to wav[i])  effective wave of individual i
                   5742:      dh[m][i] or dh[mw[mi][i]][i] is the delay between two effective waves m=mw[mi][i]
1.298     brouard  5743:      and mw[mi+1][i]. dh depends on stepm. s[m][i] exists for any wave from firstpass to lastpass
1.227     brouard  5744:   */
1.126     brouard  5745: 
1.224     brouard  5746:   int i=0, mi=0, m=0, mli=0;
1.126     brouard  5747:   /* int j, k=0,jk, ju, jl,jmin=1e+5, jmax=-1;
                   5748:      double sum=0., jmean=0.;*/
1.224     brouard  5749:   int first=0, firstwo=0, firsthree=0, firstfour=0, firstfiv=0;
1.126     brouard  5750:   int j, k=0,jk, ju, jl;
                   5751:   double sum=0.;
                   5752:   first=0;
1.214     brouard  5753:   firstwo=0;
1.217     brouard  5754:   firsthree=0;
1.218     brouard  5755:   firstfour=0;
1.164     brouard  5756:   jmin=100000;
1.126     brouard  5757:   jmax=-1;
                   5758:   jmean=0.;
1.224     brouard  5759: 
                   5760: /* Treating live states */
1.214     brouard  5761:   for(i=1; i<=imx; i++){  /* For simple cases and if state is death */
1.224     brouard  5762:     mi=0;  /* First valid wave */
1.227     brouard  5763:     mli=0; /* Last valid wave */
1.309     brouard  5764:     m=firstpass;  /* Loop on waves */
                   5765:     while(s[m][i] <= nlstate){  /* a live state or unknown state  */
1.227     brouard  5766:       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 */
                   5767:        mli=m-1;/* mw[++mi][i]=m-1; */
                   5768:       }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  5769:        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  5770:        mli=m;
1.224     brouard  5771:       } /* else might be a useless wave  -1 and mi is not incremented and mw[mi] not updated */
                   5772:       if(m < lastpass){ /* m < lastpass, standard case */
1.227     brouard  5773:        m++; /* mi gives the "effective" current wave, m the current wave, go to next wave by incrementing m */
1.216     brouard  5774:       }
1.309     brouard  5775:       else{ /* m = lastpass, eventual special issue with warning */
1.224     brouard  5776: #ifdef UNKNOWNSTATUSNOTCONTRIBUTING
1.227     brouard  5777:        break;
1.224     brouard  5778: #else
1.317     brouard  5779:        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  5780:          if(firsthree == 0){
1.302     brouard  5781:            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  5782:            firsthree=1;
1.317     brouard  5783:          }else if(firsthree >=1 && firsthree < 10){
                   5784:            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);
                   5785:            firsthree++;
                   5786:          }else if(firsthree == 10){
                   5787:            printf("Information, too many Information flags: no more reported to log either\n");
                   5788:            fprintf(ficlog,"Information, too many Information flags: no more reported to log either\n");
                   5789:            firsthree++;
                   5790:          }else{
                   5791:            firsthree++;
1.227     brouard  5792:          }
1.309     brouard  5793:          mw[++mi][i]=m; /* Valid transition with unknown status */
1.227     brouard  5794:          mli=m;
                   5795:        }
                   5796:        if(s[m][i]==-2){ /* Vital status is really unknown */
                   5797:          nbwarn++;
1.309     brouard  5798:          if((int)anint[m][i] == 9999){  /*  Has the vital status really been verified?not a transition */
1.227     brouard  5799:            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);
                   5800:            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);
                   5801:          }
                   5802:          break;
                   5803:        }
                   5804:        break;
1.224     brouard  5805: #endif
1.227     brouard  5806:       }/* End m >= lastpass */
1.126     brouard  5807:     }/* end while */
1.224     brouard  5808: 
1.227     brouard  5809:     /* 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  5810:     /* After last pass */
1.224     brouard  5811: /* Treating death states */
1.214     brouard  5812:     if (s[m][i] > nlstate){  /* In a death state */
1.227     brouard  5813:       /* if( mint[m][i]==mdc[m][i] && anint[m][i]==andc[m][i]){ /\* same date of death and date of interview *\/ */
                   5814:       /* } */
1.126     brouard  5815:       mi++;    /* Death is another wave */
                   5816:       /* if(mi==0)  never been interviewed correctly before death */
1.227     brouard  5817:       /* Only death is a correct wave */
1.126     brouard  5818:       mw[mi][i]=m;
1.257     brouard  5819:     } /* else not in a death state */
1.224     brouard  5820: #ifndef DISPATCHINGKNOWNDEATHAFTERLASTWAVE
1.257     brouard  5821:     else if ((int) andc[i] != 9999) {  /* Date of death is known */
1.218     brouard  5822:       if ((int)anint[m][i]!= 9999) { /* date of last interview is known */
1.309     brouard  5823:        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  5824:          nbwarn++;
                   5825:          if(firstfiv==0){
1.309     brouard  5826:            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  5827:            firstfiv=1;
                   5828:          }else{
1.309     brouard  5829:            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  5830:          }
1.309     brouard  5831:            s[m][i]=nlstate+1; /* Fixing the status as death. Be careful if multiple death states */
                   5832:        }else{ /* Month of Death occured afer last wave month, potential bias */
1.227     brouard  5833:          nberr++;
                   5834:          if(firstwo==0){
1.309     brouard  5835:            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  5836:            firstwo=1;
                   5837:          }
1.309     brouard  5838:          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  5839:        }
1.257     brouard  5840:       }else{ /* if date of interview is unknown */
1.227     brouard  5841:        /* death is known but not confirmed by death status at any wave */
                   5842:        if(firstfour==0){
1.309     brouard  5843:          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  5844:          firstfour=1;
                   5845:        }
1.309     brouard  5846:        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  5847:       }
1.224     brouard  5848:     } /* end if date of death is known */
                   5849: #endif
1.309     brouard  5850:     wav[i]=mi; /* mi should be the last effective wave (or mli),  */
                   5851:     /* wav[i]=mw[mi][i];   */
1.126     brouard  5852:     if(mi==0){
                   5853:       nbwarn++;
                   5854:       if(first==0){
1.227     brouard  5855:        printf("Warning! No valid information for individual %ld line=%d (skipped) and may be others, see log file\n",num[i],i);
                   5856:        first=1;
1.126     brouard  5857:       }
                   5858:       if(first==1){
1.227     brouard  5859:        fprintf(ficlog,"Warning! No valid information for individual %ld line=%d (skipped)\n",num[i],i);
1.126     brouard  5860:       }
                   5861:     } /* end mi==0 */
                   5862:   } /* End individuals */
1.214     brouard  5863:   /* wav and mw are no more changed */
1.223     brouard  5864:        
1.317     brouard  5865:   printf("Information, you have to check %d informations which haven't been logged!\n",firsthree);
                   5866:   fprintf(ficlog,"Information, you have to check %d informations which haven't been logged!\n",firsthree);
                   5867: 
                   5868: 
1.126     brouard  5869:   for(i=1; i<=imx; i++){
                   5870:     for(mi=1; mi<wav[i];mi++){
                   5871:       if (stepm <=0)
1.227     brouard  5872:        dh[mi][i]=1;
1.126     brouard  5873:       else{
1.260     brouard  5874:        if (s[mw[mi+1][i]][i] > nlstate) { /* A death, but what if date is unknown? */
1.227     brouard  5875:          if (agedc[i] < 2*AGESUP) {
                   5876:            j= rint(agedc[i]*12-agev[mw[mi][i]][i]*12); 
                   5877:            if(j==0) j=1;  /* Survives at least one month after exam */
                   5878:            else if(j<0){
                   5879:              nberr++;
                   5880:              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]);
                   5881:              j=1; /* Temporary Dangerous patch */
                   5882:              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);
                   5883:              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]);
                   5884:              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);
                   5885:            }
                   5886:            k=k+1;
                   5887:            if (j >= jmax){
                   5888:              jmax=j;
                   5889:              ijmax=i;
                   5890:            }
                   5891:            if (j <= jmin){
                   5892:              jmin=j;
                   5893:              ijmin=i;
                   5894:            }
                   5895:            sum=sum+j;
                   5896:            /*if (j<0) printf("j=%d num=%d \n",j,i);*/
                   5897:            /*    printf("%d %d %d %d\n", s[mw[mi][i]][i] ,s[mw[mi+1][i]][i],j,i);*/
                   5898:          }
                   5899:        }
                   5900:        else{
                   5901:          j= rint( (agev[mw[mi+1][i]][i]*12 - agev[mw[mi][i]][i]*12));
1.126     brouard  5902: /*       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  5903:                                        
1.227     brouard  5904:          k=k+1;
                   5905:          if (j >= jmax) {
                   5906:            jmax=j;
                   5907:            ijmax=i;
                   5908:          }
                   5909:          else if (j <= jmin){
                   5910:            jmin=j;
                   5911:            ijmin=i;
                   5912:          }
                   5913:          /*        if (j<10) printf("j=%d jmin=%d num=%d ",j,jmin,i); */
                   5914:          /*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]);*/
                   5915:          if(j<0){
                   5916:            nberr++;
                   5917:            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]);
                   5918:            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]);
                   5919:          }
                   5920:          sum=sum+j;
                   5921:        }
                   5922:        jk= j/stepm;
                   5923:        jl= j -jk*stepm;
                   5924:        ju= j -(jk+1)*stepm;
                   5925:        if(mle <=1){ /* only if we use a the linear-interpoloation pseudo-likelihood */
                   5926:          if(jl==0){
                   5927:            dh[mi][i]=jk;
                   5928:            bh[mi][i]=0;
                   5929:          }else{ /* We want a negative bias in order to only have interpolation ie
                   5930:                  * to avoid the price of an extra matrix product in likelihood */
                   5931:            dh[mi][i]=jk+1;
                   5932:            bh[mi][i]=ju;
                   5933:          }
                   5934:        }else{
                   5935:          if(jl <= -ju){
                   5936:            dh[mi][i]=jk;
                   5937:            bh[mi][i]=jl;       /* bias is positive if real duration
                   5938:                                 * is higher than the multiple of stepm and negative otherwise.
                   5939:                                 */
                   5940:          }
                   5941:          else{
                   5942:            dh[mi][i]=jk+1;
                   5943:            bh[mi][i]=ju;
                   5944:          }
                   5945:          if(dh[mi][i]==0){
                   5946:            dh[mi][i]=1; /* At least one step */
                   5947:            bh[mi][i]=ju; /* At least one step */
                   5948:            /*  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);*/
                   5949:          }
                   5950:        } /* end if mle */
1.126     brouard  5951:       }
                   5952:     } /* end wave */
                   5953:   }
                   5954:   jmean=sum/k;
                   5955:   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  5956:   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  5957: }
1.126     brouard  5958: 
                   5959: /*********** Tricode ****************************/
1.220     brouard  5960:  void tricode(int *cptcov, int *Tvar, int **nbcode, int imx, int *Ndum)
1.242     brouard  5961:  {
                   5962:    /**< Uses cptcovn+2*cptcovprod as the number of covariates */
                   5963:    /*    Tvar[i]=atoi(stre);  find 'n' in Vn and stores in Tvar. If model=V2+V1 Tvar[1]=2 and Tvar[2]=1 
                   5964:     * Boring subroutine which should only output nbcode[Tvar[j]][k]
                   5965:     * Tvar[5] in V2+V1+V3*age+V2*V4 is 4 (V4) even it is a time varying or quantitative variable
                   5966:     * nbcode[Tvar[5]][1]= nbcode[4][1]=0, nbcode[4][2]=1 (usually);
                   5967:     */
1.130     brouard  5968: 
1.242     brouard  5969:    int ij=1, k=0, j=0, i=0, maxncov=NCOVMAX;
                   5970:    int modmaxcovj=0; /* Modality max of covariates j */
                   5971:    int cptcode=0; /* Modality max of covariates j */
                   5972:    int modmincovj=0; /* Modality min of covariates j */
1.145     brouard  5973: 
                   5974: 
1.242     brouard  5975:    /* cptcoveff=0;  */
                   5976:    /* *cptcov=0; */
1.126     brouard  5977:  
1.242     brouard  5978:    for (k=1; k <= maxncov; k++) ncodemax[k]=0; /* Horrible constant again replaced by NCOVMAX */
1.285     brouard  5979:    for (k=1; k <= maxncov; k++)
                   5980:      for(j=1; j<=2; j++)
                   5981:        nbcode[k][j]=0; /* Valgrind */
1.126     brouard  5982: 
1.242     brouard  5983:    /* Loop on covariates without age and products and no quantitative variable */
1.335     brouard  5984:    for (k=1; k<=cptcovt; k++) { /* cptcovt: total number of covariates of the model (2) nbocc(+)+1 = 8 excepting constant and age and age*age */
1.242     brouard  5985:      for (j=-1; (j < maxncov); j++) Ndum[j]=0;
                   5986:      if(Dummy[k]==0 && Typevar[k] !=1){ /* Dummy covariate and not age product */ 
                   5987:        switch(Fixed[k]) {
                   5988:        case 0: /* Testing on fixed dummy covariate, simple or product of fixed */
1.311     brouard  5989:         modmaxcovj=0;
                   5990:         modmincovj=0;
1.242     brouard  5991:         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*/
                   5992:           ij=(int)(covar[Tvar[k]][i]);
                   5993:           /* ij=0 or 1 or -1. Value of the covariate Tvar[j] for individual i
                   5994:            * If product of Vn*Vm, still boolean *:
                   5995:            * If it was coded 1, 2, 3, 4 should be splitted into 3 boolean variables
                   5996:            * 1 => 0 0 0, 2 => 0 0 1, 3 => 0 1 1, 4=1 0 0   */
                   5997:           /* Finds for covariate j, n=Tvar[j] of Vn . ij is the
                   5998:              modality of the nth covariate of individual i. */
                   5999:           if (ij > modmaxcovj)
                   6000:             modmaxcovj=ij; 
                   6001:           else if (ij < modmincovj) 
                   6002:             modmincovj=ij; 
1.287     brouard  6003:           if (ij <0 || ij >1 ){
1.311     brouard  6004:             printf("ERROR, IMaCh doesn't treat covariate with missing values V%d=-1, individual %d will be skipped.\n",Tvar[k],i);
                   6005:             fprintf(ficlog,"ERROR, currently IMaCh doesn't treat covariate with missing values V%d=-1, individual %d will be skipped.\n",Tvar[k],i);
                   6006:             fflush(ficlog);
                   6007:             exit(1);
1.287     brouard  6008:           }
                   6009:           if ((ij < -1) || (ij > NCOVMAX)){
1.242     brouard  6010:             printf( "Error: minimal is less than -1 or maximal is bigger than %d. Exiting. \n", NCOVMAX );
                   6011:             exit(1);
                   6012:           }else
                   6013:             Ndum[ij]++; /*counts and stores the occurence of this modality 0, 1, -1*/
                   6014:           /*  If coded 1, 2, 3 , counts the number of 1 Ndum[1], number of 2, Ndum[2], etc */
                   6015:           /*printf("i=%d ij=%d Ndum[ij]=%d imx=%d",i,ij,Ndum[ij],imx);*/
                   6016:           /* getting the maximum value of the modality of the covariate
                   6017:              (should be 0 or 1 now) Tvar[j]. If V=sex and male is coded 0 and
                   6018:              female ies 1, then modmaxcovj=1.
                   6019:           */
                   6020:         } /* end for loop on individuals i */
                   6021:         printf(" Minimal and maximal values of %d th (fixed) covariate V%d: min=%d max=%d \n", k, Tvar[k], modmincovj, modmaxcovj);
                   6022:         fprintf(ficlog," Minimal and maximal values of %d th (fixed) covariate V%d: min=%d max=%d \n", k, Tvar[k], modmincovj, modmaxcovj);
                   6023:         cptcode=modmaxcovj;
                   6024:         /* Ndum[0] = frequency of 0 for model-covariate j, Ndum[1] frequency of 1 etc. */
                   6025:         /*for (i=0; i<=cptcode; i++) {*/
                   6026:         for (j=modmincovj;  j<=modmaxcovj; j++) { /* j=-1 ? 0 and 1*//* For each value j of the modality of model-cov k */
                   6027:           printf("Frequencies of (fixed) covariate %d ie V%d with value %d: %d\n", k, Tvar[k], j, Ndum[j]);
                   6028:           fprintf(ficlog, "Frequencies of (fixed) covariate %d ie V%d with value %d: %d\n", k, Tvar[k], j, Ndum[j]);
                   6029:           if( Ndum[j] != 0 ){ /* Counts if nobody answered modality j ie empty modality, we skip it and reorder */
                   6030:             if( j != -1){
                   6031:               ncodemax[k]++;  /* ncodemax[k]= Number of modalities of the k th
                   6032:                                  covariate for which somebody answered excluding 
                   6033:                                  undefined. Usually 2: 0 and 1. */
                   6034:             }
                   6035:             ncodemaxwundef[k]++; /* ncodemax[j]= Number of modalities of the k th
                   6036:                                     covariate for which somebody answered including 
                   6037:                                     undefined. Usually 3: -1, 0 and 1. */
                   6038:           }    /* In fact  ncodemax[k]=2 (dichotom. variables only) but it could be more for
                   6039:                 * historical reasons: 3 if coded 1, 2, 3 and 4 and Ndum[2]=0 */
                   6040:         } /* Ndum[-1] number of undefined modalities */
1.231     brouard  6041:                        
1.242     brouard  6042:         /* j is a covariate, n=Tvar[j] of Vn; Fills nbcode */
                   6043:         /* For covariate j, modalities could be 1, 2, 3, 4, 5, 6, 7. */
                   6044:         /* If Ndum[1]=0, Ndum[2]=0, Ndum[3]= 635, Ndum[4]=0, Ndum[5]=0, Ndum[6]=27, Ndum[7]=125; */
                   6045:         /* modmincovj=3; modmaxcovj = 7; */
                   6046:         /* There are only 3 modalities non empty 3, 6, 7 (or 2 if 27 is too few) : ncodemax[j]=3; */
                   6047:         /* which will be coded 0, 1, 2 which in binary on 2=3-1 digits are 0=00 1=01, 2=10; */
                   6048:         /*              defining two dummy variables: variables V1_1 and V1_2.*/
                   6049:         /* nbcode[Tvar[j]][ij]=k; */
                   6050:         /* nbcode[Tvar[j]][1]=0; */
                   6051:         /* nbcode[Tvar[j]][2]=1; */
                   6052:         /* nbcode[Tvar[j]][3]=2; */
                   6053:         /* To be continued (not working yet). */
                   6054:         ij=0; /* ij is similar to i but can jump over null modalities */
1.287     brouard  6055: 
                   6056:         /* 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*/
                   6057:         /* Skipping the case of missing values by reducing nbcode to 0 and 1 and not -1, 0, 1 */
                   6058:         /* model=V1+V2+V3, if V2=-1, 0 or 1, then nbcode[2][1]=0 and nbcode[2][2]=1 instead of
                   6059:          * nbcode[2][1]=-1, nbcode[2][2]=0 and nbcode[2][3]=1 */
                   6060:         /*, could be restored in the future */
                   6061:         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  6062:           if (Ndum[i] == 0) { /* If nobody responded to this modality k */
                   6063:             break;
                   6064:           }
                   6065:           ij++;
1.287     brouard  6066:           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  6067:           cptcode = ij; /* New max modality for covar j */
                   6068:         } /* end of loop on modality i=-1 to 1 or more */
                   6069:         break;
                   6070:        case 1: /* Testing on varying covariate, could be simple and
                   6071:                * should look at waves or product of fixed *
                   6072:                * varying. No time to test -1, assuming 0 and 1 only */
                   6073:         ij=0;
                   6074:         for(i=0; i<=1;i++){
                   6075:           nbcode[Tvar[k]][++ij]=i;
                   6076:         }
                   6077:         break;
                   6078:        default:
                   6079:         break;
                   6080:        } /* end switch */
                   6081:      } /* end dummy test */
1.334     brouard  6082:      if(Dummy[k]==1 && Typevar[k] !=1){ /* Quantitative covariate and not age product */ 
1.311     brouard  6083:        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*/
1.335     brouard  6084:         if(Tvar[k]<=0 || Tvar[k]>=NCOVMAX){
                   6085:           printf("Error k=%d \n",k);
                   6086:           exit(1);
                   6087:         }
1.311     brouard  6088:         if(isnan(covar[Tvar[k]][i])){
                   6089:           printf("ERROR, IMaCh doesn't treat fixed quantitative covariate with missing values V%d=., individual %d will be skipped.\n",Tvar[k],i);
                   6090:           fprintf(ficlog,"ERROR, currently IMaCh doesn't treat covariate with missing values V%d=., individual %d will be skipped.\n",Tvar[k],i);
                   6091:           fflush(ficlog);
                   6092:           exit(1);
                   6093:          }
                   6094:        }
1.335     brouard  6095:      } /* end Quanti */
1.287     brouard  6096:    } /* 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  6097:   
                   6098:    for (k=-1; k< maxncov; k++) Ndum[k]=0; 
                   6099:    /* Look at fixed dummy (single or product) covariates to check empty modalities */
                   6100:    for (i=1; i<=ncovmodel-2-nagesqr; i++) { /* -2, cste and age and eventually age*age */ 
                   6101:      /* Listing of all covariables in statement model to see if some covariates appear twice. For example, V1 appears twice in V1+V1*V2.*/ 
                   6102:      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 */ 
                   6103:      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 */
                   6104:      /* V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1,  {2, 1, 1, 1, 2, 1, 1, 0, 0} */
                   6105:    } /* V4+V3+V5, Ndum[1]@5={0, 0, 1, 1, 1} */
                   6106:   
                   6107:    ij=0;
                   6108:    /* for (i=0; i<=  maxncov-1; i++) { /\* modmaxcovj is unknown here. Only Ndum[2(V2),3(age*V3), 5(V3*V2) 6(V1*V4) *\/ */
1.335     brouard  6109:    for (k=1; k<=  cptcovt; k++) { /* cptcovt: total number of covariates of the model (2) nbocc(+)+1 = 8 excepting constant and age and age*age */
                   6110:      /* modmaxcovj is unknown here. Only Ndum[2(V2),3(age*V3), 5(V3*V2) 6(V1*V4) */
1.242     brouard  6111:      /*printf("Ndum[%d]=%d\n",i, Ndum[i]);*/
                   6112:      /* if((Ndum[i]!=0) && (i<=ncovcol)){  /\* Tvar[i] <= ncovmodel ? *\/ */
1.335     brouard  6113:      if(Ndum[Tvar[k]]!=0 && Dummy[k] == 0 && Typevar[k]==0){  /* Only Dummy simple and non empty in the model */
                   6114:        /* Typevar[k] =0 for simple covariate (dummy, quantitative, fixed or varying), 1 for age product, 2 for product */
                   6115:        /* Dummy[k] 0=dummy (0 1), 1 quantitative (single or product without age), 2 dummy with age product, 3 quant with age product*/
1.242     brouard  6116:        /* If product not in single variable we don't print results */
                   6117:        /*printf("diff Ndum[%d]=%d\n",i, Ndum[i]);*/
1.335     brouard  6118:        ++ij;/*    V5 + V4 + V3 + V4*V3 + V5*age + V2 +  V1*V2 + V1*age + V1, *//* V5 quanti, V2 quanti, V4, V3, V1 dummies */
                   6119:        /* k=       1    2   3     4       5       6      7       8        9  */
                   6120:        /* Tvar[k]= 5    4    3    6       5       2      7       1        1  */
                   6121:        /* ij            1    2                                            3  */  
                   6122:        /* Tvaraff[ij]=  4    3                                            1  */
                   6123:        /* Tmodelind[ij]=2    3                                            9  */
                   6124:        /* TmodelInvind[ij]=2 1                                            1  */
1.242     brouard  6125:        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*/
                   6126:        Tmodelind[ij]=k; /* Tmodelind: index in model of dummies Tmodelind[1]=2 V4: pos=2; V3: pos=3, V1=9 {2, 3, 9, ?, ?,} */
                   6127:        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 */
                   6128:        if(Fixed[k]!=0)
                   6129:         anyvaryingduminmodel=1;
                   6130:        /* }else if((Ndum[i]!=0) && (i<=ncovcol+nqv)){ */
                   6131:        /*   Tvaraff[++ij]=-10; /\* Dont'n know how to treat quantitative variables yet *\/ */
                   6132:        /* }else if((Ndum[i]!=0) && (i<=ncovcol+nqv+ntv)){ */
                   6133:        /*   Tvaraff[++ij]=i; /\*For printing (unclear) *\/ */
                   6134:        /* }else if((Ndum[i]!=0) && (i<=ncovcol+nqv+ntv+nqtv)){ */
                   6135:        /*   Tvaraff[++ij]=-20; /\* Dont'n know how to treat quantitative variables yet *\/ */
                   6136:      } 
                   6137:    } /* Tvaraff[1]@5 {3, 4, -20, 0, 0} Very strange */
                   6138:    /* ij--; */
                   6139:    /* cptcoveff=ij; /\*Number of total covariates*\/ */
1.335     brouard  6140:    *cptcov=ij; /* cptcov= Number of total real effective simple dummies (fixed or time  arying) effective (used as cptcoveff in other functions)
1.242     brouard  6141:                * because they can be excluded from the model and real
                   6142:                * if in the model but excluded because missing values, but how to get k from ij?*/
                   6143:    for(j=ij+1; j<= cptcovt; j++){
                   6144:      Tvaraff[j]=0;
                   6145:      Tmodelind[j]=0;
                   6146:    }
                   6147:    for(j=ntveff+1; j<= cptcovt; j++){
                   6148:      TmodelInvind[j]=0;
                   6149:    }
                   6150:    /* To be sorted */
                   6151:    ;
                   6152:  }
1.126     brouard  6153: 
1.145     brouard  6154: 
1.126     brouard  6155: /*********** Health Expectancies ****************/
                   6156: 
1.235     brouard  6157:  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  6158: 
                   6159: {
                   6160:   /* Health expectancies, no variances */
1.329     brouard  6161:   /* cij is the combination in the list of combination of dummy covariates */
                   6162:   /* strstart is a string of time at start of computing */
1.164     brouard  6163:   int i, j, nhstepm, hstepm, h, nstepm;
1.126     brouard  6164:   int nhstepma, nstepma; /* Decreasing with age */
                   6165:   double age, agelim, hf;
                   6166:   double ***p3mat;
                   6167:   double eip;
                   6168: 
1.238     brouard  6169:   /* pstamp(ficreseij); */
1.126     brouard  6170:   fprintf(ficreseij,"# (a) Life expectancies by health status at initial age and (b) health expectancies by health status at initial age\n");
                   6171:   fprintf(ficreseij,"# Age");
                   6172:   for(i=1; i<=nlstate;i++){
                   6173:     for(j=1; j<=nlstate;j++){
                   6174:       fprintf(ficreseij," e%1d%1d ",i,j);
                   6175:     }
                   6176:     fprintf(ficreseij," e%1d. ",i);
                   6177:   }
                   6178:   fprintf(ficreseij,"\n");
                   6179: 
                   6180:   
                   6181:   if(estepm < stepm){
                   6182:     printf ("Problem %d lower than %d\n",estepm, stepm);
                   6183:   }
                   6184:   else  hstepm=estepm;   
                   6185:   /* We compute the life expectancy from trapezoids spaced every estepm months
                   6186:    * This is mainly to measure the difference between two models: for example
                   6187:    * if stepm=24 months pijx are given only every 2 years and by summing them
                   6188:    * we are calculating an estimate of the Life Expectancy assuming a linear 
                   6189:    * progression in between and thus overestimating or underestimating according
                   6190:    * to the curvature of the survival function. If, for the same date, we 
                   6191:    * estimate the model with stepm=1 month, we can keep estepm to 24 months
                   6192:    * to compare the new estimate of Life expectancy with the same linear 
                   6193:    * hypothesis. A more precise result, taking into account a more precise
                   6194:    * curvature will be obtained if estepm is as small as stepm. */
                   6195: 
                   6196:   /* For example we decided to compute the life expectancy with the smallest unit */
                   6197:   /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm. 
                   6198:      nhstepm is the number of hstepm from age to agelim 
                   6199:      nstepm is the number of stepm from age to agelin. 
1.270     brouard  6200:      Look at hpijx to understand the reason which relies in memory size consideration
1.126     brouard  6201:      and note for a fixed period like estepm months */
                   6202:   /* We decided (b) to get a life expectancy respecting the most precise curvature of the
                   6203:      survival function given by stepm (the optimization length). Unfortunately it
                   6204:      means that if the survival funtion is printed only each two years of age and if
                   6205:      you sum them up and add 1 year (area under the trapezoids) you won't get the same 
                   6206:      results. So we changed our mind and took the option of the best precision.
                   6207:   */
                   6208:   hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */ 
                   6209: 
                   6210:   agelim=AGESUP;
                   6211:   /* If stepm=6 months */
                   6212:     /* Computed by stepm unit matrices, product of hstepm matrices, stored
                   6213:        in an array of nhstepm length: nhstepm=10, hstepm=4, stepm=6 months */
                   6214:     
                   6215: /* nhstepm age range expressed in number of stepm */
                   6216:   nstepm=(int) rint((agelim-bage)*YEARM/stepm); /* Biggest nstepm */
                   6217:   /* Typically if 20 years nstepm = 20*12/6=40 stepm */ 
                   6218:   /* if (stepm >= YEARM) hstepm=1;*/
                   6219:   nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
                   6220:   p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   6221: 
                   6222:   for (age=bage; age<=fage; age ++){ 
                   6223:     nstepma=(int) rint((agelim-bage)*YEARM/stepm); /* Biggest nstepm */
                   6224:     /* Typically if 20 years nstepm = 20*12/6=40 stepm */ 
                   6225:     /* if (stepm >= YEARM) hstepm=1;*/
                   6226:     nhstepma = nstepma/hstepm;/* Expressed in hstepm, typically nhstepma=40/4=10 */
                   6227: 
                   6228:     /* If stepm=6 months */
                   6229:     /* Computed by stepm unit matrices, product of hstepma matrices, stored
                   6230:        in an array of nhstepma length: nhstepma=10, hstepm=4, stepm=6 months */
1.330     brouard  6231:     /* 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  6232:     hpxij(p3mat,nhstepma,age,hstepm,x,nlstate,stepm,oldm, savm, cij, nres);  
1.126     brouard  6233:     
                   6234:     hf=hstepm*stepm/YEARM;  /* Duration of hstepm expressed in year unit. */
                   6235:     
                   6236:     printf("%d|",(int)age);fflush(stdout);
                   6237:     fprintf(ficlog,"%d|",(int)age);fflush(ficlog);
                   6238:     
                   6239:     /* Computing expectancies */
                   6240:     for(i=1; i<=nlstate;i++)
                   6241:       for(j=1; j<=nlstate;j++)
                   6242:        for (h=0, eij[i][j][(int)age]=0; h<=nhstepm-1; h++){
                   6243:          eij[i][j][(int)age] += (p3mat[i][j][h]+p3mat[i][j][h+1])/2.0*hf;
                   6244:          
                   6245:          /* 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]);*/
                   6246: 
                   6247:        }
                   6248: 
                   6249:     fprintf(ficreseij,"%3.0f",age );
                   6250:     for(i=1; i<=nlstate;i++){
                   6251:       eip=0;
                   6252:       for(j=1; j<=nlstate;j++){
                   6253:        eip +=eij[i][j][(int)age];
                   6254:        fprintf(ficreseij,"%9.4f", eij[i][j][(int)age] );
                   6255:       }
                   6256:       fprintf(ficreseij,"%9.4f", eip );
                   6257:     }
                   6258:     fprintf(ficreseij,"\n");
                   6259:     
                   6260:   }
                   6261:   free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   6262:   printf("\n");
                   6263:   fprintf(ficlog,"\n");
                   6264:   
                   6265: }
                   6266: 
1.235     brouard  6267:  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  6268: 
                   6269: {
                   6270:   /* Covariances of health expectancies eij and of total life expectancies according
1.222     brouard  6271:      to initial status i, ei. .
1.126     brouard  6272:   */
1.336   ! brouard  6273:   /* Very time consuming function, but already optimized with precov */
1.126     brouard  6274:   int i, j, nhstepm, hstepm, h, nstepm, k, cptj, cptj2, i2, j2, ij, ji;
                   6275:   int nhstepma, nstepma; /* Decreasing with age */
                   6276:   double age, agelim, hf;
                   6277:   double ***p3matp, ***p3matm, ***varhe;
                   6278:   double **dnewm,**doldm;
                   6279:   double *xp, *xm;
                   6280:   double **gp, **gm;
                   6281:   double ***gradg, ***trgradg;
                   6282:   int theta;
                   6283: 
                   6284:   double eip, vip;
                   6285: 
                   6286:   varhe=ma3x(1,nlstate*nlstate,1,nlstate*nlstate,(int) bage, (int) fage);
                   6287:   xp=vector(1,npar);
                   6288:   xm=vector(1,npar);
                   6289:   dnewm=matrix(1,nlstate*nlstate,1,npar);
                   6290:   doldm=matrix(1,nlstate*nlstate,1,nlstate*nlstate);
                   6291:   
                   6292:   pstamp(ficresstdeij);
                   6293:   fprintf(ficresstdeij,"# Health expectancies with standard errors\n");
                   6294:   fprintf(ficresstdeij,"# Age");
                   6295:   for(i=1; i<=nlstate;i++){
                   6296:     for(j=1; j<=nlstate;j++)
                   6297:       fprintf(ficresstdeij," e%1d%1d (SE)",i,j);
                   6298:     fprintf(ficresstdeij," e%1d. ",i);
                   6299:   }
                   6300:   fprintf(ficresstdeij,"\n");
                   6301: 
                   6302:   pstamp(ficrescveij);
                   6303:   fprintf(ficrescveij,"# Subdiagonal matrix of covariances of health expectancies by age: cov(eij,ekl)\n");
                   6304:   fprintf(ficrescveij,"# Age");
                   6305:   for(i=1; i<=nlstate;i++)
                   6306:     for(j=1; j<=nlstate;j++){
                   6307:       cptj= (j-1)*nlstate+i;
                   6308:       for(i2=1; i2<=nlstate;i2++)
                   6309:        for(j2=1; j2<=nlstate;j2++){
                   6310:          cptj2= (j2-1)*nlstate+i2;
                   6311:          if(cptj2 <= cptj)
                   6312:            fprintf(ficrescveij,"  %1d%1d,%1d%1d",i,j,i2,j2);
                   6313:        }
                   6314:     }
                   6315:   fprintf(ficrescveij,"\n");
                   6316:   
                   6317:   if(estepm < stepm){
                   6318:     printf ("Problem %d lower than %d\n",estepm, stepm);
                   6319:   }
                   6320:   else  hstepm=estepm;   
                   6321:   /* We compute the life expectancy from trapezoids spaced every estepm months
                   6322:    * This is mainly to measure the difference between two models: for example
                   6323:    * if stepm=24 months pijx are given only every 2 years and by summing them
                   6324:    * we are calculating an estimate of the Life Expectancy assuming a linear 
                   6325:    * progression in between and thus overestimating or underestimating according
                   6326:    * to the curvature of the survival function. If, for the same date, we 
                   6327:    * estimate the model with stepm=1 month, we can keep estepm to 24 months
                   6328:    * to compare the new estimate of Life expectancy with the same linear 
                   6329:    * hypothesis. A more precise result, taking into account a more precise
                   6330:    * curvature will be obtained if estepm is as small as stepm. */
                   6331: 
                   6332:   /* For example we decided to compute the life expectancy with the smallest unit */
                   6333:   /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm. 
                   6334:      nhstepm is the number of hstepm from age to agelim 
                   6335:      nstepm is the number of stepm from age to agelin. 
                   6336:      Look at hpijx to understand the reason of that which relies in memory size
                   6337:      and note for a fixed period like estepm months */
                   6338:   /* We decided (b) to get a life expectancy respecting the most precise curvature of the
                   6339:      survival function given by stepm (the optimization length). Unfortunately it
                   6340:      means that if the survival funtion is printed only each two years of age and if
                   6341:      you sum them up and add 1 year (area under the trapezoids) you won't get the same 
                   6342:      results. So we changed our mind and took the option of the best precision.
                   6343:   */
                   6344:   hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */ 
                   6345: 
                   6346:   /* If stepm=6 months */
                   6347:   /* nhstepm age range expressed in number of stepm */
                   6348:   agelim=AGESUP;
                   6349:   nstepm=(int) rint((agelim-bage)*YEARM/stepm); 
                   6350:   /* Typically if 20 years nstepm = 20*12/6=40 stepm */ 
                   6351:   /* if (stepm >= YEARM) hstepm=1;*/
                   6352:   nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
                   6353:   
                   6354:   p3matp=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   6355:   p3matm=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   6356:   gradg=ma3x(0,nhstepm,1,npar,1,nlstate*nlstate);
                   6357:   trgradg =ma3x(0,nhstepm,1,nlstate*nlstate,1,npar);
                   6358:   gp=matrix(0,nhstepm,1,nlstate*nlstate);
                   6359:   gm=matrix(0,nhstepm,1,nlstate*nlstate);
                   6360: 
                   6361:   for (age=bage; age<=fage; age ++){ 
                   6362:     nstepma=(int) rint((agelim-bage)*YEARM/stepm); /* Biggest nstepm */
                   6363:     /* Typically if 20 years nstepm = 20*12/6=40 stepm */ 
                   6364:     /* if (stepm >= YEARM) hstepm=1;*/
                   6365:     nhstepma = nstepma/hstepm;/* Expressed in hstepm, typically nhstepma=40/4=10 */
1.218     brouard  6366:                
1.126     brouard  6367:     /* If stepm=6 months */
                   6368:     /* Computed by stepm unit matrices, product of hstepma matrices, stored
                   6369:        in an array of nhstepma length: nhstepma=10, hstepm=4, stepm=6 months */
                   6370:     
                   6371:     hf=hstepm*stepm/YEARM;  /* Duration of hstepm expressed in year unit. */
1.218     brouard  6372:                
1.126     brouard  6373:     /* Computing  Variances of health expectancies */
                   6374:     /* Gradient is computed with plus gp and minus gm. Code is duplicated in order to
                   6375:        decrease memory allocation */
                   6376:     for(theta=1; theta <=npar; theta++){
                   6377:       for(i=1; i<=npar; i++){ 
1.222     brouard  6378:        xp[i] = x[i] + (i==theta ?delti[theta]:0);
                   6379:        xm[i] = x[i] - (i==theta ?delti[theta]:0);
1.126     brouard  6380:       }
1.235     brouard  6381:       hpxij(p3matp,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, cij, nres);  
                   6382:       hpxij(p3matm,nhstepm,age,hstepm,xm,nlstate,stepm,oldm,savm, cij, nres);  
1.218     brouard  6383:                        
1.126     brouard  6384:       for(j=1; j<= nlstate; j++){
1.222     brouard  6385:        for(i=1; i<=nlstate; i++){
                   6386:          for(h=0; h<=nhstepm-1; h++){
                   6387:            gp[h][(j-1)*nlstate + i] = (p3matp[i][j][h]+p3matp[i][j][h+1])/2.;
                   6388:            gm[h][(j-1)*nlstate + i] = (p3matm[i][j][h]+p3matm[i][j][h+1])/2.;
                   6389:          }
                   6390:        }
1.126     brouard  6391:       }
1.218     brouard  6392:                        
1.126     brouard  6393:       for(ij=1; ij<= nlstate*nlstate; ij++)
1.222     brouard  6394:        for(h=0; h<=nhstepm-1; h++){
                   6395:          gradg[h][theta][ij]= (gp[h][ij]-gm[h][ij])/2./delti[theta];
                   6396:        }
1.126     brouard  6397:     }/* End theta */
                   6398:     
                   6399:     
                   6400:     for(h=0; h<=nhstepm-1; h++)
                   6401:       for(j=1; j<=nlstate*nlstate;j++)
1.222     brouard  6402:        for(theta=1; theta <=npar; theta++)
                   6403:          trgradg[h][j][theta]=gradg[h][theta][j];
1.126     brouard  6404:     
1.218     brouard  6405:                
1.222     brouard  6406:     for(ij=1;ij<=nlstate*nlstate;ij++)
1.126     brouard  6407:       for(ji=1;ji<=nlstate*nlstate;ji++)
1.222     brouard  6408:        varhe[ij][ji][(int)age] =0.;
1.218     brouard  6409:                
1.222     brouard  6410:     printf("%d|",(int)age);fflush(stdout);
                   6411:     fprintf(ficlog,"%d|",(int)age);fflush(ficlog);
                   6412:     for(h=0;h<=nhstepm-1;h++){
1.126     brouard  6413:       for(k=0;k<=nhstepm-1;k++){
1.222     brouard  6414:        matprod2(dnewm,trgradg[h],1,nlstate*nlstate,1,npar,1,npar,matcov);
                   6415:        matprod2(doldm,dnewm,1,nlstate*nlstate,1,npar,1,nlstate*nlstate,gradg[k]);
                   6416:        for(ij=1;ij<=nlstate*nlstate;ij++)
                   6417:          for(ji=1;ji<=nlstate*nlstate;ji++)
                   6418:            varhe[ij][ji][(int)age] += doldm[ij][ji]*hf*hf;
1.126     brouard  6419:       }
                   6420:     }
1.320     brouard  6421:     /* if((int)age ==50){ */
                   6422:     /*   printf(" age=%d cij=%d nres=%d varhe[%d][%d]=%f ",(int)age, cij, nres, 1,2,varhe[1][2]); */
                   6423:     /* } */
1.126     brouard  6424:     /* Computing expectancies */
1.235     brouard  6425:     hpxij(p3matm,nhstepm,age,hstepm,x,nlstate,stepm,oldm, savm, cij,nres);  
1.126     brouard  6426:     for(i=1; i<=nlstate;i++)
                   6427:       for(j=1; j<=nlstate;j++)
1.222     brouard  6428:        for (h=0, eij[i][j][(int)age]=0; h<=nhstepm-1; h++){
                   6429:          eij[i][j][(int)age] += (p3matm[i][j][h]+p3matm[i][j][h+1])/2.0*hf;
1.218     brouard  6430:                                        
1.222     brouard  6431:          /* 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  6432:                                        
1.222     brouard  6433:        }
1.269     brouard  6434: 
                   6435:     /* Standard deviation of expectancies ij */                
1.126     brouard  6436:     fprintf(ficresstdeij,"%3.0f",age );
                   6437:     for(i=1; i<=nlstate;i++){
                   6438:       eip=0.;
                   6439:       vip=0.;
                   6440:       for(j=1; j<=nlstate;j++){
1.222     brouard  6441:        eip += eij[i][j][(int)age];
                   6442:        for(k=1; k<=nlstate;k++) /* Sum on j and k of cov(eij,eik) */
                   6443:          vip += varhe[(j-1)*nlstate+i][(k-1)*nlstate+i][(int)age];
                   6444:        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  6445:       }
                   6446:       fprintf(ficresstdeij," %9.4f (%.4f)", eip, sqrt(vip));
                   6447:     }
                   6448:     fprintf(ficresstdeij,"\n");
1.218     brouard  6449:                
1.269     brouard  6450:     /* Variance of expectancies ij */          
1.126     brouard  6451:     fprintf(ficrescveij,"%3.0f",age );
                   6452:     for(i=1; i<=nlstate;i++)
                   6453:       for(j=1; j<=nlstate;j++){
1.222     brouard  6454:        cptj= (j-1)*nlstate+i;
                   6455:        for(i2=1; i2<=nlstate;i2++)
                   6456:          for(j2=1; j2<=nlstate;j2++){
                   6457:            cptj2= (j2-1)*nlstate+i2;
                   6458:            if(cptj2 <= cptj)
                   6459:              fprintf(ficrescveij," %.4f", varhe[cptj][cptj2][(int)age]);
                   6460:          }
1.126     brouard  6461:       }
                   6462:     fprintf(ficrescveij,"\n");
1.218     brouard  6463:                
1.126     brouard  6464:   }
                   6465:   free_matrix(gm,0,nhstepm,1,nlstate*nlstate);
                   6466:   free_matrix(gp,0,nhstepm,1,nlstate*nlstate);
                   6467:   free_ma3x(gradg,0,nhstepm,1,npar,1,nlstate*nlstate);
                   6468:   free_ma3x(trgradg,0,nhstepm,1,nlstate*nlstate,1,npar);
                   6469:   free_ma3x(p3matm,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   6470:   free_ma3x(p3matp,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   6471:   printf("\n");
                   6472:   fprintf(ficlog,"\n");
1.218     brouard  6473:        
1.126     brouard  6474:   free_vector(xm,1,npar);
                   6475:   free_vector(xp,1,npar);
                   6476:   free_matrix(dnewm,1,nlstate*nlstate,1,npar);
                   6477:   free_matrix(doldm,1,nlstate*nlstate,1,nlstate*nlstate);
                   6478:   free_ma3x(varhe,1,nlstate*nlstate,1,nlstate*nlstate,(int) bage, (int)fage);
                   6479: }
1.218     brouard  6480:  
1.126     brouard  6481: /************ Variance ******************/
1.235     brouard  6482:  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  6483:  {
1.279     brouard  6484:    /** Variance of health expectancies 
                   6485:     *  double **prevalim(double **prlim, int nlstate, double *xp, double age, double **oldm, double ** savm,double ftolpl);
                   6486:     * double **newm;
                   6487:     * int movingaverage(double ***probs, double bage,double fage, double ***mobaverage, int mobilav) 
                   6488:     */
1.218     brouard  6489:   
                   6490:    /* int movingaverage(); */
                   6491:    double **dnewm,**doldm;
                   6492:    double **dnewmp,**doldmp;
                   6493:    int i, j, nhstepm, hstepm, h, nstepm ;
1.288     brouard  6494:    int first=0;
1.218     brouard  6495:    int k;
                   6496:    double *xp;
1.279     brouard  6497:    double **gp, **gm;  /**< for var eij */
                   6498:    double ***gradg, ***trgradg; /**< for var eij */
                   6499:    double **gradgp, **trgradgp; /**< for var p point j */
                   6500:    double *gpp, *gmp; /**< for var p point j */
                   6501:    double **varppt; /**< for var p point j nlstate to nlstate+ndeath */
1.218     brouard  6502:    double ***p3mat;
                   6503:    double age,agelim, hf;
                   6504:    /* double ***mobaverage; */
                   6505:    int theta;
                   6506:    char digit[4];
                   6507:    char digitp[25];
                   6508: 
                   6509:    char fileresprobmorprev[FILENAMELENGTH];
                   6510: 
                   6511:    if(popbased==1){
                   6512:      if(mobilav!=0)
                   6513:        strcpy(digitp,"-POPULBASED-MOBILAV_");
                   6514:      else strcpy(digitp,"-POPULBASED-NOMOBIL_");
                   6515:    }
                   6516:    else 
                   6517:      strcpy(digitp,"-STABLBASED_");
1.126     brouard  6518: 
1.218     brouard  6519:    /* if (mobilav!=0) { */
                   6520:    /*   mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX); */
                   6521:    /*   if (movingaverage(probs, bage, fage, mobaverage,mobilav)!=0){ */
                   6522:    /*     fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav); */
                   6523:    /*     printf(" Error in movingaverage mobilav=%d\n",mobilav); */
                   6524:    /*   } */
                   6525:    /* } */
                   6526: 
                   6527:    strcpy(fileresprobmorprev,"PRMORPREV-"); 
                   6528:    sprintf(digit,"%-d",ij);
                   6529:    /*printf("DIGIT=%s, ij=%d ijr=%-d|\n",digit, ij,ij);*/
                   6530:    strcat(fileresprobmorprev,digit); /* Tvar to be done */
                   6531:    strcat(fileresprobmorprev,digitp); /* Popbased or not, mobilav or not */
                   6532:    strcat(fileresprobmorprev,fileresu);
                   6533:    if((ficresprobmorprev=fopen(fileresprobmorprev,"w"))==NULL) {
                   6534:      printf("Problem with resultfile: %s\n", fileresprobmorprev);
                   6535:      fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobmorprev);
                   6536:    }
                   6537:    printf("Computing total mortality p.j=w1*p1j+w2*p2j+..: result on file '%s' \n",fileresprobmorprev);
                   6538:    fprintf(ficlog,"Computing total mortality p.j=w1*p1j+w2*p2j+..: result on file '%s' \n",fileresprobmorprev);
                   6539:    pstamp(ficresprobmorprev);
                   6540:    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  6541:    fprintf(ficresprobmorprev,"# Selected quantitative variables and dummies");
1.334     brouard  6542:    for (j=1; j<= nsq; j++){ /* For each selected (single) quantitative value */ /* To be done*/
1.332     brouard  6543:      fprintf(ficresprobmorprev," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]);
1.238     brouard  6544:    }
                   6545:    for(j=1;j<=cptcoveff;j++) 
1.334     brouard  6546:      fprintf(ficresprobmorprev," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(ij,TnsdVar[Tvaraff[j]])]);
1.238     brouard  6547:    fprintf(ficresprobmorprev,"\n");
                   6548: 
1.218     brouard  6549:    fprintf(ficresprobmorprev,"# Age cov=%-d",ij);
                   6550:    for(j=nlstate+1; j<=(nlstate+ndeath);j++){
                   6551:      fprintf(ficresprobmorprev," p.%-d SE",j);
                   6552:      for(i=1; i<=nlstate;i++)
                   6553:        fprintf(ficresprobmorprev," w%1d p%-d%-d",i,i,j);
                   6554:    }  
                   6555:    fprintf(ficresprobmorprev,"\n");
                   6556:   
                   6557:    fprintf(ficgp,"\n# Routine varevsij");
                   6558:    fprintf(ficgp,"\nunset title \n");
                   6559:    /* fprintf(fichtm, "#Local time at start: %s", strstart);*/
                   6560:    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");
                   6561:    fprintf(fichtm,"\n<br>%s  <br>\n",digitp);
1.279     brouard  6562: 
1.218     brouard  6563:    varppt = matrix(nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
                   6564:    pstamp(ficresvij);
                   6565:    fprintf(ficresvij,"# Variance and covariance of health expectancies e.j \n#  (weighted average of eij where weights are ");
                   6566:    if(popbased==1)
                   6567:      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);
                   6568:    else
                   6569:      fprintf(ficresvij,"the age specific period (stable) prevalences in each health state \n");
                   6570:    fprintf(ficresvij,"# Age");
                   6571:    for(i=1; i<=nlstate;i++)
                   6572:      for(j=1; j<=nlstate;j++)
                   6573:        fprintf(ficresvij," Cov(e.%1d, e.%1d)",i,j);
                   6574:    fprintf(ficresvij,"\n");
                   6575: 
                   6576:    xp=vector(1,npar);
                   6577:    dnewm=matrix(1,nlstate,1,npar);
                   6578:    doldm=matrix(1,nlstate,1,nlstate);
                   6579:    dnewmp= matrix(nlstate+1,nlstate+ndeath,1,npar);
                   6580:    doldmp= matrix(nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
                   6581: 
                   6582:    gradgp=matrix(1,npar,nlstate+1,nlstate+ndeath);
                   6583:    gpp=vector(nlstate+1,nlstate+ndeath);
                   6584:    gmp=vector(nlstate+1,nlstate+ndeath);
                   6585:    trgradgp =matrix(nlstate+1,nlstate+ndeath,1,npar); /* mu or p point j*/
1.126     brouard  6586:   
1.218     brouard  6587:    if(estepm < stepm){
                   6588:      printf ("Problem %d lower than %d\n",estepm, stepm);
                   6589:    }
                   6590:    else  hstepm=estepm;   
                   6591:    /* For example we decided to compute the life expectancy with the smallest unit */
                   6592:    /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm. 
                   6593:       nhstepm is the number of hstepm from age to agelim 
                   6594:       nstepm is the number of stepm from age to agelim. 
                   6595:       Look at function hpijx to understand why because of memory size limitations, 
                   6596:       we decided (b) to get a life expectancy respecting the most precise curvature of the
                   6597:       survival function given by stepm (the optimization length). Unfortunately it
                   6598:       means that if the survival funtion is printed every two years of age and if
                   6599:       you sum them up and add 1 year (area under the trapezoids) you won't get the same 
                   6600:       results. So we changed our mind and took the option of the best precision.
                   6601:    */
                   6602:    hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */ 
                   6603:    agelim = AGESUP;
                   6604:    for (age=bage; age<=fage; age ++){ /* If stepm=6 months */
                   6605:      nstepm=(int) rint((agelim-age)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */ 
                   6606:      nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
                   6607:      p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   6608:      gradg=ma3x(0,nhstepm,1,npar,1,nlstate);
                   6609:      gp=matrix(0,nhstepm,1,nlstate);
                   6610:      gm=matrix(0,nhstepm,1,nlstate);
                   6611:                
                   6612:                
                   6613:      for(theta=1; theta <=npar; theta++){
                   6614:        for(i=1; i<=npar; i++){ /* Computes gradient x + delta*/
                   6615:         xp[i] = x[i] + (i==theta ?delti[theta]:0);
                   6616:        }
1.279     brouard  6617:        /**< Computes the prevalence limit with parameter theta shifted of delta up to ftolpl precision and 
                   6618:        * returns into prlim .
1.288     brouard  6619:        */
1.242     brouard  6620:        prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp,ij, nres);
1.279     brouard  6621: 
                   6622:        /* If popbased = 1 we use crossection prevalences. Previous step is useless but prlim is created */
1.218     brouard  6623:        if (popbased==1) {
                   6624:         if(mobilav ==0){
                   6625:           for(i=1; i<=nlstate;i++)
                   6626:             prlim[i][i]=probs[(int)age][i][ij];
                   6627:         }else{ /* mobilav */ 
                   6628:           for(i=1; i<=nlstate;i++)
                   6629:             prlim[i][i]=mobaverage[(int)age][i][ij];
                   6630:         }
                   6631:        }
1.295     brouard  6632:        /**< Computes the shifted transition matrix \f$ {}{h}_p^{ij}x\f$ at horizon h.
1.279     brouard  6633:        */                      
                   6634:        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  6635:        /**< 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  6636:        * at horizon h in state j including mortality.
                   6637:        */
1.218     brouard  6638:        for(j=1; j<= nlstate; j++){
                   6639:         for(h=0; h<=nhstepm; h++){
                   6640:           for(i=1, gp[h][j]=0.;i<=nlstate;i++)
                   6641:             gp[h][j] += prlim[i][i]*p3mat[i][j][h];
                   6642:         }
                   6643:        }
1.279     brouard  6644:        /* Next for computing shifted+ probability of death (h=1 means
1.218     brouard  6645:          computed over hstepm matrices product = hstepm*stepm months) 
1.279     brouard  6646:          as a weighted average of prlim(i) * p(i,j) p.3=w1*p13 + w2*p23 .
1.218     brouard  6647:        */
                   6648:        for(j=nlstate+1;j<=nlstate+ndeath;j++){
                   6649:         for(i=1,gpp[j]=0.; i<= nlstate; i++)
                   6650:           gpp[j] += prlim[i][i]*p3mat[i][j][1];
1.279     brouard  6651:        }
                   6652:        
                   6653:        /* Again with minus shift */
1.218     brouard  6654:                        
                   6655:        for(i=1; i<=npar; i++) /* Computes gradient x - delta */
                   6656:         xp[i] = x[i] - (i==theta ?delti[theta]:0);
1.288     brouard  6657: 
1.242     brouard  6658:        prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp, ij, nres);
1.218     brouard  6659:                        
                   6660:        if (popbased==1) {
                   6661:         if(mobilav ==0){
                   6662:           for(i=1; i<=nlstate;i++)
                   6663:             prlim[i][i]=probs[(int)age][i][ij];
                   6664:         }else{ /* mobilav */ 
                   6665:           for(i=1; i<=nlstate;i++)
                   6666:             prlim[i][i]=mobaverage[(int)age][i][ij];
                   6667:         }
                   6668:        }
                   6669:                        
1.235     brouard  6670:        hpxij(p3mat,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, ij,nres);  
1.218     brouard  6671:                        
                   6672:        for(j=1; j<= nlstate; j++){  /* Sum of wi * eij = e.j */
                   6673:         for(h=0; h<=nhstepm; h++){
                   6674:           for(i=1, gm[h][j]=0.;i<=nlstate;i++)
                   6675:             gm[h][j] += prlim[i][i]*p3mat[i][j][h];
                   6676:         }
                   6677:        }
                   6678:        /* This for computing probability of death (h=1 means
                   6679:          computed over hstepm matrices product = hstepm*stepm months) 
                   6680:          as a weighted average of prlim.
                   6681:        */
                   6682:        for(j=nlstate+1;j<=nlstate+ndeath;j++){
                   6683:         for(i=1,gmp[j]=0.; i<= nlstate; i++)
                   6684:           gmp[j] += prlim[i][i]*p3mat[i][j][1];
                   6685:        }    
1.279     brouard  6686:        /* end shifting computations */
                   6687: 
                   6688:        /**< Computing gradient matrix at horizon h 
                   6689:        */
1.218     brouard  6690:        for(j=1; j<= nlstate; j++) /* vareij */
                   6691:         for(h=0; h<=nhstepm; h++){
                   6692:           gradg[h][theta][j]= (gp[h][j]-gm[h][j])/2./delti[theta];
                   6693:         }
1.279     brouard  6694:        /**< Gradient of overall mortality p.3 (or p.j) 
                   6695:        */
                   6696:        for(j=nlstate+1; j<= nlstate+ndeath; j++){ /* var mu mortality from j */
1.218     brouard  6697:         gradgp[theta][j]= (gpp[j]-gmp[j])/2./delti[theta];
                   6698:        }
                   6699:                        
                   6700:      } /* End theta */
1.279     brouard  6701:      
                   6702:      /* We got the gradient matrix for each theta and state j */               
1.218     brouard  6703:      trgradg =ma3x(0,nhstepm,1,nlstate,1,npar); /* veij */
                   6704:                
                   6705:      for(h=0; h<=nhstepm; h++) /* veij */
                   6706:        for(j=1; j<=nlstate;j++)
                   6707:         for(theta=1; theta <=npar; theta++)
                   6708:           trgradg[h][j][theta]=gradg[h][theta][j];
                   6709:                
                   6710:      for(j=nlstate+1; j<=nlstate+ndeath;j++) /* mu */
                   6711:        for(theta=1; theta <=npar; theta++)
                   6712:         trgradgp[j][theta]=gradgp[theta][j];
1.279     brouard  6713:      /**< as well as its transposed matrix 
                   6714:       */               
1.218     brouard  6715:                
                   6716:      hf=hstepm*stepm/YEARM;  /* Duration of hstepm expressed in year unit. */
                   6717:      for(i=1;i<=nlstate;i++)
                   6718:        for(j=1;j<=nlstate;j++)
                   6719:         vareij[i][j][(int)age] =0.;
1.279     brouard  6720: 
                   6721:      /* Computing trgradg by matcov by gradg at age and summing over h
                   6722:       * and k (nhstepm) formula 15 of article
                   6723:       * Lievre-Brouard-Heathcote
                   6724:       */
                   6725:      
1.218     brouard  6726:      for(h=0;h<=nhstepm;h++){
                   6727:        for(k=0;k<=nhstepm;k++){
                   6728:         matprod2(dnewm,trgradg[h],1,nlstate,1,npar,1,npar,matcov);
                   6729:         matprod2(doldm,dnewm,1,nlstate,1,npar,1,nlstate,gradg[k]);
                   6730:         for(i=1;i<=nlstate;i++)
                   6731:           for(j=1;j<=nlstate;j++)
                   6732:             vareij[i][j][(int)age] += doldm[i][j]*hf*hf;
                   6733:        }
                   6734:      }
                   6735:                
1.279     brouard  6736:      /* pptj is p.3 or p.j = trgradgp by cov by gradgp, variance of
                   6737:       * p.j overall mortality formula 49 but computed directly because
                   6738:       * we compute the grad (wix pijx) instead of grad (pijx),even if
                   6739:       * wix is independent of theta.
                   6740:       */
1.218     brouard  6741:      matprod2(dnewmp,trgradgp,nlstate+1,nlstate+ndeath,1,npar,1,npar,matcov);
                   6742:      matprod2(doldmp,dnewmp,nlstate+1,nlstate+ndeath,1,npar,nlstate+1,nlstate+ndeath,gradgp);
                   6743:      for(j=nlstate+1;j<=nlstate+ndeath;j++)
                   6744:        for(i=nlstate+1;i<=nlstate+ndeath;i++)
                   6745:         varppt[j][i]=doldmp[j][i];
                   6746:      /* end ppptj */
                   6747:      /*  x centered again */
                   6748:                
1.242     brouard  6749:      prevalim(prlim,nlstate,x,age,oldm,savm,ftolpl,ncvyearp,ij, nres);
1.218     brouard  6750:                
                   6751:      if (popbased==1) {
                   6752:        if(mobilav ==0){
                   6753:         for(i=1; i<=nlstate;i++)
                   6754:           prlim[i][i]=probs[(int)age][i][ij];
                   6755:        }else{ /* mobilav */ 
                   6756:         for(i=1; i<=nlstate;i++)
                   6757:           prlim[i][i]=mobaverage[(int)age][i][ij];
                   6758:        }
                   6759:      }
                   6760:                
                   6761:      /* This for computing probability of death (h=1 means
                   6762:        computed over hstepm (estepm) matrices product = hstepm*stepm months) 
                   6763:        as a weighted average of prlim.
                   6764:      */
1.235     brouard  6765:      hpxij(p3mat,nhstepm,age,hstepm,x,nlstate,stepm,oldm,savm, ij, nres);  
1.218     brouard  6766:      for(j=nlstate+1;j<=nlstate+ndeath;j++){
                   6767:        for(i=1,gmp[j]=0.;i<= nlstate; i++) 
                   6768:         gmp[j] += prlim[i][i]*p3mat[i][j][1]; 
                   6769:      }    
                   6770:      /* end probability of death */
                   6771:                
                   6772:      fprintf(ficresprobmorprev,"%3d %d ",(int) age, ij);
                   6773:      for(j=nlstate+1; j<=(nlstate+ndeath);j++){
                   6774:        fprintf(ficresprobmorprev," %11.3e %11.3e",gmp[j], sqrt(varppt[j][j]));
                   6775:        for(i=1; i<=nlstate;i++){
                   6776:         fprintf(ficresprobmorprev," %11.3e %11.3e ",prlim[i][i],p3mat[i][j][1]);
                   6777:        }
                   6778:      } 
                   6779:      fprintf(ficresprobmorprev,"\n");
                   6780:                
                   6781:      fprintf(ficresvij,"%.0f ",age );
                   6782:      for(i=1; i<=nlstate;i++)
                   6783:        for(j=1; j<=nlstate;j++){
                   6784:         fprintf(ficresvij," %.4f", vareij[i][j][(int)age]);
                   6785:        }
                   6786:      fprintf(ficresvij,"\n");
                   6787:      free_matrix(gp,0,nhstepm,1,nlstate);
                   6788:      free_matrix(gm,0,nhstepm,1,nlstate);
                   6789:      free_ma3x(gradg,0,nhstepm,1,npar,1,nlstate);
                   6790:      free_ma3x(trgradg,0,nhstepm,1,nlstate,1,npar);
                   6791:      free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   6792:    } /* End age */
                   6793:    free_vector(gpp,nlstate+1,nlstate+ndeath);
                   6794:    free_vector(gmp,nlstate+1,nlstate+ndeath);
                   6795:    free_matrix(gradgp,1,npar,nlstate+1,nlstate+ndeath);
                   6796:    free_matrix(trgradgp,nlstate+1,nlstate+ndeath,1,npar); /* mu or p point j*/
                   6797:    /* fprintf(ficgp,"\nunset parametric;unset label; set ter png small size 320, 240"); */
                   6798:    fprintf(ficgp,"\nunset parametric;unset label; set ter svg size 640, 480");
                   6799:    /* for(j=nlstate+1; j<= nlstate+ndeath; j++){ *//* Only the first actually */
                   6800:    fprintf(ficgp,"\n set log y; unset log x;set xlabel \"Age\"; set ylabel \"Force of mortality (year-1)\";");
                   6801:    fprintf(ficgp,"\nset out \"%s%s.svg\";",subdirf3(optionfilefiname,"VARMUPTJGR-",digitp),digit);
                   6802:    /*   fprintf(ficgp,"\n plot \"%s\"  u 1:($3*%6.3f) not w l 1 ",fileresprobmorprev,YEARM/estepm); */
                   6803:    /*   fprintf(ficgp,"\n replot \"%s\"  u 1:(($3+1.96*$4)*%6.3f) t \"95\%% interval\" w l 2 ",fileresprobmorprev,YEARM/estepm); */
                   6804:    /*   fprintf(ficgp,"\n replot \"%s\"  u 1:(($3-1.96*$4)*%6.3f) not w l 2 ",fileresprobmorprev,YEARM/estepm); */
                   6805:    fprintf(ficgp,"\n plot \"%s\"  u 1:($3) not w l lt 1 ",subdirf(fileresprobmorprev));
                   6806:    fprintf(ficgp,"\n replot \"%s\"  u 1:(($3+1.96*$4)) t \"95%% interval\" w l lt 2 ",subdirf(fileresprobmorprev));
                   6807:    fprintf(ficgp,"\n replot \"%s\"  u 1:(($3-1.96*$4)) not w l lt 2 ",subdirf(fileresprobmorprev));
                   6808:    fprintf(fichtm,"\n<br> File (multiple files are possible if covariates are present): <A href=\"%s\">%s</a>\n",subdirf(fileresprobmorprev),subdirf(fileresprobmorprev));
                   6809:    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);
                   6810:    /*  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  6811:     */
1.218     brouard  6812:    /*   fprintf(ficgp,"\nset out \"varmuptjgr%s%s%s.svg\";replot;",digitp,optionfilefiname,digit); */
                   6813:    fprintf(ficgp,"\nset out;\nset out \"%s%s.svg\";replot;set out;\n",subdirf3(optionfilefiname,"VARMUPTJGR-",digitp),digit);
1.126     brouard  6814: 
1.218     brouard  6815:    free_vector(xp,1,npar);
                   6816:    free_matrix(doldm,1,nlstate,1,nlstate);
                   6817:    free_matrix(dnewm,1,nlstate,1,npar);
                   6818:    free_matrix(doldmp,nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
                   6819:    free_matrix(dnewmp,nlstate+1,nlstate+ndeath,1,npar);
                   6820:    free_matrix(varppt,nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
                   6821:    /* if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX); */
                   6822:    fclose(ficresprobmorprev);
                   6823:    fflush(ficgp);
                   6824:    fflush(fichtm); 
                   6825:  }  /* end varevsij */
1.126     brouard  6826: 
                   6827: /************ Variance of prevlim ******************/
1.269     brouard  6828:  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  6829: {
1.205     brouard  6830:   /* Variance of prevalence limit  for each state ij using current parameters x[] and estimates of neighbourhood give by delti*/
1.126     brouard  6831:   /*  double **prevalim(double **prlim, int nlstate, double *xp, double age, double **oldm, double **savm,double ftolpl);*/
1.164     brouard  6832: 
1.268     brouard  6833:   double **dnewmpar,**doldm;
1.126     brouard  6834:   int i, j, nhstepm, hstepm;
                   6835:   double *xp;
                   6836:   double *gp, *gm;
                   6837:   double **gradg, **trgradg;
1.208     brouard  6838:   double **mgm, **mgp;
1.126     brouard  6839:   double age,agelim;
                   6840:   int theta;
                   6841:   
                   6842:   pstamp(ficresvpl);
1.288     brouard  6843:   fprintf(ficresvpl,"# Standard deviation of period (forward stable) prevalences \n");
1.241     brouard  6844:   fprintf(ficresvpl,"# Age ");
                   6845:   if(nresult >=1)
                   6846:     fprintf(ficresvpl," Result# ");
1.126     brouard  6847:   for(i=1; i<=nlstate;i++)
                   6848:       fprintf(ficresvpl," %1d-%1d",i,i);
                   6849:   fprintf(ficresvpl,"\n");
                   6850: 
                   6851:   xp=vector(1,npar);
1.268     brouard  6852:   dnewmpar=matrix(1,nlstate,1,npar);
1.126     brouard  6853:   doldm=matrix(1,nlstate,1,nlstate);
                   6854:   
                   6855:   hstepm=1*YEARM; /* Every year of age */
                   6856:   hstepm=hstepm/stepm; /* Typically in stepm units, if j= 2 years, = 2/6 months = 4 */ 
                   6857:   agelim = AGESUP;
                   6858:   for (age=bage; age<=fage; age ++){ /* If stepm=6 months */
                   6859:     nhstepm=(int) rint((agelim-age)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */ 
                   6860:     if (stepm >= YEARM) hstepm=1;
                   6861:     nhstepm = nhstepm/hstepm; /* Typically 40/4=10 */
                   6862:     gradg=matrix(1,npar,1,nlstate);
1.208     brouard  6863:     mgp=matrix(1,npar,1,nlstate);
                   6864:     mgm=matrix(1,npar,1,nlstate);
1.126     brouard  6865:     gp=vector(1,nlstate);
                   6866:     gm=vector(1,nlstate);
                   6867: 
                   6868:     for(theta=1; theta <=npar; theta++){
                   6869:       for(i=1; i<=npar; i++){ /* Computes gradient */
                   6870:        xp[i] = x[i] + (i==theta ?delti[theta]:0);
                   6871:       }
1.288     brouard  6872:       /* if((int)age==79 ||(int)age== 80 ||(int)age== 81 ) */
                   6873:       /*       prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp,ij,nres); */
                   6874:       /* else */
                   6875:       prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp,ij,nres);
1.208     brouard  6876:       for(i=1;i<=nlstate;i++){
1.126     brouard  6877:        gp[i] = prlim[i][i];
1.208     brouard  6878:        mgp[theta][i] = prlim[i][i];
                   6879:       }
1.126     brouard  6880:       for(i=1; i<=npar; i++) /* Computes gradient */
                   6881:        xp[i] = x[i] - (i==theta ?delti[theta]:0);
1.288     brouard  6882:       /* if((int)age==79 ||(int)age== 80 ||(int)age== 81 ) */
                   6883:       /*       prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp,ij,nres); */
                   6884:       /* else */
                   6885:       prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp,ij,nres);
1.208     brouard  6886:       for(i=1;i<=nlstate;i++){
1.126     brouard  6887:        gm[i] = prlim[i][i];
1.208     brouard  6888:        mgm[theta][i] = prlim[i][i];
                   6889:       }
1.126     brouard  6890:       for(i=1;i<=nlstate;i++)
                   6891:        gradg[theta][i]= (gp[i]-gm[i])/2./delti[theta];
1.209     brouard  6892:       /* gradg[theta][2]= -gradg[theta][1]; */ /* For testing if nlstate=2 */
1.126     brouard  6893:     } /* End theta */
                   6894: 
                   6895:     trgradg =matrix(1,nlstate,1,npar);
                   6896: 
                   6897:     for(j=1; j<=nlstate;j++)
                   6898:       for(theta=1; theta <=npar; theta++)
                   6899:        trgradg[j][theta]=gradg[theta][j];
1.209     brouard  6900:     /* if((int)age==79 ||(int)age== 80 ||(int)age== 81 ){ */
                   6901:     /*   printf("\nmgm mgp %d ",(int)age); */
                   6902:     /*   for(j=1; j<=nlstate;j++){ */
                   6903:     /*         printf(" %d ",j); */
                   6904:     /*         for(theta=1; theta <=npar; theta++) */
                   6905:     /*           printf(" %d %lf %lf",theta,mgm[theta][j],mgp[theta][j]); */
                   6906:     /*         printf("\n "); */
                   6907:     /*   } */
                   6908:     /* } */
                   6909:     /* if((int)age==79 ||(int)age== 80 ||(int)age== 81 ){ */
                   6910:     /*   printf("\n gradg %d ",(int)age); */
                   6911:     /*   for(j=1; j<=nlstate;j++){ */
                   6912:     /*         printf("%d ",j); */
                   6913:     /*         for(theta=1; theta <=npar; theta++) */
                   6914:     /*           printf("%d %lf ",theta,gradg[theta][j]); */
                   6915:     /*         printf("\n "); */
                   6916:     /*   } */
                   6917:     /* } */
1.126     brouard  6918: 
                   6919:     for(i=1;i<=nlstate;i++)
                   6920:       varpl[i][(int)age] =0.;
1.209     brouard  6921:     if((int)age==79 ||(int)age== 80  ||(int)age== 81){
1.268     brouard  6922:     matprod2(dnewmpar,trgradg,1,nlstate,1,npar,1,npar,matcov);
                   6923:     matprod2(doldm,dnewmpar,1,nlstate,1,npar,1,nlstate,gradg);
1.205     brouard  6924:     }else{
1.268     brouard  6925:     matprod2(dnewmpar,trgradg,1,nlstate,1,npar,1,npar,matcov);
                   6926:     matprod2(doldm,dnewmpar,1,nlstate,1,npar,1,nlstate,gradg);
1.205     brouard  6927:     }
1.126     brouard  6928:     for(i=1;i<=nlstate;i++)
                   6929:       varpl[i][(int)age] = doldm[i][i]; /* Covariances are useless */
                   6930: 
                   6931:     fprintf(ficresvpl,"%.0f ",age );
1.241     brouard  6932:     if(nresult >=1)
                   6933:       fprintf(ficresvpl,"%d ",nres );
1.288     brouard  6934:     for(i=1; i<=nlstate;i++){
1.126     brouard  6935:       fprintf(ficresvpl," %.5f (%.5f)",prlim[i][i],sqrt(varpl[i][(int)age]));
1.288     brouard  6936:       /* for(j=1;j<=nlstate;j++) */
                   6937:       /*       fprintf(ficresvpl," %d %.5f ",j,prlim[j][i]); */
                   6938:     }
1.126     brouard  6939:     fprintf(ficresvpl,"\n");
                   6940:     free_vector(gp,1,nlstate);
                   6941:     free_vector(gm,1,nlstate);
1.208     brouard  6942:     free_matrix(mgm,1,npar,1,nlstate);
                   6943:     free_matrix(mgp,1,npar,1,nlstate);
1.126     brouard  6944:     free_matrix(gradg,1,npar,1,nlstate);
                   6945:     free_matrix(trgradg,1,nlstate,1,npar);
                   6946:   } /* End age */
                   6947: 
                   6948:   free_vector(xp,1,npar);
                   6949:   free_matrix(doldm,1,nlstate,1,npar);
1.268     brouard  6950:   free_matrix(dnewmpar,1,nlstate,1,nlstate);
                   6951: 
                   6952: }
                   6953: 
                   6954: 
                   6955: /************ Variance of backprevalence limit ******************/
1.269     brouard  6956:  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  6957: {
                   6958:   /* Variance of backward prevalence limit  for each state ij using current parameters x[] and estimates of neighbourhood give by delti*/
                   6959:   /*  double **prevalim(double **prlim, int nlstate, double *xp, double age, double **oldm, double **savm,double ftolpl);*/
                   6960: 
                   6961:   double **dnewmpar,**doldm;
                   6962:   int i, j, nhstepm, hstepm;
                   6963:   double *xp;
                   6964:   double *gp, *gm;
                   6965:   double **gradg, **trgradg;
                   6966:   double **mgm, **mgp;
                   6967:   double age,agelim;
                   6968:   int theta;
                   6969:   
                   6970:   pstamp(ficresvbl);
                   6971:   fprintf(ficresvbl,"# Standard deviation of back (stable) prevalences \n");
                   6972:   fprintf(ficresvbl,"# Age ");
                   6973:   if(nresult >=1)
                   6974:     fprintf(ficresvbl," Result# ");
                   6975:   for(i=1; i<=nlstate;i++)
                   6976:       fprintf(ficresvbl," %1d-%1d",i,i);
                   6977:   fprintf(ficresvbl,"\n");
                   6978: 
                   6979:   xp=vector(1,npar);
                   6980:   dnewmpar=matrix(1,nlstate,1,npar);
                   6981:   doldm=matrix(1,nlstate,1,nlstate);
                   6982:   
                   6983:   hstepm=1*YEARM; /* Every year of age */
                   6984:   hstepm=hstepm/stepm; /* Typically in stepm units, if j= 2 years, = 2/6 months = 4 */ 
                   6985:   agelim = AGEINF;
                   6986:   for (age=fage; age>=bage; age --){ /* If stepm=6 months */
                   6987:     nhstepm=(int) rint((age-agelim)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */ 
                   6988:     if (stepm >= YEARM) hstepm=1;
                   6989:     nhstepm = nhstepm/hstepm; /* Typically 40/4=10 */
                   6990:     gradg=matrix(1,npar,1,nlstate);
                   6991:     mgp=matrix(1,npar,1,nlstate);
                   6992:     mgm=matrix(1,npar,1,nlstate);
                   6993:     gp=vector(1,nlstate);
                   6994:     gm=vector(1,nlstate);
                   6995: 
                   6996:     for(theta=1; theta <=npar; theta++){
                   6997:       for(i=1; i<=npar; i++){ /* Computes gradient */
                   6998:        xp[i] = x[i] + (i==theta ?delti[theta]:0);
                   6999:       }
                   7000:       if(mobilavproj > 0 )
                   7001:        bprevalim(bprlim, mobaverage,nlstate,xp,age,ftolpl,ncvyearp,ij,nres);
                   7002:       else
                   7003:        bprevalim(bprlim, mobaverage,nlstate,xp,age,ftolpl,ncvyearp,ij,nres);
                   7004:       for(i=1;i<=nlstate;i++){
                   7005:        gp[i] = bprlim[i][i];
                   7006:        mgp[theta][i] = bprlim[i][i];
                   7007:       }
                   7008:      for(i=1; i<=npar; i++) /* Computes gradient */
                   7009:        xp[i] = x[i] - (i==theta ?delti[theta]:0);
                   7010:        if(mobilavproj > 0 )
                   7011:        bprevalim(bprlim, mobaverage,nlstate,xp,age,ftolpl,ncvyearp,ij,nres);
                   7012:        else
                   7013:        bprevalim(bprlim, mobaverage,nlstate,xp,age,ftolpl,ncvyearp,ij,nres);
                   7014:       for(i=1;i<=nlstate;i++){
                   7015:        gm[i] = bprlim[i][i];
                   7016:        mgm[theta][i] = bprlim[i][i];
                   7017:       }
                   7018:       for(i=1;i<=nlstate;i++)
                   7019:        gradg[theta][i]= (gp[i]-gm[i])/2./delti[theta];
                   7020:       /* gradg[theta][2]= -gradg[theta][1]; */ /* For testing if nlstate=2 */
                   7021:     } /* End theta */
                   7022: 
                   7023:     trgradg =matrix(1,nlstate,1,npar);
                   7024: 
                   7025:     for(j=1; j<=nlstate;j++)
                   7026:       for(theta=1; theta <=npar; theta++)
                   7027:        trgradg[j][theta]=gradg[theta][j];
                   7028:     /* if((int)age==79 ||(int)age== 80 ||(int)age== 81 ){ */
                   7029:     /*   printf("\nmgm mgp %d ",(int)age); */
                   7030:     /*   for(j=1; j<=nlstate;j++){ */
                   7031:     /*         printf(" %d ",j); */
                   7032:     /*         for(theta=1; theta <=npar; theta++) */
                   7033:     /*           printf(" %d %lf %lf",theta,mgm[theta][j],mgp[theta][j]); */
                   7034:     /*         printf("\n "); */
                   7035:     /*   } */
                   7036:     /* } */
                   7037:     /* if((int)age==79 ||(int)age== 80 ||(int)age== 81 ){ */
                   7038:     /*   printf("\n gradg %d ",(int)age); */
                   7039:     /*   for(j=1; j<=nlstate;j++){ */
                   7040:     /*         printf("%d ",j); */
                   7041:     /*         for(theta=1; theta <=npar; theta++) */
                   7042:     /*           printf("%d %lf ",theta,gradg[theta][j]); */
                   7043:     /*         printf("\n "); */
                   7044:     /*   } */
                   7045:     /* } */
                   7046: 
                   7047:     for(i=1;i<=nlstate;i++)
                   7048:       varbpl[i][(int)age] =0.;
                   7049:     if((int)age==79 ||(int)age== 80  ||(int)age== 81){
                   7050:     matprod2(dnewmpar,trgradg,1,nlstate,1,npar,1,npar,matcov);
                   7051:     matprod2(doldm,dnewmpar,1,nlstate,1,npar,1,nlstate,gradg);
                   7052:     }else{
                   7053:     matprod2(dnewmpar,trgradg,1,nlstate,1,npar,1,npar,matcov);
                   7054:     matprod2(doldm,dnewmpar,1,nlstate,1,npar,1,nlstate,gradg);
                   7055:     }
                   7056:     for(i=1;i<=nlstate;i++)
                   7057:       varbpl[i][(int)age] = doldm[i][i]; /* Covariances are useless */
                   7058: 
                   7059:     fprintf(ficresvbl,"%.0f ",age );
                   7060:     if(nresult >=1)
                   7061:       fprintf(ficresvbl,"%d ",nres );
                   7062:     for(i=1; i<=nlstate;i++)
                   7063:       fprintf(ficresvbl," %.5f (%.5f)",bprlim[i][i],sqrt(varbpl[i][(int)age]));
                   7064:     fprintf(ficresvbl,"\n");
                   7065:     free_vector(gp,1,nlstate);
                   7066:     free_vector(gm,1,nlstate);
                   7067:     free_matrix(mgm,1,npar,1,nlstate);
                   7068:     free_matrix(mgp,1,npar,1,nlstate);
                   7069:     free_matrix(gradg,1,npar,1,nlstate);
                   7070:     free_matrix(trgradg,1,nlstate,1,npar);
                   7071:   } /* End age */
                   7072: 
                   7073:   free_vector(xp,1,npar);
                   7074:   free_matrix(doldm,1,nlstate,1,npar);
                   7075:   free_matrix(dnewmpar,1,nlstate,1,nlstate);
1.126     brouard  7076: 
                   7077: }
                   7078: 
                   7079: /************ Variance of one-step probabilities  ******************/
                   7080: 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  7081:  {
                   7082:    int i, j=0,  k1, l1, tj;
                   7083:    int k2, l2, j1,  z1;
                   7084:    int k=0, l;
                   7085:    int first=1, first1, first2;
1.326     brouard  7086:    int nres=0; /* New */
1.222     brouard  7087:    double cv12, mu1, mu2, lc1, lc2, v12, v21, v11, v22,v1,v2, c12, tnalp;
                   7088:    double **dnewm,**doldm;
                   7089:    double *xp;
                   7090:    double *gp, *gm;
                   7091:    double **gradg, **trgradg;
                   7092:    double **mu;
                   7093:    double age, cov[NCOVMAX+1];
                   7094:    double std=2.0; /* Number of standard deviation wide of confidence ellipsoids */
                   7095:    int theta;
                   7096:    char fileresprob[FILENAMELENGTH];
                   7097:    char fileresprobcov[FILENAMELENGTH];
                   7098:    char fileresprobcor[FILENAMELENGTH];
                   7099:    double ***varpij;
                   7100: 
                   7101:    strcpy(fileresprob,"PROB_"); 
                   7102:    strcat(fileresprob,fileres);
                   7103:    if((ficresprob=fopen(fileresprob,"w"))==NULL) {
                   7104:      printf("Problem with resultfile: %s\n", fileresprob);
                   7105:      fprintf(ficlog,"Problem with resultfile: %s\n", fileresprob);
                   7106:    }
                   7107:    strcpy(fileresprobcov,"PROBCOV_"); 
                   7108:    strcat(fileresprobcov,fileresu);
                   7109:    if((ficresprobcov=fopen(fileresprobcov,"w"))==NULL) {
                   7110:      printf("Problem with resultfile: %s\n", fileresprobcov);
                   7111:      fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobcov);
                   7112:    }
                   7113:    strcpy(fileresprobcor,"PROBCOR_"); 
                   7114:    strcat(fileresprobcor,fileresu);
                   7115:    if((ficresprobcor=fopen(fileresprobcor,"w"))==NULL) {
                   7116:      printf("Problem with resultfile: %s\n", fileresprobcor);
                   7117:      fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobcor);
                   7118:    }
                   7119:    printf("Computing standard deviation of one-step probabilities: result on file '%s' \n",fileresprob);
                   7120:    fprintf(ficlog,"Computing standard deviation of one-step probabilities: result on file '%s' \n",fileresprob);
                   7121:    printf("Computing matrix of variance covariance of one-step probabilities: result on file '%s' \n",fileresprobcov);
                   7122:    fprintf(ficlog,"Computing matrix of variance covariance of one-step probabilities: result on file '%s' \n",fileresprobcov);
                   7123:    printf("and correlation matrix of one-step probabilities: result on file '%s' \n",fileresprobcor);
                   7124:    fprintf(ficlog,"and correlation matrix of one-step probabilities: result on file '%s' \n",fileresprobcor);
                   7125:    pstamp(ficresprob);
                   7126:    fprintf(ficresprob,"#One-step probabilities and stand. devi in ()\n");
                   7127:    fprintf(ficresprob,"# Age");
                   7128:    pstamp(ficresprobcov);
                   7129:    fprintf(ficresprobcov,"#One-step probabilities and covariance matrix\n");
                   7130:    fprintf(ficresprobcov,"# Age");
                   7131:    pstamp(ficresprobcor);
                   7132:    fprintf(ficresprobcor,"#One-step probabilities and correlation matrix\n");
                   7133:    fprintf(ficresprobcor,"# Age");
1.126     brouard  7134: 
                   7135: 
1.222     brouard  7136:    for(i=1; i<=nlstate;i++)
                   7137:      for(j=1; j<=(nlstate+ndeath);j++){
                   7138:        fprintf(ficresprob," p%1d-%1d (SE)",i,j);
                   7139:        fprintf(ficresprobcov," p%1d-%1d ",i,j);
                   7140:        fprintf(ficresprobcor," p%1d-%1d ",i,j);
                   7141:      }  
                   7142:    /* fprintf(ficresprob,"\n");
                   7143:       fprintf(ficresprobcov,"\n");
                   7144:       fprintf(ficresprobcor,"\n");
                   7145:    */
                   7146:    xp=vector(1,npar);
                   7147:    dnewm=matrix(1,(nlstate)*(nlstate+ndeath),1,npar);
                   7148:    doldm=matrix(1,(nlstate)*(nlstate+ndeath),1,(nlstate)*(nlstate+ndeath));
                   7149:    mu=matrix(1,(nlstate)*(nlstate+ndeath), (int) bage, (int)fage);
                   7150:    varpij=ma3x(1,nlstate*(nlstate+ndeath),1,nlstate*(nlstate+ndeath),(int) bage, (int) fage);
                   7151:    first=1;
                   7152:    fprintf(ficgp,"\n# Routine varprob");
                   7153:    fprintf(fichtm,"\n<li><h4> Computing and drawing one step probabilities with their confidence intervals</h4></li>\n");
                   7154:    fprintf(fichtm,"\n");
                   7155: 
1.288     brouard  7156:    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  7157:    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);
                   7158:    fprintf(fichtmcov,"\nEllipsoids of confidence centered on point (p<inf>ij</inf>, p<inf>kl</inf>) are estimated \
1.126     brouard  7159: and drawn. It helps understanding how is the covariance between two incidences.\
                   7160:  They are expressed in year<sup>-1</sup> in order to be less dependent of stepm.<br>\n");
1.222     brouard  7161:    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  7162: It can be understood this way: if pij and pkl where uncorrelated the (2x2) matrix of covariance \
                   7163: would have been (1/(var pij), 0 , 0, 1/(var pkl)), and the confidence interval would be 2 \
                   7164: standard deviations wide on each axis. <br>\
                   7165:  Now, if both incidences are correlated (usual case) we diagonalised the inverse of the covariance matrix\
                   7166:  and made the appropriate rotation to look at the uncorrelated principal directions.<br>\
                   7167: To be simple, these graphs help to understand the significativity of each parameter in relation to a second other one.<br> \n");
                   7168: 
1.222     brouard  7169:    cov[1]=1;
                   7170:    /* tj=cptcoveff; */
1.225     brouard  7171:    tj = (int) pow(2,cptcoveff);
1.222     brouard  7172:    if (cptcovn<1) {tj=1;ncodemax[1]=1;}
                   7173:    j1=0;
1.332     brouard  7174: 
                   7175:    for(nres=1;nres <=nresult; nres++){ /* For each resultline */
                   7176:    for(j1=1; j1<=tj;j1++){ /* For any combination of dummy covariates, fixed and varying */
1.334     brouard  7177:      printf("Varprob  TKresult[nres]=%d j1=%d, nres=%d, cptcovn=%d, cptcoveff=%d tj=%d cptcovs=%d\n",  TKresult[nres], j1, nres, cptcovn, cptcoveff, tj, cptcovs);
1.332     brouard  7178:      if(tj != 1 && TKresult[nres]!= j1)
                   7179:        continue;
                   7180: 
                   7181:    /* for(j1=1; j1<=tj;j1++){  /\* For each valid combination of covariates or only once*\/ */
                   7182:      /* for(nres=1;nres <=1; nres++){ /\* For each resultline *\/ */
                   7183:      /* /\* for(nres=1;nres <=nresult; nres++){ /\\* For each resultline *\\/ *\/ */
1.222     brouard  7184:      if  (cptcovn>0) {
1.334     brouard  7185:        fprintf(ficresprob, "\n#********** Variable ");
                   7186:        fprintf(ficresprobcov, "\n#********** Variable "); 
                   7187:        fprintf(ficgp, "\n#********** Variable ");
                   7188:        fprintf(fichtmcov, "\n<hr  size=\"2\" color=\"#EC5E5E\">********** Variable "); 
                   7189:        fprintf(ficresprobcor, "\n#********** Variable ");    
                   7190: 
                   7191:        /* Including quantitative variables of the resultline to be done */
                   7192:        for (z1=1; z1<=cptcovs; z1++){ /* Loop on each variable of this resultline  */
                   7193:         printf("Varprob modelresult[%d][%d]=%d model=%s \n",nres, z1, modelresult[nres][z1], model);
                   7194:         fprintf(ficlog,"Varprob modelresult[%d][%d]=%d model=%s \n",nres, z1, modelresult[nres][z1], model);
                   7195:         /* fprintf(ficlog,"Varprob modelresult[%d][%d]=%d model=%s resultline[%d]=%s \n",nres, z1, modelresult[nres][z1], model, nres, resultline[nres]); */
                   7196:         if(Dummy[modelresult[nres][z1]]==0){/* Dummy variable of the variable in position modelresult in the model corresponding to z1 in resultline  */
                   7197:           if(Fixed[modelresult[nres][z1]]==0){ /* Fixed referenced to model equation */
                   7198:             fprintf(ficresprob,"V%d=%d ",Tvresult[nres][z1],Tresult[nres][z1]); /* Output of each value for the combination TKresult[nres], ordere by the covariate values in the resultline  */
                   7199:             fprintf(ficresprobcov,"V%d=%d ",Tvresult[nres][z1],Tresult[nres][z1]); /* Output of each value for the combination TKresult[nres], ordere by the covariate values in the resultline  */
                   7200:             fprintf(ficgp,"V%d=%d ",Tvresult[nres][z1],Tresult[nres][z1]); /* Output of each value for the combination TKresult[nres], ordere by the covariate values in the resultline  */
                   7201:             fprintf(fichtmcov,"V%d=%d ",Tvresult[nres][z1],Tresult[nres][z1]); /* Output of each value for the combination TKresult[nres], ordere by the covariate values in the resultline  */
                   7202:             fprintf(ficresprobcor,"V%d=%d ",Tvresult[nres][z1],Tresult[nres][z1]); /* Output of each value for the combination TKresult[nres], ordere by the covariate values in the resultline  */
                   7203:             fprintf(ficresprob,"fixed ");
                   7204:             fprintf(ficresprobcov,"fixed ");
                   7205:             fprintf(ficgp,"fixed ");
                   7206:             fprintf(fichtmcov,"fixed ");
                   7207:             fprintf(ficresprobcor,"fixed ");
                   7208:           }else{
                   7209:             fprintf(ficresprob,"varyi ");
                   7210:             fprintf(ficresprobcov,"varyi ");
                   7211:             fprintf(ficgp,"varyi ");
                   7212:             fprintf(fichtmcov,"varyi ");
                   7213:             fprintf(ficresprobcor,"varyi ");
                   7214:           }
                   7215:         }else if(Dummy[modelresult[nres][z1]]==1){ /* Quanti variable */
                   7216:           /* For each selected (single) quantitative value */
                   7217:           fprintf(ficresprob," V%d=%f ",Tvqresult[nres][z1],Tqresult[nres][z1]);
                   7218:           if(Fixed[modelresult[nres][z1]]==0){ /* Fixed */
                   7219:             fprintf(ficresprob,"fixed ");
                   7220:             fprintf(ficresprobcov,"fixed ");
                   7221:             fprintf(ficgp,"fixed ");
                   7222:             fprintf(fichtmcov,"fixed ");
                   7223:             fprintf(ficresprobcor,"fixed ");
                   7224:           }else{
                   7225:             fprintf(ficresprob,"varyi ");
                   7226:             fprintf(ficresprobcov,"varyi ");
                   7227:             fprintf(ficgp,"varyi ");
                   7228:             fprintf(fichtmcov,"varyi ");
                   7229:             fprintf(ficresprobcor,"varyi ");
                   7230:           }
                   7231:         }else{
                   7232:           printf("Error in varprob() Dummy[modelresult[%d][%d]]=%d, modelresult[%d][%d]=V%d cptcovs=%d, cptcoveff=%d \n", nres, z1, Dummy[modelresult[nres][z1]],nres,z1,modelresult[nres][z1],cptcovs, cptcoveff);  /* end if dummy  or quanti */
                   7233:           fprintf(ficlog,"Error in varprob() Dummy[modelresult[%d][%d]]=%d, modelresult[%d][%d]=V%d cptcovs=%d, cptcoveff=%d \n", nres, z1, Dummy[modelresult[nres][z1]],nres,z1,modelresult[nres][z1],cptcovs, cptcoveff);  /* end if dummy  or quanti */
                   7234:           exit(1);
                   7235:         }
                   7236:        } /* End loop on variable of this resultline */
                   7237:        /* for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresprob, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]); */
1.222     brouard  7238:        fprintf(ficresprob, "**********\n#\n");
                   7239:        fprintf(ficresprobcov, "**********\n#\n");
                   7240:        fprintf(ficgp, "**********\n#\n");
                   7241:        fprintf(fichtmcov, "**********\n<hr size=\"2\" color=\"#EC5E5E\">");
                   7242:        fprintf(ficresprobcor, "**********\n#");    
                   7243:        if(invalidvarcomb[j1]){
                   7244:         fprintf(ficgp,"\n#Combination (%d) ignored because no cases \n",j1); 
                   7245:         fprintf(fichtmcov,"\n<h3>Combination (%d) ignored because no cases </h3>\n",j1); 
                   7246:         continue;
                   7247:        }
                   7248:      }
                   7249:      gradg=matrix(1,npar,1,(nlstate)*(nlstate+ndeath));
                   7250:      trgradg=matrix(1,(nlstate)*(nlstate+ndeath),1,npar);
                   7251:      gp=vector(1,(nlstate)*(nlstate+ndeath));
                   7252:      gm=vector(1,(nlstate)*(nlstate+ndeath));
1.334     brouard  7253:      for (age=bage; age<=fage; age ++){ /* Fo each age we feed the model equation with covariates, using precov as in hpxij() ? */
1.222     brouard  7254:        cov[2]=age;
                   7255:        if(nagesqr==1)
                   7256:         cov[3]= age*age;
1.334     brouard  7257:        /* New code end of combination but for each resultline */
                   7258:        for(k1=1;k1<=cptcovt;k1++){ /* loop on model equation (including products) */ 
                   7259:         if(Typevar[k1]==1){ /* A product with age */
                   7260:           cov[2+nagesqr+k1]=precov[nres][k1]*cov[2];
1.326     brouard  7261:         }else{
1.334     brouard  7262:           cov[2+nagesqr+k1]=precov[nres][k1];
1.326     brouard  7263:         }
1.334     brouard  7264:        }/* End of loop on model equation */
                   7265: /* Old code */
                   7266:        /* /\* for (k=1; k<=cptcovn;k++) { *\/ */
                   7267:        /* /\*   cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(j1,k)]; *\/ */
                   7268:        /* for (k=1; k<=nsd;k++) { /\* For single dummy covariates only *\/ */
                   7269:        /*       /\* Here comes the value of the covariate 'j1' after renumbering k with single dummy covariates *\/ */
                   7270:        /*       cov[2+nagesqr+TvarsDind[k]]=nbcode[TvarsD[k]][codtabm(j1,TnsdVar[TvarsD[k]])]; */
                   7271:        /*       /\*cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(j1,Tvar[k])];*\//\* j1 1 2 3 4 */
                   7272:        /*                                                                  * 1  1 1 1 1 */
                   7273:        /*                                                                  * 2  2 1 1 1 */
                   7274:        /*                                                                  * 3  1 2 1 1 */
                   7275:        /*                                                                  *\/ */
                   7276:        /*       /\* nbcode[1][1]=0 nbcode[1][2]=1;*\/ */
                   7277:        /* } */
                   7278:        /* /\* V2+V1+V4+V3*age Tvar[4]=3 ; V1+V2*age Tvar[2]=2; V1+V1*age Tvar[2]=1, Tage[1]=2 *\/ */
                   7279:        /* /\* ) p nbcode[Tvar[Tage[k]]][(1 & (ij-1) >> (k-1))+1] *\/ */
                   7280:        /* /\*for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2]; *\/ */
                   7281:        /* for (k=1; k<=cptcovage;k++){  /\* For product with age *\/ */
                   7282:        /*       if(Dummy[Tage[k]]==2){ /\* dummy with age *\/ */
                   7283:        /*         cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(j1,TnsdVar[Tvar[Tage[k]]])]*cov[2]; */
                   7284:        /*         /\* cov[++k1]=nbcode[Tvar[Tage[k]]][codtabm(ij,k)]*cov[2]; *\/ */
                   7285:        /*       } else if(Dummy[Tage[k]]==3){ /\* quantitative with age *\/ */
                   7286:        /*         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]); */
                   7287:        /*         /\* cov[2+nagesqr+Tage[k]]=meanq[k]/idq[k]*cov[2];/\\* Using the mean of quantitative variable Tvar[Tage[k]] /\\* Tqresult[nres][k]; *\\/ *\/ */
                   7288:        /*         /\* exit(1); *\/ */
                   7289:        /*         /\* cov[++k1]=Tqresult[nres][k];  *\/ */
                   7290:        /*       } */
                   7291:        /*       /\* cov[2+Tage[k]+nagesqr]=nbcode[Tvar[Tage[k]]][codtabm(ij,k)]*cov[2]; *\/ */
                   7292:        /* } */
                   7293:        /* for (k=1; k<=cptcovprod;k++){/\* For product without age *\/ */
                   7294:        /*       if(Dummy[Tvard[k][1]]==0){ */
                   7295:        /*         if(Dummy[Tvard[k][2]]==0){ */
                   7296:        /*           cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(j1,TnsdVar[Tvard[k][1]])] * nbcode[Tvard[k][2]][codtabm(j1,TnsdVar[Tvard[k][2]])]; */
                   7297:        /*           /\* cov[++k1]=nbcode[Tvard[k][1]][codtabm(ij,k)] * nbcode[Tvard[k][2]][codtabm(ij,k)]; *\/ */
                   7298:        /*         }else{ /\* Should we use the mean of the quantitative variables? *\/ */
                   7299:        /*           cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(j1,TnsdVar[Tvard[k][1]])] * Tqresult[nres][resultmodel[nres][k]]; */
                   7300:        /*           /\* cov[++k1]=nbcode[Tvard[k][1]][codtabm(ij,k)] * Tqresult[nres][k]; *\/ */
                   7301:        /*         } */
                   7302:        /*       }else{ */
                   7303:        /*         if(Dummy[Tvard[k][2]]==0){ */
                   7304:        /*           cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][2]][codtabm(j1,TnsdVar[Tvard[k][2]])] * Tqinvresult[nres][TnsdVar[Tvard[k][1]]]; */
                   7305:        /*           /\* cov[++k1]=nbcode[Tvard[k][2]][codtabm(ij,k)] * Tqinvresult[nres][Tvard[k][1]]; *\/ */
                   7306:        /*         }else{ */
                   7307:        /*           cov[2+nagesqr+Tprod[k]]=Tqinvresult[nres][TnsdVar[Tvard[k][1]]]*  Tqinvresult[nres][TnsdVar[Tvard[k][2]]]; */
                   7308:        /*           /\* cov[++k1]=Tqinvresult[nres][Tvard[k][1]]*  Tqinvresult[nres][Tvard[k][2]]; *\/ */
                   7309:        /*         } */
                   7310:        /*       } */
                   7311:        /*       /\* cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)]*nbcode[Tvard[k][2]][codtabm(ij,k)]; *\/ */
                   7312:        /* } */                 
1.326     brouard  7313: /* For each age and combination of dummy covariates we slightly move the parameters of delti in order to get the gradient*/                    
1.222     brouard  7314:        for(theta=1; theta <=npar; theta++){
                   7315:         for(i=1; i<=npar; i++)
                   7316:           xp[i] = x[i] + (i==theta ?delti[theta]:(double)0);
1.220     brouard  7317:                                
1.222     brouard  7318:         pmij(pmmij,cov,ncovmodel,xp,nlstate);
1.220     brouard  7319:                                
1.222     brouard  7320:         k=0;
                   7321:         for(i=1; i<= (nlstate); i++){
                   7322:           for(j=1; j<=(nlstate+ndeath);j++){
                   7323:             k=k+1;
                   7324:             gp[k]=pmmij[i][j];
                   7325:           }
                   7326:         }
1.220     brouard  7327:                                
1.222     brouard  7328:         for(i=1; i<=npar; i++)
                   7329:           xp[i] = x[i] - (i==theta ?delti[theta]:(double)0);
1.220     brouard  7330:                                
1.222     brouard  7331:         pmij(pmmij,cov,ncovmodel,xp,nlstate);
                   7332:         k=0;
                   7333:         for(i=1; i<=(nlstate); i++){
                   7334:           for(j=1; j<=(nlstate+ndeath);j++){
                   7335:             k=k+1;
                   7336:             gm[k]=pmmij[i][j];
                   7337:           }
                   7338:         }
1.220     brouard  7339:                                
1.222     brouard  7340:         for(i=1; i<= (nlstate)*(nlstate+ndeath); i++) 
                   7341:           gradg[theta][i]=(gp[i]-gm[i])/(double)2./delti[theta];  
                   7342:        }
1.126     brouard  7343: 
1.222     brouard  7344:        for(j=1; j<=(nlstate)*(nlstate+ndeath);j++)
                   7345:         for(theta=1; theta <=npar; theta++)
                   7346:           trgradg[j][theta]=gradg[theta][j];
1.220     brouard  7347:                        
1.222     brouard  7348:        matprod2(dnewm,trgradg,1,(nlstate)*(nlstate+ndeath),1,npar,1,npar,matcov); 
                   7349:        matprod2(doldm,dnewm,1,(nlstate)*(nlstate+ndeath),1,npar,1,(nlstate)*(nlstate+ndeath),gradg);
1.220     brouard  7350:                        
1.222     brouard  7351:        pmij(pmmij,cov,ncovmodel,x,nlstate);
1.220     brouard  7352:                        
1.222     brouard  7353:        k=0;
                   7354:        for(i=1; i<=(nlstate); i++){
                   7355:         for(j=1; j<=(nlstate+ndeath);j++){
                   7356:           k=k+1;
                   7357:           mu[k][(int) age]=pmmij[i][j];
                   7358:         }
                   7359:        }
                   7360:        for(i=1;i<=(nlstate)*(nlstate+ndeath);i++)
                   7361:         for(j=1;j<=(nlstate)*(nlstate+ndeath);j++)
                   7362:           varpij[i][j][(int)age] = doldm[i][j];
1.220     brouard  7363:                        
1.222     brouard  7364:        /*printf("\n%d ",(int)age);
                   7365:         for (i=1; i<=(nlstate)*(nlstate+ndeath);i++){
                   7366:         printf("%e [%e ;%e] ",gm[i],gm[i]-2*sqrt(doldm[i][i]),gm[i]+2*sqrt(doldm[i][i]));
                   7367:         fprintf(ficlog,"%e [%e ;%e] ",gm[i],gm[i]-2*sqrt(doldm[i][i]),gm[i]+2*sqrt(doldm[i][i]));
                   7368:         }*/
1.220     brouard  7369:                        
1.222     brouard  7370:        fprintf(ficresprob,"\n%d ",(int)age);
                   7371:        fprintf(ficresprobcov,"\n%d ",(int)age);
                   7372:        fprintf(ficresprobcor,"\n%d ",(int)age);
1.220     brouard  7373:                        
1.222     brouard  7374:        for (i=1; i<=(nlstate)*(nlstate+ndeath);i++)
                   7375:         fprintf(ficresprob,"%11.3e (%11.3e) ",mu[i][(int) age],sqrt(varpij[i][i][(int)age]));
                   7376:        for (i=1; i<=(nlstate)*(nlstate+ndeath);i++){
                   7377:         fprintf(ficresprobcov,"%11.3e ",mu[i][(int) age]);
                   7378:         fprintf(ficresprobcor,"%11.3e ",mu[i][(int) age]);
                   7379:        }
                   7380:        i=0;
                   7381:        for (k=1; k<=(nlstate);k++){
                   7382:         for (l=1; l<=(nlstate+ndeath);l++){ 
                   7383:           i++;
                   7384:           fprintf(ficresprobcov,"\n%d %d-%d",(int)age,k,l);
                   7385:           fprintf(ficresprobcor,"\n%d %d-%d",(int)age,k,l);
                   7386:           for (j=1; j<=i;j++){
                   7387:             /* printf(" k=%d l=%d i=%d j=%d\n",k,l,i,j);fflush(stdout); */
                   7388:             fprintf(ficresprobcov," %11.3e",varpij[i][j][(int)age]);
                   7389:             fprintf(ficresprobcor," %11.3e",varpij[i][j][(int) age]/sqrt(varpij[i][i][(int) age])/sqrt(varpij[j][j][(int)age]));
                   7390:           }
                   7391:         }
                   7392:        }/* end of loop for state */
                   7393:      } /* end of loop for age */
                   7394:      free_vector(gp,1,(nlstate+ndeath)*(nlstate+ndeath));
                   7395:      free_vector(gm,1,(nlstate+ndeath)*(nlstate+ndeath));
                   7396:      free_matrix(trgradg,1,(nlstate+ndeath)*(nlstate+ndeath),1,npar);
                   7397:      free_matrix(gradg,1,(nlstate+ndeath)*(nlstate+ndeath),1,npar);
                   7398:     
                   7399:      /* Confidence intervalle of pij  */
                   7400:      /*
                   7401:        fprintf(ficgp,"\nunset parametric;unset label");
                   7402:        fprintf(ficgp,"\nset log y;unset log x; set xlabel \"Age\";set ylabel \"probability (year-1)\"");
                   7403:        fprintf(ficgp,"\nset ter png small\nset size 0.65,0.65");
                   7404:        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);
                   7405:        fprintf(fichtm,"\n<br><img src=\"pijgr%s.png\"> ",optionfilefiname);
                   7406:        fprintf(ficgp,"\nset out \"pijgr%s.png\"",optionfilefiname);
                   7407:        fprintf(ficgp,"\nplot \"%s\" every :::%d::%d u 1:2 \"\%%lf",k1,k2,xfilevarprob);
                   7408:      */
                   7409:                
                   7410:      /* Drawing ellipsoids of confidence of two variables p(k1-l1,k2-l2)*/
                   7411:      first1=1;first2=2;
                   7412:      for (k2=1; k2<=(nlstate);k2++){
                   7413:        for (l2=1; l2<=(nlstate+ndeath);l2++){ 
                   7414:         if(l2==k2) continue;
                   7415:         j=(k2-1)*(nlstate+ndeath)+l2;
                   7416:         for (k1=1; k1<=(nlstate);k1++){
                   7417:           for (l1=1; l1<=(nlstate+ndeath);l1++){ 
                   7418:             if(l1==k1) continue;
                   7419:             i=(k1-1)*(nlstate+ndeath)+l1;
                   7420:             if(i<=j) continue;
                   7421:             for (age=bage; age<=fage; age ++){ 
                   7422:               if ((int)age %5==0){
                   7423:                 v1=varpij[i][i][(int)age]/stepm*YEARM/stepm*YEARM;
                   7424:                 v2=varpij[j][j][(int)age]/stepm*YEARM/stepm*YEARM;
                   7425:                 cv12=varpij[i][j][(int)age]/stepm*YEARM/stepm*YEARM;
                   7426:                 mu1=mu[i][(int) age]/stepm*YEARM ;
                   7427:                 mu2=mu[j][(int) age]/stepm*YEARM;
                   7428:                 c12=cv12/sqrt(v1*v2);
                   7429:                 /* Computing eigen value of matrix of covariance */
                   7430:                 lc1=((v1+v2)+sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
                   7431:                 lc2=((v1+v2)-sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
                   7432:                 if ((lc2 <0) || (lc1 <0) ){
                   7433:                   if(first2==1){
                   7434:                     first1=0;
                   7435:                     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);
                   7436:                   }
                   7437:                   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);
                   7438:                   /* lc1=fabs(lc1); */ /* If we want to have them positive */
                   7439:                   /* lc2=fabs(lc2); */
                   7440:                 }
1.220     brouard  7441:                                                                
1.222     brouard  7442:                 /* Eigen vectors */
1.280     brouard  7443:                 if(1+(v1-lc1)*(v1-lc1)/cv12/cv12 <1.e-5){
                   7444:                   printf(" Error sqrt of a negative number: %lf\n",1+(v1-lc1)*(v1-lc1)/cv12/cv12);
                   7445:                   fprintf(ficlog," Error sqrt of a negative number: %lf\n",1+(v1-lc1)*(v1-lc1)/cv12/cv12);
                   7446:                   v11=(1./sqrt(fabs(1+(v1-lc1)*(v1-lc1)/cv12/cv12)));
                   7447:                 }else
                   7448:                   v11=(1./sqrt(1+(v1-lc1)*(v1-lc1)/cv12/cv12));
1.222     brouard  7449:                 /*v21=sqrt(1.-v11*v11); *//* error */
                   7450:                 v21=(lc1-v1)/cv12*v11;
                   7451:                 v12=-v21;
                   7452:                 v22=v11;
                   7453:                 tnalp=v21/v11;
                   7454:                 if(first1==1){
                   7455:                   first1=0;
                   7456:                   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);
                   7457:                 }
                   7458:                 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);
                   7459:                 /*printf(fignu*/
                   7460:                 /* mu1+ v11*lc1*cost + v12*lc2*sin(t) */
                   7461:                 /* mu2+ v21*lc1*cost + v22*lc2*sin(t) */
                   7462:                 if(first==1){
                   7463:                   first=0;
                   7464:                   fprintf(ficgp,"\n# Ellipsoids of confidence\n#\n");
                   7465:                   fprintf(ficgp,"\nset parametric;unset label");
                   7466:                   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);
                   7467:                   fprintf(ficgp,"\nset ter svg size 640, 480");
1.266     brouard  7468:                   fprintf(fichtmcov,"\n<p><br>Ellipsoids of confidence cov(p%1d%1d,p%1d%1d) expressed in year<sup>-1</sup>\
1.220     brouard  7469:  :<a href=\"%s_%d%1d%1d-%1d%1d.svg\">                                                                                                                                          \
1.201     brouard  7470: %s_%d%1d%1d-%1d%1d.svg</A>, ",k1,l1,k2,l2,\
1.222     brouard  7471:                           subdirf2(optionfilefiname,"VARPIJGR_"), j1,k1,l1,k2,l2,      \
                   7472:                           subdirf2(optionfilefiname,"VARPIJGR_"), j1,k1,l1,k2,l2);
                   7473:                   fprintf(fichtmcov,"\n<br><img src=\"%s_%d%1d%1d-%1d%1d.svg\"> ",subdirf2(optionfilefiname,"VARPIJGR_"), j1,k1,l1,k2,l2);
                   7474:                   fprintf(fichtmcov,"\n<br> Correlation at age %d (%.3f),",(int) age, c12);
                   7475:                   fprintf(ficgp,"\nset out \"%s_%d%1d%1d-%1d%1d.svg\"",subdirf2(optionfilefiname,"VARPIJGR_"), j1,k1,l1,k2,l2);
                   7476:                   fprintf(ficgp,"\nset label \"%d\" at %11.3e,%11.3e center",(int) age, mu1,mu2);
                   7477:                   fprintf(ficgp,"\n# Age %d, p%1d%1d - p%1d%1d",(int) age, k1,l1,k2,l2);
                   7478:                   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  7479:                           mu1,std,v11,sqrt(fabs(lc1)),v12,sqrt(fabs(lc2)), \
                   7480:                           mu2,std,v21,sqrt(fabs(lc1)),v22,sqrt(fabs(lc2))); /* For gnuplot only */
1.222     brouard  7481:                 }else{
                   7482:                   first=0;
                   7483:                   fprintf(fichtmcov," %d (%.3f),",(int) age, c12);
                   7484:                   fprintf(ficgp,"\n# Age %d, p%1d%1d - p%1d%1d",(int) age, k1,l1,k2,l2);
                   7485:                   fprintf(ficgp,"\nset label \"%d\" at %11.3e,%11.3e center",(int) age, mu1,mu2);
                   7486:                   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  7487:                           mu1,std,v11,sqrt(lc1),v12,sqrt(fabs(lc2)),   \
                   7488:                           mu2,std,v21,sqrt(lc1),v22,sqrt(fabs(lc2)));
1.222     brouard  7489:                 }/* if first */
                   7490:               } /* age mod 5 */
                   7491:             } /* end loop age */
                   7492:             fprintf(ficgp,"\nset out;\nset out \"%s_%d%1d%1d-%1d%1d.svg\";replot;set out;",subdirf2(optionfilefiname,"VARPIJGR_"), j1,k1,l1,k2,l2);
                   7493:             first=1;
                   7494:           } /*l12 */
                   7495:         } /* k12 */
                   7496:        } /*l1 */
                   7497:      }/* k1 */
1.332     brouard  7498:    }  /* loop on combination of covariates j1 */
1.326     brouard  7499:    } /* loop on nres */
1.222     brouard  7500:    free_ma3x(varpij,1,nlstate,1,nlstate+ndeath,(int) bage, (int)fage);
                   7501:    free_matrix(mu,1,(nlstate+ndeath)*(nlstate+ndeath),(int) bage, (int)fage);
                   7502:    free_matrix(doldm,1,(nlstate)*(nlstate+ndeath),1,(nlstate)*(nlstate+ndeath));
                   7503:    free_matrix(dnewm,1,(nlstate)*(nlstate+ndeath),1,npar);
                   7504:    free_vector(xp,1,npar);
                   7505:    fclose(ficresprob);
                   7506:    fclose(ficresprobcov);
                   7507:    fclose(ficresprobcor);
                   7508:    fflush(ficgp);
                   7509:    fflush(fichtmcov);
                   7510:  }
1.126     brouard  7511: 
                   7512: 
                   7513: /******************* Printing html file ***********/
1.201     brouard  7514: void printinghtml(char fileresu[], char title[], char datafile[], int firstpass, \
1.126     brouard  7515:                  int lastpass, int stepm, int weightopt, char model[],\
                   7516:                  int imx,int jmin, int jmax, double jmeanint,char rfileres[],\
1.296     brouard  7517:                  int popforecast, int mobilav, int prevfcast, int mobilavproj, int prevbcast, int estepm , \
                   7518:                  double jprev1, double mprev1,double anprev1, double dateprev1, double dateprojd, double dateback1, \
                   7519:                  double jprev2, double mprev2,double anprev2, double dateprev2, double dateprojf, double dateback2){
1.237     brouard  7520:   int jj1, k1, i1, cpt, k4, nres;
1.319     brouard  7521:   /* In fact some results are already printed in fichtm which is open */
1.126     brouard  7522:    fprintf(fichtm,"<ul><li><a href='#firstorder'>Result files (first order: no variance)</a>\n \
                   7523:    <li><a href='#secondorder'>Result files (second order (variance)</a>\n \
                   7524: </ul>");
1.319     brouard  7525: /*    fprintf(fichtm,"<ul><li> model=1+age+%s\n \ */
                   7526: /* </ul>", model); */
1.214     brouard  7527:    fprintf(fichtm,"<ul><li><h4><a name='firstorder'>Result files (first order: no variance)</a></h4>\n");
                   7528:    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",
                   7529:           jprev1, mprev1,anprev1,jprev2, mprev2,anprev2,subdirfext3(optionfilefiname,"PHTMFR_",".htm"),subdirfext3(optionfilefiname,"PHTMFR_",".htm"));
1.332     brouard  7530:    fprintf(fichtm,"<li> - Observed prevalence (cross-sectional 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  7531:           jprev1, mprev1,anprev1,jprev2, mprev2,anprev2,subdirfext3(optionfilefiname,"PHTM_",".htm"),subdirfext3(optionfilefiname,"PHTM_",".htm"));
                   7532:    fprintf(fichtm,",  <a href=\"%s\">%s</a> (text file) <br>\n",subdirf2(fileresu,"P_"),subdirf2(fileresu,"P_"));
1.126     brouard  7533:    fprintf(fichtm,"\
                   7534:  - Estimated transition probabilities over %d (stepm) months: <a href=\"%s\">%s</a><br>\n ",
1.201     brouard  7535:           stepm,subdirf2(fileresu,"PIJ_"),subdirf2(fileresu,"PIJ_"));
1.126     brouard  7536:    fprintf(fichtm,"\
1.217     brouard  7537:  - Estimated back transition probabilities over %d (stepm) months: <a href=\"%s\">%s</a><br>\n ",
                   7538:           stepm,subdirf2(fileresu,"PIJB_"),subdirf2(fileresu,"PIJB_"));
                   7539:    fprintf(fichtm,"\
1.288     brouard  7540:  - Period (forward) prevalence in each health state: <a href=\"%s\">%s</a> <br>\n",
1.201     brouard  7541:           subdirf2(fileresu,"PL_"),subdirf2(fileresu,"PL_"));
1.126     brouard  7542:    fprintf(fichtm,"\
1.288     brouard  7543:  - Backward prevalence in each health state: <a href=\"%s\">%s</a> <br>\n",
1.217     brouard  7544:           subdirf2(fileresu,"PLB_"),subdirf2(fileresu,"PLB_"));
                   7545:    fprintf(fichtm,"\
1.211     brouard  7546:  - (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  7547:    <a href=\"%s\">%s</a> <br>\n",
1.201     brouard  7548:           estepm,subdirf2(fileresu,"E_"),subdirf2(fileresu,"E_"));
1.211     brouard  7549:    if(prevfcast==1){
                   7550:      fprintf(fichtm,"\
                   7551:  - Prevalence projections by age and states:                           \
1.201     brouard  7552:    <a href=\"%s\">%s</a> <br>\n</li>", subdirf2(fileresu,"F_"),subdirf2(fileresu,"F_"));
1.211     brouard  7553:    }
1.126     brouard  7554: 
                   7555: 
1.225     brouard  7556:    m=pow(2,cptcoveff);
1.222     brouard  7557:    if (cptcovn < 1) {m=1;ncodemax[1]=1;}
1.126     brouard  7558: 
1.317     brouard  7559:    fprintf(fichtm," \n<ul><li><b>Graphs (first order)</b></li><p>");
1.264     brouard  7560: 
                   7561:    jj1=0;
                   7562: 
                   7563:    fprintf(fichtm," \n<ul>");
                   7564:    for(nres=1; nres <= nresult; nres++) /* For each resultline */
                   7565:    for(k1=1; k1<=m;k1++){ /* For each combination of covariate */
                   7566:      if(m != 1 && TKresult[nres]!= k1)
                   7567:        continue;
                   7568:      jj1++;
                   7569:      if (cptcovn > 0) {
                   7570:        fprintf(fichtm,"\n<li><a  size=\"1\" color=\"#EC5E5E\" href=\"#rescov");
                   7571:        for (cpt=1; cpt<=cptcoveff;cpt++){ 
                   7572:         fprintf(fichtm,"_V%d=%d_",Tvresult[nres][cpt],(int)Tresult[nres][cpt]);
                   7573:        }
                   7574:        for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
                   7575:         fprintf(fichtm,"_V%d=%f_",Tvqresult[nres][k4],Tqresult[nres][k4]);
                   7576:        }
                   7577:        fprintf(fichtm,"\">");
                   7578:        
                   7579:        /* if(nqfveff+nqtveff 0) */ /* Test to be done */
                   7580:        fprintf(fichtm,"************ Results for covariates");
                   7581:        for (cpt=1; cpt<=cptcoveff;cpt++){ 
                   7582:         fprintf(fichtm," V%d=%d ",Tvresult[nres][cpt],(int)Tresult[nres][cpt]);
                   7583:        }
                   7584:        for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
                   7585:         fprintf(fichtm," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
                   7586:        }
                   7587:        if(invalidvarcomb[k1]){
                   7588:         fprintf(fichtm," Warning Combination (%d) ignored because no cases ",k1); 
                   7589:         continue;
                   7590:        }
                   7591:        fprintf(fichtm,"</a></li>");
                   7592:      } /* cptcovn >0 */
                   7593:    }
1.317     brouard  7594:    fprintf(fichtm," \n</ul>");
1.264     brouard  7595: 
1.222     brouard  7596:    jj1=0;
1.237     brouard  7597: 
                   7598:    for(nres=1; nres <= nresult; nres++) /* For each resultline */
1.241     brouard  7599:    for(k1=1; k1<=m;k1++){ /* For each combination of covariate */
1.253     brouard  7600:      if(m != 1 && TKresult[nres]!= k1)
1.237     brouard  7601:        continue;
1.220     brouard  7602: 
1.222     brouard  7603:      /* for(i1=1; i1<=ncodemax[k1];i1++){ */
                   7604:      jj1++;
                   7605:      if (cptcovn > 0) {
1.264     brouard  7606:        fprintf(fichtm,"\n<p><a name=\"rescov");
                   7607:        for (cpt=1; cpt<=cptcoveff;cpt++){ 
                   7608:         fprintf(fichtm,"_V%d=%d_",Tvresult[nres][cpt],(int)Tresult[nres][cpt]);
                   7609:        }
                   7610:        for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
                   7611:         fprintf(fichtm,"_V%d=%f_",Tvqresult[nres][k4],Tqresult[nres][k4]);
                   7612:        }
                   7613:        fprintf(fichtm,"\"</a>");
                   7614:  
1.222     brouard  7615:        fprintf(fichtm,"<hr  size=\"2\" color=\"#EC5E5E\">************ Results for covariates");
1.225     brouard  7616:        for (cpt=1; cpt<=cptcoveff;cpt++){ 
1.237     brouard  7617:         fprintf(fichtm," V%d=%d ",Tvresult[nres][cpt],(int)Tresult[nres][cpt]);
                   7618:         printf(" V%d=%d ",Tvresult[nres][cpt],Tresult[nres][cpt]);fflush(stdout);
                   7619:         /* fprintf(fichtm," V%d=%d ",Tvaraff[cpt],nbcode[Tvaraff[cpt]][codtabm(jj1,cpt)]); */
                   7620:         /* printf(" V%d=%d ",Tvaraff[cpt],nbcode[Tvaraff[cpt]][codtabm(jj1,cpt)]);fflush(stdout); */
1.222     brouard  7621:        }
1.237     brouard  7622:        for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
                   7623:        fprintf(fichtm," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
                   7624:        printf(" V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);fflush(stdout);
                   7625:       }
                   7626:        
1.230     brouard  7627:        /* if(nqfveff+nqtveff 0) */ /* Test to be done */
1.321     brouard  7628:        fprintf(fichtm," (model=%s) ************\n<hr size=\"2\" color=\"#EC5E5E\">",model);
1.222     brouard  7629:        if(invalidvarcomb[k1]){
                   7630:         fprintf(fichtm,"\n<h3>Combination (%d) ignored because no cases </h3>\n",k1); 
                   7631:         printf("\nCombination (%d) ignored because no cases \n",k1); 
                   7632:         continue;
                   7633:        }
                   7634:      }
                   7635:      /* aij, bij */
1.259     brouard  7636:      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  7637: <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  7638:      /* Pij */
1.241     brouard  7639:      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> \
                   7640: <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  7641:      /* Quasi-incidences */
                   7642:      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  7643:  before but expressed in per year i.e. quasi incidences if stepm is small and probabilities too, \
1.211     brouard  7644:  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  7645: 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> \
                   7646: <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  7647:      /* Survival functions (period) in state j */
                   7648:      for(cpt=1; cpt<=nlstate;cpt++){
1.329     brouard  7649:        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);
                   7650:        fprintf(fichtm," (data from text file  <a href=\"%s.txt\">%s.txt</a>)\n<br>",subdirf2(optionfilefiname,"PIJ_"),subdirf2(optionfilefiname,"PIJ_"));
                   7651:        fprintf(fichtm,"<img src=\"%s_%d-%d-%d.svg\">",subdirf2(optionfilefiname,"LIJ_"),cpt,k1,nres);
1.222     brouard  7652:      }
                   7653:      /* State specific survival functions (period) */
                   7654:      for(cpt=1; cpt<=nlstate;cpt++){
1.292     brouard  7655:        fprintf(fichtm,"<br>\n- Survival functions in state %d and in any other live state (total).\
                   7656:  And probability to be observed in various states (up to %d) being in state %d at different ages.      \
1.329     brouard  7657:  <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);
                   7658:        fprintf(fichtm," (data from text file  <a href=\"%s.txt\">%s.txt</a>)\n<br>",subdirf2(optionfilefiname,"PIJ_"),subdirf2(optionfilefiname,"PIJ_"));
                   7659:        fprintf(fichtm,"<img src=\"%s_%d-%d-%d.svg\">",subdirf2(optionfilefiname,"LIJT_"),cpt,k1,nres);
1.222     brouard  7660:      }
1.288     brouard  7661:      /* Period (forward stable) prevalence in each health state */
1.222     brouard  7662:      for(cpt=1; cpt<=nlstate;cpt++){
1.329     brouard  7663:        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);
                   7664:        fprintf(fichtm," (data from text file  <a href=\"%s.txt\">%s.txt</a>)\n<br>",subdirf2(optionfilefiname,"P_"),subdirf2(optionfilefiname,"P_"));
                   7665:       fprintf(fichtm,"<img src=\"%s_%d-%d-%d.svg\">" ,subdirf2(optionfilefiname,"P_"),cpt,k1,nres);
1.222     brouard  7666:      }
1.296     brouard  7667:      if(prevbcast==1){
1.288     brouard  7668:        /* Backward prevalence in each health state */
1.222     brouard  7669:        for(cpt=1; cpt<=nlstate;cpt++){
1.264     brouard  7670:         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  7671: <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  7672:        }
1.217     brouard  7673:      }
1.222     brouard  7674:      if(prevfcast==1){
1.288     brouard  7675:        /* Projection of prevalence up to period (forward stable) prevalence in each health state */
1.222     brouard  7676:        for(cpt=1; cpt<=nlstate;cpt++){
1.314     brouard  7677:         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);
                   7678:         fprintf(fichtm," (data from text file  <a href=\"%s.txt\">%s.txt</a>)\n<br>",subdirf2(optionfilefiname,"F_"),subdirf2(optionfilefiname,"F_"));
                   7679:         fprintf(fichtm,"<img src=\"%s_%d-%d-%d.svg\">",
                   7680:                 subdirf2(optionfilefiname,"PROJ_"),cpt,k1,nres);
1.222     brouard  7681:        }
                   7682:      }
1.296     brouard  7683:      if(prevbcast==1){
1.268     brouard  7684:       /* Back projection of prevalence up to stable (mixed) back-prevalence in each health state */
                   7685:        for(cpt=1; cpt<=nlstate;cpt++){
1.273     brouard  7686:         fprintf(fichtm,"<br>\n- Back projection of cross-sectional prevalence (estimated with cases observed from %.1f to %.1f and mobil_average=%d), \
                   7687:  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 \
                   7688:  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  7689: 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);
                   7690:         fprintf(fichtm," (data from text file  <a href=\"%s.txt\">%s.txt</a>)\n<br>",subdirf2(optionfilefiname,"FB_"),subdirf2(optionfilefiname,"FB_"));
                   7691:         fprintf(fichtm," <img src=\"%s_%d-%d-%d.svg\">", subdirf2(optionfilefiname,"PROJB_"),cpt,k1,nres);
1.268     brouard  7692:        }
                   7693:      }
1.220     brouard  7694:         
1.222     brouard  7695:      for(cpt=1; cpt<=nlstate;cpt++) {
1.314     brouard  7696:        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);
                   7697:        fprintf(fichtm," (data from text file  <a href=\"%s.txt\"> %s.txt</a>)\n<br>",subdirf2(optionfilefiname,"E_"),subdirf2(optionfilefiname,"E_"));
                   7698:        fprintf(fichtm,"<img src=\"%s_%d-%d-%d.svg\">", subdirf2(optionfilefiname,"EXP_"),cpt,k1,nres );
1.222     brouard  7699:      }
                   7700:      /* } /\* end i1 *\/ */
                   7701:    }/* End k1 */
                   7702:    fprintf(fichtm,"</ul>");
1.126     brouard  7703: 
1.222     brouard  7704:    fprintf(fichtm,"\
1.126     brouard  7705: \n<br><li><h4> <a name='secondorder'>Result files (second order: variances)</a></h4>\n\
1.193     brouard  7706:  - Parameter file with estimated parameters and covariance matrix: <a href=\"%s\">%s</a> <br> \
1.203     brouard  7707:  - 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  7708: But because parameters are usually highly correlated (a higher incidence of disability \
                   7709: and a higher incidence of recovery can give very close observed transition) it might \
                   7710: be very useful to look not only at linear confidence intervals estimated from the \
                   7711: variances but at the covariance matrix. And instead of looking at the estimated coefficients \
                   7712: (parameters) of the logistic regression, it might be more meaningful to visualize the \
                   7713: covariance matrix of the one-step probabilities. \
                   7714: See page 'Matrix of variance-covariance of one-step probabilities' below. \n", rfileres,rfileres);
1.126     brouard  7715: 
1.222     brouard  7716:    fprintf(fichtm," - Standard deviation of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
                   7717:           subdirf2(fileresu,"PROB_"),subdirf2(fileresu,"PROB_"));
                   7718:    fprintf(fichtm,"\
1.126     brouard  7719:  - Variance-covariance of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
1.222     brouard  7720:           subdirf2(fileresu,"PROBCOV_"),subdirf2(fileresu,"PROBCOV_"));
1.126     brouard  7721: 
1.222     brouard  7722:    fprintf(fichtm,"\
1.126     brouard  7723:  - Correlation matrix of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
1.222     brouard  7724:           subdirf2(fileresu,"PROBCOR_"),subdirf2(fileresu,"PROBCOR_"));
                   7725:    fprintf(fichtm,"\
1.126     brouard  7726:  - 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): \
                   7727:    <a href=\"%s\">%s</a> <br>\n</li>",
1.201     brouard  7728:           estepm,subdirf2(fileresu,"CVE_"),subdirf2(fileresu,"CVE_"));
1.222     brouard  7729:    fprintf(fichtm,"\
1.126     brouard  7730:  - (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): \
                   7731:    <a href=\"%s\">%s</a> <br>\n</li>",
1.201     brouard  7732:           estepm,subdirf2(fileresu,"STDE_"),subdirf2(fileresu,"STDE_"));
1.222     brouard  7733:    fprintf(fichtm,"\
1.288     brouard  7734:  - 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  7735:           estepm, subdirf2(fileresu,"V_"),subdirf2(fileresu,"V_"));
                   7736:    fprintf(fichtm,"\
1.128     brouard  7737:  - 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  7738:           estepm, subdirf2(fileresu,"T_"),subdirf2(fileresu,"T_"));
                   7739:    fprintf(fichtm,"\
1.288     brouard  7740:  - Standard deviation of forward (period) prevalences: <a href=\"%s\">%s</a> <br>\n",\
1.222     brouard  7741:           subdirf2(fileresu,"VPL_"),subdirf2(fileresu,"VPL_"));
1.126     brouard  7742: 
                   7743: /*  if(popforecast==1) fprintf(fichtm,"\n */
                   7744: /*  - Prevalences forecasting: <a href=\"f%s\">f%s</a> <br>\n */
                   7745: /*  - Population forecasting (if popforecast=1): <a href=\"pop%s\">pop%s</a> <br>\n */
                   7746: /*     <br>",fileres,fileres,fileres,fileres); */
                   7747: /*  else  */
                   7748: /*    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  7749:    fflush(fichtm);
1.126     brouard  7750: 
1.225     brouard  7751:    m=pow(2,cptcoveff);
1.222     brouard  7752:    if (cptcovn < 1) {m=1;ncodemax[1]=1;}
1.126     brouard  7753: 
1.317     brouard  7754:    fprintf(fichtm," <ul><li><b>Graphs (second order)</b></li><p>");
                   7755: 
                   7756:   jj1=0;
                   7757: 
                   7758:    fprintf(fichtm," \n<ul>");
                   7759:    for(nres=1; nres <= nresult; nres++) /* For each resultline */
                   7760:    for(k1=1; k1<=m;k1++){ /* For each combination of covariate */
                   7761:      if(m != 1 && TKresult[nres]!= k1)
                   7762:        continue;
                   7763:      jj1++;
                   7764:      if (cptcovn > 0) {
                   7765:        fprintf(fichtm,"\n<li><a  size=\"1\" color=\"#EC5E5E\" href=\"#rescovsecond");
                   7766:        for (cpt=1; cpt<=cptcoveff;cpt++){ 
                   7767:         fprintf(fichtm,"_V%d=%d_",Tvresult[nres][cpt],(int)Tresult[nres][cpt]);
                   7768:        }
                   7769:        for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
                   7770:         fprintf(fichtm,"_V%d=%f_",Tvqresult[nres][k4],Tqresult[nres][k4]);
                   7771:        }
                   7772:        fprintf(fichtm,"\">");
                   7773:        
                   7774:        /* if(nqfveff+nqtveff 0) */ /* Test to be done */
                   7775:        fprintf(fichtm,"************ Results for covariates");
                   7776:        for (cpt=1; cpt<=cptcoveff;cpt++){ 
                   7777:         fprintf(fichtm," V%d=%d ",Tvresult[nres][cpt],(int)Tresult[nres][cpt]);
                   7778:        }
                   7779:        for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
                   7780:         fprintf(fichtm," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
                   7781:        }
                   7782:        if(invalidvarcomb[k1]){
                   7783:         fprintf(fichtm," Warning Combination (%d) ignored because no cases ",k1); 
                   7784:         continue;
                   7785:        }
                   7786:        fprintf(fichtm,"</a></li>");
                   7787:      } /* cptcovn >0 */
                   7788:    }
                   7789:    fprintf(fichtm," \n</ul>");
                   7790: 
1.222     brouard  7791:    jj1=0;
1.237     brouard  7792: 
1.241     brouard  7793:    for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.222     brouard  7794:    for(k1=1; k1<=m;k1++){
1.253     brouard  7795:      if(m != 1 && TKresult[nres]!= k1)
1.237     brouard  7796:        continue;
1.222     brouard  7797:      /* for(i1=1; i1<=ncodemax[k1];i1++){ */
                   7798:      jj1++;
1.126     brouard  7799:      if (cptcovn > 0) {
1.317     brouard  7800:        fprintf(fichtm,"\n<p><a name=\"rescovsecond");
                   7801:        for (cpt=1; cpt<=cptcoveff;cpt++){ 
                   7802:         fprintf(fichtm,"_V%d=%d_",Tvresult[nres][cpt],(int)Tresult[nres][cpt]);
                   7803:        }
                   7804:        for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
                   7805:         fprintf(fichtm,"_V%d=%f_",Tvqresult[nres][k4],Tqresult[nres][k4]);
                   7806:        }
                   7807:        fprintf(fichtm,"\"</a>");
                   7808:        
1.126     brouard  7809:        fprintf(fichtm,"<hr  size=\"2\" color=\"#EC5E5E\">************ Results for covariates");
1.317     brouard  7810:        for (cpt=1; cpt<=cptcoveff;cpt++){  /**< cptcoveff number of variables */
1.237     brouard  7811:         fprintf(fichtm," V%d=%d ",Tvresult[nres][cpt],Tresult[nres][cpt]);
1.317     brouard  7812:         printf(" V%d=%d ",Tvresult[nres][cpt],Tresult[nres][cpt]);fflush(stdout);
1.237     brouard  7813:         /* fprintf(fichtm," V%d=%d ",Tvaraff[cpt],nbcode[Tvaraff[cpt]][codtabm(jj1,cpt)]); */
1.317     brouard  7814:        }
1.237     brouard  7815:        for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
                   7816:        fprintf(fichtm," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
                   7817:       }
                   7818: 
1.321     brouard  7819:        fprintf(fichtm," (model=%s) ************\n<hr size=\"2\" color=\"#EC5E5E\">",model);
1.220     brouard  7820: 
1.222     brouard  7821:        if(invalidvarcomb[k1]){
                   7822:         fprintf(fichtm,"\n<h4>Combination (%d) ignored because no cases </h4>\n",k1); 
                   7823:         continue;
                   7824:        }
1.126     brouard  7825:      }
                   7826:      for(cpt=1; cpt<=nlstate;cpt++) {
1.258     brouard  7827:        fprintf(fichtm,"\n<br>- Observed (cross-sectional with mov_average=%d) and period (incidence based) \
1.314     brouard  7828: 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);
                   7829:        fprintf(fichtm," (data from text file  <a href=\"%s\">%s</a>)\n <br>",subdirf2(fileresu,"VPL_"),subdirf2(fileresu,"VPL_"));
                   7830:        fprintf(fichtm,"<img src=\"%s_%d-%d-%d.svg\">",subdirf2(optionfilefiname,"V_"), cpt,k1,nres);
1.126     brouard  7831:      }
                   7832:      fprintf(fichtm,"\n<br>- Total life expectancy by age and \
1.314     brouard  7833: health expectancies in each live states (1 to %d). If popbased=1 the smooth (due to the model) \
1.128     brouard  7834: true period expectancies (those weighted with period prevalences are also\
                   7835:  drawn in addition to the population based expectancies computed using\
1.314     brouard  7836:  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);
                   7837:      fprintf(fichtm," (data from text file <a href=\"%s.txt\">%s.txt</a>) \n<br>",subdirf2(optionfilefiname,"T_"),subdirf2(optionfilefiname,"T_"));
                   7838:      fprintf(fichtm,"<img src=\"%s_%d-%d.svg\">",subdirf2(optionfilefiname,"E_"),k1,nres);
1.222     brouard  7839:      /* } /\* end i1 *\/ */
                   7840:    }/* End k1 */
1.241     brouard  7841:   }/* End nres */
1.222     brouard  7842:    fprintf(fichtm,"</ul>");
                   7843:    fflush(fichtm);
1.126     brouard  7844: }
                   7845: 
                   7846: /******************* Gnuplot file **************/
1.296     brouard  7847: 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  7848: 
                   7849:   char dirfileres[132],optfileres[132];
1.264     brouard  7850:   char gplotcondition[132], gplotlabel[132];
1.237     brouard  7851:   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  7852:   int lv=0, vlv=0, kl=0;
1.130     brouard  7853:   int ng=0;
1.201     brouard  7854:   int vpopbased;
1.223     brouard  7855:   int ioffset; /* variable offset for columns */
1.270     brouard  7856:   int iyearc=1; /* variable column for year of projection  */
                   7857:   int iagec=1; /* variable column for age of projection  */
1.235     brouard  7858:   int nres=0; /* Index of resultline */
1.266     brouard  7859:   int istart=1; /* For starting graphs in projections */
1.219     brouard  7860: 
1.126     brouard  7861: /*   if((ficgp=fopen(optionfilegnuplot,"a"))==NULL) { */
                   7862: /*     printf("Problem with file %s",optionfilegnuplot); */
                   7863: /*     fprintf(ficlog,"Problem with file %s",optionfilegnuplot); */
                   7864: /*   } */
                   7865: 
                   7866:   /*#ifdef windows */
                   7867:   fprintf(ficgp,"cd \"%s\" \n",pathc);
1.223     brouard  7868:   /*#endif */
1.225     brouard  7869:   m=pow(2,cptcoveff);
1.126     brouard  7870: 
1.274     brouard  7871:   /* diagram of the model */
                   7872:   fprintf(ficgp,"\n#Diagram of the model \n");
                   7873:   fprintf(ficgp,"\ndelta=0.03;delta2=0.07;unset arrow;\n");
                   7874:   fprintf(ficgp,"yoff=(%d > 2? 0:1);\n",nlstate);
                   7875:   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);
                   7876: 
                   7877:   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);
                   7878:   fprintf(ficgp,"\n#show arrow\nunset label\n");
                   7879:   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);
                   7880:   fprintf(ficgp,"\nset label %d+1 sprintf(\"State %%d\",%d+1) center at 0.,0.  font \"helvetica, 16\" tc rgbcolor \"red\"\n",nlstate,nlstate);
                   7881:   fprintf(ficgp,"\n#show label\nunset border;unset xtics; unset ytics;\n");
                   7882:   fprintf(ficgp,"\n\nset ter svg size 640, 480;set out \"%s_.svg\" \n",subdirf2(optionfilefiname,"D_"));
                   7883:   fprintf(ficgp,"unset log y; plot [-1.2:1.2][yoff-1.2:1.2] 1/0 not; set out;reset;\n");
                   7884: 
1.202     brouard  7885:   /* Contribution to likelihood */
                   7886:   /* Plot the probability implied in the likelihood */
1.223     brouard  7887:   fprintf(ficgp,"\n# Contributions to the Likelihood, mle >=1. For mle=4 no interpolation, pure matrix products.\n#\n");
                   7888:   fprintf(ficgp,"\n set log y; unset log x;set xlabel \"Age\"; set ylabel \"Likelihood (-2Log(L))\";");
                   7889:   /* fprintf(ficgp,"\nset ter svg size 640, 480"); */ /* Too big for svg */
                   7890:   fprintf(ficgp,"\nset ter pngcairo size 640, 480");
1.204     brouard  7891: /* nice for mle=4 plot by number of matrix products.
1.202     brouard  7892:    replot  "rrtest1/toto.txt" u 2:($4 == 1 && $5==2 ? $9 : 1/0):5 t "p12" with point lc 1 */
                   7893: /* replot exp(p1+p2*x)/(1+exp(p1+p2*x)+exp(p3+p4*x)+exp(p5+p6*x)) t "p12(x)"  */
1.223     brouard  7894:   /* fprintf(ficgp,"\nset out \"%s.svg\";",subdirf2(optionfilefiname,"ILK_")); */
                   7895:   fprintf(ficgp,"\nset out \"%s-dest.png\";",subdirf2(optionfilefiname,"ILK_"));
                   7896:   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));
                   7897:   fprintf(ficgp,"\nset out \"%s-ori.png\";",subdirf2(optionfilefiname,"ILK_"));
                   7898:   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));
                   7899:   for (i=1; i<= nlstate ; i ++) {
                   7900:     fprintf(ficgp,"\nset out \"%s-p%dj.png\";set ylabel \"Probability for each individual/wave\";",subdirf2(optionfilefiname,"ILK_"),i);
                   7901:     fprintf(ficgp,"unset log;\n# plot weighted, mean weight should have point size of 0.5\n plot  \"%s\"",subdirf(fileresilk));
                   7902:     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);
                   7903:     for (j=2; j<= nlstate+ndeath ; j ++) {
                   7904:       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);
                   7905:     }
                   7906:     fprintf(ficgp,";\nset out; unset ylabel;\n"); 
                   7907:   }
                   7908:   /* 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 */               
                   7909:   /* fprintf(ficgp,"\nset log y;plot  \"%s\" u 2:(-$11):3 t \"All sample, all transitions\" with dots lc variable",subdirf(fileresilk)); */
                   7910:   /* fprintf(ficgp,"\nreplot  \"%s\" u 2:($3 <= 3 ? -$11 : 1/0):3 t \"First 3 individuals\" with line lc variable", subdirf(fileresilk)); */
                   7911:   fprintf(ficgp,"\nset out;unset log\n");
                   7912:   /* fprintf(ficgp,"\nset out \"%s.svg\"; replot; set out; # bug gnuplot",subdirf2(optionfilefiname,"ILK_")); */
1.202     brouard  7913: 
1.126     brouard  7914:   strcpy(dirfileres,optionfilefiname);
                   7915:   strcpy(optfileres,"vpl");
1.223     brouard  7916:   /* 1eme*/
1.238     brouard  7917:   for (cpt=1; cpt<= nlstate ; cpt ++){ /* For each live state */
                   7918:     for (k1=1; k1<= m ; k1 ++){ /* For each valid combination of covariate */
1.236     brouard  7919:       for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.238     brouard  7920:        /* plot [100000000000000000000:-100000000000000000000] "mysbiaspar/vplrmysbiaspar.txt to check */
1.253     brouard  7921:        if(m != 1 && TKresult[nres]!= k1)
1.238     brouard  7922:          continue;
                   7923:        /* We are interested in selected combination by the resultline */
1.246     brouard  7924:        /* printf("\n# 1st: Period (stable) prevalence with CI: 'VPL_' files and live state =%d ", cpt); */
1.288     brouard  7925:        fprintf(ficgp,"\n# 1st: Forward (stable period) prevalence with CI: 'VPL_' files  and live state =%d ", cpt);
1.264     brouard  7926:        strcpy(gplotlabel,"(");
1.238     brouard  7927:        for (k=1; k<=cptcoveff; k++){    /* For each covariate k get corresponding value lv for combination k1 */
1.332     brouard  7928:          /* lv= decodtabm(k1,k,cptcoveff); /\* Should be the value of the covariate corresponding to k1 combination *\/ */
                   7929:          lv=codtabm(k1,TnsdVar[Tvaraff[k]]);
1.238     brouard  7930:          /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   7931:          /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   7932:          /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
                   7933:          vlv= nbcode[Tvaraff[k]][lv]; /* vlv is the value of the covariate lv, 0 or 1 */
                   7934:          /* For each combination of covariate k1 (V1=1, V3=0), we printed the current covariate k and its value vlv */
1.246     brouard  7935:          /* printf(" V%d=%d ",Tvaraff[k],vlv); */
1.238     brouard  7936:          fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv);
1.264     brouard  7937:          sprintf(gplotlabel+strlen(gplotlabel)," V%d=%d ",Tvaraff[k],vlv);
1.238     brouard  7938:        }
                   7939:        for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
1.246     brouard  7940:          /* printf(" V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]); */
1.238     brouard  7941:          fprintf(ficgp," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
1.264     brouard  7942:          sprintf(gplotlabel+strlen(gplotlabel)," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
                   7943:        }
                   7944:        strcpy(gplotlabel+strlen(gplotlabel),")");
1.246     brouard  7945:        /* printf("\n#\n"); */
1.238     brouard  7946:        fprintf(ficgp,"\n#\n");
                   7947:        if(invalidvarcomb[k1]){
1.260     brouard  7948:           /*k1=k1-1;*/ /* To be checked */
1.238     brouard  7949:          fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   7950:          continue;
                   7951:        }
1.235     brouard  7952:       
1.241     brouard  7953:        fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" \n",subdirf2(optionfilefiname,"V_"),cpt,k1,nres);
                   7954:        fprintf(ficgp,"\n#set out \"V_%s_%d-%d-%d.svg\" \n",optionfilefiname,cpt,k1,nres);
1.276     brouard  7955:        /* 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  7956:        fprintf(ficgp,"set title \"Alive state %d %s model=%s\" font \"Helvetica,12\"\n",cpt,gplotlabel,model);
1.260     brouard  7957:        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);
                   7958:        /* 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); */
                   7959:       /* k1-1 error should be nres-1*/
1.238     brouard  7960:        for (i=1; i<= nlstate ; i ++) {
                   7961:          if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
                   7962:          else        fprintf(ficgp," %%*lf (%%*lf)");
                   7963:        }
1.288     brouard  7964:        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  7965:        for (i=1; i<= nlstate ; i ++) {
                   7966:          if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
                   7967:          else fprintf(ficgp," %%*lf (%%*lf)");
                   7968:        } 
1.260     brouard  7969:        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  7970:        for (i=1; i<= nlstate ; i ++) {
                   7971:          if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
                   7972:          else fprintf(ficgp," %%*lf (%%*lf)");
                   7973:        }  
1.265     brouard  7974:        /* 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)); */
                   7975:        
                   7976:        fprintf(ficgp,"\" t\"\" w l lt 1,\"%s\" u 1:((",subdirf2(fileresu,"P_"));
                   7977:         if(cptcoveff ==0){
1.271     brouard  7978:          fprintf(ficgp,"$%d)) t 'Observed prevalence in state %d' with line lt 3",      2+3*(cpt-1),  cpt );
1.265     brouard  7979:        }else{
                   7980:          kl=0;
                   7981:          for (k=1; k<=cptcoveff; k++){    /* For each combination of covariate  */
1.332     brouard  7982:            /* lv= decodtabm(k1,k,cptcoveff); /\* Should be the covariate value corresponding to k1 combination and kth covariate *\/ */
                   7983:            lv=codtabm(k1,TnsdVar[Tvaraff[k]]);
1.265     brouard  7984:            /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   7985:            /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   7986:            /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
                   7987:            vlv= nbcode[Tvaraff[k]][lv];
                   7988:            kl++;
                   7989:            /* 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 *\/ */
                   7990:            /*6+(cpt-1)*(nlstate+1)+1+(i-1)+(nlstate+1)*nlstate; 6+(1-1)*(2+1)+1+(1-1) +(2+1)*2=13 */ 
                   7991:            /*6+1+(i-1)+(nlstate+1)*nlstate; 6+1+(1-1) +(2+1)*2=13 */ 
                   7992:            /* ''  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*/
                   7993:            if(k==cptcoveff){
                   7994:              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], \
                   7995:                      2+cptcoveff*2+3*(cpt-1),  cpt );  /* 4 or 6 ?*/
                   7996:            }else{
                   7997:              fprintf(ficgp,"$%d==%d && $%d==%d && ",kl+1, Tvaraff[k],kl+1+1,nbcode[Tvaraff[k]][lv]);
                   7998:              kl++;
                   7999:            }
                   8000:          } /* end covariate */
                   8001:        } /* end if no covariate */
                   8002: 
1.296     brouard  8003:        if(prevbcast==1){ /* We need to get the corresponding values of the covariates involved in this combination k1 */
1.238     brouard  8004:          /* 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  8005:          fprintf(ficgp,",\"%s\" u 1:((",subdirf2(fileresu,"PLB_")); /* Age is in 1, nres in 2 to be fixed */
1.238     brouard  8006:          if(cptcoveff ==0){
1.245     brouard  8007:            fprintf(ficgp,"$%d)) t 'Backward prevalence in state %d' with line lt 3",    2+(cpt-1),  cpt );
1.238     brouard  8008:          }else{
                   8009:            kl=0;
                   8010:            for (k=1; k<=cptcoveff; k++){    /* For each combination of covariate  */
1.332     brouard  8011:              /* lv= decodtabm(k1,k,cptcoveff); /\* Should be the covariate value corresponding to k1 combination and kth covariate *\/ */
                   8012:              lv=codtabm(k1,TnsdVar[Tvaraff[k]]);
1.238     brouard  8013:              /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   8014:              /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   8015:              /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
1.332     brouard  8016:              /* vlv= nbcode[Tvaraff[k]][lv]; */
                   8017:              vlv= nbcode[Tvaraff[k]][codtabm(k1,TnsdVar[Tvaraff[k]])];
1.223     brouard  8018:              kl++;
1.238     brouard  8019:              /* 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 *\/ */
                   8020:              /*6+(cpt-1)*(nlstate+1)+1+(i-1)+(nlstate+1)*nlstate; 6+(1-1)*(2+1)+1+(1-1) +(2+1)*2=13 */ 
                   8021:              /*6+1+(i-1)+(nlstate+1)*nlstate; 6+1+(1-1) +(2+1)*2=13 */ 
                   8022:              /* ''  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*/
                   8023:              if(k==cptcoveff){
1.245     brouard  8024:                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  8025:                        2+cptcoveff*2+(cpt-1),  cpt );  /* 4 or 6 ?*/
1.238     brouard  8026:              }else{
1.332     brouard  8027:                fprintf(ficgp,"$%d==%d && $%d==%d && ",kl+1, Tvaraff[k],kl+1+1,nbcode[Tvaraff[k]][codtabm(k1,TnsdVar[Tvaraff[k]])]);
1.238     brouard  8028:                kl++;
                   8029:              }
                   8030:            } /* end covariate */
                   8031:          } /* end if no covariate */
1.296     brouard  8032:          if(prevbcast == 1){
1.268     brouard  8033:            fprintf(ficgp,", \"%s\" every :::%d::%d u 1:($2==%d ? $3:1/0) \"%%lf %%lf",subdirf2(fileresu,"VBL_"),nres-1,nres-1,nres);
                   8034:            /* k1-1 error should be nres-1*/
                   8035:            for (i=1; i<= nlstate ; i ++) {
                   8036:              if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
                   8037:              else        fprintf(ficgp," %%*lf (%%*lf)");
                   8038:            }
1.271     brouard  8039:            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  8040:            for (i=1; i<= nlstate ; i ++) {
                   8041:              if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
                   8042:              else fprintf(ficgp," %%*lf (%%*lf)");
                   8043:            } 
1.276     brouard  8044:            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  8045:            for (i=1; i<= nlstate ; i ++) {
                   8046:              if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
                   8047:              else fprintf(ficgp," %%*lf (%%*lf)");
                   8048:            } 
1.274     brouard  8049:            fprintf(ficgp,"\" t\"\" w l lt 4");
1.268     brouard  8050:          } /* end if backprojcast */
1.296     brouard  8051:        } /* end if prevbcast */
1.276     brouard  8052:        /* fprintf(ficgp,"\nset out ;unset label;\n"); */
                   8053:        fprintf(ficgp,"\nset out ;unset title;\n");
1.238     brouard  8054:       } /* nres */
1.201     brouard  8055:     } /* k1 */
                   8056:   } /* cpt */
1.235     brouard  8057: 
                   8058:   
1.126     brouard  8059:   /*2 eme*/
1.238     brouard  8060:   for (k1=1; k1<= m ; k1 ++){  
                   8061:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.253     brouard  8062:       if(m != 1 && TKresult[nres]!= k1)
1.238     brouard  8063:        continue;
                   8064:       fprintf(ficgp,"\n# 2nd: Total life expectancy with CI: 't' files ");
1.264     brouard  8065:       strcpy(gplotlabel,"(");
1.238     brouard  8066:       for (k=1; k<=cptcoveff; k++){    /* For each covariate and each value */
1.332     brouard  8067:        /* lv= decodtabm(k1,k,cptcoveff); /\* Should be the covariate number corresponding to k1 combination *\/ */
                   8068:        lv=codtabm(k1,TnsdVar[Tvaraff[k]]);
1.223     brouard  8069:        /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   8070:        /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   8071:        /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
1.332     brouard  8072:        /* vlv= nbcode[Tvaraff[k]][lv]; */
                   8073:        vlv= nbcode[Tvaraff[k]][codtabm(k1,TnsdVar[Tvaraff[k]])];
1.223     brouard  8074:        fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv);
1.264     brouard  8075:        sprintf(gplotlabel+strlen(gplotlabel)," V%d=%d ",Tvaraff[k],vlv);
1.211     brouard  8076:       }
1.237     brouard  8077:       /* for(k=1; k <= ncovds; k++){ */
1.236     brouard  8078:       for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
1.238     brouard  8079:        printf(" V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
1.236     brouard  8080:        fprintf(ficgp," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
1.264     brouard  8081:        sprintf(gplotlabel+strlen(gplotlabel)," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
1.238     brouard  8082:       }
1.264     brouard  8083:       strcpy(gplotlabel+strlen(gplotlabel),")");
1.211     brouard  8084:       fprintf(ficgp,"\n#\n");
1.223     brouard  8085:       if(invalidvarcomb[k1]){
                   8086:        fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   8087:        continue;
                   8088:       }
1.219     brouard  8089:                        
1.241     brouard  8090:       fprintf(ficgp,"\nset out \"%s_%d-%d.svg\" \n",subdirf2(optionfilefiname,"E_"),k1,nres);
1.238     brouard  8091:       for(vpopbased=0; vpopbased <= popbased; vpopbased++){ /* Done for vpopbased=0 and vpopbased=1 if popbased==1*/
1.264     brouard  8092:        fprintf(ficgp,"\nset label \"popbased %d %s\" at graph 0.98,0.5 center rotate font \"Helvetica,12\"\n",vpopbased,gplotlabel);
                   8093:        if(vpopbased==0){
1.238     brouard  8094:          fprintf(ficgp,"set ylabel \"Years\" \nset ter svg size 640, 480\nplot [%.f:%.f] ",ageminpar,fage);
1.264     brouard  8095:        }else
1.238     brouard  8096:          fprintf(ficgp,"\nreplot ");
                   8097:        for (i=1; i<= nlstate+1 ; i ++) {
                   8098:          k=2*i;
1.261     brouard  8099:          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  8100:          for (j=1; j<= nlstate+1 ; j ++) {
                   8101:            if (j==i) fprintf(ficgp," %%lf (%%lf)");
                   8102:            else fprintf(ficgp," %%*lf (%%*lf)");
                   8103:          }   
                   8104:          if (i== 1) fprintf(ficgp,"\" t\"TLE\" w l lt %d, \\\n",i);
                   8105:          else fprintf(ficgp,"\" t\"LE in state (%d)\" w l lt %d, \\\n",i-1,i+1);
1.261     brouard  8106:          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  8107:          for (j=1; j<= nlstate+1 ; j ++) {
                   8108:            if (j==i) fprintf(ficgp," %%lf (%%lf)");
                   8109:            else fprintf(ficgp," %%*lf (%%*lf)");
                   8110:          }   
                   8111:          fprintf(ficgp,"\" t\"\" w l lt 0,");
1.261     brouard  8112:          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  8113:          for (j=1; j<= nlstate+1 ; j ++) {
                   8114:            if (j==i) fprintf(ficgp," %%lf (%%lf)");
                   8115:            else fprintf(ficgp," %%*lf (%%*lf)");
                   8116:          }   
                   8117:          if (i== (nlstate+1)) fprintf(ficgp,"\" t\"\" w l lt 0");
                   8118:          else fprintf(ficgp,"\" t\"\" w l lt 0,\\\n");
                   8119:        } /* state */
                   8120:       } /* vpopbased */
1.264     brouard  8121:       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  8122:     } /* end nres */
                   8123:   } /* k1 end 2 eme*/
                   8124:        
                   8125:        
                   8126:   /*3eme*/
                   8127:   for (k1=1; k1<= m ; k1 ++){
                   8128:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.253     brouard  8129:       if(m != 1 && TKresult[nres]!= k1)
1.238     brouard  8130:        continue;
                   8131: 
1.332     brouard  8132:       for (cpt=1; cpt<= nlstate ; cpt ++) { /* Fragile no verification of covariate values */
1.261     brouard  8133:        fprintf(ficgp,"\n\n# 3d: Life expectancy with EXP_ files:  combination=%d state=%d",k1, cpt);
1.264     brouard  8134:        strcpy(gplotlabel,"(");
1.238     brouard  8135:        for (k=1; k<=cptcoveff; k++){    /* For each covariate and each value */
1.332     brouard  8136:          /* lv= decodtabm(k1,k,cptcoveff); /\* Should be the covariate number corresponding to k1 combination *\/ */
                   8137:          lv= codtabm(k1,TnsdVar[Tvaraff[k]]); /* Should be the covariate value corresponding to combination k1 and covariate k */
1.238     brouard  8138:          /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   8139:          /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   8140:          /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
1.332     brouard  8141:          /* vlv= nbcode[Tvaraff[k]][lv]; */
                   8142:          vlv= nbcode[Tvaraff[k]][codtabm(k1,TnsdVar[Tvaraff[k]])];
1.238     brouard  8143:          fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv);
1.264     brouard  8144:          sprintf(gplotlabel+strlen(gplotlabel)," V%d=%d ",Tvaraff[k],vlv);
1.238     brouard  8145:        }
                   8146:        for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
1.332     brouard  8147:          fprintf(ficgp," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][resultmodel[nres][k4]]);
                   8148:          sprintf(gplotlabel+strlen(gplotlabel)," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][resultmodel[nres][k4]]);
1.238     brouard  8149:        }       
1.264     brouard  8150:        strcpy(gplotlabel+strlen(gplotlabel),")");
1.238     brouard  8151:        fprintf(ficgp,"\n#\n");
                   8152:        if(invalidvarcomb[k1]){
                   8153:          fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   8154:          continue;
                   8155:        }
                   8156:                        
                   8157:        /*       k=2+nlstate*(2*cpt-2); */
                   8158:        k=2+(nlstate+1)*(cpt-1);
1.241     brouard  8159:        fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" \n",subdirf2(optionfilefiname,"EXP_"),cpt,k1,nres);
1.264     brouard  8160:        fprintf(ficgp,"set label \"%s\" at graph 0.98,0.5 center rotate font \"Helvetica,12\"\n",gplotlabel);
1.238     brouard  8161:        fprintf(ficgp,"set ter svg size 640, 480\n\
1.261     brouard  8162: 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  8163:        /*fprintf(ficgp,",\"e%s\" every :::%d::%d u 1:($%d-2*$%d) \"\%%lf ",fileres,k1-1,k1-1,k,k+1);
                   8164:          for (i=1; i<= nlstate*2 ; i ++) fprintf(ficgp,"\%%lf (\%%lf) ");
                   8165:          fprintf(ficgp,"\" t \"e%d1\" w l",cpt);
                   8166:          fprintf(ficgp,",\"e%s\" every :::%d::%d u 1:($%d+2*$%d) \"\%%lf ",fileres,k1-1,k1-1,k,k+1);
                   8167:          for (i=1; i<= nlstate*2 ; i ++) fprintf(ficgp,"\%%lf (\%%lf) ");
                   8168:          fprintf(ficgp,"\" t \"e%d1\" w l",cpt);
1.219     brouard  8169:                                
1.238     brouard  8170:        */
                   8171:        for (i=1; i< nlstate ; i ++) {
1.261     brouard  8172:          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  8173:          /*    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  8174:                                
1.238     brouard  8175:        } 
1.261     brouard  8176:        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  8177:       }
1.264     brouard  8178:       fprintf(ficgp,"\nunset label;\n");
1.238     brouard  8179:     } /* end nres */
                   8180:   } /* end kl 3eme */
1.126     brouard  8181:   
1.223     brouard  8182:   /* 4eme */
1.201     brouard  8183:   /* Survival functions (period) from state i in state j by initial state i */
1.238     brouard  8184:   for (k1=1; k1<=m; k1++){    /* For each covariate and each value */
                   8185:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.253     brouard  8186:       if(m != 1 && TKresult[nres]!= k1)
1.223     brouard  8187:        continue;
1.238     brouard  8188:       for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each life state cpt*/
1.264     brouard  8189:        strcpy(gplotlabel,"(");
1.238     brouard  8190:        fprintf(ficgp,"\n#\n#\n# Survival functions in state j : 'LIJ_' files, cov=%d state=%d",k1, cpt);
                   8191:        for (k=1; k<=cptcoveff; k++){    /* For each covariate and each value */
1.332     brouard  8192:          lv=codtabm(k1,TnsdVar[Tvaraff[k]]);
                   8193:          /* lv= decodtabm(k1,k,cptcoveff); /\* Should be the covariate number corresponding to k1 combination *\/ */
1.238     brouard  8194:          /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   8195:          /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   8196:          /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
1.332     brouard  8197:          /* vlv= nbcode[Tvaraff[k]][lv]; */
                   8198:          vlv= nbcode[Tvaraff[k]][codtabm(k1,TnsdVar[Tvaraff[k]])];
1.238     brouard  8199:          fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv);
1.264     brouard  8200:          sprintf(gplotlabel+strlen(gplotlabel)," V%d=%d ",Tvaraff[k],vlv);
1.238     brouard  8201:        }
                   8202:        for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
1.332     brouard  8203:          fprintf(ficgp," V%d=%f ",Tvqresult[nres][resultmodel[nres][k4]],Tqresult[nres][resultmodel[nres][k4]]);
                   8204:          sprintf(gplotlabel+strlen(gplotlabel)," V%d=%f ",Tvqresult[nres][resultmodel[nres][k4]],Tqresult[nres][resultmodel[nres][k4]]);
1.238     brouard  8205:        }       
1.264     brouard  8206:        strcpy(gplotlabel+strlen(gplotlabel),")");
1.238     brouard  8207:        fprintf(ficgp,"\n#\n");
                   8208:        if(invalidvarcomb[k1]){
                   8209:          fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   8210:          continue;
1.223     brouard  8211:        }
1.238     brouard  8212:       
1.241     brouard  8213:        fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" \n",subdirf2(optionfilefiname,"LIJ_"),cpt,k1,nres);
1.264     brouard  8214:        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  8215:        fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Probability to be alive\" \n\
                   8216: set ter svg size 640, 480\nunset log y\nplot [%.f:%.f]  ", ageminpar, agemaxpar);
                   8217:        k=3;
                   8218:        for (i=1; i<= nlstate ; i ++){
                   8219:          if(i==1){
                   8220:            fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"PIJ_"));
                   8221:          }else{
                   8222:            fprintf(ficgp,", '' ");
                   8223:          }
                   8224:          l=(nlstate+ndeath)*(i-1)+1;
                   8225:          fprintf(ficgp," u ($1==%d ? ($3):1/0):($%d/($%d",k1,k+l+(cpt-1),k+l);
                   8226:          for (j=2; j<= nlstate+ndeath ; j ++)
                   8227:            fprintf(ficgp,"+$%d",k+l+j-1);
                   8228:          fprintf(ficgp,")) t \"l(%d,%d)\" w l",i,cpt);
                   8229:        } /* nlstate */
1.264     brouard  8230:        fprintf(ficgp,"\nset out; unset label;\n");
1.238     brouard  8231:       } /* end cpt state*/ 
                   8232:     } /* end nres */
                   8233:   } /* end covariate k1 */  
                   8234: 
1.220     brouard  8235: /* 5eme */
1.201     brouard  8236:   /* Survival functions (period) from state i in state j by final state j */
1.238     brouard  8237:   for (k1=1; k1<= m ; k1++){ /* For each covariate combination if any */
                   8238:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.253     brouard  8239:       if(m != 1 && TKresult[nres]!= k1)
1.227     brouard  8240:        continue;
1.238     brouard  8241:       for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each inital state  */
1.264     brouard  8242:        strcpy(gplotlabel,"(");
1.238     brouard  8243:        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);
                   8244:        for (k=1; k<=cptcoveff; k++){    /* For each covariate and each value */
1.332     brouard  8245:          lv=codtabm(k1,TnsdVar[Tvaraff[k]]);
                   8246:          /* lv= decodtabm(k1,k,cptcoveff); /\* Should be the covariate number corresponding to k1 combination *\/ */
1.238     brouard  8247:          /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   8248:          /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   8249:          /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
1.332     brouard  8250:          /* vlv= nbcode[Tvaraff[k]][lv]; */
                   8251:          vlv= nbcode[Tvaraff[k]][codtabm(k1,TnsdVar[Tvaraff[k]])];
1.238     brouard  8252:          fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv);
1.264     brouard  8253:          sprintf(gplotlabel+strlen(gplotlabel)," V%d=%d ",Tvaraff[k],vlv);
1.238     brouard  8254:        }
                   8255:        for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
1.332     brouard  8256:          fprintf(ficgp," V%d=%f ",Tvqresult[nres][resultmodel[nres][k4]],Tqresult[nres][resultmodel[nres][k4]]);
                   8257:          sprintf(gplotlabel+strlen(gplotlabel)," V%d=%f ",Tvqresult[nres][resultmodel[nres][k4]],Tqresult[nres][resultmodel[nres][k4]]);
1.238     brouard  8258:        }       
1.264     brouard  8259:        strcpy(gplotlabel+strlen(gplotlabel),")");
1.238     brouard  8260:        fprintf(ficgp,"\n#\n");
                   8261:        if(invalidvarcomb[k1]){
                   8262:          fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   8263:          continue;
                   8264:        }
1.227     brouard  8265:       
1.241     brouard  8266:        fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" \n",subdirf2(optionfilefiname,"LIJT_"),cpt,k1,nres);
1.264     brouard  8267:        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  8268:        fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Probability to be alive\" \n\
                   8269: set ter svg size 640, 480\nunset log y\nplot [%.f:%.f]  ", ageminpar, agemaxpar);
                   8270:        k=3;
                   8271:        for (j=1; j<= nlstate ; j ++){ /* Lived in state j */
                   8272:          if(j==1)
                   8273:            fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"PIJ_"));
                   8274:          else
                   8275:            fprintf(ficgp,", '' ");
                   8276:          l=(nlstate+ndeath)*(cpt-1) +j;
                   8277:          fprintf(ficgp," u (($1==%d && (floor($2)%%5 == 0)) ? ($3):1/0):($%d",k1,k+l);
                   8278:          /* for (i=2; i<= nlstate+ndeath ; i ++) */
                   8279:          /*   fprintf(ficgp,"+$%d",k+l+i-1); */
                   8280:          fprintf(ficgp,") t \"l(%d,%d)\" w l",cpt,j);
                   8281:        } /* nlstate */
                   8282:        fprintf(ficgp,", '' ");
                   8283:        fprintf(ficgp," u (($1==%d && (floor($2)%%5 == 0)) ? ($3):1/0):(",k1);
                   8284:        for (j=1; j<= nlstate ; j ++){ /* Lived in state j */
                   8285:          l=(nlstate+ndeath)*(cpt-1) +j;
                   8286:          if(j < nlstate)
                   8287:            fprintf(ficgp,"$%d +",k+l);
                   8288:          else
                   8289:            fprintf(ficgp,"$%d) t\"l(%d,.)\" w l",k+l,cpt);
                   8290:        }
1.264     brouard  8291:        fprintf(ficgp,"\nset out; unset label;\n");
1.238     brouard  8292:       } /* end cpt state*/ 
                   8293:     } /* end covariate */  
                   8294:   } /* end nres */
1.227     brouard  8295:   
1.220     brouard  8296: /* 6eme */
1.202     brouard  8297:   /* CV preval stable (period) for each covariate */
1.237     brouard  8298:   for (k1=1; k1<= m ; k1 ++) /* For each covariate combination if any */
                   8299:   for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.253     brouard  8300:     if(m != 1 && TKresult[nres]!= k1)
1.237     brouard  8301:       continue;
1.255     brouard  8302:     for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each life state of arrival */
1.264     brouard  8303:       strcpy(gplotlabel,"(");      
1.288     brouard  8304:       fprintf(ficgp,"\n#\n#\n#CV preval stable (forward): 'pij' files, covariatecombination#=%d state=%d",k1, cpt);
1.225     brouard  8305:       for (k=1; k<=cptcoveff; k++){    /* For each covariate and each value */
1.332     brouard  8306:        /* lv= decodtabm(k1,k,cptcoveff); /\* Should be the covariate number corresponding to k1 combination *\/ */
                   8307:        lv=codtabm(k1,TnsdVar[Tvaraff[k]]);
1.227     brouard  8308:        /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   8309:        /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   8310:        /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
1.332     brouard  8311:        /* vlv= nbcode[Tvaraff[k]][lv]; */
                   8312:        vlv= nbcode[Tvaraff[k]][codtabm(k1,TnsdVar[Tvaraff[k]])];
1.227     brouard  8313:        fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv);
1.264     brouard  8314:        sprintf(gplotlabel+strlen(gplotlabel)," V%d=%d ",Tvaraff[k],vlv);
1.211     brouard  8315:       }
1.237     brouard  8316:       for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
1.332     brouard  8317:        fprintf(ficgp," V%d=%f ",Tvqresult[nres][resultmodel[nres][k4]],Tqresult[nres][resultmodel[nres][k4]]);
                   8318:        sprintf(gplotlabel+strlen(gplotlabel)," V%d=%f ",Tvqresult[nres][resultmodel[nres][k4]],Tqresult[nres][resultmodel[nres][k4]]);
1.237     brouard  8319:       }        
1.264     brouard  8320:       strcpy(gplotlabel+strlen(gplotlabel),")");
1.211     brouard  8321:       fprintf(ficgp,"\n#\n");
1.223     brouard  8322:       if(invalidvarcomb[k1]){
1.227     brouard  8323:        fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   8324:        continue;
1.223     brouard  8325:       }
1.227     brouard  8326:       
1.241     brouard  8327:       fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" \n",subdirf2(optionfilefiname,"P_"),cpt,k1,nres);
1.264     brouard  8328:       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  8329:       fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Probability\" \n\
1.238     brouard  8330: set ter svg size 640, 480\nunset log y\nplot [%.f:%.f]  ", ageminpar, agemaxpar);
1.211     brouard  8331:       k=3; /* Offset */
1.255     brouard  8332:       for (i=1; i<= nlstate ; i ++){ /* State of origin */
1.227     brouard  8333:        if(i==1)
                   8334:          fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"PIJ_"));
                   8335:        else
                   8336:          fprintf(ficgp,", '' ");
1.255     brouard  8337:        l=(nlstate+ndeath)*(i-1)+1; /* 1, 1+ nlstate+ndeath, 1+2*(nlstate+ndeath) */
1.227     brouard  8338:        fprintf(ficgp," u ($1==%d ? ($3):1/0):($%d/($%d",k1,k+l+(cpt-1),k+l);
                   8339:        for (j=2; j<= nlstate ; j ++)
                   8340:          fprintf(ficgp,"+$%d",k+l+j-1);
                   8341:        fprintf(ficgp,")) t \"prev(%d,%d)\" w l",i,cpt);
1.153     brouard  8342:       } /* nlstate */
1.264     brouard  8343:       fprintf(ficgp,"\nset out; unset label;\n");
1.153     brouard  8344:     } /* end cpt state*/ 
                   8345:   } /* end covariate */  
1.227     brouard  8346:   
                   8347:   
1.220     brouard  8348: /* 7eme */
1.296     brouard  8349:   if(prevbcast == 1){
1.288     brouard  8350:     /* CV backward prevalence  for each covariate */
1.237     brouard  8351:     for (k1=1; k1<= m ; k1 ++) /* For each covariate combination if any */
                   8352:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.253     brouard  8353:       if(m != 1 && TKresult[nres]!= k1)
1.237     brouard  8354:        continue;
1.268     brouard  8355:       for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each life origin state */
1.264     brouard  8356:        strcpy(gplotlabel,"(");      
1.288     brouard  8357:        fprintf(ficgp,"\n#\n#\n#CV Backward stable prevalence: 'pijb' files, covariatecombination#=%d state=%d",k1, cpt);
1.227     brouard  8358:        for (k=1; k<=cptcoveff; k++){    /* For each covariate and each value */
1.332     brouard  8359:          /* lv= decodtabm(k1,k,cptcoveff); /\* Should be the covariate number corresponding to k1 combination *\/ */
                   8360:          lv=codtabm(k1,TnsdVar[Tvaraff[k]]);
1.227     brouard  8361:          /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   8362:          /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
1.223     brouard  8363:          /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
1.332     brouard  8364:          /* vlv= nbcode[Tvaraff[k]][lv]; */
                   8365:          vlv= nbcode[Tvaraff[k]][codtabm(k1,TnsdVar[Tvaraff[k]])];
1.227     brouard  8366:          fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv);
1.264     brouard  8367:          sprintf(gplotlabel+strlen(gplotlabel)," V%d=%d ",Tvaraff[k],vlv);
1.227     brouard  8368:        }
1.237     brouard  8369:        for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
1.332     brouard  8370:          fprintf(ficgp," V%d=%f ",Tvqresult[nres][resultmodel[nres][k4]],Tqresult[nres][resultmodel[nres][k4]]);
                   8371:          sprintf(gplotlabel+strlen(gplotlabel)," V%d=%f ",Tvqresult[nres][resultmodel[nres][k4]],Tqresult[nres][resultmodel[nres][k4]]);
1.237     brouard  8372:        }       
1.264     brouard  8373:        strcpy(gplotlabel+strlen(gplotlabel),")");
1.227     brouard  8374:        fprintf(ficgp,"\n#\n");
                   8375:        if(invalidvarcomb[k1]){
                   8376:          fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   8377:          continue;
                   8378:        }
                   8379:        
1.241     brouard  8380:        fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" \n",subdirf2(optionfilefiname,"PB_"),cpt,k1,nres);
1.268     brouard  8381:        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  8382:        fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Probability\" \n\
1.238     brouard  8383: set ter svg size 640, 480\nunset log y\nplot [%.f:%.f]  ", ageminpar, agemaxpar);
1.227     brouard  8384:        k=3; /* Offset */
1.268     brouard  8385:        for (i=1; i<= nlstate ; i ++){ /* State of arrival */
1.227     brouard  8386:          if(i==1)
                   8387:            fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"PIJB_"));
                   8388:          else
                   8389:            fprintf(ficgp,", '' ");
                   8390:          /* l=(nlstate+ndeath)*(i-1)+1; */
1.255     brouard  8391:          l=(nlstate+ndeath)*(cpt-1)+1; /* fixed for i; cpt=1 1, cpt=2 1+ nlstate+ndeath, 1+2*(nlstate+ndeath) */
1.324     brouard  8392:          /* fprintf(ficgp," u ($1==%d ? ($3):1/0):($%d/($%d",k1,k+l+(cpt-1),k+l); /\* a vérifier *\/ */
                   8393:          /* 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  8394:          fprintf(ficgp," u ($1==%d ? ($3):1/0):($%d",k1,k+l+i-1); /* To be verified */
1.227     brouard  8395:          /* for (j=2; j<= nlstate ; j ++) */
                   8396:          /*    fprintf(ficgp,"+$%d",k+l+j-1); */
                   8397:          /*    /\* fprintf(ficgp,"+$%d",k+l+j-1); *\/ */
1.268     brouard  8398:          fprintf(ficgp,") t \"bprev(%d,%d)\" w l",cpt,i);
1.227     brouard  8399:        } /* nlstate */
1.264     brouard  8400:        fprintf(ficgp,"\nset out; unset label;\n");
1.218     brouard  8401:       } /* end cpt state*/ 
                   8402:     } /* end covariate */  
1.296     brouard  8403:   } /* End if prevbcast */
1.218     brouard  8404:   
1.223     brouard  8405:   /* 8eme */
1.218     brouard  8406:   if(prevfcast==1){
1.288     brouard  8407:     /* Projection from cross-sectional to forward stable (period) prevalence for each covariate */
1.218     brouard  8408:     
1.237     brouard  8409:     for (k1=1; k1<= m ; k1 ++) /* For each covariate combination if any */
                   8410:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.253     brouard  8411:       if(m != 1 && TKresult[nres]!= k1)
1.237     brouard  8412:        continue;
1.211     brouard  8413:       for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each life state */
1.264     brouard  8414:        strcpy(gplotlabel,"(");      
1.288     brouard  8415:        fprintf(ficgp,"\n#\n#\n#Projection of prevalence to forward stable prevalence (period): 'PROJ_' files, covariatecombination#=%d state=%d",k1, cpt);
1.227     brouard  8416:        for (k=1; k<=cptcoveff; k++){    /* For each correspondig covariate value  */
1.332     brouard  8417:          /* lv= decodtabm(k1,k,cptcoveff); /\* Should be the covariate value corresponding to k1 combination and kth covariate *\/ */
                   8418:          lv=codtabm(k1,TnsdVar[Tvaraff[k]]);
1.227     brouard  8419:          /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   8420:          /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   8421:          /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
1.332     brouard  8422:          /* vlv= nbcode[Tvaraff[k]][lv]; */
                   8423:          vlv= nbcode[Tvaraff[k]][codtabm(k1,TnsdVar[Tvaraff[k]])];
1.227     brouard  8424:          fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv);
1.264     brouard  8425:          sprintf(gplotlabel+strlen(gplotlabel)," V%d=%d ",Tvaraff[k],vlv);
1.227     brouard  8426:        }
1.237     brouard  8427:        for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
1.332     brouard  8428:          fprintf(ficgp," V%d=%f ",Tvqresult[nres][resultmodel[nres][k4]],Tqresult[nres][resultmodel[nres][k4]]);
                   8429:          sprintf(gplotlabel+strlen(gplotlabel)," V%d=%f ",Tvqresult[nres][resultmodel[nres][k4]],Tqresult[nres][resultmodel[nres][k4]]);
1.237     brouard  8430:        }       
1.264     brouard  8431:        strcpy(gplotlabel+strlen(gplotlabel),")");
1.227     brouard  8432:        fprintf(ficgp,"\n#\n");
                   8433:        if(invalidvarcomb[k1]){
                   8434:          fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   8435:          continue;
                   8436:        }
                   8437:        
                   8438:        fprintf(ficgp,"# hpijx=probability over h years, hp.jx is weighted by observed prev\n ");
1.241     brouard  8439:        fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" \n",subdirf2(optionfilefiname,"PROJ_"),cpt,k1,nres);
1.264     brouard  8440:        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  8441:        fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Prevalence\" \n\
1.238     brouard  8442: set ter svg size 640, 480\nunset log y\nplot [%.f:%.f]  ", ageminpar, agemaxpar);
1.266     brouard  8443: 
                   8444:        /* for (i=1; i<= nlstate+1 ; i ++){  /\* nlstate +1 p11 p21 p.1 *\/ */
                   8445:        istart=nlstate+1; /* Could be one if by state, but nlstate+1 is w.i projection only */
                   8446:        /*istart=1;*/ /* Could be one if by state, but nlstate+1 is w.i projection only */
                   8447:        for (i=istart; i<= nlstate+1 ; i ++){  /* nlstate +1 p11 p21 p.1 */
1.227     brouard  8448:          /*#  V1  = 1  V2 =  0 yearproj age p11 p21 p.1 p12 p22 p.2 p13 p23 p.3*/
                   8449:          /*#   1    2   3    4    5      6  7   8   9   10   11 12  13   14  15 */   
                   8450:          /*# yearproj age p11 p21 p.1 p12 p22 p.2 p13 p23 p.3*/
                   8451:          /*#   1       2   3    4    5      6  7   8   9   10   11 12  13   14  15 */   
1.266     brouard  8452:          if(i==istart){
1.227     brouard  8453:            fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"F_"));
                   8454:          }else{
                   8455:            fprintf(ficgp,",\\\n '' ");
                   8456:          }
                   8457:          if(cptcoveff ==0){ /* No covariate */
                   8458:            ioffset=2; /* Age is in 2 */
                   8459:            /*# yearproj age p11 p21 p31 p.1 p12 p22 p32 p.2 p13 p23 p33 p.3 p14 p24 p34 p.4*/
                   8460:            /*#   1       2   3   4   5  6    7  8   9   10  11  12  13  14  15  16  17  18 */
                   8461:            /*# V1  = 1 yearproj age p11 p21 p31 p.1 p12 p22 p32 p.2 p13 p23 p33 p.3 p14 p24 p34 p.4*/
                   8462:            /*#  1    2        3   4   5  6    7  8   9   10  11  12  13  14  15  16  17  18 */
                   8463:            fprintf(ficgp," u %d:(", ioffset); 
1.266     brouard  8464:            if(i==nlstate+1){
1.270     brouard  8465:              fprintf(ficgp," $%d/(1.-$%d)):1 t 'pw.%d' with line lc variable ",        \
1.266     brouard  8466:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1),  ioffset+1+(i-1)+(nlstate+1)*nlstate,cpt );
                   8467:              fprintf(ficgp,",\\\n '' ");
                   8468:              fprintf(ficgp," u %d:(",ioffset); 
1.270     brouard  8469:              fprintf(ficgp," (($1-$2) == %d ) ? $%d/(1.-$%d) : 1/0):1 with labels center not ", \
1.266     brouard  8470:                     offyear,                           \
1.268     brouard  8471:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1),  ioffset+1+(i-1)+(nlstate+1)*nlstate );
1.266     brouard  8472:            }else
1.227     brouard  8473:              fprintf(ficgp," $%d/(1.-$%d)) t 'p%d%d' with line ",      \
                   8474:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1),  ioffset+1+(i-1)+(nlstate+1)*nlstate,i,cpt );
                   8475:          }else{ /* more than 2 covariates */
1.270     brouard  8476:            ioffset=2*cptcoveff+2; /* Age is in 4 or 6 or etc.*/
                   8477:            /*#  V1  = 1  V2 =  0 yearproj age p11 p21 p.1 p12 p22 p.2 p13 p23 p.3*/
                   8478:            /*#   1    2   3    4    5      6  7   8   9   10   11 12  13   14  15 */
                   8479:            iyearc=ioffset-1;
                   8480:            iagec=ioffset;
1.227     brouard  8481:            fprintf(ficgp," u %d:(",ioffset); 
                   8482:            kl=0;
                   8483:            strcpy(gplotcondition,"(");
                   8484:            for (k=1; k<=cptcoveff; k++){    /* For each covariate writing the chain of conditions */
1.332     brouard  8485:              /* lv= decodtabm(k1,k,cptcoveff); /\* Should be the covariate value corresponding to combination k1 and covariate k *\/ */
                   8486:              lv=codtabm(k1,TnsdVar[Tvaraff[k]]);
1.227     brouard  8487:              /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   8488:              /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   8489:              /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
1.332     brouard  8490:              /* vlv= nbcode[Tvaraff[k]][lv]; /\* Value of the modality of Tvaraff[k] *\/ */
                   8491:              vlv= nbcode[Tvaraff[k]][codtabm(k1,TnsdVar[Tvaraff[k]])];
1.227     brouard  8492:              kl++;
                   8493:              sprintf(gplotcondition+strlen(gplotcondition),"$%d==%d && $%d==%d " ,kl,Tvaraff[k], kl+1, nbcode[Tvaraff[k]][lv]);
                   8494:              kl++;
                   8495:              if(k <cptcoveff && cptcoveff>1)
                   8496:                sprintf(gplotcondition+strlen(gplotcondition)," && ");
                   8497:            }
                   8498:            strcpy(gplotcondition+strlen(gplotcondition),")");
                   8499:            /* 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 *\/ */
                   8500:            /*6+(cpt-1)*(nlstate+1)+1+(i-1)+(nlstate+1)*nlstate; 6+(1-1)*(2+1)+1+(1-1) +(2+1)*2=13 */ 
                   8501:            /*6+1+(i-1)+(nlstate+1)*nlstate; 6+1+(1-1) +(2+1)*2=13 */ 
                   8502:            /* ''  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*/
                   8503:            if(i==nlstate+1){
1.270     brouard  8504:              fprintf(ficgp,"%s ? $%d/(1.-$%d) : 1/0):%d t 'p.%d' with line lc variable", gplotcondition, \
                   8505:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1),  ioffset+1+(i-1)+(nlstate+1)*nlstate,iyearc, cpt );
1.266     brouard  8506:              fprintf(ficgp,",\\\n '' ");
1.270     brouard  8507:              fprintf(ficgp," u %d:(",iagec); 
                   8508:              fprintf(ficgp,"%s && (($%d-$%d) == %d ) ? $%d/(1.-$%d) : 1/0):%d with labels center not ", gplotcondition, \
                   8509:                      iyearc, iagec, offyear,                           \
                   8510:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1),  ioffset+1+(i-1)+(nlstate+1)*nlstate, iyearc );
1.266     brouard  8511: /*  '' 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  8512:            }else{
                   8513:              fprintf(ficgp,"%s ? $%d/(1.-$%d) : 1/0) t 'p%d%d' with line ", gplotcondition, \
                   8514:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1), ioffset +1+(i-1)+(nlstate+1)*nlstate,i,cpt );
                   8515:            }
                   8516:          } /* end if covariate */
                   8517:        } /* nlstate */
1.264     brouard  8518:        fprintf(ficgp,"\nset out; unset label;\n");
1.223     brouard  8519:       } /* end cpt state*/
                   8520:     } /* end covariate */
                   8521:   } /* End if prevfcast */
1.227     brouard  8522:   
1.296     brouard  8523:   if(prevbcast==1){
1.268     brouard  8524:     /* Back projection from cross-sectional to stable (mixed) for each covariate */
                   8525:     
                   8526:     for (k1=1; k1<= m ; k1 ++) /* For each covariate combination if any */
                   8527:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
                   8528:       if(m != 1 && TKresult[nres]!= k1)
                   8529:        continue;
                   8530:       for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each life state */
                   8531:        strcpy(gplotlabel,"(");      
                   8532:        fprintf(ficgp,"\n#\n#\n#Back projection of prevalence to stable (mixed) back prevalence: 'BPROJ_' files, covariatecombination#=%d originstate=%d",k1, cpt);
                   8533:        for (k=1; k<=cptcoveff; k++){    /* For each correspondig covariate value  */
1.332     brouard  8534:          /* lv= decodtabm(k1,k,cptcoveff); /\* Should be the covariate value corresponding to k1 combination and kth covariate *\/ */
                   8535:          lv= codtabm(k1,TnsdVar[Tvaraff[k]]); /* Should be the covariate value corresponding to combination k1 and covariate k */
1.268     brouard  8536:          /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   8537:          /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   8538:          /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
1.332     brouard  8539:          /* vlv= nbcode[Tvaraff[k]][lv]; */
                   8540:          vlv= nbcode[Tvaraff[k]][codtabm(k1,TnsdVar[Tvaraff[k]])];
1.268     brouard  8541:          fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv);
                   8542:          sprintf(gplotlabel+strlen(gplotlabel)," V%d=%d ",Tvaraff[k],vlv);
                   8543:        }
                   8544:        for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
1.332     brouard  8545:          fprintf(ficgp," V%d=%f ",Tvqresult[nres][resultmodel[nres][k4]],Tqresult[nres][resultmodel[nres][k4]]);
                   8546:          sprintf(gplotlabel+strlen(gplotlabel)," V%d=%f ",Tvqresult[nres][resultmodel[nres][k4]],Tqresult[nres][resultmodel[nres][k4]]);
1.268     brouard  8547:        }       
                   8548:        strcpy(gplotlabel+strlen(gplotlabel),")");
                   8549:        fprintf(ficgp,"\n#\n");
                   8550:        if(invalidvarcomb[k1]){
                   8551:          fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   8552:          continue;
                   8553:        }
                   8554:        
                   8555:        fprintf(ficgp,"# hbijx=backprobability over h years, hb.jx is weighted by observed prev at destination state\n ");
                   8556:        fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" \n",subdirf2(optionfilefiname,"PROJB_"),cpt,k1,nres);
                   8557:        fprintf(ficgp,"set label \"Origin alive state %d %s\" at graph 0.98,0.5 center rotate font \"Helvetica,12\"\n",cpt,gplotlabel);
                   8558:        fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Prevalence\" \n\
                   8559: set ter svg size 640, 480\nunset log y\nplot [%.f:%.f]  ", ageminpar, agemaxpar);
                   8560: 
                   8561:        /* for (i=1; i<= nlstate+1 ; i ++){  /\* nlstate +1 p11 p21 p.1 *\/ */
                   8562:        istart=nlstate+1; /* Could be one if by state, but nlstate+1 is w.i projection only */
                   8563:        /*istart=1;*/ /* Could be one if by state, but nlstate+1 is w.i projection only */
                   8564:        for (i=istart; i<= nlstate+1 ; i ++){  /* nlstate +1 p11 p21 p.1 */
                   8565:          /*#  V1  = 1  V2 =  0 yearproj age p11 p21 p.1 p12 p22 p.2 p13 p23 p.3*/
                   8566:          /*#   1    2   3    4    5      6  7   8   9   10   11 12  13   14  15 */   
                   8567:          /*# yearproj age p11 p21 p.1 p12 p22 p.2 p13 p23 p.3*/
                   8568:          /*#   1       2   3    4    5      6  7   8   9   10   11 12  13   14  15 */   
                   8569:          if(i==istart){
                   8570:            fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"FB_"));
                   8571:          }else{
                   8572:            fprintf(ficgp,",\\\n '' ");
                   8573:          }
                   8574:          if(cptcoveff ==0){ /* No covariate */
                   8575:            ioffset=2; /* Age is in 2 */
                   8576:            /*# yearproj age p11 p21 p31 p.1 p12 p22 p32 p.2 p13 p23 p33 p.3 p14 p24 p34 p.4*/
                   8577:            /*#   1       2   3   4   5  6    7  8   9   10  11  12  13  14  15  16  17  18 */
                   8578:            /*# V1  = 1 yearproj age p11 p21 p31 p.1 p12 p22 p32 p.2 p13 p23 p33 p.3 p14 p24 p34 p.4*/
                   8579:            /*#  1    2        3   4   5  6    7  8   9   10  11  12  13  14  15  16  17  18 */
                   8580:            fprintf(ficgp," u %d:(", ioffset); 
                   8581:            if(i==nlstate+1){
1.270     brouard  8582:              fprintf(ficgp," $%d/(1.-$%d)):1 t 'bw%d' with line lc variable ", \
1.268     brouard  8583:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1),  ioffset+1+(i-1)+(nlstate+1)*nlstate,cpt );
                   8584:              fprintf(ficgp,",\\\n '' ");
                   8585:              fprintf(ficgp," u %d:(",ioffset); 
1.270     brouard  8586:              fprintf(ficgp," (($1-$2) == %d ) ? $%d : 1/0):1 with labels center not ", \
1.268     brouard  8587:                     offbyear,                          \
                   8588:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1) );
                   8589:            }else
                   8590:              fprintf(ficgp," $%d/(1.-$%d)) t 'b%d%d' with line ",      \
                   8591:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1),  ioffset+1+(i-1)+(nlstate+1)*nlstate,cpt,i );
                   8592:          }else{ /* more than 2 covariates */
1.270     brouard  8593:            ioffset=2*cptcoveff+2; /* Age is in 4 or 6 or etc.*/
                   8594:            /*#  V1  = 1  V2 =  0 yearproj age p11 p21 p.1 p12 p22 p.2 p13 p23 p.3*/
                   8595:            /*#   1    2   3    4    5      6  7   8   9   10   11 12  13   14  15 */
                   8596:            iyearc=ioffset-1;
                   8597:            iagec=ioffset;
1.268     brouard  8598:            fprintf(ficgp," u %d:(",ioffset); 
                   8599:            kl=0;
                   8600:            strcpy(gplotcondition,"(");
                   8601:            for (k=1; k<=cptcoveff; k++){    /* For each covariate writing the chain of conditions */
1.332     brouard  8602:              /* lv= decodtabm(k1,k,cptcoveff); /\* Should be the covariate value corresponding to combination k1 and covariate k *\/ */
                   8603:              lv= codtabm(k1,TnsdVar[Tvaraff[k]]); /* Should be the covariate value corresponding to combination k1 and covariate k */
1.268     brouard  8604:              /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   8605:              /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   8606:              /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
1.332     brouard  8607:              /* vlv= nbcode[Tvaraff[k]][lv]; /\* Value of the modality of Tvaraff[k] *\/ */
                   8608:              vlv= nbcode[Tvaraff[k]][codtabm(k1,TnsdVar[Tvaraff[k]])];
1.268     brouard  8609:              kl++;
                   8610:              sprintf(gplotcondition+strlen(gplotcondition),"$%d==%d && $%d==%d " ,kl,Tvaraff[k], kl+1, nbcode[Tvaraff[k]][lv]);
                   8611:              kl++;
                   8612:              if(k <cptcoveff && cptcoveff>1)
                   8613:                sprintf(gplotcondition+strlen(gplotcondition)," && ");
                   8614:            }
                   8615:            strcpy(gplotcondition+strlen(gplotcondition),")");
                   8616:            /* 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 *\/ */
                   8617:            /*6+(cpt-1)*(nlstate+1)+1+(i-1)+(nlstate+1)*nlstate; 6+(1-1)*(2+1)+1+(1-1) +(2+1)*2=13 */ 
                   8618:            /*6+1+(i-1)+(nlstate+1)*nlstate; 6+1+(1-1) +(2+1)*2=13 */ 
                   8619:            /* ''  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*/
                   8620:            if(i==nlstate+1){
1.270     brouard  8621:              fprintf(ficgp,"%s ? $%d : 1/0):%d t 'bw%d' with line lc variable", gplotcondition, \
                   8622:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1),iyearc,cpt );
1.268     brouard  8623:              fprintf(ficgp,",\\\n '' ");
1.270     brouard  8624:              fprintf(ficgp," u %d:(",iagec); 
1.268     brouard  8625:              /* fprintf(ficgp,"%s && (($5-$6) == %d ) ? $%d/(1.-$%d) : 1/0):5 with labels center not ", gplotcondition, \ */
1.270     brouard  8626:              fprintf(ficgp,"%s && (($%d-$%d) == %d ) ? $%d : 1/0):%d with labels center not ", gplotcondition, \
                   8627:                      iyearc,iagec,offbyear,                            \
                   8628:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1), iyearc );
1.268     brouard  8629: /*  '' u 6:(($1==1 && $2==0  && $3==2 && $4==0) && (($5-$6) == 1947) ? $10/(1.-$22) : 1/0):5 with labels center boxed not*/
                   8630:            }else{
                   8631:              /* fprintf(ficgp,"%s ? $%d/(1.-$%d) : 1/0) t 'p%d%d' with line ", gplotcondition, \ */
                   8632:              fprintf(ficgp,"%s ? $%d : 1/0) t 'b%d%d' with line ", gplotcondition, \
                   8633:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1), cpt,i );
                   8634:            }
                   8635:          } /* end if covariate */
                   8636:        } /* nlstate */
                   8637:        fprintf(ficgp,"\nset out; unset label;\n");
                   8638:       } /* end cpt state*/
                   8639:     } /* end covariate */
1.296     brouard  8640:   } /* End if prevbcast */
1.268     brouard  8641:   
1.227     brouard  8642:   
1.238     brouard  8643:   /* 9eme writing MLE parameters */
                   8644:   fprintf(ficgp,"\n##############\n#9eme MLE estimated parameters\n#############\n");
1.126     brouard  8645:   for(i=1,jk=1; i <=nlstate; i++){
1.187     brouard  8646:     fprintf(ficgp,"# initial state %d\n",i);
1.126     brouard  8647:     for(k=1; k <=(nlstate+ndeath); k++){
                   8648:       if (k != i) {
1.227     brouard  8649:        fprintf(ficgp,"#   current state %d\n",k);
                   8650:        for(j=1; j <=ncovmodel; j++){
                   8651:          fprintf(ficgp,"p%d=%f; ",jk,p[jk]);
                   8652:          jk++; 
                   8653:        }
                   8654:        fprintf(ficgp,"\n");
1.126     brouard  8655:       }
                   8656:     }
1.223     brouard  8657:   }
1.187     brouard  8658:   fprintf(ficgp,"##############\n#\n");
1.227     brouard  8659:   
1.145     brouard  8660:   /*goto avoid;*/
1.238     brouard  8661:   /* 10eme Graphics of probabilities or incidences using written MLE parameters */
                   8662:   fprintf(ficgp,"\n##############\n#10eme Graphics of probabilities or incidences\n#############\n");
1.187     brouard  8663:   fprintf(ficgp,"# logi(p12/p11)=a12+b12*age+c12age*age+d12*V1+e12*V1*age\n");
                   8664:   fprintf(ficgp,"# logi(p12/p11)=p1 +p2*age +p3*age*age+ p4*V1+ p5*V1*age\n");
                   8665:   fprintf(ficgp,"# logi(p13/p11)=a13+b13*age+c13age*age+d13*V1+e13*V1*age\n");
                   8666:   fprintf(ficgp,"# logi(p13/p11)=p6 +p7*age +p8*age*age+ p9*V1+ p10*V1*age\n");
                   8667:   fprintf(ficgp,"# p12+p13+p14+p11=1=p11(1+exp(a12+b12*age+c12age*age+d12*V1+e12*V1*age)\n");
                   8668:   fprintf(ficgp,"#                      +exp(a13+b13*age+c13age*age+d13*V1+e13*V1*age)+...)\n");
                   8669:   fprintf(ficgp,"# p11=1/(1+exp(a12+b12*age+c12age*age+d12*V1+e12*V1*age)\n");
                   8670:   fprintf(ficgp,"#                      +exp(a13+b13*age+c13age*age+d13*V1+e13*V1*age)+...)\n");
                   8671:   fprintf(ficgp,"# p12=exp(a12+b12*age+c12age*age+d12*V1+e12*V1*age)/\n");
                   8672:   fprintf(ficgp,"#     (1+exp(a12+b12*age+c12age*age+d12*V1+e12*V1*age)\n");
                   8673:   fprintf(ficgp,"#       +exp(a13+b13*age+c13age*age+d13*V1+e13*V1*age))\n");
                   8674:   fprintf(ficgp,"#       +exp(a14+b14*age+c14age*age+d14*V1+e14*V1*age)+...)\n");
                   8675:   fprintf(ficgp,"#\n");
1.223     brouard  8676:   for(ng=1; ng<=3;ng++){ /* Number of graphics: first is logit, 2nd is probabilities, third is incidences per year*/
1.238     brouard  8677:     fprintf(ficgp,"#Number of graphics: first is logit, 2nd is probabilities, third is incidences per year\n");
1.237     brouard  8678:     fprintf(ficgp,"#model=%s \n",model);
1.238     brouard  8679:     fprintf(ficgp,"# Type of graphic ng=%d\n",ng);
1.264     brouard  8680:     fprintf(ficgp,"#   k1=1 to 2^%d=%d\n",cptcoveff,m);/* to be checked */
                   8681:     for(k1=1; k1 <=m; k1++)  /* For each combination of covariate */
1.237     brouard  8682:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.264     brouard  8683:       if(m != 1 && TKresult[nres]!= k1)
1.237     brouard  8684:        continue;
1.264     brouard  8685:       fprintf(ficgp,"\n\n# Combination of dummy  k1=%d which is ",k1);
                   8686:       strcpy(gplotlabel,"(");
1.276     brouard  8687:       /*sprintf(gplotlabel+strlen(gplotlabel)," Dummy combination %d ",k1);*/
1.264     brouard  8688:       for (k=1; k<=cptcoveff; k++){    /* For each correspondig covariate value  */
1.332     brouard  8689:        /* lv= decodtabm(k1,k,cptcoveff); /\* Should be the covariate value corresponding to k1 combination and kth covariate *\/ */
                   8690:        lv= codtabm(k1,TnsdVar[Tvaraff[k]]); /* Should be the covariate value corresponding to combination k1 and covariate k */
1.264     brouard  8691:        /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   8692:        /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   8693:        /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
1.332     brouard  8694:        /* vlv= nbcode[Tvaraff[k]][lv]; */
                   8695:        vlv= nbcode[Tvaraff[k]][codtabm(k1,TnsdVar[Tvaraff[k]])];
1.264     brouard  8696:        fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv);
                   8697:        sprintf(gplotlabel+strlen(gplotlabel)," V%d=%d ",Tvaraff[k],vlv);
                   8698:       }
1.237     brouard  8699:       for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
1.332     brouard  8700:        fprintf(ficgp," V%d=%f ",Tvqresult[nres][resultmodel[nres][k4]],Tqresult[nres][resultmodel[nres][k4]]);
                   8701:        sprintf(gplotlabel+strlen(gplotlabel)," V%d=%f ",Tvqresult[nres][resultmodel[nres][k4]],Tqresult[nres][resultmodel[nres][k4]]);
1.237     brouard  8702:       }        
1.264     brouard  8703:       strcpy(gplotlabel+strlen(gplotlabel),")");
1.237     brouard  8704:       fprintf(ficgp,"\n#\n");
1.264     brouard  8705:       fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" ",subdirf2(optionfilefiname,"PE_"),k1,ng,nres);
1.276     brouard  8706:       fprintf(ficgp,"\nset key outside ");
                   8707:       /* fprintf(ficgp,"\nset label \"%s\" at graph 1.2,0.5 center rotate font \"Helvetica,12\"\n",gplotlabel); */
                   8708:       fprintf(ficgp,"\nset title \"%s\" font \"Helvetica,12\"\n",gplotlabel);
1.223     brouard  8709:       fprintf(ficgp,"\nset ter svg size 640, 480 ");
                   8710:       if (ng==1){
                   8711:        fprintf(ficgp,"\nset ylabel \"Value of the logit of the model\"\n"); /* exp(a12+b12*x) could be nice */
                   8712:        fprintf(ficgp,"\nunset log y");
                   8713:       }else if (ng==2){
                   8714:        fprintf(ficgp,"\nset ylabel \"Probability\"\n");
                   8715:        fprintf(ficgp,"\nset log y");
                   8716:       }else if (ng==3){
                   8717:        fprintf(ficgp,"\nset ylabel \"Quasi-incidence per year\"\n");
                   8718:        fprintf(ficgp,"\nset log y");
                   8719:       }else
                   8720:        fprintf(ficgp,"\nunset title ");
                   8721:       fprintf(ficgp,"\nplot  [%.f:%.f] ",ageminpar,agemaxpar);
                   8722:       i=1;
                   8723:       for(k2=1; k2<=nlstate; k2++) {
                   8724:        k3=i;
                   8725:        for(k=1; k<=(nlstate+ndeath); k++) {
                   8726:          if (k != k2){
                   8727:            switch( ng) {
                   8728:            case 1:
                   8729:              if(nagesqr==0)
                   8730:                fprintf(ficgp," p%d+p%d*x",i,i+1);
                   8731:              else /* nagesqr =1 */
                   8732:                fprintf(ficgp," p%d+p%d*x+p%d*x*x",i,i+1,i+1+nagesqr);
                   8733:              break;
                   8734:            case 2: /* ng=2 */
                   8735:              if(nagesqr==0)
                   8736:                fprintf(ficgp," exp(p%d+p%d*x",i,i+1);
                   8737:              else /* nagesqr =1 */
                   8738:                fprintf(ficgp," exp(p%d+p%d*x+p%d*x*x",i,i+1,i+1+nagesqr);
                   8739:              break;
                   8740:            case 3:
                   8741:              if(nagesqr==0)
                   8742:                fprintf(ficgp," %f*exp(p%d+p%d*x",YEARM/stepm,i,i+1);
                   8743:              else /* nagesqr =1 */
                   8744:                fprintf(ficgp," %f*exp(p%d+p%d*x+p%d*x*x",YEARM/stepm,i,i+1,i+1+nagesqr);
                   8745:              break;
                   8746:            }
                   8747:            ij=1;/* To be checked else nbcode[0][0] wrong */
1.237     brouard  8748:            ijp=1; /* product no age */
                   8749:            /* for(j=3; j <=ncovmodel-nagesqr; j++) { */
                   8750:            for(j=1; j <=cptcovt; j++) { /* For each covariate of the simplified model */
1.223     brouard  8751:              /* printf("Tage[%d]=%d, j=%d\n", ij, Tage[ij], j); */
1.329     brouard  8752:              switch(Typevar[j]){
                   8753:              case 1:
                   8754:                if(cptcovage >0){ /* V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1, 2 V5 and V1 */
                   8755:                  if(j==Tage[ij]) { /* Product by age  To be looked at!!*//* Bug valgrind */
                   8756:                    if(ij <=cptcovage) { /* V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1, 2 V5 and V1 */
                   8757:                      if(DummyV[j]==0){/* Bug valgrind */
                   8758:                        fprintf(ficgp,"+p%d*%d*x",i+j+2+nagesqr-1,Tinvresult[nres][Tvar[j]]);;
                   8759:                      }else{ /* quantitative */
                   8760:                        fprintf(ficgp,"+p%d*%f*x",i+j+2+nagesqr-1,Tqinvresult[nres][Tvar[j]]); /* Tqinvresult in decoderesult */
                   8761:                        /* fprintf(ficgp,"+p%d*%d*x",i+j+nagesqr-1,nbcode[Tvar[j-2]][codtabm(k1,Tvar[j-2])]); */
                   8762:                      }
                   8763:                      ij++;
1.268     brouard  8764:                    }
1.237     brouard  8765:                  }
1.329     brouard  8766:                }
                   8767:                break;
                   8768:              case 2:
                   8769:                if(cptcovprod >0){
                   8770:                  if(j==Tprod[ijp]) { /* */ 
                   8771:                    /* printf("Tprod[%d]=%d, j=%d\n", ij, Tprod[ijp], j); */
                   8772:                    if(ijp <=cptcovprod) { /* Product */
                   8773:                      if(DummyV[Tvard[ijp][1]]==0){/* Vn is dummy */
                   8774:                        if(DummyV[Tvard[ijp][2]]==0){/* Vn and Vm are dummy */
                   8775:                          /* 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)]); */
                   8776:                          fprintf(ficgp,"+p%d*%d*%d",i+j+2+nagesqr-1,Tinvresult[nres][Tvard[ijp][1]],Tinvresult[nres][Tvard[ijp][2]]);
                   8777:                        }else{ /* Vn is dummy and Vm is quanti */
                   8778:                          /* fprintf(ficgp,"+p%d*%d*%f",i+j+2+nagesqr-1,nbcode[Tvard[ijp][1]][codtabm(k1,j)],Tqinvresult[nres][Tvard[ijp][2]]); */
                   8779:                          fprintf(ficgp,"+p%d*%d*%f",i+j+2+nagesqr-1,Tinvresult[nres][Tvard[ijp][1]],Tqinvresult[nres][Tvard[ijp][2]]);
                   8780:                        }
                   8781:                      }else{ /* Vn*Vm Vn is quanti */
                   8782:                        if(DummyV[Tvard[ijp][2]]==0){
                   8783:                          fprintf(ficgp,"+p%d*%d*%f",i+j+2+nagesqr-1,Tinvresult[nres][Tvard[ijp][2]],Tqinvresult[nres][Tvard[ijp][1]]);
                   8784:                        }else{ /* Both quanti */
                   8785:                          fprintf(ficgp,"+p%d*%f*%f",i+j+2+nagesqr-1,Tqinvresult[nres][Tvard[ijp][1]],Tqinvresult[nres][Tvard[ijp][2]]);
                   8786:                        }
1.268     brouard  8787:                      }
1.329     brouard  8788:                      ijp++;
1.237     brouard  8789:                    }
1.329     brouard  8790:                  } /* end Tprod */
                   8791:                }
                   8792:                break;
                   8793:              case 0:
                   8794:                /* simple covariate */
1.264     brouard  8795:                /* fprintf(ficgp,"+p%d*%d",i+j+2+nagesqr-1,nbcode[Tvar[j]][codtabm(k1,j)]); /\* Valgrind bug nbcode *\/ */
1.237     brouard  8796:                if(Dummy[j]==0){
                   8797:                  fprintf(ficgp,"+p%d*%d",i+j+2+nagesqr-1,Tinvresult[nres][Tvar[j]]); /*  */
                   8798:                }else{ /* quantitative */
                   8799:                  fprintf(ficgp,"+p%d*%f",i+j+2+nagesqr-1,Tqinvresult[nres][Tvar[j]]); /* */
1.264     brouard  8800:                  /* fprintf(ficgp,"+p%d*%d*x",i+j+nagesqr-1,nbcode[Tvar[j-2]][codtabm(k1,Tvar[j-2])]); */
1.223     brouard  8801:                }
1.329     brouard  8802:               /* end simple */
                   8803:                break;
                   8804:              default:
                   8805:                break;
                   8806:              } /* end switch */
1.237     brouard  8807:            } /* end j */
1.329     brouard  8808:          }else{ /* k=k2 */
                   8809:            if(ng !=1 ){ /* For logit formula of log p11 is more difficult to get */
                   8810:              fprintf(ficgp," (1.");i=i-ncovmodel;
                   8811:            }else
                   8812:              i=i-ncovmodel;
1.223     brouard  8813:          }
1.227     brouard  8814:          
1.223     brouard  8815:          if(ng != 1){
                   8816:            fprintf(ficgp,")/(1");
1.227     brouard  8817:            
1.264     brouard  8818:            for(cpt=1; cpt <=nlstate; cpt++){ 
1.223     brouard  8819:              if(nagesqr==0)
1.264     brouard  8820:                fprintf(ficgp,"+exp(p%d+p%d*x",k3+(cpt-1)*ncovmodel,k3+(cpt-1)*ncovmodel+1);
1.223     brouard  8821:              else /* nagesqr =1 */
1.264     brouard  8822:                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  8823:               
1.223     brouard  8824:              ij=1;
1.329     brouard  8825:              ijp=1;
                   8826:              /* for(j=3; j <=ncovmodel-nagesqr; j++){ */
                   8827:              for(j=1; j <=cptcovt; j++) { /* For each covariate of the simplified model */
                   8828:                switch(Typevar[j]){
                   8829:                case 1:
                   8830:                  if(cptcovage >0){ 
                   8831:                    if(j==Tage[ij]) { /* Bug valgrind */
                   8832:                      if(ij <=cptcovage) { /* Bug valgrind */
                   8833:                        if(DummyV[j]==0){/* Bug valgrind */
                   8834:                          /* fprintf(ficgp,"+p%d*%d*x",k3+(cpt-1)*ncovmodel+1+j-2+nagesqr,nbcode[Tvar[j-2]][codtabm(k1,j-2)]); */
                   8835:                          /* fprintf(ficgp,"+p%d*%d*x",k3+(cpt-1)*ncovmodel+1+j+nagesqr,nbcode[Tvar[j]][codtabm(k1,j)]); */
                   8836:                          fprintf(ficgp,"+p%d*%d*x",k3+(cpt-1)*ncovmodel+1+j+nagesqr,Tinvresult[nres][Tvar[j]]);
                   8837:                          /* fprintf(ficgp,"+p%d*%d*x",i+j+2+nagesqr-1,Tinvresult[nres][Tvar[j]]);; */
                   8838:                          /* fprintf(ficgp,"+p%d*%d*x",k3+(cpt-1)*ncovmodel+1+j-2+nagesqr,nbcode[Tvar[j-2]][codtabm(k1,Tvar[j-2])]); */
                   8839:                        }else{ /* quantitative */
                   8840:                          /* fprintf(ficgp,"+p%d*%f*x",i+j+2+nagesqr-1,Tqinvresult[nres][Tvar[j]]); /\* Tqinvresult in decoderesult *\/ */
                   8841:                          fprintf(ficgp,"+p%d*%f*x",k3+(cpt-1)*ncovmodel+1+j+nagesqr,Tqinvresult[nres][Tvar[j]]); /* Tqinvresult in decoderesult */
                   8842:                          /* fprintf(ficgp,"+p%d*%f*x",i+j+2+nagesqr-1,Tqinvresult[nres][Tvar[j]]); /\* Tqinvresult in decoderesult *\/ */
                   8843:                          /* fprintf(ficgp,"+p%d*%d*x",i+j+nagesqr-1,nbcode[Tvar[j-2]][codtabm(k1,Tvar[j-2])]); */
                   8844:                        }
                   8845:                        ij++;
                   8846:                      }
                   8847:                    }
                   8848:                  }
                   8849:                  break;
                   8850:                case 2:
                   8851:                  if(cptcovprod >0){
                   8852:                    if(j==Tprod[ijp]) { /* */ 
                   8853:                      /* printf("Tprod[%d]=%d, j=%d\n", ij, Tprod[ijp], j); */
                   8854:                      if(ijp <=cptcovprod) { /* Product */
                   8855:                        if(DummyV[Tvard[ijp][1]]==0){/* Vn is dummy */
                   8856:                          if(DummyV[Tvard[ijp][2]]==0){/* Vn and Vm are dummy */
                   8857:                            /* 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)]); */
                   8858:                            fprintf(ficgp,"+p%d*%d*%d",k3+(cpt-1)*ncovmodel+1+j+nagesqr,Tinvresult[nres][Tvard[ijp][1]],Tinvresult[nres][Tvard[ijp][2]]);
                   8859:                            /* fprintf(ficgp,"+p%d*%d*%d",i+j+2+nagesqr-1,Tinvresult[nres][Tvard[ijp][1]],Tinvresult[nres][Tvard[ijp][2]]); */
                   8860:                          }else{ /* Vn is dummy and Vm is quanti */
                   8861:                            /* fprintf(ficgp,"+p%d*%d*%f",i+j+2+nagesqr-1,nbcode[Tvard[ijp][1]][codtabm(k1,j)],Tqinvresult[nres][Tvard[ijp][2]]); */
                   8862:                            fprintf(ficgp,"+p%d*%d*%f",k3+(cpt-1)*ncovmodel+1+j+nagesqr,Tinvresult[nres][Tvard[ijp][1]],Tqinvresult[nres][Tvard[ijp][2]]);
                   8863:                            /* fprintf(ficgp,"+p%d*%d*%f",i+j+2+nagesqr-1,Tinvresult[nres][Tvard[ijp][1]],Tqinvresult[nres][Tvard[ijp][2]]); */
                   8864:                          }
                   8865:                        }else{ /* Vn*Vm Vn is quanti */
                   8866:                          if(DummyV[Tvard[ijp][2]]==0){
                   8867:                            fprintf(ficgp,"+p%d*%d*%f",k3+(cpt-1)*ncovmodel+1+j+nagesqr,Tinvresult[nres][Tvard[ijp][2]],Tqinvresult[nres][Tvard[ijp][1]]);
                   8868:                            /* fprintf(ficgp,"+p%d*%d*%f",i+j+2+nagesqr-1,Tinvresult[nres][Tvard[ijp][2]],Tqinvresult[nres][Tvard[ijp][1]]); */
                   8869:                          }else{ /* Both quanti */
                   8870:                            fprintf(ficgp,"+p%d*%f*%f",k3+(cpt-1)*ncovmodel+1+j+nagesqr,Tqinvresult[nres][Tvard[ijp][1]],Tqinvresult[nres][Tvard[ijp][2]]);
                   8871:                            /* fprintf(ficgp,"+p%d*%f*%f",i+j+2+nagesqr-1,Tqinvresult[nres][Tvard[ijp][1]],Tqinvresult[nres][Tvard[ijp][2]]); */
                   8872:                          } 
                   8873:                        }
                   8874:                        ijp++;
                   8875:                      }
                   8876:                    } /* end Tprod */
                   8877:                  } /* end if */
                   8878:                  break;
                   8879:                case 0: 
                   8880:                  /* simple covariate */
                   8881:                  /* fprintf(ficgp,"+p%d*%d",i+j+2+nagesqr-1,nbcode[Tvar[j]][codtabm(k1,j)]); /\* Valgrind bug nbcode *\/ */
                   8882:                  if(Dummy[j]==0){
                   8883:                    /* fprintf(ficgp,"+p%d*%d",i+j+2+nagesqr-1,Tinvresult[nres][Tvar[j]]); /\*  *\/ */
                   8884:                    fprintf(ficgp,"+p%d*%d",k3+(cpt-1)*ncovmodel+1+j+nagesqr,Tinvresult[nres][Tvar[j]]); /*  */
                   8885:                    /* fprintf(ficgp,"+p%d*%d",i+j+2+nagesqr-1,Tinvresult[nres][Tvar[j]]); /\*  *\/ */
                   8886:                  }else{ /* quantitative */
                   8887:                    fprintf(ficgp,"+p%d*%f",k3+(cpt-1)*ncovmodel+1+j+nagesqr,Tqinvresult[nres][Tvar[j]]); /* */
                   8888:                    /* fprintf(ficgp,"+p%d*%f",i+j+2+nagesqr-1,Tqinvresult[nres][Tvar[j]]); /\* *\/ */
                   8889:                    /* fprintf(ficgp,"+p%d*%d*x",i+j+nagesqr-1,nbcode[Tvar[j-2]][codtabm(k1,Tvar[j-2])]); */
                   8890:                  }
                   8891:                  /* end simple */
                   8892:                  /* fprintf(ficgp,"+p%d*%d",k3+(cpt-1)*ncovmodel+1+j-2+nagesqr,nbcode[Tvar[j-2]][codtabm(k1,j-2)]);/\* Valgrind bug nbcode *\/ */
                   8893:                  break;
                   8894:                default:
                   8895:                  break;
                   8896:                } /* end switch */
1.223     brouard  8897:              }
                   8898:              fprintf(ficgp,")");
                   8899:            }
                   8900:            fprintf(ficgp,")");
                   8901:            if(ng ==2)
1.276     brouard  8902:              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  8903:            else /* ng= 3 */
1.276     brouard  8904:              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  8905:           }else{ /* end ng <> 1 */
1.223     brouard  8906:            if( k !=k2) /* logit p11 is hard to draw */
1.276     brouard  8907:              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  8908:          }
                   8909:          if ((k+k2)!= (nlstate*2+ndeath) && ng != 1)
                   8910:            fprintf(ficgp,",");
                   8911:          if (ng == 1 && k!=k2 && (k+k2)!= (nlstate*2+ndeath))
                   8912:            fprintf(ficgp,",");
                   8913:          i=i+ncovmodel;
                   8914:        } /* end k */
                   8915:       } /* end k2 */
1.276     brouard  8916:       /* fprintf(ficgp,"\n set out; unset label;set key default;\n"); */
                   8917:       fprintf(ficgp,"\n set out; unset title;set key default;\n");
1.264     brouard  8918:     } /* end k1 */
1.223     brouard  8919:   } /* end ng */
                   8920:   /* avoid: */
                   8921:   fflush(ficgp); 
1.126     brouard  8922: }  /* end gnuplot */
                   8923: 
                   8924: 
                   8925: /*************** Moving average **************/
1.219     brouard  8926: /* int movingaverage(double ***probs, double bage, double fage, double ***mobaverage, int mobilav, double bageout, double fageout){ */
1.222     brouard  8927:  int movingaverage(double ***probs, double bage, double fage, double ***mobaverage, int mobilav){
1.218     brouard  8928:    
1.222     brouard  8929:    int i, cpt, cptcod;
                   8930:    int modcovmax =1;
                   8931:    int mobilavrange, mob;
                   8932:    int iage=0;
1.288     brouard  8933:    int firstA1=0, firstA2=0;
1.222     brouard  8934: 
1.266     brouard  8935:    double sum=0., sumr=0.;
1.222     brouard  8936:    double age;
1.266     brouard  8937:    double *sumnewp, *sumnewm, *sumnewmr;
                   8938:    double *agemingood, *agemaxgood; 
                   8939:    double *agemingoodr, *agemaxgoodr; 
1.222     brouard  8940:   
                   8941:   
1.278     brouard  8942:    /* modcovmax=2*cptcoveff;  Max number of modalities. We suppose  */
                   8943:    /*             a covariate has 2 modalities, should be equal to ncovcombmax   */
1.222     brouard  8944: 
                   8945:    sumnewp = vector(1,ncovcombmax);
                   8946:    sumnewm = vector(1,ncovcombmax);
1.266     brouard  8947:    sumnewmr = vector(1,ncovcombmax);
1.222     brouard  8948:    agemingood = vector(1,ncovcombmax); 
1.266     brouard  8949:    agemingoodr = vector(1,ncovcombmax);        
1.222     brouard  8950:    agemaxgood = vector(1,ncovcombmax);
1.266     brouard  8951:    agemaxgoodr = vector(1,ncovcombmax);
1.222     brouard  8952: 
                   8953:    for (cptcod=1;cptcod<=ncovcombmax;cptcod++){
1.266     brouard  8954:      sumnewm[cptcod]=0.; sumnewmr[cptcod]=0.;
1.222     brouard  8955:      sumnewp[cptcod]=0.;
1.266     brouard  8956:      agemingood[cptcod]=0, agemingoodr[cptcod]=0;
                   8957:      agemaxgood[cptcod]=0, agemaxgoodr[cptcod]=0;
1.222     brouard  8958:    }
                   8959:    if (cptcovn<1) ncovcombmax=1; /* At least 1 pass */
                   8960:   
1.266     brouard  8961:    if(mobilav==-1 || mobilav==1||mobilav ==3 ||mobilav==5 ||mobilav== 7){
                   8962:      if(mobilav==1 || mobilav==-1) mobilavrange=5; /* default */
1.222     brouard  8963:      else mobilavrange=mobilav;
                   8964:      for (age=bage; age<=fage; age++)
                   8965:        for (i=1; i<=nlstate;i++)
                   8966:         for (cptcod=1;cptcod<=ncovcombmax;cptcod++)
                   8967:           mobaverage[(int)age][i][cptcod]=probs[(int)age][i][cptcod];
                   8968:      /* We keep the original values on the extreme ages bage, fage and for 
                   8969:        fage+1 and bage-1 we use a 3 terms moving average; for fage+2 bage+2
                   8970:        we use a 5 terms etc. until the borders are no more concerned. 
                   8971:      */ 
                   8972:      for (mob=3;mob <=mobilavrange;mob=mob+2){
                   8973:        for (age=bage+(mob-1)/2; age<=fage-(mob-1)/2; age++){
1.266     brouard  8974:         for (cptcod=1;cptcod<=ncovcombmax;cptcod++){
                   8975:           sumnewm[cptcod]=0.;
                   8976:           for (i=1; i<=nlstate;i++){
1.222     brouard  8977:             mobaverage[(int)age][i][cptcod] =probs[(int)age][i][cptcod];
                   8978:             for (cpt=1;cpt<=(mob-1)/2;cpt++){
                   8979:               mobaverage[(int)age][i][cptcod] +=probs[(int)age-cpt][i][cptcod];
                   8980:               mobaverage[(int)age][i][cptcod] +=probs[(int)age+cpt][i][cptcod];
                   8981:             }
                   8982:             mobaverage[(int)age][i][cptcod]=mobaverage[(int)age][i][cptcod]/mob;
1.266     brouard  8983:             sumnewm[cptcod]+=mobaverage[(int)age][i][cptcod];
                   8984:           } /* end i */
                   8985:           if(sumnewm[cptcod] >1.e-3) mobaverage[(int)age][i][cptcod]=mobaverage[(int)age][i][cptcod]/sumnewm[cptcod]; /* Rescaling to sum one */
                   8986:         } /* end cptcod */
1.222     brouard  8987:        }/* end age */
                   8988:      }/* end mob */
1.266     brouard  8989:    }else{
                   8990:      printf("Error internal in movingaverage, mobilav=%d.\n",mobilav);
1.222     brouard  8991:      return -1;
1.266     brouard  8992:    }
                   8993: 
                   8994:    for (cptcod=1;cptcod<=ncovcombmax;cptcod++){ /* for each combination */
1.222     brouard  8995:      /* for (age=bage+(mob-1)/2; age<=fage-(mob-1)/2; age++){ */
                   8996:      if(invalidvarcomb[cptcod]){
                   8997:        printf("\nCombination (%d) ignored because no cases \n",cptcod); 
                   8998:        continue;
                   8999:      }
1.219     brouard  9000: 
1.266     brouard  9001:      for (age=fage-(mob-1)/2; age>=bage+(mob-1)/2; age--){ /*looking for the youngest and oldest good age */
                   9002:        sumnewm[cptcod]=0.;
                   9003:        sumnewmr[cptcod]=0.;
                   9004:        for (i=1; i<=nlstate;i++){
                   9005:         sumnewm[cptcod]+=mobaverage[(int)age][i][cptcod];
                   9006:         sumnewmr[cptcod]+=probs[(int)age][i][cptcod];
                   9007:        }
                   9008:        if(fabs(sumnewmr[cptcod] - 1.) <= 1.e-3) { /* good without smoothing */
                   9009:         agemingoodr[cptcod]=age;
                   9010:        }
                   9011:        if(fabs(sumnewm[cptcod] - 1.) <= 1.e-3) { /* good */
                   9012:           agemingood[cptcod]=age;
                   9013:        }
                   9014:      } /* age */
                   9015:      for (age=bage+(mob-1)/2; age<=fage-(mob-1)/2; age++){ /*looking for the youngest and oldest good age */
1.222     brouard  9016:        sumnewm[cptcod]=0.;
1.266     brouard  9017:        sumnewmr[cptcod]=0.;
1.222     brouard  9018:        for (i=1; i<=nlstate;i++){
                   9019:         sumnewm[cptcod]+=mobaverage[(int)age][i][cptcod];
1.266     brouard  9020:         sumnewmr[cptcod]+=probs[(int)age][i][cptcod];
                   9021:        }
                   9022:        if(fabs(sumnewmr[cptcod] - 1.) <= 1.e-3) { /* good without smoothing */
                   9023:         agemaxgoodr[cptcod]=age;
1.222     brouard  9024:        }
                   9025:        if(fabs(sumnewm[cptcod] - 1.) <= 1.e-3) { /* good */
1.266     brouard  9026:         agemaxgood[cptcod]=age;
                   9027:        }
                   9028:      } /* age */
                   9029:      /* Thus we have agemingood and agemaxgood as well as goodr for raw (preobs) */
                   9030:      /* but they will change */
1.288     brouard  9031:      firstA1=0;firstA2=0;
1.266     brouard  9032:      for (age=fage-(mob-1)/2; age>=bage; age--){/* From oldest to youngest, filling up to the youngest */
                   9033:        sumnewm[cptcod]=0.;
                   9034:        sumnewmr[cptcod]=0.;
                   9035:        for (i=1; i<=nlstate;i++){
                   9036:         sumnewm[cptcod]+=mobaverage[(int)age][i][cptcod];
                   9037:         sumnewmr[cptcod]+=probs[(int)age][i][cptcod];
                   9038:        }
                   9039:        if(mobilav==-1){ /* Forcing raw ages if good else agemingood */
                   9040:         if(fabs(sumnewmr[cptcod] - 1.) <= 1.e-3) { /* good without smoothing */
                   9041:           agemaxgoodr[cptcod]=age;  /* age min */
                   9042:           for (i=1; i<=nlstate;i++)
                   9043:             mobaverage[(int)age][i][cptcod]=probs[(int)age][i][cptcod];
                   9044:         }else{ /* bad we change the value with the values of good ages */
                   9045:           for (i=1; i<=nlstate;i++){
                   9046:             mobaverage[(int)age][i][cptcod]=mobaverage[(int)agemaxgoodr[cptcod]][i][cptcod];
                   9047:           } /* i */
                   9048:         } /* end bad */
                   9049:        }else{
                   9050:         if(fabs(sumnewm[cptcod] - 1.) <= 1.e-3) { /* good */
                   9051:           agemaxgood[cptcod]=age;
                   9052:         }else{ /* bad we change the value with the values of good ages */
                   9053:           for (i=1; i<=nlstate;i++){
                   9054:             mobaverage[(int)age][i][cptcod]=mobaverage[(int)agemaxgood[cptcod]][i][cptcod];
                   9055:           } /* i */
                   9056:         } /* end bad */
                   9057:        }/* end else */
                   9058:        sum=0.;sumr=0.;
                   9059:        for (i=1; i<=nlstate;i++){
                   9060:         sum+=mobaverage[(int)age][i][cptcod];
                   9061:         sumr+=probs[(int)age][i][cptcod];
                   9062:        }
                   9063:        if(fabs(sum - 1.) > 1.e-3) { /* bad */
1.288     brouard  9064:         if(!firstA1){
                   9065:           firstA1=1;
                   9066:           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);
                   9067:         }
                   9068:         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  9069:        } /* end bad */
                   9070:        /* else{ /\* We found some ages summing to one, we will smooth the oldest *\/ */
                   9071:        if(fabs(sumr - 1.) > 1.e-3) { /* bad */
1.288     brouard  9072:         if(!firstA2){
                   9073:           firstA2=1;
                   9074:           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);
                   9075:         }
                   9076:         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  9077:        } /* end bad */
                   9078:      }/* age */
1.266     brouard  9079: 
                   9080:      for (age=bage+(mob-1)/2; age<=fage; age++){/* From youngest, finding the oldest wrong */
1.222     brouard  9081:        sumnewm[cptcod]=0.;
1.266     brouard  9082:        sumnewmr[cptcod]=0.;
1.222     brouard  9083:        for (i=1; i<=nlstate;i++){
                   9084:         sumnewm[cptcod]+=mobaverage[(int)age][i][cptcod];
1.266     brouard  9085:         sumnewmr[cptcod]+=probs[(int)age][i][cptcod];
                   9086:        } 
                   9087:        if(mobilav==-1){ /* Forcing raw ages if good else agemingood */
                   9088:         if(fabs(sumnewmr[cptcod] - 1.) <= 1.e-3) { /* good */
                   9089:           agemingoodr[cptcod]=age;
                   9090:           for (i=1; i<=nlstate;i++)
                   9091:             mobaverage[(int)age][i][cptcod]=probs[(int)age][i][cptcod];
                   9092:         }else{ /* bad we change the value with the values of good ages */
                   9093:           for (i=1; i<=nlstate;i++){
                   9094:             mobaverage[(int)age][i][cptcod]=mobaverage[(int)agemingoodr[cptcod]][i][cptcod];
                   9095:           } /* i */
                   9096:         } /* end bad */
                   9097:        }else{
                   9098:         if(fabs(sumnewm[cptcod] - 1.) <= 1.e-3) { /* good */
                   9099:           agemingood[cptcod]=age;
                   9100:         }else{ /* bad */
                   9101:           for (i=1; i<=nlstate;i++){
                   9102:             mobaverage[(int)age][i][cptcod]=mobaverage[(int)agemingood[cptcod]][i][cptcod];
                   9103:           } /* i */
                   9104:         } /* end bad */
                   9105:        }/* end else */
                   9106:        sum=0.;sumr=0.;
                   9107:        for (i=1; i<=nlstate;i++){
                   9108:         sum+=mobaverage[(int)age][i][cptcod];
                   9109:         sumr+=mobaverage[(int)age][i][cptcod];
1.222     brouard  9110:        }
1.266     brouard  9111:        if(fabs(sum - 1.) > 1.e-3) { /* bad */
1.268     brouard  9112:         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  9113:        } /* end bad */
                   9114:        /* else{ /\* We found some ages summing to one, we will smooth the oldest *\/ */
                   9115:        if(fabs(sumr - 1.) > 1.e-3) { /* bad */
1.268     brouard  9116:         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  9117:        } /* end bad */
                   9118:      }/* age */
1.266     brouard  9119: 
1.222     brouard  9120:                
                   9121:      for (age=bage; age<=fage; age++){
1.235     brouard  9122:        /* printf("%d %d ", cptcod, (int)age); */
1.222     brouard  9123:        sumnewp[cptcod]=0.;
                   9124:        sumnewm[cptcod]=0.;
                   9125:        for (i=1; i<=nlstate;i++){
                   9126:         sumnewp[cptcod]+=probs[(int)age][i][cptcod];
                   9127:         sumnewm[cptcod]+=mobaverage[(int)age][i][cptcod];
                   9128:         /* printf("%.4f %.4f ",probs[(int)age][i][cptcod], mobaverage[(int)age][i][cptcod]); */
                   9129:        }
                   9130:        /* printf("%.4f %.4f \n",sumnewp[cptcod], sumnewm[cptcod]); */
                   9131:      }
                   9132:      /* printf("\n"); */
                   9133:      /* } */
1.266     brouard  9134: 
1.222     brouard  9135:      /* brutal averaging */
1.266     brouard  9136:      /* for (i=1; i<=nlstate;i++){ */
                   9137:      /*   for (age=1; age<=bage; age++){ */
                   9138:      /*         mobaverage[(int)age][i][cptcod]=mobaverage[(int)agemingood[cptcod]][i][cptcod]; */
                   9139:      /*         /\* printf("age=%d i=%d cptcod=%d mobaverage=%.4f \n",(int)age,i, cptcod, mobaverage[(int)age][i][cptcod]); *\/ */
                   9140:      /*   }     */
                   9141:      /*   for (age=fage; age<=AGESUP; age++){ */
                   9142:      /*         mobaverage[(int)age][i][cptcod]=mobaverage[(int)agemaxgood[cptcod]][i][cptcod]; */
                   9143:      /*         /\* printf("age=%d i=%d cptcod=%d mobaverage=%.4f \n",(int)age,i, cptcod, mobaverage[(int)age][i][cptcod]); *\/ */
                   9144:      /*   } */
                   9145:      /* } /\* end i status *\/ */
                   9146:      /* for (i=nlstate+1; i<=nlstate+ndeath;i++){ */
                   9147:      /*   for (age=1; age<=AGESUP; age++){ */
                   9148:      /*         /\*printf("i=%d, age=%d, cptcod=%d\n",i, (int)age, cptcod);*\/ */
                   9149:      /*         mobaverage[(int)age][i][cptcod]=0.; */
                   9150:      /*   } */
                   9151:      /* } */
1.222     brouard  9152:    }/* end cptcod */
1.266     brouard  9153:    free_vector(agemaxgoodr,1, ncovcombmax);
                   9154:    free_vector(agemaxgood,1, ncovcombmax);
                   9155:    free_vector(agemingood,1, ncovcombmax);
                   9156:    free_vector(agemingoodr,1, ncovcombmax);
                   9157:    free_vector(sumnewmr,1, ncovcombmax);
1.222     brouard  9158:    free_vector(sumnewm,1, ncovcombmax);
                   9159:    free_vector(sumnewp,1, ncovcombmax);
                   9160:    return 0;
                   9161:  }/* End movingaverage */
1.218     brouard  9162:  
1.126     brouard  9163: 
1.296     brouard  9164:  
1.126     brouard  9165: /************** Forecasting ******************/
1.296     brouard  9166: /* 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)*/
                   9167: 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){
                   9168:   /* dateintemean, mean date of interviews
                   9169:      dateprojd, year, month, day of starting projection 
                   9170:      dateprojf date of end of projection;year of end of projection (same day and month as proj1).
1.126     brouard  9171:      agemin, agemax range of age
                   9172:      dateprev1 dateprev2 range of dates during which prevalence is computed
                   9173:   */
1.296     brouard  9174:   /* double anprojd, mprojd, jprojd; */
                   9175:   /* double anprojf, mprojf, jprojf; */
1.267     brouard  9176:   int yearp, stepsize, hstepm, nhstepm, j, k, cptcod, i, h, i1, k4, nres=0;
1.126     brouard  9177:   double agec; /* generic age */
1.296     brouard  9178:   double agelim, ppij, yp,yp1,yp2;
1.126     brouard  9179:   double *popeffectif,*popcount;
                   9180:   double ***p3mat;
1.218     brouard  9181:   /* double ***mobaverage; */
1.126     brouard  9182:   char fileresf[FILENAMELENGTH];
                   9183: 
                   9184:   agelim=AGESUP;
1.211     brouard  9185:   /* Compute observed prevalence between dateprev1 and dateprev2 by counting the number of people
                   9186:      in each health status at the date of interview (if between dateprev1 and dateprev2).
                   9187:      We still use firstpass and lastpass as another selection.
                   9188:   */
1.214     brouard  9189:   /* freqsummary(fileres, agemin, agemax, s, agev, nlstate, imx,Tvaraff,nbcode, ncodemax,mint,anint,strstart,\ */
                   9190:   /*         firstpass, lastpass,  stepm,  weightopt, model); */
1.126     brouard  9191:  
1.201     brouard  9192:   strcpy(fileresf,"F_"); 
                   9193:   strcat(fileresf,fileresu);
1.126     brouard  9194:   if((ficresf=fopen(fileresf,"w"))==NULL) {
                   9195:     printf("Problem with forecast resultfile: %s\n", fileresf);
                   9196:     fprintf(ficlog,"Problem with forecast resultfile: %s\n", fileresf);
                   9197:   }
1.235     brouard  9198:   printf("\nComputing forecasting: result on file '%s', please wait... \n", fileresf);
                   9199:   fprintf(ficlog,"\nComputing forecasting: result on file '%s', please wait... \n", fileresf);
1.126     brouard  9200: 
1.225     brouard  9201:   if (cptcoveff==0) ncodemax[cptcoveff]=1;
1.126     brouard  9202: 
                   9203: 
                   9204:   stepsize=(int) (stepm+YEARM-1)/YEARM;
                   9205:   if (stepm<=12) stepsize=1;
                   9206:   if(estepm < stepm){
                   9207:     printf ("Problem %d lower than %d\n",estepm, stepm);
                   9208:   }
1.270     brouard  9209:   else{
                   9210:     hstepm=estepm;   
                   9211:   }
                   9212:   if(estepm > stepm){ /* Yes every two year */
                   9213:     stepsize=2;
                   9214:   }
1.296     brouard  9215:   hstepm=hstepm/stepm;
1.126     brouard  9216: 
1.296     brouard  9217:   
                   9218:   /* yp1=modf(dateintmean,&yp);/\* extracts integral of datemean in yp  and */
                   9219:   /*                              fractional in yp1 *\/ */
                   9220:   /* aintmean=yp; */
                   9221:   /* yp2=modf((yp1*12),&yp); */
                   9222:   /* mintmean=yp; */
                   9223:   /* yp1=modf((yp2*30.5),&yp); */
                   9224:   /* jintmean=yp; */
                   9225:   /* if(jintmean==0) jintmean=1; */
                   9226:   /* if(mintmean==0) mintmean=1; */
1.126     brouard  9227: 
1.296     brouard  9228: 
                   9229:   /* date2dmy(dateintmean,&jintmean,&mintmean,&aintmean); */
                   9230:   /* date2dmy(dateprojd,&jprojd, &mprojd, &anprojd); */
                   9231:   /* date2dmy(dateprojf,&jprojf, &mprojf, &anprojf); */
1.227     brouard  9232:   i1=pow(2,cptcoveff);
1.126     brouard  9233:   if (cptcovn < 1){i1=1;}
                   9234:   
1.296     brouard  9235:   fprintf(ficresf,"# Mean day of interviews %.lf/%.lf/%.lf (%.2f) between %.2f and %.2f \n",jintmean,mintmean,aintmean,dateintmean,dateprev1,dateprev2); 
1.126     brouard  9236:   
                   9237:   fprintf(ficresf,"#****** Routine prevforecast **\n");
1.227     brouard  9238:   
1.126     brouard  9239: /*           if (h==(int)(YEARM*yearp)){ */
1.235     brouard  9240:   for(nres=1; nres <= nresult; nres++) /* For each resultline */
1.332     brouard  9241:     for(k=1; k<=i1;k++){ /* We want to find the combination k corresponding to the values of the dummies given in this resut line (to be cleaned one day) */
1.253     brouard  9242:     if(i1 != 1 && TKresult[nres]!= k)
1.235     brouard  9243:       continue;
1.227     brouard  9244:     if(invalidvarcomb[k]){
                   9245:       printf("\nCombination (%d) projection ignored because no cases \n",k); 
                   9246:       continue;
                   9247:     }
                   9248:     fprintf(ficresf,"\n#****** hpijx=probability over h years, hp.jx is weighted by observed prev \n#");
                   9249:     for(j=1;j<=cptcoveff;j++) {
1.332     brouard  9250:       /* fprintf(ficresf," V%d (=) %d",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,Tvaraff[j])]); */
                   9251:       fprintf(ficresf," V%d (=) %d",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]);
1.227     brouard  9252:     }
1.235     brouard  9253:     for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
1.238     brouard  9254:       fprintf(ficresf," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
1.235     brouard  9255:     }
1.227     brouard  9256:     fprintf(ficresf," yearproj age");
                   9257:     for(j=1; j<=nlstate+ndeath;j++){ 
                   9258:       for(i=1; i<=nlstate;i++)               
                   9259:        fprintf(ficresf," p%d%d",i,j);
                   9260:       fprintf(ficresf," wp.%d",j);
                   9261:     }
1.296     brouard  9262:     for (yearp=0; yearp<=(anprojf-anprojd);yearp +=stepsize) {
1.227     brouard  9263:       fprintf(ficresf,"\n");
1.296     brouard  9264:       fprintf(ficresf,"\n# Forecasting at date %.lf/%.lf/%.lf ",jprojd,mprojd,anprojd+yearp);   
1.270     brouard  9265:       /* for (agec=fage; agec>=(ageminpar-1); agec--){  */
                   9266:       for (agec=fage; agec>=(bage); agec--){ 
1.227     brouard  9267:        nhstepm=(int) rint((agelim-agec)*YEARM/stepm); 
                   9268:        nhstepm = nhstepm/hstepm; 
                   9269:        p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   9270:        oldm=oldms;savm=savms;
1.268     brouard  9271:        /* We compute pii at age agec over nhstepm);*/
1.235     brouard  9272:        hpxij(p3mat,nhstepm,agec,hstepm,p,nlstate,stepm,oldm,savm, k,nres);
1.268     brouard  9273:        /* Then we print p3mat for h corresponding to the right agec+h*stepms=yearp */
1.227     brouard  9274:        for (h=0; h<=nhstepm; h++){
                   9275:          if (h*hstepm/YEARM*stepm ==yearp) {
1.268     brouard  9276:            break;
                   9277:          }
                   9278:        }
                   9279:        fprintf(ficresf,"\n");
                   9280:        for(j=1;j<=cptcoveff;j++) 
1.332     brouard  9281:          /* fprintf(ficresf,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,Tvaraff[j])]); /\* Tvaraff not correct *\/ */
                   9282:          fprintf(ficresf,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); /* TnsdVar[Tvaraff]  correct */
1.296     brouard  9283:        fprintf(ficresf,"%.f %.f ",anprojd+yearp,agec+h*hstepm/YEARM*stepm);
1.268     brouard  9284:        
                   9285:        for(j=1; j<=nlstate+ndeath;j++) {
                   9286:          ppij=0.;
                   9287:          for(i=1; i<=nlstate;i++) {
1.278     brouard  9288:            if (mobilav>=1)
                   9289:             ppij=ppij+p3mat[i][j][h]*prev[(int)agec][i][k];
                   9290:            else { /* even if mobilav==-1 we use mobaverage, probs may not sums to 1 */
                   9291:                ppij=ppij+p3mat[i][j][h]*probs[(int)(agec)][i][k];
                   9292:            }
1.268     brouard  9293:            fprintf(ficresf," %.3f", p3mat[i][j][h]);
                   9294:          } /* end i */
                   9295:          fprintf(ficresf," %.3f", ppij);
                   9296:        }/* end j */
1.227     brouard  9297:        free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   9298:       } /* end agec */
1.266     brouard  9299:       /* diffyear=(int) anproj1+yearp-ageminpar-1; */
                   9300:       /*printf("Prevforecast %d+%d-%d=diffyear=%d\n",(int) anproj1, (int)yearp,(int)ageminpar,(int) anproj1-(int)ageminpar);*/
1.227     brouard  9301:     } /* end yearp */
                   9302:   } /* end  k */
1.219     brouard  9303:        
1.126     brouard  9304:   fclose(ficresf);
1.215     brouard  9305:   printf("End of Computing forecasting \n");
                   9306:   fprintf(ficlog,"End of Computing forecasting\n");
                   9307: 
1.126     brouard  9308: }
                   9309: 
1.269     brouard  9310: /************** Back Forecasting ******************/
1.296     brouard  9311:  /* 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){ */
                   9312:  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){
                   9313:   /* back1, year, month, day of starting backprojection
1.267     brouard  9314:      agemin, agemax range of age
                   9315:      dateprev1 dateprev2 range of dates during which prevalence is computed
1.269     brouard  9316:      anback2 year of end of backprojection (same day and month as back1).
                   9317:      prevacurrent and prev are prevalences.
1.267     brouard  9318:   */
                   9319:   int yearp, stepsize, hstepm, nhstepm, j, k, cptcod, i, h, i1, k4, nres=0;
                   9320:   double agec; /* generic age */
1.302     brouard  9321:   double agelim, ppij, ppi, yp,yp1,yp2; /* ,jintmean,mintmean,aintmean;*/
1.267     brouard  9322:   double *popeffectif,*popcount;
                   9323:   double ***p3mat;
                   9324:   /* double ***mobaverage; */
                   9325:   char fileresfb[FILENAMELENGTH];
                   9326:  
1.268     brouard  9327:   agelim=AGEINF;
1.267     brouard  9328:   /* Compute observed prevalence between dateprev1 and dateprev2 by counting the number of people
                   9329:      in each health status at the date of interview (if between dateprev1 and dateprev2).
                   9330:      We still use firstpass and lastpass as another selection.
                   9331:   */
                   9332:   /* freqsummary(fileres, agemin, agemax, s, agev, nlstate, imx,Tvaraff,nbcode, ncodemax,mint,anint,strstart,\ */
                   9333:   /*         firstpass, lastpass,  stepm,  weightopt, model); */
                   9334: 
                   9335:   /*Do we need to compute prevalence again?*/
                   9336: 
                   9337:   /* prevalence(probs, ageminpar, agemax, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass); */
                   9338:   
                   9339:   strcpy(fileresfb,"FB_");
                   9340:   strcat(fileresfb,fileresu);
                   9341:   if((ficresfb=fopen(fileresfb,"w"))==NULL) {
                   9342:     printf("Problem with back forecast resultfile: %s\n", fileresfb);
                   9343:     fprintf(ficlog,"Problem with back forecast resultfile: %s\n", fileresfb);
                   9344:   }
                   9345:   printf("\nComputing back forecasting: result on file '%s', please wait... \n", fileresfb);
                   9346:   fprintf(ficlog,"\nComputing back forecasting: result on file '%s', please wait... \n", fileresfb);
                   9347:   
                   9348:   if (cptcoveff==0) ncodemax[cptcoveff]=1;
                   9349:   
                   9350:    
                   9351:   stepsize=(int) (stepm+YEARM-1)/YEARM;
                   9352:   if (stepm<=12) stepsize=1;
                   9353:   if(estepm < stepm){
                   9354:     printf ("Problem %d lower than %d\n",estepm, stepm);
                   9355:   }
1.270     brouard  9356:   else{
                   9357:     hstepm=estepm;   
                   9358:   }
                   9359:   if(estepm >= stepm){ /* Yes every two year */
                   9360:     stepsize=2;
                   9361:   }
1.267     brouard  9362:   
                   9363:   hstepm=hstepm/stepm;
1.296     brouard  9364:   /* yp1=modf(dateintmean,&yp);/\* extracts integral of datemean in yp  and */
                   9365:   /*                              fractional in yp1 *\/ */
                   9366:   /* aintmean=yp; */
                   9367:   /* yp2=modf((yp1*12),&yp); */
                   9368:   /* mintmean=yp; */
                   9369:   /* yp1=modf((yp2*30.5),&yp); */
                   9370:   /* jintmean=yp; */
                   9371:   /* if(jintmean==0) jintmean=1; */
                   9372:   /* if(mintmean==0) jintmean=1; */
1.267     brouard  9373:   
                   9374:   i1=pow(2,cptcoveff);
                   9375:   if (cptcovn < 1){i1=1;}
                   9376:   
1.296     brouard  9377:   fprintf(ficresfb,"# Mean day of interviews %.lf/%.lf/%.lf (%.2f) between %.2f and %.2f \n",jintmean,mintmean,aintmean,dateintmean,dateprev1,dateprev2);
                   9378:   printf("# Mean day of interviews %.lf/%.lf/%.lf (%.2f) between %.2f and %.2f \n",jintmean,mintmean,aintmean,dateintmean,dateprev1,dateprev2);
1.267     brouard  9379:   
                   9380:   fprintf(ficresfb,"#****** Routine prevbackforecast **\n");
                   9381:   
                   9382:   for(nres=1; nres <= nresult; nres++) /* For each resultline */
                   9383:   for(k=1; k<=i1;k++){
                   9384:     if(i1 != 1 && TKresult[nres]!= k)
                   9385:       continue;
                   9386:     if(invalidvarcomb[k]){
                   9387:       printf("\nCombination (%d) projection ignored because no cases \n",k); 
                   9388:       continue;
                   9389:     }
1.268     brouard  9390:     fprintf(ficresfb,"\n#****** hbijx=probability over h years, hb.jx is weighted by observed prev \n#");
1.267     brouard  9391:     for(j=1;j<=cptcoveff;j++) {
1.332     brouard  9392:       fprintf(ficresfb," V%d (=) %d",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]);
1.267     brouard  9393:     }
                   9394:     for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
                   9395:       fprintf(ficresf," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
                   9396:     }
                   9397:     fprintf(ficresfb," yearbproj age");
                   9398:     for(j=1; j<=nlstate+ndeath;j++){
                   9399:       for(i=1; i<=nlstate;i++)
1.268     brouard  9400:        fprintf(ficresfb," b%d%d",i,j);
                   9401:       fprintf(ficresfb," b.%d",j);
1.267     brouard  9402:     }
1.296     brouard  9403:     for (yearp=0; yearp>=(anbackf-anbackd);yearp -=stepsize) {
1.267     brouard  9404:       /* for (yearp=0; yearp<=(anproj2-anproj1);yearp +=stepsize) {  */
                   9405:       fprintf(ficresfb,"\n");
1.296     brouard  9406:       fprintf(ficresfb,"\n# Back Forecasting at date %.lf/%.lf/%.lf ",jbackd,mbackd,anbackd+yearp);
1.273     brouard  9407:       /* printf("\n# Back Forecasting at date %.lf/%.lf/%.lf ",jback1,mback1,anback1+yearp); */
1.270     brouard  9408:       /* for (agec=bage; agec<=agemax-1; agec++){  /\* testing *\/ */
                   9409:       for (agec=bage; agec<=fage; agec++){  /* testing */
1.268     brouard  9410:        /* We compute bij at age agec over nhstepm, nhstepm decreases when agec increases because of agemax;*/
1.271     brouard  9411:        nhstepm=(int) (agec-agelim) *YEARM/stepm;/*     nhstepm=(int) rint((agec-agelim)*YEARM/stepm);*/
1.267     brouard  9412:        nhstepm = nhstepm/hstepm;
                   9413:        p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   9414:        oldm=oldms;savm=savms;
1.268     brouard  9415:        /* computes hbxij at age agec over 1 to nhstepm */
1.271     brouard  9416:        /* printf("####prevbackforecast debug  agec=%.2f nhstepm=%d\n",agec, nhstepm);fflush(stdout); */
1.267     brouard  9417:        hbxij(p3mat,nhstepm,agec,hstepm,p,prevacurrent,nlstate,stepm, k, nres);
1.268     brouard  9418:        /* hpxij(p3mat,nhstepm,agec,hstepm,p,             nlstate,stepm,oldm,savm, k,nres); */
                   9419:        /* Then we print p3mat for h corresponding to the right agec+h*stepms=yearp */
                   9420:        /* printf(" agec=%.2f\n",agec);fflush(stdout); */
1.267     brouard  9421:        for (h=0; h<=nhstepm; h++){
1.268     brouard  9422:          if (h*hstepm/YEARM*stepm ==-yearp) {
                   9423:            break;
                   9424:          }
                   9425:        }
                   9426:        fprintf(ficresfb,"\n");
                   9427:        for(j=1;j<=cptcoveff;j++)
1.332     brouard  9428:          fprintf(ficresfb,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]);
1.296     brouard  9429:        fprintf(ficresfb,"%.f %.f ",anbackd+yearp,agec-h*hstepm/YEARM*stepm);
1.268     brouard  9430:        for(i=1; i<=nlstate+ndeath;i++) {
                   9431:          ppij=0.;ppi=0.;
                   9432:          for(j=1; j<=nlstate;j++) {
                   9433:            /* if (mobilav==1) */
1.269     brouard  9434:            ppij=ppij+p3mat[i][j][h]*prevacurrent[(int)agec][j][k];
                   9435:            ppi=ppi+prevacurrent[(int)agec][j][k];
                   9436:            /* ppij=ppij+p3mat[i][j][h]*mobaverage[(int)agec][j][k]; */
                   9437:            /* ppi=ppi+mobaverage[(int)agec][j][k]; */
1.267     brouard  9438:              /* else { */
                   9439:              /*        ppij=ppij+p3mat[i][j][h]*probs[(int)(agec)][i][k]; */
                   9440:              /* } */
1.268     brouard  9441:            fprintf(ficresfb," %.3f", p3mat[i][j][h]);
                   9442:          } /* end j */
                   9443:          if(ppi <0.99){
                   9444:            printf("Error in prevbackforecast, prevalence doesn't sum to 1 for state %d: %3f\n",i, ppi);
                   9445:            fprintf(ficlog,"Error in prevbackforecast, prevalence doesn't sum to 1 for state %d: %3f\n",i, ppi);
                   9446:          }
                   9447:          fprintf(ficresfb," %.3f", ppij);
                   9448:        }/* end j */
1.267     brouard  9449:        free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   9450:       } /* end agec */
                   9451:     } /* end yearp */
                   9452:   } /* end k */
1.217     brouard  9453:   
1.267     brouard  9454:   /* if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX); */
1.217     brouard  9455:   
1.267     brouard  9456:   fclose(ficresfb);
                   9457:   printf("End of Computing Back forecasting \n");
                   9458:   fprintf(ficlog,"End of Computing Back forecasting\n");
1.218     brouard  9459:        
1.267     brouard  9460: }
1.217     brouard  9461: 
1.269     brouard  9462: /* Variance of prevalence limit: varprlim */
                   9463:  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  9464:     /*------- Variance of forward period (stable) prevalence------*/   
1.269     brouard  9465:  
                   9466:    char fileresvpl[FILENAMELENGTH];  
                   9467:    FILE *ficresvpl;
                   9468:    double **oldm, **savm;
                   9469:    double **varpl; /* Variances of prevalence limits by age */   
                   9470:    int i1, k, nres, j ;
                   9471:    
                   9472:     strcpy(fileresvpl,"VPL_");
                   9473:     strcat(fileresvpl,fileresu);
                   9474:     if((ficresvpl=fopen(fileresvpl,"w"))==NULL) {
1.288     brouard  9475:       printf("Problem with variance of forward period (stable) prevalence  resultfile: %s\n", fileresvpl);
1.269     brouard  9476:       exit(0);
                   9477:     }
1.288     brouard  9478:     printf("Computing Variance-covariance of forward period (stable) prevalence: file '%s' ...", fileresvpl);fflush(stdout);
                   9479:     fprintf(ficlog, "Computing Variance-covariance of forward period (stable) prevalence: file '%s' ...", fileresvpl);fflush(ficlog);
1.269     brouard  9480:     
                   9481:     /*for(cptcov=1,k=0;cptcov<=i1;cptcov++){
                   9482:       for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*/
                   9483:     
                   9484:     i1=pow(2,cptcoveff);
                   9485:     if (cptcovn < 1){i1=1;}
                   9486: 
                   9487:     for(nres=1; nres <= nresult; nres++) /* For each resultline */
1.332     brouard  9488:       for(k=1; k<=i1;k++){ /* We find the combination equivalent to result line values of dummies */
1.269     brouard  9489:       if(i1 != 1 && TKresult[nres]!= k)
                   9490:        continue;
                   9491:       fprintf(ficresvpl,"\n#****** ");
                   9492:       printf("\n#****** ");
                   9493:       fprintf(ficlog,"\n#****** ");
                   9494:       for(j=1;j<=cptcoveff;j++) {
1.332     brouard  9495:        fprintf(ficresvpl,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]);
                   9496:        fprintf(ficlog,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]);
                   9497:        printf("V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]);
1.269     brouard  9498:       }
                   9499:       for (j=1; j<= nsq; j++){ /* For each selected (single) quantitative value */
1.332     brouard  9500:        printf(" V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]);
                   9501:        fprintf(ficresvpl," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]);
                   9502:        fprintf(ficlog," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]);
1.269     brouard  9503:       }        
                   9504:       fprintf(ficresvpl,"******\n");
                   9505:       printf("******\n");
                   9506:       fprintf(ficlog,"******\n");
                   9507:       
                   9508:       varpl=matrix(1,nlstate,(int) bage, (int) fage);
                   9509:       oldm=oldms;savm=savms;
                   9510:       varprevlim(fileresvpl, ficresvpl, varpl, matcov, p, delti, nlstate, stepm, (int) bage, (int) fage, oldm, savm, prlim, ftolpl, ncvyearp, k, strstart, nres);
                   9511:       free_matrix(varpl,1,nlstate,(int) bage, (int)fage);
                   9512:       /*}*/
                   9513:     }
                   9514:     
                   9515:     fclose(ficresvpl);
1.288     brouard  9516:     printf("done variance-covariance of forward period prevalence\n");fflush(stdout);
                   9517:     fprintf(ficlog,"done variance-covariance of forward period prevalence\n");fflush(ficlog);
1.269     brouard  9518: 
                   9519:  }
                   9520: /* Variance of back prevalence: varbprlim */
                   9521:  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){
                   9522:       /*------- Variance of back (stable) prevalence------*/
                   9523: 
                   9524:    char fileresvbl[FILENAMELENGTH];  
                   9525:    FILE  *ficresvbl;
                   9526: 
                   9527:    double **oldm, **savm;
                   9528:    double **varbpl; /* Variances of back prevalence limits by age */   
                   9529:    int i1, k, nres, j ;
                   9530: 
                   9531:    strcpy(fileresvbl,"VBL_");
                   9532:    strcat(fileresvbl,fileresu);
                   9533:    if((ficresvbl=fopen(fileresvbl,"w"))==NULL) {
                   9534:      printf("Problem with variance of back (stable) prevalence  resultfile: %s\n", fileresvbl);
                   9535:      exit(0);
                   9536:    }
                   9537:    printf("Computing Variance-covariance of back (stable) prevalence: file '%s' ...", fileresvbl);fflush(stdout);
                   9538:    fprintf(ficlog, "Computing Variance-covariance of back (stable) prevalence: file '%s' ...", fileresvbl);fflush(ficlog);
                   9539:    
                   9540:    
                   9541:    i1=pow(2,cptcoveff);
                   9542:    if (cptcovn < 1){i1=1;}
                   9543:    
                   9544:    for(nres=1; nres <= nresult; nres++) /* For each resultline */
                   9545:      for(k=1; k<=i1;k++){
                   9546:        if(i1 != 1 && TKresult[nres]!= k)
                   9547:         continue;
                   9548:        fprintf(ficresvbl,"\n#****** ");
                   9549:        printf("\n#****** ");
                   9550:        fprintf(ficlog,"\n#****** ");
                   9551:        for(j=1;j<=cptcoveff;j++) {
1.332     brouard  9552:         fprintf(ficresvbl,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]);
                   9553:         fprintf(ficlog,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]);
                   9554:         printf("V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]);
1.269     brouard  9555:        }
                   9556:        for (j=1; j<= nsq; j++){ /* For each selected (single) quantitative value */
1.332     brouard  9557:         printf(" V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]);
                   9558:         fprintf(ficresvbl," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]);
                   9559:         fprintf(ficlog," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]);
1.269     brouard  9560:        }
                   9561:        fprintf(ficresvbl,"******\n");
                   9562:        printf("******\n");
                   9563:        fprintf(ficlog,"******\n");
                   9564:        
                   9565:        varbpl=matrix(1,nlstate,(int) bage, (int) fage);
                   9566:        oldm=oldms;savm=savms;
                   9567:        
                   9568:        varbrevlim(fileresvbl, ficresvbl, varbpl, matcov, p, delti, nlstate, stepm, (int) bage, (int) fage, oldm, savm, bprlim, ftolpl, mobilavproj, ncvyearp, k, strstart, nres);
                   9569:        free_matrix(varbpl,1,nlstate,(int) bage, (int)fage);
                   9570:        /*}*/
                   9571:      }
                   9572:    
                   9573:    fclose(ficresvbl);
                   9574:    printf("done variance-covariance of back prevalence\n");fflush(stdout);
                   9575:    fprintf(ficlog,"done variance-covariance of back prevalence\n");fflush(ficlog);
                   9576: 
                   9577:  } /* End of varbprlim */
                   9578: 
1.126     brouard  9579: /************** Forecasting *****not tested NB*************/
1.227     brouard  9580: /* 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  9581:   
1.227     brouard  9582: /*   int cpt, stepsize, hstepm, nhstepm, j,k,c, cptcod, i,h; */
                   9583: /*   int *popage; */
                   9584: /*   double calagedatem, agelim, kk1, kk2; */
                   9585: /*   double *popeffectif,*popcount; */
                   9586: /*   double ***p3mat,***tabpop,***tabpopprev; */
                   9587: /*   /\* double ***mobaverage; *\/ */
                   9588: /*   char filerespop[FILENAMELENGTH]; */
1.126     brouard  9589: 
1.227     brouard  9590: /*   tabpop= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX); */
                   9591: /*   tabpopprev= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX); */
                   9592: /*   agelim=AGESUP; */
                   9593: /*   calagedatem=(anpyram+mpyram/12.+jpyram/365.-dateintmean)*YEARM; */
1.126     brouard  9594:   
1.227     brouard  9595: /*   prevalence(probs, ageminpar, agemax, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass); */
1.126     brouard  9596:   
                   9597:   
1.227     brouard  9598: /*   strcpy(filerespop,"POP_");  */
                   9599: /*   strcat(filerespop,fileresu); */
                   9600: /*   if((ficrespop=fopen(filerespop,"w"))==NULL) { */
                   9601: /*     printf("Problem with forecast resultfile: %s\n", filerespop); */
                   9602: /*     fprintf(ficlog,"Problem with forecast resultfile: %s\n", filerespop); */
                   9603: /*   } */
                   9604: /*   printf("Computing forecasting: result on file '%s' \n", filerespop); */
                   9605: /*   fprintf(ficlog,"Computing forecasting: result on file '%s' \n", filerespop); */
1.126     brouard  9606: 
1.227     brouard  9607: /*   if (cptcoveff==0) ncodemax[cptcoveff]=1; */
1.126     brouard  9608: 
1.227     brouard  9609: /*   /\* if (mobilav!=0) { *\/ */
                   9610: /*   /\*   mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX); *\/ */
                   9611: /*   /\*   if (movingaverage(probs, ageminpar, fage, mobaverage,mobilav)!=0){ *\/ */
                   9612: /*   /\*     fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav); *\/ */
                   9613: /*   /\*     printf(" Error in movingaverage mobilav=%d\n",mobilav); *\/ */
                   9614: /*   /\*   } *\/ */
                   9615: /*   /\* } *\/ */
1.126     brouard  9616: 
1.227     brouard  9617: /*   stepsize=(int) (stepm+YEARM-1)/YEARM; */
                   9618: /*   if (stepm<=12) stepsize=1; */
1.126     brouard  9619:   
1.227     brouard  9620: /*   agelim=AGESUP; */
1.126     brouard  9621:   
1.227     brouard  9622: /*   hstepm=1; */
                   9623: /*   hstepm=hstepm/stepm;  */
1.218     brouard  9624:        
1.227     brouard  9625: /*   if (popforecast==1) { */
                   9626: /*     if((ficpop=fopen(popfile,"r"))==NULL) { */
                   9627: /*       printf("Problem with population file : %s\n",popfile);exit(0); */
                   9628: /*       fprintf(ficlog,"Problem with population file : %s\n",popfile);exit(0); */
                   9629: /*     }  */
                   9630: /*     popage=ivector(0,AGESUP); */
                   9631: /*     popeffectif=vector(0,AGESUP); */
                   9632: /*     popcount=vector(0,AGESUP); */
1.126     brouard  9633:     
1.227     brouard  9634: /*     i=1;    */
                   9635: /*     while ((c=fscanf(ficpop,"%d %lf\n",&popage[i],&popcount[i])) != EOF) i=i+1; */
1.218     brouard  9636:     
1.227     brouard  9637: /*     imx=i; */
                   9638: /*     for (i=1; i<imx;i++) popeffectif[popage[i]]=popcount[i]; */
                   9639: /*   } */
1.218     brouard  9640:   
1.227     brouard  9641: /*   for(cptcov=1,k=0;cptcov<=i2;cptcov++){ */
                   9642: /*     for(cptcod=1;cptcod<=ncodemax[cptcoveff];cptcod++){ */
                   9643: /*       k=k+1; */
                   9644: /*       fprintf(ficrespop,"\n#******"); */
                   9645: /*       for(j=1;j<=cptcoveff;j++) { */
                   9646: /*     fprintf(ficrespop," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]); */
                   9647: /*       } */
                   9648: /*       fprintf(ficrespop,"******\n"); */
                   9649: /*       fprintf(ficrespop,"# Age"); */
                   9650: /*       for(j=1; j<=nlstate+ndeath;j++) fprintf(ficrespop," P.%d",j); */
                   9651: /*       if (popforecast==1)  fprintf(ficrespop," [Population]"); */
1.126     brouard  9652:       
1.227     brouard  9653: /*       for (cpt=0; cpt<=0;cpt++) {  */
                   9654: /*     fprintf(ficrespop,"\n\n# Forecasting at date %.lf/%.lf/%.lf ",jpyram,mpyram,anpyram+cpt);    */
1.126     brouard  9655:        
1.227     brouard  9656: /*     for (agedeb=(fage-((int)calagedatem %12/12.)); agedeb>=(ageminpar-((int)calagedatem %12)/12.); agedeb--){  */
                   9657: /*       nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm);  */
                   9658: /*       nhstepm = nhstepm/hstepm;  */
1.126     brouard  9659:          
1.227     brouard  9660: /*       p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm); */
                   9661: /*       oldm=oldms;savm=savms; */
                   9662: /*       hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);   */
1.218     brouard  9663:          
1.227     brouard  9664: /*       for (h=0; h<=nhstepm; h++){ */
                   9665: /*         if (h==(int) (calagedatem+YEARM*cpt)) { */
                   9666: /*           fprintf(ficrespop,"\n %3.f ",agedeb+h*hstepm/YEARM*stepm); */
                   9667: /*         }  */
                   9668: /*         for(j=1; j<=nlstate+ndeath;j++) { */
                   9669: /*           kk1=0.;kk2=0; */
                   9670: /*           for(i=1; i<=nlstate;i++) {               */
                   9671: /*             if (mobilav==1)  */
                   9672: /*               kk1=kk1+p3mat[i][j][h]*mobaverage[(int)agedeb+1][i][cptcod]; */
                   9673: /*             else { */
                   9674: /*               kk1=kk1+p3mat[i][j][h]*probs[(int)(agedeb+1)][i][cptcod]; */
                   9675: /*             } */
                   9676: /*           } */
                   9677: /*           if (h==(int)(calagedatem+12*cpt)){ */
                   9678: /*             tabpop[(int)(agedeb)][j][cptcod]=kk1; */
                   9679: /*             /\*fprintf(ficrespop," %.3f", kk1); */
                   9680: /*               if (popforecast==1) fprintf(ficrespop," [%.f]", kk1*popeffectif[(int)agedeb+1]);*\/ */
                   9681: /*           } */
                   9682: /*         } */
                   9683: /*         for(i=1; i<=nlstate;i++){ */
                   9684: /*           kk1=0.; */
                   9685: /*           for(j=1; j<=nlstate;j++){ */
                   9686: /*             kk1= kk1+tabpop[(int)(agedeb)][j][cptcod];  */
                   9687: /*           } */
                   9688: /*           tabpopprev[(int)(agedeb)][i][cptcod]=tabpop[(int)(agedeb)][i][cptcod]/kk1*popeffectif[(int)(agedeb+(calagedatem+12*cpt)*hstepm/YEARM*stepm-1)]; */
                   9689: /*         } */
1.218     brouard  9690:            
1.227     brouard  9691: /*         if (h==(int)(calagedatem+12*cpt)) */
                   9692: /*           for(j=1; j<=nlstate;j++)  */
                   9693: /*             fprintf(ficrespop," %15.2f",tabpopprev[(int)(agedeb+1)][j][cptcod]); */
                   9694: /*       } */
                   9695: /*       free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm); */
                   9696: /*     } */
                   9697: /*       } */
1.218     brouard  9698:       
1.227     brouard  9699: /*       /\******\/ */
1.218     brouard  9700:       
1.227     brouard  9701: /*       for (cpt=1; cpt<=(anpyram1-anpyram);cpt++) {  */
                   9702: /*     fprintf(ficrespop,"\n\n# Forecasting at date %.lf/%.lf/%.lf ",jpyram,mpyram,anpyram+cpt);    */
                   9703: /*     for (agedeb=(fage-((int)calagedatem %12/12.)); agedeb>=(ageminpar-((int)calagedatem %12)/12.); agedeb--){  */
                   9704: /*       nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm);  */
                   9705: /*       nhstepm = nhstepm/hstepm;  */
1.126     brouard  9706:          
1.227     brouard  9707: /*       p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm); */
                   9708: /*       oldm=oldms;savm=savms; */
                   9709: /*       hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);   */
                   9710: /*       for (h=0; h<=nhstepm; h++){ */
                   9711: /*         if (h==(int) (calagedatem+YEARM*cpt)) { */
                   9712: /*           fprintf(ficresf,"\n %3.f ",agedeb+h*hstepm/YEARM*stepm); */
                   9713: /*         }  */
                   9714: /*         for(j=1; j<=nlstate+ndeath;j++) { */
                   9715: /*           kk1=0.;kk2=0; */
                   9716: /*           for(i=1; i<=nlstate;i++) {               */
                   9717: /*             kk1=kk1+p3mat[i][j][h]*tabpopprev[(int)agedeb+1][i][cptcod];     */
                   9718: /*           } */
                   9719: /*           if (h==(int)(calagedatem+12*cpt)) fprintf(ficresf," %15.2f", kk1);         */
                   9720: /*         } */
                   9721: /*       } */
                   9722: /*       free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm); */
                   9723: /*     } */
                   9724: /*       } */
                   9725: /*     }  */
                   9726: /*   } */
1.218     brouard  9727:   
1.227     brouard  9728: /*   /\* if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX); *\/ */
1.218     brouard  9729:   
1.227     brouard  9730: /*   if (popforecast==1) { */
                   9731: /*     free_ivector(popage,0,AGESUP); */
                   9732: /*     free_vector(popeffectif,0,AGESUP); */
                   9733: /*     free_vector(popcount,0,AGESUP); */
                   9734: /*   } */
                   9735: /*   free_ma3x(tabpop,1, AGESUP,1,NCOVMAX, 1,NCOVMAX); */
                   9736: /*   free_ma3x(tabpopprev,1, AGESUP,1,NCOVMAX, 1,NCOVMAX); */
                   9737: /*   fclose(ficrespop); */
                   9738: /* } /\* End of popforecast *\/ */
1.218     brouard  9739:  
1.126     brouard  9740: int fileappend(FILE *fichier, char *optionfich)
                   9741: {
                   9742:   if((fichier=fopen(optionfich,"a"))==NULL) {
                   9743:     printf("Problem with file: %s\n", optionfich);
                   9744:     fprintf(ficlog,"Problem with file: %s\n", optionfich);
                   9745:     return (0);
                   9746:   }
                   9747:   fflush(fichier);
                   9748:   return (1);
                   9749: }
                   9750: 
                   9751: 
                   9752: /**************** function prwizard **********************/
                   9753: void prwizard(int ncovmodel, int nlstate, int ndeath,  char model[], FILE *ficparo)
                   9754: {
                   9755: 
                   9756:   /* Wizard to print covariance matrix template */
                   9757: 
1.164     brouard  9758:   char ca[32], cb[32];
                   9759:   int i,j, k, li, lj, lk, ll, jj, npar, itimes;
1.126     brouard  9760:   int numlinepar;
                   9761: 
                   9762:   printf("# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
                   9763:   fprintf(ficparo,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
                   9764:   for(i=1; i <=nlstate; i++){
                   9765:     jj=0;
                   9766:     for(j=1; j <=nlstate+ndeath; j++){
                   9767:       if(j==i) continue;
                   9768:       jj++;
                   9769:       /*ca[0]= k+'a'-1;ca[1]='\0';*/
                   9770:       printf("%1d%1d",i,j);
                   9771:       fprintf(ficparo,"%1d%1d",i,j);
                   9772:       for(k=1; k<=ncovmodel;k++){
                   9773:        /*        printf(" %lf",param[i][j][k]); */
                   9774:        /*        fprintf(ficparo," %lf",param[i][j][k]); */
                   9775:        printf(" 0.");
                   9776:        fprintf(ficparo," 0.");
                   9777:       }
                   9778:       printf("\n");
                   9779:       fprintf(ficparo,"\n");
                   9780:     }
                   9781:   }
                   9782:   printf("# Scales (for hessian or gradient estimation)\n");
                   9783:   fprintf(ficparo,"# Scales (for hessian or gradient estimation)\n");
                   9784:   npar= (nlstate+ndeath-1)*nlstate*ncovmodel; /* Number of parameters*/ 
                   9785:   for(i=1; i <=nlstate; i++){
                   9786:     jj=0;
                   9787:     for(j=1; j <=nlstate+ndeath; j++){
                   9788:       if(j==i) continue;
                   9789:       jj++;
                   9790:       fprintf(ficparo,"%1d%1d",i,j);
                   9791:       printf("%1d%1d",i,j);
                   9792:       fflush(stdout);
                   9793:       for(k=1; k<=ncovmodel;k++){
                   9794:        /*      printf(" %le",delti3[i][j][k]); */
                   9795:        /*      fprintf(ficparo," %le",delti3[i][j][k]); */
                   9796:        printf(" 0.");
                   9797:        fprintf(ficparo," 0.");
                   9798:       }
                   9799:       numlinepar++;
                   9800:       printf("\n");
                   9801:       fprintf(ficparo,"\n");
                   9802:     }
                   9803:   }
                   9804:   printf("# Covariance matrix\n");
                   9805: /* # 121 Var(a12)\n\ */
                   9806: /* # 122 Cov(b12,a12) Var(b12)\n\ */
                   9807: /* # 131 Cov(a13,a12) Cov(a13,b12, Var(a13)\n\ */
                   9808: /* # 132 Cov(b13,a12) Cov(b13,b12, Cov(b13,a13) Var(b13)\n\ */
                   9809: /* # 212 Cov(a21,a12) Cov(a21,b12, Cov(a21,a13) Cov(a21,b13) Var(a21)\n\ */
                   9810: /* # 212 Cov(b21,a12) Cov(b21,b12, Cov(b21,a13) Cov(b21,b13) Cov(b21,a21) Var(b21)\n\ */
                   9811: /* # 232 Cov(a23,a12) Cov(a23,b12, Cov(a23,a13) Cov(a23,b13) Cov(a23,a21) Cov(a23,b21) Var(a23)\n\ */
                   9812: /* # 232 Cov(b23,a12) Cov(b23,b12) ... Var (b23)\n" */
                   9813:   fflush(stdout);
                   9814:   fprintf(ficparo,"# Covariance matrix\n");
                   9815:   /* # 121 Var(a12)\n\ */
                   9816:   /* # 122 Cov(b12,a12) Var(b12)\n\ */
                   9817:   /* #   ...\n\ */
                   9818:   /* # 232 Cov(b23,a12)  Cov(b23,b12) ... Var (b23)\n" */
                   9819:   
                   9820:   for(itimes=1;itimes<=2;itimes++){
                   9821:     jj=0;
                   9822:     for(i=1; i <=nlstate; i++){
                   9823:       for(j=1; j <=nlstate+ndeath; j++){
                   9824:        if(j==i) continue;
                   9825:        for(k=1; k<=ncovmodel;k++){
                   9826:          jj++;
                   9827:          ca[0]= k+'a'-1;ca[1]='\0';
                   9828:          if(itimes==1){
                   9829:            printf("#%1d%1d%d",i,j,k);
                   9830:            fprintf(ficparo,"#%1d%1d%d",i,j,k);
                   9831:          }else{
                   9832:            printf("%1d%1d%d",i,j,k);
                   9833:            fprintf(ficparo,"%1d%1d%d",i,j,k);
                   9834:            /*  printf(" %.5le",matcov[i][j]); */
                   9835:          }
                   9836:          ll=0;
                   9837:          for(li=1;li <=nlstate; li++){
                   9838:            for(lj=1;lj <=nlstate+ndeath; lj++){
                   9839:              if(lj==li) continue;
                   9840:              for(lk=1;lk<=ncovmodel;lk++){
                   9841:                ll++;
                   9842:                if(ll<=jj){
                   9843:                  cb[0]= lk +'a'-1;cb[1]='\0';
                   9844:                  if(ll<jj){
                   9845:                    if(itimes==1){
                   9846:                      printf(" Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
                   9847:                      fprintf(ficparo," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
                   9848:                    }else{
                   9849:                      printf(" 0.");
                   9850:                      fprintf(ficparo," 0.");
                   9851:                    }
                   9852:                  }else{
                   9853:                    if(itimes==1){
                   9854:                      printf(" Var(%s%1d%1d)",ca,i,j);
                   9855:                      fprintf(ficparo," Var(%s%1d%1d)",ca,i,j);
                   9856:                    }else{
                   9857:                      printf(" 0.");
                   9858:                      fprintf(ficparo," 0.");
                   9859:                    }
                   9860:                  }
                   9861:                }
                   9862:              } /* end lk */
                   9863:            } /* end lj */
                   9864:          } /* end li */
                   9865:          printf("\n");
                   9866:          fprintf(ficparo,"\n");
                   9867:          numlinepar++;
                   9868:        } /* end k*/
                   9869:       } /*end j */
                   9870:     } /* end i */
                   9871:   } /* end itimes */
                   9872: 
                   9873: } /* end of prwizard */
                   9874: /******************* Gompertz Likelihood ******************************/
                   9875: double gompertz(double x[])
                   9876: { 
1.302     brouard  9877:   double A=0.0,B=0.,L=0.0,sump=0.,num=0.;
1.126     brouard  9878:   int i,n=0; /* n is the size of the sample */
                   9879: 
1.220     brouard  9880:   for (i=1;i<=imx ; i++) {
1.126     brouard  9881:     sump=sump+weight[i];
                   9882:     /*    sump=sump+1;*/
                   9883:     num=num+1;
                   9884:   }
1.302     brouard  9885:   L=0.0;
                   9886:   /* agegomp=AGEGOMP; */
1.126     brouard  9887:   /* for (i=0; i<=imx; i++) 
                   9888:      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]);*/
                   9889: 
1.302     brouard  9890:   for (i=1;i<=imx ; i++) {
                   9891:     /* mu(a)=mu(agecomp)*exp(teta*(age-agegomp))
                   9892:        mu(a)=x[1]*exp(x[2]*(age-agegomp)); x[1] and x[2] are per year.
                   9893:      * L= Product mu(agedeces)exp(-\int_ageexam^agedc mu(u) du ) for a death between agedc (in month) 
                   9894:      *   and agedc +1 month, cens[i]=0: log(x[1]/YEARM)
                   9895:      * +
                   9896:      * exp(-\int_ageexam^agecens mu(u) du ) when censored, cens[i]=1
                   9897:      */
                   9898:      if (wav[i] > 1 || agedc[i] < AGESUP) {
                   9899:        if (cens[i] == 1){
                   9900:         A=-x[1]/(x[2])*(exp(x[2]*(agecens[i]-agegomp))-exp(x[2]*(ageexmed[i]-agegomp)));
                   9901:        } else if (cens[i] == 0){
1.126     brouard  9902:        A=-x[1]/(x[2])*(exp(x[2]*(agedc[i]-agegomp))-exp(x[2]*(ageexmed[i]-agegomp)))
1.302     brouard  9903:          +log(x[1]/YEARM) +x[2]*(agedc[i]-agegomp)+log(YEARM);
                   9904:       } else
                   9905:         printf("Gompertz cens[%d] neither 1 nor 0\n",i);
1.126     brouard  9906:       /*if (wav[i] > 1 && agecens[i] > 15) {*/ /* ??? */
1.302     brouard  9907:        L=L+A*weight[i];
1.126     brouard  9908:        /*      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  9909:      }
                   9910:   }
1.126     brouard  9911: 
1.302     brouard  9912:   /*printf("x1=%2.9f x2=%2.9f x3=%2.9f L=%f\n",x[1],x[2],x[3],L);*/
1.126     brouard  9913:  
                   9914:   return -2*L*num/sump;
                   9915: }
                   9916: 
1.136     brouard  9917: #ifdef GSL
                   9918: /******************* Gompertz_f Likelihood ******************************/
                   9919: double gompertz_f(const gsl_vector *v, void *params)
                   9920: { 
1.302     brouard  9921:   double A=0.,B=0.,LL=0.0,sump=0.,num=0.;
1.136     brouard  9922:   double *x= (double *) v->data;
                   9923:   int i,n=0; /* n is the size of the sample */
                   9924: 
                   9925:   for (i=0;i<=imx-1 ; i++) {
                   9926:     sump=sump+weight[i];
                   9927:     /*    sump=sump+1;*/
                   9928:     num=num+1;
                   9929:   }
                   9930:  
                   9931:  
                   9932:   /* for (i=0; i<=imx; i++) 
                   9933:      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]);*/
                   9934:   printf("x[0]=%lf x[1]=%lf\n",x[0],x[1]);
                   9935:   for (i=1;i<=imx ; i++)
                   9936:     {
                   9937:       if (cens[i] == 1 && wav[i]>1)
                   9938:        A=-x[0]/(x[1])*(exp(x[1]*(agecens[i]-agegomp))-exp(x[1]*(ageexmed[i]-agegomp)));
                   9939:       
                   9940:       if (cens[i] == 0 && wav[i]>1)
                   9941:        A=-x[0]/(x[1])*(exp(x[1]*(agedc[i]-agegomp))-exp(x[1]*(ageexmed[i]-agegomp)))
                   9942:             +log(x[0]/YEARM)+x[1]*(agedc[i]-agegomp)+log(YEARM);  
                   9943:       
                   9944:       /*if (wav[i] > 1 && agecens[i] > 15) {*/ /* ??? */
                   9945:       if (wav[i] > 1 ) { /* ??? */
                   9946:        LL=LL+A*weight[i];
                   9947:        /*      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]);*/
                   9948:       }
                   9949:     }
                   9950: 
                   9951:  /*printf("x1=%2.9f x2=%2.9f x3=%2.9f L=%f\n",x[1],x[2],x[3],L);*/
                   9952:   printf("x[0]=%lf x[1]=%lf -2*LL*num/sump=%lf\n",x[0],x[1],-2*LL*num/sump);
                   9953:  
                   9954:   return -2*LL*num/sump;
                   9955: }
                   9956: #endif
                   9957: 
1.126     brouard  9958: /******************* Printing html file ***********/
1.201     brouard  9959: void printinghtmlmort(char fileresu[], char title[], char datafile[], int firstpass, \
1.126     brouard  9960:                  int lastpass, int stepm, int weightopt, char model[],\
                   9961:                  int imx,  double p[],double **matcov,double agemortsup){
                   9962:   int i,k;
                   9963: 
                   9964:   fprintf(fichtm,"<ul><li><h4>Result files </h4>\n Force of mortality. Parameters of the Gompertz fit (with confidence interval in brackets):<br>");
                   9965:   fprintf(fichtm,"  mu(age) =%lf*exp(%lf*(age-%d)) per year<br><br>",p[1],p[2],agegomp);
                   9966:   for (i=1;i<=2;i++) 
                   9967:     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  9968:   fprintf(fichtm,"<br><br><img src=\"graphmort.svg\">");
1.126     brouard  9969:   fprintf(fichtm,"</ul>");
                   9970: 
                   9971: fprintf(fichtm,"<ul><li><h4>Life table</h4>\n <br>");
                   9972: 
                   9973:  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>");
                   9974: 
                   9975:  for (k=agegomp;k<(agemortsup-2);k++) 
                   9976:    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]);
                   9977: 
                   9978:  
                   9979:   fflush(fichtm);
                   9980: }
                   9981: 
                   9982: /******************* Gnuplot file **************/
1.201     brouard  9983: void printinggnuplotmort(char fileresu[], char optionfilefiname[], double ageminpar, double agemaxpar, double fage , char pathc[], double p[]){
1.126     brouard  9984: 
                   9985:   char dirfileres[132],optfileres[132];
1.164     brouard  9986: 
1.126     brouard  9987:   int ng;
                   9988: 
                   9989: 
                   9990:   /*#ifdef windows */
                   9991:   fprintf(ficgp,"cd \"%s\" \n",pathc);
                   9992:     /*#endif */
                   9993: 
                   9994: 
                   9995:   strcpy(dirfileres,optionfilefiname);
                   9996:   strcpy(optfileres,"vpl");
1.199     brouard  9997:   fprintf(ficgp,"set out \"graphmort.svg\"\n "); 
1.126     brouard  9998:   fprintf(ficgp,"set xlabel \"Age\"\n set ylabel \"Force of mortality (per year)\" \n "); 
1.199     brouard  9999:   fprintf(ficgp, "set ter svg size 640, 480\n set log y\n"); 
1.145     brouard  10000:   /* fprintf(ficgp, "set size 0.65,0.65\n"); */
1.126     brouard  10001:   fprintf(ficgp,"plot [%d:100] %lf*exp(%lf*(x-%d))",agegomp,p[1],p[2],agegomp);
                   10002: 
                   10003: } 
                   10004: 
1.136     brouard  10005: int readdata(char datafile[], int firstobs, int lastobs, int *imax)
                   10006: {
1.126     brouard  10007: 
1.136     brouard  10008:   /*-------- data file ----------*/
                   10009:   FILE *fic;
                   10010:   char dummy[]="                         ";
1.240     brouard  10011:   int i=0, j=0, n=0, iv=0, v;
1.223     brouard  10012:   int lstra;
1.136     brouard  10013:   int linei, month, year,iout;
1.302     brouard  10014:   int noffset=0; /* This is the offset if BOM data file */
1.136     brouard  10015:   char line[MAXLINE], linetmp[MAXLINE];
1.164     brouard  10016:   char stra[MAXLINE], strb[MAXLINE];
1.136     brouard  10017:   char *stratrunc;
1.223     brouard  10018: 
1.240     brouard  10019:   DummyV=ivector(1,NCOVMAX); /* 1 to 3 */
                   10020:   FixedV=ivector(1,NCOVMAX); /* 1 to 3 */
1.328     brouard  10021:   for(v=1;v<NCOVMAX;v++){
                   10022:     DummyV[v]=0;
                   10023:     FixedV[v]=0;
                   10024:   }
1.126     brouard  10025: 
1.240     brouard  10026:   for(v=1; v <=ncovcol;v++){
                   10027:     DummyV[v]=0;
                   10028:     FixedV[v]=0;
                   10029:   }
                   10030:   for(v=ncovcol+1; v <=ncovcol+nqv;v++){
                   10031:     DummyV[v]=1;
                   10032:     FixedV[v]=0;
                   10033:   }
                   10034:   for(v=ncovcol+nqv+1; v <=ncovcol+nqv+ntv;v++){
                   10035:     DummyV[v]=0;
                   10036:     FixedV[v]=1;
                   10037:   }
                   10038:   for(v=ncovcol+nqv+ntv+1; v <=ncovcol+nqv+ntv+nqtv;v++){
                   10039:     DummyV[v]=1;
                   10040:     FixedV[v]=1;
                   10041:   }
                   10042:   for(v=1; v <=ncovcol+nqv+ntv+nqtv;v++){
                   10043:     printf("Covariate type in the data: V%d, DummyV(V%d)=%d, FixedV(V%d)=%d\n",v,v,DummyV[v],v,FixedV[v]);
                   10044:     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]);
                   10045:   }
1.126     brouard  10046: 
1.136     brouard  10047:   if((fic=fopen(datafile,"r"))==NULL)    {
1.218     brouard  10048:     printf("Problem while opening datafile: %s with errno='%s'\n", datafile,strerror(errno));fflush(stdout);
                   10049:     fprintf(ficlog,"Problem while opening datafile: %s with errno='%s'\n", datafile,strerror(errno));fflush(ficlog);return 1;
1.136     brouard  10050:   }
1.126     brouard  10051: 
1.302     brouard  10052:     /* Is it a BOM UTF-8 Windows file? */
                   10053:   /* First data line */
                   10054:   linei=0;
                   10055:   while(fgets(line, MAXLINE, fic)) {
                   10056:     noffset=0;
                   10057:     if( line[0] == (char)0xEF && line[1] == (char)0xBB) /* EF BB BF */
                   10058:     {
                   10059:       noffset=noffset+3;
                   10060:       printf("# Data file '%s'  is an UTF8 BOM file, please convert to UTF8 or ascii file and rerun.\n",datafile);fflush(stdout);
                   10061:       fprintf(ficlog,"# Data file '%s'  is an UTF8 BOM file, please convert to UTF8 or ascii file and rerun.\n",datafile);
                   10062:       fflush(ficlog); return 1;
                   10063:     }
                   10064:     /*    else if( line[0] == (char)0xFE && line[1] == (char)0xFF)*/
                   10065:     else if( line[0] == (char)0xFF && line[1] == (char)0xFE)
                   10066:     {
                   10067:       noffset=noffset+2;
1.304     brouard  10068:       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);
                   10069:       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  10070:       fflush(ficlog); return 1;
                   10071:     }
                   10072:     else if( line[0] == 0 && line[1] == 0)
                   10073:     {
                   10074:       if( line[2] == (char)0xFE && line[3] == (char)0xFF){
                   10075:        noffset=noffset+4;
1.304     brouard  10076:        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);
                   10077:        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  10078:        fflush(ficlog); return 1;
                   10079:       }
                   10080:     } else{
                   10081:       ;/*printf(" Not a BOM file\n");*/
                   10082:     }
                   10083:         /* If line starts with a # it is a comment */
                   10084:     if (line[noffset] == '#') {
                   10085:       linei=linei+1;
                   10086:       break;
                   10087:     }else{
                   10088:       break;
                   10089:     }
                   10090:   }
                   10091:   fclose(fic);
                   10092:   if((fic=fopen(datafile,"r"))==NULL)    {
                   10093:     printf("Problem while opening datafile: %s with errno='%s'\n", datafile,strerror(errno));fflush(stdout);
                   10094:     fprintf(ficlog,"Problem while opening datafile: %s with errno='%s'\n", datafile,strerror(errno));fflush(ficlog);return 1;
                   10095:   }
                   10096:   /* Not a Bom file */
                   10097:   
1.136     brouard  10098:   i=1;
                   10099:   while ((fgets(line, MAXLINE, fic) != NULL) &&((i >= firstobs) && (i <=lastobs))) {
                   10100:     linei=linei+1;
                   10101:     for(j=strlen(line); j>=0;j--){  /* Untabifies line */
                   10102:       if(line[j] == '\t')
                   10103:        line[j] = ' ';
                   10104:     }
                   10105:     for(j=strlen(line)-1; (line[j]==' ')||(line[j]==10)||(line[j]==13);j--){
                   10106:       ;
                   10107:     };
                   10108:     line[j+1]=0;  /* Trims blanks at end of line */
                   10109:     if(line[0]=='#'){
                   10110:       fprintf(ficlog,"Comment line\n%s\n",line);
                   10111:       printf("Comment line\n%s\n",line);
                   10112:       continue;
                   10113:     }
                   10114:     trimbb(linetmp,line); /* Trims multiple blanks in line */
1.164     brouard  10115:     strcpy(line, linetmp);
1.223     brouard  10116:     
                   10117:     /* Loops on waves */
                   10118:     for (j=maxwav;j>=1;j--){
                   10119:       for (iv=nqtv;iv>=1;iv--){  /* Loop  on time varying quantitative variables */
1.238     brouard  10120:        cutv(stra, strb, line, ' '); 
                   10121:        if(strb[0]=='.') { /* Missing value */
                   10122:          lval=-1;
                   10123:          cotqvar[j][iv][i]=-1; /* 0.0/0.0 */
                   10124:          cotvar[j][ntv+iv][i]=-1; /* For performance reasons */
                   10125:          if(isalpha(strb[1])) { /* .m or .d Really Missing value */
                   10126:            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);
                   10127:            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);
                   10128:            return 1;
                   10129:          }
                   10130:        }else{
                   10131:          errno=0;
                   10132:          /* what_kind_of_number(strb); */
                   10133:          dval=strtod(strb,&endptr); 
                   10134:          /* if( strb[0]=='\0' || (*endptr != '\0')){ */
                   10135:          /* if(strb != endptr && *endptr == '\0') */
                   10136:          /*    dval=dlval; */
                   10137:          /* if (errno == ERANGE && (lval == LONG_MAX || lval == LONG_MIN)) */
                   10138:          if( strb[0]=='\0' || (*endptr != '\0')){
                   10139:            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);
                   10140:            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);
                   10141:            return 1;
                   10142:          }
                   10143:          cotqvar[j][iv][i]=dval; 
                   10144:          cotvar[j][ntv+iv][i]=dval; 
                   10145:        }
                   10146:        strcpy(line,stra);
1.223     brouard  10147:       }/* end loop ntqv */
1.225     brouard  10148:       
1.223     brouard  10149:       for (iv=ntv;iv>=1;iv--){  /* Loop  on time varying dummies */
1.238     brouard  10150:        cutv(stra, strb, line, ' '); 
                   10151:        if(strb[0]=='.') { /* Missing value */
                   10152:          lval=-1;
                   10153:        }else{
                   10154:          errno=0;
                   10155:          lval=strtol(strb,&endptr,10); 
                   10156:          /*    if (errno == ERANGE && (lval == LONG_MAX || lval == LONG_MIN))*/
                   10157:          if( strb[0]=='\0' || (*endptr != '\0')){
                   10158:            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);
                   10159:            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);
                   10160:            return 1;
                   10161:          }
                   10162:        }
                   10163:        if(lval <-1 || lval >1){
                   10164:          printf("Error reading data around '%ld' at line number %d for individual %d, '%s'\n \
1.319     brouard  10165:  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  10166:  for the alternative. IMaCh does not build design variables automatically, do it yourself.\n \
1.238     brouard  10167:  For example, for multinomial values like 1, 2 and 3,\n                        \
                   10168:  build V1=0 V2=0 for the reference value (1),\n                                \
                   10169:         V1=1 V2=0 for (2) \n                                           \
1.223     brouard  10170:  and V1=0 V2=1 for (3). V1=1 V2=1 should not exist and the corresponding\n \
1.238     brouard  10171:  output of IMaCh is often meaningless.\n                               \
1.319     brouard  10172:  Exiting.\n",lval,linei, i,line,iv,j);
1.238     brouard  10173:          fprintf(ficlog,"Error reading data around '%ld' at line number %d for individual %d, '%s'\n \
1.319     brouard  10174:  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  10175:  for the alternative. IMaCh does not build design variables automatically, do it yourself.\n \
1.238     brouard  10176:  For example, for multinomial values like 1, 2 and 3,\n                        \
                   10177:  build V1=0 V2=0 for the reference value (1),\n                                \
                   10178:         V1=1 V2=0 for (2) \n                                           \
1.223     brouard  10179:  and V1=0 V2=1 for (3). V1=1 V2=1 should not exist and the corresponding\n \
1.238     brouard  10180:  output of IMaCh is often meaningless.\n                               \
1.319     brouard  10181:  Exiting.\n",lval,linei, i,line,iv,j);fflush(ficlog);
1.238     brouard  10182:          return 1;
                   10183:        }
                   10184:        cotvar[j][iv][i]=(double)(lval);
                   10185:        strcpy(line,stra);
1.223     brouard  10186:       }/* end loop ntv */
1.225     brouard  10187:       
1.223     brouard  10188:       /* Statuses  at wave */
1.137     brouard  10189:       cutv(stra, strb, line, ' '); 
1.223     brouard  10190:       if(strb[0]=='.') { /* Missing value */
1.238     brouard  10191:        lval=-1;
1.136     brouard  10192:       }else{
1.238     brouard  10193:        errno=0;
                   10194:        lval=strtol(strb,&endptr,10); 
                   10195:        /*      if (errno == ERANGE && (lval == LONG_MAX || lval == LONG_MIN))*/
                   10196:        if( strb[0]=='\0' || (*endptr != '\0')){
                   10197:          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);
                   10198:          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);
                   10199:          return 1;
                   10200:        }
1.136     brouard  10201:       }
1.225     brouard  10202:       
1.136     brouard  10203:       s[j][i]=lval;
1.225     brouard  10204:       
1.223     brouard  10205:       /* Date of Interview */
1.136     brouard  10206:       strcpy(line,stra);
                   10207:       cutv(stra, strb,line,' ');
1.169     brouard  10208:       if( (iout=sscanf(strb,"%d/%d",&month, &year)) != 0){
1.136     brouard  10209:       }
1.169     brouard  10210:       else  if( (iout=sscanf(strb,"%s.",dummy)) != 0){
1.225     brouard  10211:        month=99;
                   10212:        year=9999;
1.136     brouard  10213:       }else{
1.225     brouard  10214:        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);
                   10215:        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);
                   10216:        return 1;
1.136     brouard  10217:       }
                   10218:       anint[j][i]= (double) year; 
1.302     brouard  10219:       mint[j][i]= (double)month;
                   10220:       /* if( (int)anint[j][i]+ (int)(mint[j][i])/12. < (int) (moisnais[i]/12.+annais[i])){ */
                   10221:       /*       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]); */
                   10222:       /*       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]); */
                   10223:       /* } */
1.136     brouard  10224:       strcpy(line,stra);
1.223     brouard  10225:     } /* End loop on waves */
1.225     brouard  10226:     
1.223     brouard  10227:     /* Date of death */
1.136     brouard  10228:     cutv(stra, strb,line,' '); 
1.169     brouard  10229:     if( (iout=sscanf(strb,"%d/%d",&month, &year)) != 0){
1.136     brouard  10230:     }
1.169     brouard  10231:     else  if( (iout=sscanf(strb,"%s.",dummy)) != 0){
1.136     brouard  10232:       month=99;
                   10233:       year=9999;
                   10234:     }else{
1.141     brouard  10235:       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  10236:       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);
                   10237:       return 1;
1.136     brouard  10238:     }
                   10239:     andc[i]=(double) year; 
                   10240:     moisdc[i]=(double) month; 
                   10241:     strcpy(line,stra);
                   10242:     
1.223     brouard  10243:     /* Date of birth */
1.136     brouard  10244:     cutv(stra, strb,line,' '); 
1.169     brouard  10245:     if( (iout=sscanf(strb,"%d/%d",&month, &year)) != 0){
1.136     brouard  10246:     }
1.169     brouard  10247:     else  if( (iout=sscanf(strb,"%s.", dummy)) != 0){
1.136     brouard  10248:       month=99;
                   10249:       year=9999;
                   10250:     }else{
1.141     brouard  10251:       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);
                   10252:       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  10253:       return 1;
1.136     brouard  10254:     }
                   10255:     if (year==9999) {
1.141     brouard  10256:       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);
                   10257:       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  10258:       return 1;
                   10259:       
1.136     brouard  10260:     }
                   10261:     annais[i]=(double)(year);
1.302     brouard  10262:     moisnais[i]=(double)(month);
                   10263:     for (j=1;j<=maxwav;j++){
                   10264:       if( (int)anint[j][i]+ (int)(mint[j][i])/12. < (int) (moisnais[i]/12.+annais[i])){
                   10265:        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]);
                   10266:        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]);
                   10267:       }
                   10268:     }
                   10269: 
1.136     brouard  10270:     strcpy(line,stra);
1.225     brouard  10271:     
1.223     brouard  10272:     /* Sample weight */
1.136     brouard  10273:     cutv(stra, strb,line,' '); 
                   10274:     errno=0;
                   10275:     dval=strtod(strb,&endptr); 
                   10276:     if( strb[0]=='\0' || (*endptr != '\0')){
1.141     brouard  10277:       printf("Error reading data around '%f' at line number %d, \"%s\" for individual %d\nShould be a weight.  Exiting.\n",dval, i,line,linei);
                   10278:       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  10279:       fflush(ficlog);
                   10280:       return 1;
                   10281:     }
                   10282:     weight[i]=dval; 
                   10283:     strcpy(line,stra);
1.225     brouard  10284:     
1.223     brouard  10285:     for (iv=nqv;iv>=1;iv--){  /* Loop  on fixed quantitative variables */
                   10286:       cutv(stra, strb, line, ' '); 
                   10287:       if(strb[0]=='.') { /* Missing value */
1.225     brouard  10288:        lval=-1;
1.311     brouard  10289:        coqvar[iv][i]=NAN; 
                   10290:        covar[ncovcol+iv][i]=NAN; /* including qvar in standard covar for performance reasons */ 
1.223     brouard  10291:       }else{
1.225     brouard  10292:        errno=0;
                   10293:        /* what_kind_of_number(strb); */
                   10294:        dval=strtod(strb,&endptr);
                   10295:        /* if(strb != endptr && *endptr == '\0') */
                   10296:        /*   dval=dlval; */
                   10297:        /* if (errno == ERANGE && (lval == LONG_MAX || lval == LONG_MIN)) */
                   10298:        if( strb[0]=='\0' || (*endptr != '\0')){
                   10299:          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);
                   10300:          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);
                   10301:          return 1;
                   10302:        }
                   10303:        coqvar[iv][i]=dval; 
1.226     brouard  10304:        covar[ncovcol+iv][i]=dval; /* including qvar in standard covar for performance reasons */ 
1.223     brouard  10305:       }
                   10306:       strcpy(line,stra);
                   10307:     }/* end loop nqv */
1.136     brouard  10308:     
1.223     brouard  10309:     /* Covariate values */
1.136     brouard  10310:     for (j=ncovcol;j>=1;j--){
                   10311:       cutv(stra, strb,line,' '); 
1.223     brouard  10312:       if(strb[0]=='.') { /* Missing covariate value */
1.225     brouard  10313:        lval=-1;
1.136     brouard  10314:       }else{
1.225     brouard  10315:        errno=0;
                   10316:        lval=strtol(strb,&endptr,10); 
                   10317:        if( strb[0]=='\0' || (*endptr != '\0')){
                   10318:          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);
                   10319:          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);
                   10320:          return 1;
                   10321:        }
1.136     brouard  10322:       }
                   10323:       if(lval <-1 || lval >1){
1.225     brouard  10324:        printf("Error reading data around '%ld' at line number %d for individual %d, '%s'\n \
1.136     brouard  10325:  Should be a value of %d(nth) covariate (0 should be the value for the reference and 1\n \
                   10326:  for the alternative. IMaCh does not build design variables automatically, do it yourself.\n \
1.225     brouard  10327:  For example, for multinomial values like 1, 2 and 3,\n                        \
                   10328:  build V1=0 V2=0 for the reference value (1),\n                                \
                   10329:         V1=1 V2=0 for (2) \n                                           \
1.136     brouard  10330:  and V1=0 V2=1 for (3). V1=1 V2=1 should not exist and the corresponding\n \
1.225     brouard  10331:  output of IMaCh is often meaningless.\n                               \
1.136     brouard  10332:  Exiting.\n",lval,linei, i,line,j);
1.225     brouard  10333:        fprintf(ficlog,"Error reading data around '%ld' at line number %d for individual %d, '%s'\n \
1.136     brouard  10334:  Should be a value of %d(nth) covariate (0 should be the value for the reference and 1\n \
                   10335:  for the alternative. IMaCh does not build design variables automatically, do it yourself.\n \
1.225     brouard  10336:  For example, for multinomial values like 1, 2 and 3,\n                        \
                   10337:  build V1=0 V2=0 for the reference value (1),\n                                \
                   10338:         V1=1 V2=0 for (2) \n                                           \
1.136     brouard  10339:  and V1=0 V2=1 for (3). V1=1 V2=1 should not exist and the corresponding\n \
1.225     brouard  10340:  output of IMaCh is often meaningless.\n                               \
1.136     brouard  10341:  Exiting.\n",lval,linei, i,line,j);fflush(ficlog);
1.225     brouard  10342:        return 1;
1.136     brouard  10343:       }
                   10344:       covar[j][i]=(double)(lval);
                   10345:       strcpy(line,stra);
                   10346:     }  
                   10347:     lstra=strlen(stra);
1.225     brouard  10348:     
1.136     brouard  10349:     if(lstra > 9){ /* More than 2**32 or max of what printf can write with %ld */
                   10350:       stratrunc = &(stra[lstra-9]);
                   10351:       num[i]=atol(stratrunc);
                   10352:     }
                   10353:     else
                   10354:       num[i]=atol(stra);
                   10355:     /*if((s[2][i]==2) && (s[3][i]==-1)&&(s[4][i]==9)){
                   10356:       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;}*/
                   10357:     
                   10358:     i=i+1;
                   10359:   } /* End loop reading  data */
1.225     brouard  10360:   
1.136     brouard  10361:   *imax=i-1; /* Number of individuals */
                   10362:   fclose(fic);
1.225     brouard  10363:   
1.136     brouard  10364:   return (0);
1.164     brouard  10365:   /* endread: */
1.225     brouard  10366:   printf("Exiting readdata: ");
                   10367:   fclose(fic);
                   10368:   return (1);
1.223     brouard  10369: }
1.126     brouard  10370: 
1.234     brouard  10371: void removefirstspace(char **stri){/*, char stro[]) {*/
1.230     brouard  10372:   char *p1 = *stri, *p2 = *stri;
1.235     brouard  10373:   while (*p2 == ' ')
1.234     brouard  10374:     p2++; 
                   10375:   /* while ((*p1++ = *p2++) !=0) */
                   10376:   /*   ; */
                   10377:   /* do */
                   10378:   /*   while (*p2 == ' ') */
                   10379:   /*     p2++; */
                   10380:   /* while (*p1++ == *p2++); */
                   10381:   *stri=p2; 
1.145     brouard  10382: }
                   10383: 
1.330     brouard  10384: int decoderesult( char resultline[], int nres)
1.230     brouard  10385: /**< This routine decode one result line and returns the combination # of dummy covariates only **/
                   10386: {
1.235     brouard  10387:   int j=0, k=0, k1=0, k2=0, k3=0, k4=0, match=0, k2q=0, k3q=0, k4q=0;
1.230     brouard  10388:   char resultsav[MAXLINE];
1.330     brouard  10389:   /* int resultmodel[MAXLINE]; */
1.334     brouard  10390:   /* int modelresult[MAXLINE]; */
1.230     brouard  10391:   char stra[80], strb[80], strc[80], strd[80],stre[80];
                   10392: 
1.234     brouard  10393:   removefirstspace(&resultline);
1.332     brouard  10394:   printf("decoderesult:%s\n",resultline);
1.230     brouard  10395: 
1.332     brouard  10396:   strcpy(resultsav,resultline);
                   10397:   printf("Decoderesult resultsav=\"%s\" resultline=\"%s\"\n", resultsav, resultline);
1.230     brouard  10398:   if (strlen(resultsav) >1){
1.334     brouard  10399:     j=nbocc(resultsav,'='); /**< j=Number of covariate values'=' in this resultline */
1.230     brouard  10400:   }
1.253     brouard  10401:   if(j == 0){ /* Resultline but no = */
                   10402:     TKresult[nres]=0; /* Combination for the nresult and the model */
                   10403:     return (0);
                   10404:   }
1.234     brouard  10405:   if( j != cptcovs ){ /* Be careful if a variable is in a product but not single */
1.334     brouard  10406:     printf("ERROR: the number of variables in the resultline which is %d, differs from the number %d of single variables used in the model line, %s.\n",j, cptcovs, model);
                   10407:     fprintf(ficlog,"ERROR: the number of variables in the resultline which is %d, differs from the number %d of single variables used in the model line, %s.\n",j, cptcovs, model);
1.332     brouard  10408:     /* return 1;*/
1.234     brouard  10409:   }
1.334     brouard  10410:   for(k=1; k<=j;k++){ /* Loop on any covariate of the RESULT LINE */
1.234     brouard  10411:     if(nbocc(resultsav,'=') >1){
1.318     brouard  10412:       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" */
1.332     brouard  10413:       /* If resultsav= "V4= 1 V5=25.1 V3=0" with a blank then strb="V4=" and stra="1 V5=25.1 V3=0" */
1.318     brouard  10414:       cutl(strc,strd,strb,'=');  /* strb:"V4=1" strc="1" strd="V4" */
1.332     brouard  10415:       /* If a blank, then strc="V4=" and strd='\0' */
                   10416:       if(strc[0]=='\0'){
                   10417:       printf("Error in resultline, probably a blank after the \"%s\", \"result:%s\", stra=\"%s\" resultsav=\"%s\"\n",strb,resultline, stra, resultsav);
                   10418:        fprintf(ficlog,"Error in resultline, probably a blank after the \"V%s=\", resultline=%s\n",strb,resultline);
                   10419:        return 1;
                   10420:       }
1.234     brouard  10421:     }else
                   10422:       cutl(strc,strd,resultsav,'=');
1.318     brouard  10423:     Tvalsel[k]=atof(strc); /* 1 */ /* Tvalsel of k is the float value of the kth covariate appearing in this result line */
1.234     brouard  10424:     
1.230     brouard  10425:     cutl(strc,stre,strd,'V'); /* strd='V4' strc=4 stre='V' */;
1.318     brouard  10426:     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  10427:     /* Typevarsel[k]=1;  /\* 1 for age product *\/ */
                   10428:     /* cptcovsel++;     */
                   10429:     if (nbocc(stra,'=') >0)
                   10430:       strcpy(resultsav,stra); /* and analyzes it */
                   10431:   }
1.235     brouard  10432:   /* Checking for missing or useless values in comparison of current model needs */
1.332     brouard  10433:   /* Feeds resultmodel[nres][k1]=k2 for k1th product covariate with age in the model equation fed by the index k2 of the resutline*/
1.334     brouard  10434:   for(k1=1; k1<= cptcovt ;k1++){ /* Loop on MODEL LINE V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
1.332     brouard  10435:     if(Typevar[k1]==0){ /* Single covariate in model */
                   10436:       /* 0 for simple covariate (dummy, quantitative, fixed or varying), 1 for age product, 2 for  product */
1.234     brouard  10437:       match=0;
1.318     brouard  10438:       for(k2=1; k2 <=j;k2++){/* Loop on resultline. In result line V4=1 V5=24.1 V3=1  V2=8 V1=0 */
                   10439:        if(Tvar[k1]==Tvarsel[k2]) {/* Tvar is coming from the model, Tvarsel from the result. Tvar[1]=5 == Tvarsel[2]=5   */
1.334     brouard  10440:          modelresult[nres][k2]=k1;/* modelresult[2]=1 modelresult[1]=2  modelresult[3]=3  modelresult[6]=4 modelresult[9]=5 */
1.318     brouard  10441:          match=1; /* modelresult of k2 variable of resultline is identical to k1 variable of the model good */
1.234     brouard  10442:          break;
                   10443:        }
                   10444:       }
                   10445:       if(match == 0){
1.332     brouard  10446:        printf("Error in result line (Dummy single): V%d is missing in result: %s according to model=%s. Tvar[k1=%d]=%d is different from Tvarsel[k2=%d]=%d.\n",Tvar[k1], resultline, model,k1, Tvar[k1], k2, Tvarsel[k2]);
                   10447:        fprintf(ficlog,"Error in result line (Dummy single): V%d is missing in result: %s according to model=%s\n",Tvar[k1], resultline, model);
1.310     brouard  10448:        return 1;
1.234     brouard  10449:       }
1.332     brouard  10450:     }else if(Typevar[k1]==1){ /* Product with age We want to get the position k2 in the resultline of the product k1 in the model line*/
                   10451:       /* We feed resultmodel[k1]=k2; */
                   10452:       match=0;
                   10453:       for(k2=1; k2 <=j;k2++){/* Loop on resultline.  jth occurence of = signs in the result line. In result line V4=1 V5=24.1 V3=1  V2=8 V1=0 */
                   10454:        if(Tvar[k1]==Tvarsel[k2]) {/* Tvar is coming from the model, Tvarsel from the result. Tvar[1]=5 == Tvarsel[2]=5   */
1.334     brouard  10455:          modelresult[nres][k2]=k1;/* we found a Vn=1 corrresponding to Vn*age in the model modelresult[2]=1 modelresult[1]=2  modelresult[3]=3  modelresult[6]=4 modelresult[9]=5 */
1.332     brouard  10456:          resultmodel[nres][k1]=k2; /* Added here */
                   10457:          printf("Decoderesult first modelresult[k2=%d]=%d (k1) V%d*AGE\n",k2,k1,Tvar[k1]);
                   10458:          match=1; /* modelresult of k2 variable of resultline is identical to k1 variable of the model good */
                   10459:          break;
                   10460:        }
                   10461:       }
                   10462:       if(match == 0){
                   10463:        printf("Error in result line (Product with age): V%d is missing in result: %s according to model=%s (Tvarsel[k2=%d]=%d)\n",Tvar[k1], resultline, model, k2, Tvarsel[k2]);
1.333     brouard  10464:        fprintf(ficlog,"Error in result line (Product with age): V%d is missing in result: %s according to model=%s (Tvarsel[k2=%d]=%d)\n",Tvar[k1], resultline, model, k2, Tvarsel[k2]);
1.332     brouard  10465:       return 1;
                   10466:       }
                   10467:     }else if(Typevar[k1]==2){ /* Product No age We want to get the position in the resultline of the product in the model line*/
                   10468:       /* resultmodel[nres][of such a Vn * Vm product k1] is not unique, so can't exist, we feed Tvard[k1][1] and [2] */ 
                   10469:       match=0;
                   10470:       printf("Decoderesult very first Product Tvardk[k1=%d][1]=%d Tvardk[k1=%d][2]=%d V%d * V%d\n",k1,Tvardk[k1][1],k1,Tvardk[k1][2],Tvardk[k1][1],Tvardk[k1][2]);
                   10471:       for(k2=1; k2 <=j;k2++){/* Loop on resultline. In result line V4=1 V5=24.1 V3=1  V2=8 V1=0 */
                   10472:        if(Tvardk[k1][1]==Tvarsel[k2]) {/* Tvardk is coming from the model, Tvarsel from the result. Tvar[1]=5 == Tvarsel[2]=5   */
                   10473:          /* modelresult[k2]=k1; */
                   10474:          printf("Decoderesult first Product modelresult[k2=%d]=%d (k1) V%d * \n",k2,k1,Tvarsel[k2]);
                   10475:          match=1; /* modelresult of k2 variable of resultline is identical to k1 variable of the model good */
                   10476:        }
                   10477:       }
                   10478:       if(match == 0){
                   10479:        printf("Error in result line (Product without age first variable): V%d is missing in result: %s according to model=%s\n",Tvardk[k1][1], resultline, model);
1.333     brouard  10480:        fprintf(ficlog,"Error in result line (Product without age first variable): V%d is missing in result: %s according to model=%s\n",Tvardk[k1][1], resultline, model);
1.332     brouard  10481:        return 1;
                   10482:       }
                   10483:       match=0;
                   10484:       for(k2=1; k2 <=j;k2++){/* Loop on resultline. In result line V4=1 V5=24.1 V3=1  V2=8 V1=0 */
                   10485:        if(Tvardk[k1][2]==Tvarsel[k2]) {/* Tvardk is coming from the model, Tvarsel from the result. Tvar[1]=5 == Tvarsel[2]=5   */
                   10486:          /* modelresult[k2]=k1;*/
                   10487:          printf("Decoderesult second Product modelresult[k2=%d]=%d (k1) * V%d \n ",k2,k1,Tvarsel[k2]);
                   10488:          match=1; /* modelresult of k2 variable of resultline is identical to k1 variable of the model good */
                   10489:          break;
                   10490:        }
                   10491:       }
                   10492:       if(match == 0){
                   10493:        printf("Error in result line (Product without age second variable): V%d is missing in result: %s according to model=%s\n",Tvardk[k1][2], resultline, model);
1.333     brouard  10494:        fprintf(ficlog,"Error in result line (Product without age second variable): V%d is missing in result : %s according to model=%s\n",Tvardk[k1][2], resultline, model);
1.332     brouard  10495:        return 1;
                   10496:       }
                   10497:     }/* End of testing */
1.333     brouard  10498:   }/* End loop cptcovt */
1.235     brouard  10499:   /* Checking for missing or useless values in comparison of current model needs */
1.332     brouard  10500:   /* Feeds resultmodel[nres][k1]=k2 for single covariate (k1) in the model equation */
1.334     brouard  10501:   for(k2=1; k2 <=j;k2++){ /* j or cptcovs is the number of single covariates used either in the model line as well as in the result line (dummy or quantitative)
                   10502:                           * Loop on resultline variables: result line V4=1 V5=24.1 V3=1  V2=8 V1=0 */
1.234     brouard  10503:     match=0;
1.318     brouard  10504:     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.332     brouard  10505:       if(Typevar[k1]==0){ /* Single only */
1.237     brouard  10506:        if(Tvar[k1]==Tvarsel[k2]) { /* Tvar[2]=4 == Tvarsel[1]=4   */
1.330     brouard  10507:          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.334     brouard  10508:          modelresult[nres][k2]=k1; /* k1th position in the model equation corresponds to k2th position in the result line. modelresult[1]=2 modelresult[2]=1  modelresult[3]=3  remodelresult[4]=6 modelresult[5]=9 */
1.234     brouard  10509:          ++match;
                   10510:        }
                   10511:       }
                   10512:     }
                   10513:     if(match == 0){
1.332     brouard  10514:       printf("Error in result line: variable V%d is missing in model; result: %s, model=%s\n",Tvarsel[k2], resultline, model);
                   10515:       fprintf(ficlog,"Error in result line: variable V%d is missing in model; result: %s, model=%s\n",Tvarsel[k2], resultline, model);
1.310     brouard  10516:       return 1;
1.234     brouard  10517:     }else if(match > 1){
                   10518:       printf("Error in result line: %d doubled; result: %s, model=%s\n",k2, resultline, model);
1.310     brouard  10519:       fprintf(ficlog,"Error in result line: %d doubled; result: %s, model=%s\n",k2, resultline, model);
                   10520:       return 1;
1.234     brouard  10521:     }
                   10522:   }
1.334     brouard  10523:   /* cptcovres=j /\* Number of variables in the resultline is equal to cptcovs and thus useless *\/     */
1.234     brouard  10524:   /* We need to deduce which combination number is chosen and save quantitative values */
1.235     brouard  10525:   /* model line V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
1.330     brouard  10526:   /* nres=1st result line: V4=1 V5=25.1 V3=0  V2=8 V1=1 */
                   10527:   /* 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*/
                   10528:   /* nres=2nd result line: V4=1 V5=24.1 V3=1  V2=8 V1=0 */
1.235     brouard  10529:   /* should give a combination of dummy V4=1, V3=1, V1=0 => V4*2**(0) + V3*2**(1) + V1*2**(2) = 3 + (1offset) = 4*/
                   10530:   /*    1 0 0 0 */
                   10531:   /*    2 1 0 0 */
                   10532:   /*    3 0 1 0 */ 
1.330     brouard  10533:   /*    4 1 1 0 */ /* V4=1, V3=1, V1=0 (nres=2)*/
1.235     brouard  10534:   /*    5 0 0 1 */
1.330     brouard  10535:   /*    6 1 0 1 */ /* V4=1, V3=0, V1=1 (nres=1)*/
1.235     brouard  10536:   /*    7 0 1 1 */
                   10537:   /*    8 1 1 1 */
1.237     brouard  10538:   /* V(Tvresult)=Tresult V4=1 V3=0 V1=1 Tresult[nres=1][2]=0 */
                   10539:   /* V(Tvqresult)=Tqresult V5=25.1 V2=8 Tqresult[nres=1][1]=25.1 */
                   10540:   /* V5*age V5 known which value for nres?  */
                   10541:   /* Tqinvresult[2]=8 Tqinvresult[1]=25.1  */
1.334     brouard  10542:   for(k1=1, k=0, k4=0, k4q=0; k1 <=cptcovt;k1++){ /* cptcovt number of covariates (excluding 1 and age or age*age) in the MODEL equation.
                   10543:                                                   * loop on position k1 in the MODEL LINE */
1.331     brouard  10544:     /* k counting number of combination of single dummies in the equation model */
                   10545:     /* k4 counting single dummies in the equation model */
                   10546:     /* k4q counting single quantitatives in the equation model */
1.334     brouard  10547:     if( Dummy[k1]==0 && Typevar[k1]==0 ){ /* Dummy and Single, k1 is sorting according to MODEL, but k3 to resultline */
                   10548:        /* k4+1= (not always if quant in model) position in the resultline V(Tvarsel)=Tvalsel=Tresult[nres][pos](value); V(Tvresult[nres][pos] (variable): V(variable)=value) */
1.332     brouard  10549:       /* modelresult[k3]=k1: k3th position in the result line corresponds to the k1 position in the model line (doesn't work with products)*/
1.330     brouard  10550:       /* Value in the (current nres) resultline of the variable at the k1th position in the model equation resultmodel[nres][k1]= k3 */
1.332     brouard  10551:       /* resultmodel[nres][k1]=k3: k1th position in the model correspond to the k3 position in the resultline                        */
                   10552:       /*      k3 is the position in the nres result line of the k1th variable of the model equation                                  */
                   10553:       /* Tvarsel[k3]: Name of the variable at the k3th position in the result line.                                                  */
                   10554:       /* Tvalsel[k3]: Value of the variable at the k3th position in the result line.                                                 */
                   10555:       /* Tresult[nres][result_position]= value of the dummy variable at the result_position in the nres resultline                   */
1.334     brouard  10556:       /* Tvresult[nres][result_position]= name of the dummy variable at the result_position in the nres resultline                     */
1.332     brouard  10557:       /* Tinvresult[nres][Name of a dummy variable]= value of the variable in the result line                                        */
1.330     brouard  10558:       /* TinvDoQresult[nres][Name of a Dummy or Q variable]= value of the variable in the result line                                                      */
1.332     brouard  10559:       k3= resultmodel[nres][k1]; /* From position k1 in model get position k3 in result line */
                   10560:       /* nres=1 k1=2 resultmodel[2(V4)] = 1=k3 ; k1=3 resultmodel[3(V3)] = 2=k3*/
                   10561:       k2=(int)Tvarsel[k3]; /* from position k3 in resultline get name k2: nres=1 k1=2=>k3=1 Tvarsel[resultmodel[2]]= Tvarsel[1] = 4=k2 (V4); k1=3=>k3=2 Tvarsel[2]=3 (V3)*/
1.330     brouard  10562:       k+=Tvalsel[k3]*pow(2,k4);  /* nres=1 k1=2 Tvalsel[1]=1 (V4=1); k1=3 k3=2 Tvalsel[2]=0 (V3=0) */
1.334     brouard  10563:       TinvDoQresult[nres][(int)Tvarsel[k3]]=Tvalsel[k3]; /* TinvDoQresult[nres][Name]=Value; stores the value into the name of the variable. */
1.332     brouard  10564:       /* Tinvresult[nres][4]=1 */
1.334     brouard  10565:       /* Tresult[nres][k4+1]=Tvalsel[k3];/\* Tresult[nres=2][1]=1(V4=1)  Tresult[nres=2][2]=0(V3=0) *\/ */
                   10566:       Tresult[nres][k3]=Tvalsel[k3];/* Tresult[nres=2][1]=1(V4=1)  Tresult[nres=2][2]=0(V3=0) */
                   10567:       /* Tvresult[nres][k4+1]=(int)Tvarsel[k3];/\* Tvresult[nres][1]=4 Tvresult[nres][3]=1 *\/ */
                   10568:       Tvresult[nres][k3]=(int)Tvarsel[k3];/* Tvresult[nres][1]=4 Tvresult[nres][3]=1 */
1.237     brouard  10569:       Tinvresult[nres][(int)Tvarsel[k3]]=Tvalsel[k3]; /* Tinvresult[nres][4]=1 */
1.334     brouard  10570:       precov[nres][k1]=Tvalsel[k3]; /* Value from resultline of the variable at the k1 position in the model */
1.332     brouard  10571:       printf("Decoderesult Dummy k=%d, k1=%d precov[nres=%d][k1=%d]=%.f V(k2=V%d)= Tvalsel[%d]=%d, 2**(%d)\n",k, k1, nres, k1,precov[nres][k1], k2, k3, (int)Tvalsel[k3], k4);
1.235     brouard  10572:       k4++;;
1.331     brouard  10573:     }else if( Dummy[k1]==1 && Typevar[k1]==0 ){ /* Quantitative and single */
1.330     brouard  10574:       /* Tqresult[nres][result_position]= value of the variable at the result_position in the nres resultline                                 */
1.332     brouard  10575:       /* Tvqresult[nres][result_position]= id of the variable at the result_position in the nres resultline                                 */
1.330     brouard  10576:       /* Tqinvresult[nres][Name of a quantitative variable]= value of the variable in the result line                                                      */
1.332     brouard  10577:       k3q= resultmodel[nres][k1]; /* resultmodel[1(V5)] = 5 =k3q */
                   10578:       k2q=(int)Tvarsel[k3q]; /*  Name of variable at k3q th position in the resultline */
                   10579:       /* Tvarsel[resultmodel[1]]= Tvarsel[1] = 4=k2 */
1.334     brouard  10580:       /* Tqresult[nres][k4q+1]=Tvalsel[k3q]; /\* Tqresult[nres][1]=25.1 *\/ */
                   10581:       /* Tvresult[nres][k4q+1]=(int)Tvarsel[k3q];/\* Tvresult[nres][1]=4 Tvresult[nres][3]=1 *\/ */
                   10582:       /* Tvqresult[nres][k4q+1]=(int)Tvarsel[k3q]; /\* Tvqresult[nres][1]=5 *\/ */
                   10583:       Tqresult[nres][k3q]=Tvalsel[k3q]; /* Tqresult[nres][1]=25.1 */
                   10584:       Tvresult[nres][k3q]=(int)Tvarsel[k3q];/* Tvresult[nres][1]=4 Tvresult[nres][3]=1 */
                   10585:       Tvqresult[nres][k3q]=(int)Tvarsel[k3q]; /* Tvqresult[nres][1]=5 */
1.237     brouard  10586:       Tqinvresult[nres][(int)Tvarsel[k3q]]=Tvalsel[k3q]; /* Tqinvresult[nres][5]=25.1 */
1.330     brouard  10587:       TinvDoQresult[nres][(int)Tvarsel[k3q]]=Tvalsel[k3q]; /* Tqinvresult[nres][5]=25.1 */
1.332     brouard  10588:       precov[nres][k1]=Tvalsel[k3q];
                   10589:       printf("Decoderesult Quantitative nres=%d,precov[nres=%d][k1=%d]=%.f V(k2q=V%d)= Tvalsel[%d]=%d, Tvarsel[%d]=%f\n",nres, nres, k1,precov[nres][k1], k2q, k3q, Tvarsel[k3q], k3q, Tvalsel[k3q]);
1.235     brouard  10590:       k4q++;;
1.331     brouard  10591:     }else if( Dummy[k1]==2 ){ /* For dummy with age product */
                   10592:       /* Tvar[k1]; */ /* Age variable */
1.332     brouard  10593:       /* Wrong we want the value of variable name Tvar[k1] */
                   10594:       
                   10595:       k3= resultmodel[nres][k1]; /* nres=1 k1=2 resultmodel[2(V4)] = 1=k3 ; k1=3 resultmodel[3(V3)] = 2=k3*/
1.331     brouard  10596:       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)*/
1.334     brouard  10597:       TinvDoQresult[nres][(int)Tvarsel[k3]]=Tvalsel[k3]; /* TinvDoQresult[nres][4]=1 */
1.332     brouard  10598:       precov[nres][k1]=Tvalsel[k3];
                   10599:       printf("Decoderesult Dummy with age k=%d, k1=%d precov[nres=%d][k1=%d]=%.f Tvar[%d]=V%d k2=Tvarsel[%d]=%d Tvalsel[%d]=%d\n",k, k1, nres, k1,precov[nres][k1], k1, Tvar[k1], k3,(int)Tvarsel[k3], k3, (int)Tvalsel[k3]);
1.331     brouard  10600:     }else if( Dummy[k1]==3 ){ /* For quant with age product */
1.332     brouard  10601:       k3q= resultmodel[nres][k1]; /* resultmodel[1(V5)] = 25.1=k3q */
1.331     brouard  10602:       k2q=(int)Tvarsel[k3q]; /*  Tvarsel[resultmodel[1]]= Tvarsel[1] = 4=k2 */
1.334     brouard  10603:       TinvDoQresult[nres][(int)Tvarsel[k3q]]=Tvalsel[k3q]; /* TinvDoQresult[nres][5]=25.1 */
1.332     brouard  10604:       precov[nres][k1]=Tvalsel[k3q];
1.334     brouard  10605:       printf("Decoderesult Quantitative with age nres=%d, k1=%d, precov[nres=%d][k1=%d]=%f Tvar[%d]=V%d V(k2q=%d)= Tvarsel[%d]=%d, Tvalsel[%d]=%f\n",nres, k1, nres, k1,precov[nres][k1], k1,  Tvar[k1], k2q, k3q, Tvarsel[k3q], k3q, Tvalsel[k3q]);
1.331     brouard  10606:     }else if(Typevar[k1]==2 ){ /* For product quant or dummy (not with age) */
1.332     brouard  10607:       precov[nres][k1]=TinvDoQresult[nres][Tvardk[k1][1]] * TinvDoQresult[nres][Tvardk[k1][2]];      
                   10608:       printf("Decoderesult Quantitative or Dummy (not with age) nres=%d k1=%d precov[nres=%d][k1=%d]=%.f V%d(=%.f) * V%d(=%.f) \n",nres, k1, nres, k1,precov[nres][k1], Tvardk[k1][1], TinvDoQresult[nres][Tvardk[k1][1]], Tvardk[k1][2], TinvDoQresult[nres][Tvardk[k1][2]]);
1.330     brouard  10609:     }else{
1.332     brouard  10610:       printf("Error Decoderesult probably a product  Dummy[%d]==%d && Typevar[%d]==%d\n", k1, Dummy[k1], k1, Typevar[k1]);
                   10611:       fprintf(ficlog,"Error Decoderesult probably a product  Dummy[%d]==%d && Typevar[%d]==%d\n", k1, Dummy[k1], k1, Typevar[k1]);
1.235     brouard  10612:     }
                   10613:   }
1.234     brouard  10614:   
1.334     brouard  10615:   TKresult[nres]=++k; /* Number of combinations of dummies for the nresult and the model =Tvalsel[k3]*pow(2,k4) + 1*/
1.230     brouard  10616:   return (0);
                   10617: }
1.235     brouard  10618: 
1.230     brouard  10619: int decodemodel( char model[], int lastobs)
                   10620:  /**< This routine decodes the model and returns:
1.224     brouard  10621:        * Model  V1+V2+V3+V8+V7*V8+V5*V6+V8*age+V3*age+age*age
                   10622:        * - nagesqr = 1 if age*age in the model, otherwise 0.
                   10623:        * - cptcovt total number of covariates of the model nbocc(+)+1 = 8 excepting constant and age and age*age
                   10624:        * - cptcovn or number of covariates k of the models excluding age*products =6 and age*age
                   10625:        * - cptcovage number of covariates with age*products =2
                   10626:        * - cptcovs number of simple covariates
                   10627:        * - 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
                   10628:        *     which is a new column after the 9 (ncovcol) variables. 
1.319     brouard  10629:        * - if k is a product Vn*Vm, covar[k][i] is filled with correct values for each individual
1.224     brouard  10630:        * - Tprod[l] gives the kth covariates of the product Vn*Vm l=1 to cptcovprod-cptcovage
                   10631:        *    Tprod[1]@2 {5, 6}: position of first product V7*V8 is 5, and second V5*V6 is 6.
                   10632:        * - Tvard[k]  p Tvard[1][1]@4 {7, 8, 5, 6} for V7*V8 and V5*V6 .
                   10633:        */
1.319     brouard  10634: /* 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  10635: {
1.238     brouard  10636:   int i, j, k, ks, v;
1.227     brouard  10637:   int  j1, k1, k2, k3, k4;
1.136     brouard  10638:   char modelsav[80];
1.145     brouard  10639:   char stra[80], strb[80], strc[80], strd[80],stre[80];
1.187     brouard  10640:   char *strpt;
1.136     brouard  10641: 
1.145     brouard  10642:   /*removespace(model);*/
1.136     brouard  10643:   if (strlen(model) >1){ /* If there is at least 1 covariate */
1.145     brouard  10644:     j=0, j1=0, k1=0, k2=-1, ks=0, cptcovn=0;
1.137     brouard  10645:     if (strstr(model,"AGE") !=0){
1.192     brouard  10646:       printf("Error. AGE must be in lower case 'age' model=1+age+%s. ",model);
                   10647:       fprintf(ficlog,"Error. AGE must be in lower case model=1+age+%s. ",model);fflush(ficlog);
1.136     brouard  10648:       return 1;
                   10649:     }
1.141     brouard  10650:     if (strstr(model,"v") !=0){
                   10651:       printf("Error. 'v' must be in upper case 'V' model=%s ",model);
                   10652:       fprintf(ficlog,"Error. 'v' must be in upper case model=%s ",model);fflush(ficlog);
                   10653:       return 1;
                   10654:     }
1.187     brouard  10655:     strcpy(modelsav,model); 
                   10656:     if ((strpt=strstr(model,"age*age")) !=0){
                   10657:       printf(" strpt=%s, model=%s\n",strpt, model);
                   10658:       if(strpt != model){
1.234     brouard  10659:        printf("Error in model: 'model=%s'; 'age*age' should in first place before other covariates\n \
1.192     brouard  10660:  'model=1+age+age*age+V1.' or 'model=1+age+age*age+V1+V1*age.', please swap as well as \n \
1.187     brouard  10661:  corresponding column of parameters.\n",model);
1.234     brouard  10662:        fprintf(ficlog,"Error in model: 'model=%s'; 'age*age' should in first place before other covariates\n \
1.192     brouard  10663:  'model=1+age+age*age+V1.' or 'model=1+age+age*age+V1+V1*age.', please swap as well as \n \
1.187     brouard  10664:  corresponding column of parameters.\n",model); fflush(ficlog);
1.234     brouard  10665:        return 1;
1.225     brouard  10666:       }
1.187     brouard  10667:       nagesqr=1;
                   10668:       if (strstr(model,"+age*age") !=0)
1.234     brouard  10669:        substrchaine(modelsav, model, "+age*age");
1.187     brouard  10670:       else if (strstr(model,"age*age+") !=0)
1.234     brouard  10671:        substrchaine(modelsav, model, "age*age+");
1.187     brouard  10672:       else 
1.234     brouard  10673:        substrchaine(modelsav, model, "age*age");
1.187     brouard  10674:     }else
                   10675:       nagesqr=0;
                   10676:     if (strlen(modelsav) >1){
                   10677:       j=nbocc(modelsav,'+'); /**< j=Number of '+' */
                   10678:       j1=nbocc(modelsav,'*'); /**< j1=Number of '*' */
1.224     brouard  10679:       cptcovs=j+1-j1; /**<  Number of simple covariates V1+V1*age+V3 +V3*V4+age*age=> V1 + V3 =5-3=2  */
1.187     brouard  10680:       cptcovt= j+1; /* Number of total covariates in the model, not including
1.225     brouard  10681:                     * cst, age and age*age 
                   10682:                     * V1+V1*age+ V3 + V3*V4+age*age=> 3+1=4*/
                   10683:       /* including age products which are counted in cptcovage.
                   10684:        * but the covariates which are products must be treated 
                   10685:        * separately: ncovn=4- 2=2 (V1+V3). */
1.187     brouard  10686:       cptcovprod=j1; /**< Number of products  V1*V2 +v3*age = 2 */
                   10687:       cptcovprodnoage=0; /**< Number of covariate products without age: V3*V4 =1  */
1.225     brouard  10688:       
                   10689:       
1.187     brouard  10690:       /*   Design
                   10691:        *  V1   V2   V3   V4  V5  V6  V7  V8  V9 Weight
                   10692:        *  <          ncovcol=8                >
                   10693:        * Model V2 + V1 + V3*age + V3 + V5*V6 + V7*V8 + V8*age + V8
                   10694:        *   k=  1    2      3       4     5       6      7        8
                   10695:        *  cptcovn number of covariates (not including constant and age ) = # of + plus 1 = 7+1=8
                   10696:        *  covar[k,i], value of kth covariate if not including age for individual i:
1.224     brouard  10697:        *       covar[1][i]= (V1), covar[4][i]=(V4), covar[8][i]=(V8)
                   10698:        *  Tvar[k] # of the kth covariate:  Tvar[1]=2  Tvar[2]=1 Tvar[4]=3 Tvar[8]=8
1.187     brouard  10699:        *       if multiplied by age: V3*age Tvar[3=V3*age]=3 (V3) Tvar[7]=8 and 
                   10700:        *  Tage[++cptcovage]=k
                   10701:        *       if products, new covar are created after ncovcol with k1
                   10702:        *  Tvar[k]=ncovcol+k1; # of the kth covariate product:  Tvar[5]=ncovcol+1=10  Tvar[6]=ncovcol+1=11
                   10703:        *  Tprod[k1]=k; Tprod[1]=5 Tprod[2]= 6; gives the position of the k1th product
                   10704:        *  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
                   10705:        *  Tvar[cptcovn+k2]=Tvard[k1][1];Tvar[cptcovn+k2+1]=Tvard[k1][2];
                   10706:        *  Tvar[8+1]=5;Tvar[8+2]=6;Tvar[8+3]=7;Tvar[8+4]=8 inverted
                   10707:        *  V1   V2   V3   V4  V5  V6  V7  V8  V9  V10  V11
                   10708:        *  <          ncovcol=8                >
                   10709:        *       Model V2 + V1 + V3*age + V3 + V5*V6 + V7*V8 + V8*age + V8    d1   d1   d2  d2
                   10710:        *          k=  1    2      3       4     5       6      7        8    9   10   11  12
                   10711:        *     Tvar[k]= 2    1      3       3    10      11      8        8    5    6    7   8
1.319     brouard  10712:        * p Tvar[1]@12={2,   1,     3,      3,  11,     10,     8,       8,   7,   8,   5,  6}
1.187     brouard  10713:        * p Tprod[1]@2={                         6, 5}
                   10714:        *p Tvard[1][1]@4= {7, 8, 5, 6}
                   10715:        * covar[k][i]= V2   V1      ?      V3    V5*V6?   V7*V8?  ?       V8   
                   10716:        *  cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];
1.319     brouard  10717:        *How to reorganize? Tvars(orted)
1.187     brouard  10718:        * Model V1 + V2 + V3 + V8 + V5*V6 + V7*V8 + V3*age + V8*age
                   10719:        * Tvars {2,   1,     3,      3,   11,     10,     8,       8,   7,   8,   5,  6}
                   10720:        *       {2,   1,     4,      8,    5,      6,     3,       7}
                   10721:        * Struct []
                   10722:        */
1.225     brouard  10723:       
1.187     brouard  10724:       /* This loop fills the array Tvar from the string 'model'.*/
                   10725:       /* j is the number of + signs in the model V1+V2+V3 j=2 i=3 to 1 */
                   10726:       /*   modelsav=V2+V1+V4+age*V3 strb=age*V3 stra=V2+V1+V4  */
                   10727:       /*       k=4 (age*V3) Tvar[k=4]= 3 (from V3) Tage[cptcovage=1]=4 */
                   10728:       /*       k=3 V4 Tvar[k=3]= 4 (from V4) */
                   10729:       /*       k=2 V1 Tvar[k=2]= 1 (from V1) */
                   10730:       /*       k=1 Tvar[1]=2 (from V2) */
                   10731:       /*       k=5 Tvar[5] */
                   10732:       /* for (k=1; k<=cptcovn;k++) { */
1.198     brouard  10733:       /*       cov[2+k]=nbcode[Tvar[k]][codtabm(ij,Tvar[k])]; */
1.187     brouard  10734:       /*       } */
1.198     brouard  10735:       /* for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,Tvar[Tage[k])]]*cov[2]; */
1.187     brouard  10736:       /*
                   10737:        * Treating invertedly V2+V1+V3*age+V2*V4 is as if written V2*V4 +V3*age + V1 + V2 */
1.227     brouard  10738:       for(k=cptcovt; k>=1;k--){ /**< Number of covariates not including constant and age, neither age*age*/
                   10739:         Tvar[k]=0; Tprod[k]=0; Tposprod[k]=0;
                   10740:       }
1.187     brouard  10741:       cptcovage=0;
1.319     brouard  10742:       for(k=1; k<=cptcovt;k++){ /* Loop on total covariates of the model line */
                   10743:        cutl(stra,strb,modelsav,'+'); /* keeps in strb after the first '+' cutl from left to right
                   10744:                                         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" */
                   10745:        if (nbocc(modelsav,'+')==0)
                   10746:          strcpy(strb,modelsav); /* and analyzes it */
1.234     brouard  10747:        /*      printf("i=%d a=%s b=%s sav=%s\n",i, stra,strb,modelsav);*/
                   10748:        /*scanf("%d",i);*/
1.319     brouard  10749:        if (strchr(strb,'*')) {  /**< Model includes a product V2+V1+V5*age+ V4+V3*age strb=V3*age */
                   10750:          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  10751:          if (strcmp(strc,"age")==0) { /**< Model includes age: Vn*age */
                   10752:            /* covar is not filled and then is empty */
                   10753:            cptcovprod--;
                   10754:            cutl(stre,strb,strd,'V'); /* strd=V3(input): stre="3" */
1.319     brouard  10755:            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  10756:            Typevar[k]=1;  /* 1 for age product */
1.319     brouard  10757:            cptcovage++; /* Counts the number of covariates which include age as a product */
                   10758:            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  10759:            /*printf("stre=%s ", stre);*/
                   10760:          } else if (strcmp(strd,"age")==0) { /* or age*Vn */
                   10761:            cptcovprod--;
                   10762:            cutl(stre,strb,strc,'V');
                   10763:            Tvar[k]=atoi(stre);
                   10764:            Typevar[k]=1;  /* 1 for age product */
                   10765:            cptcovage++;
                   10766:            Tage[cptcovage]=k;
                   10767:          } else {  /* Age is not in the model product V2+V1+V1*V4+V3*age+V3*V2  strb=V3*V2*/
                   10768:            /* loops on k1=1 (V3*V2) and k1=2 V4*V3 */
                   10769:            cptcovn++;
                   10770:            cptcovprodnoage++;k1++;
                   10771:            cutl(stre,strb,strc,'V'); /* strc= Vn, stre is n; strb=V3*V2 stre=3 strc=*/
                   10772:            Tvar[k]=ncovcol+nqv+ntv+nqtv+k1; /* For model-covariate k tells which data-covariate to use but
                   10773:                                                because this model-covariate is a construction we invent a new column
                   10774:                                                which is after existing variables ncovcol+nqv+ntv+nqtv + k1
1.335     brouard  10775:                                                If already ncovcol=4 and model= V2 + V1 + V1*V4 + age*V3 + V3*V2
1.319     brouard  10776:                                                thus after V4 we invent V5 and V6 because age*V3 will be computed in 4
                   10777:                                                Tvar[3=V1*V4]=4+1=5 Tvar[5=V3*V2]=4 + 2= 6, Tvar[4=age*V3]=4 etc */
1.335     brouard  10778:            /* Please remark that the new variables are model dependent */
                   10779:            /* If we have 4 variable but the model uses only 3, like in
                   10780:             * model= V1 + age*V1 + V2 + V3 + age*V2 + age*V3 + V1*V2 + V1*V3
                   10781:             *  k=     1     2       3   4     5        6        7       8
                   10782:             * Tvar[k]=1     1       2   3     2        3       (5       6) (and not 4 5 because of V4 missing)
                   10783:             * Tage[kk]    [1]= 2           [2]=5      [3]=6                  kk=1 to cptcovage=3
                   10784:             * Tvar[Tage[kk]][1]=2          [2]=2      [3]=3
                   10785:             */
1.234     brouard  10786:            Typevar[k]=2;  /* 2 for double fixed dummy covariates */
                   10787:            cutl(strc,strb,strd,'V'); /* strd was Vm, strc is m */
                   10788:            Tprod[k1]=k;  /* Tprod[1]=3(=V1*V4) for V2+V1+V1*V4+age*V3+V3*V2  */
1.319     brouard  10789:            Tposprod[k]=k1; /* Tposprod[3]=1, Tposprod[2]=5 */
1.234     brouard  10790:            Tvard[k1][1] =atoi(strc); /* m 1 for V1*/
1.330     brouard  10791:            Tvardk[k][1] =atoi(strc); /* m 1 for V1*/
1.234     brouard  10792:            Tvard[k1][2] =atoi(stre); /* n 4 for V4*/
1.330     brouard  10793:            Tvardk[k][2] =atoi(stre); /* n 4 for V4*/
1.234     brouard  10794:            k2=k2+2;  /* k2 is initialize to -1, We want to store the n and m in Vn*Vm at the end of Tvar */
                   10795:            /* Tvar[cptcovt+k2]=Tvard[k1][1]; /\* Tvar[(cptcovt=4+k2=1)=5]= 1 (V1) *\/ */
                   10796:            /* Tvar[cptcovt+k2+1]=Tvard[k1][2];  /\* Tvar[(cptcovt=4+(k2=1)+1)=6]= 4 (V4) *\/ */
1.225     brouard  10797:             /*ncovcol=4 and model=V2+V1+V1*V4+age*V3+V3*V2, Tvar[3]=5, Tvar[4]=6, cptcovt=5 */
1.234     brouard  10798:            /*                     1  2   3      4     5 | Tvar[5+1)=1, Tvar[7]=2   */
                   10799:            for (i=1; i<=lastobs;i++){
                   10800:              /* Computes the new covariate which is a product of
                   10801:                 covar[n][i]* covar[m][i] and stores it at ncovol+k1 May not be defined */
                   10802:              covar[ncovcol+k1][i]=covar[atoi(stre)][i]*covar[atoi(strc)][i];
                   10803:            }
                   10804:          } /* End age is not in the model */
                   10805:        } /* End if model includes a product */
1.319     brouard  10806:        else { /* not a product */
1.234     brouard  10807:          /*printf("d=%s c=%s b=%s\n", strd,strc,strb);*/
                   10808:          /*  scanf("%d",i);*/
                   10809:          cutl(strd,strc,strb,'V');
                   10810:          ks++; /**< Number of simple covariates dummy or quantitative, fixe or varying */
                   10811:          cptcovn++; /** V4+V3+V5: V4 and V3 timevarying dummy covariates, V5 timevarying quantitative */
                   10812:          Tvar[k]=atoi(strd);
                   10813:          Typevar[k]=0;  /* 0 for simple covariates */
                   10814:        }
                   10815:        strcpy(modelsav,stra);  /* modelsav=V2+V1+V4 stra=V2+V1+V4 */ 
1.223     brouard  10816:                                /*printf("a=%s b=%s sav=%s\n", stra,strb,modelsav);
1.225     brouard  10817:                                  scanf("%d",i);*/
1.187     brouard  10818:       } /* end of loop + on total covariates */
                   10819:     } /* end if strlen(modelsave == 0) age*age might exist */
                   10820:   } /* end if strlen(model == 0) */
1.136     brouard  10821:   
                   10822:   /*The number n of Vn is stored in Tvar. cptcovage =number of age covariate. Tage gives the position of age. cptcovprod= number of products.
                   10823:     If model=V1+V1*age then Tvar[1]=1 Tvar[2]=1 cptcovage=1 Tage[1]=2 cptcovprod=0*/
1.225     brouard  10824:   
1.136     brouard  10825:   /* printf("tvar1=%d tvar2=%d tvar3=%d cptcovage=%d Tage=%d",Tvar[1],Tvar[2],Tvar[3],cptcovage,Tage[1]);
1.225     brouard  10826:      printf("cptcovprod=%d ", cptcovprod);
                   10827:      fprintf(ficlog,"cptcovprod=%d ", cptcovprod);
                   10828:      scanf("%d ",i);*/
                   10829: 
                   10830: 
1.230     brouard  10831: /* Until here, decodemodel knows only the grammar (simple, product, age*) of the model but not what kind
                   10832:    of variable (dummy vs quantitative, fixed vs time varying) is behind. But we know the # of each. */
1.226     brouard  10833: /* ncovcol= 1, nqv=1 | ntv=2, nqtv= 1  = 5 possible variables data: 2 fixed 3, varying
                   10834:    model=        V5 + V4 +V3 + V4*V3 + V5*age + V2 + V1*V2 + V1*age + V5*age, V1 is not used saving its place
                   10835:    k =           1    2   3     4       5       6      7      8        9
                   10836:    Tvar[k]=      5    4   3 1+1+2+1+1=6 5       2      7      1        5
1.319     brouard  10837:    Typevar[k]=   0    0   0     2       1       0      2      1        0
1.227     brouard  10838:    Fixed[k]      1    1   1     1       3       0    0 or 2   2        3
                   10839:    Dummy[k]      1    0   0     0       3       1      1      2        3
                   10840:          Tmodelind[combination of covar]=k;
1.225     brouard  10841: */  
                   10842: /* Dispatching between quantitative and time varying covariates */
1.226     brouard  10843:   /* If Tvar[k] >ncovcol it is a product */
1.225     brouard  10844:   /* 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  10845:        /* Computing effective variables, ie used by the model, that is from the cptcovt variables */
1.318     brouard  10846:   printf("Model=1+age+%s\n\
1.227     brouard  10847: Typevar: 0 for simple covariate (dummy, quantitative, fixed or varying), 1 for age product, 2 for  product \n\
                   10848: Fixed[k] 0=fixed (product or simple), 1 varying, 2 fixed with age product, 3 varying with age product \n\
                   10849: 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  10850:   fprintf(ficlog,"Model=1+age+%s\n\
1.227     brouard  10851: Typevar: 0 for simple covariate (dummy, quantitative, fixed or varying), 1 for age product, 2 for  product \n\
                   10852: Fixed[k] 0=fixed (product or simple), 1 varying, 2 fixed with age product, 3 varying with age product \n\
                   10853: 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  10854:   for(k=-1;k<=cptcovt; k++){ Fixed[k]=0; Dummy[k]=0;}
1.234     brouard  10855:   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 */
                   10856:     if (Tvar[k] <=ncovcol && Typevar[k]==0 ){ /* Simple fixed dummy (<=ncovcol) covariates */
1.227     brouard  10857:       Fixed[k]= 0;
                   10858:       Dummy[k]= 0;
1.225     brouard  10859:       ncoveff++;
1.232     brouard  10860:       ncovf++;
1.234     brouard  10861:       nsd++;
                   10862:       modell[k].maintype= FTYPE;
                   10863:       TvarsD[nsd]=Tvar[k];
                   10864:       TvarsDind[nsd]=k;
1.330     brouard  10865:       TnsdVar[Tvar[k]]=nsd;
1.234     brouard  10866:       TvarF[ncovf]=Tvar[k];
                   10867:       TvarFind[ncovf]=k;
                   10868:       TvarFD[ncoveff]=Tvar[k]; /* TvarFD[1]=V1 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
                   10869:       TvarFDind[ncoveff]=k; /* TvarFDind[1]=9 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
                   10870:     }else if( Tvar[k] <=ncovcol &&  Typevar[k]==2){ /* Product of fixed dummy (<=ncovcol) covariates */
                   10871:       Fixed[k]= 0;
                   10872:       Dummy[k]= 0;
                   10873:       ncoveff++;
                   10874:       ncovf++;
                   10875:       modell[k].maintype= FTYPE;
                   10876:       TvarF[ncovf]=Tvar[k];
1.330     brouard  10877:       /* TnsdVar[Tvar[k]]=nsd; */ /* To be done */
1.234     brouard  10878:       TvarFind[ncovf]=k;
1.230     brouard  10879:       TvarFD[ncoveff]=Tvar[k]; /* TvarFD[1]=V1 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
1.231     brouard  10880:       TvarFDind[ncoveff]=k; /* TvarFDind[1]=9 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
1.240     brouard  10881:     }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  10882:       Fixed[k]= 0;
                   10883:       Dummy[k]= 1;
1.230     brouard  10884:       nqfveff++;
1.234     brouard  10885:       modell[k].maintype= FTYPE;
                   10886:       modell[k].subtype= FQ;
                   10887:       nsq++;
1.334     brouard  10888:       TvarsQ[nsq]=Tvar[k]; /* Gives the variable name (extended to products) of first nsq simple quantitative covariates (fixed or time vary see below */
                   10889:       TvarsQind[nsq]=k;    /* Gives the position in the model equation of the first nsq simple quantitative covariates (fixed or time vary) */
1.232     brouard  10890:       ncovf++;
1.234     brouard  10891:       TvarF[ncovf]=Tvar[k];
                   10892:       TvarFind[ncovf]=k;
1.231     brouard  10893:       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  10894:       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  10895:     }else if( Tvar[k] <=ncovcol+nqv+ntv && Typevar[k]==0){/* Only simple time varying dummy variables */
1.227     brouard  10896:       Fixed[k]= 1;
                   10897:       Dummy[k]= 0;
1.225     brouard  10898:       ntveff++; /* Only simple time varying dummy variable */
1.234     brouard  10899:       modell[k].maintype= VTYPE;
                   10900:       modell[k].subtype= VD;
                   10901:       nsd++;
                   10902:       TvarsD[nsd]=Tvar[k];
                   10903:       TvarsDind[nsd]=k;
1.330     brouard  10904:       TnsdVar[Tvar[k]]=nsd; /* To be verified */
1.234     brouard  10905:       ncovv++; /* Only simple time varying variables */
                   10906:       TvarV[ncovv]=Tvar[k];
1.242     brouard  10907:       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  10908:       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 */
                   10909:       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  10910:       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);
                   10911:       printf("Quasi TmodelInvind[%d]=%d\n",k,Tvar[k]- ncovcol-nqv);
1.231     brouard  10912:     }else if( Tvar[k] <=ncovcol+nqv+ntv+nqtv  && Typevar[k]==0){ /* Only simple time varying quantitative variable V5*/
1.234     brouard  10913:       Fixed[k]= 1;
                   10914:       Dummy[k]= 1;
                   10915:       nqtveff++;
                   10916:       modell[k].maintype= VTYPE;
                   10917:       modell[k].subtype= VQ;
                   10918:       ncovv++; /* Only simple time varying variables */
                   10919:       nsq++;
1.334     brouard  10920:       TvarsQ[nsq]=Tvar[k]; /* k=1 Tvar=5 nsq=1 TvarsQ[1]=5 */ /* Gives the variable name (extended to products) of first nsq simple quantitative covariates (fixed or time vary here) */
                   10921:       TvarsQind[nsq]=k; /* For single quantitative covariate gives the model position of each single quantitative covariate *//* Gives the position in the model equation of the first nsq simple quantitative covariates (fixed or time vary) */
1.234     brouard  10922:       TvarV[ncovv]=Tvar[k];
1.242     brouard  10923:       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  10924:       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 */
                   10925:       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  10926:       TmodelInvQind[nqtveff]=Tvar[k]- ncovcol-nqv-ntv;/* Only simple time varying quantitative variable */
                   10927:       /* Tmodeliqind[k]=nqtveff;/\* Only simple time varying quantitative variable *\/ */
                   10928:       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  10929:       printf("Quasi TmodelInvQind[%d]=%d\n",k,Tvar[k]- ncovcol-nqv-ntv);
1.227     brouard  10930:     }else if (Typevar[k] == 1) {  /* product with age */
1.234     brouard  10931:       ncova++;
                   10932:       TvarA[ncova]=Tvar[k];
                   10933:       TvarAind[ncova]=k;
1.231     brouard  10934:       if (Tvar[k] <=ncovcol ){ /* Product age with fixed dummy covariatee */
1.240     brouard  10935:        Fixed[k]= 2;
                   10936:        Dummy[k]= 2;
                   10937:        modell[k].maintype= ATYPE;
                   10938:        modell[k].subtype= APFD;
                   10939:        /* ncoveff++; */
1.227     brouard  10940:       }else if( Tvar[k] <=ncovcol+nqv) { /* Remind that product Vn*Vm are added in k*/
1.240     brouard  10941:        Fixed[k]= 2;
                   10942:        Dummy[k]= 3;
                   10943:        modell[k].maintype= ATYPE;
                   10944:        modell[k].subtype= APFQ;                /*      Product age * fixed quantitative */
                   10945:        /* nqfveff++;  /\* Only simple fixed quantitative variable *\/ */
1.227     brouard  10946:       }else if( Tvar[k] <=ncovcol+nqv+ntv ){
1.240     brouard  10947:        Fixed[k]= 3;
                   10948:        Dummy[k]= 2;
                   10949:        modell[k].maintype= ATYPE;
                   10950:        modell[k].subtype= APVD;                /*      Product age * varying dummy */
                   10951:        /* ntveff++; /\* Only simple time varying dummy variable *\/ */
1.227     brouard  10952:       }else if( Tvar[k] <=ncovcol+nqv+ntv+nqtv){
1.240     brouard  10953:        Fixed[k]= 3;
                   10954:        Dummy[k]= 3;
                   10955:        modell[k].maintype= ATYPE;
                   10956:        modell[k].subtype= APVQ;                /*      Product age * varying quantitative */
                   10957:        /* nqtveff++;/\* Only simple time varying quantitative variable *\/ */
1.227     brouard  10958:       }
                   10959:     }else if (Typevar[k] == 2) {  /* product without age */
                   10960:       k1=Tposprod[k];
                   10961:       if(Tvard[k1][1] <=ncovcol){
1.240     brouard  10962:        if(Tvard[k1][2] <=ncovcol){
                   10963:          Fixed[k]= 1;
                   10964:          Dummy[k]= 0;
                   10965:          modell[k].maintype= FTYPE;
                   10966:          modell[k].subtype= FPDD;              /*      Product fixed dummy * fixed dummy */
                   10967:          ncovf++; /* Fixed variables without age */
                   10968:          TvarF[ncovf]=Tvar[k];
                   10969:          TvarFind[ncovf]=k;
                   10970:        }else if(Tvard[k1][2] <=ncovcol+nqv){
                   10971:          Fixed[k]= 0;  /* or 2 ?*/
                   10972:          Dummy[k]= 1;
                   10973:          modell[k].maintype= FTYPE;
                   10974:          modell[k].subtype= FPDQ;              /*      Product fixed dummy * fixed quantitative */
                   10975:          ncovf++; /* Varying variables without age */
                   10976:          TvarF[ncovf]=Tvar[k];
                   10977:          TvarFind[ncovf]=k;
                   10978:        }else if(Tvard[k1][2] <=ncovcol+nqv+ntv){
                   10979:          Fixed[k]= 1;
                   10980:          Dummy[k]= 0;
                   10981:          modell[k].maintype= VTYPE;
                   10982:          modell[k].subtype= VPDD;              /*      Product fixed dummy * varying dummy */
                   10983:          ncovv++; /* Varying variables without age */
                   10984:          TvarV[ncovv]=Tvar[k];
                   10985:          TvarVind[ncovv]=k;
                   10986:        }else if(Tvard[k1][2] <=ncovcol+nqv+ntv+nqtv){
                   10987:          Fixed[k]= 1;
                   10988:          Dummy[k]= 1;
                   10989:          modell[k].maintype= VTYPE;
                   10990:          modell[k].subtype= VPDQ;              /*      Product fixed dummy * varying quantitative */
                   10991:          ncovv++; /* Varying variables without age */
                   10992:          TvarV[ncovv]=Tvar[k];
                   10993:          TvarVind[ncovv]=k;
                   10994:        }
1.227     brouard  10995:       }else if(Tvard[k1][1] <=ncovcol+nqv){
1.240     brouard  10996:        if(Tvard[k1][2] <=ncovcol){
                   10997:          Fixed[k]= 0;  /* or 2 ?*/
                   10998:          Dummy[k]= 1;
                   10999:          modell[k].maintype= FTYPE;
                   11000:          modell[k].subtype= FPDQ;              /*      Product fixed quantitative * fixed dummy */
                   11001:          ncovf++; /* Fixed variables without age */
                   11002:          TvarF[ncovf]=Tvar[k];
                   11003:          TvarFind[ncovf]=k;
                   11004:        }else if(Tvard[k1][2] <=ncovcol+nqv+ntv){
                   11005:          Fixed[k]= 1;
                   11006:          Dummy[k]= 1;
                   11007:          modell[k].maintype= VTYPE;
                   11008:          modell[k].subtype= VPDQ;              /*      Product fixed quantitative * varying dummy */
                   11009:          ncovv++; /* Varying variables without age */
                   11010:          TvarV[ncovv]=Tvar[k];
                   11011:          TvarVind[ncovv]=k;
                   11012:        }else if(Tvard[k1][2] <=ncovcol+nqv+ntv+nqtv){
                   11013:          Fixed[k]= 1;
                   11014:          Dummy[k]= 1;
                   11015:          modell[k].maintype= VTYPE;
                   11016:          modell[k].subtype= VPQQ;              /*      Product fixed quantitative * varying quantitative */
                   11017:          ncovv++; /* Varying variables without age */
                   11018:          TvarV[ncovv]=Tvar[k];
                   11019:          TvarVind[ncovv]=k;
                   11020:          ncovv++; /* Varying variables without age */
                   11021:          TvarV[ncovv]=Tvar[k];
                   11022:          TvarVind[ncovv]=k;
                   11023:        }
1.227     brouard  11024:       }else if(Tvard[k1][1] <=ncovcol+nqv+ntv){
1.240     brouard  11025:        if(Tvard[k1][2] <=ncovcol){
                   11026:          Fixed[k]= 1;
                   11027:          Dummy[k]= 1;
                   11028:          modell[k].maintype= VTYPE;
                   11029:          modell[k].subtype= VPDD;              /*      Product time varying dummy * fixed dummy */
                   11030:          ncovv++; /* Varying variables without age */
                   11031:          TvarV[ncovv]=Tvar[k];
                   11032:          TvarVind[ncovv]=k;
                   11033:        }else if(Tvard[k1][2] <=ncovcol+nqv){
                   11034:          Fixed[k]= 1;
                   11035:          Dummy[k]= 1;
                   11036:          modell[k].maintype= VTYPE;
                   11037:          modell[k].subtype= VPDQ;              /*      Product time varying dummy * fixed quantitative */
                   11038:          ncovv++; /* Varying variables without age */
                   11039:          TvarV[ncovv]=Tvar[k];
                   11040:          TvarVind[ncovv]=k;
                   11041:        }else if(Tvard[k1][2] <=ncovcol+nqv+ntv){
                   11042:          Fixed[k]= 1;
                   11043:          Dummy[k]= 0;
                   11044:          modell[k].maintype= VTYPE;
                   11045:          modell[k].subtype= VPDD;              /*      Product time varying dummy * time varying dummy */
                   11046:          ncovv++; /* Varying variables without age */
                   11047:          TvarV[ncovv]=Tvar[k];
                   11048:          TvarVind[ncovv]=k;
                   11049:        }else if(Tvard[k1][2] <=ncovcol+nqv+ntv+nqtv){
                   11050:          Fixed[k]= 1;
                   11051:          Dummy[k]= 1;
                   11052:          modell[k].maintype= VTYPE;
                   11053:          modell[k].subtype= VPDQ;              /*      Product time varying dummy * time varying quantitative */
                   11054:          ncovv++; /* Varying variables without age */
                   11055:          TvarV[ncovv]=Tvar[k];
                   11056:          TvarVind[ncovv]=k;
                   11057:        }
1.227     brouard  11058:       }else if(Tvard[k1][1] <=ncovcol+nqv+ntv+nqtv){
1.240     brouard  11059:        if(Tvard[k1][2] <=ncovcol){
                   11060:          Fixed[k]= 1;
                   11061:          Dummy[k]= 1;
                   11062:          modell[k].maintype= VTYPE;
                   11063:          modell[k].subtype= VPDQ;              /*      Product time varying quantitative * fixed dummy */
                   11064:          ncovv++; /* Varying variables without age */
                   11065:          TvarV[ncovv]=Tvar[k];
                   11066:          TvarVind[ncovv]=k;
                   11067:        }else if(Tvard[k1][2] <=ncovcol+nqv){
                   11068:          Fixed[k]= 1;
                   11069:          Dummy[k]= 1;
                   11070:          modell[k].maintype= VTYPE;
                   11071:          modell[k].subtype= VPQQ;              /*      Product time varying quantitative * fixed quantitative */
                   11072:          ncovv++; /* Varying variables without age */
                   11073:          TvarV[ncovv]=Tvar[k];
                   11074:          TvarVind[ncovv]=k;
                   11075:        }else if(Tvard[k1][2] <=ncovcol+nqv+ntv){
                   11076:          Fixed[k]= 1;
                   11077:          Dummy[k]= 1;
                   11078:          modell[k].maintype= VTYPE;
                   11079:          modell[k].subtype= VPDQ;              /*      Product time varying quantitative * time varying dummy */
                   11080:          ncovv++; /* Varying variables without age */
                   11081:          TvarV[ncovv]=Tvar[k];
                   11082:          TvarVind[ncovv]=k;
                   11083:        }else if(Tvard[k1][2] <=ncovcol+nqv+ntv+nqtv){
                   11084:          Fixed[k]= 1;
                   11085:          Dummy[k]= 1;
                   11086:          modell[k].maintype= VTYPE;
                   11087:          modell[k].subtype= VPQQ;              /*      Product time varying quantitative * time varying quantitative */
                   11088:          ncovv++; /* Varying variables without age */
                   11089:          TvarV[ncovv]=Tvar[k];
                   11090:          TvarVind[ncovv]=k;
                   11091:        }
1.227     brouard  11092:       }else{
1.240     brouard  11093:        printf("Error unknown type of covariate: Tvard[%d][1]=%d,Tvard[%d][2]=%d\n",k1,Tvard[k1][1],k1,Tvard[k1][2]);
                   11094:        fprintf(ficlog,"Error unknown type of covariate: Tvard[%d][1]=%d,Tvard[%d][2]=%d\n",k1,Tvard[k1][1],k1,Tvard[k1][2]);
                   11095:       } /*end k1*/
1.225     brouard  11096:     }else{
1.226     brouard  11097:       printf("Error, current version can't treat for performance reasons, Tvar[%d]=%d, Typevar[%d]=%d\n", k, Tvar[k], k, Typevar[k]);
                   11098:       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  11099:     }
1.227     brouard  11100:     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  11101:     printf("           modell[%d].maintype=%d, modell[%d].subtype=%d\n",k,modell[k].maintype,k,modell[k].subtype);
1.227     brouard  11102:     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]);
                   11103:   }
                   11104:   /* Searching for doublons in the model */
                   11105:   for(k1=1; k1<= cptcovt;k1++){
                   11106:     for(k2=1; k2 <k1;k2++){
1.285     brouard  11107:       /* if((Typevar[k1]==Typevar[k2]) && (Fixed[Tvar[k1]]==Fixed[Tvar[k2]]) && (Dummy[Tvar[k1]]==Dummy[Tvar[k2]] )){ */
                   11108:       if((Typevar[k1]==Typevar[k2]) && (Fixed[k1]==Fixed[k2]) && (Dummy[k1]==Dummy[k2] )){
1.234     brouard  11109:        if((Typevar[k1] == 0 || Typevar[k1] == 1)){ /* Simple or age product */
                   11110:          if(Tvar[k1]==Tvar[k2]){
1.285     brouard  11111:            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]);
                   11112:            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  11113:            return(1);
                   11114:          }
                   11115:        }else if (Typevar[k1] ==2){
                   11116:          k3=Tposprod[k1];
                   11117:          k4=Tposprod[k2];
                   11118:          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])) ){
                   11119:            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]]);
                   11120:            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);
                   11121:            return(1);
                   11122:          }
                   11123:        }
1.227     brouard  11124:       }
                   11125:     }
1.225     brouard  11126:   }
                   11127:   printf("ncoveff=%d, nqfveff=%d, ntveff=%d, nqtveff=%d, cptcovn=%d\n",ncoveff,nqfveff,ntveff,nqtveff,cptcovn);
                   11128:   fprintf(ficlog,"ncoveff=%d, nqfveff=%d, ntveff=%d, nqtveff=%d, cptcovn=%d\n",ncoveff,nqfveff,ntveff,nqtveff,cptcovn);
1.234     brouard  11129:   printf("ncovf=%d, ncovv=%d, ncova=%d, nsd=%d, nsq=%d\n",ncovf,ncovv,ncova,nsd,nsq);
                   11130:   fprintf(ficlog,"ncovf=%d, ncovv=%d, ncova=%d, nsd=%d, nsq=%d\n",ncovf,ncovv,ncova,nsd, nsq);
1.137     brouard  11131:   return (0); /* with covar[new additional covariate if product] and Tage if age */ 
1.164     brouard  11132:   /*endread:*/
1.225     brouard  11133:   printf("Exiting decodemodel: ");
                   11134:   return (1);
1.136     brouard  11135: }
                   11136: 
1.169     brouard  11137: int calandcheckages(int imx, int maxwav, double *agemin, double *agemax, int *nberr, int *nbwarn )
1.248     brouard  11138: {/* Check ages at death */
1.136     brouard  11139:   int i, m;
1.218     brouard  11140:   int firstone=0;
                   11141:   
1.136     brouard  11142:   for (i=1; i<=imx; i++) {
                   11143:     for(m=2; (m<= maxwav); m++) {
                   11144:       if (((int)mint[m][i]== 99) && (s[m][i] <= nlstate)){
                   11145:        anint[m][i]=9999;
1.216     brouard  11146:        if (s[m][i] != -2) /* Keeping initial status of unknown vital status */
                   11147:          s[m][i]=-1;
1.136     brouard  11148:       }
                   11149:       if((int)moisdc[i]==99 && (int)andc[i]==9999 && s[m][i]>nlstate){
1.260     brouard  11150:        *nberr = *nberr + 1;
1.218     brouard  11151:        if(firstone == 0){
                   11152:          firstone=1;
1.260     brouard  11153:        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  11154:        }
1.262     brouard  11155:        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  11156:        s[m][i]=-1;  /* Droping the death status */
1.136     brouard  11157:       }
                   11158:       if((int)moisdc[i]==99 && (int)andc[i]!=9999 && s[m][i]>nlstate){
1.169     brouard  11159:        (*nberr)++;
1.259     brouard  11160:        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  11161:        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  11162:        s[m][i]=-2; /* We prefer to skip it (and to skip it in version 0.8a1 too */
1.136     brouard  11163:       }
                   11164:     }
                   11165:   }
                   11166: 
                   11167:   for (i=1; i<=imx; i++)  {
                   11168:     agedc[i]=(moisdc[i]/12.+andc[i])-(moisnais[i]/12.+annais[i]);
                   11169:     for(m=firstpass; (m<= lastpass); m++){
1.214     brouard  11170:       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  11171:        if (s[m][i] >= nlstate+1) {
1.169     brouard  11172:          if(agedc[i]>0){
                   11173:            if((int)moisdc[i]!=99 && (int)andc[i]!=9999){
1.136     brouard  11174:              agev[m][i]=agedc[i];
1.214     brouard  11175:              /*if(moisdc[i]==99 && andc[i]==9999) s[m][i]=-1;*/
1.169     brouard  11176:            }else {
1.136     brouard  11177:              if ((int)andc[i]!=9999){
                   11178:                nbwarn++;
                   11179:                printf("Warning negative age at death: %ld line:%d\n",num[i],i);
                   11180:                fprintf(ficlog,"Warning negative age at death: %ld line:%d\n",num[i],i);
                   11181:                agev[m][i]=-1;
                   11182:              }
                   11183:            }
1.169     brouard  11184:          } /* agedc > 0 */
1.214     brouard  11185:        } /* end if */
1.136     brouard  11186:        else if(s[m][i] !=9){ /* Standard case, age in fractional
                   11187:                                 years but with the precision of a month */
                   11188:          agev[m][i]=(mint[m][i]/12.+1./24.+anint[m][i])-(moisnais[i]/12.+1./24.+annais[i]);
                   11189:          if((int)mint[m][i]==99 || (int)anint[m][i]==9999)
                   11190:            agev[m][i]=1;
                   11191:          else if(agev[m][i] < *agemin){ 
                   11192:            *agemin=agev[m][i];
                   11193:            printf(" Min anint[%d][%d]=%.2f annais[%d]=%.2f, agemin=%.2f\n",m,i,anint[m][i], i,annais[i], *agemin);
                   11194:          }
                   11195:          else if(agev[m][i] >*agemax){
                   11196:            *agemax=agev[m][i];
1.156     brouard  11197:            /* printf(" Max anint[%d][%d]=%.0f annais[%d]=%.0f, agemax=%.2f\n",m,i,anint[m][i], i,annais[i], *agemax);*/
1.136     brouard  11198:          }
                   11199:          /*agev[m][i]=anint[m][i]-annais[i];*/
                   11200:          /*     agev[m][i] = age[i]+2*m;*/
1.214     brouard  11201:        } /* en if 9*/
1.136     brouard  11202:        else { /* =9 */
1.214     brouard  11203:          /* printf("Debug num[%d]=%ld s[%d][%d]=%d\n",i,num[i], m,i, s[m][i]); */
1.136     brouard  11204:          agev[m][i]=1;
                   11205:          s[m][i]=-1;
                   11206:        }
                   11207:       }
1.214     brouard  11208:       else if(s[m][i]==0) /*= 0 Unknown */
1.136     brouard  11209:        agev[m][i]=1;
1.214     brouard  11210:       else{
                   11211:        printf("Warning, num[%d]=%ld, s[%d][%d]=%d\n", i, num[i], m, i,s[m][i]); 
                   11212:        fprintf(ficlog, "Warning, num[%d]=%ld, s[%d][%d]=%d\n", i, num[i], m, i,s[m][i]); 
                   11213:        agev[m][i]=0;
                   11214:       }
                   11215:     } /* End for lastpass */
                   11216:   }
1.136     brouard  11217:     
                   11218:   for (i=1; i<=imx; i++)  {
                   11219:     for(m=firstpass; (m<=lastpass); m++){
                   11220:       if (s[m][i] > (nlstate+ndeath)) {
1.169     brouard  11221:        (*nberr)++;
1.136     brouard  11222:        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);     
                   11223:        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);     
                   11224:        return 1;
                   11225:       }
                   11226:     }
                   11227:   }
                   11228: 
                   11229:   /*for (i=1; i<=imx; i++){
                   11230:   for (m=firstpass; (m<lastpass); m++){
                   11231:      printf("%ld %d %.lf %d %d\n", num[i],(covar[1][i]),agev[m][i],s[m][i],s[m+1][i]);
                   11232: }
                   11233: 
                   11234: }*/
                   11235: 
                   11236: 
1.139     brouard  11237:   printf("Total number of individuals= %d, Agemin = %.2f, Agemax= %.2f\n\n", imx, *agemin, *agemax);
                   11238:   fprintf(ficlog,"Total number of individuals= %d, Agemin = %.2f, Agemax= %.2f\n\n", imx, *agemin, *agemax); 
1.136     brouard  11239: 
                   11240:   return (0);
1.164     brouard  11241:  /* endread:*/
1.136     brouard  11242:     printf("Exiting calandcheckages: ");
                   11243:     return (1);
                   11244: }
                   11245: 
1.172     brouard  11246: #if defined(_MSC_VER)
                   11247: /*printf("Visual C++ compiler: %s \n;", _MSC_FULL_VER);*/
                   11248: /*fprintf(ficlog, "Visual C++ compiler: %s \n;", _MSC_FULL_VER);*/
                   11249: //#include "stdafx.h"
                   11250: //#include <stdio.h>
                   11251: //#include <tchar.h>
                   11252: //#include <windows.h>
                   11253: //#include <iostream>
                   11254: typedef BOOL(WINAPI *LPFN_ISWOW64PROCESS) (HANDLE, PBOOL);
                   11255: 
                   11256: LPFN_ISWOW64PROCESS fnIsWow64Process;
                   11257: 
                   11258: BOOL IsWow64()
                   11259: {
                   11260:        BOOL bIsWow64 = FALSE;
                   11261: 
                   11262:        //typedef BOOL (APIENTRY *LPFN_ISWOW64PROCESS)
                   11263:        //  (HANDLE, PBOOL);
                   11264: 
                   11265:        //LPFN_ISWOW64PROCESS fnIsWow64Process;
                   11266: 
                   11267:        HMODULE module = GetModuleHandle(_T("kernel32"));
                   11268:        const char funcName[] = "IsWow64Process";
                   11269:        fnIsWow64Process = (LPFN_ISWOW64PROCESS)
                   11270:                GetProcAddress(module, funcName);
                   11271: 
                   11272:        if (NULL != fnIsWow64Process)
                   11273:        {
                   11274:                if (!fnIsWow64Process(GetCurrentProcess(),
                   11275:                        &bIsWow64))
                   11276:                        //throw std::exception("Unknown error");
                   11277:                        printf("Unknown error\n");
                   11278:        }
                   11279:        return bIsWow64 != FALSE;
                   11280: }
                   11281: #endif
1.177     brouard  11282: 
1.191     brouard  11283: void syscompilerinfo(int logged)
1.292     brouard  11284: {
                   11285: #include <stdint.h>
                   11286: 
                   11287:   /* #include "syscompilerinfo.h"*/
1.185     brouard  11288:    /* command line Intel compiler 32bit windows, XP compatible:*/
                   11289:    /* /GS /W3 /Gy
                   11290:       /Zc:wchar_t /Zi /O2 /Fd"Release\vc120.pdb" /D "WIN32" /D "NDEBUG" /D
                   11291:       "_CONSOLE" /D "_LIB" /D "_USING_V110_SDK71_" /D "_UNICODE" /D
                   11292:       "UNICODE" /Qipo /Zc:forScope /Gd /Oi /MT /Fa"Release\" /EHsc /nologo
1.186     brouard  11293:       /Fo"Release\" /Qprof-dir "Release\" /Fp"Release\IMaCh.pch"
                   11294:    */ 
                   11295:    /* 64 bits */
1.185     brouard  11296:    /*
                   11297:      /GS /W3 /Gy
                   11298:      /Zc:wchar_t /Zi /O2 /Fd"x64\Release\vc120.pdb" /D "WIN32" /D "NDEBUG"
                   11299:      /D "_CONSOLE" /D "_LIB" /D "_UNICODE" /D "UNICODE" /Qipo /Zc:forScope
                   11300:      /Oi /MD /Fa"x64\Release\" /EHsc /nologo /Fo"x64\Release\" /Qprof-dir
                   11301:      "x64\Release\" /Fp"x64\Release\IMaCh.pch" */
                   11302:    /* Optimization are useless and O3 is slower than O2 */
                   11303:    /*
                   11304:      /GS /W3 /Gy /Zc:wchar_t /Zi /O3 /Fd"x64\Release\vc120.pdb" /D "WIN32" 
                   11305:      /D "NDEBUG" /D "_CONSOLE" /D "_LIB" /D "_UNICODE" /D "UNICODE" /Qipo 
                   11306:      /Zc:forScope /Oi /MD /Fa"x64\Release\" /EHsc /nologo /Qparallel 
                   11307:      /Fo"x64\Release\" /Qprof-dir "x64\Release\" /Fp"x64\Release\IMaCh.pch" 
                   11308:    */
1.186     brouard  11309:    /* Link is */ /* /OUT:"visual studio
1.185     brouard  11310:       2013\Projects\IMaCh\Release\IMaCh.exe" /MANIFEST /NXCOMPAT
                   11311:       /PDB:"visual studio
                   11312:       2013\Projects\IMaCh\Release\IMaCh.pdb" /DYNAMICBASE
                   11313:       "kernel32.lib" "user32.lib" "gdi32.lib" "winspool.lib"
                   11314:       "comdlg32.lib" "advapi32.lib" "shell32.lib" "ole32.lib"
                   11315:       "oleaut32.lib" "uuid.lib" "odbc32.lib" "odbccp32.lib"
                   11316:       /MACHINE:X86 /OPT:REF /SAFESEH /INCREMENTAL:NO
                   11317:       /SUBSYSTEM:CONSOLE",5.01" /MANIFESTUAC:"level='asInvoker'
                   11318:       uiAccess='false'"
                   11319:       /ManifestFile:"Release\IMaCh.exe.intermediate.manifest" /OPT:ICF
                   11320:       /NOLOGO /TLBID:1
                   11321:    */
1.292     brouard  11322: 
                   11323: 
1.177     brouard  11324: #if defined __INTEL_COMPILER
1.178     brouard  11325: #if defined(__GNUC__)
                   11326:        struct utsname sysInfo;  /* For Intel on Linux and OS/X */
                   11327: #endif
1.177     brouard  11328: #elif defined(__GNUC__) 
1.179     brouard  11329: #ifndef  __APPLE__
1.174     brouard  11330: #include <gnu/libc-version.h>  /* Only on gnu */
1.179     brouard  11331: #endif
1.177     brouard  11332:    struct utsname sysInfo;
1.178     brouard  11333:    int cross = CROSS;
                   11334:    if (cross){
                   11335:           printf("Cross-");
1.191     brouard  11336:           if(logged) fprintf(ficlog, "Cross-");
1.178     brouard  11337:    }
1.174     brouard  11338: #endif
                   11339: 
1.191     brouard  11340:    printf("Compiled with:");if(logged)fprintf(ficlog,"Compiled with:");
1.169     brouard  11341: #if defined(__clang__)
1.191     brouard  11342:    printf(" Clang/LLVM");if(logged)fprintf(ficlog," Clang/LLVM");      /* Clang/LLVM. ---------------------------------------------- */
1.169     brouard  11343: #endif
                   11344: #if defined(__ICC) || defined(__INTEL_COMPILER)
1.191     brouard  11345:    printf(" Intel ICC/ICPC");if(logged)fprintf(ficlog," Intel ICC/ICPC");/* Intel ICC/ICPC. ------------------------------------------ */
1.169     brouard  11346: #endif
                   11347: #if defined(__GNUC__) || defined(__GNUG__)
1.191     brouard  11348:    printf(" GNU GCC/G++");if(logged)fprintf(ficlog," GNU GCC/G++");/* GNU GCC/G++. --------------------------------------------- */
1.169     brouard  11349: #endif
                   11350: #if defined(__HP_cc) || defined(__HP_aCC)
1.191     brouard  11351:    printf(" Hewlett-Packard C/aC++");if(logged)fprintf(fcilog," Hewlett-Packard C/aC++"); /* Hewlett-Packard C/aC++. ---------------------------------- */
1.169     brouard  11352: #endif
                   11353: #if defined(__IBMC__) || defined(__IBMCPP__)
1.191     brouard  11354:    printf(" IBM XL C/C++"); if(logged) fprintf(ficlog," IBM XL C/C++");/* IBM XL C/C++. -------------------------------------------- */
1.169     brouard  11355: #endif
                   11356: #if defined(_MSC_VER)
1.191     brouard  11357:    printf(" Microsoft Visual Studio");if(logged)fprintf(ficlog," Microsoft Visual Studio");/* Microsoft Visual Studio. --------------------------------- */
1.169     brouard  11358: #endif
                   11359: #if defined(__PGI)
1.191     brouard  11360:    printf(" Portland Group PGCC/PGCPP");if(logged) fprintf(ficlog," Portland Group PGCC/PGCPP");/* Portland Group PGCC/PGCPP. ------------------------------- */
1.169     brouard  11361: #endif
                   11362: #if defined(__SUNPRO_C) || defined(__SUNPRO_CC)
1.191     brouard  11363:    printf(" Oracle Solaris Studio");if(logged)fprintf(ficlog," Oracle Solaris Studio\n");/* Oracle Solaris Studio. ----------------------------------- */
1.167     brouard  11364: #endif
1.191     brouard  11365:    printf(" for "); if (logged) fprintf(ficlog, " for ");
1.169     brouard  11366:    
1.167     brouard  11367: // http://stackoverflow.com/questions/4605842/how-to-identify-platform-compiler-from-preprocessor-macros
                   11368: #ifdef _WIN32 // note the underscore: without it, it's not msdn official!
                   11369:     // Windows (x64 and x86)
1.191     brouard  11370:    printf("Windows (x64 and x86) ");if(logged) fprintf(ficlog,"Windows (x64 and x86) ");
1.167     brouard  11371: #elif __unix__ // all unices, not all compilers
                   11372:     // Unix
1.191     brouard  11373:    printf("Unix ");if(logged) fprintf(ficlog,"Unix ");
1.167     brouard  11374: #elif __linux__
                   11375:     // linux
1.191     brouard  11376:    printf("linux ");if(logged) fprintf(ficlog,"linux ");
1.167     brouard  11377: #elif __APPLE__
1.174     brouard  11378:     // Mac OS, not sure if this is covered by __posix__ and/or __unix__ though..
1.191     brouard  11379:    printf("Mac OS ");if(logged) fprintf(ficlog,"Mac OS ");
1.167     brouard  11380: #endif
                   11381: 
                   11382: /*  __MINGW32__          */
                   11383: /*  __CYGWIN__  */
                   11384: /* __MINGW64__  */
                   11385: // http://msdn.microsoft.com/en-us/library/b0084kay.aspx
                   11386: /* _MSC_VER  //the Visual C++ compiler is 17.00.51106.1, the _MSC_VER macro evaluates to 1700. Type cl /?  */
                   11387: /* _MSC_FULL_VER //the Visual C++ compiler is 15.00.20706.01, the _MSC_FULL_VER macro evaluates to 150020706 */
                   11388: /* _WIN64  // Defined for applications for Win64. */
                   11389: /* _M_X64 // Defined for compilations that target x64 processors. */
                   11390: /* _DEBUG // Defined when you compile with /LDd, /MDd, and /MTd. */
1.171     brouard  11391: 
1.167     brouard  11392: #if UINTPTR_MAX == 0xffffffff
1.191     brouard  11393:    printf(" 32-bit"); if(logged) fprintf(ficlog," 32-bit");/* 32-bit */
1.167     brouard  11394: #elif UINTPTR_MAX == 0xffffffffffffffff
1.191     brouard  11395:    printf(" 64-bit"); if(logged) fprintf(ficlog," 64-bit");/* 64-bit */
1.167     brouard  11396: #else
1.191     brouard  11397:    printf(" wtf-bit"); if(logged) fprintf(ficlog," wtf-bit");/* wtf */
1.167     brouard  11398: #endif
                   11399: 
1.169     brouard  11400: #if defined(__GNUC__)
                   11401: # if defined(__GNUC_PATCHLEVEL__)
                   11402: #  define __GNUC_VERSION__ (__GNUC__ * 10000 \
                   11403:                             + __GNUC_MINOR__ * 100 \
                   11404:                             + __GNUC_PATCHLEVEL__)
                   11405: # else
                   11406: #  define __GNUC_VERSION__ (__GNUC__ * 10000 \
                   11407:                             + __GNUC_MINOR__ * 100)
                   11408: # endif
1.174     brouard  11409:    printf(" using GNU C version %d.\n", __GNUC_VERSION__);
1.191     brouard  11410:    if(logged) fprintf(ficlog, " using GNU C version %d.\n", __GNUC_VERSION__);
1.176     brouard  11411: 
                   11412:    if (uname(&sysInfo) != -1) {
                   11413:      printf("Running on: %s %s %s %s %s\n",sysInfo.sysname, sysInfo.nodename, sysInfo.release, sysInfo.version, sysInfo.machine);
1.191     brouard  11414:         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  11415:    }
                   11416:    else
                   11417:       perror("uname() error");
1.179     brouard  11418:    //#ifndef __INTEL_COMPILER 
                   11419: #if !defined (__INTEL_COMPILER) && !defined(__APPLE__)
1.174     brouard  11420:    printf("GNU libc version: %s\n", gnu_get_libc_version()); 
1.191     brouard  11421:    if(logged) fprintf(ficlog,"GNU libc version: %s\n", gnu_get_libc_version());
1.177     brouard  11422: #endif
1.169     brouard  11423: #endif
1.172     brouard  11424: 
1.286     brouard  11425:    //   void main ()
1.172     brouard  11426:    //   {
1.169     brouard  11427: #if defined(_MSC_VER)
1.174     brouard  11428:    if (IsWow64()){
1.191     brouard  11429:           printf("\nThe program (probably compiled for 32bit) is running under WOW64 (64bit) emulation.\n");
                   11430:           if (logged) fprintf(ficlog, "\nThe program (probably compiled for 32bit) is running under WOW64 (64bit) emulation.\n");
1.174     brouard  11431:    }
                   11432:    else{
1.191     brouard  11433:           printf("\nThe program is not running under WOW64 (i.e probably on a 64bit Windows).\n");
                   11434:           if (logged) fprintf(ficlog, "\nThe programm is not running under WOW64 (i.e probably on a 64bit Windows).\n");
1.174     brouard  11435:    }
1.172     brouard  11436:    //     printf("\nPress Enter to continue...");
                   11437:    //     getchar();
                   11438:    //   }
                   11439: 
1.169     brouard  11440: #endif
                   11441:    
1.167     brouard  11442: 
1.219     brouard  11443: }
1.136     brouard  11444: 
1.219     brouard  11445: int prevalence_limit(double *p, double **prlim, double ageminpar, double agemaxpar, double ftolpl, int *ncvyearp){
1.288     brouard  11446:   /*--------------- Prevalence limit  (forward period or forward stable prevalence) --------------*/
1.332     brouard  11447:   /* Computes the prevalence limit for each combination of the dummy covariates */
1.235     brouard  11448:   int i, j, k, i1, k4=0, nres=0 ;
1.202     brouard  11449:   /* double ftolpl = 1.e-10; */
1.180     brouard  11450:   double age, agebase, agelim;
1.203     brouard  11451:   double tot;
1.180     brouard  11452: 
1.202     brouard  11453:   strcpy(filerespl,"PL_");
                   11454:   strcat(filerespl,fileresu);
                   11455:   if((ficrespl=fopen(filerespl,"w"))==NULL) {
1.288     brouard  11456:     printf("Problem with forward period (stable) prevalence resultfile: %s\n", filerespl);return 1;
                   11457:     fprintf(ficlog,"Problem with forward period (stable) prevalence resultfile: %s\n", filerespl);return 1;
1.202     brouard  11458:   }
1.288     brouard  11459:   printf("\nComputing forward period (stable) prevalence: result on file '%s' \n", filerespl);
                   11460:   fprintf(ficlog,"\nComputing forward period (stable) prevalence: result on file '%s' \n", filerespl);
1.202     brouard  11461:   pstamp(ficrespl);
1.288     brouard  11462:   fprintf(ficrespl,"# Forward period (stable) prevalence. Precision given by ftolpl=%g \n", ftolpl);
1.202     brouard  11463:   fprintf(ficrespl,"#Age ");
                   11464:   for(i=1; i<=nlstate;i++) fprintf(ficrespl,"%d-%d ",i,i);
                   11465:   fprintf(ficrespl,"\n");
1.180     brouard  11466:   
1.219     brouard  11467:   /* prlim=matrix(1,nlstate,1,nlstate);*/ /* back in main */
1.180     brouard  11468: 
1.219     brouard  11469:   agebase=ageminpar;
                   11470:   agelim=agemaxpar;
1.180     brouard  11471: 
1.227     brouard  11472:   /* i1=pow(2,ncoveff); */
1.234     brouard  11473:   i1=pow(2,cptcoveff); /* Number of combination of dummy covariates */
1.219     brouard  11474:   if (cptcovn < 1){i1=1;}
1.180     brouard  11475: 
1.238     brouard  11476:   for(k=1; k<=i1;k++){ /* For each combination k of dummy covariates in the model */
                   11477:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.253     brouard  11478:       if(i1 != 1 && TKresult[nres]!= k)
1.238     brouard  11479:        continue;
1.235     brouard  11480: 
1.238     brouard  11481:       /* for(cptcov=1,k=0;cptcov<=i1;cptcov++){ */
                   11482:       /* for(cptcov=1,k=0;cptcov<=1;cptcov++){ */
                   11483:       //for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){
                   11484:       /* k=k+1; */
                   11485:       /* to clean */
1.332     brouard  11486:       /*printf("cptcov=%d cptcod=%d codtab=%d\n",cptcov, cptcod,codtabm(cptcod,cptcov));*/
1.238     brouard  11487:       fprintf(ficrespl,"#******");
                   11488:       printf("#******");
                   11489:       fprintf(ficlog,"#******");
                   11490:       for(j=1;j<=cptcoveff ;j++) {/* all covariates */
1.332     brouard  11491:        /* fprintf(ficrespl," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,Tvaraff[j])]); /\* Here problem for varying dummy*\/ */
                   11492:        fprintf(ficrespl," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); /* Here problem for varying dummy*/
                   11493:        printf(" V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]);
                   11494:        fprintf(ficlog," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]);
1.238     brouard  11495:       }
                   11496:       for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
                   11497:        printf(" V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
                   11498:        fprintf(ficrespl," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
                   11499:        fprintf(ficlog," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
                   11500:       }
                   11501:       fprintf(ficrespl,"******\n");
                   11502:       printf("******\n");
                   11503:       fprintf(ficlog,"******\n");
                   11504:       if(invalidvarcomb[k]){
                   11505:        printf("\nCombination (%d) ignored because no case \n",k); 
                   11506:        fprintf(ficrespl,"#Combination (%d) ignored because no case \n",k); 
                   11507:        fprintf(ficlog,"\nCombination (%d) ignored because no case \n",k); 
                   11508:        continue;
                   11509:       }
1.219     brouard  11510: 
1.238     brouard  11511:       fprintf(ficrespl,"#Age ");
                   11512:       for(j=1;j<=cptcoveff;j++) {
1.332     brouard  11513:        fprintf(ficrespl,"V%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]);
1.238     brouard  11514:       }
                   11515:       for(i=1; i<=nlstate;i++) fprintf(ficrespl,"  %d-%d   ",i,i);
                   11516:       fprintf(ficrespl,"Total Years_to_converge\n");
1.227     brouard  11517:     
1.238     brouard  11518:       for (age=agebase; age<=agelim; age++){
                   11519:        /* for (age=agebase; age<=agebase; age++){ */
                   11520:        prevalim(prlim, nlstate, p, age, oldm, savm, ftolpl, ncvyearp, k, nres);
                   11521:        fprintf(ficrespl,"%.0f ",age );
                   11522:        for(j=1;j<=cptcoveff;j++)
1.332     brouard  11523:          fprintf(ficrespl,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]);
1.238     brouard  11524:        tot=0.;
                   11525:        for(i=1; i<=nlstate;i++){
                   11526:          tot +=  prlim[i][i];
                   11527:          fprintf(ficrespl," %.5f", prlim[i][i]);
                   11528:        }
                   11529:        fprintf(ficrespl," %.3f %d\n", tot, *ncvyearp);
                   11530:       } /* Age */
                   11531:       /* was end of cptcod */
                   11532:     } /* cptcov */
                   11533:   } /* nres */
1.219     brouard  11534:   return 0;
1.180     brouard  11535: }
                   11536: 
1.218     brouard  11537: 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  11538:        /*--------------- Back Prevalence limit  (backward stable prevalence) --------------*/
1.218     brouard  11539:        
                   11540:        /* Computes the back prevalence limit  for any combination      of covariate values 
                   11541:    * at any age between ageminpar and agemaxpar
                   11542:         */
1.235     brouard  11543:   int i, j, k, i1, nres=0 ;
1.217     brouard  11544:   /* double ftolpl = 1.e-10; */
                   11545:   double age, agebase, agelim;
                   11546:   double tot;
1.218     brouard  11547:   /* double ***mobaverage; */
                   11548:   /* double     **dnewm, **doldm, **dsavm;  /\* for use *\/ */
1.217     brouard  11549: 
                   11550:   strcpy(fileresplb,"PLB_");
                   11551:   strcat(fileresplb,fileresu);
                   11552:   if((ficresplb=fopen(fileresplb,"w"))==NULL) {
1.288     brouard  11553:     printf("Problem with backward prevalence resultfile: %s\n", fileresplb);return 1;
                   11554:     fprintf(ficlog,"Problem with backward prevalence resultfile: %s\n", fileresplb);return 1;
1.217     brouard  11555:   }
1.288     brouard  11556:   printf("Computing backward prevalence: result on file '%s' \n", fileresplb);
                   11557:   fprintf(ficlog,"Computing backward prevalence: result on file '%s' \n", fileresplb);
1.217     brouard  11558:   pstamp(ficresplb);
1.288     brouard  11559:   fprintf(ficresplb,"# Backward prevalence. Precision given by ftolpl=%g \n", ftolpl);
1.217     brouard  11560:   fprintf(ficresplb,"#Age ");
                   11561:   for(i=1; i<=nlstate;i++) fprintf(ficresplb,"%d-%d ",i,i);
                   11562:   fprintf(ficresplb,"\n");
                   11563:   
1.218     brouard  11564:   
                   11565:   /* prlim=matrix(1,nlstate,1,nlstate);*/ /* back in main */
                   11566:   
                   11567:   agebase=ageminpar;
                   11568:   agelim=agemaxpar;
                   11569:   
                   11570:   
1.227     brouard  11571:   i1=pow(2,cptcoveff);
1.218     brouard  11572:   if (cptcovn < 1){i1=1;}
1.227     brouard  11573:   
1.238     brouard  11574:   for(nres=1; nres <= nresult; nres++){ /* For each resultline */
                   11575:     for(k=1; k<=i1;k++){ /* For any combination of dummy covariates, fixed and varying */
1.253     brouard  11576:      if(i1 != 1 && TKresult[nres]!= k)
1.238     brouard  11577:        continue;
1.332     brouard  11578:      /*printf("cptcov=%d cptcod=%d codtab=%d\n",cptcov, cptcod,codtabm(cptcod,cptcov));*/
1.238     brouard  11579:       fprintf(ficresplb,"#******");
                   11580:       printf("#******");
                   11581:       fprintf(ficlog,"#******");
                   11582:       for(j=1;j<=cptcoveff ;j++) {/* all covariates */
1.332     brouard  11583:        fprintf(ficresplb," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]);
                   11584:        printf(" V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]);
                   11585:        fprintf(ficlog," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]);
1.238     brouard  11586:       }
                   11587:       for (j=1; j<= nsq; j++){ /* For each selected (single) quantitative value */
1.332     brouard  11588:        printf(" V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]);
                   11589:        fprintf(ficresplb," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]);
                   11590:        fprintf(ficlog," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]);
1.238     brouard  11591:       }
                   11592:       fprintf(ficresplb,"******\n");
                   11593:       printf("******\n");
                   11594:       fprintf(ficlog,"******\n");
                   11595:       if(invalidvarcomb[k]){
                   11596:        printf("\nCombination (%d) ignored because no cases \n",k); 
                   11597:        fprintf(ficresplb,"#Combination (%d) ignored because no cases \n",k); 
                   11598:        fprintf(ficlog,"\nCombination (%d) ignored because no cases \n",k); 
                   11599:        continue;
                   11600:       }
1.218     brouard  11601:     
1.238     brouard  11602:       fprintf(ficresplb,"#Age ");
                   11603:       for(j=1;j<=cptcoveff;j++) {
1.332     brouard  11604:        fprintf(ficresplb,"V%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]);
1.238     brouard  11605:       }
                   11606:       for(i=1; i<=nlstate;i++) fprintf(ficresplb,"  %d-%d   ",i,i);
                   11607:       fprintf(ficresplb,"Total Years_to_converge\n");
1.218     brouard  11608:     
                   11609:     
1.238     brouard  11610:       for (age=agebase; age<=agelim; age++){
                   11611:        /* for (age=agebase; age<=agebase; age++){ */
                   11612:        if(mobilavproj > 0){
                   11613:          /* bprevalim(bprlim, mobaverage, nlstate, p, age, ageminpar, agemaxpar, oldm, savm, doldm, dsavm, ftolpl, ncvyearp, k); */
                   11614:          /* bprevalim(bprlim, mobaverage, nlstate, p, age, oldm, savm, dnewm, doldm, dsavm, ftolpl, ncvyearp, k); */
1.242     brouard  11615:          bprevalim(bprlim, mobaverage, nlstate, p, age, ftolpl, ncvyearp, k, nres);
1.238     brouard  11616:        }else if (mobilavproj == 0){
                   11617:          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);
                   11618:          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);
                   11619:          exit(1);
                   11620:        }else{
                   11621:          /* bprevalim(bprlim, probs, nlstate, p, age, oldm, savm, dnewm, doldm, dsavm, ftolpl, ncvyearp, k); */
1.242     brouard  11622:          bprevalim(bprlim, probs, nlstate, p, age, ftolpl, ncvyearp, k,nres);
1.266     brouard  11623:          /* printf("TOTOT\n"); */
                   11624:           /* exit(1); */
1.238     brouard  11625:        }
                   11626:        fprintf(ficresplb,"%.0f ",age );
                   11627:        for(j=1;j<=cptcoveff;j++)
1.332     brouard  11628:          fprintf(ficresplb,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]);
1.238     brouard  11629:        tot=0.;
                   11630:        for(i=1; i<=nlstate;i++){
                   11631:          tot +=  bprlim[i][i];
                   11632:          fprintf(ficresplb," %.5f", bprlim[i][i]);
                   11633:        }
                   11634:        fprintf(ficresplb," %.3f %d\n", tot, *ncvyearp);
                   11635:       } /* Age */
                   11636:       /* was end of cptcod */
1.255     brouard  11637:       /*fprintf(ficresplb,"\n");*/ /* Seems to be necessary for gnuplot only if two result lines and no covariate. */
1.238     brouard  11638:     } /* end of any combination */
                   11639:   } /* end of nres */  
1.218     brouard  11640:   /* hBijx(p, bage, fage); */
                   11641:   /* fclose(ficrespijb); */
                   11642:   
                   11643:   return 0;
1.217     brouard  11644: }
1.218     brouard  11645:  
1.180     brouard  11646: int hPijx(double *p, int bage, int fage){
                   11647:     /*------------- h Pij x at various ages ------------*/
1.336   ! brouard  11648:   /* to be optimized with precov */
1.180     brouard  11649:   int stepsize;
                   11650:   int agelim;
                   11651:   int hstepm;
                   11652:   int nhstepm;
1.235     brouard  11653:   int h, i, i1, j, k, k4, nres=0;
1.180     brouard  11654: 
                   11655:   double agedeb;
                   11656:   double ***p3mat;
                   11657: 
1.201     brouard  11658:     strcpy(filerespij,"PIJ_");  strcat(filerespij,fileresu);
1.180     brouard  11659:     if((ficrespij=fopen(filerespij,"w"))==NULL) {
                   11660:       printf("Problem with Pij resultfile: %s\n", filerespij); return 1;
                   11661:       fprintf(ficlog,"Problem with Pij resultfile: %s\n", filerespij); return 1;
                   11662:     }
                   11663:     printf("Computing pij: result on file '%s' \n", filerespij);
                   11664:     fprintf(ficlog,"Computing pij: result on file '%s' \n", filerespij);
                   11665:   
                   11666:     stepsize=(int) (stepm+YEARM-1)/YEARM;
                   11667:     /*if (stepm<=24) stepsize=2;*/
                   11668: 
                   11669:     agelim=AGESUP;
                   11670:     hstepm=stepsize*YEARM; /* Every year of age */
                   11671:     hstepm=hstepm/stepm; /* Typically 2 years, = 2/6 months = 4 */ 
1.218     brouard  11672:                
1.180     brouard  11673:     /* hstepm=1;   aff par mois*/
                   11674:     pstamp(ficrespij);
                   11675:     fprintf(ficrespij,"#****** h Pij x Probability to be in state j at age x+h being in i at x ");
1.227     brouard  11676:     i1= pow(2,cptcoveff);
1.218     brouard  11677:                /* for(cptcov=1,k=0;cptcov<=i1;cptcov++){ */
                   11678:                /*    /\*for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*\/ */
                   11679:                /*      k=k+1;  */
1.235     brouard  11680:     for(nres=1; nres <= nresult; nres++) /* For each resultline */
                   11681:     for(k=1; k<=i1;k++){
1.253     brouard  11682:       if(i1 != 1 && TKresult[nres]!= k)
1.235     brouard  11683:        continue;
1.183     brouard  11684:       fprintf(ficrespij,"\n#****** ");
1.227     brouard  11685:       for(j=1;j<=cptcoveff;j++) 
1.332     brouard  11686:        fprintf(ficrespij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]);
1.235     brouard  11687:       for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
                   11688:        printf(" V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
                   11689:        fprintf(ficrespij," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
                   11690:       }
1.183     brouard  11691:       fprintf(ficrespij,"******\n");
                   11692:       
                   11693:       for (agedeb=fage; agedeb>=bage; agedeb--){ /* If stepm=6 months */
                   11694:        nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */ 
                   11695:        nhstepm = nhstepm/hstepm; /* Typically 40/4=10 */
                   11696:        
                   11697:        /*        nhstepm=nhstepm*YEARM; aff par mois*/
1.180     brouard  11698:        
1.183     brouard  11699:        p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   11700:        oldm=oldms;savm=savms;
1.235     brouard  11701:        hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k, nres);  
1.183     brouard  11702:        fprintf(ficrespij,"# Cov Agex agex+h hpijx with i,j=");
                   11703:        for(i=1; i<=nlstate;i++)
                   11704:          for(j=1; j<=nlstate+ndeath;j++)
                   11705:            fprintf(ficrespij," %1d-%1d",i,j);
                   11706:        fprintf(ficrespij,"\n");
                   11707:        for (h=0; h<=nhstepm; h++){
                   11708:          /*agedebphstep = agedeb + h*hstepm/YEARM*stepm;*/
                   11709:          fprintf(ficrespij,"%d %3.f %3.f",k, agedeb, agedeb + h*hstepm/YEARM*stepm );
1.180     brouard  11710:          for(i=1; i<=nlstate;i++)
                   11711:            for(j=1; j<=nlstate+ndeath;j++)
1.183     brouard  11712:              fprintf(ficrespij," %.5f", p3mat[i][j][h]);
1.180     brouard  11713:          fprintf(ficrespij,"\n");
                   11714:        }
1.183     brouard  11715:        free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   11716:        fprintf(ficrespij,"\n");
                   11717:       }
1.180     brouard  11718:       /*}*/
                   11719:     }
1.218     brouard  11720:     return 0;
1.180     brouard  11721: }
1.218     brouard  11722:  
                   11723:  int hBijx(double *p, int bage, int fage, double ***prevacurrent){
1.217     brouard  11724:     /*------------- h Bij x at various ages ------------*/
1.336   ! brouard  11725:     /* To be optimized with precov */
1.217     brouard  11726:   int stepsize;
1.218     brouard  11727:   /* int agelim; */
                   11728:        int ageminl;
1.217     brouard  11729:   int hstepm;
                   11730:   int nhstepm;
1.238     brouard  11731:   int h, i, i1, j, k, nres;
1.218     brouard  11732:        
1.217     brouard  11733:   double agedeb;
                   11734:   double ***p3mat;
1.218     brouard  11735:        
                   11736:   strcpy(filerespijb,"PIJB_");  strcat(filerespijb,fileresu);
                   11737:   if((ficrespijb=fopen(filerespijb,"w"))==NULL) {
                   11738:     printf("Problem with Pij back resultfile: %s\n", filerespijb); return 1;
                   11739:     fprintf(ficlog,"Problem with Pij back resultfile: %s\n", filerespijb); return 1;
                   11740:   }
                   11741:   printf("Computing pij back: result on file '%s' \n", filerespijb);
                   11742:   fprintf(ficlog,"Computing pij back: result on file '%s' \n", filerespijb);
                   11743:   
                   11744:   stepsize=(int) (stepm+YEARM-1)/YEARM;
                   11745:   /*if (stepm<=24) stepsize=2;*/
1.217     brouard  11746:   
1.218     brouard  11747:   /* agelim=AGESUP; */
1.289     brouard  11748:   ageminl=AGEINF; /* was 30 */
1.218     brouard  11749:   hstepm=stepsize*YEARM; /* Every year of age */
                   11750:   hstepm=hstepm/stepm; /* Typically 2 years, = 2/6 months = 4 */
                   11751:   
                   11752:   /* hstepm=1;   aff par mois*/
                   11753:   pstamp(ficrespijb);
1.255     brouard  11754:   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  11755:   i1= pow(2,cptcoveff);
1.218     brouard  11756:   /* for(cptcov=1,k=0;cptcov<=i1;cptcov++){ */
                   11757:   /*    /\*for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*\/ */
                   11758:   /*   k=k+1;  */
1.238     brouard  11759:   for(nres=1; nres <= nresult; nres++){ /* For each resultline */
                   11760:     for(k=1; k<=i1;k++){ /* For any combination of dummy covariates, fixed and varying */
1.253     brouard  11761:       if(i1 != 1 && TKresult[nres]!= k)
1.238     brouard  11762:        continue;
                   11763:       fprintf(ficrespijb,"\n#****** ");
                   11764:       for(j=1;j<=cptcoveff;j++)
1.332     brouard  11765:        fprintf(ficrespijb,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]);
1.238     brouard  11766:       for (j=1; j<= nsq; j++){ /* For each selected (single) quantitative value */
1.332     brouard  11767:        fprintf(ficrespijb," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]);
1.238     brouard  11768:       }
                   11769:       fprintf(ficrespijb,"******\n");
1.264     brouard  11770:       if(invalidvarcomb[k]){  /* Is it necessary here? */
1.238     brouard  11771:        fprintf(ficrespijb,"\n#Combination (%d) ignored because no cases \n",k); 
                   11772:        continue;
                   11773:       }
                   11774:       
                   11775:       /* for (agedeb=fage; agedeb>=bage; agedeb--){ /\* If stepm=6 months *\/ */
                   11776:       for (agedeb=bage; agedeb<=fage; agedeb++){ /* If stepm=6 months and estepm=24 (2 years) */
                   11777:        /* nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm); /\* Typically 20 years = 20*12/6=40 *\/ */
1.297     brouard  11778:        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 */
                   11779:        nhstepm = nhstepm/hstepm; /* Typically 40/4=10, because estepm=24 stepm=6 => hstepm=24/6=4 or 28*/
1.238     brouard  11780:        
                   11781:        /*        nhstepm=nhstepm*YEARM; aff par mois*/
                   11782:        
1.266     brouard  11783:        p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm); /* We can't have it at an upper level because of nhstepm */
                   11784:        /* and memory limitations if stepm is small */
                   11785: 
1.238     brouard  11786:        /* oldm=oldms;savm=savms; */
                   11787:        /* hbxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);   */
1.325     brouard  11788:        hbxij(p3mat,nhstepm,agedeb,hstepm,p,prevacurrent,nlstate,stepm, k, nres);/* Bug valgrind */
1.238     brouard  11789:        /* hbxij(p3mat,nhstepm,agedeb,hstepm,p,prevacurrent,nlstate,stepm,oldm,savm, dnewm, doldm, dsavm, k); */
1.255     brouard  11790:        fprintf(ficrespijb,"# Cov Agex agex-h hbijx with i,j=");
1.217     brouard  11791:        for(i=1; i<=nlstate;i++)
                   11792:          for(j=1; j<=nlstate+ndeath;j++)
1.238     brouard  11793:            fprintf(ficrespijb," %1d-%1d",i,j);
1.217     brouard  11794:        fprintf(ficrespijb,"\n");
1.238     brouard  11795:        for (h=0; h<=nhstepm; h++){
                   11796:          /*agedebphstep = agedeb + h*hstepm/YEARM*stepm;*/
                   11797:          fprintf(ficrespijb,"%d %3.f %3.f",k, agedeb, agedeb - h*hstepm/YEARM*stepm );
                   11798:          /* fprintf(ficrespijb,"%d %3.f %3.f",k, agedeb, agedeb + h*hstepm/YEARM*stepm ); */
                   11799:          for(i=1; i<=nlstate;i++)
                   11800:            for(j=1; j<=nlstate+ndeath;j++)
1.325     brouard  11801:              fprintf(ficrespijb," %.5f", p3mat[i][j][h]);/* Bug valgrind */
1.238     brouard  11802:          fprintf(ficrespijb,"\n");
                   11803:        }
                   11804:        free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   11805:        fprintf(ficrespijb,"\n");
                   11806:       } /* end age deb */
                   11807:     } /* end combination */
                   11808:   } /* end nres */
1.218     brouard  11809:   return 0;
                   11810:  } /*  hBijx */
1.217     brouard  11811: 
1.180     brouard  11812: 
1.136     brouard  11813: /***********************************************/
                   11814: /**************** Main Program *****************/
                   11815: /***********************************************/
                   11816: 
                   11817: int main(int argc, char *argv[])
                   11818: {
                   11819: #ifdef GSL
                   11820:   const gsl_multimin_fminimizer_type *T;
                   11821:   size_t iteri = 0, it;
                   11822:   int rval = GSL_CONTINUE;
                   11823:   int status = GSL_SUCCESS;
                   11824:   double ssval;
                   11825: #endif
                   11826:   int movingaverage(double ***probs, double bage,double fage, double ***mobaverage, int mobilav);
1.290     brouard  11827:   int i,j, k, iter=0,m,size=100, cptcod; /* Suppressing because nobs */
                   11828:   /* int i,j, k, n=MAXN,iter=0,m,size=100, cptcod; */
1.209     brouard  11829:   int ncvyear=0; /* Number of years needed for the period prevalence to converge */
1.164     brouard  11830:   int jj, ll, li, lj, lk;
1.136     brouard  11831:   int numlinepar=0; /* Current linenumber of parameter file */
1.197     brouard  11832:   int num_filled;
1.136     brouard  11833:   int itimes;
                   11834:   int NDIM=2;
                   11835:   int vpopbased=0;
1.235     brouard  11836:   int nres=0;
1.258     brouard  11837:   int endishere=0;
1.277     brouard  11838:   int noffset=0;
1.274     brouard  11839:   int ncurrv=0; /* Temporary variable */
                   11840:   
1.164     brouard  11841:   char ca[32], cb[32];
1.136     brouard  11842:   /*  FILE *fichtm; *//* Html File */
                   11843:   /* FILE *ficgp;*/ /*Gnuplot File */
                   11844:   struct stat info;
1.191     brouard  11845:   double agedeb=0.;
1.194     brouard  11846: 
                   11847:   double ageminpar=AGEOVERFLOW,agemin=AGEOVERFLOW, agemaxpar=-AGEOVERFLOW, agemax=-AGEOVERFLOW;
1.219     brouard  11848:   double ageminout=-AGEOVERFLOW,agemaxout=AGEOVERFLOW; /* Smaller Age range redefined after movingaverage */
1.136     brouard  11849: 
1.165     brouard  11850:   double fret;
1.191     brouard  11851:   double dum=0.; /* Dummy variable */
1.136     brouard  11852:   double ***p3mat;
1.218     brouard  11853:   /* double ***mobaverage; */
1.319     brouard  11854:   double wald;
1.164     brouard  11855: 
                   11856:   char line[MAXLINE];
1.197     brouard  11857:   char path[MAXLINE],pathc[MAXLINE],pathcd[MAXLINE],pathtot[MAXLINE];
                   11858: 
1.234     brouard  11859:   char  modeltemp[MAXLINE];
1.332     brouard  11860:   char resultline[MAXLINE], resultlineori[MAXLINE];
1.230     brouard  11861:   
1.136     brouard  11862:   char pathr[MAXLINE], pathimach[MAXLINE]; 
1.164     brouard  11863:   char *tok, *val; /* pathtot */
1.334     brouard  11864:   /* int firstobs=1, lastobs=10; /\* nobs = lastobs-firstobs declared globally ;*\/ */
1.195     brouard  11865:   int c,  h , cpt, c2;
1.191     brouard  11866:   int jl=0;
                   11867:   int i1, j1, jk, stepsize=0;
1.194     brouard  11868:   int count=0;
                   11869: 
1.164     brouard  11870:   int *tab; 
1.136     brouard  11871:   int mobilavproj=0 , prevfcast=0 ; /* moving average of prev, If prevfcast=1 prevalence projection */
1.296     brouard  11872:   /* double anprojd, mprojd, jprojd; /\* For eventual projections *\/ */
                   11873:   /* double anprojf, mprojf, jprojf; */
                   11874:   /* double jintmean,mintmean,aintmean;   */
                   11875:   int prvforecast = 0; /* Might be 1 (date of beginning of projection is a choice or 2 is the dateintmean */
                   11876:   int prvbackcast = 0; /* Might be 1 (date of beginning of projection is a choice or 2 is the dateintmean */
                   11877:   double yrfproj= 10.0; /* Number of years of forward projections */
                   11878:   double yrbproj= 10.0; /* Number of years of backward projections */
                   11879:   int prevbcast=0; /* defined as global for mlikeli and mle, replacing backcast */
1.136     brouard  11880:   int mobilav=0,popforecast=0;
1.191     brouard  11881:   int hstepm=0, nhstepm=0;
1.136     brouard  11882:   int agemortsup;
                   11883:   float  sumlpop=0.;
                   11884:   double jprev1=1, mprev1=1,anprev1=2000,jprev2=1, mprev2=1,anprev2=2000;
                   11885:   double jpyram=1, mpyram=1,anpyram=2000,jpyram1=1, mpyram1=1,anpyram1=2000;
                   11886: 
1.191     brouard  11887:   double bage=0, fage=110., age, agelim=0., agebase=0.;
1.136     brouard  11888:   double ftolpl=FTOL;
                   11889:   double **prlim;
1.217     brouard  11890:   double **bprlim;
1.317     brouard  11891:   double ***param; /* Matrix of parameters, param[i][j][k] param=ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel) 
                   11892:                     state of origin, state of destination including death, for each covariate: constante, age, and V1 V2 etc. */
1.251     brouard  11893:   double ***paramstart; /* Matrix of starting parameter values */
                   11894:   double  *p, *pstart; /* p=param[1][1] pstart is for starting values guessed by freqsummary */
1.136     brouard  11895:   double **matcov; /* Matrix of covariance */
1.203     brouard  11896:   double **hess; /* Hessian matrix */
1.136     brouard  11897:   double ***delti3; /* Scale */
                   11898:   double *delti; /* Scale */
                   11899:   double ***eij, ***vareij;
                   11900:   double **varpl; /* Variances of prevalence limits by age */
1.269     brouard  11901: 
1.136     brouard  11902:   double *epj, vepp;
1.164     brouard  11903: 
1.273     brouard  11904:   double dateprev1, dateprev2;
1.296     brouard  11905:   double jproj1=1,mproj1=1,anproj1=2000,jproj2=1,mproj2=1,anproj2=2000, dateproj1=0, dateproj2=0, dateprojd=0, dateprojf=0;
                   11906:   double jback1=1,mback1=1,anback1=2000,jback2=1,mback2=1,anback2=2000, dateback1=0, dateback2=0, datebackd=0, datebackf=0;
                   11907: 
1.217     brouard  11908: 
1.136     brouard  11909:   double **ximort;
1.145     brouard  11910:   char *alph[]={"a","a","b","c","d","e"}, str[4]="1234";
1.136     brouard  11911:   int *dcwave;
                   11912: 
1.164     brouard  11913:   char z[1]="c";
1.136     brouard  11914: 
                   11915:   /*char  *strt;*/
                   11916:   char strtend[80];
1.126     brouard  11917: 
1.164     brouard  11918: 
1.126     brouard  11919: /*   setlocale (LC_ALL, ""); */
                   11920: /*   bindtextdomain (PACKAGE, LOCALEDIR); */
                   11921: /*   textdomain (PACKAGE); */
                   11922: /*   setlocale (LC_CTYPE, ""); */
                   11923: /*   setlocale (LC_MESSAGES, ""); */
                   11924: 
                   11925:   /*   gettimeofday(&start_time, (struct timezone*)0); */ /* at first time */
1.157     brouard  11926:   rstart_time = time(NULL);  
                   11927:   /*  (void) gettimeofday(&start_time,&tzp);*/
                   11928:   start_time = *localtime(&rstart_time);
1.126     brouard  11929:   curr_time=start_time;
1.157     brouard  11930:   /*tml = *localtime(&start_time.tm_sec);*/
                   11931:   /* strcpy(strstart,asctime(&tml)); */
                   11932:   strcpy(strstart,asctime(&start_time));
1.126     brouard  11933: 
                   11934: /*  printf("Localtime (at start)=%s",strstart); */
1.157     brouard  11935: /*  tp.tm_sec = tp.tm_sec +86400; */
                   11936: /*  tm = *localtime(&start_time.tm_sec); */
1.126     brouard  11937: /*   tmg.tm_year=tmg.tm_year +dsign*dyear; */
                   11938: /*   tmg.tm_mon=tmg.tm_mon +dsign*dmonth; */
                   11939: /*   tmg.tm_hour=tmg.tm_hour + 1; */
1.157     brouard  11940: /*   tp.tm_sec = mktime(&tmg); */
1.126     brouard  11941: /*   strt=asctime(&tmg); */
                   11942: /*   printf("Time(after) =%s",strstart);  */
                   11943: /*  (void) time (&time_value);
                   11944: *  printf("time=%d,t-=%d\n",time_value,time_value-86400);
                   11945: *  tm = *localtime(&time_value);
                   11946: *  strstart=asctime(&tm);
                   11947: *  printf("tim_value=%d,asctime=%s\n",time_value,strstart); 
                   11948: */
                   11949: 
                   11950:   nberr=0; /* Number of errors and warnings */
                   11951:   nbwarn=0;
1.184     brouard  11952: #ifdef WIN32
                   11953:   _getcwd(pathcd, size);
                   11954: #else
1.126     brouard  11955:   getcwd(pathcd, size);
1.184     brouard  11956: #endif
1.191     brouard  11957:   syscompilerinfo(0);
1.196     brouard  11958:   printf("\nIMaCh version %s, %s\n%s",version, copyright, fullversion);
1.126     brouard  11959:   if(argc <=1){
                   11960:     printf("\nEnter the parameter file name: ");
1.205     brouard  11961:     if(!fgets(pathr,FILENAMELENGTH,stdin)){
                   11962:       printf("ERROR Empty parameter file name\n");
                   11963:       goto end;
                   11964:     }
1.126     brouard  11965:     i=strlen(pathr);
                   11966:     if(pathr[i-1]=='\n')
                   11967:       pathr[i-1]='\0';
1.156     brouard  11968:     i=strlen(pathr);
1.205     brouard  11969:     if(i >= 1 && pathr[i-1]==' ') {/* This may happen when dragging on oS/X! */
1.156     brouard  11970:       pathr[i-1]='\0';
1.205     brouard  11971:     }
                   11972:     i=strlen(pathr);
                   11973:     if( i==0 ){
                   11974:       printf("ERROR Empty parameter file name\n");
                   11975:       goto end;
                   11976:     }
                   11977:     for (tok = pathr; tok != NULL; ){
1.126     brouard  11978:       printf("Pathr |%s|\n",pathr);
                   11979:       while ((val = strsep(&tok, "\"" )) != NULL && *val == '\0');
                   11980:       printf("val= |%s| pathr=%s\n",val,pathr);
                   11981:       strcpy (pathtot, val);
                   11982:       if(pathr[0] == '\0') break; /* Dirty */
                   11983:     }
                   11984:   }
1.281     brouard  11985:   else if (argc<=2){
                   11986:     strcpy(pathtot,argv[1]);
                   11987:   }
1.126     brouard  11988:   else{
                   11989:     strcpy(pathtot,argv[1]);
1.281     brouard  11990:     strcpy(z,argv[2]);
                   11991:     printf("\nargv[2]=%s z=%c\n",argv[2],z[0]);
1.126     brouard  11992:   }
                   11993:   /*if(getcwd(pathcd, MAXLINE)!= NULL)printf ("Error pathcd\n");*/
                   11994:   /*cygwin_split_path(pathtot,path,optionfile);
                   11995:     printf("pathtot=%s, path=%s, optionfile=%s\n",pathtot,path,optionfile);*/
                   11996:   /* cutv(path,optionfile,pathtot,'\\');*/
                   11997: 
                   11998:   /* Split argv[0], imach program to get pathimach */
                   11999:   printf("\nargv[0]=%s argv[1]=%s, \n",argv[0],argv[1]);
                   12000:   split(argv[0],pathimach,optionfile,optionfilext,optionfilefiname);
                   12001:   printf("\nargv[0]=%s pathimach=%s, \noptionfile=%s \noptionfilext=%s \noptionfilefiname=%s\n",argv[0],pathimach,optionfile,optionfilext,optionfilefiname);
                   12002:  /*   strcpy(pathimach,argv[0]); */
                   12003:   /* Split argv[1]=pathtot, parameter file name to get path, optionfile, extension and name */
                   12004:   split(pathtot,path,optionfile,optionfilext,optionfilefiname);
                   12005:   printf("\npathtot=%s,\npath=%s,\noptionfile=%s \noptionfilext=%s \noptionfilefiname=%s\n",pathtot,path,optionfile,optionfilext,optionfilefiname);
1.184     brouard  12006: #ifdef WIN32
                   12007:   _chdir(path); /* Can be a relative path */
                   12008:   if(_getcwd(pathcd,MAXLINE) > 0) /* So pathcd is the full path */
                   12009: #else
1.126     brouard  12010:   chdir(path); /* Can be a relative path */
1.184     brouard  12011:   if (getcwd(pathcd, MAXLINE) > 0) /* So pathcd is the full path */
                   12012: #endif
                   12013:   printf("Current directory %s!\n",pathcd);
1.126     brouard  12014:   strcpy(command,"mkdir ");
                   12015:   strcat(command,optionfilefiname);
                   12016:   if((outcmd=system(command)) != 0){
1.169     brouard  12017:     printf("Directory already exists (or can't create it) %s%s, err=%d\n",path,optionfilefiname,outcmd);
1.126     brouard  12018:     /* fprintf(ficlog,"Problem creating directory %s%s\n",path,optionfilefiname); */
                   12019:     /* fclose(ficlog); */
                   12020: /*     exit(1); */
                   12021:   }
                   12022: /*   if((imk=mkdir(optionfilefiname))<0){ */
                   12023: /*     perror("mkdir"); */
                   12024: /*   } */
                   12025: 
                   12026:   /*-------- arguments in the command line --------*/
                   12027: 
1.186     brouard  12028:   /* Main Log file */
1.126     brouard  12029:   strcat(filelog, optionfilefiname);
                   12030:   strcat(filelog,".log");    /* */
                   12031:   if((ficlog=fopen(filelog,"w"))==NULL)    {
                   12032:     printf("Problem with logfile %s\n",filelog);
                   12033:     goto end;
                   12034:   }
                   12035:   fprintf(ficlog,"Log filename:%s\n",filelog);
1.197     brouard  12036:   fprintf(ficlog,"Version %s %s",version,fullversion);
1.126     brouard  12037:   fprintf(ficlog,"\nEnter the parameter file name: \n");
                   12038:   fprintf(ficlog,"pathimach=%s\npathtot=%s\n\
                   12039:  path=%s \n\
                   12040:  optionfile=%s\n\
                   12041:  optionfilext=%s\n\
1.156     brouard  12042:  optionfilefiname='%s'\n",pathimach,pathtot,path,optionfile,optionfilext,optionfilefiname);
1.126     brouard  12043: 
1.197     brouard  12044:   syscompilerinfo(1);
1.167     brouard  12045: 
1.126     brouard  12046:   printf("Local time (at start):%s",strstart);
                   12047:   fprintf(ficlog,"Local time (at start): %s",strstart);
                   12048:   fflush(ficlog);
                   12049: /*   (void) gettimeofday(&curr_time,&tzp); */
1.157     brouard  12050: /*   printf("Elapsed time %d\n", asc_diff_time(curr_time.tm_sec-start_time.tm_sec,tmpout)); */
1.126     brouard  12051: 
                   12052:   /* */
                   12053:   strcpy(fileres,"r");
                   12054:   strcat(fileres, optionfilefiname);
1.201     brouard  12055:   strcat(fileresu, optionfilefiname); /* Without r in front */
1.126     brouard  12056:   strcat(fileres,".txt");    /* Other files have txt extension */
1.201     brouard  12057:   strcat(fileresu,".txt");    /* Other files have txt extension */
1.126     brouard  12058: 
1.186     brouard  12059:   /* Main ---------arguments file --------*/
1.126     brouard  12060: 
                   12061:   if((ficpar=fopen(optionfile,"r"))==NULL)    {
1.155     brouard  12062:     printf("Problem with optionfile '%s' with errno='%s'\n",optionfile,strerror(errno));
                   12063:     fprintf(ficlog,"Problem with optionfile '%s' with errno='%s'\n",optionfile,strerror(errno));
1.126     brouard  12064:     fflush(ficlog);
1.149     brouard  12065:     /* goto end; */
                   12066:     exit(70); 
1.126     brouard  12067:   }
                   12068: 
                   12069:   strcpy(filereso,"o");
1.201     brouard  12070:   strcat(filereso,fileresu);
1.126     brouard  12071:   if((ficparo=fopen(filereso,"w"))==NULL) { /* opened on subdirectory */
                   12072:     printf("Problem with Output resultfile: %s\n", filereso);
                   12073:     fprintf(ficlog,"Problem with Output resultfile: %s\n", filereso);
                   12074:     fflush(ficlog);
                   12075:     goto end;
                   12076:   }
1.278     brouard  12077:       /*-------- Rewriting parameter file ----------*/
                   12078:   strcpy(rfileres,"r");    /* "Rparameterfile */
                   12079:   strcat(rfileres,optionfilefiname);    /* Parameter file first name */
                   12080:   strcat(rfileres,".");    /* */
                   12081:   strcat(rfileres,optionfilext);    /* Other files have txt extension */
                   12082:   if((ficres =fopen(rfileres,"w"))==NULL) {
                   12083:     printf("Problem writing new parameter file: %s\n", rfileres);goto end;
                   12084:     fprintf(ficlog,"Problem writing new parameter file: %s\n", rfileres);goto end;
                   12085:     fflush(ficlog);
                   12086:     goto end;
                   12087:   }
                   12088:   fprintf(ficres,"#IMaCh %s\n",version);
1.126     brouard  12089: 
1.278     brouard  12090:                                      
1.126     brouard  12091:   /* Reads comments: lines beginning with '#' */
                   12092:   numlinepar=0;
1.277     brouard  12093:   /* Is it a BOM UTF-8 Windows file? */
                   12094:   /* First parameter line */
1.197     brouard  12095:   while(fgets(line, MAXLINE, ficpar)) {
1.277     brouard  12096:     noffset=0;
                   12097:     if( line[0] == (char)0xEF && line[1] == (char)0xBB) /* EF BB BF */
                   12098:     {
                   12099:       noffset=noffset+3;
                   12100:       printf("# File is an UTF8 Bom.\n"); // 0xBF
                   12101:     }
1.302     brouard  12102: /*    else if( line[0] == (char)0xFE && line[1] == (char)0xFF)*/
                   12103:     else if( line[0] == (char)0xFF && line[1] == (char)0xFE)
1.277     brouard  12104:     {
                   12105:       noffset=noffset+2;
                   12106:       printf("# File is an UTF16BE BOM file\n");
                   12107:     }
                   12108:     else if( line[0] == 0 && line[1] == 0)
                   12109:     {
                   12110:       if( line[2] == (char)0xFE && line[3] == (char)0xFF){
                   12111:        noffset=noffset+4;
                   12112:        printf("# File is an UTF16BE BOM file\n");
                   12113:       }
                   12114:     } else{
                   12115:       ;/*printf(" Not a BOM file\n");*/
                   12116:     }
                   12117:   
1.197     brouard  12118:     /* If line starts with a # it is a comment */
1.277     brouard  12119:     if (line[noffset] == '#') {
1.197     brouard  12120:       numlinepar++;
                   12121:       fputs(line,stdout);
                   12122:       fputs(line,ficparo);
1.278     brouard  12123:       fputs(line,ficres);
1.197     brouard  12124:       fputs(line,ficlog);
                   12125:       continue;
                   12126:     }else
                   12127:       break;
                   12128:   }
                   12129:   if((num_filled=sscanf(line,"title=%s datafile=%s lastobs=%d firstpass=%d lastpass=%d\n", \
                   12130:                        title, datafile, &lastobs, &firstpass,&lastpass)) !=EOF){
                   12131:     if (num_filled != 5) {
                   12132:       printf("Should be 5 parameters\n");
1.283     brouard  12133:       fprintf(ficlog,"Should be 5 parameters\n");
1.197     brouard  12134:     }
1.126     brouard  12135:     numlinepar++;
1.197     brouard  12136:     printf("title=%s datafile=%s lastobs=%d firstpass=%d lastpass=%d\n", title, datafile, lastobs, firstpass,lastpass);
1.283     brouard  12137:     fprintf(ficparo,"title=%s datafile=%s lastobs=%d firstpass=%d lastpass=%d\n", title, datafile, lastobs, firstpass,lastpass);
                   12138:     fprintf(ficres,"title=%s datafile=%s lastobs=%d firstpass=%d lastpass=%d\n", title, datafile, lastobs, firstpass,lastpass);
                   12139:     fprintf(ficlog,"title=%s datafile=%s lastobs=%d firstpass=%d lastpass=%d\n", title, datafile, lastobs, firstpass,lastpass);
1.197     brouard  12140:   }
                   12141:   /* Second parameter line */
                   12142:   while(fgets(line, MAXLINE, ficpar)) {
1.283     brouard  12143:     /* while(fscanf(ficpar,"%[^\n]", line)) { */
                   12144:     /* If line starts with a # it is a comment. Strangely fgets reads the EOL and fputs doesn't */
1.197     brouard  12145:     if (line[0] == '#') {
                   12146:       numlinepar++;
1.283     brouard  12147:       printf("%s",line);
                   12148:       fprintf(ficres,"%s",line);
                   12149:       fprintf(ficparo,"%s",line);
                   12150:       fprintf(ficlog,"%s",line);
1.197     brouard  12151:       continue;
                   12152:     }else
                   12153:       break;
                   12154:   }
1.223     brouard  12155:   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", \
                   12156:                        &ftol, &stepm, &ncovcol, &nqv, &ntv, &nqtv, &nlstate, &ndeath, &maxwav, &mle, &weightopt)) !=EOF){
                   12157:     if (num_filled != 11) {
                   12158:       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  12159:       printf("but line=%s\n",line);
1.283     brouard  12160:       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");
                   12161:       fprintf(ficlog,"but line=%s\n",line);
1.197     brouard  12162:     }
1.286     brouard  12163:     if( lastpass > maxwav){
                   12164:       printf("Error (lastpass = %d) > (maxwav = %d)\n",lastpass, maxwav);
                   12165:       fprintf(ficlog,"Error (lastpass = %d) > (maxwav = %d)\n",lastpass, maxwav);
                   12166:       fflush(ficlog);
                   12167:       goto end;
                   12168:     }
                   12169:       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  12170:     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  12171:     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  12172:     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  12173:   }
1.203     brouard  12174:   /* ftolpl=6*ftol*1.e5; /\* 6.e-3 make convergences in less than 80 loops for the prevalence limit *\/ */
1.209     brouard  12175:   /*ftolpl=6.e-4; *//* 6.e-3 make convergences in less than 80 loops for the prevalence limit */
1.197     brouard  12176:   /* Third parameter line */
                   12177:   while(fgets(line, MAXLINE, ficpar)) {
                   12178:     /* If line starts with a # it is a comment */
                   12179:     if (line[0] == '#') {
                   12180:       numlinepar++;
1.283     brouard  12181:       printf("%s",line);
                   12182:       fprintf(ficres,"%s",line);
                   12183:       fprintf(ficparo,"%s",line);
                   12184:       fprintf(ficlog,"%s",line);
1.197     brouard  12185:       continue;
                   12186:     }else
                   12187:       break;
                   12188:   }
1.201     brouard  12189:   if((num_filled=sscanf(line,"model=1+age%[^.\n]", model)) !=EOF){
1.279     brouard  12190:     if (num_filled != 1){
1.302     brouard  12191:       printf("ERROR %d: Model should be at minimum 'model=1+age+' instead of '%s'\n",num_filled, line);
                   12192:       fprintf(ficlog,"ERROR %d: Model should be at minimum 'model=1+age+' instead of '%s'\n",num_filled, line);
1.197     brouard  12193:       model[0]='\0';
                   12194:       goto end;
                   12195:     }
                   12196:     else{
                   12197:       if (model[0]=='+'){
                   12198:        for(i=1; i<=strlen(model);i++)
                   12199:          modeltemp[i-1]=model[i];
1.201     brouard  12200:        strcpy(model,modeltemp); 
1.197     brouard  12201:       }
                   12202:     }
1.199     brouard  12203:     /* printf(" model=1+age%s modeltemp= %s, model=%s\n",model, modeltemp, model);fflush(stdout); */
1.203     brouard  12204:     printf("model=1+age+%s\n",model);fflush(stdout);
1.283     brouard  12205:     fprintf(ficparo,"model=1+age+%s\n",model);fflush(stdout);
                   12206:     fprintf(ficres,"model=1+age+%s\n",model);fflush(stdout);
                   12207:     fprintf(ficlog,"model=1+age+%s\n",model);fflush(stdout);
1.197     brouard  12208:   }
                   12209:   /* 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); */
                   12210:   /* numlinepar=numlinepar+3; /\* In general *\/ */
                   12211:   /* 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  12212:   /* 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); */
                   12213:   /* 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  12214:   fflush(ficlog);
1.190     brouard  12215:   /* if(model[0]=='#'|| model[0]== '\0'){ */
                   12216:   if(model[0]=='#'){
1.279     brouard  12217:     printf("Error in 'model' line: model should start with 'model=1+age+' and end without space \n \
                   12218:  'model=1+age+' or 'model=1+age+V1.' or 'model=1+age+age*age+V1+V1*age' or \n \
                   12219:  'model=1+age+V1+V2' or 'model=1+age+V1+V2+V1*V2' etc. \n");           \
1.187     brouard  12220:     if(mle != -1){
1.279     brouard  12221:       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  12222:       exit(1);
                   12223:     }
                   12224:   }
1.126     brouard  12225:   while((c=getc(ficpar))=='#' && c!= EOF){
                   12226:     ungetc(c,ficpar);
                   12227:     fgets(line, MAXLINE, ficpar);
                   12228:     numlinepar++;
1.195     brouard  12229:     if(line[1]=='q'){ /* This #q will quit imach (the answer is q) */
                   12230:       z[0]=line[1];
                   12231:     }
                   12232:     /* printf("****line [1] = %c \n",line[1]); */
1.141     brouard  12233:     fputs(line, stdout);
                   12234:     //puts(line);
1.126     brouard  12235:     fputs(line,ficparo);
                   12236:     fputs(line,ficlog);
                   12237:   }
                   12238:   ungetc(c,ficpar);
                   12239: 
                   12240:    
1.290     brouard  12241:   covar=matrix(0,NCOVMAX,firstobs,lastobs);  /**< used in readdata */
                   12242:   if(nqv>=1)coqvar=matrix(1,nqv,firstobs,lastobs);  /**< Fixed quantitative covariate */
                   12243:   if(nqtv>=1)cotqvar=ma3x(1,maxwav,1,nqtv,firstobs,lastobs);  /**< Time varying quantitative covariate */
                   12244:   if(ntv+nqtv>=1)cotvar=ma3x(1,maxwav,1,ntv+nqtv,firstobs,lastobs);  /**< Time varying covariate (dummy and quantitative)*/
1.136     brouard  12245:   cptcovn=0; /*Number of covariates, i.e. number of '+' in model statement plus one, indepently of n in Vn*/
                   12246:   /* v1+v2+v3+v2*v4+v5*age makes cptcovn = 5
                   12247:      v1+v2*age+v2*v3 makes cptcovn = 3
                   12248:   */
                   12249:   if (strlen(model)>1) 
1.187     brouard  12250:     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  12251:   else
1.187     brouard  12252:     ncovmodel=2; /* Constant and age */
1.133     brouard  12253:   nforce= (nlstate+ndeath-1)*nlstate; /* Number of forces ij from state i to j */
                   12254:   npar= nforce*ncovmodel; /* Number of parameters like aij*/
1.131     brouard  12255:   if(npar >MAXPARM || nlstate >NLSTATEMAX || ndeath >NDEATHMAX || ncovmodel>NCOVMAX){
                   12256:     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);
                   12257:     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);
                   12258:     fflush(stdout);
                   12259:     fclose (ficlog);
                   12260:     goto end;
                   12261:   }
1.126     brouard  12262:   delti3= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
                   12263:   delti=delti3[1][1];
                   12264:   /*delti=vector(1,npar); *//* Scale of each paramater (output from hesscov)*/
                   12265:   if(mle==-1){ /* Print a wizard for help writing covariance matrix */
1.247     brouard  12266: /* We could also provide initial parameters values giving by simple logistic regression 
                   12267:  * only one way, that is without matrix product. We will have nlstate maximizations */
                   12268:       /* for(i=1;i<nlstate;i++){ */
                   12269:       /*       /\*reducing xi for 1 to npar to 1 to ncovmodel; *\/ */
                   12270:       /*    mlikeli(ficres,p, ncovmodel, ncovmodel, nlstate, ftol, funcnoprod); */
                   12271:       /* } */
1.126     brouard  12272:     prwizard(ncovmodel, nlstate, ndeath, model, ficparo);
1.191     brouard  12273:     printf(" You chose mle=-1, look at file %s for a template of covariance matrix \n",filereso);
                   12274:     fprintf(ficlog," You chose mle=-1, look at file %s for a template of covariance matrix \n",filereso);
1.126     brouard  12275:     free_ma3x(delti3,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel); 
                   12276:     fclose (ficparo);
                   12277:     fclose (ficlog);
                   12278:     goto end;
                   12279:     exit(0);
1.220     brouard  12280:   }  else if(mle==-5) { /* Main Wizard */
1.126     brouard  12281:     prwizard(ncovmodel, nlstate, ndeath, model, ficparo);
1.192     brouard  12282:     printf(" You chose mle=-3, look at file %s for a template of covariance matrix \n",filereso);
                   12283:     fprintf(ficlog," You chose mle=-3, look at file %s for a template of covariance matrix \n",filereso);
1.126     brouard  12284:     param= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
                   12285:     matcov=matrix(1,npar,1,npar);
1.203     brouard  12286:     hess=matrix(1,npar,1,npar);
1.220     brouard  12287:   }  else{ /* Begin of mle != -1 or -5 */
1.145     brouard  12288:     /* Read guessed parameters */
1.126     brouard  12289:     /* Reads comments: lines beginning with '#' */
                   12290:     while((c=getc(ficpar))=='#' && c!= EOF){
                   12291:       ungetc(c,ficpar);
                   12292:       fgets(line, MAXLINE, ficpar);
                   12293:       numlinepar++;
1.141     brouard  12294:       fputs(line,stdout);
1.126     brouard  12295:       fputs(line,ficparo);
                   12296:       fputs(line,ficlog);
                   12297:     }
                   12298:     ungetc(c,ficpar);
                   12299:     
                   12300:     param= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
1.251     brouard  12301:     paramstart= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
1.126     brouard  12302:     for(i=1; i <=nlstate; i++){
1.234     brouard  12303:       j=0;
1.126     brouard  12304:       for(jj=1; jj <=nlstate+ndeath; jj++){
1.234     brouard  12305:        if(jj==i) continue;
                   12306:        j++;
1.292     brouard  12307:        while((c=getc(ficpar))=='#' && c!= EOF){
                   12308:          ungetc(c,ficpar);
                   12309:          fgets(line, MAXLINE, ficpar);
                   12310:          numlinepar++;
                   12311:          fputs(line,stdout);
                   12312:          fputs(line,ficparo);
                   12313:          fputs(line,ficlog);
                   12314:        }
                   12315:        ungetc(c,ficpar);
1.234     brouard  12316:        fscanf(ficpar,"%1d%1d",&i1,&j1);
                   12317:        if ((i1 != i) || (j1 != jj)){
                   12318:          printf("Error in line parameters number %d, %1d%1d instead of %1d%1d \n \
1.126     brouard  12319: It might be a problem of design; if ncovcol and the model are correct\n \
                   12320: run imach with mle=-1 to get a correct template of the parameter file.\n",numlinepar, i,j, i1, j1);
1.234     brouard  12321:          exit(1);
                   12322:        }
                   12323:        fprintf(ficparo,"%1d%1d",i1,j1);
                   12324:        if(mle==1)
                   12325:          printf("%1d%1d",i,jj);
                   12326:        fprintf(ficlog,"%1d%1d",i,jj);
                   12327:        for(k=1; k<=ncovmodel;k++){
                   12328:          fscanf(ficpar," %lf",&param[i][j][k]);
                   12329:          if(mle==1){
                   12330:            printf(" %lf",param[i][j][k]);
                   12331:            fprintf(ficlog," %lf",param[i][j][k]);
                   12332:          }
                   12333:          else
                   12334:            fprintf(ficlog," %lf",param[i][j][k]);
                   12335:          fprintf(ficparo," %lf",param[i][j][k]);
                   12336:        }
                   12337:        fscanf(ficpar,"\n");
                   12338:        numlinepar++;
                   12339:        if(mle==1)
                   12340:          printf("\n");
                   12341:        fprintf(ficlog,"\n");
                   12342:        fprintf(ficparo,"\n");
1.126     brouard  12343:       }
                   12344:     }  
                   12345:     fflush(ficlog);
1.234     brouard  12346:     
1.251     brouard  12347:     /* Reads parameters values */
1.126     brouard  12348:     p=param[1][1];
1.251     brouard  12349:     pstart=paramstart[1][1];
1.126     brouard  12350:     
                   12351:     /* Reads comments: lines beginning with '#' */
                   12352:     while((c=getc(ficpar))=='#' && c!= EOF){
                   12353:       ungetc(c,ficpar);
                   12354:       fgets(line, MAXLINE, ficpar);
                   12355:       numlinepar++;
1.141     brouard  12356:       fputs(line,stdout);
1.126     brouard  12357:       fputs(line,ficparo);
                   12358:       fputs(line,ficlog);
                   12359:     }
                   12360:     ungetc(c,ficpar);
                   12361: 
                   12362:     for(i=1; i <=nlstate; i++){
                   12363:       for(j=1; j <=nlstate+ndeath-1; j++){
1.234     brouard  12364:        fscanf(ficpar,"%1d%1d",&i1,&j1);
                   12365:        if ( (i1-i) * (j1-j) != 0){
                   12366:          printf("Error in line parameters number %d, %1d%1d instead of %1d%1d \n",numlinepar, i,j, i1, j1);
                   12367:          exit(1);
                   12368:        }
                   12369:        printf("%1d%1d",i,j);
                   12370:        fprintf(ficparo,"%1d%1d",i1,j1);
                   12371:        fprintf(ficlog,"%1d%1d",i1,j1);
                   12372:        for(k=1; k<=ncovmodel;k++){
                   12373:          fscanf(ficpar,"%le",&delti3[i][j][k]);
                   12374:          printf(" %le",delti3[i][j][k]);
                   12375:          fprintf(ficparo," %le",delti3[i][j][k]);
                   12376:          fprintf(ficlog," %le",delti3[i][j][k]);
                   12377:        }
                   12378:        fscanf(ficpar,"\n");
                   12379:        numlinepar++;
                   12380:        printf("\n");
                   12381:        fprintf(ficparo,"\n");
                   12382:        fprintf(ficlog,"\n");
1.126     brouard  12383:       }
                   12384:     }
                   12385:     fflush(ficlog);
1.234     brouard  12386:     
1.145     brouard  12387:     /* Reads covariance matrix */
1.126     brouard  12388:     delti=delti3[1][1];
1.220     brouard  12389:                
                   12390:                
1.126     brouard  12391:     /* 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  12392:                
1.126     brouard  12393:     /* Reads comments: lines beginning with '#' */
                   12394:     while((c=getc(ficpar))=='#' && c!= EOF){
                   12395:       ungetc(c,ficpar);
                   12396:       fgets(line, MAXLINE, ficpar);
                   12397:       numlinepar++;
1.141     brouard  12398:       fputs(line,stdout);
1.126     brouard  12399:       fputs(line,ficparo);
                   12400:       fputs(line,ficlog);
                   12401:     }
                   12402:     ungetc(c,ficpar);
1.220     brouard  12403:                
1.126     brouard  12404:     matcov=matrix(1,npar,1,npar);
1.203     brouard  12405:     hess=matrix(1,npar,1,npar);
1.131     brouard  12406:     for(i=1; i <=npar; i++)
                   12407:       for(j=1; j <=npar; j++) matcov[i][j]=0.;
1.220     brouard  12408:                
1.194     brouard  12409:     /* Scans npar lines */
1.126     brouard  12410:     for(i=1; i <=npar; i++){
1.226     brouard  12411:       count=fscanf(ficpar,"%1d%1d%d",&i1,&j1,&jk);
1.194     brouard  12412:       if(count != 3){
1.226     brouard  12413:        printf("Error! Error in parameter file %s at line %d after line starting with %1d%1d%1d\n\
1.194     brouard  12414: This is probably because your covariance matrix doesn't \n  contain exactly %d lines corresponding to your model line '1+age+%s'.\n\
                   12415: Please run with mle=-1 to get a correct covariance matrix.\n",optionfile,numlinepar, i1,j1,jk, npar, model);
1.226     brouard  12416:        fprintf(ficlog,"Error! Error in parameter file %s at line %d after line starting with %1d%1d%1d\n\
1.194     brouard  12417: This is probably because your covariance matrix doesn't \n  contain exactly %d lines corresponding to your model line '1+age+%s'.\n\
                   12418: Please run with mle=-1 to get a correct covariance matrix.\n",optionfile,numlinepar, i1,j1,jk, npar, model);
1.226     brouard  12419:        exit(1);
1.220     brouard  12420:       }else{
1.226     brouard  12421:        if(mle==1)
                   12422:          printf("%1d%1d%d",i1,j1,jk);
                   12423:       }
                   12424:       fprintf(ficlog,"%1d%1d%d",i1,j1,jk);
                   12425:       fprintf(ficparo,"%1d%1d%d",i1,j1,jk);
1.126     brouard  12426:       for(j=1; j <=i; j++){
1.226     brouard  12427:        fscanf(ficpar," %le",&matcov[i][j]);
                   12428:        if(mle==1){
                   12429:          printf(" %.5le",matcov[i][j]);
                   12430:        }
                   12431:        fprintf(ficlog," %.5le",matcov[i][j]);
                   12432:        fprintf(ficparo," %.5le",matcov[i][j]);
1.126     brouard  12433:       }
                   12434:       fscanf(ficpar,"\n");
                   12435:       numlinepar++;
                   12436:       if(mle==1)
1.220     brouard  12437:                                printf("\n");
1.126     brouard  12438:       fprintf(ficlog,"\n");
                   12439:       fprintf(ficparo,"\n");
                   12440:     }
1.194     brouard  12441:     /* End of read covariance matrix npar lines */
1.126     brouard  12442:     for(i=1; i <=npar; i++)
                   12443:       for(j=i+1;j<=npar;j++)
1.226     brouard  12444:        matcov[i][j]=matcov[j][i];
1.126     brouard  12445:     
                   12446:     if(mle==1)
                   12447:       printf("\n");
                   12448:     fprintf(ficlog,"\n");
                   12449:     
                   12450:     fflush(ficlog);
                   12451:     
                   12452:   }    /* End of mle != -3 */
1.218     brouard  12453:   
1.186     brouard  12454:   /*  Main data
                   12455:    */
1.290     brouard  12456:   nobs=lastobs-firstobs+1; /* was = lastobs;*/
                   12457:   /* num=lvector(1,n); */
                   12458:   /* moisnais=vector(1,n); */
                   12459:   /* annais=vector(1,n); */
                   12460:   /* moisdc=vector(1,n); */
                   12461:   /* andc=vector(1,n); */
                   12462:   /* weight=vector(1,n); */
                   12463:   /* agedc=vector(1,n); */
                   12464:   /* cod=ivector(1,n); */
                   12465:   /* for(i=1;i<=n;i++){ */
                   12466:   num=lvector(firstobs,lastobs);
                   12467:   moisnais=vector(firstobs,lastobs);
                   12468:   annais=vector(firstobs,lastobs);
                   12469:   moisdc=vector(firstobs,lastobs);
                   12470:   andc=vector(firstobs,lastobs);
                   12471:   weight=vector(firstobs,lastobs);
                   12472:   agedc=vector(firstobs,lastobs);
                   12473:   cod=ivector(firstobs,lastobs);
                   12474:   for(i=firstobs;i<=lastobs;i++){
1.234     brouard  12475:     num[i]=0;
                   12476:     moisnais[i]=0;
                   12477:     annais[i]=0;
                   12478:     moisdc[i]=0;
                   12479:     andc[i]=0;
                   12480:     agedc[i]=0;
                   12481:     cod[i]=0;
                   12482:     weight[i]=1.0; /* Equal weights, 1 by default */
                   12483:   }
1.290     brouard  12484:   mint=matrix(1,maxwav,firstobs,lastobs);
                   12485:   anint=matrix(1,maxwav,firstobs,lastobs);
1.325     brouard  12486:   s=imatrix(1,maxwav+1,firstobs,lastobs); /* s[i][j] health state for wave i and individual j */
1.336   ! brouard  12487:   /* printf("BUG ncovmodel=%d NCOVMAX=%d 2**ncovmodel=%f BUG\n",ncovmodel,NCOVMAX,pow(2,ncovmodel)); */
1.126     brouard  12488:   tab=ivector(1,NCOVMAX);
1.144     brouard  12489:   ncodemax=ivector(1,NCOVMAX); /* Number of code per covariate; if O and 1 only, 2**ncov; V1+V2+V3+V4=>16 */
1.192     brouard  12490:   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  12491: 
1.136     brouard  12492:   /* Reads data from file datafile */
                   12493:   if (readdata(datafile, firstobs, lastobs, &imx)==1)
                   12494:     goto end;
                   12495: 
                   12496:   /* Calculation of the number of parameters from char model */
1.234     brouard  12497:   /*    modelsav=V2+V1+V4+age*V3 strb=age*V3 stra=V2+V1+V4 
1.137     brouard  12498:        k=4 (age*V3) Tvar[k=4]= 3 (from V3) Tag[cptcovage=1]=4
                   12499:        k=3 V4 Tvar[k=3]= 4 (from V4)
                   12500:        k=2 V1 Tvar[k=2]= 1 (from V1)
                   12501:        k=1 Tvar[1]=2 (from V2)
1.234     brouard  12502:   */
                   12503:   
                   12504:   Tvar=ivector(1,NCOVMAX); /* Was 15 changed to NCOVMAX. */
                   12505:   TvarsDind=ivector(1,NCOVMAX); /*  */
1.330     brouard  12506:   TnsdVar=ivector(1,NCOVMAX); /*  */
1.335     brouard  12507:     /* for(i=1; i<=NCOVMAX;i++) TnsdVar[i]=3; */
1.234     brouard  12508:   TvarsD=ivector(1,NCOVMAX); /*  */
                   12509:   TvarsQind=ivector(1,NCOVMAX); /*  */
                   12510:   TvarsQ=ivector(1,NCOVMAX); /*  */
1.232     brouard  12511:   TvarF=ivector(1,NCOVMAX); /*  */
                   12512:   TvarFind=ivector(1,NCOVMAX); /*  */
                   12513:   TvarV=ivector(1,NCOVMAX); /*  */
                   12514:   TvarVind=ivector(1,NCOVMAX); /*  */
                   12515:   TvarA=ivector(1,NCOVMAX); /*  */
                   12516:   TvarAind=ivector(1,NCOVMAX); /*  */
1.231     brouard  12517:   TvarFD=ivector(1,NCOVMAX); /*  */
                   12518:   TvarFDind=ivector(1,NCOVMAX); /*  */
                   12519:   TvarFQ=ivector(1,NCOVMAX); /*  */
                   12520:   TvarFQind=ivector(1,NCOVMAX); /*  */
                   12521:   TvarVD=ivector(1,NCOVMAX); /*  */
                   12522:   TvarVDind=ivector(1,NCOVMAX); /*  */
                   12523:   TvarVQ=ivector(1,NCOVMAX); /*  */
                   12524:   TvarVQind=ivector(1,NCOVMAX); /*  */
                   12525: 
1.230     brouard  12526:   Tvalsel=vector(1,NCOVMAX); /*  */
1.233     brouard  12527:   Tvarsel=ivector(1,NCOVMAX); /*  */
1.226     brouard  12528:   Typevar=ivector(-1,NCOVMAX); /* -1 to 2 */
                   12529:   Fixed=ivector(-1,NCOVMAX); /* -1 to 3 */
                   12530:   Dummy=ivector(-1,NCOVMAX); /* -1 to 3 */
1.137     brouard  12531:   /*  V2+V1+V4+age*V3 is a model with 4 covariates (3 plus signs). 
                   12532:       For each model-covariate stores the data-covariate id. Tvar[1]=2, Tvar[2]=1, Tvar[3]=4, 
                   12533:       Tvar[4=age*V3] is 3 and 'age' is recorded in Tage.
                   12534:   */
                   12535:   /* For model-covariate k tells which data-covariate to use but
                   12536:     because this model-covariate is a construction we invent a new column
                   12537:     ncovcol + k1
                   12538:     If already ncovcol=4 and model=V2+V1+V1*V4+age*V3
                   12539:     Tvar[3=V1*V4]=4+1 etc */
1.227     brouard  12540:   Tprod=ivector(1,NCOVMAX); /* Gives the k position of the k1 product */
                   12541:   Tposprod=ivector(1,NCOVMAX); /* Gives the k1 product from the k position */
1.137     brouard  12542:   /* Tprod[k1=1]=3(=V1*V4) for V2+V1+V1*V4+age*V3
                   12543:      if  V2+V1+V1*V4+age*V3+V3*V2   TProd[k1=2]=5 (V3*V2)
1.227     brouard  12544:      Tposprod[k]=k1 , Tposprod[3]=1, Tposprod[5]=2 
1.137     brouard  12545:   */
1.145     brouard  12546:   Tvaraff=ivector(1,NCOVMAX); /* Unclear */
                   12547:   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  12548:                            * For V3*V2 (in V2+V1+V1*V4+age*V3+V3*V2), V3*V2 position is 2nd. 
                   12549:                            * Tvard[k1=2][1]=3 (V3) Tvard[k1=2][2]=2(V2) */
1.330     brouard  12550:   Tvardk=imatrix(1,NCOVMAX,1,2);
1.145     brouard  12551:   Tage=ivector(1,NCOVMAX); /* Gives the covariate id of covariates associated with age: V2 + V1 + age*V4 + V3*age
1.137     brouard  12552:                         4 covariates (3 plus signs)
                   12553:                         Tage[1=V3*age]= 4; Tage[2=age*V4] = 3
1.328     brouard  12554:                           */  
                   12555:   for(i=1;i<NCOVMAX;i++)
                   12556:     Tage[i]=0;
1.230     brouard  12557:   Tmodelind=ivector(1,NCOVMAX);/** gives the k model position of an
1.227     brouard  12558:                                * individual dummy, fixed or varying:
                   12559:                                * Tmodelind[Tvaraff[3]]=9,Tvaraff[1]@9={4,
                   12560:                                * 3, 1, 0, 0, 0, 0, 0, 0},
1.230     brouard  12561:                                * model=V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 , 
                   12562:                                * V1 df, V2 qf, V3 & V4 dv, V5 qv
                   12563:                                * Tmodelind[1]@9={9,0,3,2,}*/
                   12564:   TmodelInvind=ivector(1,NCOVMAX); /* TmodelInvind=Tvar[k]- ncovcol-nqv={5-2-1=2,*/
                   12565:   TmodelInvQind=ivector(1,NCOVMAX);/** gives the k model position of an
1.228     brouard  12566:                                * individual quantitative, fixed or varying:
                   12567:                                * Tmodelqind[1]=1,Tvaraff[1]@9={4,
                   12568:                                * 3, 1, 0, 0, 0, 0, 0, 0},
                   12569:                                * model=V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1*/
1.186     brouard  12570: /* Main decodemodel */
                   12571: 
1.187     brouard  12572: 
1.223     brouard  12573:   if(decodemodel(model, lastobs) == 1) /* In order to get Tvar[k] V4+V3+V5 p Tvar[1]@3  = {4, 3, 5}*/
1.136     brouard  12574:     goto end;
                   12575: 
1.137     brouard  12576:   if((double)(lastobs-imx)/(double)imx > 1.10){
                   12577:     nbwarn++;
                   12578:     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); 
                   12579:     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); 
                   12580:   }
1.136     brouard  12581:     /*  if(mle==1){*/
1.137     brouard  12582:   if (weightopt != 1) { /* Maximisation without weights. We can have weights different from 1 but want no weight*/
                   12583:     for(i=1;i<=imx;i++) weight[i]=1.0; /* changed to imx */
1.136     brouard  12584:   }
                   12585: 
                   12586:     /*-calculation of age at interview from date of interview and age at death -*/
                   12587:   agev=matrix(1,maxwav,1,imx);
                   12588: 
                   12589:   if(calandcheckages(imx, maxwav, &agemin, &agemax, &nberr, &nbwarn) == 1)
                   12590:     goto end;
                   12591: 
1.126     brouard  12592: 
1.136     brouard  12593:   agegomp=(int)agemin;
1.290     brouard  12594:   free_vector(moisnais,firstobs,lastobs);
                   12595:   free_vector(annais,firstobs,lastobs);
1.126     brouard  12596:   /* free_matrix(mint,1,maxwav,1,n);
                   12597:      free_matrix(anint,1,maxwav,1,n);*/
1.215     brouard  12598:   /* free_vector(moisdc,1,n); */
                   12599:   /* free_vector(andc,1,n); */
1.145     brouard  12600:   /* */
                   12601:   
1.126     brouard  12602:   wav=ivector(1,imx);
1.214     brouard  12603:   /* dh=imatrix(1,lastpass-firstpass+1,1,imx); */
                   12604:   /* bh=imatrix(1,lastpass-firstpass+1,1,imx); */
                   12605:   /* mw=imatrix(1,lastpass-firstpass+1,1,imx); */
                   12606:   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.*/
                   12607:   bh=imatrix(1,lastpass-firstpass+2,1,imx);
                   12608:   mw=imatrix(1,lastpass-firstpass+2,1,imx);
1.126     brouard  12609:    
                   12610:   /* Concatenates waves */
1.214     brouard  12611:   /* Concatenates waves: wav[i] is the number of effective (useful waves) of individual i.
                   12612:      Death is a valid wave (if date is known).
                   12613:      mw[mi][i] is the number of (mi=1 to wav[i]) effective wave out of mi of individual i
                   12614:      dh[m][i] or dh[mw[mi][i]][i] is the delay between two effective waves m=mw[mi][i]
                   12615:      and mw[mi+1][i]. dh depends on stepm.
                   12616:   */
                   12617: 
1.126     brouard  12618:   concatwav(wav, dh, bh, mw, s, agedc, agev,  firstpass, lastpass, imx, nlstate, stepm);
1.248     brouard  12619:   /* Concatenates waves */
1.145     brouard  12620:  
1.290     brouard  12621:   free_vector(moisdc,firstobs,lastobs);
                   12622:   free_vector(andc,firstobs,lastobs);
1.215     brouard  12623: 
1.126     brouard  12624:   /* Routine tricode is to calculate cptcoveff (real number of unique covariates) and to associate covariable number and modality */
                   12625:   nbcode=imatrix(0,NCOVMAX,0,NCOVMAX); 
                   12626:   ncodemax[1]=1;
1.145     brouard  12627:   Ndum =ivector(-1,NCOVMAX);  
1.225     brouard  12628:   cptcoveff=0;
1.220     brouard  12629:   if (ncovmodel-nagesqr > 2 ){ /* That is if covariate other than cst, age and age*age */
1.335     brouard  12630:     tricode(&cptcoveff,Tvar,nbcode,imx, Ndum); /**< Fills nbcode[Tvar[j]][l]; as well as calculate cptcoveff or number of total effective dummy covariates*/
1.227     brouard  12631:   }
                   12632:   
                   12633:   ncovcombmax=pow(2,cptcoveff);
                   12634:   invalidvarcomb=ivector(1, ncovcombmax); 
                   12635:   for(i=1;i<ncovcombmax;i++)
                   12636:     invalidvarcomb[i]=0;
                   12637:   
1.211     brouard  12638:   /* Nbcode gives the value of the lth modality (currently 1 to 2) of jth covariate, in
1.186     brouard  12639:      V2+V1*age, there are 3 covariates Tvar[2]=1 (V1).*/
1.211     brouard  12640:   /* 1 to ncodemax[j] which is the maximum value of this jth covariate */
1.227     brouard  12641:   
1.200     brouard  12642:   /*  codtab=imatrix(1,100,1,10);*/ /* codtab[h,k]=( (h-1) - mod(k-1,2**(k-1) )/2**(k-1) */
1.198     brouard  12643:   /*printf(" codtab[1,1],codtab[100,10]=%d,%d\n", codtab[1][1],codtabm(100,10));*/
1.186     brouard  12644:   /* codtab gives the value 1 or 2 of the hth combination of k covariates (1 or 2).*/
1.211     brouard  12645:   /* nbcode[Tvaraff[j]][codtabm(h,j)]) : if there are only 2 modalities for a covariate j, 
                   12646:    * codtabm(h,j) gives its value classified at position h and nbcode gives how it is coded 
                   12647:    * (currently 0 or 1) in the data.
                   12648:    * In a loop on h=1 to 2**k, and a loop on j (=1 to k), we get the value of 
                   12649:    * corresponding modality (h,j).
                   12650:    */
                   12651: 
1.145     brouard  12652:   h=0;
                   12653:   /*if (cptcovn > 0) */
1.126     brouard  12654:   m=pow(2,cptcoveff);
                   12655:  
1.144     brouard  12656:          /**< codtab(h,k)  k   = codtab[h,k]=( (h-1) - mod(k-1,2**(k-1) )/2**(k-1) + 1
1.211     brouard  12657:           * For k=4 covariates, h goes from 1 to m=2**k
                   12658:           * codtabm(h,k)=  (1 & (h-1) >> (k-1)) + 1;
                   12659:            * #define codtabm(h,k)  (1 & (h-1) >> (k-1))+1
1.329     brouard  12660:           *     h\k   1     2     3     4   *  h-1\k-1  4  3  2  1          
                   12661:           *______________________________   *______________________
                   12662:           *     1 i=1 1 i=1 1 i=1 1 i=1 1   *     0     0  0  0  0 
                   12663:           *     2     2     1     1     1   *     1     0  0  0  1 
                   12664:           *     3 i=2 1     2     1     1   *     2     0  0  1  0 
                   12665:           *     4     2     2     1     1   *     3     0  0  1  1 
                   12666:           *     5 i=3 1 i=2 1     2     1   *     4     0  1  0  0 
                   12667:           *     6     2     1     2     1   *     5     0  1  0  1 
                   12668:           *     7 i=4 1     2     2     1   *     6     0  1  1  0 
                   12669:           *     8     2     2     2     1   *     7     0  1  1  1 
                   12670:           *     9 i=5 1 i=3 1 i=2 1     2   *     8     1  0  0  0 
                   12671:           *    10     2     1     1     2   *     9     1  0  0  1 
                   12672:           *    11 i=6 1     2     1     2   *    10     1  0  1  0 
                   12673:           *    12     2     2     1     2   *    11     1  0  1  1 
                   12674:           *    13 i=7 1 i=4 1     2     2   *    12     1  1  0  0  
                   12675:           *    14     2     1     2     2   *    13     1  1  0  1 
                   12676:           *    15 i=8 1     2     2     2   *    14     1  1  1  0 
                   12677:           *    16     2     2     2     2   *    15     1  1  1  1          
                   12678:           */                                     
1.212     brouard  12679:   /* How to do the opposite? From combination h (=1 to 2**k) how to get the value on the covariates? */
1.211     brouard  12680:      /* from h=5 and m, we get then number of covariates k=log(m)/log(2)=4
                   12681:      * and the value of each covariate?
                   12682:      * V1=1, V2=1, V3=2, V4=1 ?
                   12683:      * h-1=4 and 4 is 0100 or reverse 0010, and +1 is 1121 ok.
                   12684:      * h=6, 6-1=5, 5 is 0101, 1010, 2121, V1=2nd, V2=1st, V3=2nd, V4=1st.
                   12685:      * In order to get the real value in the data, we use nbcode
                   12686:      * nbcode[Tvar[3][2nd]]=1 and nbcode[Tvar[4][1]]=0
                   12687:      * We are keeping this crazy system in order to be able (in the future?) 
                   12688:      * to have more than 2 values (0 or 1) for a covariate.
                   12689:      * #define codtabm(h,k)  (1 & (h-1) >> (k-1))+1
                   12690:      * h=6, k=2? h-1=5=0101, reverse 1010, +1=2121, k=2nd position: value is 1: codtabm(6,2)=1
                   12691:      *              bbbbbbbb
                   12692:      *              76543210     
                   12693:      *   h-1        00000101 (6-1=5)
1.219     brouard  12694:      *(h-1)>>(k-1)= 00000010 >> (2-1) = 1 right shift
1.211     brouard  12695:      *           &
                   12696:      *     1        00000001 (1)
1.219     brouard  12697:      *              00000000        = 1 & ((h-1) >> (k-1))
                   12698:      *          +1= 00000001 =1 
1.211     brouard  12699:      *
                   12700:      * h=14, k=3 => h'=h-1=13, k'=k-1=2
                   12701:      *          h'      1101 =2^3+2^2+0x2^1+2^0
                   12702:      *    >>k'            11
                   12703:      *          &   00000001
                   12704:      *            = 00000001
                   12705:      *      +1    = 00000010=2    =  codtabm(14,3)   
                   12706:      * Reverse h=6 and m=16?
                   12707:      * cptcoveff=log(16)/log(2)=4 covariate: 6-1=5=0101 reversed=1010 +1=2121 =>V1=2, V2=1, V3=2, V4=1.
                   12708:      * for (j=1 to cptcoveff) Vj=decodtabm(j,h,cptcoveff)
                   12709:      * decodtabm(h,j,cptcoveff)= (((h-1) >> (j-1)) & 1) +1 
                   12710:      * decodtabm(h,j,cptcoveff)= (h <= (1<<cptcoveff)?(((h-1) >> (j-1)) & 1) +1 : -1)
                   12711:      * V3=decodtabm(14,3,2**4)=2
                   12712:      *          h'=13   1101 =2^3+2^2+0x2^1+2^0
                   12713:      *(h-1) >> (j-1)    0011 =13 >> 2
                   12714:      *          &1 000000001
                   12715:      *           = 000000001
                   12716:      *         +1= 000000010 =2
                   12717:      *                  2211
                   12718:      *                  V1=1+1, V2=0+1, V3=1+1, V4=1+1
                   12719:      *                  V3=2
1.220     brouard  12720:                 * codtabm and decodtabm are identical
1.211     brouard  12721:      */
                   12722: 
1.145     brouard  12723: 
                   12724:  free_ivector(Ndum,-1,NCOVMAX);
                   12725: 
                   12726: 
1.126     brouard  12727:     
1.186     brouard  12728:   /* Initialisation of ----------- gnuplot -------------*/
1.126     brouard  12729:   strcpy(optionfilegnuplot,optionfilefiname);
                   12730:   if(mle==-3)
1.201     brouard  12731:     strcat(optionfilegnuplot,"-MORT_");
1.126     brouard  12732:   strcat(optionfilegnuplot,".gp");
                   12733: 
                   12734:   if((ficgp=fopen(optionfilegnuplot,"w"))==NULL) {
                   12735:     printf("Problem with file %s",optionfilegnuplot);
                   12736:   }
                   12737:   else{
1.204     brouard  12738:     fprintf(ficgp,"\n# IMaCh-%s\n", version); 
1.126     brouard  12739:     fprintf(ficgp,"# %s\n", optionfilegnuplot); 
1.141     brouard  12740:     //fprintf(ficgp,"set missing 'NaNq'\n");
                   12741:     fprintf(ficgp,"set datafile missing 'NaNq'\n");
1.126     brouard  12742:   }
                   12743:   /*  fclose(ficgp);*/
1.186     brouard  12744: 
                   12745: 
                   12746:   /* Initialisation of --------- index.htm --------*/
1.126     brouard  12747: 
                   12748:   strcpy(optionfilehtm,optionfilefiname); /* Main html file */
                   12749:   if(mle==-3)
1.201     brouard  12750:     strcat(optionfilehtm,"-MORT_");
1.126     brouard  12751:   strcat(optionfilehtm,".htm");
                   12752:   if((fichtm=fopen(optionfilehtm,"w"))==NULL)    {
1.131     brouard  12753:     printf("Problem with %s \n",optionfilehtm);
                   12754:     exit(0);
1.126     brouard  12755:   }
                   12756: 
                   12757:   strcpy(optionfilehtmcov,optionfilefiname); /* Only for matrix of covariance */
                   12758:   strcat(optionfilehtmcov,"-cov.htm");
                   12759:   if((fichtmcov=fopen(optionfilehtmcov,"w"))==NULL)    {
                   12760:     printf("Problem with %s \n",optionfilehtmcov), exit(0);
                   12761:   }
                   12762:   else{
                   12763:   fprintf(fichtmcov,"<html><head>\n<title>IMaCh Cov %s</title></head>\n <body><font size=\"2\">%s <br> %s</font> \
                   12764: <hr size=\"2\" color=\"#EC5E5E\"> \n\
1.204     brouard  12765: Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=1+age+%s<br>\n",\
1.126     brouard  12766:          optionfilehtmcov,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model);
                   12767:   }
                   12768: 
1.335     brouard  12769:   fprintf(fichtm,"<html><head>\n<meta charset=\"utf-8\"/><meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\" />\n\
                   12770: <title>IMaCh %s</title></head>\n\
                   12771:  <body><font size=\"7\"><a href=http:/euroreves.ined.fr/imach>IMaCh for Interpolated Markov Chain</a> </font><br>\n\
                   12772: <font size=\"3\">Sponsored by Copyright (C)  2002-2015 <a href=http://www.ined.fr>INED</a>\
                   12773: -EUROREVES-Institut de longévité-2013-2022-Japan Society for the Promotion of Sciences 日本学術振興会 \
                   12774: (<a href=https://www.jsps.go.jp/english/e-grants/>Grant-in-Aid for Scientific Research 25293121</a>) - \
                   12775: <a href=https://software.intel.com/en-us>Intel Software 2015-2018</a></font><br> \n", optionfilehtm);
                   12776:   
                   12777:   fprintf(fichtm,"<hr size=\"2\" color=\"#EC5E5E\"> \n\
1.204     brouard  12778: <font size=\"2\">IMaCh-%s <br> %s</font> \
1.126     brouard  12779: <hr size=\"2\" color=\"#EC5E5E\"> \n\
1.335     brouard  12780: This file: <a href=\"%s\">%s</a>Title=%s <br>Datafile=<a href=\"%s\">%s</a> Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=1+age+%s<br>\n\
1.126     brouard  12781: \n\
                   12782: <hr  size=\"2\" color=\"#EC5E5E\">\
                   12783:  <ul><li><h4>Parameter files</h4>\n\
                   12784:  - Parameter file: <a href=\"%s.%s\">%s.%s</a><br>\n\
                   12785:  - Copy of the parameter file: <a href=\"o%s\">o%s</a><br>\n\
                   12786:  - Log file of the run: <a href=\"%s\">%s</a><br>\n\
                   12787:  - Gnuplot file name: <a href=\"%s\">%s</a><br>\n\
                   12788:  - Date and time at start: %s</ul>\n",\
1.335     brouard  12789:          version,fullversion,optionfilehtm,optionfilehtm,title,datafile,datafile,firstpass,lastpass,stepm, weightopt, model, \
1.126     brouard  12790:          optionfilefiname,optionfilext,optionfilefiname,optionfilext,\
                   12791:          fileres,fileres,\
                   12792:          filelog,filelog,optionfilegnuplot,optionfilegnuplot,strstart);
                   12793:   fflush(fichtm);
                   12794: 
                   12795:   strcpy(pathr,path);
                   12796:   strcat(pathr,optionfilefiname);
1.184     brouard  12797: #ifdef WIN32
                   12798:   _chdir(optionfilefiname); /* Move to directory named optionfile */
                   12799: #else
1.126     brouard  12800:   chdir(optionfilefiname); /* Move to directory named optionfile */
1.184     brouard  12801: #endif
                   12802:          
1.126     brouard  12803:   
1.220     brouard  12804:   /* Calculates basic frequencies. Computes observed prevalence at single age 
                   12805:                 and for any valid combination of covariates
1.126     brouard  12806:      and prints on file fileres'p'. */
1.251     brouard  12807:   freqsummary(fileres, p, pstart, agemin, agemax, s, agev, nlstate, imx, Tvaraff, invalidvarcomb, nbcode, ncodemax,mint,anint,strstart, \
1.227     brouard  12808:              firstpass, lastpass,  stepm,  weightopt, model);
1.126     brouard  12809: 
                   12810:   fprintf(fichtm,"\n");
1.286     brouard  12811:   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  12812:          ftol, stepm);
                   12813:   fprintf(fichtm,"\n<li>Number of fixed dummy covariates: ncovcol=%d ", ncovcol);
                   12814:   ncurrv=1;
                   12815:   for(i=ncurrv; i <=ncovcol; i++) fprintf(fichtm,"V%d ", i);
                   12816:   fprintf(fichtm,"\n<li> Number of fixed quantitative variables: nqv=%d ", nqv); 
                   12817:   ncurrv=i;
                   12818:   for(i=ncurrv; i <=ncurrv-1+nqv; i++) fprintf(fichtm,"V%d ", i);
1.290     brouard  12819:   fprintf(fichtm,"\n<li> Number of time varying (wave varying) dummy covariates: ntv=%d ", ntv);
1.274     brouard  12820:   ncurrv=i;
                   12821:   for(i=ncurrv; i <=ncurrv-1+ntv; i++) fprintf(fichtm,"V%d ", i);
1.290     brouard  12822:   fprintf(fichtm,"\n<li>Number of time varying  quantitative covariates: nqtv=%d ", nqtv);
1.274     brouard  12823:   ncurrv=i;
                   12824:   for(i=ncurrv; i <=ncurrv-1+nqtv; i++) fprintf(fichtm,"V%d ", i);
                   12825:   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", \
                   12826:           nlstate, ndeath, maxwav, mle, weightopt);
                   12827: 
                   12828:   fprintf(fichtm,"<h4> Diagram of states <a href=\"%s_.svg\">%s_.svg</a></h4> \n\
                   12829: <img src=\"%s_.svg\">", subdirf2(optionfilefiname,"D_"),subdirf2(optionfilefiname,"D_"),subdirf2(optionfilefiname,"D_"));
                   12830: 
                   12831:   
1.317     brouard  12832:   fprintf(fichtm,"\n<h4>Some descriptive statistics </h4>\n<br>Number of (used) observations=%d <br>\n\
1.126     brouard  12833: Youngest age at first (selected) pass %.2f, oldest age %.2f<br>\n\
                   12834: Interval (in months) between two waves: Min=%d Max=%d Mean=%.2lf<br>\n",\
1.274     brouard  12835:   imx,agemin,agemax,jmin,jmax,jmean);
1.126     brouard  12836:   pmmij= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
1.268     brouard  12837:   oldms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
                   12838:   newms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
                   12839:   savms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
                   12840:   oldm=oldms; newm=newms; savm=savms; /* Keeps fixed addresses to free */
1.218     brouard  12841: 
1.126     brouard  12842:   /* For Powell, parameters are in a vector p[] starting at p[1]
                   12843:      so we point p on param[1][1] so that p[1] maps on param[1][1][1] */
                   12844:   p=param[1][1]; /* *(*(*(param +1)+1)+0) */
                   12845: 
                   12846:   globpr=0; /* To get the number ipmx of contributions and the sum of weights*/
1.186     brouard  12847:   /* For mortality only */
1.126     brouard  12848:   if (mle==-3){
1.136     brouard  12849:     ximort=matrix(1,NDIM,1,NDIM); 
1.248     brouard  12850:     for(i=1;i<=NDIM;i++)
                   12851:       for(j=1;j<=NDIM;j++)
                   12852:        ximort[i][j]=0.;
1.186     brouard  12853:     /*     ximort=gsl_matrix_alloc(1,NDIM,1,NDIM); */
1.290     brouard  12854:     cens=ivector(firstobs,lastobs);
                   12855:     ageexmed=vector(firstobs,lastobs);
                   12856:     agecens=vector(firstobs,lastobs);
                   12857:     dcwave=ivector(firstobs,lastobs);
1.223     brouard  12858:                
1.126     brouard  12859:     for (i=1; i<=imx; i++){
                   12860:       dcwave[i]=-1;
                   12861:       for (m=firstpass; m<=lastpass; m++)
1.226     brouard  12862:        if (s[m][i]>nlstate) {
                   12863:          dcwave[i]=m;
                   12864:          /*    printf("i=%d j=%d s=%d dcwave=%d\n",i,j, s[j][i],dcwave[i]);*/
                   12865:          break;
                   12866:        }
1.126     brouard  12867:     }
1.226     brouard  12868:     
1.126     brouard  12869:     for (i=1; i<=imx; i++) {
                   12870:       if (wav[i]>0){
1.226     brouard  12871:        ageexmed[i]=agev[mw[1][i]][i];
                   12872:        j=wav[i];
                   12873:        agecens[i]=1.; 
                   12874:        
                   12875:        if (ageexmed[i]> 1 && wav[i] > 0){
                   12876:          agecens[i]=agev[mw[j][i]][i];
                   12877:          cens[i]= 1;
                   12878:        }else if (ageexmed[i]< 1) 
                   12879:          cens[i]= -1;
                   12880:        if (agedc[i]< AGESUP && agedc[i]>1 && dcwave[i]>firstpass && dcwave[i]<=lastpass)
                   12881:          cens[i]=0 ;
1.126     brouard  12882:       }
                   12883:       else cens[i]=-1;
                   12884:     }
                   12885:     
                   12886:     for (i=1;i<=NDIM;i++) {
                   12887:       for (j=1;j<=NDIM;j++)
1.226     brouard  12888:        ximort[i][j]=(i == j ? 1.0 : 0.0);
1.126     brouard  12889:     }
                   12890:     
1.302     brouard  12891:     p[1]=0.0268; p[NDIM]=0.083;
                   12892:     /* printf("%lf %lf", p[1], p[2]); */
1.126     brouard  12893:     
                   12894:     
1.136     brouard  12895: #ifdef GSL
                   12896:     printf("GSL optimization\n");  fprintf(ficlog,"Powell\n");
1.162     brouard  12897: #else
1.126     brouard  12898:     printf("Powell\n");  fprintf(ficlog,"Powell\n");
1.136     brouard  12899: #endif
1.201     brouard  12900:     strcpy(filerespow,"POW-MORT_"); 
                   12901:     strcat(filerespow,fileresu);
1.126     brouard  12902:     if((ficrespow=fopen(filerespow,"w"))==NULL) {
                   12903:       printf("Problem with resultfile: %s\n", filerespow);
                   12904:       fprintf(ficlog,"Problem with resultfile: %s\n", filerespow);
                   12905:     }
1.136     brouard  12906: #ifdef GSL
                   12907:     fprintf(ficrespow,"# GSL optimization\n# iter -2*LL");
1.162     brouard  12908: #else
1.126     brouard  12909:     fprintf(ficrespow,"# Powell\n# iter -2*LL");
1.136     brouard  12910: #endif
1.126     brouard  12911:     /*  for (i=1;i<=nlstate;i++)
                   12912:        for(j=1;j<=nlstate+ndeath;j++)
                   12913:        if(j!=i)fprintf(ficrespow," p%1d%1d",i,j);
                   12914:     */
                   12915:     fprintf(ficrespow,"\n");
1.136     brouard  12916: #ifdef GSL
                   12917:     /* gsl starts here */ 
                   12918:     T = gsl_multimin_fminimizer_nmsimplex;
                   12919:     gsl_multimin_fminimizer *sfm = NULL;
                   12920:     gsl_vector *ss, *x;
                   12921:     gsl_multimin_function minex_func;
                   12922: 
                   12923:     /* Initial vertex size vector */
                   12924:     ss = gsl_vector_alloc (NDIM);
                   12925:     
                   12926:     if (ss == NULL){
                   12927:       GSL_ERROR_VAL ("failed to allocate space for ss", GSL_ENOMEM, 0);
                   12928:     }
                   12929:     /* Set all step sizes to 1 */
                   12930:     gsl_vector_set_all (ss, 0.001);
                   12931: 
                   12932:     /* Starting point */
1.126     brouard  12933:     
1.136     brouard  12934:     x = gsl_vector_alloc (NDIM);
                   12935:     
                   12936:     if (x == NULL){
                   12937:       gsl_vector_free(ss);
                   12938:       GSL_ERROR_VAL ("failed to allocate space for x", GSL_ENOMEM, 0);
                   12939:     }
                   12940:   
                   12941:     /* Initialize method and iterate */
                   12942:     /*     p[1]=0.0268; p[NDIM]=0.083; */
1.186     brouard  12943:     /*     gsl_vector_set(x, 0, 0.0268); */
                   12944:     /*     gsl_vector_set(x, 1, 0.083); */
1.136     brouard  12945:     gsl_vector_set(x, 0, p[1]);
                   12946:     gsl_vector_set(x, 1, p[2]);
                   12947: 
                   12948:     minex_func.f = &gompertz_f;
                   12949:     minex_func.n = NDIM;
                   12950:     minex_func.params = (void *)&p; /* ??? */
                   12951:     
                   12952:     sfm = gsl_multimin_fminimizer_alloc (T, NDIM);
                   12953:     gsl_multimin_fminimizer_set (sfm, &minex_func, x, ss);
                   12954:     
                   12955:     printf("Iterations beginning .....\n\n");
                   12956:     printf("Iter. #    Intercept       Slope     -Log Likelihood     Simplex size\n");
                   12957: 
                   12958:     iteri=0;
                   12959:     while (rval == GSL_CONTINUE){
                   12960:       iteri++;
                   12961:       status = gsl_multimin_fminimizer_iterate(sfm);
                   12962:       
                   12963:       if (status) printf("error: %s\n", gsl_strerror (status));
                   12964:       fflush(0);
                   12965:       
                   12966:       if (status) 
                   12967:         break;
                   12968:       
                   12969:       rval = gsl_multimin_test_size (gsl_multimin_fminimizer_size (sfm), 1e-6);
                   12970:       ssval = gsl_multimin_fminimizer_size (sfm);
                   12971:       
                   12972:       if (rval == GSL_SUCCESS)
                   12973:         printf ("converged to a local maximum at\n");
                   12974:       
                   12975:       printf("%5d ", iteri);
                   12976:       for (it = 0; it < NDIM; it++){
                   12977:        printf ("%10.5f ", gsl_vector_get (sfm->x, it));
                   12978:       }
                   12979:       printf("f() = %-10.5f ssize = %.7f\n", sfm->fval, ssval);
                   12980:     }
                   12981:     
                   12982:     printf("\n\n Please note: Program should be run many times with varying starting points to detemine global maximum\n\n");
                   12983:     
                   12984:     gsl_vector_free(x); /* initial values */
                   12985:     gsl_vector_free(ss); /* inital step size */
                   12986:     for (it=0; it<NDIM; it++){
                   12987:       p[it+1]=gsl_vector_get(sfm->x,it);
                   12988:       fprintf(ficrespow," %.12lf", p[it]);
                   12989:     }
                   12990:     gsl_multimin_fminimizer_free (sfm); /* p *(sfm.x.data) et p *(sfm.x.data+1)  */
                   12991: #endif
                   12992: #ifdef POWELL
                   12993:      powell(p,ximort,NDIM,ftol,&iter,&fret,gompertz);
                   12994: #endif  
1.126     brouard  12995:     fclose(ficrespow);
                   12996:     
1.203     brouard  12997:     hesscov(matcov, hess, p, NDIM, delti, 1e-4, gompertz); 
1.126     brouard  12998: 
                   12999:     for(i=1; i <=NDIM; i++)
                   13000:       for(j=i+1;j<=NDIM;j++)
1.220     brouard  13001:                                matcov[i][j]=matcov[j][i];
1.126     brouard  13002:     
                   13003:     printf("\nCovariance matrix\n ");
1.203     brouard  13004:     fprintf(ficlog,"\nCovariance matrix\n ");
1.126     brouard  13005:     for(i=1; i <=NDIM; i++) {
                   13006:       for(j=1;j<=NDIM;j++){ 
1.220     brouard  13007:                                printf("%f ",matcov[i][j]);
                   13008:                                fprintf(ficlog,"%f ",matcov[i][j]);
1.126     brouard  13009:       }
1.203     brouard  13010:       printf("\n ");  fprintf(ficlog,"\n ");
1.126     brouard  13011:     }
                   13012:     
                   13013:     printf("iter=%d MLE=%f Eq=%lf*exp(%lf*(age-%d))\n",iter,-gompertz(p),p[1],p[2],agegomp);
1.193     brouard  13014:     for (i=1;i<=NDIM;i++) {
1.126     brouard  13015:       printf("%f [%f ; %f]\n",p[i],p[i]-2*sqrt(matcov[i][i]),p[i]+2*sqrt(matcov[i][i]));
1.193     brouard  13016:       fprintf(ficlog,"%f [%f ; %f]\n",p[i],p[i]-2*sqrt(matcov[i][i]),p[i]+2*sqrt(matcov[i][i]));
                   13017:     }
1.302     brouard  13018:     lsurv=vector(agegomp,AGESUP);
                   13019:     lpop=vector(agegomp,AGESUP);
                   13020:     tpop=vector(agegomp,AGESUP);
1.126     brouard  13021:     lsurv[agegomp]=100000;
                   13022:     
                   13023:     for (k=agegomp;k<=AGESUP;k++) {
                   13024:       agemortsup=k;
                   13025:       if (p[1]*exp(p[2]*(k-agegomp))>1) break;
                   13026:     }
                   13027:     
                   13028:     for (k=agegomp;k<agemortsup;k++)
                   13029:       lsurv[k+1]=lsurv[k]-lsurv[k]*(p[1]*exp(p[2]*(k-agegomp)));
                   13030:     
                   13031:     for (k=agegomp;k<agemortsup;k++){
                   13032:       lpop[k]=(lsurv[k]+lsurv[k+1])/2.;
                   13033:       sumlpop=sumlpop+lpop[k];
                   13034:     }
                   13035:     
                   13036:     tpop[agegomp]=sumlpop;
                   13037:     for (k=agegomp;k<(agemortsup-3);k++){
                   13038:       /*  tpop[k+1]=2;*/
                   13039:       tpop[k+1]=tpop[k]-lpop[k];
                   13040:     }
                   13041:     
                   13042:     
                   13043:     printf("\nAge   lx     qx    dx    Lx     Tx     e(x)\n");
                   13044:     for (k=agegomp;k<(agemortsup-2);k++) 
                   13045:       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]);
                   13046:     
                   13047:     
                   13048:     replace_back_to_slash(pathc,pathcd); /* Even gnuplot wants a / */
1.220     brouard  13049:                ageminpar=50;
                   13050:                agemaxpar=100;
1.194     brouard  13051:     if(ageminpar == AGEOVERFLOW ||agemaxpar == AGEOVERFLOW){
                   13052:        printf("Warning! Error in gnuplot file with ageminpar %f or agemaxpar %f overflow\n\
                   13053: This is probably because your parameter file doesn't \n  contain the exact number of lines (or columns) corresponding to your model line.\n\
                   13054: Please run with mle=-1 to get a correct covariance matrix.\n",ageminpar,agemaxpar);
                   13055:        fprintf(ficlog,"Warning! Error in gnuplot file with ageminpar %f or agemaxpar %f overflow\n\
                   13056: This is probably because your parameter file doesn't \n  contain the exact number of lines (or columns) corresponding to your model line.\n\
                   13057: Please run with mle=-1 to get a correct covariance matrix.\n",ageminpar,agemaxpar);
1.220     brouard  13058:     }else{
                   13059:                        printf("Warning! ageminpar %f and agemaxpar %f have been fixed because for simplification until it is fixed...\n\n",ageminpar,agemaxpar);
                   13060:                        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  13061:       printinggnuplotmort(fileresu, optionfilefiname,ageminpar,agemaxpar,fage, pathc,p);
1.220     brouard  13062:                }
1.201     brouard  13063:     printinghtmlmort(fileresu,title,datafile, firstpass, lastpass, \
1.126     brouard  13064:                     stepm, weightopt,\
                   13065:                     model,imx,p,matcov,agemortsup);
                   13066:     
1.302     brouard  13067:     free_vector(lsurv,agegomp,AGESUP);
                   13068:     free_vector(lpop,agegomp,AGESUP);
                   13069:     free_vector(tpop,agegomp,AGESUP);
1.220     brouard  13070:     free_matrix(ximort,1,NDIM,1,NDIM);
1.290     brouard  13071:     free_ivector(dcwave,firstobs,lastobs);
                   13072:     free_vector(agecens,firstobs,lastobs);
                   13073:     free_vector(ageexmed,firstobs,lastobs);
                   13074:     free_ivector(cens,firstobs,lastobs);
1.220     brouard  13075: #ifdef GSL
1.136     brouard  13076: #endif
1.186     brouard  13077:   } /* Endof if mle==-3 mortality only */
1.205     brouard  13078:   /* Standard  */
                   13079:   else{ /* For mle !=- 3, could be 0 or 1 or 4 etc. */
                   13080:     globpr=0;/* Computes sum of likelihood for globpr=1 and funcone */
                   13081:     /* Computes likelihood for initial parameters, uses funcone to compute gpimx and gsw */
1.132     brouard  13082:     likelione(ficres, p, npar, nlstate, &globpr, &ipmx, &sw, &fretone, funcone); /* Prints the contributions to the likelihood */
1.126     brouard  13083:     printf("First Likeli=%12.6f ipmx=%ld sw=%12.6f",fretone,ipmx,sw);
                   13084:     for (k=1; k<=npar;k++)
                   13085:       printf(" %d %8.5f",k,p[k]);
                   13086:     printf("\n");
1.205     brouard  13087:     if(mle>=1){ /* Could be 1 or 2, Real Maximization */
                   13088:       /* mlikeli uses func not funcone */
1.247     brouard  13089:       /* for(i=1;i<nlstate;i++){ */
                   13090:       /*       /\*reducing xi for 1 to npar to 1 to ncovmodel; *\/ */
                   13091:       /*    mlikeli(ficres,p, ncovmodel, ncovmodel, nlstate, ftol, funcnoprod); */
                   13092:       /* } */
1.205     brouard  13093:       mlikeli(ficres,p, npar, ncovmodel, nlstate, ftol, func);
                   13094:     }
                   13095:     if(mle==0) {/* No optimization, will print the likelihoods for the datafile */
                   13096:       globpr=0;/* Computes sum of likelihood for globpr=1 and funcone */
                   13097:       /* Computes likelihood for initial parameters, uses funcone to compute gpimx and gsw */
                   13098:       likelione(ficres, p, npar, nlstate, &globpr, &ipmx, &sw, &fretone, funcone); /* Prints the contributions to the likelihood */
                   13099:     }
                   13100:     globpr=1; /* again, to print the individual contributions using computed gpimx and gsw */
1.126     brouard  13101:     likelione(ficres, p, npar, nlstate, &globpr, &ipmx, &sw, &fretone, funcone); /* Prints the contributions to the likelihood */
                   13102:     printf("Second Likeli=%12.6f ipmx=%ld sw=%12.6f",fretone,ipmx,sw);
1.335     brouard  13103:           /* exit(0); */
1.126     brouard  13104:     for (k=1; k<=npar;k++)
                   13105:       printf(" %d %8.5f",k,p[k]);
                   13106:     printf("\n");
                   13107:     
                   13108:     /*--------- results files --------------*/
1.283     brouard  13109:     /* 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  13110:     
                   13111:     
                   13112:     fprintf(ficres,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
1.319     brouard  13113:     printf("# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n"); /* Printing model equation */
1.126     brouard  13114:     fprintf(ficlog,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
1.319     brouard  13115: 
                   13116:     printf("#model=  1      +     age ");
                   13117:     fprintf(ficres,"#model=  1      +     age ");
                   13118:     fprintf(ficlog,"#model=  1      +     age ");
                   13119:     fprintf(fichtm,"\n<ul><li> model=1+age+%s\n \
                   13120: </ul>", model);
                   13121: 
                   13122:     fprintf(fichtm,"\n<table style=\"text-align:center; border: 1px solid\">\n");
                   13123:     fprintf(fichtm, "<tr><th>Model=</th><th>1</th><th>+ age</th>");
                   13124:     if(nagesqr==1){
                   13125:       printf("  + age*age  ");
                   13126:       fprintf(ficres,"  + age*age  ");
                   13127:       fprintf(ficlog,"  + age*age  ");
                   13128:       fprintf(fichtm, "<th>+ age*age</th>");
                   13129:     }
                   13130:     for(j=1;j <=ncovmodel-2;j++){
                   13131:       if(Typevar[j]==0) {
                   13132:        printf("  +      V%d  ",Tvar[j]);
                   13133:        fprintf(ficres,"  +      V%d  ",Tvar[j]);
                   13134:        fprintf(ficlog,"  +      V%d  ",Tvar[j]);
                   13135:        fprintf(fichtm, "<th>+ V%d</th>",Tvar[j]);
                   13136:       }else if(Typevar[j]==1) {
                   13137:        printf("  +    V%d*age ",Tvar[j]);
                   13138:        fprintf(ficres,"  +    V%d*age ",Tvar[j]);
                   13139:        fprintf(ficlog,"  +    V%d*age ",Tvar[j]);
                   13140:        fprintf(fichtm, "<th>+  V%d*age</th>",Tvar[j]);
                   13141:       }else if(Typevar[j]==2) {
                   13142:        printf("  +    V%d*V%d ",Tvard[Tposprod[j]][1],Tvard[Tposprod[j]][2]);
                   13143:        fprintf(ficres,"  +    V%d*V%d ",Tvard[Tposprod[j]][1],Tvard[Tposprod[j]][2]);
                   13144:        fprintf(ficlog,"  +    V%d*V%d ",Tvard[Tposprod[j]][1],Tvard[Tposprod[j]][2]);
                   13145:        fprintf(fichtm, "<th>+  V%d*V%d</th>",Tvard[Tposprod[j]][1],Tvard[Tposprod[j]][2]);
                   13146:       }
                   13147:     }
                   13148:     printf("\n");
                   13149:     fprintf(ficres,"\n");
                   13150:     fprintf(ficlog,"\n");
                   13151:     fprintf(fichtm, "</tr>");
                   13152:     fprintf(fichtm, "\n");
                   13153:     
                   13154:     
1.126     brouard  13155:     for(i=1,jk=1; i <=nlstate; i++){
                   13156:       for(k=1; k <=(nlstate+ndeath); k++){
1.225     brouard  13157:        if (k != i) {
1.319     brouard  13158:          fprintf(fichtm, "<tr>");
1.225     brouard  13159:          printf("%d%d ",i,k);
                   13160:          fprintf(ficlog,"%d%d ",i,k);
                   13161:          fprintf(ficres,"%1d%1d ",i,k);
1.319     brouard  13162:          fprintf(fichtm, "<td>%1d%1d</td>",i,k);
1.225     brouard  13163:          for(j=1; j <=ncovmodel; j++){
                   13164:            printf("%12.7f ",p[jk]);
                   13165:            fprintf(ficlog,"%12.7f ",p[jk]);
                   13166:            fprintf(ficres,"%12.7f ",p[jk]);
1.319     brouard  13167:            fprintf(fichtm, "<td>%12.7f</td>",p[jk]);
1.225     brouard  13168:            jk++; 
                   13169:          }
                   13170:          printf("\n");
                   13171:          fprintf(ficlog,"\n");
                   13172:          fprintf(ficres,"\n");
1.319     brouard  13173:          fprintf(fichtm, "</tr>\n");
1.225     brouard  13174:        }
1.126     brouard  13175:       }
                   13176:     }
1.319     brouard  13177:     /* fprintf(fichtm,"</tr>\n"); */
                   13178:     fprintf(fichtm,"</table>\n");
                   13179:     fprintf(fichtm, "\n");
                   13180: 
1.203     brouard  13181:     if(mle != 0){
                   13182:       /* Computing hessian and covariance matrix only at a peak of the Likelihood, that is after optimization */
1.126     brouard  13183:       ftolhess=ftol; /* Usually correct */
1.203     brouard  13184:       hesscov(matcov, hess, p, npar, delti, ftolhess, func);
                   13185:       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");
                   13186:       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  13187:       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  13188:       fprintf(fichtm,"\n<table style=\"text-align:center; border: 1px solid\">");
                   13189:       fprintf(fichtm, "\n<tr><th>Model=</th><th>1</th><th>+ age</th>");
                   13190:       if(nagesqr==1){
                   13191:        printf("  + age*age  ");
                   13192:        fprintf(ficres,"  + age*age  ");
                   13193:        fprintf(ficlog,"  + age*age  ");
                   13194:        fprintf(fichtm, "<th>+ age*age</th>");
                   13195:       }
                   13196:       for(j=1;j <=ncovmodel-2;j++){
                   13197:        if(Typevar[j]==0) {
                   13198:          printf("  +      V%d  ",Tvar[j]);
                   13199:          fprintf(fichtm, "<th>+ V%d</th>",Tvar[j]);
                   13200:        }else if(Typevar[j]==1) {
                   13201:          printf("  +    V%d*age ",Tvar[j]);
                   13202:          fprintf(fichtm, "<th>+  V%d*age</th>",Tvar[j]);
                   13203:        }else if(Typevar[j]==2) {
                   13204:          fprintf(fichtm, "<th>+  V%d*V%d</th>",Tvard[Tposprod[j]][1],Tvard[Tposprod[j]][2]);
                   13205:        }
                   13206:       }
                   13207:       fprintf(fichtm, "</tr>\n");
                   13208:  
1.203     brouard  13209:       for(i=1,jk=1; i <=nlstate; i++){
1.225     brouard  13210:        for(k=1; k <=(nlstate+ndeath); k++){
                   13211:          if (k != i) {
1.319     brouard  13212:            fprintf(fichtm, "<tr valign=top>");
1.225     brouard  13213:            printf("%d%d ",i,k);
                   13214:            fprintf(ficlog,"%d%d ",i,k);
1.319     brouard  13215:            fprintf(fichtm, "<td>%1d%1d</td>",i,k);
1.225     brouard  13216:            for(j=1; j <=ncovmodel; j++){
1.319     brouard  13217:              wald=p[jk]/sqrt(matcov[jk][jk]);
1.324     brouard  13218:              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]));
                   13219:              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  13220:              if(fabs(wald) > 1.96){
1.321     brouard  13221:                fprintf(fichtm, "<td><b>%12.7f</b></br> (%12.7f)</br>",p[jk],sqrt(matcov[jk][jk]));
1.319     brouard  13222:              }else{
                   13223:                fprintf(fichtm, "<td>%12.7f (%12.7f)</br>",p[jk],sqrt(matcov[jk][jk]));
                   13224:              }
1.324     brouard  13225:              fprintf(fichtm,"W=%8.3f</br>",wald);
1.319     brouard  13226:              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  13227:              jk++; 
                   13228:            }
                   13229:            printf("\n");
                   13230:            fprintf(ficlog,"\n");
1.319     brouard  13231:            fprintf(fichtm, "</tr>\n");
1.225     brouard  13232:          }
                   13233:        }
1.193     brouard  13234:       }
1.203     brouard  13235:     } /* end of hesscov and Wald tests */
1.319     brouard  13236:     fprintf(fichtm,"</table>\n");
1.225     brouard  13237:     
1.203     brouard  13238:     /*  */
1.126     brouard  13239:     fprintf(ficres,"# Scales (for hessian or gradient estimation)\n");
                   13240:     printf("# Scales (for hessian or gradient estimation)\n");
                   13241:     fprintf(ficlog,"# Scales (for hessian or gradient estimation)\n");
                   13242:     for(i=1,jk=1; i <=nlstate; i++){
                   13243:       for(j=1; j <=nlstate+ndeath; j++){
1.225     brouard  13244:        if (j!=i) {
                   13245:          fprintf(ficres,"%1d%1d",i,j);
                   13246:          printf("%1d%1d",i,j);
                   13247:          fprintf(ficlog,"%1d%1d",i,j);
                   13248:          for(k=1; k<=ncovmodel;k++){
                   13249:            printf(" %.5e",delti[jk]);
                   13250:            fprintf(ficlog," %.5e",delti[jk]);
                   13251:            fprintf(ficres," %.5e",delti[jk]);
                   13252:            jk++;
                   13253:          }
                   13254:          printf("\n");
                   13255:          fprintf(ficlog,"\n");
                   13256:          fprintf(ficres,"\n");
                   13257:        }
1.126     brouard  13258:       }
                   13259:     }
                   13260:     
                   13261:     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  13262:     if(mle >= 1) /* To big for the screen */
1.126     brouard  13263:       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");
                   13264:     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");
                   13265:     /* # 121 Var(a12)\n\ */
                   13266:     /* # 122 Cov(b12,a12) Var(b12)\n\ */
                   13267:     /* # 131 Cov(a13,a12) Cov(a13,b12, Var(a13)\n\ */
                   13268:     /* # 132 Cov(b13,a12) Cov(b13,b12, Cov(b13,a13) Var(b13)\n\ */
                   13269:     /* # 212 Cov(a21,a12) Cov(a21,b12, Cov(a21,a13) Cov(a21,b13) Var(a21)\n\ */
                   13270:     /* # 212 Cov(b21,a12) Cov(b21,b12, Cov(b21,a13) Cov(b21,b13) Cov(b21,a21) Var(b21)\n\ */
                   13271:     /* # 232 Cov(a23,a12) Cov(a23,b12, Cov(a23,a13) Cov(a23,b13) Cov(a23,a21) Cov(a23,b21) Var(a23)\n\ */
                   13272:     /* # 232 Cov(b23,a12) Cov(b23,b12) ... Var (b23)\n" */
                   13273:     
                   13274:     
                   13275:     /* Just to have a covariance matrix which will be more understandable
                   13276:        even is we still don't want to manage dictionary of variables
                   13277:     */
                   13278:     for(itimes=1;itimes<=2;itimes++){
                   13279:       jj=0;
                   13280:       for(i=1; i <=nlstate; i++){
1.225     brouard  13281:        for(j=1; j <=nlstate+ndeath; j++){
                   13282:          if(j==i) continue;
                   13283:          for(k=1; k<=ncovmodel;k++){
                   13284:            jj++;
                   13285:            ca[0]= k+'a'-1;ca[1]='\0';
                   13286:            if(itimes==1){
                   13287:              if(mle>=1)
                   13288:                printf("#%1d%1d%d",i,j,k);
                   13289:              fprintf(ficlog,"#%1d%1d%d",i,j,k);
                   13290:              fprintf(ficres,"#%1d%1d%d",i,j,k);
                   13291:            }else{
                   13292:              if(mle>=1)
                   13293:                printf("%1d%1d%d",i,j,k);
                   13294:              fprintf(ficlog,"%1d%1d%d",i,j,k);
                   13295:              fprintf(ficres,"%1d%1d%d",i,j,k);
                   13296:            }
                   13297:            ll=0;
                   13298:            for(li=1;li <=nlstate; li++){
                   13299:              for(lj=1;lj <=nlstate+ndeath; lj++){
                   13300:                if(lj==li) continue;
                   13301:                for(lk=1;lk<=ncovmodel;lk++){
                   13302:                  ll++;
                   13303:                  if(ll<=jj){
                   13304:                    cb[0]= lk +'a'-1;cb[1]='\0';
                   13305:                    if(ll<jj){
                   13306:                      if(itimes==1){
                   13307:                        if(mle>=1)
                   13308:                          printf(" Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
                   13309:                        fprintf(ficlog," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
                   13310:                        fprintf(ficres," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
                   13311:                      }else{
                   13312:                        if(mle>=1)
                   13313:                          printf(" %.5e",matcov[jj][ll]); 
                   13314:                        fprintf(ficlog," %.5e",matcov[jj][ll]); 
                   13315:                        fprintf(ficres," %.5e",matcov[jj][ll]); 
                   13316:                      }
                   13317:                    }else{
                   13318:                      if(itimes==1){
                   13319:                        if(mle>=1)
                   13320:                          printf(" Var(%s%1d%1d)",ca,i,j);
                   13321:                        fprintf(ficlog," Var(%s%1d%1d)",ca,i,j);
                   13322:                        fprintf(ficres," Var(%s%1d%1d)",ca,i,j);
                   13323:                      }else{
                   13324:                        if(mle>=1)
                   13325:                          printf(" %.7e",matcov[jj][ll]); 
                   13326:                        fprintf(ficlog," %.7e",matcov[jj][ll]); 
                   13327:                        fprintf(ficres," %.7e",matcov[jj][ll]); 
                   13328:                      }
                   13329:                    }
                   13330:                  }
                   13331:                } /* end lk */
                   13332:              } /* end lj */
                   13333:            } /* end li */
                   13334:            if(mle>=1)
                   13335:              printf("\n");
                   13336:            fprintf(ficlog,"\n");
                   13337:            fprintf(ficres,"\n");
                   13338:            numlinepar++;
                   13339:          } /* end k*/
                   13340:        } /*end j */
1.126     brouard  13341:       } /* end i */
                   13342:     } /* end itimes */
                   13343:     
                   13344:     fflush(ficlog);
                   13345:     fflush(ficres);
1.225     brouard  13346:     while(fgets(line, MAXLINE, ficpar)) {
                   13347:       /* If line starts with a # it is a comment */
                   13348:       if (line[0] == '#') {
                   13349:        numlinepar++;
                   13350:        fputs(line,stdout);
                   13351:        fputs(line,ficparo);
                   13352:        fputs(line,ficlog);
1.299     brouard  13353:        fputs(line,ficres);
1.225     brouard  13354:        continue;
                   13355:       }else
                   13356:        break;
                   13357:     }
                   13358:     
1.209     brouard  13359:     /* while((c=getc(ficpar))=='#' && c!= EOF){ */
                   13360:     /*   ungetc(c,ficpar); */
                   13361:     /*   fgets(line, MAXLINE, ficpar); */
                   13362:     /*   fputs(line,stdout); */
                   13363:     /*   fputs(line,ficparo); */
                   13364:     /* } */
                   13365:     /* ungetc(c,ficpar); */
1.126     brouard  13366:     
                   13367:     estepm=0;
1.209     brouard  13368:     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  13369:       
                   13370:       if (num_filled != 6) {
                   13371:        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);
                   13372:        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);
                   13373:        goto end;
                   13374:       }
                   13375:       printf("agemin=%lf agemax=%lf bage=%lf fage=%lf estepm=%d ftolpl=%lf\n",ageminpar,agemaxpar, bage, fage, estepm, ftolpl);
                   13376:     }
                   13377:     /* ftolpl=6*ftol*1.e5; /\* 6.e-3 make convergences in less than 80 loops for the prevalence limit *\/ */
                   13378:     /*ftolpl=6.e-4;*/ /* 6.e-3 make convergences in less than 80 loops for the prevalence limit */
                   13379:     
1.209     brouard  13380:     /* fscanf(ficpar,"agemin=%lf agemax=%lf bage=%lf fage=%lf estepm=%d ftolpl=%\n",&ageminpar,&agemaxpar, &bage, &fage, &estepm); */
1.126     brouard  13381:     if (estepm==0 || estepm < stepm) estepm=stepm;
                   13382:     if (fage <= 2) {
                   13383:       bage = ageminpar;
                   13384:       fage = agemaxpar;
                   13385:     }
                   13386:     
                   13387:     fprintf(ficres,"# agemin agemax for life expectancy, bage fage (if mle==0 ie no data nor Max likelihood).\n");
1.211     brouard  13388:     fprintf(ficres,"agemin=%.0f agemax=%.0f bage=%.0f fage=%.0f estepm=%d ftolpl=%e\n",ageminpar,agemaxpar,bage,fage, estepm, ftolpl);
                   13389:     fprintf(ficparo,"agemin=%.0f agemax=%.0f bage=%.0f fage=%.0f estepm=%d, ftolpl=%e\n",ageminpar,agemaxpar,bage,fage, estepm, ftolpl);
1.220     brouard  13390:                
1.186     brouard  13391:     /* Other stuffs, more or less useful */    
1.254     brouard  13392:     while(fgets(line, MAXLINE, ficpar)) {
                   13393:       /* If line starts with a # it is a comment */
                   13394:       if (line[0] == '#') {
                   13395:        numlinepar++;
                   13396:        fputs(line,stdout);
                   13397:        fputs(line,ficparo);
                   13398:        fputs(line,ficlog);
1.299     brouard  13399:        fputs(line,ficres);
1.254     brouard  13400:        continue;
                   13401:       }else
                   13402:        break;
                   13403:     }
                   13404: 
                   13405:     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){
                   13406:       
                   13407:       if (num_filled != 7) {
                   13408:        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);
                   13409:        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);
                   13410:        goto end;
                   13411:       }
                   13412:       printf("begin-prev-date=%.lf/%.lf/%.lf end-prev-date=%.lf/%.lf/%.lf mov_average=%d\n",jprev1, mprev1,anprev1,jprev2, mprev2,anprev2,mobilav);
                   13413:       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);
                   13414:       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);
                   13415:       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  13416:     }
1.254     brouard  13417: 
                   13418:     while(fgets(line, MAXLINE, ficpar)) {
                   13419:       /* If line starts with a # it is a comment */
                   13420:       if (line[0] == '#') {
                   13421:        numlinepar++;
                   13422:        fputs(line,stdout);
                   13423:        fputs(line,ficparo);
                   13424:        fputs(line,ficlog);
1.299     brouard  13425:        fputs(line,ficres);
1.254     brouard  13426:        continue;
                   13427:       }else
                   13428:        break;
1.126     brouard  13429:     }
                   13430:     
                   13431:     
                   13432:     dateprev1=anprev1+(mprev1-1)/12.+(jprev1-1)/365.;
                   13433:     dateprev2=anprev2+(mprev2-1)/12.+(jprev2-1)/365.;
                   13434:     
1.254     brouard  13435:     if((num_filled=sscanf(line,"pop_based=%d\n",&popbased)) !=EOF){
                   13436:       if (num_filled != 1) {
                   13437:        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);
                   13438:        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);
                   13439:        goto end;
                   13440:       }
                   13441:       printf("pop_based=%d\n",popbased);
                   13442:       fprintf(ficlog,"pop_based=%d\n",popbased);
                   13443:       fprintf(ficparo,"pop_based=%d\n",popbased);   
                   13444:       fprintf(ficres,"pop_based=%d\n",popbased);   
                   13445:     }
                   13446:      
1.258     brouard  13447:     /* Results */
1.332     brouard  13448:     /* Value of covariate in each resultine will be compututed (if product) and sorted according to model rank */
                   13449:     /* It is precov[] because we need the varying age in order to compute the real cov[] of the model equation */  
                   13450:     precov=matrix(1,MAXRESULTLINESPONE,1,NCOVMAX+1);
1.307     brouard  13451:     endishere=0;
1.258     brouard  13452:     nresult=0;
1.308     brouard  13453:     parameterline=0;
1.258     brouard  13454:     do{
                   13455:       if(!fgets(line, MAXLINE, ficpar)){
                   13456:        endishere=1;
1.308     brouard  13457:        parameterline=15;
1.258     brouard  13458:       }else if (line[0] == '#') {
                   13459:        /* If line starts with a # it is a comment */
1.254     brouard  13460:        numlinepar++;
                   13461:        fputs(line,stdout);
                   13462:        fputs(line,ficparo);
                   13463:        fputs(line,ficlog);
1.299     brouard  13464:        fputs(line,ficres);
1.254     brouard  13465:        continue;
1.258     brouard  13466:       }else if(sscanf(line,"prevforecast=%[^\n]\n",modeltemp))
                   13467:        parameterline=11;
1.296     brouard  13468:       else if(sscanf(line,"prevbackcast=%[^\n]\n",modeltemp))
1.258     brouard  13469:        parameterline=12;
1.307     brouard  13470:       else if(sscanf(line,"result:%[^\n]\n",modeltemp)){
1.258     brouard  13471:        parameterline=13;
1.307     brouard  13472:       }
1.258     brouard  13473:       else{
                   13474:        parameterline=14;
1.254     brouard  13475:       }
1.308     brouard  13476:       switch (parameterline){ /* =0 only if only comments */
1.258     brouard  13477:       case 11:
1.296     brouard  13478:        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)){
                   13479:                  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  13480:          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);
                   13481:          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);
                   13482:          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);
                   13483:          /* day and month of proj2 are not used but only year anproj2.*/
1.273     brouard  13484:          dateproj1=anproj1+(mproj1-1)/12.+(jproj1-1)/365.;
                   13485:          dateproj2=anproj2+(mproj2-1)/12.+(jproj2-1)/365.;
1.296     brouard  13486:           prvforecast = 1;
                   13487:        } 
                   13488:        else if((num_filled=sscanf(line,"prevforecast=%d yearsfproj=%lf mobil_average=%d\n",&prevfcast,&yrfproj,&mobilavproj)) !=EOF){/* && (num_filled == 3))*/
1.313     brouard  13489:          printf("prevforecast=%d yearsfproj=%.2lf mobil_average=%d\n",prevfcast,yrfproj,mobilavproj);
                   13490:          fprintf(ficlog,"prevforecast=%d yearsfproj=%.2lf mobil_average=%d\n",prevfcast,yrfproj,mobilavproj);
                   13491:          fprintf(ficres,"prevforecast=%d yearsfproj=%.2lf mobil_average=%d\n",prevfcast,yrfproj,mobilavproj);
1.296     brouard  13492:           prvforecast = 2;
                   13493:        }
                   13494:        else {
                   13495:          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);
                   13496:          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);
                   13497:          goto end;
1.258     brouard  13498:        }
1.254     brouard  13499:        break;
1.258     brouard  13500:       case 12:
1.296     brouard  13501:        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)){
                   13502:           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);
                   13503:          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);
                   13504:          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);
                   13505:          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);
                   13506:          /* day and month of back2 are not used but only year anback2.*/
1.273     brouard  13507:          dateback1=anback1+(mback1-1)/12.+(jback1-1)/365.;
                   13508:          dateback2=anback2+(mback2-1)/12.+(jback2-1)/365.;
1.296     brouard  13509:           prvbackcast = 1;
                   13510:        } 
                   13511:        else if((num_filled=sscanf(line,"prevbackcast=%d yearsbproj=%lf mobil_average=%d\n",&prevbcast,&yrbproj,&mobilavproj)) ==3){/* && (num_filled == 3))*/
1.313     brouard  13512:          printf("prevbackcast=%d yearsbproj=%.2lf mobil_average=%d\n",prevbcast,yrbproj,mobilavproj);
                   13513:          fprintf(ficlog,"prevbackcast=%d yearsbproj=%.2lf mobil_average=%d\n",prevbcast,yrbproj,mobilavproj);
                   13514:          fprintf(ficres,"prevbackcast=%d yearsbproj=%.2lf mobil_average=%d\n",prevbcast,yrbproj,mobilavproj);
1.296     brouard  13515:           prvbackcast = 2;
                   13516:        }
                   13517:        else {
                   13518:          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);
                   13519:          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);
                   13520:          goto end;
1.258     brouard  13521:        }
1.230     brouard  13522:        break;
1.258     brouard  13523:       case 13:
1.332     brouard  13524:        num_filled=sscanf(line,"result:%[^\n]\n",resultlineori);
1.307     brouard  13525:        nresult++; /* Sum of resultlines */
1.332     brouard  13526:        printf("Result %d: result:%s\n",nresult, resultlineori);
                   13527:        /* removefirstspace(&resultlineori); */
                   13528:        
                   13529:        if(strstr(resultlineori,"v") !=0){
                   13530:          printf("Error. 'v' must be in upper case 'V' result: %s ",resultlineori);
                   13531:          fprintf(ficlog,"Error. 'v' must be in upper case result: %s ",resultlineori);fflush(ficlog);
                   13532:          return 1;
                   13533:        }
                   13534:        trimbb(resultline, resultlineori); /* Suppressing double blank in the resultline */
                   13535:        printf("Decoderesult resultline=\"%s\" resultlineori=\"%s\"\n", resultline, resultlineori);
1.318     brouard  13536:        if(nresult > MAXRESULTLINESPONE-1){
                   13537:          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);
                   13538:          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  13539:          goto end;
                   13540:        }
1.332     brouard  13541:        
1.310     brouard  13542:        if(!decoderesult(resultline, nresult)){ /* Fills TKresult[nresult] combination and Tresult[nresult][k4+1] combination values */
1.314     brouard  13543:          fprintf(ficparo,"result: %s\n",resultline);
                   13544:          fprintf(ficres,"result: %s\n",resultline);
                   13545:          fprintf(ficlog,"result: %s\n",resultline);
1.310     brouard  13546:        } else
                   13547:          goto end;
1.307     brouard  13548:        break;
                   13549:       case 14:
                   13550:        printf("Error: Unknown command '%s'\n",line);
                   13551:        fprintf(ficlog,"Error: Unknown command '%s'\n",line);
1.314     brouard  13552:        if(line[0] == ' ' || line[0] == '\n'){
                   13553:          printf("It should not be an empty line '%s'\n",line);
                   13554:          fprintf(ficlog,"It should not be an empty line '%s'\n",line);
                   13555:        }         
1.307     brouard  13556:        if(ncovmodel >=2 && nresult==0 ){
                   13557:          printf("ERROR: no result lines! It should be at minimum 'result: V2=0 V1=1 or result:.' %s\n",line);
                   13558:          fprintf(ficlog,"ERROR: no result lines! It should be at minimum 'result: V2=0 V1=1 or result:.' %s\n",line);
1.258     brouard  13559:        }
1.307     brouard  13560:        /* goto end; */
                   13561:        break;
1.308     brouard  13562:       case 15:
                   13563:        printf("End of resultlines.\n");
                   13564:        fprintf(ficlog,"End of resultlines.\n");
                   13565:        break;
                   13566:       default: /* parameterline =0 */
1.307     brouard  13567:        nresult=1;
                   13568:        decoderesult(".",nresult ); /* No covariate */
1.258     brouard  13569:       } /* End switch parameterline */
                   13570:     }while(endishere==0); /* End do */
1.126     brouard  13571:     
1.230     brouard  13572:     /* freqsummary(fileres, agemin, agemax, s, agev, nlstate, imx,Tvaraff,nbcode, ncodemax,mint,anint); */
1.145     brouard  13573:     /* ,dateprev1,dateprev2,jprev1, mprev1,anprev1,jprev2, mprev2,anprev2); */
1.126     brouard  13574:     
                   13575:     replace_back_to_slash(pathc,pathcd); /* Even gnuplot wants a / */
1.194     brouard  13576:     if(ageminpar == AGEOVERFLOW ||agemaxpar == -AGEOVERFLOW){
1.230     brouard  13577:       printf("Warning! Error in gnuplot file with ageminpar %f or agemaxpar %f overflow\n\
1.194     brouard  13578: This is probably because your parameter file doesn't \n  contain the exact number of lines (or columns) corresponding to your model line.\n\
                   13579: Please run with mle=-1 to get a correct covariance matrix.\n",ageminpar,agemaxpar);
1.230     brouard  13580:       fprintf(ficlog,"Warning! Error in gnuplot file with ageminpar %f or agemaxpar %f overflow\n\
1.194     brouard  13581: This is probably because your parameter file doesn't \n  contain the exact number of lines (or columns) corresponding to your model line.\n\
                   13582: Please run with mle=-1 to get a correct covariance matrix.\n",ageminpar,agemaxpar);
1.220     brouard  13583:     }else{
1.270     brouard  13584:       /* printinggnuplot(fileresu, optionfilefiname,ageminpar,agemaxpar,fage, prevfcast, backcast, pathc,p, (int)anproj1-(int)agemin, (int)anback1-(int)agemax+1); */
1.296     brouard  13585:       /* It seems that anprojd which is computed from the mean year at interview which is known yet because of freqsummary */
                   13586:       /* date2dmy(dateintmean,&jintmean,&mintmean,&aintmean); */ /* Done in freqsummary */
                   13587:       if(prvforecast==1){
                   13588:         dateprojd=(jproj1+12*mproj1+365*anproj1)/365;
                   13589:         jprojd=jproj1;
                   13590:         mprojd=mproj1;
                   13591:         anprojd=anproj1;
                   13592:         dateprojf=(jproj2+12*mproj2+365*anproj2)/365;
                   13593:         jprojf=jproj2;
                   13594:         mprojf=mproj2;
                   13595:         anprojf=anproj2;
                   13596:       } else if(prvforecast == 2){
                   13597:         dateprojd=dateintmean;
                   13598:         date2dmy(dateprojd,&jprojd, &mprojd, &anprojd);
                   13599:         dateprojf=dateintmean+yrfproj;
                   13600:         date2dmy(dateprojf,&jprojf, &mprojf, &anprojf);
                   13601:       }
                   13602:       if(prvbackcast==1){
                   13603:         datebackd=(jback1+12*mback1+365*anback1)/365;
                   13604:         jbackd=jback1;
                   13605:         mbackd=mback1;
                   13606:         anbackd=anback1;
                   13607:         datebackf=(jback2+12*mback2+365*anback2)/365;
                   13608:         jbackf=jback2;
                   13609:         mbackf=mback2;
                   13610:         anbackf=anback2;
                   13611:       } else if(prvbackcast == 2){
                   13612:         datebackd=dateintmean;
                   13613:         date2dmy(datebackd,&jbackd, &mbackd, &anbackd);
                   13614:         datebackf=dateintmean-yrbproj;
                   13615:         date2dmy(datebackf,&jbackf, &mbackf, &anbackf);
                   13616:       }
                   13617:       
                   13618:       printinggnuplot(fileresu, optionfilefiname,ageminpar,agemaxpar,bage, fage, prevfcast, prevbcast, pathc,p, (int)anprojd-bage, (int)anbackd-fage);
1.220     brouard  13619:     }
                   13620:     printinghtml(fileresu,title,datafile, firstpass, lastpass, stepm, weightopt, \
1.296     brouard  13621:                 model,imx,jmin,jmax,jmean,rfileres,popforecast,mobilav,prevfcast,mobilavproj,prevbcast, estepm, \
                   13622:                 jprev1,mprev1,anprev1,dateprev1, dateprojd, datebackd,jprev2,mprev2,anprev2,dateprev2,dateprojf, datebackf);
1.220     brouard  13623:                
1.225     brouard  13624:     /*------------ free_vector  -------------*/
                   13625:     /*  chdir(path); */
1.220     brouard  13626:                
1.215     brouard  13627:     /* free_ivector(wav,1,imx); */  /* Moved after last prevalence call */
                   13628:     /* free_imatrix(dh,1,lastpass-firstpass+2,1,imx); */
                   13629:     /* free_imatrix(bh,1,lastpass-firstpass+2,1,imx); */
                   13630:     /* free_imatrix(mw,1,lastpass-firstpass+2,1,imx);    */
1.290     brouard  13631:     free_lvector(num,firstobs,lastobs);
                   13632:     free_vector(agedc,firstobs,lastobs);
1.126     brouard  13633:     /*free_matrix(covar,0,NCOVMAX,1,n);*/
                   13634:     /*free_matrix(covar,1,NCOVMAX,1,n);*/
                   13635:     fclose(ficparo);
                   13636:     fclose(ficres);
1.220     brouard  13637:                
                   13638:                
1.186     brouard  13639:     /* Other results (useful)*/
1.220     brouard  13640:                
                   13641:                
1.126     brouard  13642:     /*--------------- Prevalence limit  (period or stable prevalence) --------------*/
1.180     brouard  13643:     /*#include "prevlim.h"*/  /* Use ficrespl, ficlog */
                   13644:     prlim=matrix(1,nlstate,1,nlstate);
1.332     brouard  13645:     /* Computes the prevalence limit for each combination k of the dummy covariates by calling prevalim(k) */
1.209     brouard  13646:     prevalence_limit(p, prlim,  ageminpar, agemaxpar, ftolpl, &ncvyear);
1.126     brouard  13647:     fclose(ficrespl);
                   13648: 
                   13649:     /*------------- h Pij x at various ages ------------*/
1.180     brouard  13650:     /*#include "hpijx.h"*/
1.332     brouard  13651:     /** h Pij x Probability to be in state j at age x+h being in i at x, for each combination k of dummies in the model line or to nres?*/
                   13652:     /* calls hpxij with combination k */
1.180     brouard  13653:     hPijx(p, bage, fage);
1.145     brouard  13654:     fclose(ficrespij);
1.227     brouard  13655:     
1.220     brouard  13656:     /* ncovcombmax=  pow(2,cptcoveff); */
1.332     brouard  13657:     /*-------------- Variance of one-step probabilities for a combination ij or for nres ?---*/
1.145     brouard  13658:     k=1;
1.126     brouard  13659:     varprob(optionfilefiname, matcov, p, delti, nlstate, bage, fage,k,Tvar,nbcode, ncodemax,strstart);
1.227     brouard  13660:     
1.269     brouard  13661:     /* Prevalence for each covariate combination in probs[age][status][cov] */
                   13662:     probs= ma3x(AGEINF,AGESUP,1,nlstate+ndeath, 1,ncovcombmax);
                   13663:     for(i=AGEINF;i<=AGESUP;i++)
1.219     brouard  13664:       for(j=1;j<=nlstate+ndeath;j++) /* ndeath is useless but a necessity to be compared with mobaverages */
1.225     brouard  13665:        for(k=1;k<=ncovcombmax;k++)
                   13666:          probs[i][j][k]=0.;
1.269     brouard  13667:     prevalence(probs, ageminpar, agemaxpar, s, agev, nlstate, imx, Tvar, nbcode, 
                   13668:               ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass);
1.219     brouard  13669:     if (mobilav!=0 ||mobilavproj !=0 ) {
1.269     brouard  13670:       mobaverages= ma3x(AGEINF, AGESUP,1,nlstate+ndeath, 1,ncovcombmax);
                   13671:       for(i=AGEINF;i<=AGESUP;i++)
1.268     brouard  13672:        for(j=1;j<=nlstate+ndeath;j++)
1.227     brouard  13673:          for(k=1;k<=ncovcombmax;k++)
                   13674:            mobaverages[i][j][k]=0.;
1.219     brouard  13675:       mobaverage=mobaverages;
                   13676:       if (mobilav!=0) {
1.235     brouard  13677:        printf("Movingaveraging observed prevalence\n");
1.258     brouard  13678:        fprintf(ficlog,"Movingaveraging observed prevalence\n");
1.227     brouard  13679:        if (movingaverage(probs, ageminpar, agemaxpar, mobaverage, mobilav)!=0){
                   13680:          fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);
                   13681:          printf(" Error in movingaverage mobilav=%d\n",mobilav);
                   13682:        }
1.269     brouard  13683:       } else if (mobilavproj !=0) {
1.235     brouard  13684:        printf("Movingaveraging projected observed prevalence\n");
1.258     brouard  13685:        fprintf(ficlog,"Movingaveraging projected observed prevalence\n");
1.227     brouard  13686:        if (movingaverage(probs, ageminpar, agemaxpar, mobaverage, mobilavproj)!=0){
                   13687:          fprintf(ficlog," Error in movingaverage mobilavproj=%d\n",mobilavproj);
                   13688:          printf(" Error in movingaverage mobilavproj=%d\n",mobilavproj);
                   13689:        }
1.269     brouard  13690:       }else{
                   13691:        printf("Internal error moving average\n");
                   13692:        fflush(stdout);
                   13693:        exit(1);
1.219     brouard  13694:       }
                   13695:     }/* end if moving average */
1.227     brouard  13696:     
1.126     brouard  13697:     /*---------- Forecasting ------------------*/
1.296     brouard  13698:     if(prevfcast==1){ 
                   13699:       /*   /\*    if(stepm ==1){*\/ */
                   13700:       /*   /\*  anproj1, mproj1, jproj1 either read explicitly or yrfproj *\/ */
                   13701:       /*This done previously after freqsummary.*/
                   13702:       /*   dateprojd=(jproj1+12*mproj1+365*anproj1)/365; */
                   13703:       /*   dateprojf=(jproj2+12*mproj2+365*anproj2)/365; */
                   13704:       
                   13705:       /* } else if (prvforecast==2){ */
                   13706:       /*   /\*    if(stepm ==1){*\/ */
                   13707:       /*   /\*  anproj1, mproj1, jproj1 either read explicitly or yrfproj *\/ */
                   13708:       /* } */
                   13709:       /*prevforecast(fileresu, dateintmean, anproj1, mproj1, jproj1, agemin, agemax, dateprev1, dateprev2, mobilavproj, mobaverage, bage, fage, firstpass, lastpass, anproj2, p, cptcoveff);*/
                   13710:       prevforecast(fileresu,dateintmean, dateprojd, dateprojf, agemin, agemax, dateprev1, dateprev2, mobilavproj, mobaverage, bage, fage, firstpass, lastpass, p, cptcoveff);
1.126     brouard  13711:     }
1.269     brouard  13712: 
1.296     brouard  13713:     /* Prevbcasting */
                   13714:     if(prevbcast==1){
1.219     brouard  13715:       ddnewms=matrix(1,nlstate+ndeath,1,nlstate+ndeath);       
                   13716:       ddoldms=matrix(1,nlstate+ndeath,1,nlstate+ndeath);       
                   13717:       ddsavms=matrix(1,nlstate+ndeath,1,nlstate+ndeath);
                   13718: 
                   13719:       /*--------------- Back Prevalence limit  (period or stable prevalence) --------------*/
                   13720: 
                   13721:       bprlim=matrix(1,nlstate,1,nlstate);
1.269     brouard  13722: 
1.219     brouard  13723:       back_prevalence_limit(p, bprlim,  ageminpar, agemaxpar, ftolpl, &ncvyear, dateprev1, dateprev2, firstpass, lastpass, mobilavproj);
                   13724:       fclose(ficresplb);
                   13725: 
1.222     brouard  13726:       hBijx(p, bage, fage, mobaverage);
                   13727:       fclose(ficrespijb);
1.219     brouard  13728: 
1.296     brouard  13729:       /* /\* prevbackforecast(fileresu, mobaverage, anback1, mback1, jback1, agemin, agemax, dateprev1, dateprev2, *\/ */
                   13730:       /* /\*                  mobilavproj, bage, fage, firstpass, lastpass, anback2, p, cptcoveff); *\/ */
                   13731:       /* prevbackforecast(fileresu, mobaverage, anback1, mback1, jback1, agemin, agemax, dateprev1, dateprev2, */
                   13732:       /*                      mobilavproj, bage, fage, firstpass, lastpass, anback2, p, cptcoveff); */
                   13733:       prevbackforecast(fileresu, mobaverage, dateintmean, dateprojd, dateprojf, agemin, agemax, dateprev1, dateprev2,
                   13734:                       mobilavproj, bage, fage, firstpass, lastpass, p, cptcoveff);
                   13735: 
                   13736:       
1.269     brouard  13737:       varbprlim(fileresu, nresult, mobaverage, mobilavproj, bage, fage, bprlim, &ncvyear, ftolpl, p, matcov, delti, stepm, cptcoveff);
1.268     brouard  13738: 
                   13739:       
1.269     brouard  13740:       free_matrix(bprlim,1,nlstate,1,nlstate); /*here or after loop ? */
1.219     brouard  13741:       free_matrix(ddnewms, 1, nlstate+ndeath, 1, nlstate+ndeath);
                   13742:       free_matrix(ddsavms, 1, nlstate+ndeath, 1, nlstate+ndeath);
                   13743:       free_matrix(ddoldms, 1, nlstate+ndeath, 1, nlstate+ndeath);
1.296     brouard  13744:     }    /* end  Prevbcasting */
1.268     brouard  13745:  
1.186     brouard  13746:  
                   13747:     /* ------ Other prevalence ratios------------ */
1.126     brouard  13748: 
1.215     brouard  13749:     free_ivector(wav,1,imx);
                   13750:     free_imatrix(dh,1,lastpass-firstpass+2,1,imx);
                   13751:     free_imatrix(bh,1,lastpass-firstpass+2,1,imx);
                   13752:     free_imatrix(mw,1,lastpass-firstpass+2,1,imx);   
1.218     brouard  13753:                
                   13754:                
1.127     brouard  13755:     /*---------- Health expectancies, no variances ------------*/
1.218     brouard  13756:                
1.201     brouard  13757:     strcpy(filerese,"E_");
                   13758:     strcat(filerese,fileresu);
1.126     brouard  13759:     if((ficreseij=fopen(filerese,"w"))==NULL) {
                   13760:       printf("Problem with Health Exp. resultfile: %s\n", filerese); exit(0);
                   13761:       fprintf(ficlog,"Problem with Health Exp. resultfile: %s\n", filerese); exit(0);
                   13762:     }
1.208     brouard  13763:     printf("Computing Health Expectancies: result on file '%s' ...", filerese);fflush(stdout);
                   13764:     fprintf(ficlog,"Computing Health Expectancies: result on file '%s' ...", filerese);fflush(ficlog);
1.238     brouard  13765: 
                   13766:     pstamp(ficreseij);
1.219     brouard  13767:                
1.235     brouard  13768:     i1=pow(2,cptcoveff); /* Number of combination of dummy covariates */
                   13769:     if (cptcovn < 1){i1=1;}
                   13770:     
                   13771:     for(nres=1; nres <= nresult; nres++) /* For each resultline */
                   13772:     for(k=1; k<=i1;k++){ /* For any combination of dummy covariates, fixed and varying */
1.253     brouard  13773:       if(i1 != 1 && TKresult[nres]!= k)
1.235     brouard  13774:        continue;
1.219     brouard  13775:       fprintf(ficreseij,"\n#****** ");
1.235     brouard  13776:       printf("\n#****** ");
1.225     brouard  13777:       for(j=1;j<=cptcoveff;j++) {
1.332     brouard  13778:        fprintf(ficreseij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]);
                   13779:        printf("V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]);
1.235     brouard  13780:       }
                   13781:       for (j=1; j<= nsq; j++){ /* For each selected (single) quantitative value */
1.334     brouard  13782:        printf(" V%d=%f ",TvarsQ[j], TinvDoQresult[nres][TvarsQ[j]]); /* TvarsQ[j] gives the name of the jth quantitative (fixed or time v) */
                   13783:        fprintf(ficreseij,"V%d=%f ",TvarsQ[j], TinvDoQresult[nres][TvarsQ[j]]);
1.219     brouard  13784:       }
                   13785:       fprintf(ficreseij,"******\n");
1.235     brouard  13786:       printf("******\n");
1.219     brouard  13787:       
                   13788:       eij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
                   13789:       oldm=oldms;savm=savms;
1.330     brouard  13790:       /* 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  13791:       evsij(eij, p, nlstate, stepm, (int) bage, (int)fage, oldm, savm, k, estepm, strstart, nres);  
1.127     brouard  13792:       
1.219     brouard  13793:       free_ma3x(eij,1,nlstate,1,nlstate,(int) bage, (int)fage);
1.127     brouard  13794:     }
                   13795:     fclose(ficreseij);
1.208     brouard  13796:     printf("done evsij\n");fflush(stdout);
                   13797:     fprintf(ficlog,"done evsij\n");fflush(ficlog);
1.269     brouard  13798: 
1.218     brouard  13799:                
1.227     brouard  13800:     /*---------- State-specific expectancies and variances ------------*/
1.336   ! brouard  13801:     /* Should be moved in a function */                
1.201     brouard  13802:     strcpy(filerest,"T_");
                   13803:     strcat(filerest,fileresu);
1.127     brouard  13804:     if((ficrest=fopen(filerest,"w"))==NULL) {
                   13805:       printf("Problem with total LE resultfile: %s\n", filerest);goto end;
                   13806:       fprintf(ficlog,"Problem with total LE resultfile: %s\n", filerest);goto end;
                   13807:     }
1.208     brouard  13808:     printf("Computing Total Life expectancies with their standard errors: file '%s' ...\n", filerest); fflush(stdout);
                   13809:     fprintf(ficlog,"Computing Total Life expectancies with their standard errors: file '%s' ...\n", filerest); fflush(ficlog);
1.201     brouard  13810:     strcpy(fileresstde,"STDE_");
                   13811:     strcat(fileresstde,fileresu);
1.126     brouard  13812:     if((ficresstdeij=fopen(fileresstde,"w"))==NULL) {
1.227     brouard  13813:       printf("Problem with State specific Exp. and std errors resultfile: %s\n", fileresstde); exit(0);
                   13814:       fprintf(ficlog,"Problem with State specific Exp. and std errors resultfile: %s\n", fileresstde); exit(0);
1.126     brouard  13815:     }
1.227     brouard  13816:     printf("  Computing State-specific Expectancies and standard errors: result on file '%s' \n", fileresstde);
                   13817:     fprintf(ficlog,"  Computing State-specific Expectancies and standard errors: result on file '%s' \n", fileresstde);
1.126     brouard  13818: 
1.201     brouard  13819:     strcpy(filerescve,"CVE_");
                   13820:     strcat(filerescve,fileresu);
1.126     brouard  13821:     if((ficrescveij=fopen(filerescve,"w"))==NULL) {
1.227     brouard  13822:       printf("Problem with Covar. State-specific Exp. resultfile: %s\n", filerescve); exit(0);
                   13823:       fprintf(ficlog,"Problem with Covar. State-specific Exp. resultfile: %s\n", filerescve); exit(0);
1.126     brouard  13824:     }
1.227     brouard  13825:     printf("    Computing Covar. of State-specific Expectancies: result on file '%s' \n", filerescve);
                   13826:     fprintf(ficlog,"    Computing Covar. of State-specific Expectancies: result on file '%s' \n", filerescve);
1.126     brouard  13827: 
1.201     brouard  13828:     strcpy(fileresv,"V_");
                   13829:     strcat(fileresv,fileresu);
1.126     brouard  13830:     if((ficresvij=fopen(fileresv,"w"))==NULL) {
                   13831:       printf("Problem with variance resultfile: %s\n", fileresv);exit(0);
                   13832:       fprintf(ficlog,"Problem with variance resultfile: %s\n", fileresv);exit(0);
                   13833:     }
1.227     brouard  13834:     printf("      Computing Variance-covariance of State-specific Expectancies: file '%s' ... ", fileresv);fflush(stdout);
                   13835:     fprintf(ficlog,"      Computing Variance-covariance of State-specific Expectancies: file '%s' ... ", fileresv);fflush(ficlog);
1.126     brouard  13836: 
1.235     brouard  13837:     i1=pow(2,cptcoveff); /* Number of combination of dummy covariates */
                   13838:     if (cptcovn < 1){i1=1;}
                   13839:     
1.334     brouard  13840:     for(nres=1; nres <= nresult; nres++) /* For each resultline, find the combination and output results according to the values of dummies and then quanti.  */
                   13841:     for(k=1; k<=i1;k++){ /* For any combination of dummy covariates, fixed and varying. For each nres and each value at position k
                   13842:                          * we know Tresult[nres][result_position]= value of the dummy variable at the result_position in the nres resultline
                   13843:                          * Tvqresult[nres][result_position]= id of the variable at the result_position in the nres resultline 
                   13844:                          * and Tqresult[nres][result_position]= value of the variable at the result_position in the nres resultline */
                   13845:       /* */
                   13846:       if(i1 != 1 && TKresult[nres]!= k) /* TKresult[nres] is the combination of this nres resultline. All the i1 combinations are not output */
1.235     brouard  13847:        continue;
1.321     brouard  13848:       printf("\n# model %s \n#****** Result for:", model);
                   13849:       fprintf(ficrest,"\n# model %s \n#****** Result for:", model);
                   13850:       fprintf(ficlog,"\n# model %s \n#****** Result for:", model);
1.334     brouard  13851:       /* It might not be a good idea to mix dummies and quantitative */
                   13852:       /* for(j=1;j<=cptcoveff;j++){ /\* j=resultpos. Could be a loop on cptcovs: number of single dummy covariate in the result line as well as in the model *\/ */
                   13853:       for(j=1;j<=cptcovs;j++){ /* j=resultpos. Could be a loop on cptcovs: number of single covariate (dummy or quantitative) in the result line as well as in the model */
                   13854:        /* printf("V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); /\* Output by variables in the resultline *\/ */
                   13855:        /* Tvaraff[j] is the name of the dummy variable in position j in the equation model:
                   13856:         * Tvaraff[1]@9={4, 3, 0, 0, 0, 0, 0, 0, 0}, in model=V5+V4+V3+V4*V3+V5*age
                   13857:         * (V5 is quanti) V4 and V3 are dummies
                   13858:         * TnsdVar[4] is the position 1 and TnsdVar[3]=2 in codtabm(k,l)(V4  V3)=V4  V3
                   13859:         *                                                              l=1 l=2
                   13860:         *                                                           k=1  1   1   0   0
                   13861:         *                                                           k=2  2   1   1   0
                   13862:         *                                                           k=3 [1] [2]  0   1
                   13863:         *                                                           k=4  2   2   1   1
                   13864:         * If nres=1 result: V3=1 V4=0 then k=3 and outputs
                   13865:         * If nres=2 result: V4=1 V3=0 then k=2 and outputs
                   13866:         * nres=1 =>k=3 j=1 V4= nbcode[4][codtabm(3,1)=1)=0; j=2  V3= nbcode[3][codtabm(3,2)=2]=1
                   13867:         * nres=2 =>k=2 j=1 V4= nbcode[4][codtabm(2,1)=2)=1; j=2  V3= nbcode[3][codtabm(2,2)=1]=0
                   13868:         */
                   13869:        /* Tvresult[nres][j] Name of the variable at position j in this resultline */
                   13870:        /* Tresult[nres][j] Value of this variable at position j could be a float if quantitative  */
                   13871: /* We give up with the combinations!! */
                   13872:        printf("\n j=%d In computing T_ Dummy[modelresult[%d][%d]]=%d, modelresult[%d][%d]=%d cptcovs=%d, cptcoveff=%d Fixed[modelresult[nres][j]]=%d\n", j, nres, j, Dummy[modelresult[nres][j]],nres,j,modelresult[nres][j],cptcovs, cptcoveff,Fixed[modelresult[nres][j]]);  /* end if dummy  or quanti */
                   13873: 
                   13874:        if(Dummy[modelresult[nres][j]]==0){/* Dummy variable of the variable in position modelresult in the model corresponding to j in resultline  */
                   13875:          printf("V%d=%d ",Tvresult[nres][j],Tresult[nres][j]); /* Output of each value for the combination TKresult[nres], ordere by the covariate values in the resultline  */
                   13876:          fprintf(ficlog,"V%d=%d ",Tvresult[nres][j],Tresult[nres][j]); /* Output of each value for the combination TKresult[nres], ordere by the covariate values in the resultline  */
                   13877:          fprintf(ficrest,"V%d=%d ",Tvresult[nres][j],Tresult[nres][j]); /* Output of each value for the combination TKresult[nres], ordere by the covariate values in the resultline  */
                   13878:          if(Fixed[modelresult[nres][j]]==0){ /* Fixed */
                   13879:            printf("fixed ");fprintf(ficlog,"fixed ");fprintf(ficrest,"fixed ");
                   13880:          }else{
                   13881:            printf("varyi ");fprintf(ficlog,"varyi ");fprintf(ficrest,"varyi ");
                   13882:          }
                   13883:          /* fprintf(ficrest,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   13884:          /* fprintf(ficlog,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   13885:        }else if(Dummy[modelresult[nres][j]]==1){ /* Quanti variable */
                   13886:          /* For each selected (single) quantitative value */
                   13887:          printf(" V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]);
                   13888:          if(Fixed[modelresult[nres][j]]==0){ /* Fixed */
                   13889:            printf("fixed ");fprintf(ficlog,"fixed ");fprintf(ficrest,"fixed ");
                   13890:          }else{
                   13891:            printf("varyi ");fprintf(ficlog,"varyi ");fprintf(ficrest,"varyi ");
                   13892:          }
                   13893:        }else{
                   13894:          printf("Error in computing T_ Dummy[modelresult[%d][%d]]=%d, modelresult[%d][%d]=%d cptcovs=%d, cptcoveff=%d \n", nres, j, Dummy[modelresult[nres][j]],nres,j,modelresult[nres][j],cptcovs, cptcoveff);  /* end if dummy  or quanti */
                   13895:          fprintf(ficlog,"Error in computing T_ Dummy[modelresult[%d][%d]]=%d, modelresult[%d][%d]=%d cptcovs=%d, cptcoveff=%d \n", nres, j, Dummy[modelresult[nres][j]],nres,j,modelresult[nres][j],cptcovs, cptcoveff);  /* end if dummy  or quanti */
                   13896:          exit(1);
                   13897:        }
1.335     brouard  13898:       } /* End loop for each variable in the resultline */
1.334     brouard  13899:       /* for (j=1; j<= nsq; j++){ /\* For each selected (single) quantitative value *\/ */
                   13900:       /*       printf(" V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]); /\* Wrong j is not in the equation model *\/ */
                   13901:       /*       fprintf(ficrest," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]); */
                   13902:       /*       fprintf(ficlog," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]); */
                   13903:       /* }      */
1.208     brouard  13904:       fprintf(ficrest,"******\n");
1.227     brouard  13905:       fprintf(ficlog,"******\n");
                   13906:       printf("******\n");
1.208     brouard  13907:       
                   13908:       fprintf(ficresstdeij,"\n#****** ");
                   13909:       fprintf(ficrescveij,"\n#****** ");
1.225     brouard  13910:       for(j=1;j<=cptcoveff;j++) {
1.334     brouard  13911:        fprintf(ficresstdeij,"V%d=%d ",Tvresult[nres][j],Tresult[nres][j]);
                   13912:        /* fprintf(ficresstdeij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   13913:        /* fprintf(ficrescveij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   13914:       }
                   13915:       for (j=1; j<= nsq; j++){ /* For each selected (single) quantitative value, TvarsQind gives the position of a quantitative in model equation  */
                   13916:        fprintf(ficresstdeij," V%d=%f ",Tvar[TvarsQind[j]],Tqresult[nres][resultmodel[nres][TvarsQind[j]]]);
                   13917:        fprintf(ficrescveij," V%d=%f ",Tvar[TvarsQind[j]],Tqresult[nres][resultmodel[nres][TvarsQind[j]]]);
1.235     brouard  13918:       }        
1.208     brouard  13919:       fprintf(ficresstdeij,"******\n");
                   13920:       fprintf(ficrescveij,"******\n");
                   13921:       
                   13922:       fprintf(ficresvij,"\n#****** ");
1.238     brouard  13923:       /* pstamp(ficresvij); */
1.225     brouard  13924:       for(j=1;j<=cptcoveff;j++) 
1.335     brouard  13925:        fprintf(ficresvij,"V%d=%d ",Tvresult[nres][j],Tresult[nres][j]);
                   13926:        /* fprintf(ficresvij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[TnsdVar[Tvaraff[j]]])]); */
1.235     brouard  13927:       for (j=1; j<= nsq; j++){ /* For each selected (single) quantitative value */
1.332     brouard  13928:        /* fprintf(ficresvij," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]); /\* To solve *\/ */
                   13929:        fprintf(ficresvij," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]); /* Solved */
1.235     brouard  13930:       }        
1.208     brouard  13931:       fprintf(ficresvij,"******\n");
                   13932:       
                   13933:       eij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
                   13934:       oldm=oldms;savm=savms;
1.235     brouard  13935:       printf(" cvevsij ");
                   13936:       fprintf(ficlog, " cvevsij ");
                   13937:       cvevsij(eij, p, nlstate, stepm, (int) bage, (int)fage, oldm, savm, k, estepm, delti, matcov, strstart, nres);
1.208     brouard  13938:       printf(" end cvevsij \n ");
                   13939:       fprintf(ficlog, " end cvevsij \n ");
                   13940:       
                   13941:       /*
                   13942:        */
                   13943:       /* goto endfree; */
                   13944:       
                   13945:       vareij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
                   13946:       pstamp(ficrest);
                   13947:       
1.269     brouard  13948:       epj=vector(1,nlstate+1);
1.208     brouard  13949:       for(vpopbased=0; vpopbased <= popbased; vpopbased++){ /* Done for vpopbased=0 and vpopbased=1 if popbased==1*/
1.227     brouard  13950:        oldm=oldms;savm=savms; /* ZZ Segmentation fault */
                   13951:        cptcod= 0; /* To be deleted */
                   13952:        printf("varevsij vpopbased=%d \n",vpopbased);
                   13953:        fprintf(ficlog, "varevsij vpopbased=%d \n",vpopbased);
1.235     brouard  13954:        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  13955:        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 ");
                   13956:        if(vpopbased==1)
                   13957:          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);
                   13958:        else
1.288     brouard  13959:          fprintf(ficrest,"the age specific forward period (stable) prevalences in each health state \n");
1.335     brouard  13960:        fprintf(ficrest,"# Age popbased mobilav e.. (std) "); /* Adding covariate values? */
1.227     brouard  13961:        for (i=1;i<=nlstate;i++) fprintf(ficrest,"e.%d (std) ",i);
                   13962:        fprintf(ficrest,"\n");
                   13963:        /* printf("Which p?\n"); for(i=1;i<=npar;i++)printf("p[i=%d]=%lf,",i,p[i]);printf("\n"); */
1.288     brouard  13964:        printf("Computing age specific forward period (stable) prevalences in each health state \n");
                   13965:        fprintf(ficlog,"Computing age specific forward period (stable) prevalences in each health state \n");
1.227     brouard  13966:        for(age=bage; age <=fage ;age++){
1.235     brouard  13967:          prevalim(prlim, nlstate, p, age, oldm, savm, ftolpl, &ncvyear, k, nres); /*ZZ Is it the correct prevalim */
1.227     brouard  13968:          if (vpopbased==1) {
                   13969:            if(mobilav ==0){
                   13970:              for(i=1; i<=nlstate;i++)
                   13971:                prlim[i][i]=probs[(int)age][i][k];
                   13972:            }else{ /* mobilav */ 
                   13973:              for(i=1; i<=nlstate;i++)
                   13974:                prlim[i][i]=mobaverage[(int)age][i][k];
                   13975:            }
                   13976:          }
1.219     brouard  13977:          
1.227     brouard  13978:          fprintf(ficrest," %4.0f %d %d",age, vpopbased, mobilav);
                   13979:          /* fprintf(ficrest," %4.0f %d %d %d %d",age, vpopbased, mobilav,Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]); */ /* to be done */
                   13980:          /* printf(" age %4.0f ",age); */
                   13981:          for(j=1, epj[nlstate+1]=0.;j <=nlstate;j++){
                   13982:            for(i=1, epj[j]=0.;i <=nlstate;i++) {
                   13983:              epj[j] += prlim[i][i]*eij[i][j][(int)age];
                   13984:              /*ZZZ  printf("%lf %lf ", prlim[i][i] ,eij[i][j][(int)age]);*/
                   13985:              /* printf("%lf %lf ", prlim[i][i] ,eij[i][j][(int)age]); */
                   13986:            }
                   13987:            epj[nlstate+1] +=epj[j];
                   13988:          }
                   13989:          /* printf(" age %4.0f \n",age); */
1.219     brouard  13990:          
1.227     brouard  13991:          for(i=1, vepp=0.;i <=nlstate;i++)
                   13992:            for(j=1;j <=nlstate;j++)
                   13993:              vepp += vareij[i][j][(int)age];
                   13994:          fprintf(ficrest," %7.3f (%7.3f)", epj[nlstate+1],sqrt(vepp));
                   13995:          for(j=1;j <=nlstate;j++){
                   13996:            fprintf(ficrest," %7.3f (%7.3f)", epj[j],sqrt(vareij[j][j][(int)age]));
                   13997:          }
                   13998:          fprintf(ficrest,"\n");
                   13999:        }
1.208     brouard  14000:       } /* End vpopbased */
1.269     brouard  14001:       free_vector(epj,1,nlstate+1);
1.208     brouard  14002:       free_ma3x(eij,1,nlstate,1,nlstate,(int) bage, (int)fage);
                   14003:       free_ma3x(vareij,1,nlstate,1,nlstate,(int) bage, (int)fage);
1.235     brouard  14004:       printf("done selection\n");fflush(stdout);
                   14005:       fprintf(ficlog,"done selection\n");fflush(ficlog);
1.208     brouard  14006:       
1.335     brouard  14007:     } /* End k selection or end covariate selection for nres */
1.227     brouard  14008: 
                   14009:     printf("done State-specific expectancies\n");fflush(stdout);
                   14010:     fprintf(ficlog,"done State-specific expectancies\n");fflush(ficlog);
                   14011: 
1.335     brouard  14012:     /* variance-covariance of forward period prevalence */
1.269     brouard  14013:     varprlim(fileresu, nresult, mobaverage, mobilavproj, bage, fage, prlim, &ncvyear, ftolpl, p, matcov, delti, stepm, cptcoveff);
1.268     brouard  14014: 
1.227     brouard  14015:     
1.290     brouard  14016:     free_vector(weight,firstobs,lastobs);
1.330     brouard  14017:     free_imatrix(Tvardk,1,NCOVMAX,1,2);
1.227     brouard  14018:     free_imatrix(Tvard,1,NCOVMAX,1,2);
1.290     brouard  14019:     free_imatrix(s,1,maxwav+1,firstobs,lastobs);
                   14020:     free_matrix(anint,1,maxwav,firstobs,lastobs); 
                   14021:     free_matrix(mint,1,maxwav,firstobs,lastobs);
                   14022:     free_ivector(cod,firstobs,lastobs);
1.227     brouard  14023:     free_ivector(tab,1,NCOVMAX);
                   14024:     fclose(ficresstdeij);
                   14025:     fclose(ficrescveij);
                   14026:     fclose(ficresvij);
                   14027:     fclose(ficrest);
                   14028:     fclose(ficpar);
                   14029:     
                   14030:     
1.126     brouard  14031:     /*---------- End : free ----------------*/
1.219     brouard  14032:     if (mobilav!=0 ||mobilavproj !=0)
1.269     brouard  14033:       free_ma3x(mobaverages,AGEINF, AGESUP,1,nlstate+ndeath, 1,ncovcombmax); /* We need to have a squared matrix with prevalence of the dead! */
                   14034:     free_ma3x(probs,AGEINF,AGESUP,1,nlstate+ndeath, 1,ncovcombmax);
1.220     brouard  14035:     free_matrix(prlim,1,nlstate,1,nlstate); /*here or after loop ? */
                   14036:     free_matrix(pmmij,1,nlstate+ndeath,1,nlstate+ndeath);
1.126     brouard  14037:   }  /* mle==-3 arrives here for freeing */
1.227     brouard  14038:   /* endfree:*/
                   14039:   free_matrix(oldms, 1,nlstate+ndeath,1,nlstate+ndeath);
                   14040:   free_matrix(newms, 1,nlstate+ndeath,1,nlstate+ndeath);
                   14041:   free_matrix(savms, 1,nlstate+ndeath,1,nlstate+ndeath);
1.290     brouard  14042:   if(ntv+nqtv>=1)free_ma3x(cotvar,1,maxwav,1,ntv+nqtv,firstobs,lastobs);
                   14043:   if(nqtv>=1)free_ma3x(cotqvar,1,maxwav,1,nqtv,firstobs,lastobs);
                   14044:   if(nqv>=1)free_matrix(coqvar,1,nqv,firstobs,lastobs);
                   14045:   free_matrix(covar,0,NCOVMAX,firstobs,lastobs);
1.227     brouard  14046:   free_matrix(matcov,1,npar,1,npar);
                   14047:   free_matrix(hess,1,npar,1,npar);
                   14048:   /*free_vector(delti,1,npar);*/
                   14049:   free_ma3x(delti3,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel); 
                   14050:   free_matrix(agev,1,maxwav,1,imx);
1.269     brouard  14051:   free_ma3x(paramstart,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel);
1.227     brouard  14052:   free_ma3x(param,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel);
                   14053:   
                   14054:   free_ivector(ncodemax,1,NCOVMAX);
                   14055:   free_ivector(ncodemaxwundef,1,NCOVMAX);
                   14056:   free_ivector(Dummy,-1,NCOVMAX);
                   14057:   free_ivector(Fixed,-1,NCOVMAX);
1.238     brouard  14058:   free_ivector(DummyV,1,NCOVMAX);
                   14059:   free_ivector(FixedV,1,NCOVMAX);
1.227     brouard  14060:   free_ivector(Typevar,-1,NCOVMAX);
                   14061:   free_ivector(Tvar,1,NCOVMAX);
1.234     brouard  14062:   free_ivector(TvarsQ,1,NCOVMAX);
                   14063:   free_ivector(TvarsQind,1,NCOVMAX);
                   14064:   free_ivector(TvarsD,1,NCOVMAX);
1.330     brouard  14065:   free_ivector(TnsdVar,1,NCOVMAX);
1.234     brouard  14066:   free_ivector(TvarsDind,1,NCOVMAX);
1.231     brouard  14067:   free_ivector(TvarFD,1,NCOVMAX);
                   14068:   free_ivector(TvarFDind,1,NCOVMAX);
1.232     brouard  14069:   free_ivector(TvarF,1,NCOVMAX);
                   14070:   free_ivector(TvarFind,1,NCOVMAX);
                   14071:   free_ivector(TvarV,1,NCOVMAX);
                   14072:   free_ivector(TvarVind,1,NCOVMAX);
                   14073:   free_ivector(TvarA,1,NCOVMAX);
                   14074:   free_ivector(TvarAind,1,NCOVMAX);
1.231     brouard  14075:   free_ivector(TvarFQ,1,NCOVMAX);
                   14076:   free_ivector(TvarFQind,1,NCOVMAX);
                   14077:   free_ivector(TvarVD,1,NCOVMAX);
                   14078:   free_ivector(TvarVDind,1,NCOVMAX);
                   14079:   free_ivector(TvarVQ,1,NCOVMAX);
                   14080:   free_ivector(TvarVQind,1,NCOVMAX);
1.230     brouard  14081:   free_ivector(Tvarsel,1,NCOVMAX);
                   14082:   free_vector(Tvalsel,1,NCOVMAX);
1.227     brouard  14083:   free_ivector(Tposprod,1,NCOVMAX);
                   14084:   free_ivector(Tprod,1,NCOVMAX);
                   14085:   free_ivector(Tvaraff,1,NCOVMAX);
                   14086:   free_ivector(invalidvarcomb,1,ncovcombmax);
                   14087:   free_ivector(Tage,1,NCOVMAX);
                   14088:   free_ivector(Tmodelind,1,NCOVMAX);
1.228     brouard  14089:   free_ivector(TmodelInvind,1,NCOVMAX);
                   14090:   free_ivector(TmodelInvQind,1,NCOVMAX);
1.332     brouard  14091: 
                   14092:   free_matrix(precov, 1,MAXRESULTLINESPONE,1,NCOVMAX+1); /* Could be elsewhere ?*/
                   14093: 
1.227     brouard  14094:   free_imatrix(nbcode,0,NCOVMAX,0,NCOVMAX);
                   14095:   /* free_imatrix(codtab,1,100,1,10); */
1.126     brouard  14096:   fflush(fichtm);
                   14097:   fflush(ficgp);
                   14098:   
1.227     brouard  14099:   
1.126     brouard  14100:   if((nberr >0) || (nbwarn>0)){
1.216     brouard  14101:     printf("End of Imach with %d errors and/or %d warnings. Please look at the log file for details.\n",nberr,nbwarn);
                   14102:     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  14103:   }else{
                   14104:     printf("End of Imach\n");
                   14105:     fprintf(ficlog,"End of Imach\n");
                   14106:   }
                   14107:   printf("See log file on %s\n",filelog);
                   14108:   /*  gettimeofday(&end_time, (struct timezone*)0);*/  /* after time */
1.157     brouard  14109:   /*(void) gettimeofday(&end_time,&tzp);*/
                   14110:   rend_time = time(NULL);  
                   14111:   end_time = *localtime(&rend_time);
                   14112:   /* tml = *localtime(&end_time.tm_sec); */
                   14113:   strcpy(strtend,asctime(&end_time));
1.126     brouard  14114:   printf("Local time at start %s\nLocal time at end   %s",strstart, strtend); 
                   14115:   fprintf(ficlog,"Local time at start %s\nLocal time at end   %s\n",strstart, strtend); 
1.157     brouard  14116:   printf("Total time used %s\n", asc_diff_time(rend_time -rstart_time,tmpout));
1.227     brouard  14117:   
1.157     brouard  14118:   printf("Total time was %.0lf Sec.\n", difftime(rend_time,rstart_time));
                   14119:   fprintf(ficlog,"Total time used %s\n", asc_diff_time(rend_time -rstart_time,tmpout));
                   14120:   fprintf(ficlog,"Total time was %.0lf Sec.\n", difftime(rend_time,rstart_time));
1.126     brouard  14121:   /*  printf("Total time was %d uSec.\n", total_usecs);*/
                   14122: /*   if(fileappend(fichtm,optionfilehtm)){ */
                   14123:   fprintf(fichtm,"<br>Local time at start %s<br>Local time at end   %s<br>\n</body></html>",strstart, strtend);
                   14124:   fclose(fichtm);
                   14125:   fprintf(fichtmcov,"<br>Local time at start %s<br>Local time at end   %s<br>\n</body></html>",strstart, strtend);
                   14126:   fclose(fichtmcov);
                   14127:   fclose(ficgp);
                   14128:   fclose(ficlog);
                   14129:   /*------ End -----------*/
1.227     brouard  14130:   
1.281     brouard  14131: 
                   14132: /* Executes gnuplot */
1.227     brouard  14133:   
                   14134:   printf("Before Current directory %s!\n",pathcd);
1.184     brouard  14135: #ifdef WIN32
1.227     brouard  14136:   if (_chdir(pathcd) != 0)
                   14137:     printf("Can't move to directory %s!\n",path);
                   14138:   if(_getcwd(pathcd,MAXLINE) > 0)
1.184     brouard  14139: #else
1.227     brouard  14140:     if(chdir(pathcd) != 0)
                   14141:       printf("Can't move to directory %s!\n", path);
                   14142:   if (getcwd(pathcd, MAXLINE) > 0)
1.184     brouard  14143: #endif 
1.126     brouard  14144:     printf("Current directory %s!\n",pathcd);
                   14145:   /*strcat(plotcmd,CHARSEPARATOR);*/
                   14146:   sprintf(plotcmd,"gnuplot");
1.157     brouard  14147: #ifdef _WIN32
1.126     brouard  14148:   sprintf(plotcmd,"\"%sgnuplot.exe\"",pathimach);
                   14149: #endif
                   14150:   if(!stat(plotcmd,&info)){
1.158     brouard  14151:     printf("Error or gnuplot program not found: '%s'\n",plotcmd);fflush(stdout);
1.126     brouard  14152:     if(!stat(getenv("GNUPLOTBIN"),&info)){
1.158     brouard  14153:       printf("Error or gnuplot program not found: '%s' Environment GNUPLOTBIN not set.\n",plotcmd);fflush(stdout);
1.126     brouard  14154:     }else
                   14155:       strcpy(pplotcmd,plotcmd);
1.157     brouard  14156: #ifdef __unix
1.126     brouard  14157:     strcpy(plotcmd,GNUPLOTPROGRAM);
                   14158:     if(!stat(plotcmd,&info)){
1.158     brouard  14159:       printf("Error gnuplot program not found: '%s'\n",plotcmd);fflush(stdout);
1.126     brouard  14160:     }else
                   14161:       strcpy(pplotcmd,plotcmd);
                   14162: #endif
                   14163:   }else
                   14164:     strcpy(pplotcmd,plotcmd);
                   14165:   
                   14166:   sprintf(plotcmd,"%s %s",pplotcmd, optionfilegnuplot);
1.158     brouard  14167:   printf("Starting graphs with: '%s'\n",plotcmd);fflush(stdout);
1.292     brouard  14168:   strcpy(pplotcmd,plotcmd);
1.227     brouard  14169:   
1.126     brouard  14170:   if((outcmd=system(plotcmd)) != 0){
1.292     brouard  14171:     printf("Error in gnuplot, command might not be in your path: '%s', err=%d\n", plotcmd, outcmd);
1.154     brouard  14172:     printf("\n Trying if gnuplot resides on the same directory that IMaCh\n");
1.152     brouard  14173:     sprintf(plotcmd,"%sgnuplot %s", pathimach, optionfilegnuplot);
1.292     brouard  14174:     if((outcmd=system(plotcmd)) != 0){
1.153     brouard  14175:       printf("\n Still a problem with gnuplot command %s, err=%d\n", plotcmd, outcmd);
1.292     brouard  14176:       strcpy(plotcmd,pplotcmd);
                   14177:     }
1.126     brouard  14178:   }
1.158     brouard  14179:   printf(" Successful, please wait...");
1.126     brouard  14180:   while (z[0] != 'q') {
                   14181:     /* chdir(path); */
1.154     brouard  14182:     printf("\nType e to edit results with your browser, g to graph again and q for exit: ");
1.126     brouard  14183:     scanf("%s",z);
                   14184: /*     if (z[0] == 'c') system("./imach"); */
                   14185:     if (z[0] == 'e') {
1.158     brouard  14186: #ifdef __APPLE__
1.152     brouard  14187:       sprintf(pplotcmd, "open %s", optionfilehtm);
1.157     brouard  14188: #elif __linux
                   14189:       sprintf(pplotcmd, "xdg-open %s", optionfilehtm);
1.153     brouard  14190: #else
1.152     brouard  14191:       sprintf(pplotcmd, "%s", optionfilehtm);
1.153     brouard  14192: #endif
                   14193:       printf("Starting browser with: %s",pplotcmd);fflush(stdout);
                   14194:       system(pplotcmd);
1.126     brouard  14195:     }
                   14196:     else if (z[0] == 'g') system(plotcmd);
                   14197:     else if (z[0] == 'q') exit(0);
                   14198:   }
1.227     brouard  14199: end:
1.126     brouard  14200:   while (z[0] != 'q') {
1.195     brouard  14201:     printf("\nType  q for exiting: "); fflush(stdout);
1.126     brouard  14202:     scanf("%s",z);
                   14203:   }
1.283     brouard  14204:   printf("End\n");
1.282     brouard  14205:   exit(0);
1.126     brouard  14206: }

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